aboutsummaryrefslogtreecommitdiffstats
path: root/vanilla/node_modules/vite
diff options
context:
space:
mode:
authorAdam Mathes <adam@adammathes.com>2026-02-14 14:46:37 -0800
committerAdam Mathes <adam@adammathes.com>2026-02-14 14:46:37 -0800
commitafa87af01c79a9baa539f2992d32154d2a4739bd (patch)
tree92c7416db734270a2fee1d72ee9cc119379ff8e1 /vanilla/node_modules/vite
parent3b927e84d200402281f68181cd4253bc77e5528d (diff)
downloadneko-afa87af01c79a9baa539f2992d32154d2a4739bd.tar.gz
neko-afa87af01c79a9baa539f2992d32154d2a4739bd.tar.bz2
neko-afa87af01c79a9baa539f2992d32154d2a4739bd.zip
task: delete vanilla js prototype\n\n- Removed vanilla/ directory and web/dist/vanilla directory\n- Updated Makefile, Dockerfile, and CI workflow to remove vanilla references\n- Cleaned up web/web.go to remove vanilla embed and routes\n- Verified build and tests pass\n\nCloses NK-2tcnmq
Diffstat (limited to 'vanilla/node_modules/vite')
-rw-r--r--vanilla/node_modules/vite/LICENSE.md2120
-rw-r--r--vanilla/node_modules/vite/README.md20
-rw-r--r--vanilla/node_modules/vite/bin/openChrome.js68
-rwxr-xr-xvanilla/node_modules/vite/bin/vite.js79
-rw-r--r--vanilla/node_modules/vite/client.d.ts279
-rw-r--r--vanilla/node_modules/vite/dist/client/client.mjs1106
-rw-r--r--vanilla/node_modules/vite/dist/client/env.mjs19
-rw-r--r--vanilla/node_modules/vite/dist/node/chunks/build.js4
-rw-r--r--vanilla/node_modules/vite/dist/node/chunks/build2.js5538
-rw-r--r--vanilla/node_modules/vite/dist/node/chunks/chunk.js48
-rw-r--r--vanilla/node_modules/vite/dist/node/chunks/config.js35978
-rw-r--r--vanilla/node_modules/vite/dist/node/chunks/config2.js4
-rw-r--r--vanilla/node_modules/vite/dist/node/chunks/dist.js6758
-rw-r--r--vanilla/node_modules/vite/dist/node/chunks/lib.js377
-rw-r--r--vanilla/node_modules/vite/dist/node/chunks/logger.js329
-rw-r--r--vanilla/node_modules/vite/dist/node/chunks/moduleRunnerTransport.d.ts96
-rw-r--r--vanilla/node_modules/vite/dist/node/chunks/optimizer.js4
-rw-r--r--vanilla/node_modules/vite/dist/node/chunks/postcss-import.js479
-rw-r--r--vanilla/node_modules/vite/dist/node/chunks/preview.js4
-rw-r--r--vanilla/node_modules/vite/dist/node/chunks/server.js4
-rw-r--r--vanilla/node_modules/vite/dist/node/cli.js698
-rw-r--r--vanilla/node_modules/vite/dist/node/index.d.ts3713
-rw-r--r--vanilla/node_modules/vite/dist/node/index.js30
-rw-r--r--vanilla/node_modules/vite/dist/node/module-runner.d.ts311
-rw-r--r--vanilla/node_modules/vite/dist/node/module-runner.js1160
-rw-r--r--vanilla/node_modules/vite/misc/false.js1
-rw-r--r--vanilla/node_modules/vite/misc/true.js1
-rw-r--r--vanilla/node_modules/vite/package.json199
-rw-r--r--vanilla/node_modules/vite/types/customEvent.d.ts50
-rw-r--r--vanilla/node_modules/vite/types/hmrPayload.d.ts74
-rw-r--r--vanilla/node_modules/vite/types/hot.d.ts39
-rw-r--r--vanilla/node_modules/vite/types/import-meta.d.ts5
-rw-r--r--vanilla/node_modules/vite/types/importGlob.d.ts89
-rw-r--r--vanilla/node_modules/vite/types/importMeta.d.ts30
-rw-r--r--vanilla/node_modules/vite/types/internal/cssPreprocessorOptions.d.ts44
-rw-r--r--vanilla/node_modules/vite/types/internal/lightningcssOptions.d.ts18
-rw-r--r--vanilla/node_modules/vite/types/internal/terserOptions.d.ts11
-rw-r--r--vanilla/node_modules/vite/types/metadata.d.ts33
-rw-r--r--vanilla/node_modules/vite/types/package.json4
39 files changed, 0 insertions, 59824 deletions
diff --git a/vanilla/node_modules/vite/LICENSE.md b/vanilla/node_modules/vite/LICENSE.md
deleted file mode 100644
index c0f6ed8..0000000
--- a/vanilla/node_modules/vite/LICENSE.md
+++ /dev/null
@@ -1,2120 +0,0 @@
-# Vite core license
-Vite is released under the MIT license:
-
-MIT License
-
-Copyright (c) 2019-present, VoidZero Inc. and Vite 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.
-
-# Licenses of bundled dependencies
-The published Vite artifact additionally contains code with the following licenses:
-BSD-2-Clause, CC0-1.0, ISC, MIT
-
-# Bundled dependencies:
-## @jridgewell/gen-mapping, @jridgewell/remapping, @jridgewell/sourcemap-codec, @jridgewell/trace-mapping
-License: MIT
-By: Justin Ridgewell
-Repositories: https://github.com/jridgewell/sourcemaps, https://github.com/jridgewell/sourcemaps, https://github.com/jridgewell/sourcemaps, https://github.com/jridgewell/sourcemaps
-
-> Copyright 2024 Justin Ridgewell <justin@ridgewell.name>
->
-> 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.
-
----------------------------------------
-
-## @jridgewell/resolve-uri
-License: MIT
-By: Justin Ridgewell
-Repository: https://github.com/jridgewell/resolve-uri
-
-> Copyright 2019 Justin Ridgewell <jridgewell@google.com>
->
-> 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.
-
----------------------------------------
-
-## @polka/compression
-License: MIT
-Repository: https://github.com/lukeed/polka
-
----------------------------------------
-
-## @polka/url
-License: MIT
-By: Luke Edwards
-Repository: https://github.com/lukeed/polka
-
----------------------------------------
-
-## @rolldown/pluginutils
-License: MIT
-Repository: https://github.com/rolldown/rolldown
-
-> MIT License
->
-> Copyright (c) 2024-present VoidZero Inc. & 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.
->
-> end of terms and conditions
->
-> The licenses of externally maintained libraries from which parts of the Software is derived are listed [here](https://github.com/rolldown/rolldown/blob/main/THIRD-PARTY-LICENSE).
-
----------------------------------------
-
-## @rollup/plugin-alias, @rollup/plugin-commonjs, @rollup/plugin-dynamic-import-vars, @rollup/pluginutils
-License: MIT
-By: Johannes Stein
-Repository: https://github.com/rollup/plugins
-
-License: MIT
-By: Rich Harris
-Repository: https://github.com/rollup/plugins
-
-License: MIT
-By: LarsDenBakker
-Repository: https://github.com/rollup/plugins
-
-License: MIT
-By: Rich Harris
-Repository: https://github.com/rollup/plugins
-
-> The MIT License (MIT)
->
-> Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/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.
-
----------------------------------------
-
-## anymatch
-License: ISC
-By: Elan Shanker
-Repository: https://github.com/micromatch/anymatch
-
-> The ISC License
->
-> Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com)
->
-> Permission to use, copy, modify, and/or 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.
-
----------------------------------------
-
-## artichokie
-License: MIT
-By: sapphi-red, Evan You
-Repository: https://github.com/sapphi-red/artichokie
-
-> MIT License
->
-> Copyright (c) 2020-present, Yuxi (Evan) You
-> Copyright (c) 2023-present, sapphi-red
->
-> 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.
-
----------------------------------------
-
-## binary-extensions
-License: MIT
-By: Sindre Sorhus
-Repository: https://github.com/sindresorhus/binary-extensions
-
-> MIT License
->
-> Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
-> Copyright (c) Paul Miller (https://paulmillr.com)
->
-> 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.
-
----------------------------------------
-
-## braces, fill-range, is-number
-License: MIT
-By: Jon Schlinkert, Brian Woodward, Elan Shanker, Eugene Sharygin, hemanth.hm
-Repository: https://github.com/micromatch/braces
-
-License: MIT
-By: Jon Schlinkert, Edo Rivai, Paul Miller, Rouven Weßling
-Repository: https://github.com/jonschlinkert/fill-range
-
-License: MIT
-By: Jon Schlinkert, Olsten Larck, Rouven Weßling
-Repository: https://github.com/jonschlinkert/is-number
-
-> The MIT License (MIT)
->
-> Copyright (c) 2014-present, Jon Schlinkert.
->
-> 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.
-
----------------------------------------
-
-## bundle-name, default-browser, default-browser-id, define-lazy-prop, is-docker, is-inside-container, is-wsl, open, run-applescript, wsl-utils
-License: MIT
-By: Sindre Sorhus
-Repositories: https://github.com/sindresorhus/bundle-name, https://github.com/sindresorhus/default-browser, https://github.com/sindresorhus/default-browser-id, https://github.com/sindresorhus/define-lazy-prop, https://github.com/sindresorhus/is-docker, https://github.com/sindresorhus/is-inside-container, https://github.com/sindresorhus/is-wsl, https://github.com/sindresorhus/open, https://github.com/sindresorhus/run-applescript, https://github.com/sindresorhus/wsl-utils
-
-> MIT License
->
-> Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
->
-> 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.
-
----------------------------------------
-
-## cac
-License: MIT
-By: egoist
-Repository: https://github.com/egoist/cac
-
-> The MIT License (MIT)
->
-> Copyright (c) EGOIST <0x142857@gmail.com> (https://github.com/egoist)
->
-> 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.
-
----------------------------------------
-
-## chokidar
-License: MIT
-By: Paul Miller, Elan Shanker
-Repository: https://github.com/paulmillr/chokidar
-
-> The MIT License (MIT)
->
-> Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker
->
-> 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.
-
----------------------------------------
-
-## commondir, shell-quote
-License: MIT
-By: James Halliday
-Repositories: http://github.com/substack/node-commondir, http://github.com/ljharb/shell-quote
-
-> The MIT License
->
-> Copyright (c) 2013 James Halliday (mail@substack.net)
->
-> 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.
-
----------------------------------------
-
-## connect
-License: MIT
-By: TJ Holowaychuk, Douglas Christopher Wilson, Jonathan Ong, Tim Caswell
-Repository: https://github.com/senchalabs/connect
-
-> (The MIT License)
->
-> Copyright (c) 2010 Sencha Inc.
-> Copyright (c) 2011 LearnBoost
-> Copyright (c) 2011-2014 TJ Holowaychuk
-> Copyright (c) 2015 Douglas Christopher Wilson
->
-> 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.
-
----------------------------------------
-
-## convert-source-map
-License: MIT
-By: Thorsten Lorenz
-Repository: https://github.com/thlorenz/convert-source-map
-
-> Copyright 2013 Thorsten Lorenz.
-> All rights reserved.
->
-> 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.
-
----------------------------------------
-
-## cors
-License: MIT
-By: Troy Goode
-Repository: https://github.com/expressjs/cors
-
-> (The MIT License)
->
-> Copyright (c) 2013 Troy Goode <troygoode@gmail.com>
->
-> 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.
-
----------------------------------------
-
-## cross-spawn
-License: MIT
-By: André Cruz
-Repository: https://github.com/moxystudio/node-cross-spawn
-
-> The MIT License (MIT)
->
-> Copyright (c) 2018 Made With MOXY Lda <hello@moxy.studio>
->
-> 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.
-
----------------------------------------
-
-## cssesc
-License: MIT
-By: Mathias Bynens
-Repository: https://github.com/mathiasbynens/cssesc
-
-> Copyright Mathias Bynens <https://mathiasbynens.be/>
->
-> 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.
-
----------------------------------------
-
-## dotenv
-License: BSD-2-Clause
-Repository: https://github.com/motdotla/dotenv
-
-> Copyright (c) 2015, Scott Motte
-> 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.
->
-> 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.
-
----------------------------------------
-
-## dotenv-expand
-License: BSD-2-Clause
-By: motdotla
-Repository: https://github.com/motdotla/dotenv-expand
-
-> Copyright (c) 2016, Scott Motte
-> 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.
->
-> 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.
-
----------------------------------------
-
-## ee-first
-License: MIT
-By: Jonathan Ong, Douglas Christopher Wilson
-Repository: https://github.com/jonathanong/ee-first
-
-> The MIT License (MIT)
->
-> Copyright (c) 2014 Jonathan Ong me@jongleberry.com
->
-> 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.
-
----------------------------------------
-
-## encodeurl
-License: MIT
-By: Douglas Christopher Wilson
-Repository: https://github.com/pillarjs/encodeurl
-
-> (The MIT License)
->
-> Copyright (c) 2016 Douglas Christopher Wilson
->
-> 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.
-
----------------------------------------
-
-## entities
-License: BSD-2-Clause
-By: Felix Boehm
-Repository: https://github.com/fb55/entities
-
-> Copyright (c) Felix Böhm
-> 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.
->
-> THIS 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,
-> EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
----------------------------------------
-
-## es-module-lexer
-License: MIT
-By: Guy Bedford
-Repository: https://github.com/guybedford/es-module-lexer
-
-> MIT License
-> -----------
->
-> Copyright (C) 2018-2022 Guy Bedford
->
-> 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.
-
----------------------------------------
-
-## escape-html
-License: MIT
-Repository: https://github.com/component/escape-html
-
-> (The MIT License)
->
-> Copyright (c) 2012-2013 TJ Holowaychuk
-> Copyright (c) 2015 Andreas Lubbe
-> Copyright (c) 2015 Tiancheng "Timothy" Gu
->
-> 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.
-
----------------------------------------
-
-## estree-walker
-License: MIT
-By: Rich Harris
-Repository: https://github.com/Rich-Harris/estree-walker
-
-> Copyright (c) 2015-20 [these people](https://github.com/Rich-Harris/estree-walker/graphs/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.
-
----------------------------------------
-
-## etag
-License: MIT
-By: Douglas Christopher Wilson, David Björklund
-Repository: https://github.com/jshttp/etag
-
-> (The MIT License)
->
-> Copyright (c) 2014-2016 Douglas Christopher Wilson
->
-> 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.
-
----------------------------------------
-
-## finalhandler
-License: MIT
-By: Douglas Christopher Wilson
-Repository: https://github.com/pillarjs/finalhandler
-
-> (The MIT License)
->
-> Copyright (c) 2014-2017 Douglas Christopher Wilson <doug@somethingdoug.com>
->
-> 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.
-
----------------------------------------
-
-## follow-redirects
-License: MIT
-By: Ruben Verborgh, Olivier Lalonde, James Talmage
-Repository: https://github.com/follow-redirects/follow-redirects
-
-> Copyright 2014–present Olivier Lalonde <olalonde@gmail.com>, James Talmage <james@talmage.io>, Ruben Verborgh
->
-> 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.
-
----------------------------------------
-
-## generic-names
-License: MIT
-By: Alexey Litvinov
-Repository: https://github.com/css-modules/generic-names
-
-> The MIT License (MIT)
->
-> Copyright (c) 2015 Alexey Litvinov
->
-> 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.
-
----------------------------------------
-
-## glob-parent
-License: ISC
-By: Gulp Team, Elan Shanker, Blaine Bublitz
-Repository: https://github.com/gulpjs/glob-parent
-
-> The ISC License
->
-> Copyright (c) 2015, 2019 Elan Shanker
->
-> Permission to use, copy, modify, and/or 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.
-
----------------------------------------
-
-## host-validation-middleware
-License: MIT
-By: sapphi-red
-Repository: https://github.com/sapphi-red/host-validation-middleware
-
-> MIT License
->
-> Copyright (c) 2025 sapphi-red
->
-> 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.
-
----------------------------------------
-
-## http-proxy-3
-License: MIT
-By: William Stein, Charlie Robbins, Jimb Esser, jcrugzz
-Repository: https://github.com/sagemathinc/http-proxy-3
-
-> node-http-3
->
-> Copyright (c) 2010-2025 William Stein, Charlie Robbins, Jarrett Cruger & the 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.
-
----------------------------------------
-
-## icss-utils
-License: ISC
-By: Glen Maddern
-Repository: https://github.com/css-modules/icss-utils
-
-> ISC License (ISC)
-> Copyright 2018 Glen Maddern
->
-> Permission to use, copy, modify, and/or 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.
-
----------------------------------------
-
-## is-binary-path
-License: MIT
-By: Sindre Sorhus
-Repository: https://github.com/sindresorhus/is-binary-path
-
-> MIT License
->
-> Copyright (c) 2019 Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com), Paul Miller (https://paulmillr.com)
->
-> 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.
-
----------------------------------------
-
-## is-extglob
-License: MIT
-By: Jon Schlinkert
-Repository: https://github.com/jonschlinkert/is-extglob
-
-> The MIT License (MIT)
->
-> Copyright (c) 2014-2016, Jon Schlinkert
->
-> 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.
-
----------------------------------------
-
-## is-glob
-License: MIT
-By: Jon Schlinkert, Brian Woodward, Daniel Perez
-Repository: https://github.com/micromatch/is-glob
-
-> The MIT License (MIT)
->
-> Copyright (c) 2014-2017, Jon Schlinkert.
->
-> 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.
-
----------------------------------------
-
-## is-reference
-License: MIT
-By: Rich Harris
-Repository: https://github.com/Rich-Harris/is-reference
-
----------------------------------------
-
-## isexe, which
-License: ISC
-By: Isaac Z. Schlueter
-Repositories: https://github.com/isaacs/isexe, https://github.com/isaacs/node-which
-
-> The ISC License
->
-> Copyright (c) Isaac Z. Schlueter and Contributors
->
-> Permission to use, copy, modify, and/or 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.
-
----------------------------------------
-
-## js-tokens
-License: MIT
-By: Simon Lydell
-Repository: https://github.com/lydell/js-tokens
-
-> The MIT License (MIT)
->
-> Copyright (c) 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024 Simon Lydell
->
-> 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.
-
----------------------------------------
-
-## launch-editor, launch-editor-middleware
-License: MIT
-By: Evan You
-Repositories: https://github.com/yyx990803/launch-editor, https://github.com/yyx990803/launch-editor
-
-> The MIT License (MIT)
->
-> Copyright (c) 2017-present, Yuxi (Evan) You
->
-> 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.
-
----------------------------------------
-
-## lilconfig
-License: MIT
-By: antonk52
-Repository: https://github.com/antonk52/lilconfig
-
-> MIT License
->
-> Copyright (c) 2022 Anton Kastritskiy
->
-> 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.
-
----------------------------------------
-
-## loader-utils
-License: MIT
-By: Tobias Koppers @sokra
-Repository: https://github.com/webpack/loader-utils
-
-> Copyright JS Foundation and other 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.
-
----------------------------------------
-
-## lodash.camelcase
-License: MIT
-By: John-David Dalton, Blaine Bublitz, Mathias Bynens
-Repository: https://github.com/lodash/lodash
-
-> Copyright jQuery Foundation and other contributors <https://jquery.org/>
->
-> Based on Underscore.js, copyright Jeremy Ashkenas,
-> DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
->
-> This software consists of voluntary contributions made by many
-> individuals. For exact contribution history, see the revision history
-> available at https://github.com/lodash/lodash
->
-> The following license applies to all parts of this software except as
-> documented below:
->
-> ====
->
-> 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.
->
-> ====
->
-> Copyright and related rights for sample code are waived via CC0. Sample
-> code is defined as all source code displayed within the prose of the
-> documentation.
->
-> CC0: http://creativecommons.org/publicdomain/zero/1.0/
->
-> ====
->
-> Files located in the node_modules and vendor directories are externally
-> maintained libraries used by this software which have their own
-> licenses; we recommend you read them, as their terms may differ from the
-> terms above.
-
----------------------------------------
-
-## magic-string
-License: MIT
-By: Rich Harris
-Repository: https://github.com/Rich-Harris/magic-string
-
-> Copyright 2018 Rich Harris
->
-> 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.
-
----------------------------------------
-
-## mlly, ufo
-License: MIT
-Repositories: https://github.com/unjs/mlly, https://github.com/unjs/ufo
-
-> MIT License
->
-> Copyright (c) Pooya Parsa <pooya@pi0.io>
->
-> 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.
-
----------------------------------------
-
-## mrmime
-License: MIT
-By: Luke Edwards
-Repository: https://github.com/lukeed/mrmime
-
-> The MIT License (MIT)
->
-> Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (https://lukeed.com)
->
-> 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.
-
----------------------------------------
-
-## normalize-path
-License: MIT
-By: Jon Schlinkert, Blaine Bublitz
-Repository: https://github.com/jonschlinkert/normalize-path
-
-> The MIT License (MIT)
->
-> Copyright (c) 2014-2018, Jon Schlinkert.
->
-> 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.
-
----------------------------------------
-
-## object-assign
-License: MIT
-By: Sindre Sorhus
-Repository: https://github.com/sindresorhus/object-assign
-
-> The MIT License (MIT)
->
-> Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
->
-> 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.
-
----------------------------------------
-
-## obug
-License: MIT
-By: Kevin Deng
-Repository: https://github.com/sxzz/obug
-
-> The MIT License (MIT)
->
-> Copyright © 2025-PRESENT Kevin Deng (https://github.com/sxzz)
-> Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca>
-> Copyright (c) 2018-2021 Josh Junon
->
-> 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.
-
----------------------------------------
-
-## on-finished
-License: MIT
-By: Douglas Christopher Wilson, Jonathan Ong
-Repository: https://github.com/jshttp/on-finished
-
-> (The MIT License)
->
-> Copyright (c) 2013 Jonathan Ong <me@jongleberry.com>
-> Copyright (c) 2014 Douglas Christopher Wilson <doug@somethingdoug.com>
->
-> 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.
-
----------------------------------------
-
-## parse5
-License: MIT
-By: Ivan Nikulin, https://github.com/inikulin/parse5/graphs/contributors
-Repository: https://github.com/inikulin/parse5
-
-> Copyright (c) 2013-2019 Ivan Nikulin (ifaaan@gmail.com, https://github.com/inikulin)
->
-> 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.
-
----------------------------------------
-
-## parseurl
-License: MIT
-By: Douglas Christopher Wilson, Jonathan Ong
-Repository: https://github.com/pillarjs/parseurl
-
-> (The MIT License)
->
-> Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
-> Copyright (c) 2014-2017 Douglas Christopher Wilson <doug@somethingdoug.com>
->
-> 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.
-
----------------------------------------
-
-## path-key, shebang-regex
-License: MIT
-By: Sindre Sorhus
-Repositories: https://github.com/sindresorhus/path-key, https://github.com/sindresorhus/shebang-regex
-
-> MIT License
->
-> Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
->
-> 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.
-
----------------------------------------
-
-## periscopic
-License: MIT
-Repository: https://github.com/Rich-Harris/periscopic
-
-> Copyright (c) 2019 Rich Harris
->
-> 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.
-
----------------------------------------
-
-## picocolors
-License: ISC
-By: Alexey Raspopov
-Repository: https://github.com/alexeyraspopov/picocolors
-
-> ISC License
->
-> Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov
->
-> Permission to use, copy, modify, and/or 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.
-
----------------------------------------
-
-## postcss-import
-License: MIT
-By: Maxime Thirouin
-Repository: https://github.com/postcss/postcss-import
-
-> The MIT License (MIT)
->
-> Copyright (c) 2014 Maxime Thirouin, Jason Campbell & Kevin Mårtensson
->
-> 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.
-
----------------------------------------
-
-## postcss-load-config
-License: MIT
-By: Michael Ciniawky, Ryan Dunckel, Mateusz Derks, Dalton Santos, Patrick Gilday, François Wouts
-Repository: https://github.com/postcss/postcss-load-config
-
-> The MIT License (MIT)
->
-> Copyright Michael Ciniawsky <michael.ciniawsky@gmail.com>
->
-> 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.
-
----------------------------------------
-
-## postcss-modules
-License: MIT
-By: Alexander Madyankin
-Repository: https://github.com/css-modules/postcss-modules
-
-> The MIT License (MIT)
->
-> Copyright 2015-present Alexander Madyankin <alexander@madyankin.name>
->
-> 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.
-
----------------------------------------
-
-## postcss-modules-extract-imports
-License: ISC
-By: Glen Maddern
-Repository: https://github.com/css-modules/postcss-modules-extract-imports
-
-> Copyright 2015 Glen Maddern
->
-> Permission to use, copy, modify, and/or 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.
-
----------------------------------------
-
-## postcss-modules-local-by-default
-License: MIT
-By: Mark Dalgleish
-Repository: https://github.com/css-modules/postcss-modules-local-by-default
-
-> The MIT License (MIT)
->
-> Copyright 2015 Mark Dalgleish <mark.john.dalgleish@gmail.com>
->
-> 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.
-
----------------------------------------
-
-## postcss-modules-scope
-License: ISC
-By: Glen Maddern
-Repository: https://github.com/css-modules/postcss-modules-scope
-
-> ISC License (ISC)
->
-> Copyright (c) 2015, Glen Maddern
->
-> Permission to use, copy, modify, and/or 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.
-
----------------------------------------
-
-## postcss-modules-values
-License: ISC
-By: Glen Maddern
-Repository: https://github.com/css-modules/postcss-modules-values
-
-> ISC License (ISC)
->
-> Copyright (c) 2015, Glen Maddern
->
-> Permission to use, copy, modify, and/or 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.
-
----------------------------------------
-
-## postcss-selector-parser
-License: MIT
-By: Ben Briggs, Chris Eppstein
-Repository: https://github.com/postcss/postcss-selector-parser
-
-> Copyright (c) Ben Briggs <beneb.info@gmail.com> (http://beneb.info)
->
-> 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.
-
----------------------------------------
-
-## postcss-value-parser
-License: MIT
-By: Bogdan Chadkin
-Repository: https://github.com/TrySound/postcss-value-parser
-
-> Copyright (c) Bogdan Chadkin <trysound@yandex.ru>
->
-> 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.
-
----------------------------------------
-
-## readdirp
-License: MIT
-By: Thorsten Lorenz, Paul Miller
-Repository: https://github.com/paulmillr/readdirp
-
-> MIT License
->
-> Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (https://paulmillr.com)
->
-> 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.
-
----------------------------------------
-
-## resolve.exports, totalist
-License: MIT
-By: Luke Edwards
-Repositories: https://github.com/lukeed/resolve.exports, https://github.com/lukeed/totalist
-
-> The MIT License (MIT)
->
-> Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)
->
-> 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.
-
----------------------------------------
-
-## shebang-command
-License: MIT
-By: Kevin Mårtensson
-Repository: https://github.com/kevva/shebang-command
-
-> MIT License
->
-> Copyright (c) Kevin Mårtensson <kevinmartensson@gmail.com> (github.com/kevva)
->
-> 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.
-
----------------------------------------
-
-## sirv
-License: MIT
-By: Luke Edwards
-Repository: https://github.com/lukeed/sirv
-
----------------------------------------
-
-## statuses
-License: MIT
-By: Douglas Christopher Wilson, Jonathan Ong
-Repository: https://github.com/jshttp/statuses
-
-> The MIT License (MIT)
->
-> Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
-> Copyright (c) 2016 Douglas Christopher Wilson <doug@somethingdoug.com>
->
-> 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.
-
----------------------------------------
-
-## string-hash
-License: CC0-1.0
-By: The Dark Sky Company
-Repository: https://github.com/darkskyapp/string-hash
-
----------------------------------------
-
-## strip-literal
-License: MIT
-By: Anthony Fu
-Repository: https://github.com/antfu/strip-literal
-
-> MIT License
->
-> Copyright (c) 2022 Anthony Fu <https://github.com/antfu>
->
-> 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.
-
----------------------------------------
-
-## to-regex-range
-License: MIT
-By: Jon Schlinkert, Rouven Weßling
-Repository: https://github.com/micromatch/to-regex-range
-
-> The MIT License (MIT)
->
-> Copyright (c) 2015-present, Jon Schlinkert.
->
-> 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.
-
----------------------------------------
-
-## tsconfck
-License: MIT
-By: dominikg
-Repository: https://github.com/dominikg/tsconfck
-
-> MIT License
->
-> Copyright (c) 2021-present dominikg and [contributors](https://github.com/dominikg/tsconfck/graphs/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.
->
-> -- Licenses for 3rd-party code included in tsconfck --
->
-> # strip-bom and strip-json-comments
-> MIT License
->
-> Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
->
-> 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.
-
----------------------------------------
-
-## unpipe
-License: MIT
-By: Douglas Christopher Wilson
-Repository: https://github.com/stream-utils/unpipe
-
-> (The MIT License)
->
-> Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
->
-> 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.
-
----------------------------------------
-
-## util-deprecate
-License: MIT
-By: Nathan Rajlich
-Repository: https://github.com/TooTallNate/util-deprecate
-
-> (The MIT License)
->
-> Copyright (c) 2014 Nathan Rajlich <nathan@tootallnate.net>
->
-> 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.
-
----------------------------------------
-
-## utils-merge
-License: MIT
-By: Jared Hanson
-Repository: https://github.com/jaredhanson/utils-merge
-
-> The MIT License (MIT)
->
-> Copyright (c) 2013-2017 Jared Hanson
->
-> 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.
-
----------------------------------------
-
-## vary
-License: MIT
-By: Douglas Christopher Wilson
-Repository: https://github.com/jshttp/vary
-
-> (The MIT License)
->
-> Copyright (c) 2014-2017 Douglas Christopher Wilson
->
-> 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.
-
----------------------------------------
-
-## ws
-License: MIT
-By: Einar Otto Stangvik
-Repository: https://github.com/websockets/ws
-
-> Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
-> Copyright (c) 2013 Arnout Kazemier and contributors
-> Copyright (c) 2016 Luigi Pinca and 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.
diff --git a/vanilla/node_modules/vite/README.md b/vanilla/node_modules/vite/README.md
deleted file mode 100644
index b0e348b..0000000
--- a/vanilla/node_modules/vite/README.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# Vite ⚡
-
-> Next Generation Frontend Tooling
-
-- 💡 Instant Server Start
-- ⚡️ Lightning Fast HMR
-- 🛠️ Rich Features
-- 📦 Optimized Build
-- 🔩 Universal Plugin Interface
-- 🔑 Fully Typed APIs
-
-Vite (French word for "fast", pronounced `/vit/`) is a new breed of frontend build tool that significantly improves the frontend development experience. It consists of two major parts:
-
-- A dev server that serves your source files over [native ES modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), with [rich built-in features](https://vite.dev/guide/features.html) and astonishingly fast [Hot Module Replacement (HMR)](https://vite.dev/guide/features.html#hot-module-replacement).
-
-- A [build command](https://vite.dev/guide/build.html) that bundles your code with [Rollup](https://rollupjs.org), pre-configured to output highly optimized static assets for production.
-
-In addition, Vite is highly extensible via its [Plugin API](https://vite.dev/guide/api-plugin.html) and [JavaScript API](https://vite.dev/guide/api-javascript.html) with full typing support.
-
-[Read the Docs to Learn More](https://vite.dev).
diff --git a/vanilla/node_modules/vite/bin/openChrome.js b/vanilla/node_modules/vite/bin/openChrome.js
deleted file mode 100644
index 5a4aa95..0000000
--- a/vanilla/node_modules/vite/bin/openChrome.js
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
-Copyright (c) 2015-present, Facebook, Inc.
-
-This source code is licensed under the MIT license found in the
-LICENSE file at
-https://github.com/facebook/create-react-app/blob/main/LICENSE
-*/
-
-/* global Application */
-
-// eslint-disable-next-line @typescript-eslint/no-unused-vars
-function run(argv) {
- const urlToOpen = argv[0]
- // Allow requested program to be optional, default to Google Chrome
- const programName = argv[1] ?? 'Google Chrome'
-
- const app = Application(programName)
-
- if (app.windows.length === 0) {
- app.Window().make()
- }
-
- // 1: Looking for tab running debugger then,
- // Reload debugging tab if found, then return
- const found = lookupTabWithUrl(urlToOpen, app)
- if (found) {
- found.targetWindow.activeTabIndex = found.targetTabIndex
- found.targetTab.reload()
- found.targetWindow.index = 1
- app.activate()
- return
- }
-
- // 2: Looking for Empty tab
- // In case debugging tab was not found
- // We try to find an empty tab instead
- const emptyTabFound = lookupTabWithUrl('chrome://newtab/', app)
- if (emptyTabFound) {
- emptyTabFound.targetWindow.activeTabIndex = emptyTabFound.targetTabIndex
- emptyTabFound.targetTab.url = urlToOpen
- app.activate()
- return
- }
-
- // 3: Create new tab
- // both debugging and empty tab were not found make a new tab with url
- const firstWindow = app.windows[0]
- firstWindow.tabs.push(app.Tab({ url: urlToOpen }))
- app.activate()
-}
-
-/**
- * Lookup tab with given url
- */
-function lookupTabWithUrl(lookupUrl, app) {
- const windows = app.windows()
- for (const window of windows) {
- for (const [tabIndex, tab] of window.tabs().entries()) {
- if (tab.url().includes(lookupUrl)) {
- return {
- targetTab: tab,
- targetTabIndex: tabIndex + 1,
- targetWindow: window,
- }
- }
- }
- }
-}
diff --git a/vanilla/node_modules/vite/bin/vite.js b/vanilla/node_modules/vite/bin/vite.js
deleted file mode 100755
index 79c49ab..0000000
--- a/vanilla/node_modules/vite/bin/vite.js
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/env node
-import { performance } from 'node:perf_hooks'
-import module from 'node:module'
-
-if (!import.meta.url.includes('node_modules')) {
- if (!process.env.DEBUG_DISABLE_SOURCE_MAP) {
- // eslint-disable-next-line n/no-unsupported-features/node-builtins -- only used in dev
- process.setSourceMapsEnabled(true)
- }
-
- process.on('unhandledRejection', (err) => {
- throw new Error('UNHANDLED PROMISE REJECTION', { cause: err })
- })
-}
-
-global.__vite_start_time = performance.now()
-
-// check debug mode first before requiring the CLI.
-const debugIndex = process.argv.findIndex((arg) => /^(?:-d|--debug)$/.test(arg))
-const filterIndex = process.argv.findIndex((arg) =>
- /^(?:-f|--filter)$/.test(arg),
-)
-const profileIndex = process.argv.indexOf('--profile')
-
-if (debugIndex > 0) {
- let value = process.argv[debugIndex + 1]
- if (!value || value[0] === '-') {
- value = 'vite:*'
- } else {
- // support debugging multiple flags with comma-separated list
- value = value
- .split(',')
- .map((v) => `vite:${v}`)
- .join(',')
- }
- process.env.DEBUG = `${
- process.env.DEBUG ? process.env.DEBUG + ',' : ''
- }${value}`
-
- if (filterIndex > 0) {
- const filter = process.argv[filterIndex + 1]
- if (filter && filter[0] !== '-') {
- process.env.VITE_DEBUG_FILTER = filter
- }
- }
-}
-
-function start() {
- try {
- // eslint-disable-next-line n/no-unsupported-features/node-builtins -- it is supported in Node 22.8.0+ and only called if it exists
- module.enableCompileCache?.()
- // flush the cache after 10s because the cache is not flushed until process end
- // for dev server, the cache is never flushed unless manually flushed because the process.exit is called
- // also flushing the cache in SIGINT handler seems to cause the process to hang
- setTimeout(() => {
- try {
- // eslint-disable-next-line n/no-unsupported-features/node-builtins -- it is supported in Node 22.12.0+ and only called if it exists
- module.flushCompileCache?.()
- } catch {}
- }, 10 * 1000).unref()
- } catch {}
- return import('../dist/node/cli.js')
-}
-
-if (profileIndex > 0) {
- process.argv.splice(profileIndex, 1)
- const next = process.argv[profileIndex]
- if (next && next[0] !== '-') {
- process.argv.splice(profileIndex, 1)
- }
- const inspector = await import('node:inspector').then((r) => r.default)
- const session = (global.__vite_profile_session = new inspector.Session())
- session.connect()
- session.post('Profiler.enable', () => {
- session.post('Profiler.start', start)
- })
-} else {
- start()
-}
diff --git a/vanilla/node_modules/vite/client.d.ts b/vanilla/node_modules/vite/client.d.ts
deleted file mode 100644
index 3a9dd88..0000000
--- a/vanilla/node_modules/vite/client.d.ts
+++ /dev/null
@@ -1,279 +0,0 @@
-/// <reference path="./types/importMeta.d.ts" />
-
-// CSS modules
-type CSSModuleClasses = { readonly [key: string]: string }
-
-declare module '*.module.css' {
- const classes: CSSModuleClasses
- export default classes
-}
-declare module '*.module.scss' {
- const classes: CSSModuleClasses
- export default classes
-}
-declare module '*.module.sass' {
- const classes: CSSModuleClasses
- export default classes
-}
-declare module '*.module.less' {
- const classes: CSSModuleClasses
- export default classes
-}
-declare module '*.module.styl' {
- const classes: CSSModuleClasses
- export default classes
-}
-declare module '*.module.stylus' {
- const classes: CSSModuleClasses
- export default classes
-}
-declare module '*.module.pcss' {
- const classes: CSSModuleClasses
- export default classes
-}
-declare module '*.module.sss' {
- const classes: CSSModuleClasses
- export default classes
-}
-
-// CSS
-declare module '*.css' {}
-declare module '*.scss' {}
-declare module '*.sass' {}
-declare module '*.less' {}
-declare module '*.styl' {}
-declare module '*.stylus' {}
-declare module '*.pcss' {}
-declare module '*.sss' {}
-
-// Built-in asset types
-// see `src/node/constants.ts`
-
-// images
-declare module '*.apng' {
- const src: string
- export default src
-}
-declare module '*.bmp' {
- const src: string
- export default src
-}
-declare module '*.png' {
- const src: string
- export default src
-}
-declare module '*.jpg' {
- const src: string
- export default src
-}
-declare module '*.jpeg' {
- const src: string
- export default src
-}
-declare module '*.jfif' {
- const src: string
- export default src
-}
-declare module '*.pjpeg' {
- const src: string
- export default src
-}
-declare module '*.pjp' {
- const src: string
- export default src
-}
-declare module '*.gif' {
- const src: string
- export default src
-}
-declare module '*.svg' {
- const src: string
- export default src
-}
-declare module '*.ico' {
- const src: string
- export default src
-}
-declare module '*.webp' {
- const src: string
- export default src
-}
-declare module '*.avif' {
- const src: string
- export default src
-}
-declare module '*.cur' {
- const src: string
- export default src
-}
-declare module '*.jxl' {
- const src: string
- export default src
-}
-
-// media
-declare module '*.mp4' {
- const src: string
- export default src
-}
-declare module '*.webm' {
- const src: string
- export default src
-}
-declare module '*.ogg' {
- const src: string
- export default src
-}
-declare module '*.mp3' {
- const src: string
- export default src
-}
-declare module '*.wav' {
- const src: string
- export default src
-}
-declare module '*.flac' {
- const src: string
- export default src
-}
-declare module '*.aac' {
- const src: string
- export default src
-}
-declare module '*.opus' {
- const src: string
- export default src
-}
-declare module '*.mov' {
- const src: string
- export default src
-}
-declare module '*.m4a' {
- const src: string
- export default src
-}
-declare module '*.vtt' {
- const src: string
- export default src
-}
-
-// fonts
-declare module '*.woff' {
- const src: string
- export default src
-}
-declare module '*.woff2' {
- const src: string
- export default src
-}
-declare module '*.eot' {
- const src: string
- export default src
-}
-declare module '*.ttf' {
- const src: string
- export default src
-}
-declare module '*.otf' {
- const src: string
- export default src
-}
-
-// other
-declare module '*.webmanifest' {
- const src: string
- export default src
-}
-declare module '*.pdf' {
- const src: string
- export default src
-}
-declare module '*.txt' {
- const src: string
- export default src
-}
-
-// wasm?init
-declare module '*.wasm?init' {
- const initWasm: (
- options?: WebAssembly.Imports,
- ) => Promise<WebAssembly.Instance>
- export default initWasm
-}
-
-// web worker
-declare module '*?worker' {
- const workerConstructor: {
- new (options?: { name?: string }): Worker
- }
- export default workerConstructor
-}
-
-declare module '*?worker&inline' {
- const workerConstructor: {
- new (options?: { name?: string }): Worker
- }
- export default workerConstructor
-}
-
-declare module '*?worker&url' {
- const src: string
- export default src
-}
-
-declare module '*?sharedworker' {
- const sharedWorkerConstructor: {
- new (options?: { name?: string }): SharedWorker
- }
- export default sharedWorkerConstructor
-}
-
-declare module '*?sharedworker&inline' {
- const sharedWorkerConstructor: {
- new (options?: { name?: string }): SharedWorker
- }
- export default sharedWorkerConstructor
-}
-
-declare module '*?sharedworker&url' {
- const src: string
- export default src
-}
-
-declare module '*?raw' {
- const src: string
- export default src
-}
-
-declare module '*?url' {
- const src: string
- export default src
-}
-
-declare module '*?inline' {
- const src: string
- export default src
-}
-
-declare module '*?no-inline' {
- const src: string
- export default src
-}
-
-declare module '*?url&inline' {
- const src: string
- export default src
-}
-
-declare module '*?url&no-inline' {
- const src: string
- export default src
-}
-
-declare interface VitePreloadErrorEvent extends Event {
- payload: Error
-}
-
-declare interface WindowEventMap {
- 'vite:preloadError': VitePreloadErrorEvent
-}
diff --git a/vanilla/node_modules/vite/dist/client/client.mjs b/vanilla/node_modules/vite/dist/client/client.mjs
deleted file mode 100644
index 977c527..0000000
--- a/vanilla/node_modules/vite/dist/client/client.mjs
+++ /dev/null
@@ -1,1106 +0,0 @@
-import "@vite/env";
-
-//#region \0@oxc-project+runtime@0.99.0/helpers/typeof.js
-function _typeof(o) {
- "@babel/helpers - typeof";
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
- return typeof o$1;
- } : function(o$1) {
- return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
- }, _typeof(o);
-}
-
-//#endregion
-//#region \0@oxc-project+runtime@0.99.0/helpers/toPrimitive.js
-function toPrimitive(t, r) {
- if ("object" != _typeof(t) || !t) return t;
- var e = t[Symbol.toPrimitive];
- if (void 0 !== e) {
- var i = e.call(t, r || "default");
- if ("object" != _typeof(i)) return i;
- throw new TypeError("@@toPrimitive must return a primitive value.");
- }
- return ("string" === r ? String : Number)(t);
-}
-
-//#endregion
-//#region \0@oxc-project+runtime@0.99.0/helpers/toPropertyKey.js
-function toPropertyKey(t) {
- var i = toPrimitive(t, "string");
- return "symbol" == _typeof(i) ? i : i + "";
-}
-
-//#endregion
-//#region \0@oxc-project+runtime@0.99.0/helpers/defineProperty.js
-function _defineProperty(e, r, t) {
- return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
- value: t,
- enumerable: !0,
- configurable: !0,
- writable: !0
- }) : e[r] = t, e;
-}
-
-//#endregion
-//#region src/shared/hmr.ts
-var HMRContext = class {
- constructor(hmrClient$1, ownerPath) {
- this.hmrClient = hmrClient$1;
- this.ownerPath = ownerPath;
- _defineProperty(this, "newListeners", void 0);
- if (!hmrClient$1.dataMap.has(ownerPath)) hmrClient$1.dataMap.set(ownerPath, {});
- const mod = hmrClient$1.hotModulesMap.get(ownerPath);
- if (mod) mod.callbacks = [];
- const staleListeners = hmrClient$1.ctxToListenersMap.get(ownerPath);
- if (staleListeners) for (const [event, staleFns] of staleListeners) {
- const listeners = hmrClient$1.customListenersMap.get(event);
- if (listeners) hmrClient$1.customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l)));
- }
- this.newListeners = /* @__PURE__ */ new Map();
- hmrClient$1.ctxToListenersMap.set(ownerPath, this.newListeners);
- }
- get data() {
- return this.hmrClient.dataMap.get(this.ownerPath);
- }
- accept(deps, callback) {
- if (typeof deps === "function" || !deps) this.acceptDeps([this.ownerPath], ([mod]) => deps?.(mod));
- else if (typeof deps === "string") this.acceptDeps([deps], ([mod]) => callback?.(mod));
- else if (Array.isArray(deps)) this.acceptDeps(deps, callback);
- else throw new Error(`invalid hot.accept() usage.`);
- }
- acceptExports(_, callback) {
- this.acceptDeps([this.ownerPath], ([mod]) => callback?.(mod));
- }
- dispose(cb) {
- this.hmrClient.disposeMap.set(this.ownerPath, cb);
- }
- prune(cb) {
- this.hmrClient.pruneMap.set(this.ownerPath, cb);
- }
- decline() {}
- invalidate(message) {
- const firstInvalidatedBy = this.hmrClient.currentFirstInvalidatedBy ?? this.ownerPath;
- this.hmrClient.notifyListeners("vite:invalidate", {
- path: this.ownerPath,
- message,
- firstInvalidatedBy
- });
- this.send("vite:invalidate", {
- path: this.ownerPath,
- message,
- firstInvalidatedBy
- });
- this.hmrClient.logger.debug(`invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`);
- }
- on(event, cb) {
- const addToMap = (map) => {
- const existing = map.get(event) || [];
- existing.push(cb);
- map.set(event, existing);
- };
- addToMap(this.hmrClient.customListenersMap);
- addToMap(this.newListeners);
- }
- off(event, cb) {
- const removeFromMap = (map) => {
- const existing = map.get(event);
- if (existing === void 0) return;
- const pruned = existing.filter((l) => l !== cb);
- if (pruned.length === 0) {
- map.delete(event);
- return;
- }
- map.set(event, pruned);
- };
- removeFromMap(this.hmrClient.customListenersMap);
- removeFromMap(this.newListeners);
- }
- send(event, data) {
- this.hmrClient.send({
- type: "custom",
- event,
- data
- });
- }
- acceptDeps(deps, callback = () => {}) {
- const mod = this.hmrClient.hotModulesMap.get(this.ownerPath) || {
- id: this.ownerPath,
- callbacks: []
- };
- mod.callbacks.push({
- deps,
- fn: callback
- });
- this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
- }
-};
-var HMRClient = class {
- constructor(logger, transport$1, importUpdatedModule) {
- this.logger = logger;
- this.transport = transport$1;
- this.importUpdatedModule = importUpdatedModule;
- _defineProperty(this, "hotModulesMap", /* @__PURE__ */ new Map());
- _defineProperty(this, "disposeMap", /* @__PURE__ */ new Map());
- _defineProperty(this, "pruneMap", /* @__PURE__ */ new Map());
- _defineProperty(this, "dataMap", /* @__PURE__ */ new Map());
- _defineProperty(this, "customListenersMap", /* @__PURE__ */ new Map());
- _defineProperty(this, "ctxToListenersMap", /* @__PURE__ */ new Map());
- _defineProperty(this, "currentFirstInvalidatedBy", void 0);
- _defineProperty(this, "updateQueue", []);
- _defineProperty(this, "pendingUpdateQueue", false);
- }
- async notifyListeners(event, data) {
- const cbs = this.customListenersMap.get(event);
- if (cbs) await Promise.allSettled(cbs.map((cb) => cb(data)));
- }
- send(payload) {
- this.transport.send(payload).catch((err) => {
- this.logger.error(err);
- });
- }
- clear() {
- this.hotModulesMap.clear();
- this.disposeMap.clear();
- this.pruneMap.clear();
- this.dataMap.clear();
- this.customListenersMap.clear();
- this.ctxToListenersMap.clear();
- }
- async prunePaths(paths) {
- await Promise.all(paths.map((path) => {
- const disposer = this.disposeMap.get(path);
- if (disposer) return disposer(this.dataMap.get(path));
- }));
- await Promise.all(paths.map((path) => {
- const fn = this.pruneMap.get(path);
- if (fn) return fn(this.dataMap.get(path));
- }));
- }
- warnFailedUpdate(err, path) {
- if (!(err instanceof Error) || !err.message.includes("fetch")) this.logger.error(err);
- this.logger.error(`Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`);
- }
- /**
- * buffer multiple hot updates triggered by the same src change
- * so that they are invoked in the same order they were sent.
- * (otherwise the order may be inconsistent because of the http request round trip)
- */
- async queueUpdate(payload) {
- this.updateQueue.push(this.fetchUpdate(payload));
- if (!this.pendingUpdateQueue) {
- this.pendingUpdateQueue = true;
- await Promise.resolve();
- this.pendingUpdateQueue = false;
- const loading = [...this.updateQueue];
- this.updateQueue = [];
- (await Promise.all(loading)).forEach((fn) => fn && fn());
- }
- }
- async fetchUpdate(update) {
- const { path, acceptedPath, firstInvalidatedBy } = update;
- const mod = this.hotModulesMap.get(path);
- if (!mod) return;
- let fetchedModule;
- const isSelfUpdate = path === acceptedPath;
- const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => deps.includes(acceptedPath));
- if (isSelfUpdate || qualifiedCallbacks.length > 0) {
- const disposer = this.disposeMap.get(acceptedPath);
- if (disposer) await disposer(this.dataMap.get(acceptedPath));
- try {
- fetchedModule = await this.importUpdatedModule(update);
- } catch (e) {
- this.warnFailedUpdate(e, acceptedPath);
- }
- }
- return () => {
- try {
- this.currentFirstInvalidatedBy = firstInvalidatedBy;
- for (const { deps, fn } of qualifiedCallbacks) fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
- const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
- this.logger.debug(`hot updated: ${loggedPath}`);
- } finally {
- this.currentFirstInvalidatedBy = void 0;
- }
- };
- }
-};
-
-//#endregion
-//#region ../../node_modules/.pnpm/nanoid@5.1.6/node_modules/nanoid/non-secure/index.js
-let urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
-let nanoid = (size = 21) => {
- let id = "";
- let i = size | 0;
- while (i--) id += urlAlphabet[Math.random() * 64 | 0];
- return id;
-};
-
-//#endregion
-//#region src/shared/constants.ts
-let SOURCEMAPPING_URL = "sourceMa";
-SOURCEMAPPING_URL += "ppingURL";
-
-//#endregion
-//#region src/shared/utils.ts
-const isWindows = typeof process !== "undefined" && process.platform === "win32";
-const AsyncFunction = async function() {}.constructor;
-function promiseWithResolvers() {
- let resolve;
- let reject;
- return {
- promise: new Promise((_resolve, _reject) => {
- resolve = _resolve;
- reject = _reject;
- }),
- resolve,
- reject
- };
-}
-
-//#endregion
-//#region src/shared/moduleRunnerTransport.ts
-function reviveInvokeError(e) {
- const error = new Error(e.message || "Unknown invoke error");
- Object.assign(error, e, { runnerError: /* @__PURE__ */ new Error("RunnerError") });
- return error;
-}
-const createInvokeableTransport = (transport$1) => {
- if (transport$1.invoke) return {
- ...transport$1,
- async invoke(name, data) {
- const result = await transport$1.invoke({
- type: "custom",
- event: "vite:invoke",
- data: {
- id: "send",
- name,
- data
- }
- });
- if ("error" in result) throw reviveInvokeError(result.error);
- return result.result;
- }
- };
- if (!transport$1.send || !transport$1.connect) throw new Error("transport must implement send and connect when invoke is not implemented");
- const rpcPromises = /* @__PURE__ */ new Map();
- return {
- ...transport$1,
- connect({ onMessage, onDisconnection }) {
- return transport$1.connect({
- onMessage(payload) {
- if (payload.type === "custom" && payload.event === "vite:invoke") {
- const data = payload.data;
- if (data.id.startsWith("response:")) {
- const invokeId = data.id.slice(9);
- const promise = rpcPromises.get(invokeId);
- if (!promise) return;
- if (promise.timeoutId) clearTimeout(promise.timeoutId);
- rpcPromises.delete(invokeId);
- const { error, result } = data.data;
- if (error) promise.reject(error);
- else promise.resolve(result);
- return;
- }
- }
- onMessage(payload);
- },
- onDisconnection
- });
- },
- disconnect() {
- rpcPromises.forEach((promise) => {
- promise.reject(/* @__PURE__ */ new Error(`transport was disconnected, cannot call ${JSON.stringify(promise.name)}`));
- });
- rpcPromises.clear();
- return transport$1.disconnect?.();
- },
- send(data) {
- return transport$1.send(data);
- },
- async invoke(name, data) {
- const promiseId = nanoid();
- const wrappedData = {
- type: "custom",
- event: "vite:invoke",
- data: {
- name,
- id: `send:${promiseId}`,
- data
- }
- };
- const sendPromise = transport$1.send(wrappedData);
- const { promise, resolve, reject } = promiseWithResolvers();
- const timeout = transport$1.timeout ?? 6e4;
- let timeoutId;
- if (timeout > 0) {
- timeoutId = setTimeout(() => {
- rpcPromises.delete(promiseId);
- reject(/* @__PURE__ */ new Error(`transport invoke timed out after ${timeout}ms (data: ${JSON.stringify(wrappedData)})`));
- }, timeout);
- timeoutId?.unref?.();
- }
- rpcPromises.set(promiseId, {
- resolve,
- reject,
- name,
- timeoutId
- });
- if (sendPromise) sendPromise.catch((err) => {
- clearTimeout(timeoutId);
- rpcPromises.delete(promiseId);
- reject(err);
- });
- try {
- return await promise;
- } catch (err) {
- throw reviveInvokeError(err);
- }
- }
- };
-};
-const normalizeModuleRunnerTransport = (transport$1) => {
- const invokeableTransport = createInvokeableTransport(transport$1);
- let isConnected = !invokeableTransport.connect;
- let connectingPromise;
- return {
- ...transport$1,
- ...invokeableTransport.connect ? { async connect(onMessage) {
- if (isConnected) return;
- if (connectingPromise) {
- await connectingPromise;
- return;
- }
- const maybePromise = invokeableTransport.connect({
- onMessage: onMessage ?? (() => {}),
- onDisconnection() {
- isConnected = false;
- }
- });
- if (maybePromise) {
- connectingPromise = maybePromise;
- await connectingPromise;
- connectingPromise = void 0;
- }
- isConnected = true;
- } } : {},
- ...invokeableTransport.disconnect ? { async disconnect() {
- if (!isConnected) return;
- if (connectingPromise) await connectingPromise;
- isConnected = false;
- await invokeableTransport.disconnect();
- } } : {},
- async send(data) {
- if (!invokeableTransport.send) return;
- if (!isConnected) if (connectingPromise) await connectingPromise;
- else throw new Error("send was called before connect");
- await invokeableTransport.send(data);
- },
- async invoke(name, data) {
- if (!isConnected) if (connectingPromise) await connectingPromise;
- else throw new Error("invoke was called before connect");
- return invokeableTransport.invoke(name, data);
- }
- };
-};
-const createWebSocketModuleRunnerTransport = (options) => {
- const pingInterval = options.pingInterval ?? 3e4;
- let ws;
- let pingIntervalId;
- return {
- async connect({ onMessage, onDisconnection }) {
- const socket = options.createConnection();
- socket.addEventListener("message", async ({ data }) => {
- onMessage(JSON.parse(data));
- });
- let isOpened = socket.readyState === socket.OPEN;
- if (!isOpened) await new Promise((resolve, reject) => {
- socket.addEventListener("open", () => {
- isOpened = true;
- resolve();
- }, { once: true });
- socket.addEventListener("close", async () => {
- if (!isOpened) {
- reject(/* @__PURE__ */ new Error("WebSocket closed without opened."));
- return;
- }
- onMessage({
- type: "custom",
- event: "vite:ws:disconnect",
- data: { webSocket: socket }
- });
- onDisconnection();
- });
- });
- onMessage({
- type: "custom",
- event: "vite:ws:connect",
- data: { webSocket: socket }
- });
- ws = socket;
- pingIntervalId = setInterval(() => {
- if (socket.readyState === socket.OPEN) socket.send(JSON.stringify({ type: "ping" }));
- }, pingInterval);
- },
- disconnect() {
- clearInterval(pingIntervalId);
- ws?.close();
- },
- send(data) {
- ws.send(JSON.stringify(data));
- }
- };
-};
-
-//#endregion
-//#region src/shared/hmrHandler.ts
-function createHMRHandler(handler) {
- const queue = new Queue();
- return (payload) => queue.enqueue(() => handler(payload));
-}
-var Queue = class {
- constructor() {
- _defineProperty(this, "queue", []);
- _defineProperty(this, "pending", false);
- }
- enqueue(promise) {
- return new Promise((resolve, reject) => {
- this.queue.push({
- promise,
- resolve,
- reject
- });
- this.dequeue();
- });
- }
- dequeue() {
- if (this.pending) return false;
- const item = this.queue.shift();
- if (!item) return false;
- this.pending = true;
- item.promise().then(item.resolve).catch(item.reject).finally(() => {
- this.pending = false;
- this.dequeue();
- });
- return true;
- }
-};
-
-//#endregion
-//#region src/client/overlay.ts
-const hmrConfigName = __HMR_CONFIG_NAME__;
-const base$1 = __BASE__ || "/";
-const cspNonce = "document" in globalThis ? document.querySelector("meta[property=csp-nonce]")?.nonce : void 0;
-function h(e, attrs = {}, ...children) {
- const elem = document.createElement(e);
- for (const [k, v] of Object.entries(attrs)) if (v !== void 0) elem.setAttribute(k, v);
- elem.append(...children);
- return elem;
-}
-const templateStyle = `
-:host {
- position: fixed;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- z-index: 99999;
- --monospace: 'SFMono-Regular', Consolas,
- 'Liberation Mono', Menlo, Courier, monospace;
- --red: #ff5555;
- --yellow: #e2aa53;
- --purple: #cfa4ff;
- --cyan: #2dd9da;
- --dim: #c9c9c9;
-
- --window-background: #181818;
- --window-color: #d8d8d8;
-}
-
-.backdrop {
- position: fixed;
- z-index: 99999;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- overflow-y: scroll;
- margin: 0;
- background: rgba(0, 0, 0, 0.66);
-}
-
-.window {
- font-family: var(--monospace);
- line-height: 1.5;
- max-width: 80vw;
- color: var(--window-color);
- box-sizing: border-box;
- margin: 30px auto;
- padding: 2.5vh 4vw;
- position: relative;
- background: var(--window-background);
- border-radius: 6px 6px 8px 8px;
- box-shadow: 0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0,0,0,0.22);
- overflow: hidden;
- border-top: 8px solid var(--red);
- direction: ltr;
- text-align: left;
-}
-
-pre {
- font-family: var(--monospace);
- font-size: 16px;
- margin-top: 0;
- margin-bottom: 1em;
- overflow-x: scroll;
- scrollbar-width: none;
-}
-
-pre::-webkit-scrollbar {
- display: none;
-}
-
-pre.frame::-webkit-scrollbar {
- display: block;
- height: 5px;
-}
-
-pre.frame::-webkit-scrollbar-thumb {
- background: #999;
- border-radius: 5px;
-}
-
-pre.frame {
- scrollbar-width: thin;
-}
-
-.message {
- line-height: 1.3;
- font-weight: 600;
- white-space: pre-wrap;
-}
-
-.message-body {
- color: var(--red);
-}
-
-.plugin {
- color: var(--purple);
-}
-
-.file {
- color: var(--cyan);
- margin-bottom: 0;
- white-space: pre-wrap;
- word-break: break-all;
-}
-
-.frame {
- color: var(--yellow);
-}
-
-.stack {
- font-size: 13px;
- color: var(--dim);
-}
-
-.tip {
- font-size: 13px;
- color: #999;
- border-top: 1px dotted #999;
- padding-top: 13px;
- line-height: 1.8;
-}
-
-code {
- font-size: 13px;
- font-family: var(--monospace);
- color: var(--yellow);
-}
-
-.file-link {
- text-decoration: underline;
- cursor: pointer;
-}
-
-kbd {
- line-height: 1.5;
- font-family: ui-monospace, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
- font-size: 0.75rem;
- font-weight: 700;
- background-color: rgb(38, 40, 44);
- color: rgb(166, 167, 171);
- padding: 0.15rem 0.3rem;
- border-radius: 0.25rem;
- border-width: 0.0625rem 0.0625rem 0.1875rem;
- border-style: solid;
- border-color: rgb(54, 57, 64);
- border-image: initial;
-}
-`;
-const createTemplate = () => h("div", {
- class: "backdrop",
- part: "backdrop"
-}, h("div", {
- class: "window",
- part: "window"
-}, h("pre", {
- class: "message",
- part: "message"
-}, h("span", {
- class: "plugin",
- part: "plugin"
-}), h("span", {
- class: "message-body",
- part: "message-body"
-})), h("pre", {
- class: "file",
- part: "file"
-}), h("pre", {
- class: "frame",
- part: "frame"
-}), h("pre", {
- class: "stack",
- part: "stack"
-}), h("div", {
- class: "tip",
- part: "tip"
-}, "Click outside, press ", h("kbd", {}, "Esc"), " key, or fix the code to dismiss.", h("br"), "You can also disable this overlay by setting ", h("code", { part: "config-option-name" }, "server.hmr.overlay"), " to ", h("code", { part: "config-option-value" }, "false"), " in ", h("code", { part: "config-file-name" }, hmrConfigName), ".")), h("style", { nonce: cspNonce }, templateStyle));
-const fileRE = /(?:file:\/\/)?(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g;
-const codeframeRE = /^(?:>?\s*\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm;
-const { HTMLElement = class {} } = globalThis;
-var ErrorOverlay = class extends HTMLElement {
- constructor(err, links = true) {
- super();
- _defineProperty(this, "root", void 0);
- _defineProperty(this, "closeOnEsc", void 0);
- this.root = this.attachShadow({ mode: "open" });
- this.root.appendChild(createTemplate());
- codeframeRE.lastIndex = 0;
- const hasFrame = err.frame && codeframeRE.test(err.frame);
- const message = hasFrame ? err.message.replace(codeframeRE, "") : err.message;
- if (err.plugin) this.text(".plugin", `[plugin:${err.plugin}] `);
- this.text(".message-body", message.trim());
- const [file] = (err.loc?.file || err.id || "unknown file").split(`?`);
- if (err.loc) this.text(".file", `${file}:${err.loc.line}:${err.loc.column}`, links);
- else if (err.id) this.text(".file", file);
- if (hasFrame) this.text(".frame", err.frame.trim());
- this.text(".stack", err.stack, links);
- this.root.querySelector(".window").addEventListener("click", (e) => {
- e.stopPropagation();
- });
- this.addEventListener("click", () => {
- this.close();
- });
- this.closeOnEsc = (e) => {
- if (e.key === "Escape" || e.code === "Escape") this.close();
- };
- document.addEventListener("keydown", this.closeOnEsc);
- }
- text(selector, text, linkFiles = false) {
- const el = this.root.querySelector(selector);
- if (!linkFiles) el.textContent = text;
- else {
- let curIndex = 0;
- let match;
- fileRE.lastIndex = 0;
- while (match = fileRE.exec(text)) {
- const { 0: file, index } = match;
- const frag = text.slice(curIndex, index);
- el.appendChild(document.createTextNode(frag));
- const link = document.createElement("a");
- link.textContent = file;
- link.className = "file-link";
- link.onclick = () => {
- fetch(new URL(`${base$1}__open-in-editor?file=${encodeURIComponent(file)}`, import.meta.url));
- };
- el.appendChild(link);
- curIndex += frag.length + file.length;
- }
- if (curIndex < text.length) el.appendChild(document.createTextNode(text.slice(curIndex)));
- }
- }
- close() {
- this.parentNode?.removeChild(this);
- document.removeEventListener("keydown", this.closeOnEsc);
- }
-};
-const overlayId = "vite-error-overlay";
-const { customElements } = globalThis;
-if (customElements && !customElements.get(overlayId)) customElements.define(overlayId, ErrorOverlay);
-
-//#endregion
-//#region src/client/client.ts
-console.debug("[vite] connecting...");
-const importMetaUrl = new URL(import.meta.url);
-const serverHost = __SERVER_HOST__;
-const socketProtocol = __HMR_PROTOCOL__ || (importMetaUrl.protocol === "https:" ? "wss" : "ws");
-const hmrPort = __HMR_PORT__;
-const socketHost = `${__HMR_HOSTNAME__ || importMetaUrl.hostname}:${hmrPort || importMetaUrl.port}${__HMR_BASE__}`;
-const directSocketHost = __HMR_DIRECT_TARGET__;
-const base = __BASE__ || "/";
-const hmrTimeout = __HMR_TIMEOUT__;
-const wsToken = __WS_TOKEN__;
-const transport = normalizeModuleRunnerTransport((() => {
- let wsTransport = createWebSocketModuleRunnerTransport({
- createConnection: () => new WebSocket(`${socketProtocol}://${socketHost}?token=${wsToken}`, "vite-hmr"),
- pingInterval: hmrTimeout
- });
- return {
- async connect(handlers) {
- try {
- await wsTransport.connect(handlers);
- } catch (e) {
- if (!hmrPort) {
- wsTransport = createWebSocketModuleRunnerTransport({
- createConnection: () => new WebSocket(`${socketProtocol}://${directSocketHost}?token=${wsToken}`, "vite-hmr"),
- pingInterval: hmrTimeout
- });
- try {
- await wsTransport.connect(handlers);
- console.info("[vite] Direct websocket connection fallback. Check out https://vite.dev/config/server-options.html#server-hmr to remove the previous connection error.");
- } catch (e$1) {
- if (e$1 instanceof Error && e$1.message.includes("WebSocket closed without opened.")) {
- const currentScriptHostURL = new URL(import.meta.url);
- const currentScriptHost = currentScriptHostURL.host + currentScriptHostURL.pathname.replace(/@vite\/client$/, "");
- console.error(`[vite] failed to connect to websocket.
-your current setup:
- (browser) ${currentScriptHost} <--[HTTP]--> ${serverHost} (server)\n (browser) ${socketHost} <--[WebSocket (failing)]--> ${directSocketHost} (server)\nCheck out your Vite / network configuration and https://vite.dev/config/server-options.html#server-hmr .`);
- }
- }
- return;
- }
- console.error(`[vite] failed to connect to websocket (${e}). `);
- throw e;
- }
- },
- async disconnect() {
- await wsTransport.disconnect();
- },
- send(data) {
- wsTransport.send(data);
- }
- };
-})());
-let willUnload = false;
-if (typeof window !== "undefined") window.addEventListener?.("beforeunload", () => {
- willUnload = true;
-});
-function cleanUrl(pathname) {
- const url = new URL(pathname, "http://vite.dev");
- url.searchParams.delete("direct");
- return url.pathname + url.search;
-}
-let isFirstUpdate = true;
-const outdatedLinkTags = /* @__PURE__ */ new WeakSet();
-const debounceReload = (time) => {
- let timer;
- return () => {
- if (timer) {
- clearTimeout(timer);
- timer = null;
- }
- timer = setTimeout(() => {
- location.reload();
- }, time);
- };
-};
-const pageReload = debounceReload(20);
-const hmrClient = new HMRClient({
- error: (err) => console.error("[vite]", err),
- debug: (...msg) => console.debug("[vite]", ...msg)
-}, transport, async function importUpdatedModule({ acceptedPath, timestamp, explicitImportRequired, isWithinCircularImport }) {
- const [acceptedPathWithoutQuery, query] = acceptedPath.split(`?`);
- const importPromise = import(
- /* @vite-ignore */
- base + acceptedPathWithoutQuery.slice(1) + `?${explicitImportRequired ? "import&" : ""}t=${timestamp}${query ? `&${query}` : ""}`
-);
- if (isWithinCircularImport) importPromise.catch(() => {
- console.info(`[hmr] ${acceptedPath} failed to apply HMR as it's within a circular import. Reloading page to reset the execution order. To debug and break the circular import, you can run \`vite --debug hmr\` to log the circular dependency path if a file change triggered it.`);
- pageReload();
- });
- return await importPromise;
-});
-transport.connect(createHMRHandler(handleMessage));
-async function handleMessage(payload) {
- switch (payload.type) {
- case "connected":
- console.debug(`[vite] connected.`);
- break;
- case "update":
- await hmrClient.notifyListeners("vite:beforeUpdate", payload);
- if (hasDocument) if (isFirstUpdate && hasErrorOverlay()) {
- location.reload();
- return;
- } else {
- if (enableOverlay) clearErrorOverlay();
- isFirstUpdate = false;
- }
- await Promise.all(payload.updates.map(async (update) => {
- if (update.type === "js-update") return hmrClient.queueUpdate(update);
- const { path, timestamp } = update;
- const searchUrl = cleanUrl(path);
- const el = Array.from(document.querySelectorAll("link")).find((e) => !outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl));
- if (!el) return;
- const newPath = `${base}${searchUrl.slice(1)}${searchUrl.includes("?") ? "&" : "?"}t=${timestamp}`;
- return new Promise((resolve) => {
- const newLinkTag = el.cloneNode();
- newLinkTag.href = new URL(newPath, el.href).href;
- const removeOldEl = () => {
- el.remove();
- console.debug(`[vite] css hot updated: ${searchUrl}`);
- resolve();
- };
- newLinkTag.addEventListener("load", removeOldEl);
- newLinkTag.addEventListener("error", removeOldEl);
- outdatedLinkTags.add(el);
- el.after(newLinkTag);
- });
- }));
- await hmrClient.notifyListeners("vite:afterUpdate", payload);
- break;
- case "custom":
- await hmrClient.notifyListeners(payload.event, payload.data);
- if (payload.event === "vite:ws:disconnect") {
- if (hasDocument && !willUnload) {
- console.log(`[vite] server connection lost. Polling for restart...`);
- const socket = payload.data.webSocket;
- const url = new URL(socket.url);
- url.search = "";
- await waitForSuccessfulPing(url.href);
- location.reload();
- }
- }
- break;
- case "full-reload":
- await hmrClient.notifyListeners("vite:beforeFullReload", payload);
- if (hasDocument) if (payload.path && payload.path.endsWith(".html")) {
- const pagePath = decodeURI(location.pathname);
- const payloadPath = base + payload.path.slice(1);
- if (pagePath === payloadPath || payload.path === "/index.html" || pagePath.endsWith("/") && pagePath + "index.html" === payloadPath) pageReload();
- return;
- } else pageReload();
- break;
- case "prune":
- await hmrClient.notifyListeners("vite:beforePrune", payload);
- await hmrClient.prunePaths(payload.paths);
- break;
- case "error":
- await hmrClient.notifyListeners("vite:error", payload);
- if (hasDocument) {
- const err = payload.err;
- if (enableOverlay) createErrorOverlay(err);
- else console.error(`[vite] Internal Server Error\n${err.message}\n${err.stack}`);
- }
- break;
- case "ping": break;
- default: return payload;
- }
-}
-const enableOverlay = __HMR_ENABLE_OVERLAY__;
-const hasDocument = "document" in globalThis;
-function createErrorOverlay(err) {
- clearErrorOverlay();
- const { customElements: customElements$1 } = globalThis;
- if (customElements$1) {
- const ErrorOverlayConstructor = customElements$1.get(overlayId);
- document.body.appendChild(new ErrorOverlayConstructor(err));
- }
-}
-function clearErrorOverlay() {
- document.querySelectorAll(overlayId).forEach((n) => n.close());
-}
-function hasErrorOverlay() {
- return document.querySelectorAll(overlayId).length;
-}
-function waitForSuccessfulPing(socketUrl) {
- if (typeof SharedWorker === "undefined") {
- const visibilityManager = {
- currentState: document.visibilityState,
- listeners: /* @__PURE__ */ new Set()
- };
- const onVisibilityChange = () => {
- visibilityManager.currentState = document.visibilityState;
- for (const listener of visibilityManager.listeners) listener(visibilityManager.currentState);
- };
- document.addEventListener("visibilitychange", onVisibilityChange);
- return waitForSuccessfulPingInternal(socketUrl, visibilityManager);
- }
- const blob = new Blob([
- "\"use strict\";",
- `const waitForSuccessfulPingInternal = ${waitForSuccessfulPingInternal.toString()};`,
- `const fn = ${pingWorkerContentMain.toString()};`,
- `fn(${JSON.stringify(socketUrl)})`
- ], { type: "application/javascript" });
- const objURL = URL.createObjectURL(blob);
- const sharedWorker = new SharedWorker(objURL);
- return new Promise((resolve, reject) => {
- const onVisibilityChange = () => {
- sharedWorker.port.postMessage({ visibility: document.visibilityState });
- };
- document.addEventListener("visibilitychange", onVisibilityChange);
- sharedWorker.port.addEventListener("message", (event) => {
- document.removeEventListener("visibilitychange", onVisibilityChange);
- sharedWorker.port.close();
- const data = event.data;
- if (data.type === "error") {
- reject(data.error);
- return;
- }
- resolve();
- });
- onVisibilityChange();
- sharedWorker.port.start();
- });
-}
-function pingWorkerContentMain(socketUrl) {
- self.addEventListener("connect", (_event) => {
- const port = _event.ports[0];
- if (!socketUrl) {
- port.postMessage({
- type: "error",
- error: /* @__PURE__ */ new Error("socketUrl not found")
- });
- return;
- }
- const visibilityManager = {
- currentState: "visible",
- listeners: /* @__PURE__ */ new Set()
- };
- port.addEventListener("message", (event) => {
- const { visibility } = event.data;
- visibilityManager.currentState = visibility;
- console.debug("[vite] new window visibility", visibility);
- for (const listener of visibilityManager.listeners) listener(visibility);
- });
- port.start();
- console.debug("[vite] connected from window");
- waitForSuccessfulPingInternal(socketUrl, visibilityManager).then(() => {
- console.debug("[vite] ping successful");
- try {
- port.postMessage({ type: "success" });
- } catch (error) {
- port.postMessage({
- type: "error",
- error
- });
- }
- }, (error) => {
- console.debug("[vite] error happened", error);
- try {
- port.postMessage({
- type: "error",
- error
- });
- } catch (error$1) {
- port.postMessage({
- type: "error",
- error: error$1
- });
- }
- });
- });
-}
-async function waitForSuccessfulPingInternal(socketUrl, visibilityManager, ms = 1e3) {
- function wait(ms$1) {
- return new Promise((resolve) => setTimeout(resolve, ms$1));
- }
- async function ping() {
- try {
- const socket = new WebSocket(socketUrl, "vite-ping");
- return new Promise((resolve) => {
- function onOpen() {
- resolve(true);
- close();
- }
- function onError() {
- resolve(false);
- close();
- }
- function close() {
- socket.removeEventListener("open", onOpen);
- socket.removeEventListener("error", onError);
- socket.close();
- }
- socket.addEventListener("open", onOpen);
- socket.addEventListener("error", onError);
- });
- } catch {
- return false;
- }
- }
- function waitForWindowShow(visibilityManager$1) {
- return new Promise((resolve) => {
- const onChange = (newVisibility) => {
- if (newVisibility === "visible") {
- resolve();
- visibilityManager$1.listeners.delete(onChange);
- }
- };
- visibilityManager$1.listeners.add(onChange);
- });
- }
- if (await ping()) return;
- await wait(ms);
- while (true) if (visibilityManager.currentState === "visible") {
- if (await ping()) break;
- await wait(ms);
- } else await waitForWindowShow(visibilityManager);
-}
-const sheetsMap = /* @__PURE__ */ new Map();
-const linkSheetsMap = /* @__PURE__ */ new Map();
-if ("document" in globalThis) {
- document.querySelectorAll("style[data-vite-dev-id]").forEach((el) => {
- sheetsMap.set(el.getAttribute("data-vite-dev-id"), el);
- });
- document.querySelectorAll("link[rel=\"stylesheet\"][data-vite-dev-id]").forEach((el) => {
- linkSheetsMap.set(el.getAttribute("data-vite-dev-id"), el);
- });
-}
-let lastInsertedStyle;
-function updateStyle(id, content) {
- if (linkSheetsMap.has(id)) return;
- let style = sheetsMap.get(id);
- if (!style) {
- style = document.createElement("style");
- style.setAttribute("type", "text/css");
- style.setAttribute("data-vite-dev-id", id);
- style.textContent = content;
- if (cspNonce) style.setAttribute("nonce", cspNonce);
- if (!lastInsertedStyle) {
- document.head.appendChild(style);
- setTimeout(() => {
- lastInsertedStyle = void 0;
- }, 0);
- } else lastInsertedStyle.insertAdjacentElement("afterend", style);
- lastInsertedStyle = style;
- } else style.textContent = content;
- sheetsMap.set(id, style);
-}
-function removeStyle(id) {
- if (linkSheetsMap.has(id)) {
- document.querySelectorAll(`link[rel="stylesheet"][data-vite-dev-id]`).forEach((el) => {
- if (el.getAttribute("data-vite-dev-id") === id) el.remove();
- });
- linkSheetsMap.delete(id);
- }
- const style = sheetsMap.get(id);
- if (style) {
- document.head.removeChild(style);
- sheetsMap.delete(id);
- }
-}
-function createHotContext(ownerPath) {
- return new HMRContext(hmrClient, ownerPath);
-}
-/**
-* urls here are dynamic import() urls that couldn't be statically analyzed
-*/
-function injectQuery(url, queryToInject) {
- if (url[0] !== "." && url[0] !== "/") return url;
- const pathname = url.replace(/[?#].*$/, "");
- const { search, hash } = new URL(url, "http://vite.dev");
- return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ""}${hash || ""}`;
-}
-
-//#endregion
-export { ErrorOverlay, createHotContext, injectQuery, removeStyle, updateStyle }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/client/env.mjs b/vanilla/node_modules/vite/dist/client/env.mjs
deleted file mode 100644
index c28abfd..0000000
--- a/vanilla/node_modules/vite/dist/client/env.mjs
+++ /dev/null
@@ -1,19 +0,0 @@
-//#region src/client/env.ts
-const context = (() => {
- if (typeof globalThis !== "undefined") return globalThis;
- else if (typeof self !== "undefined") return self;
- else if (typeof window !== "undefined") return window;
- else return Function("return this")();
-})();
-const defines = __DEFINES__;
-Object.keys(defines).forEach((key) => {
- const segments = key.split(".");
- let target = context;
- for (let i = 0; i < segments.length; i++) {
- const segment = segments[i];
- if (i === segments.length - 1) target[segment] = defines[key];
- else target = target[segment] || (target[segment] = {});
- }
-});
-
-//#endregion \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/chunks/build.js b/vanilla/node_modules/vite/dist/node/chunks/build.js
deleted file mode 100644
index cd247f6..0000000
--- a/vanilla/node_modules/vite/dist/node/chunks/build.js
+++ /dev/null
@@ -1,4 +0,0 @@
-import "./logger.js";
-import { A as toOutputFilePathInCss, C as onRollupLog, D as resolveBuilderOptions, E as resolveBuildPlugins, M as toOutputFilePathInJS, N as toOutputFilePathWithoutRuntime, O as resolveLibFilename, S as injectEnvironmentToHooks, T as resolveBuildOutputs, _ as build, b as createBuilder, g as BuildEnvironment, j as toOutputFilePathInHtml, k as resolveUserExternal, v as buildEnvironmentOptionsDefaults, w as resolveBuildEnvironmentOptions, x as createToImportMetaURLBasedRelativeRuntime, y as builderOptionsDefaults } from "./config.js";
-
-export { createBuilder, resolveBuildPlugins }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/chunks/build2.js b/vanilla/node_modules/vite/dist/node/chunks/build2.js
deleted file mode 100644
index c7ecfa3..0000000
--- a/vanilla/node_modules/vite/dist/node/chunks/build2.js
+++ /dev/null
@@ -1,5538 +0,0 @@
-import { i as __require, t as __commonJSMin } from "./chunk.js";
-import { t as require_lib } from "./lib.js";
-
-//#region ../../node_modules/.pnpm/postcss-modules@6.0.1_postcss@8.5.6/node_modules/postcss-modules/build/fs.js
-var require_fs = /* @__PURE__ */ __commonJSMin(((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getFileSystem = getFileSystem;
- exports.setFileSystem = setFileSystem;
- let fileSystem = {
- readFile: () => {
- throw Error("readFile not implemented");
- },
- writeFile: () => {
- throw Error("writeFile not implemented");
- }
- };
- function setFileSystem(fs) {
- fileSystem.readFile = fs.readFile;
- fileSystem.writeFile = fs.writeFile;
- }
- function getFileSystem() {
- return fileSystem;
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-modules@6.0.1_postcss@8.5.6/node_modules/postcss-modules/build/unquote.js
-var require_unquote = /* @__PURE__ */ __commonJSMin(((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.default = unquote;
- const reg = /['"]/;
- function unquote(str$1) {
- if (!str$1) return "";
- if (reg.test(str$1.charAt(0))) str$1 = str$1.substr(1);
- if (reg.test(str$1.charAt(str$1.length - 1))) str$1 = str$1.substr(0, str$1.length - 1);
- return str$1;
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/icss-utils@5.1.0_postcss@8.5.6/node_modules/icss-utils/src/replaceValueSymbols.js
-var require_replaceValueSymbols = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const matchValueName = /[$]?[\w-]+/g;
- const replaceValueSymbols$2 = (value, replacements) => {
- let matches;
- while (matches = matchValueName.exec(value)) {
- const replacement = replacements[matches[0]];
- if (replacement) {
- value = value.slice(0, matches.index) + replacement + value.slice(matchValueName.lastIndex);
- matchValueName.lastIndex -= matches[0].length - replacement.length;
- }
- }
- return value;
- };
- module.exports = replaceValueSymbols$2;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/icss-utils@5.1.0_postcss@8.5.6/node_modules/icss-utils/src/replaceSymbols.js
-var require_replaceSymbols = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const replaceValueSymbols$1 = require_replaceValueSymbols();
- const replaceSymbols$1 = (css, replacements) => {
- css.walk((node) => {
- if (node.type === "decl" && node.value) node.value = replaceValueSymbols$1(node.value.toString(), replacements);
- else if (node.type === "rule" && node.selector) node.selector = replaceValueSymbols$1(node.selector.toString(), replacements);
- else if (node.type === "atrule" && node.params) node.params = replaceValueSymbols$1(node.params.toString(), replacements);
- });
- };
- module.exports = replaceSymbols$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/icss-utils@5.1.0_postcss@8.5.6/node_modules/icss-utils/src/extractICSS.js
-var require_extractICSS = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
- const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/;
- const getDeclsObject = (rule) => {
- const object = {};
- rule.walkDecls((decl) => {
- const before = decl.raws.before ? decl.raws.before.trim() : "";
- object[before + decl.prop] = decl.value;
- });
- return object;
- };
- /**
- *
- * @param {string} css
- * @param {boolean} removeRules
- * @param {'auto' | 'rule' | 'at-rule'} mode
- */
- const extractICSS$2 = (css, removeRules = true, mode = "auto") => {
- const icssImports = {};
- const icssExports = {};
- function addImports(node, path$2) {
- const unquoted = path$2.replace(/'|"/g, "");
- icssImports[unquoted] = Object.assign(icssImports[unquoted] || {}, getDeclsObject(node));
- if (removeRules) node.remove();
- }
- function addExports(node) {
- Object.assign(icssExports, getDeclsObject(node));
- if (removeRules) node.remove();
- }
- css.each((node) => {
- if (node.type === "rule" && mode !== "at-rule") {
- if (node.selector.slice(0, 7) === ":import") {
- const matches = importPattern.exec(node.selector);
- if (matches) addImports(node, matches[1]);
- }
- if (node.selector === ":export") addExports(node);
- }
- if (node.type === "atrule" && mode !== "rule") {
- if (node.name === "icss-import") {
- const matches = balancedQuotes.exec(node.params);
- if (matches) addImports(node, matches[1]);
- }
- if (node.name === "icss-export") addExports(node);
- }
- });
- return {
- icssImports,
- icssExports
- };
- };
- module.exports = extractICSS$2;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/icss-utils@5.1.0_postcss@8.5.6/node_modules/icss-utils/src/createICSSRules.js
-var require_createICSSRules = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const createImports = (imports, postcss, mode = "rule") => {
- return Object.keys(imports).map((path$2) => {
- const aliases = imports[path$2];
- const declarations = Object.keys(aliases).map((key) => postcss.decl({
- prop: key,
- value: aliases[key],
- raws: { before: "\n " }
- }));
- const hasDeclarations = declarations.length > 0;
- const rule = mode === "rule" ? postcss.rule({
- selector: `:import('${path$2}')`,
- raws: { after: hasDeclarations ? "\n" : "" }
- }) : postcss.atRule({
- name: "icss-import",
- params: `'${path$2}'`,
- raws: { after: hasDeclarations ? "\n" : "" }
- });
- if (hasDeclarations) rule.append(declarations);
- return rule;
- });
- };
- const createExports = (exports$1, postcss, mode = "rule") => {
- const declarations = Object.keys(exports$1).map((key) => postcss.decl({
- prop: key,
- value: exports$1[key],
- raws: { before: "\n " }
- }));
- if (declarations.length === 0) return [];
- const rule = mode === "rule" ? postcss.rule({
- selector: `:export`,
- raws: { after: "\n" }
- }) : postcss.atRule({
- name: "icss-export",
- raws: { after: "\n" }
- });
- rule.append(declarations);
- return [rule];
- };
- const createICSSRules$1 = (imports, exports$1, postcss, mode) => [...createImports(imports, postcss, mode), ...createExports(exports$1, postcss, mode)];
- module.exports = createICSSRules$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/icss-utils@5.1.0_postcss@8.5.6/node_modules/icss-utils/src/index.js
-var require_src$4 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const replaceValueSymbols = require_replaceValueSymbols();
- const replaceSymbols = require_replaceSymbols();
- const extractICSS$1 = require_extractICSS();
- const createICSSRules = require_createICSSRules();
- module.exports = {
- replaceValueSymbols,
- replaceSymbols,
- extractICSS: extractICSS$1,
- createICSSRules
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-modules@6.0.1_postcss@8.5.6/node_modules/postcss-modules/build/Parser.js
-var require_Parser = /* @__PURE__ */ __commonJSMin(((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.default = void 0;
- var _icssUtils = require_src$4();
- const importRegexp = /^:import\((.+)\)$/;
- var Parser$1 = class {
- constructor(pathFetcher, trace) {
- this.pathFetcher = pathFetcher;
- this.plugin = this.plugin.bind(this);
- this.exportTokens = {};
- this.translations = {};
- this.trace = trace;
- }
- plugin() {
- const parser$1 = this;
- return {
- postcssPlugin: "css-modules-parser",
- async OnceExit(css) {
- await Promise.all(parser$1.fetchAllImports(css));
- parser$1.linkImportedSymbols(css);
- return parser$1.extractExports(css);
- }
- };
- }
- fetchAllImports(css) {
- let imports = [];
- css.each((node) => {
- if (node.type == "rule" && node.selector.match(importRegexp)) imports.push(this.fetchImport(node, css.source.input.from, imports.length));
- });
- return imports;
- }
- linkImportedSymbols(css) {
- (0, _icssUtils.replaceSymbols)(css, this.translations);
- }
- extractExports(css) {
- css.each((node) => {
- if (node.type == "rule" && node.selector == ":export") this.handleExport(node);
- });
- }
- handleExport(exportNode) {
- exportNode.each((decl) => {
- if (decl.type == "decl") {
- Object.keys(this.translations).forEach((translation) => {
- decl.value = decl.value.replace(translation, this.translations[translation]);
- });
- this.exportTokens[decl.prop] = decl.value;
- }
- });
- exportNode.remove();
- }
- async fetchImport(importNode, relativeTo, depNr) {
- const file = importNode.selector.match(importRegexp)[1];
- const depTrace = this.trace + String.fromCharCode(depNr);
- const exports$1 = await this.pathFetcher(file, relativeTo, depTrace);
- try {
- importNode.each((decl) => {
- if (decl.type == "decl") this.translations[decl.prop] = exports$1[decl.value];
- });
- importNode.remove();
- } catch (err) {
- console.log(err);
- }
- }
- };
- exports.default = Parser$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-modules@6.0.1_postcss@8.5.6/node_modules/postcss-modules/build/saveJSON.js
-var require_saveJSON = /* @__PURE__ */ __commonJSMin(((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.default = saveJSON;
- var _fs$2 = require_fs();
- function saveJSON(cssFile, json) {
- return new Promise((resolve, reject) => {
- const { writeFile } = (0, _fs$2.getFileSystem)();
- writeFile(`${cssFile}.json`, JSON.stringify(json), (e) => e ? reject(e) : resolve(json));
- });
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/lodash.camelcase@4.3.0/node_modules/lodash.camelcase/index.js
-var require_lodash = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /**
- * lodash (Custom Build) <https://lodash.com/>
- * Build: `lodash modularize exports="npm" -o ./`
- * Copyright jQuery Foundation and other contributors <https://jquery.org/>
- * Released under MIT license <https://lodash.com/license>
- * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
- * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- */
- /** Used as references for various `Number` constants. */
- var INFINITY = Infinity;
- /** `Object#toString` result references. */
- var symbolTag = "[object Symbol]";
- /** Used to match words composed of alphanumeric characters. */
- var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
- /** Used to match Latin Unicode letters (excluding mathematical operators). */
- var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
- /** Used to compose unicode character classes. */
- var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23", rsComboSymbolsRange = "\\u20d0-\\u20f0", rsDingbatRange = "\\u2700-\\u27bf", rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff", rsMathOpRange = "\\xac\\xb1\\xd7\\xf7", rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf", rsPunctuationRange = "\\u2000-\\u206f", rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde", rsVarRange = "\\ufe0e\\ufe0f", rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
- /** Used to compose unicode capture groups. */
- var rsApos = "['’]", rsAstral = "[" + rsAstralRange + "]", rsBreak = "[" + rsBreakRange + "]", rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]", rsDigits = "\\d+", rsDingbat = "[" + rsDingbatRange + "]", rsLower = "[" + rsLowerRange + "]", rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsUpper = "[" + rsUpperRange + "]", rsZWJ = "\\u200d";
- /** Used to compose unicode regexes. */
- var rsLowerMisc = "(?:" + rsLower + "|" + rsMisc + ")", rsUpperMisc = "(?:" + rsUpper + "|" + rsMisc + ")", rsOptLowerContr = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?", rsOptUpperContr = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange + "]?", rsOptJoin = "(?:" + rsZWJ + "(?:" + [
- rsNonAstral,
- rsRegional,
- rsSurrPair
- ].join("|") + ")" + rsOptVar + reOptMod + ")*", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = "(?:" + [
- rsDingbat,
- rsRegional,
- rsSurrPair
- ].join("|") + ")" + rsSeq, rsSymbol = "(?:" + [
- rsNonAstral + rsCombo + "?",
- rsCombo,
- rsRegional,
- rsSurrPair,
- rsAstral
- ].join("|") + ")";
- /** Used to match apostrophes. */
- var reApos = RegExp(rsApos, "g");
- /**
- * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
- * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
- */
- var reComboMark = RegExp(rsCombo, "g");
- /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
- var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g");
- /** Used to match complex or compound words. */
- var reUnicodeWord = RegExp([
- rsUpper + "?" + rsLower + "+" + rsOptLowerContr + "(?=" + [
- rsBreak,
- rsUpper,
- "$"
- ].join("|") + ")",
- rsUpperMisc + "+" + rsOptUpperContr + "(?=" + [
- rsBreak,
- rsUpper + rsLowerMisc,
- "$"
- ].join("|") + ")",
- rsUpper + "?" + rsLowerMisc + "+" + rsOptLowerContr,
- rsUpper + "+" + rsOptUpperContr,
- rsDigits,
- rsEmoji
- ].join("|"), "g");
- /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
- var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + "]");
- /** Used to detect strings that need a more robust regexp to match words. */
- var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
- /** Used to map Latin Unicode letters to basic Latin letters. */
- var deburredLetters = {
- "À": "A",
- "Á": "A",
- "Â": "A",
- "Ã": "A",
- "Ä": "A",
- "Å": "A",
- "à": "a",
- "á": "a",
- "â": "a",
- "ã": "a",
- "ä": "a",
- "å": "a",
- "Ç": "C",
- "ç": "c",
- "Ð": "D",
- "ð": "d",
- "È": "E",
- "É": "E",
- "Ê": "E",
- "Ë": "E",
- "è": "e",
- "é": "e",
- "ê": "e",
- "ë": "e",
- "Ì": "I",
- "Í": "I",
- "Î": "I",
- "Ï": "I",
- "ì": "i",
- "í": "i",
- "î": "i",
- "ï": "i",
- "Ñ": "N",
- "ñ": "n",
- "Ò": "O",
- "Ó": "O",
- "Ô": "O",
- "Õ": "O",
- "Ö": "O",
- "Ø": "O",
- "ò": "o",
- "ó": "o",
- "ô": "o",
- "õ": "o",
- "ö": "o",
- "ø": "o",
- "Ù": "U",
- "Ú": "U",
- "Û": "U",
- "Ü": "U",
- "ù": "u",
- "ú": "u",
- "û": "u",
- "ü": "u",
- "Ý": "Y",
- "ý": "y",
- "ÿ": "y",
- "Æ": "Ae",
- "æ": "ae",
- "Þ": "Th",
- "þ": "th",
- "ß": "ss",
- "Ā": "A",
- "Ă": "A",
- "Ą": "A",
- "ā": "a",
- "ă": "a",
- "ą": "a",
- "Ć": "C",
- "Ĉ": "C",
- "Ċ": "C",
- "Č": "C",
- "ć": "c",
- "ĉ": "c",
- "ċ": "c",
- "č": "c",
- "Ď": "D",
- "Đ": "D",
- "ď": "d",
- "đ": "d",
- "Ē": "E",
- "Ĕ": "E",
- "Ė": "E",
- "Ę": "E",
- "Ě": "E",
- "ē": "e",
- "ĕ": "e",
- "ė": "e",
- "ę": "e",
- "ě": "e",
- "Ĝ": "G",
- "Ğ": "G",
- "Ġ": "G",
- "Ģ": "G",
- "ĝ": "g",
- "ğ": "g",
- "ġ": "g",
- "ģ": "g",
- "Ĥ": "H",
- "Ħ": "H",
- "ĥ": "h",
- "ħ": "h",
- "Ĩ": "I",
- "Ī": "I",
- "Ĭ": "I",
- "Į": "I",
- "İ": "I",
- "ĩ": "i",
- "ī": "i",
- "ĭ": "i",
- "į": "i",
- "ı": "i",
- "Ĵ": "J",
- "ĵ": "j",
- "Ķ": "K",
- "ķ": "k",
- "ĸ": "k",
- "Ĺ": "L",
- "Ļ": "L",
- "Ľ": "L",
- "Ŀ": "L",
- "Ł": "L",
- "ĺ": "l",
- "ļ": "l",
- "ľ": "l",
- "ŀ": "l",
- "ł": "l",
- "Ń": "N",
- "Ņ": "N",
- "Ň": "N",
- "Ŋ": "N",
- "ń": "n",
- "ņ": "n",
- "ň": "n",
- "ŋ": "n",
- "Ō": "O",
- "Ŏ": "O",
- "Ő": "O",
- "ō": "o",
- "ŏ": "o",
- "ő": "o",
- "Ŕ": "R",
- "Ŗ": "R",
- "Ř": "R",
- "ŕ": "r",
- "ŗ": "r",
- "ř": "r",
- "Ś": "S",
- "Ŝ": "S",
- "Ş": "S",
- "Š": "S",
- "ś": "s",
- "ŝ": "s",
- "ş": "s",
- "š": "s",
- "Ţ": "T",
- "Ť": "T",
- "Ŧ": "T",
- "ţ": "t",
- "ť": "t",
- "ŧ": "t",
- "Ũ": "U",
- "Ū": "U",
- "Ŭ": "U",
- "Ů": "U",
- "Ű": "U",
- "Ų": "U",
- "ũ": "u",
- "ū": "u",
- "ŭ": "u",
- "ů": "u",
- "ű": "u",
- "ų": "u",
- "Ŵ": "W",
- "ŵ": "w",
- "Ŷ": "Y",
- "ŷ": "y",
- "Ÿ": "Y",
- "Ź": "Z",
- "Ż": "Z",
- "Ž": "Z",
- "ź": "z",
- "ż": "z",
- "ž": "z",
- "IJ": "IJ",
- "ij": "ij",
- "Œ": "Oe",
- "œ": "oe",
- "ʼn": "'n",
- "ſ": "ss"
- };
- /** Detect free variable `global` from Node.js. */
- var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
- /** Detect free variable `self`. */
- var freeSelf = typeof self == "object" && self && self.Object === Object && self;
- /** Used as a reference to the global object. */
- var root$1 = freeGlobal || freeSelf || Function("return this")();
- /**
- * A specialized version of `_.reduce` for arrays without support for
- * iteratee shorthands.
- *
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} iteratee The function invoked per iteration.
- * @param {*} [accumulator] The initial value.
- * @param {boolean} [initAccum] Specify using the first element of `array` as
- * the initial value.
- * @returns {*} Returns the accumulated value.
- */
- function arrayReduce(array, iteratee, accumulator, initAccum) {
- var index = -1, length = array ? array.length : 0;
- if (initAccum && length) accumulator = array[++index];
- while (++index < length) accumulator = iteratee(accumulator, array[index], index, array);
- return accumulator;
- }
- /**
- * Converts an ASCII `string` to an array.
- *
- * @private
- * @param {string} string The string to convert.
- * @returns {Array} Returns the converted array.
- */
- function asciiToArray(string$1) {
- return string$1.split("");
- }
- /**
- * Splits an ASCII `string` into an array of its words.
- *
- * @private
- * @param {string} The string to inspect.
- * @returns {Array} Returns the words of `string`.
- */
- function asciiWords(string$1) {
- return string$1.match(reAsciiWord) || [];
- }
- /**
- * The base implementation of `_.propertyOf` without support for deep paths.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Function} Returns the new accessor function.
- */
- function basePropertyOf(object) {
- return function(key) {
- return object == null ? void 0 : object[key];
- };
- }
- /**
- * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
- * letters to basic Latin letters.
- *
- * @private
- * @param {string} letter The matched letter to deburr.
- * @returns {string} Returns the deburred letter.
- */
- var deburrLetter = basePropertyOf(deburredLetters);
- /**
- * Checks if `string` contains Unicode symbols.
- *
- * @private
- * @param {string} string The string to inspect.
- * @returns {boolean} Returns `true` if a symbol is found, else `false`.
- */
- function hasUnicode(string$1) {
- return reHasUnicode.test(string$1);
- }
- /**
- * Checks if `string` contains a word composed of Unicode symbols.
- *
- * @private
- * @param {string} string The string to inspect.
- * @returns {boolean} Returns `true` if a word is found, else `false`.
- */
- function hasUnicodeWord(string$1) {
- return reHasUnicodeWord.test(string$1);
- }
- /**
- * Converts `string` to an array.
- *
- * @private
- * @param {string} string The string to convert.
- * @returns {Array} Returns the converted array.
- */
- function stringToArray(string$1) {
- return hasUnicode(string$1) ? unicodeToArray(string$1) : asciiToArray(string$1);
- }
- /**
- * Converts a Unicode `string` to an array.
- *
- * @private
- * @param {string} string The string to convert.
- * @returns {Array} Returns the converted array.
- */
- function unicodeToArray(string$1) {
- return string$1.match(reUnicode) || [];
- }
- /**
- * Splits a Unicode `string` into an array of its words.
- *
- * @private
- * @param {string} The string to inspect.
- * @returns {Array} Returns the words of `string`.
- */
- function unicodeWords(string$1) {
- return string$1.match(reUnicodeWord) || [];
- }
- /**
- * Used to resolve the
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
- * of values.
- */
- var objectToString = Object.prototype.toString;
- /** Built-in value references. */
- var Symbol$1 = root$1.Symbol;
- /** Used to convert symbols to primitives and strings. */
- var symbolProto = Symbol$1 ? Symbol$1.prototype : void 0, symbolToString = symbolProto ? symbolProto.toString : void 0;
- /**
- * The base implementation of `_.slice` without an iteratee call guard.
- *
- * @private
- * @param {Array} array The array to slice.
- * @param {number} [start=0] The start position.
- * @param {number} [end=array.length] The end position.
- * @returns {Array} Returns the slice of `array`.
- */
- function baseSlice(array, start, end) {
- var index = -1, length = array.length;
- if (start < 0) start = -start > length ? 0 : length + start;
- end = end > length ? length : end;
- if (end < 0) end += length;
- length = start > end ? 0 : end - start >>> 0;
- start >>>= 0;
- var result = Array(length);
- while (++index < length) result[index] = array[index + start];
- return result;
- }
- /**
- * The base implementation of `_.toString` which doesn't convert nullish
- * values to empty strings.
- *
- * @private
- * @param {*} value The value to process.
- * @returns {string} Returns the string.
- */
- function baseToString(value) {
- if (typeof value == "string") return value;
- if (isSymbol(value)) return symbolToString ? symbolToString.call(value) : "";
- var result = value + "";
- return result == "0" && 1 / value == -INFINITY ? "-0" : result;
- }
- /**
- * Casts `array` to a slice if it's needed.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {number} start The start position.
- * @param {number} [end=array.length] The end position.
- * @returns {Array} Returns the cast slice.
- */
- function castSlice(array, start, end) {
- var length = array.length;
- end = end === void 0 ? length : end;
- return !start && end >= length ? array : baseSlice(array, start, end);
- }
- /**
- * Creates a function like `_.lowerFirst`.
- *
- * @private
- * @param {string} methodName The name of the `String` case method to use.
- * @returns {Function} Returns the new case function.
- */
- function createCaseFirst(methodName) {
- return function(string$1) {
- string$1 = toString(string$1);
- var strSymbols = hasUnicode(string$1) ? stringToArray(string$1) : void 0;
- var chr = strSymbols ? strSymbols[0] : string$1.charAt(0);
- var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string$1.slice(1);
- return chr[methodName]() + trailing;
- };
- }
- /**
- * Creates a function like `_.camelCase`.
- *
- * @private
- * @param {Function} callback The function to combine each word.
- * @returns {Function} Returns the new compounder function.
- */
- function createCompounder(callback) {
- return function(string$1) {
- return arrayReduce(words(deburr(string$1).replace(reApos, "")), callback, "");
- };
- }
- /**
- * Checks if `value` is object-like. A value is object-like if it's not `null`
- * and has a `typeof` result of "object".
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
- * @example
- *
- * _.isObjectLike({});
- * // => true
- *
- * _.isObjectLike([1, 2, 3]);
- * // => true
- *
- * _.isObjectLike(_.noop);
- * // => false
- *
- * _.isObjectLike(null);
- * // => false
- */
- function isObjectLike(value) {
- return !!value && typeof value == "object";
- }
- /**
- * Checks if `value` is classified as a `Symbol` primitive or object.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
- * @example
- *
- * _.isSymbol(Symbol.iterator);
- * // => true
- *
- * _.isSymbol('abc');
- * // => false
- */
- function isSymbol(value) {
- return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
- }
- /**
- * Converts `value` to a string. An empty string is returned for `null`
- * and `undefined` values. The sign of `-0` is preserved.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to process.
- * @returns {string} Returns the string.
- * @example
- *
- * _.toString(null);
- * // => ''
- *
- * _.toString(-0);
- * // => '-0'
- *
- * _.toString([1, 2, 3]);
- * // => '1,2,3'
- */
- function toString(value) {
- return value == null ? "" : baseToString(value);
- }
- /**
- * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category String
- * @param {string} [string=''] The string to convert.
- * @returns {string} Returns the camel cased string.
- * @example
- *
- * _.camelCase('Foo Bar');
- * // => 'fooBar'
- *
- * _.camelCase('--foo-bar--');
- * // => 'fooBar'
- *
- * _.camelCase('__FOO_BAR__');
- * // => 'fooBar'
- */
- var camelCase = createCompounder(function(result, word$1, index) {
- word$1 = word$1.toLowerCase();
- return result + (index ? capitalize(word$1) : word$1);
- });
- /**
- * Converts the first character of `string` to upper case and the remaining
- * to lower case.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category String
- * @param {string} [string=''] The string to capitalize.
- * @returns {string} Returns the capitalized string.
- * @example
- *
- * _.capitalize('FRED');
- * // => 'Fred'
- */
- function capitalize(string$1) {
- return upperFirst(toString(string$1).toLowerCase());
- }
- /**
- * Deburrs `string` by converting
- * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
- * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
- * letters to basic Latin letters and removing
- * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category String
- * @param {string} [string=''] The string to deburr.
- * @returns {string} Returns the deburred string.
- * @example
- *
- * _.deburr('déjà vu');
- * // => 'deja vu'
- */
- function deburr(string$1) {
- string$1 = toString(string$1);
- return string$1 && string$1.replace(reLatin, deburrLetter).replace(reComboMark, "");
- }
- /**
- * Converts the first character of `string` to upper case.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category String
- * @param {string} [string=''] The string to convert.
- * @returns {string} Returns the converted string.
- * @example
- *
- * _.upperFirst('fred');
- * // => 'Fred'
- *
- * _.upperFirst('FRED');
- * // => 'FRED'
- */
- var upperFirst = createCaseFirst("toUpperCase");
- /**
- * Splits `string` into an array of its words.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category String
- * @param {string} [string=''] The string to inspect.
- * @param {RegExp|string} [pattern] The pattern to match words.
- * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
- * @returns {Array} Returns the words of `string`.
- * @example
- *
- * _.words('fred, barney, & pebbles');
- * // => ['fred', 'barney', 'pebbles']
- *
- * _.words('fred, barney, & pebbles', /[^, ]+/g);
- * // => ['fred', 'barney', '&', 'pebbles']
- */
- function words(string$1, pattern, guard) {
- string$1 = toString(string$1);
- pattern = guard ? void 0 : pattern;
- if (pattern === void 0) return hasUnicodeWord(string$1) ? unicodeWords(string$1) : asciiWords(string$1);
- return string$1.match(pattern) || [];
- }
- module.exports = camelCase;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-modules@6.0.1_postcss@8.5.6/node_modules/postcss-modules/build/localsConvention.js
-var require_localsConvention = /* @__PURE__ */ __commonJSMin(((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.makeLocalsConventionReducer = makeLocalsConventionReducer;
- var _lodash = _interopRequireDefault$22(require_lodash());
- function _interopRequireDefault$22(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- function dashesCamelCase(string$1) {
- return string$1.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase());
- }
- function makeLocalsConventionReducer(localsConvention, inputFile) {
- const isFunc = typeof localsConvention === "function";
- return (tokens$1, [className$1, value]) => {
- if (isFunc) {
- const convention = localsConvention(className$1, value, inputFile);
- tokens$1[convention] = value;
- return tokens$1;
- }
- switch (localsConvention) {
- case "camelCase":
- tokens$1[className$1] = value;
- tokens$1[(0, _lodash.default)(className$1)] = value;
- break;
- case "camelCaseOnly":
- tokens$1[(0, _lodash.default)(className$1)] = value;
- break;
- case "dashes":
- tokens$1[className$1] = value;
- tokens$1[dashesCamelCase(className$1)] = value;
- break;
- case "dashesOnly":
- tokens$1[dashesCamelCase(className$1)] = value;
- break;
- }
- return tokens$1;
- };
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-modules@6.0.1_postcss@8.5.6/node_modules/postcss-modules/build/FileSystemLoader.js
-var require_FileSystemLoader = /* @__PURE__ */ __commonJSMin(((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.default = void 0;
- var _postcss$1 = _interopRequireDefault$21(__require("postcss"));
- var _path = _interopRequireDefault$21(__require("path"));
- var _Parser$1 = _interopRequireDefault$21(require_Parser());
- var _fs$1 = require_fs();
- function _interopRequireDefault$21(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- var Core = class Core {
- constructor(plugins) {
- this.plugins = plugins || Core.defaultPlugins;
- }
- async load(sourceString, sourcePath, trace, pathFetcher) {
- const parser$1 = new _Parser$1.default(pathFetcher, trace);
- const plugins = this.plugins.concat([parser$1.plugin()]);
- return {
- injectableSource: (await (0, _postcss$1.default)(plugins).process(sourceString, { from: sourcePath })).css,
- exportTokens: parser$1.exportTokens
- };
- }
- };
- const traceKeySorter = (a, b) => {
- if (a.length < b.length) return a < b.substring(0, a.length) ? -1 : 1;
- if (a.length > b.length) return a.substring(0, b.length) <= b ? -1 : 1;
- return a < b ? -1 : 1;
- };
- var FileSystemLoader = class {
- constructor(root$2, plugins, fileResolve) {
- if (root$2 === "/" && process.platform === "win32") {
- const cwdDrive = process.cwd().slice(0, 3);
- if (!/^[A-Za-z]:\\$/.test(cwdDrive)) throw new Error(`Failed to obtain root from "${process.cwd()}".`);
- root$2 = cwdDrive;
- }
- this.root = root$2;
- this.fileResolve = fileResolve;
- this.sources = {};
- this.traces = {};
- this.importNr = 0;
- this.core = new Core(plugins);
- this.tokensByFile = {};
- this.fs = (0, _fs$1.getFileSystem)();
- }
- async fetch(_newPath, relativeTo, _trace) {
- const newPath = _newPath.replace(/^["']|["']$/g, "");
- const trace = _trace || String.fromCharCode(this.importNr++);
- const useFileResolve = typeof this.fileResolve === "function";
- const fileResolvedPath = useFileResolve ? await this.fileResolve(newPath, relativeTo) : await Promise.resolve();
- if (fileResolvedPath && !_path.default.isAbsolute(fileResolvedPath)) throw new Error("The returned path from the \"fileResolve\" option must be absolute.");
- const relativeDir = _path.default.dirname(relativeTo);
- const rootRelativePath = fileResolvedPath || _path.default.resolve(relativeDir, newPath);
- let fileRelativePath = fileResolvedPath || _path.default.resolve(_path.default.resolve(this.root, relativeDir), newPath);
- if (!useFileResolve && newPath[0] !== "." && !_path.default.isAbsolute(newPath)) try {
- fileRelativePath = __require.resolve(newPath);
- } catch (e) {}
- const tokens$1 = this.tokensByFile[fileRelativePath];
- if (tokens$1) return tokens$1;
- return new Promise((resolve, reject) => {
- this.fs.readFile(fileRelativePath, "utf-8", async (err, source) => {
- if (err) reject(err);
- const { injectableSource, exportTokens } = await this.core.load(source, rootRelativePath, trace, this.fetch.bind(this));
- this.sources[fileRelativePath] = injectableSource;
- this.traces[trace] = fileRelativePath;
- this.tokensByFile[fileRelativePath] = exportTokens;
- resolve(exportTokens);
- });
- });
- }
- get finalSource() {
- const traces = this.traces;
- const sources = this.sources;
- let written = /* @__PURE__ */ new Set();
- return Object.keys(traces).sort(traceKeySorter).map((key) => {
- const filename = traces[key];
- if (written.has(filename)) return null;
- written.add(filename);
- return sources[filename];
- }).join("");
- }
- };
- exports.default = FileSystemLoader;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-modules-extract-imports@3.1.0_postcss@8.5.6/node_modules/postcss-modules-extract-imports/src/topologicalSort.js
-var require_topologicalSort = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const PERMANENT_MARKER = 2;
- const TEMPORARY_MARKER = 1;
- function createError(node, graph) {
- const er = /* @__PURE__ */ new Error("Nondeterministic import's order");
- er.nodes = [node, graph[node].find((relatedNode) => graph[relatedNode].indexOf(node) > -1)];
- return er;
- }
- function walkGraph(node, graph, state, result, strict) {
- if (state[node] === PERMANENT_MARKER) return;
- if (state[node] === TEMPORARY_MARKER) {
- if (strict) return createError(node, graph);
- return;
- }
- state[node] = TEMPORARY_MARKER;
- const children = graph[node];
- const length = children.length;
- for (let i$1 = 0; i$1 < length; ++i$1) {
- const error = walkGraph(children[i$1], graph, state, result, strict);
- if (error instanceof Error) return error;
- }
- state[node] = PERMANENT_MARKER;
- result.push(node);
- }
- function topologicalSort$1(graph, strict) {
- const result = [];
- const state = {};
- const nodes = Object.keys(graph);
- const length = nodes.length;
- for (let i$1 = 0; i$1 < length; ++i$1) {
- const er = walkGraph(nodes[i$1], graph, state, result, strict);
- if (er instanceof Error) return er;
- }
- return result;
- }
- module.exports = topologicalSort$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-modules-extract-imports@3.1.0_postcss@8.5.6/node_modules/postcss-modules-extract-imports/src/index.js
-var require_src$3 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const topologicalSort = require_topologicalSort();
- const matchImports$1 = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/;
- const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/;
- const VISITED_MARKER = 1;
- /**
- * :import('G') {}
- *
- * Rule
- * composes: ... from 'A'
- * composes: ... from 'B'
-
- * Rule
- * composes: ... from 'A'
- * composes: ... from 'A'
- * composes: ... from 'C'
- *
- * Results in:
- *
- * graph: {
- * G: [],
- * A: [],
- * B: ['A'],
- * C: ['A'],
- * }
- */
- function addImportToGraph(importId, parentId, graph, visited) {
- const siblingsId = parentId + "_siblings";
- const visitedId = parentId + "_" + importId;
- if (visited[visitedId] !== VISITED_MARKER) {
- if (!Array.isArray(visited[siblingsId])) visited[siblingsId] = [];
- const siblings = visited[siblingsId];
- if (Array.isArray(graph[importId])) graph[importId] = graph[importId].concat(siblings);
- else graph[importId] = siblings.slice();
- visited[visitedId] = VISITED_MARKER;
- siblings.push(importId);
- }
- }
- module.exports = (options = {}) => {
- let importIndex = 0;
- const createImportedName = typeof options.createImportedName !== "function" ? (importName) => `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}` : options.createImportedName;
- const failOnWrongOrder = options.failOnWrongOrder;
- return {
- postcssPlugin: "postcss-modules-extract-imports",
- prepare() {
- const graph = {};
- const visited = {};
- const existingImports = {};
- const importDecls = {};
- const imports = {};
- return { Once(root$2, postcss) {
- root$2.walkRules((rule) => {
- const matches = icssImport.exec(rule.selector);
- if (matches) {
- const [, doubleQuotePath, singleQuotePath] = matches;
- const importPath = doubleQuotePath || singleQuotePath;
- addImportToGraph(importPath, "root", graph, visited);
- existingImports[importPath] = rule;
- }
- });
- root$2.walkDecls(/^composes$/, (declaration) => {
- const multiple = declaration.value.split(",");
- const values = [];
- multiple.forEach((value) => {
- const matches = value.trim().match(matchImports$1);
- if (!matches) {
- values.push(value);
- return;
- }
- let tmpSymbols;
- let [, symbols, doubleQuotePath, singleQuotePath, global$1] = matches;
- if (global$1) tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`);
- else {
- const importPath = doubleQuotePath || singleQuotePath;
- let parent = declaration.parent;
- let parentIndexes = "";
- while (parent.type !== "root") {
- parentIndexes = parent.parent.index(parent) + "_" + parentIndexes;
- parent = parent.parent;
- }
- const { selector: selector$1 } = declaration.parent;
- addImportToGraph(importPath, `_${parentIndexes}${selector$1}`, graph, visited);
- importDecls[importPath] = declaration;
- imports[importPath] = imports[importPath] || {};
- tmpSymbols = symbols.split(/\s+/).map((s) => {
- if (!imports[importPath][s]) imports[importPath][s] = createImportedName(s, importPath);
- return imports[importPath][s];
- });
- }
- values.push(tmpSymbols.join(" "));
- });
- declaration.value = values.join(", ");
- });
- const importsOrder = topologicalSort(graph, failOnWrongOrder);
- if (importsOrder instanceof Error) throw importDecls[importsOrder.nodes.find((importPath) => importDecls.hasOwnProperty(importPath))].error("Failed to resolve order of composed modules " + importsOrder.nodes.map((importPath) => "`" + importPath + "`").join(", ") + ".", {
- plugin: "postcss-modules-extract-imports",
- word: "composes"
- });
- let lastImportRule;
- importsOrder.forEach((path$2) => {
- const importedSymbols = imports[path$2];
- let rule = existingImports[path$2];
- if (!rule && importedSymbols) {
- rule = postcss.rule({
- selector: `:import("${path$2}")`,
- raws: { after: "\n" }
- });
- if (lastImportRule) root$2.insertAfter(lastImportRule, rule);
- else root$2.prepend(rule);
- }
- lastImportRule = rule;
- if (!importedSymbols) return;
- Object.keys(importedSymbols).forEach((importedSymbol) => {
- rule.append(postcss.decl({
- value: importedSymbol,
- prop: importedSymbols[importedSymbol],
- raws: { before: "\n " }
- }));
- });
- });
- } };
- }
- };
- };
- module.exports.postcss = true;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/loader-utils@3.3.1/node_modules/loader-utils/lib/hash/wasm-hash.js
-var require_wasm_hash = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const MAX_SHORT_STRING$1 = Math.floor(65472 / 4) & -4;
- var WasmHash = class {
- /**
- * @param {WebAssembly.Instance} instance wasm instance
- * @param {WebAssembly.Instance[]} instancesPool pool of instances
- * @param {number} chunkSize size of data chunks passed to wasm
- * @param {number} digestSize size of digest returned by wasm
- */
- constructor(instance, instancesPool, chunkSize, digestSize) {
- const exports$1 = instance.exports;
- exports$1.init();
- this.exports = exports$1;
- this.mem = Buffer.from(exports$1.memory.buffer, 0, 65536);
- this.buffered = 0;
- this.instancesPool = instancesPool;
- this.chunkSize = chunkSize;
- this.digestSize = digestSize;
- }
- reset() {
- this.buffered = 0;
- this.exports.init();
- }
- /**
- * @param {Buffer | string} data data
- * @param {BufferEncoding=} encoding encoding
- * @returns {this} itself
- */
- update(data, encoding) {
- if (typeof data === "string") {
- while (data.length > MAX_SHORT_STRING$1) {
- this._updateWithShortString(data.slice(0, MAX_SHORT_STRING$1), encoding);
- data = data.slice(MAX_SHORT_STRING$1);
- }
- this._updateWithShortString(data, encoding);
- return this;
- }
- this._updateWithBuffer(data);
- return this;
- }
- /**
- * @param {string} data data
- * @param {BufferEncoding=} encoding encoding
- * @returns {void}
- */
- _updateWithShortString(data, encoding) {
- const { exports: exports$1, buffered, mem, chunkSize } = this;
- let endPos;
- if (data.length < 70) if (!encoding || encoding === "utf-8" || encoding === "utf8") {
- endPos = buffered;
- for (let i$1 = 0; i$1 < data.length; i$1++) {
- const cc = data.charCodeAt(i$1);
- if (cc < 128) mem[endPos++] = cc;
- else if (cc < 2048) {
- mem[endPos] = cc >> 6 | 192;
- mem[endPos + 1] = cc & 63 | 128;
- endPos += 2;
- } else {
- endPos += mem.write(data.slice(i$1), endPos, encoding);
- break;
- }
- }
- } else if (encoding === "latin1") {
- endPos = buffered;
- for (let i$1 = 0; i$1 < data.length; i$1++) {
- const cc = data.charCodeAt(i$1);
- mem[endPos++] = cc;
- }
- } else endPos = buffered + mem.write(data, buffered, encoding);
- else endPos = buffered + mem.write(data, buffered, encoding);
- if (endPos < chunkSize) this.buffered = endPos;
- else {
- const l = endPos & ~(this.chunkSize - 1);
- exports$1.update(l);
- const newBuffered = endPos - l;
- this.buffered = newBuffered;
- if (newBuffered > 0) mem.copyWithin(0, l, endPos);
- }
- }
- /**
- * @param {Buffer} data data
- * @returns {void}
- */
- _updateWithBuffer(data) {
- const { exports: exports$1, buffered, mem } = this;
- const length = data.length;
- if (buffered + length < this.chunkSize) {
- data.copy(mem, buffered, 0, length);
- this.buffered += length;
- } else {
- const l = buffered + length & ~(this.chunkSize - 1);
- if (l > 65536) {
- let i$1 = 65536 - buffered;
- data.copy(mem, buffered, 0, i$1);
- exports$1.update(65536);
- const stop = l - buffered - 65536;
- while (i$1 < stop) {
- data.copy(mem, 0, i$1, i$1 + 65536);
- exports$1.update(65536);
- i$1 += 65536;
- }
- data.copy(mem, 0, i$1, l - buffered);
- exports$1.update(l - buffered - i$1);
- } else {
- data.copy(mem, buffered, 0, l - buffered);
- exports$1.update(l);
- }
- const newBuffered = length + buffered - l;
- this.buffered = newBuffered;
- if (newBuffered > 0) data.copy(mem, 0, length - newBuffered, length);
- }
- }
- digest(type) {
- const { exports: exports$1, buffered, mem, digestSize } = this;
- exports$1.final(buffered);
- this.instancesPool.push(this);
- const hex$1 = mem.toString("latin1", 0, digestSize);
- if (type === "hex") return hex$1;
- if (type === "binary" || !type) return Buffer.from(hex$1, "hex");
- return Buffer.from(hex$1, "hex").toString(type);
- }
- };
- const create$2 = (wasmModule, instancesPool, chunkSize, digestSize) => {
- if (instancesPool.length > 0) {
- const old = instancesPool.pop();
- old.reset();
- return old;
- } else return new WasmHash(new WebAssembly.Instance(wasmModule), instancesPool, chunkSize, digestSize);
- };
- module.exports = create$2;
- module.exports.MAX_SHORT_STRING = MAX_SHORT_STRING$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/loader-utils@3.3.1/node_modules/loader-utils/lib/hash/xxhash64.js
-var require_xxhash64 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const create$1 = require_wasm_hash();
- const xxhash64 = new WebAssembly.Module(Buffer.from("AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACrUIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAAgAUEgaiIBSw0ACyACJAAgAyQBIAQkAiAFJAMLqwYCAX8EfiMEQgBSBH4jACICQgGJIwEiA0IHiXwjAiIEQgyJfCMDIgVCEol8IAJCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0gA0LP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSAEQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IAVCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0FQsXP2bLx5brqJwsjBCAArXx8IQIDQCABQQhqIABNBEAgAiABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQIgAUEIaiEBDAELCyABQQRqIABNBEACfyACIAE1AgBCh5Wvr5i23puef36FQheJQs/W077Sx6vZQn5C+fPd8Zn2masWfCECIAFBBGoLIQELA0AgACABRwRAIAIgATEAAELFz9my8eW66id+hUILiUKHla+vmLbem55/fiECIAFBAWohAQwBCwtBACACIAJCIYiFQs/W077Sx6vZQn4iAiACQh2IhUL5893xmfaZqxZ+IgIgAkIgiIUiAkIgiCIDQv//A4NCIIYgA0KAgPz/D4NCEIiEIgNC/4GAgPAfg0IQhiADQoD+g4CA4D+DQgiIhCIDQo+AvIDwgcAHg0IIhiADQvCBwIeAnoD4AINCBIiEIgNChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IANCsODAgYOGjJgwhHw3AwBBCCACQv////8PgyICQv//A4NCIIYgAkKAgPz/D4NCEIiEIgJC/4GAgPAfg0IQhiACQoD+g4CA4D+DQgiIhCICQo+AvIDwgcAHg0IIhiACQvCBwIeAnoD4AINCBIiEIgJChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IAJCsODAgYOGjJgwhHw3AwAL", "base64"));
- module.exports = create$1.bind(null, xxhash64, [], 32, 16);
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/loader-utils@3.3.1/node_modules/loader-utils/lib/hash/BatchedHash.js
-var require_BatchedHash = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const MAX_SHORT_STRING = require_wasm_hash().MAX_SHORT_STRING;
- var BatchedHash$1 = class {
- constructor(hash$1) {
- this.string = void 0;
- this.encoding = void 0;
- this.hash = hash$1;
- }
- /**
- * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
- * @param {string|Buffer} data data
- * @param {string=} inputEncoding data encoding
- * @returns {this} updated hash
- */
- update(data, inputEncoding) {
- if (this.string !== void 0) {
- if (typeof data === "string" && inputEncoding === this.encoding && this.string.length + data.length < MAX_SHORT_STRING) {
- this.string += data;
- return this;
- }
- this.hash.update(this.string, this.encoding);
- this.string = void 0;
- }
- if (typeof data === "string") if (data.length < MAX_SHORT_STRING && (!inputEncoding || !inputEncoding.startsWith("ba"))) {
- this.string = data;
- this.encoding = inputEncoding;
- } else this.hash.update(data, inputEncoding);
- else this.hash.update(data);
- return this;
- }
- /**
- * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
- * @param {string=} encoding encoding of the return value
- * @returns {string|Buffer} digest
- */
- digest(encoding) {
- if (this.string !== void 0) this.hash.update(this.string, this.encoding);
- return this.hash.digest(encoding);
- }
- };
- module.exports = BatchedHash$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/loader-utils@3.3.1/node_modules/loader-utils/lib/hash/md4.js
-var require_md4 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const create = require_wasm_hash();
- const md4 = new WebAssembly.Module(Buffer.from("AGFzbQEAAAABCAJgAX8AYAAAAwUEAQAAAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAAGdXBkYXRlAAIFZmluYWwAAwZtZW1vcnkCAAqFEAQmAEGBxpS6BiQBQYnXtv5+JAJB/rnrxXkkA0H2qMmBASQEQQAkAAvMCgEYfyMBIQojAiEGIwMhByMEIQgDQCAAIAVLBEAgBSgCCCINIAcgBiAFKAIEIgsgCCAHIAUoAgAiDCAKIAggBiAHIAhzcXNqakEDdyIDIAYgB3Nxc2pqQQd3IgEgAyAGc3FzampBC3chAiAFKAIUIg8gASACIAUoAhAiCSADIAEgBSgCDCIOIAYgAyACIAEgA3Nxc2pqQRN3IgQgASACc3FzampBA3ciAyACIARzcXNqakEHdyEBIAUoAiAiEiADIAEgBSgCHCIRIAQgAyAFKAIYIhAgAiAEIAEgAyAEc3FzampBC3ciAiABIANzcXNqakETdyIEIAEgAnNxc2pqQQN3IQMgBSgCLCIVIAQgAyAFKAIoIhQgAiAEIAUoAiQiEyABIAIgAyACIARzcXNqakEHdyIBIAMgBHNxc2pqQQt3IgIgASADc3FzampBE3chBCAPIBAgCSAVIBQgEyAFKAI4IhYgAiAEIAUoAjQiFyABIAIgBSgCMCIYIAMgASAEIAEgAnNxc2pqQQN3IgEgAiAEc3FzampBB3ciAiABIARzcXNqakELdyIDIAkgAiAMIAEgBSgCPCIJIAQgASADIAEgAnNxc2pqQRN3IgEgAiADcnEgAiADcXJqakGZ84nUBWpBA3ciAiABIANycSABIANxcmpqQZnzidQFakEFdyIEIAEgAnJxIAEgAnFyaiASakGZ84nUBWpBCXciAyAPIAQgCyACIBggASADIAIgBHJxIAIgBHFyampBmfOJ1AVqQQ13IgEgAyAEcnEgAyAEcXJqakGZ84nUBWpBA3ciAiABIANycSABIANxcmpqQZnzidQFakEFdyIEIAEgAnJxIAEgAnFyampBmfOJ1AVqQQl3IgMgECAEIAIgFyABIAMgAiAEcnEgAiAEcXJqakGZ84nUBWpBDXciASADIARycSADIARxcmogDWpBmfOJ1AVqQQN3IgIgASADcnEgASADcXJqakGZ84nUBWpBBXciBCABIAJycSABIAJxcmpqQZnzidQFakEJdyIDIBEgBCAOIAIgFiABIAMgAiAEcnEgAiAEcXJqakGZ84nUBWpBDXciASADIARycSADIARxcmpqQZnzidQFakEDdyICIAEgA3JxIAEgA3FyampBmfOJ1AVqQQV3IgQgASACcnEgASACcXJqakGZ84nUBWpBCXciAyAMIAIgAyAJIAEgAyACIARycSACIARxcmpqQZnzidQFakENdyIBcyAEc2pqQaHX5/YGakEDdyICIAQgASACcyADc2ogEmpBodfn9gZqQQl3IgRzIAFzampBodfn9gZqQQt3IgMgAiADIBggASADIARzIAJzampBodfn9gZqQQ93IgFzIARzaiANakGh1+f2BmpBA3ciAiAUIAQgASACcyADc2pqQaHX5/YGakEJdyIEcyABc2pqQaHX5/YGakELdyIDIAsgAiADIBYgASADIARzIAJzampBodfn9gZqQQ93IgFzIARzampBodfn9gZqQQN3IgIgEyAEIAEgAnMgA3NqakGh1+f2BmpBCXciBHMgAXNqakGh1+f2BmpBC3chAyAKIA4gAiADIBcgASADIARzIAJzampBodfn9gZqQQ93IgFzIARzampBodfn9gZqQQN3IgJqIQogBiAJIAEgESADIAIgFSAEIAEgAnMgA3NqakGh1+f2BmpBCXciBHMgAXNqakGh1+f2BmpBC3ciAyAEcyACc2pqQaHX5/YGakEPd2ohBiADIAdqIQcgBCAIaiEIIAVBQGshBQwBCwsgCiQBIAYkAiAHJAMgCCQECw0AIAAQASMAIABqJAAL/wQCA38BfiMAIABqrUIDhiEEIABByABqQUBxIgJBCGshAyAAIgFBAWohACABQYABOgAAA0AgACACSUEAIABBB3EbBEAgAEEAOgAAIABBAWohAAwBCwsDQCAAIAJJBEAgAEIANwMAIABBCGohAAwBCwsgAyAENwMAIAIQAUEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=", "base64"));
- module.exports = create.bind(null, md4, [], 64, 32);
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/loader-utils@3.3.1/node_modules/loader-utils/lib/hash/BulkUpdateDecorator.js
-var require_BulkUpdateDecorator = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const BULK_SIZE = 2e3;
- const digestCaches = {};
- var BulkUpdateDecorator$1 = class {
- /**
- * @param {Hash | function(): Hash} hashOrFactory function to create a hash
- * @param {string=} hashKey key for caching
- */
- constructor(hashOrFactory, hashKey) {
- this.hashKey = hashKey;
- if (typeof hashOrFactory === "function") {
- this.hashFactory = hashOrFactory;
- this.hash = void 0;
- } else {
- this.hashFactory = void 0;
- this.hash = hashOrFactory;
- }
- this.buffer = "";
- }
- /**
- * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
- * @param {string|Buffer} data data
- * @param {string=} inputEncoding data encoding
- * @returns {this} updated hash
- */
- update(data, inputEncoding) {
- if (inputEncoding !== void 0 || typeof data !== "string" || data.length > BULK_SIZE) {
- if (this.hash === void 0) this.hash = this.hashFactory();
- if (this.buffer.length > 0) {
- this.hash.update(this.buffer);
- this.buffer = "";
- }
- this.hash.update(data, inputEncoding);
- } else {
- this.buffer += data;
- if (this.buffer.length > BULK_SIZE) {
- if (this.hash === void 0) this.hash = this.hashFactory();
- this.hash.update(this.buffer);
- this.buffer = "";
- }
- }
- return this;
- }
- /**
- * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
- * @param {string=} encoding encoding of the return value
- * @returns {string|Buffer} digest
- */
- digest(encoding) {
- let digestCache;
- const buffer = this.buffer;
- if (this.hash === void 0) {
- const cacheKey = `${this.hashKey}-${encoding}`;
- digestCache = digestCaches[cacheKey];
- if (digestCache === void 0) digestCache = digestCaches[cacheKey] = /* @__PURE__ */ new Map();
- const cacheEntry = digestCache.get(buffer);
- if (cacheEntry !== void 0) return cacheEntry;
- this.hash = this.hashFactory();
- }
- if (buffer.length > 0) this.hash.update(buffer);
- const digestResult = this.hash.digest(encoding);
- if (digestCache !== void 0) digestCache.set(buffer, digestResult);
- return digestResult;
- }
- };
- module.exports = BulkUpdateDecorator$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/loader-utils@3.3.1/node_modules/loader-utils/lib/getHashDigest.js
-var require_getHashDigest = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const baseEncodeTables = {
- 26: "abcdefghijklmnopqrstuvwxyz",
- 32: "123456789abcdefghjkmnpqrstuvwxyz",
- 36: "0123456789abcdefghijklmnopqrstuvwxyz",
- 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ",
- 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
- 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ",
- 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
- 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
- };
- /**
- * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
- * @param {number} divisor The divisor
- * @return {number} Modulo (remainder) of the division
- */
- function divmod32(uint32Array, divisor) {
- let carry = 0;
- for (let i$1 = uint32Array.length - 1; i$1 >= 0; i$1--) {
- const value = carry * 4294967296 + uint32Array[i$1];
- carry = value % divisor;
- uint32Array[i$1] = Math.floor(value / divisor);
- }
- return carry;
- }
- function encodeBufferToBase(buffer, base, length) {
- const encodeTable = baseEncodeTables[base];
- if (!encodeTable) throw new Error("Unknown encoding base" + base);
- const limit = Math.ceil(buffer.length * 8 / Math.log2(base));
- length = Math.min(length, limit);
- const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
- buffer.copy(Buffer.from(uint32Array.buffer));
- let output = "";
- for (let i$1 = 0; i$1 < length; i$1++) output = encodeTable[divmod32(uint32Array, base)] + output;
- return output;
- }
- let crypto = void 0;
- let createXXHash64 = void 0;
- let createMd4 = void 0;
- let BatchedHash = void 0;
- let BulkUpdateDecorator = void 0;
- function getHashDigest$1(buffer, algorithm, digestType, maxLength) {
- algorithm = algorithm || "xxhash64";
- maxLength = maxLength || 9999;
- let hash$1;
- if (algorithm === "xxhash64") {
- if (createXXHash64 === void 0) {
- createXXHash64 = require_xxhash64();
- if (BatchedHash === void 0) BatchedHash = require_BatchedHash();
- }
- hash$1 = new BatchedHash(createXXHash64());
- } else if (algorithm === "md4") {
- if (createMd4 === void 0) {
- createMd4 = require_md4();
- if (BatchedHash === void 0) BatchedHash = require_BatchedHash();
- }
- hash$1 = new BatchedHash(createMd4());
- } else if (algorithm === "native-md4") {
- if (typeof crypto === "undefined") {
- crypto = __require("crypto");
- if (BulkUpdateDecorator === void 0) BulkUpdateDecorator = require_BulkUpdateDecorator();
- }
- hash$1 = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4");
- } else {
- if (typeof crypto === "undefined") {
- crypto = __require("crypto");
- if (BulkUpdateDecorator === void 0) BulkUpdateDecorator = require_BulkUpdateDecorator();
- }
- hash$1 = new BulkUpdateDecorator(() => crypto.createHash(algorithm), algorithm);
- }
- hash$1.update(buffer);
- if (digestType === "base26" || digestType === "base32" || digestType === "base36" || digestType === "base49" || digestType === "base52" || digestType === "base58" || digestType === "base62" || digestType === "base64safe") return encodeBufferToBase(hash$1.digest(), digestType === "base64safe" ? 64 : digestType.substr(4), maxLength);
- return hash$1.digest(digestType || "hex").substr(0, maxLength);
- }
- module.exports = getHashDigest$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/loader-utils@3.3.1/node_modules/loader-utils/lib/interpolateName.js
-var require_interpolateName = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const path$1 = __require("path");
- const getHashDigest = require_getHashDigest();
- function interpolateName$1(loaderContext, name, options = {}) {
- let filename;
- const hasQuery = loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
- if (typeof name === "function") filename = name(loaderContext.resourcePath, hasQuery ? loaderContext.resourceQuery : void 0);
- else filename = name || "[hash].[ext]";
- const context = options.context;
- const content = options.content;
- const regExp = options.regExp;
- let ext = "bin";
- let basename = "file";
- let directory = "";
- let folder = "";
- let query = "";
- if (loaderContext.resourcePath) {
- const parsed = path$1.parse(loaderContext.resourcePath);
- let resourcePath = loaderContext.resourcePath;
- if (parsed.ext) ext = parsed.ext.substr(1);
- if (parsed.dir) {
- basename = parsed.name;
- resourcePath = parsed.dir + path$1.sep;
- }
- if (typeof context !== "undefined") {
- directory = path$1.relative(context, resourcePath + "_").replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
- directory = directory.substr(0, directory.length - 1);
- } else directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
- if (directory.length <= 1) directory = "";
- else folder = path$1.basename(directory);
- }
- if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
- query = loaderContext.resourceQuery;
- const hashIdx = query.indexOf("#");
- if (hashIdx >= 0) query = query.substr(0, hashIdx);
- }
- let url = filename;
- if (content) url = url.replace(/\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*(?:safe)?))?(?::(\d+))?\]/gi, (all, hashType, digestType, maxLength) => getHashDigest(content, hashType, digestType, parseInt(maxLength, 10)));
- url = url.replace(/\[ext\]/gi, () => ext).replace(/\[name\]/gi, () => basename).replace(/\[path\]/gi, () => directory).replace(/\[folder\]/gi, () => folder).replace(/\[query\]/gi, () => query);
- if (regExp && loaderContext.resourcePath) {
- const match = loaderContext.resourcePath.match(new RegExp(regExp));
- match && match.forEach((matched, i$1) => {
- url = url.replace(new RegExp("\\[" + i$1 + "\\]", "ig"), matched);
- });
- }
- if (typeof loaderContext.options === "object" && typeof loaderContext.options.customInterpolateName === "function") url = loaderContext.options.customInterpolateName.call(loaderContext, url, name, options);
- return url;
- }
- module.exports = interpolateName$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/generic-names@4.0.0/node_modules/generic-names/index.js
-var require_generic_names = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- var interpolateName = require_interpolateName();
- var path = __require("path");
- /**
- * @param {string} pattern
- * @param {object} options
- * @param {string} options.context
- * @param {string} options.hashPrefix
- * @return {function}
- */
- module.exports = function createGenerator(pattern, options) {
- options = options || {};
- var context = options && typeof options.context === "string" ? options.context : process.cwd();
- var hashPrefix = options && typeof options.hashPrefix === "string" ? options.hashPrefix : "";
- /**
- * @param {string} localName Usually a class name
- * @param {string} filepath Absolute path
- * @return {string}
- */
- return function generate(localName, filepath) {
- var name = pattern.replace(/\[local\]/gi, localName);
- return interpolateName({ resourcePath: filepath }, name, {
- content: hashPrefix + path.relative(context, filepath).replace(/\\/g, "/") + "\0" + localName,
- context
- }).replace(new RegExp("[^a-zA-Z0-9\\-_\xA0-￿]", "g"), "-").replace(/^((-?[0-9])|--)/, "_$1");
- };
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/util/unesc.js
-var require_unesc = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = unesc;
- /**
- *
- * @param {string} str
- * @returns {[string, number]|undefined}
- */
- function gobbleHex(str$1) {
- var lower = str$1.toLowerCase();
- var hex$1 = "";
- var spaceTerminated = false;
- for (var i$1 = 0; i$1 < 6 && lower[i$1] !== void 0; i$1++) {
- var code = lower.charCodeAt(i$1);
- var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
- spaceTerminated = code === 32;
- if (!valid) break;
- hex$1 += lower[i$1];
- }
- if (hex$1.length === 0) return;
- var codePoint = parseInt(hex$1, 16);
- if (codePoint >= 55296 && codePoint <= 57343 || codePoint === 0 || codePoint > 1114111) return ["�", hex$1.length + (spaceTerminated ? 1 : 0)];
- return [String.fromCodePoint(codePoint), hex$1.length + (spaceTerminated ? 1 : 0)];
- }
- var CONTAINS_ESCAPE = /\\/;
- function unesc(str$1) {
- if (!CONTAINS_ESCAPE.test(str$1)) return str$1;
- var ret = "";
- for (var i$1 = 0; i$1 < str$1.length; i$1++) {
- if (str$1[i$1] === "\\") {
- var gobbled = gobbleHex(str$1.slice(i$1 + 1, i$1 + 7));
- if (gobbled !== void 0) {
- ret += gobbled[0];
- i$1 += gobbled[1];
- continue;
- }
- if (str$1[i$1 + 1] === "\\") {
- ret += "\\";
- i$1++;
- continue;
- }
- if (str$1.length === i$1 + 1) ret += str$1[i$1];
- continue;
- }
- ret += str$1[i$1];
- }
- return ret;
- }
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/util/getProp.js
-var require_getProp = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = getProp;
- function getProp(obj) {
- for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) props[_key - 1] = arguments[_key];
- while (props.length > 0) {
- var prop = props.shift();
- if (!obj[prop]) return;
- obj = obj[prop];
- }
- return obj;
- }
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/util/ensureObject.js
-var require_ensureObject = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = ensureObject;
- function ensureObject(obj) {
- for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) props[_key - 1] = arguments[_key];
- while (props.length > 0) {
- var prop = props.shift();
- if (!obj[prop]) obj[prop] = {};
- obj = obj[prop];
- }
- }
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/util/stripComments.js
-var require_stripComments = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = stripComments;
- function stripComments(str$1) {
- var s = "";
- var commentStart = str$1.indexOf("/*");
- var lastEnd = 0;
- while (commentStart >= 0) {
- s = s + str$1.slice(lastEnd, commentStart);
- var commentEnd = str$1.indexOf("*/", commentStart + 2);
- if (commentEnd < 0) return s;
- lastEnd = commentEnd + 2;
- commentStart = str$1.indexOf("/*", lastEnd);
- }
- s = s + str$1.slice(lastEnd);
- return s;
- }
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/util/index.js
-var require_util = /* @__PURE__ */ __commonJSMin(((exports) => {
- exports.__esModule = true;
- exports.unesc = exports.stripComments = exports.getProp = exports.ensureObject = void 0;
- var _unesc$1 = _interopRequireDefault$20(require_unesc());
- exports.unesc = _unesc$1["default"];
- var _getProp = _interopRequireDefault$20(require_getProp());
- exports.getProp = _getProp["default"];
- var _ensureObject = _interopRequireDefault$20(require_ensureObject());
- exports.ensureObject = _ensureObject["default"];
- var _stripComments = _interopRequireDefault$20(require_stripComments());
- exports.stripComments = _stripComments["default"];
- function _interopRequireDefault$20(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/node.js
-var require_node$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _util$3 = require_util();
- function _defineProperties$6(target, props) {
- for (var i$1 = 0; i$1 < props.length; i$1++) {
- var descriptor = props[i$1];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, descriptor.key, descriptor);
- }
- }
- function _createClass$6(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties$6(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties$6(Constructor, staticProps);
- Object.defineProperty(Constructor, "prototype", { writable: false });
- return Constructor;
- }
- var cloneNode = function cloneNode$1(obj, parent) {
- if (typeof obj !== "object" || obj === null) return obj;
- var cloned = new obj.constructor();
- for (var i$1 in obj) {
- if (!obj.hasOwnProperty(i$1)) continue;
- var value = obj[i$1];
- if (i$1 === "parent" && typeof value === "object") {
- if (parent) cloned[i$1] = parent;
- } else if (value instanceof Array) cloned[i$1] = value.map(function(j) {
- return cloneNode$1(j, cloned);
- });
- else cloned[i$1] = cloneNode$1(value, cloned);
- }
- return cloned;
- };
- var Node = /* @__PURE__ */ function() {
- function Node$1(opts) {
- if (opts === void 0) opts = {};
- Object.assign(this, opts);
- this.spaces = this.spaces || {};
- this.spaces.before = this.spaces.before || "";
- this.spaces.after = this.spaces.after || "";
- }
- var _proto = Node$1.prototype;
- _proto.remove = function remove() {
- if (this.parent) this.parent.removeChild(this);
- this.parent = void 0;
- return this;
- };
- _proto.replaceWith = function replaceWith() {
- if (this.parent) {
- for (var index in arguments) this.parent.insertBefore(this, arguments[index]);
- this.remove();
- }
- return this;
- };
- _proto.next = function next() {
- return this.parent.at(this.parent.index(this) + 1);
- };
- _proto.prev = function prev() {
- return this.parent.at(this.parent.index(this) - 1);
- };
- _proto.clone = function clone(overrides) {
- if (overrides === void 0) overrides = {};
- var cloned = cloneNode(this);
- for (var name in overrides) cloned[name] = overrides[name];
- return cloned;
- };
- _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
- if (!this.raws) this.raws = {};
- var originalValue = this[name];
- var originalEscaped = this.raws[name];
- this[name] = originalValue + value;
- if (originalEscaped || valueEscaped !== value) this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
- else delete this.raws[name];
- };
- _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
- if (!this.raws) this.raws = {};
- this[name] = value;
- this.raws[name] = valueEscaped;
- };
- _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
- this[name] = value;
- if (this.raws) delete this.raws[name];
- };
- _proto.isAtPosition = function isAtPosition(line, column) {
- if (this.source && this.source.start && this.source.end) {
- if (this.source.start.line > line) return false;
- if (this.source.end.line < line) return false;
- if (this.source.start.line === line && this.source.start.column > column) return false;
- if (this.source.end.line === line && this.source.end.column < column) return false;
- return true;
- }
- };
- _proto.stringifyProperty = function stringifyProperty(name) {
- return this.raws && this.raws[name] || this[name];
- };
- _proto.valueToString = function valueToString() {
- return String(this.stringifyProperty("value"));
- };
- _proto.toString = function toString$1() {
- return [
- this.rawSpaceBefore,
- this.valueToString(),
- this.rawSpaceAfter
- ].join("");
- };
- _createClass$6(Node$1, [{
- key: "rawSpaceBefore",
- get: function get() {
- var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
- if (rawSpace === void 0) rawSpace = this.spaces && this.spaces.before;
- return rawSpace || "";
- },
- set: function set(raw) {
- (0, _util$3.ensureObject)(this, "raws", "spaces");
- this.raws.spaces.before = raw;
- }
- }, {
- key: "rawSpaceAfter",
- get: function get() {
- var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
- if (rawSpace === void 0) rawSpace = this.spaces.after;
- return rawSpace || "";
- },
- set: function set(raw) {
- (0, _util$3.ensureObject)(this, "raws", "spaces");
- this.raws.spaces.after = raw;
- }
- }]);
- return Node$1;
- }();
- exports["default"] = Node;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/types.js
-var require_types = /* @__PURE__ */ __commonJSMin(((exports) => {
- exports.__esModule = true;
- exports.UNIVERSAL = exports.TAG = exports.STRING = exports.SELECTOR = exports.ROOT = exports.PSEUDO = exports.NESTING = exports.ID = exports.COMMENT = exports.COMBINATOR = exports.CLASS = exports.ATTRIBUTE = void 0;
- var TAG = "tag";
- exports.TAG = TAG;
- var STRING = "string";
- exports.STRING = STRING;
- var SELECTOR = "selector";
- exports.SELECTOR = SELECTOR;
- var ROOT = "root";
- exports.ROOT = ROOT;
- var PSEUDO = "pseudo";
- exports.PSEUDO = PSEUDO;
- var NESTING = "nesting";
- exports.NESTING = NESTING;
- var ID$1 = "id";
- exports.ID = ID$1;
- var COMMENT = "comment";
- exports.COMMENT = COMMENT;
- var COMBINATOR = "combinator";
- exports.COMBINATOR = COMBINATOR;
- var CLASS = "class";
- exports.CLASS = CLASS;
- var ATTRIBUTE = "attribute";
- exports.ATTRIBUTE = ATTRIBUTE;
- var UNIVERSAL = "universal";
- exports.UNIVERSAL = UNIVERSAL;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/container.js
-var require_container = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _node$7 = _interopRequireDefault$19(require_node$1());
- var types$1 = _interopRequireWildcard$3(require_types());
- function _getRequireWildcardCache$3(nodeInterop) {
- if (typeof WeakMap !== "function") return null;
- var cacheBabelInterop = /* @__PURE__ */ new WeakMap();
- var cacheNodeInterop = /* @__PURE__ */ new WeakMap();
- return (_getRequireWildcardCache$3 = function _getRequireWildcardCache$4(nodeInterop$1) {
- return nodeInterop$1 ? cacheNodeInterop : cacheBabelInterop;
- })(nodeInterop);
- }
- function _interopRequireWildcard$3(obj, nodeInterop) {
- if (!nodeInterop && obj && obj.__esModule) return obj;
- if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { "default": obj };
- var cache = _getRequireWildcardCache$3(nodeInterop);
- if (cache && cache.has(obj)) return cache.get(obj);
- var newObj = {};
- var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
- for (var key in obj) if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
- var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
- if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc);
- else newObj[key] = obj[key];
- }
- newObj["default"] = obj;
- if (cache) cache.set(obj, newObj);
- return newObj;
- }
- function _interopRequireDefault$19(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- function _createForOfIteratorHelperLoose(o, allowArrayLike) {
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
- if (it) return (it = it.call(o)).next.bind(it);
- if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
- if (it) o = it;
- var i$1 = 0;
- return function() {
- if (i$1 >= o.length) return { done: true };
- return {
- done: false,
- value: o[i$1++]
- };
- };
- }
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
- }
- function _unsupportedIterableToArray(o, minLen) {
- if (!o) return;
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
- var n = Object.prototype.toString.call(o).slice(8, -1);
- if (n === "Object" && o.constructor) n = o.constructor.name;
- if (n === "Map" || n === "Set") return Array.from(o);
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
- }
- function _arrayLikeToArray(arr, len) {
- if (len == null || len > arr.length) len = arr.length;
- for (var i$1 = 0, arr2 = new Array(len); i$1 < len; i$1++) arr2[i$1] = arr[i$1];
- return arr2;
- }
- function _defineProperties$5(target, props) {
- for (var i$1 = 0; i$1 < props.length; i$1++) {
- var descriptor = props[i$1];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, descriptor.key, descriptor);
- }
- }
- function _createClass$5(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties$5(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties$5(Constructor, staticProps);
- Object.defineProperty(Constructor, "prototype", { writable: false });
- return Constructor;
- }
- function _inheritsLoose$13(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf$13(subClass, superClass);
- }
- function _setPrototypeOf$13(o, p) {
- _setPrototypeOf$13 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf$14(o$1, p$1) {
- o$1.__proto__ = p$1;
- return o$1;
- };
- return _setPrototypeOf$13(o, p);
- }
- var Container = /* @__PURE__ */ function(_Node) {
- _inheritsLoose$13(Container$1, _Node);
- function Container$1(opts) {
- var _this = _Node.call(this, opts) || this;
- if (!_this.nodes) _this.nodes = [];
- return _this;
- }
- var _proto = Container$1.prototype;
- _proto.append = function append(selector$1) {
- selector$1.parent = this;
- this.nodes.push(selector$1);
- return this;
- };
- _proto.prepend = function prepend(selector$1) {
- selector$1.parent = this;
- this.nodes.unshift(selector$1);
- for (var id$1 in this.indexes) this.indexes[id$1]++;
- return this;
- };
- _proto.at = function at$1(index) {
- return this.nodes[index];
- };
- _proto.index = function index(child) {
- if (typeof child === "number") return child;
- return this.nodes.indexOf(child);
- };
- _proto.removeChild = function removeChild(child) {
- child = this.index(child);
- this.at(child).parent = void 0;
- this.nodes.splice(child, 1);
- var index;
- for (var id$1 in this.indexes) {
- index = this.indexes[id$1];
- if (index >= child) this.indexes[id$1] = index - 1;
- }
- return this;
- };
- _proto.removeAll = function removeAll() {
- for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
- var node = _step.value;
- node.parent = void 0;
- }
- this.nodes = [];
- return this;
- };
- _proto.empty = function empty() {
- return this.removeAll();
- };
- _proto.insertAfter = function insertAfter(oldNode, newNode) {
- var _this$nodes;
- newNode.parent = this;
- var oldIndex = this.index(oldNode);
- var resetNode = [];
- for (var i$1 = 2; i$1 < arguments.length; i$1++) resetNode.push(arguments[i$1]);
- (_this$nodes = this.nodes).splice.apply(_this$nodes, [
- oldIndex + 1,
- 0,
- newNode
- ].concat(resetNode));
- newNode.parent = this;
- var index;
- for (var id$1 in this.indexes) {
- index = this.indexes[id$1];
- if (oldIndex < index) this.indexes[id$1] = index + arguments.length - 1;
- }
- return this;
- };
- _proto.insertBefore = function insertBefore(oldNode, newNode) {
- var _this$nodes2;
- newNode.parent = this;
- var oldIndex = this.index(oldNode);
- var resetNode = [];
- for (var i$1 = 2; i$1 < arguments.length; i$1++) resetNode.push(arguments[i$1]);
- (_this$nodes2 = this.nodes).splice.apply(_this$nodes2, [
- oldIndex,
- 0,
- newNode
- ].concat(resetNode));
- newNode.parent = this;
- var index;
- for (var id$1 in this.indexes) {
- index = this.indexes[id$1];
- if (index >= oldIndex) this.indexes[id$1] = index + arguments.length - 1;
- }
- return this;
- };
- _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
- var found = void 0;
- this.each(function(node) {
- if (node.atPosition) {
- var foundChild = node.atPosition(line, col);
- if (foundChild) {
- found = foundChild;
- return false;
- }
- } else if (node.isAtPosition(line, col)) {
- found = node;
- return false;
- }
- });
- return found;
- };
- _proto.atPosition = function atPosition(line, col) {
- if (this.isAtPosition(line, col)) return this._findChildAtPosition(line, col) || this;
- else return;
- };
- _proto._inferEndPosition = function _inferEndPosition() {
- if (this.last && this.last.source && this.last.source.end) {
- this.source = this.source || {};
- this.source.end = this.source.end || {};
- Object.assign(this.source.end, this.last.source.end);
- }
- };
- _proto.each = function each(callback) {
- if (!this.lastEach) this.lastEach = 0;
- if (!this.indexes) this.indexes = {};
- this.lastEach++;
- var id$1 = this.lastEach;
- this.indexes[id$1] = 0;
- if (!this.length) return;
- var index, result;
- while (this.indexes[id$1] < this.length) {
- index = this.indexes[id$1];
- result = callback(this.at(index), index);
- if (result === false) break;
- this.indexes[id$1] += 1;
- }
- delete this.indexes[id$1];
- if (result === false) return false;
- };
- _proto.walk = function walk(callback) {
- return this.each(function(node, i$1) {
- var result = callback(node, i$1);
- if (result !== false && node.length) result = node.walk(callback);
- if (result === false) return false;
- });
- };
- _proto.walkAttributes = function walkAttributes(callback) {
- var _this2 = this;
- return this.walk(function(selector$1) {
- if (selector$1.type === types$1.ATTRIBUTE) return callback.call(_this2, selector$1);
- });
- };
- _proto.walkClasses = function walkClasses(callback) {
- var _this3 = this;
- return this.walk(function(selector$1) {
- if (selector$1.type === types$1.CLASS) return callback.call(_this3, selector$1);
- });
- };
- _proto.walkCombinators = function walkCombinators(callback) {
- var _this4 = this;
- return this.walk(function(selector$1) {
- if (selector$1.type === types$1.COMBINATOR) return callback.call(_this4, selector$1);
- });
- };
- _proto.walkComments = function walkComments(callback) {
- var _this5 = this;
- return this.walk(function(selector$1) {
- if (selector$1.type === types$1.COMMENT) return callback.call(_this5, selector$1);
- });
- };
- _proto.walkIds = function walkIds(callback) {
- var _this6 = this;
- return this.walk(function(selector$1) {
- if (selector$1.type === types$1.ID) return callback.call(_this6, selector$1);
- });
- };
- _proto.walkNesting = function walkNesting(callback) {
- var _this7 = this;
- return this.walk(function(selector$1) {
- if (selector$1.type === types$1.NESTING) return callback.call(_this7, selector$1);
- });
- };
- _proto.walkPseudos = function walkPseudos(callback) {
- var _this8 = this;
- return this.walk(function(selector$1) {
- if (selector$1.type === types$1.PSEUDO) return callback.call(_this8, selector$1);
- });
- };
- _proto.walkTags = function walkTags(callback) {
- var _this9 = this;
- return this.walk(function(selector$1) {
- if (selector$1.type === types$1.TAG) return callback.call(_this9, selector$1);
- });
- };
- _proto.walkUniversals = function walkUniversals(callback) {
- var _this10 = this;
- return this.walk(function(selector$1) {
- if (selector$1.type === types$1.UNIVERSAL) return callback.call(_this10, selector$1);
- });
- };
- _proto.split = function split(callback) {
- var _this11 = this;
- var current = [];
- return this.reduce(function(memo, node, index) {
- var split$1 = callback.call(_this11, node);
- current.push(node);
- if (split$1) {
- memo.push(current);
- current = [];
- } else if (index === _this11.length - 1) memo.push(current);
- return memo;
- }, []);
- };
- _proto.map = function map(callback) {
- return this.nodes.map(callback);
- };
- _proto.reduce = function reduce(callback, memo) {
- return this.nodes.reduce(callback, memo);
- };
- _proto.every = function every(callback) {
- return this.nodes.every(callback);
- };
- _proto.some = function some(callback) {
- return this.nodes.some(callback);
- };
- _proto.filter = function filter(callback) {
- return this.nodes.filter(callback);
- };
- _proto.sort = function sort(callback) {
- return this.nodes.sort(callback);
- };
- _proto.toString = function toString$1() {
- return this.map(String).join("");
- };
- _createClass$5(Container$1, [
- {
- key: "first",
- get: function get() {
- return this.at(0);
- }
- },
- {
- key: "last",
- get: function get() {
- return this.at(this.length - 1);
- }
- },
- {
- key: "length",
- get: function get() {
- return this.nodes.length;
- }
- }
- ]);
- return Container$1;
- }(_node$7["default"]);
- exports["default"] = Container;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/root.js
-var require_root = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _container$2 = _interopRequireDefault$18(require_container());
- var _types$13 = require_types();
- function _interopRequireDefault$18(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- function _defineProperties$4(target, props) {
- for (var i$1 = 0; i$1 < props.length; i$1++) {
- var descriptor = props[i$1];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, descriptor.key, descriptor);
- }
- }
- function _createClass$4(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties$4(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties$4(Constructor, staticProps);
- Object.defineProperty(Constructor, "prototype", { writable: false });
- return Constructor;
- }
- function _inheritsLoose$12(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf$12(subClass, superClass);
- }
- function _setPrototypeOf$12(o, p) {
- _setPrototypeOf$12 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf$14(o$1, p$1) {
- o$1.__proto__ = p$1;
- return o$1;
- };
- return _setPrototypeOf$12(o, p);
- }
- var Root = /* @__PURE__ */ function(_Container) {
- _inheritsLoose$12(Root$1, _Container);
- function Root$1(opts) {
- var _this = _Container.call(this, opts) || this;
- _this.type = _types$13.ROOT;
- return _this;
- }
- var _proto = Root$1.prototype;
- _proto.toString = function toString$1() {
- var str$1 = this.reduce(function(memo, selector$1) {
- memo.push(String(selector$1));
- return memo;
- }, []).join(",");
- return this.trailingComma ? str$1 + "," : str$1;
- };
- _proto.error = function error(message, options) {
- if (this._error) return this._error(message, options);
- else return new Error(message);
- };
- _createClass$4(Root$1, [{
- key: "errorGenerator",
- set: function set(handler) {
- this._error = handler;
- }
- }]);
- return Root$1;
- }(_container$2["default"]);
- exports["default"] = Root;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/selector.js
-var require_selector = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _container$1 = _interopRequireDefault$17(require_container());
- var _types$12 = require_types();
- function _interopRequireDefault$17(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- function _inheritsLoose$11(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf$11(subClass, superClass);
- }
- function _setPrototypeOf$11(o, p) {
- _setPrototypeOf$11 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf$14(o$1, p$1) {
- o$1.__proto__ = p$1;
- return o$1;
- };
- return _setPrototypeOf$11(o, p);
- }
- var Selector = /* @__PURE__ */ function(_Container) {
- _inheritsLoose$11(Selector$1, _Container);
- function Selector$1(opts) {
- var _this = _Container.call(this, opts) || this;
- _this.type = _types$12.SELECTOR;
- return _this;
- }
- return Selector$1;
- }(_container$1["default"]);
- exports["default"] = Selector;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/cssesc@3.0.0/node_modules/cssesc/cssesc.js
-/*! https://mths.be/cssesc v3.0.0 by @mathias */
-var require_cssesc = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- var hasOwnProperty$1 = {}.hasOwnProperty;
- var merge = function merge$1(options, defaults) {
- if (!options) return defaults;
- var result = {};
- for (var key in defaults) result[key] = hasOwnProperty$1.call(options, key) ? options[key] : defaults[key];
- return result;
- };
- var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
- var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
- var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
- var cssesc = function cssesc$1(string$1, options) {
- options = merge(options, cssesc$1.options);
- if (options.quotes != "single" && options.quotes != "double") options.quotes = "single";
- var quote = options.quotes == "double" ? "\"" : "'";
- var isIdentifier$1 = options.isIdentifier;
- var firstChar = string$1.charAt(0);
- var output = "";
- var counter = 0;
- var length = string$1.length;
- while (counter < length) {
- var character = string$1.charAt(counter++);
- var codePoint = character.charCodeAt();
- var value = void 0;
- if (codePoint < 32 || codePoint > 126) {
- if (codePoint >= 55296 && codePoint <= 56319 && counter < length) {
- var extra = string$1.charCodeAt(counter++);
- if ((extra & 64512) == 56320) codePoint = ((codePoint & 1023) << 10) + (extra & 1023) + 65536;
- else counter--;
- }
- value = "\\" + codePoint.toString(16).toUpperCase() + " ";
- } else if (options.escapeEverything) if (regexAnySingleEscape.test(character)) value = "\\" + character;
- else value = "\\" + codePoint.toString(16).toUpperCase() + " ";
- else if (/[\t\n\f\r\x0B]/.test(character)) value = "\\" + codePoint.toString(16).toUpperCase() + " ";
- else if (character == "\\" || !isIdentifier$1 && (character == "\"" && quote == character || character == "'" && quote == character) || isIdentifier$1 && regexSingleEscape.test(character)) value = "\\" + character;
- else value = character;
- output += value;
- }
- if (isIdentifier$1) {
- if (/^-[-\d]/.test(output)) output = "\\-" + output.slice(1);
- else if (/\d/.test(firstChar)) output = "\\3" + firstChar + " " + output.slice(1);
- }
- output = output.replace(regexExcessiveSpaces, function($0, $1, $2) {
- if ($1 && $1.length % 2) return $0;
- return ($1 || "") + $2;
- });
- if (!isIdentifier$1 && options.wrap) return quote + output + quote;
- return output;
- };
- cssesc.options = {
- "escapeEverything": false,
- "isIdentifier": false,
- "quotes": "single",
- "wrap": false
- };
- cssesc.version = "3.0.0";
- module.exports = cssesc;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/className.js
-var require_className = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _cssesc$2 = _interopRequireDefault$16(require_cssesc());
- var _util$2 = require_util();
- var _node$6 = _interopRequireDefault$16(require_node$1());
- var _types$11 = require_types();
- function _interopRequireDefault$16(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- function _defineProperties$3(target, props) {
- for (var i$1 = 0; i$1 < props.length; i$1++) {
- var descriptor = props[i$1];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, descriptor.key, descriptor);
- }
- }
- function _createClass$3(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties$3(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties$3(Constructor, staticProps);
- Object.defineProperty(Constructor, "prototype", { writable: false });
- return Constructor;
- }
- function _inheritsLoose$10(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf$10(subClass, superClass);
- }
- function _setPrototypeOf$10(o, p) {
- _setPrototypeOf$10 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf$14(o$1, p$1) {
- o$1.__proto__ = p$1;
- return o$1;
- };
- return _setPrototypeOf$10(o, p);
- }
- var ClassName = /* @__PURE__ */ function(_Node) {
- _inheritsLoose$10(ClassName$1, _Node);
- function ClassName$1(opts) {
- var _this = _Node.call(this, opts) || this;
- _this.type = _types$11.CLASS;
- _this._constructed = true;
- return _this;
- }
- var _proto = ClassName$1.prototype;
- _proto.valueToString = function valueToString() {
- return "." + _Node.prototype.valueToString.call(this);
- };
- _createClass$3(ClassName$1, [{
- key: "value",
- get: function get() {
- return this._value;
- },
- set: function set(v) {
- if (this._constructed) {
- var escaped = (0, _cssesc$2["default"])(v, { isIdentifier: true });
- if (escaped !== v) {
- (0, _util$2.ensureObject)(this, "raws");
- this.raws.value = escaped;
- } else if (this.raws) delete this.raws.value;
- }
- this._value = v;
- }
- }]);
- return ClassName$1;
- }(_node$6["default"]);
- exports["default"] = ClassName;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/comment.js
-var require_comment = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _node$5 = _interopRequireDefault$15(require_node$1());
- var _types$10 = require_types();
- function _interopRequireDefault$15(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- function _inheritsLoose$9(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf$9(subClass, superClass);
- }
- function _setPrototypeOf$9(o, p) {
- _setPrototypeOf$9 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf$14(o$1, p$1) {
- o$1.__proto__ = p$1;
- return o$1;
- };
- return _setPrototypeOf$9(o, p);
- }
- var Comment = /* @__PURE__ */ function(_Node) {
- _inheritsLoose$9(Comment$1, _Node);
- function Comment$1(opts) {
- var _this = _Node.call(this, opts) || this;
- _this.type = _types$10.COMMENT;
- return _this;
- }
- return Comment$1;
- }(_node$5["default"]);
- exports["default"] = Comment;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/id.js
-var require_id = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _node$4 = _interopRequireDefault$14(require_node$1());
- var _types$9 = require_types();
- function _interopRequireDefault$14(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- function _inheritsLoose$8(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf$8(subClass, superClass);
- }
- function _setPrototypeOf$8(o, p) {
- _setPrototypeOf$8 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf$14(o$1, p$1) {
- o$1.__proto__ = p$1;
- return o$1;
- };
- return _setPrototypeOf$8(o, p);
- }
- var ID = /* @__PURE__ */ function(_Node) {
- _inheritsLoose$8(ID$2, _Node);
- function ID$2(opts) {
- var _this = _Node.call(this, opts) || this;
- _this.type = _types$9.ID;
- return _this;
- }
- var _proto = ID$2.prototype;
- _proto.valueToString = function valueToString() {
- return "#" + _Node.prototype.valueToString.call(this);
- };
- return ID$2;
- }(_node$4["default"]);
- exports["default"] = ID;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/namespace.js
-var require_namespace = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _cssesc$1 = _interopRequireDefault$13(require_cssesc());
- var _util$1 = require_util();
- var _node$3 = _interopRequireDefault$13(require_node$1());
- function _interopRequireDefault$13(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- function _defineProperties$2(target, props) {
- for (var i$1 = 0; i$1 < props.length; i$1++) {
- var descriptor = props[i$1];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, descriptor.key, descriptor);
- }
- }
- function _createClass$2(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties$2(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties$2(Constructor, staticProps);
- Object.defineProperty(Constructor, "prototype", { writable: false });
- return Constructor;
- }
- function _inheritsLoose$7(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf$7(subClass, superClass);
- }
- function _setPrototypeOf$7(o, p) {
- _setPrototypeOf$7 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf$14(o$1, p$1) {
- o$1.__proto__ = p$1;
- return o$1;
- };
- return _setPrototypeOf$7(o, p);
- }
- var Namespace = /* @__PURE__ */ function(_Node) {
- _inheritsLoose$7(Namespace$1, _Node);
- function Namespace$1() {
- return _Node.apply(this, arguments) || this;
- }
- var _proto = Namespace$1.prototype;
- _proto.qualifiedName = function qualifiedName(value) {
- if (this.namespace) return this.namespaceString + "|" + value;
- else return value;
- };
- _proto.valueToString = function valueToString() {
- return this.qualifiedName(_Node.prototype.valueToString.call(this));
- };
- _createClass$2(Namespace$1, [
- {
- key: "namespace",
- get: function get() {
- return this._namespace;
- },
- set: function set(namespace) {
- if (namespace === true || namespace === "*" || namespace === "&") {
- this._namespace = namespace;
- if (this.raws) delete this.raws.namespace;
- return;
- }
- var escaped = (0, _cssesc$1["default"])(namespace, { isIdentifier: true });
- this._namespace = namespace;
- if (escaped !== namespace) {
- (0, _util$1.ensureObject)(this, "raws");
- this.raws.namespace = escaped;
- } else if (this.raws) delete this.raws.namespace;
- }
- },
- {
- key: "ns",
- get: function get() {
- return this._namespace;
- },
- set: function set(namespace) {
- this.namespace = namespace;
- }
- },
- {
- key: "namespaceString",
- get: function get() {
- if (this.namespace) {
- var ns = this.stringifyProperty("namespace");
- if (ns === true) return "";
- else return ns;
- } else return "";
- }
- }
- ]);
- return Namespace$1;
- }(_node$3["default"]);
- exports["default"] = Namespace;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/tag.js
-var require_tag = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _namespace$2 = _interopRequireDefault$12(require_namespace());
- var _types$8 = require_types();
- function _interopRequireDefault$12(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- function _inheritsLoose$6(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf$6(subClass, superClass);
- }
- function _setPrototypeOf$6(o, p) {
- _setPrototypeOf$6 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf$14(o$1, p$1) {
- o$1.__proto__ = p$1;
- return o$1;
- };
- return _setPrototypeOf$6(o, p);
- }
- var Tag = /* @__PURE__ */ function(_Namespace) {
- _inheritsLoose$6(Tag$1, _Namespace);
- function Tag$1(opts) {
- var _this = _Namespace.call(this, opts) || this;
- _this.type = _types$8.TAG;
- return _this;
- }
- return Tag$1;
- }(_namespace$2["default"]);
- exports["default"] = Tag;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/string.js
-var require_string = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _node$2 = _interopRequireDefault$11(require_node$1());
- var _types$7 = require_types();
- function _interopRequireDefault$11(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- function _inheritsLoose$5(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf$5(subClass, superClass);
- }
- function _setPrototypeOf$5(o, p) {
- _setPrototypeOf$5 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf$14(o$1, p$1) {
- o$1.__proto__ = p$1;
- return o$1;
- };
- return _setPrototypeOf$5(o, p);
- }
- var String$1 = /* @__PURE__ */ function(_Node) {
- _inheritsLoose$5(String$2, _Node);
- function String$2(opts) {
- var _this = _Node.call(this, opts) || this;
- _this.type = _types$7.STRING;
- return _this;
- }
- return String$2;
- }(_node$2["default"]);
- exports["default"] = String$1;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/pseudo.js
-var require_pseudo = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _container = _interopRequireDefault$10(require_container());
- var _types$6 = require_types();
- function _interopRequireDefault$10(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- function _inheritsLoose$4(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf$4(subClass, superClass);
- }
- function _setPrototypeOf$4(o, p) {
- _setPrototypeOf$4 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf$14(o$1, p$1) {
- o$1.__proto__ = p$1;
- return o$1;
- };
- return _setPrototypeOf$4(o, p);
- }
- var Pseudo = /* @__PURE__ */ function(_Container) {
- _inheritsLoose$4(Pseudo$1, _Container);
- function Pseudo$1(opts) {
- var _this = _Container.call(this, opts) || this;
- _this.type = _types$6.PSEUDO;
- return _this;
- }
- var _proto = Pseudo$1.prototype;
- _proto.toString = function toString$1() {
- var params = this.length ? "(" + this.map(String).join(",") + ")" : "";
- return [
- this.rawSpaceBefore,
- this.stringifyProperty("value"),
- params,
- this.rawSpaceAfter
- ].join("");
- };
- return Pseudo$1;
- }(_container["default"]);
- exports["default"] = Pseudo;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/util-deprecate@1.0.2/node_modules/util-deprecate/node.js
-var require_node = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /**
- * For Node.js, simply re-export the core `util.deprecate` function.
- */
- module.exports = __require("util").deprecate;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/attribute.js
-var require_attribute = /* @__PURE__ */ __commonJSMin(((exports) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- exports.unescapeValue = unescapeValue;
- var _cssesc = _interopRequireDefault$9(require_cssesc());
- var _unesc = _interopRequireDefault$9(require_unesc());
- var _namespace$1 = _interopRequireDefault$9(require_namespace());
- var _types$5 = require_types();
- var _CSSESC_QUOTE_OPTIONS;
- function _interopRequireDefault$9(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- function _defineProperties$1(target, props) {
- for (var i$1 = 0; i$1 < props.length; i$1++) {
- var descriptor = props[i$1];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, descriptor.key, descriptor);
- }
- }
- function _createClass$1(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties$1(Constructor, staticProps);
- Object.defineProperty(Constructor, "prototype", { writable: false });
- return Constructor;
- }
- function _inheritsLoose$3(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf$3(subClass, superClass);
- }
- function _setPrototypeOf$3(o, p) {
- _setPrototypeOf$3 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf$14(o$1, p$1) {
- o$1.__proto__ = p$1;
- return o$1;
- };
- return _setPrototypeOf$3(o, p);
- }
- var deprecate = require_node();
- var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
- var warnOfDeprecatedValueAssignment = deprecate(function() {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. Call attribute.setValue() instead.");
- var warnOfDeprecatedQuotedAssignment = deprecate(function() {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
- var warnOfDeprecatedConstructor = deprecate(function() {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
- function unescapeValue(value) {
- var deprecatedUsage = false;
- var quoteMark = null;
- var unescaped = value;
- var m = unescaped.match(WRAPPED_IN_QUOTES);
- if (m) {
- quoteMark = m[1];
- unescaped = m[2];
- }
- unescaped = (0, _unesc["default"])(unescaped);
- if (unescaped !== value) deprecatedUsage = true;
- return {
- deprecatedUsage,
- unescaped,
- quoteMark
- };
- }
- function handleDeprecatedContructorOpts(opts) {
- if (opts.quoteMark !== void 0) return opts;
- if (opts.value === void 0) return opts;
- warnOfDeprecatedConstructor();
- var _unescapeValue = unescapeValue(opts.value), quoteMark = _unescapeValue.quoteMark, unescaped = _unescapeValue.unescaped;
- if (!opts.raws) opts.raws = {};
- if (opts.raws.value === void 0) opts.raws.value = opts.value;
- opts.value = unescaped;
- opts.quoteMark = quoteMark;
- return opts;
- }
- var Attribute = /* @__PURE__ */ function(_Namespace) {
- _inheritsLoose$3(Attribute$1, _Namespace);
- function Attribute$1(opts) {
- var _this;
- if (opts === void 0) opts = {};
- _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
- _this.type = _types$5.ATTRIBUTE;
- _this.raws = _this.raws || {};
- Object.defineProperty(_this.raws, "unquoted", {
- get: deprecate(function() {
- return _this.value;
- }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
- set: deprecate(function() {
- return _this.value;
- }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
- });
- _this._constructed = true;
- return _this;
- }
- /**
- * Returns the Attribute's value quoted such that it would be legal to use
- * in the value of a css file. The original value's quotation setting
- * used for stringification is left unchanged. See `setValue(value, options)`
- * if you want to control the quote settings of a new value for the attribute.
- *
- * You can also change the quotation used for the current value by setting quoteMark.
- *
- * Options:
- * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
- * option is not set, the original value for quoteMark will be used. If
- * indeterminate, a double quote is used. The legal values are:
- * * `null` - the value will be unquoted and characters will be escaped as necessary.
- * * `'` - the value will be quoted with a single quote and single quotes are escaped.
- * * `"` - the value will be quoted with a double quote and double quotes are escaped.
- * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
- * over the quoteMark option value.
- * * smart {boolean} - if true, will select a quote mark based on the value
- * and the other options specified here. See the `smartQuoteMark()`
- * method.
- **/
- var _proto = Attribute$1.prototype;
- _proto.getQuotedValue = function getQuotedValue(options) {
- if (options === void 0) options = {};
- var cssescopts = CSSESC_QUOTE_OPTIONS[this._determineQuoteMark(options)];
- return (0, _cssesc["default"])(this._value, cssescopts);
- };
- _proto._determineQuoteMark = function _determineQuoteMark(options) {
- return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
- };
- _proto.setValue = function setValue(value, options) {
- if (options === void 0) options = {};
- this._value = value;
- this._quoteMark = this._determineQuoteMark(options);
- this._syncRawValue();
- };
- _proto.smartQuoteMark = function smartQuoteMark(options) {
- var v = this.value;
- var numSingleQuotes = v.replace(/[^']/g, "").length;
- var numDoubleQuotes = v.replace(/[^"]/g, "").length;
- if (numSingleQuotes + numDoubleQuotes === 0) {
- var escaped = (0, _cssesc["default"])(v, { isIdentifier: true });
- if (escaped === v) return Attribute$1.NO_QUOTE;
- else {
- var pref = this.preferredQuoteMark(options);
- if (pref === Attribute$1.NO_QUOTE) {
- var quote = this.quoteMark || options.quoteMark || Attribute$1.DOUBLE_QUOTE;
- var opts = CSSESC_QUOTE_OPTIONS[quote];
- if ((0, _cssesc["default"])(v, opts).length < escaped.length) return quote;
- }
- return pref;
- }
- } else if (numDoubleQuotes === numSingleQuotes) return this.preferredQuoteMark(options);
- else if (numDoubleQuotes < numSingleQuotes) return Attribute$1.DOUBLE_QUOTE;
- else return Attribute$1.SINGLE_QUOTE;
- };
- _proto.preferredQuoteMark = function preferredQuoteMark(options) {
- var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
- if (quoteMark === void 0) quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
- if (quoteMark === void 0) quoteMark = Attribute$1.DOUBLE_QUOTE;
- return quoteMark;
- };
- _proto._syncRawValue = function _syncRawValue() {
- var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
- if (rawValue === this._value) {
- if (this.raws) delete this.raws.value;
- } else this.raws.value = rawValue;
- };
- _proto._handleEscapes = function _handleEscapes(prop, value) {
- if (this._constructed) {
- var escaped = (0, _cssesc["default"])(value, { isIdentifier: true });
- if (escaped !== value) this.raws[prop] = escaped;
- else delete this.raws[prop];
- }
- };
- _proto._spacesFor = function _spacesFor(name) {
- var attrSpaces = {
- before: "",
- after: ""
- };
- var spaces = this.spaces[name] || {};
- var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
- return Object.assign(attrSpaces, spaces, rawSpaces);
- };
- _proto._stringFor = function _stringFor(name, spaceName, concat) {
- if (spaceName === void 0) spaceName = name;
- if (concat === void 0) concat = defaultAttrConcat;
- var attrSpaces = this._spacesFor(spaceName);
- return concat(this.stringifyProperty(name), attrSpaces);
- };
- _proto.offsetOf = function offsetOf(name) {
- var count = 1;
- var attributeSpaces = this._spacesFor("attribute");
- count += attributeSpaces.before.length;
- if (name === "namespace" || name === "ns") return this.namespace ? count : -1;
- if (name === "attributeNS") return count;
- count += this.namespaceString.length;
- if (this.namespace) count += 1;
- if (name === "attribute") return count;
- count += this.stringifyProperty("attribute").length;
- count += attributeSpaces.after.length;
- var operatorSpaces = this._spacesFor("operator");
- count += operatorSpaces.before.length;
- var operator = this.stringifyProperty("operator");
- if (name === "operator") return operator ? count : -1;
- count += operator.length;
- count += operatorSpaces.after.length;
- var valueSpaces = this._spacesFor("value");
- count += valueSpaces.before.length;
- var value = this.stringifyProperty("value");
- if (name === "value") return value ? count : -1;
- count += value.length;
- count += valueSpaces.after.length;
- var insensitiveSpaces = this._spacesFor("insensitive");
- count += insensitiveSpaces.before.length;
- if (name === "insensitive") return this.insensitive ? count : -1;
- return -1;
- };
- _proto.toString = function toString$1() {
- var _this2 = this;
- var selector$1 = [this.rawSpaceBefore, "["];
- selector$1.push(this._stringFor("qualifiedAttribute", "attribute"));
- if (this.operator && (this.value || this.value === "")) {
- selector$1.push(this._stringFor("operator"));
- selector$1.push(this._stringFor("value"));
- selector$1.push(this._stringFor("insensitiveFlag", "insensitive", function(attrValue, attrSpaces) {
- if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) attrSpaces.before = " ";
- return defaultAttrConcat(attrValue, attrSpaces);
- }));
- }
- selector$1.push("]");
- selector$1.push(this.rawSpaceAfter);
- return selector$1.join("");
- };
- _createClass$1(Attribute$1, [
- {
- key: "quoted",
- get: function get() {
- var qm = this.quoteMark;
- return qm === "'" || qm === "\"";
- },
- set: function set(value) {
- warnOfDeprecatedQuotedAssignment();
- }
- },
- {
- key: "quoteMark",
- get: function get() {
- return this._quoteMark;
- },
- set: function set(quoteMark) {
- if (!this._constructed) {
- this._quoteMark = quoteMark;
- return;
- }
- if (this._quoteMark !== quoteMark) {
- this._quoteMark = quoteMark;
- this._syncRawValue();
- }
- }
- },
- {
- key: "qualifiedAttribute",
- get: function get() {
- return this.qualifiedName(this.raws.attribute || this.attribute);
- }
- },
- {
- key: "insensitiveFlag",
- get: function get() {
- return this.insensitive ? "i" : "";
- }
- },
- {
- key: "value",
- get: function get() {
- return this._value;
- },
- set: function set(v) {
- if (this._constructed) {
- var _unescapeValue2 = unescapeValue(v), deprecatedUsage = _unescapeValue2.deprecatedUsage, unescaped = _unescapeValue2.unescaped, quoteMark = _unescapeValue2.quoteMark;
- if (deprecatedUsage) warnOfDeprecatedValueAssignment();
- if (unescaped === this._value && quoteMark === this._quoteMark) return;
- this._value = unescaped;
- this._quoteMark = quoteMark;
- this._syncRawValue();
- } else this._value = v;
- }
- },
- {
- key: "insensitive",
- get: function get() {
- return this._insensitive;
- },
- set: function set(insensitive) {
- if (!insensitive) {
- this._insensitive = false;
- if (this.raws && (this.raws.insensitiveFlag === "I" || this.raws.insensitiveFlag === "i")) this.raws.insensitiveFlag = void 0;
- }
- this._insensitive = insensitive;
- }
- },
- {
- key: "attribute",
- get: function get() {
- return this._attribute;
- },
- set: function set(name) {
- this._handleEscapes("attribute", name);
- this._attribute = name;
- }
- }
- ]);
- return Attribute$1;
- }(_namespace$1["default"]);
- exports["default"] = Attribute;
- Attribute.NO_QUOTE = null;
- Attribute.SINGLE_QUOTE = "'";
- Attribute.DOUBLE_QUOTE = "\"";
- var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
- "'": {
- quotes: "single",
- wrap: true
- },
- "\"": {
- quotes: "double",
- wrap: true
- }
- }, _CSSESC_QUOTE_OPTIONS[null] = { isIdentifier: true }, _CSSESC_QUOTE_OPTIONS);
- function defaultAttrConcat(attrValue, attrSpaces) {
- return "" + attrSpaces.before + attrValue + attrSpaces.after;
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/universal.js
-var require_universal = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _namespace = _interopRequireDefault$8(require_namespace());
- var _types$4 = require_types();
- function _interopRequireDefault$8(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- function _inheritsLoose$2(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf$2(subClass, superClass);
- }
- function _setPrototypeOf$2(o, p) {
- _setPrototypeOf$2 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf$14(o$1, p$1) {
- o$1.__proto__ = p$1;
- return o$1;
- };
- return _setPrototypeOf$2(o, p);
- }
- var Universal = /* @__PURE__ */ function(_Namespace) {
- _inheritsLoose$2(Universal$1, _Namespace);
- function Universal$1(opts) {
- var _this = _Namespace.call(this, opts) || this;
- _this.type = _types$4.UNIVERSAL;
- _this.value = "*";
- return _this;
- }
- return Universal$1;
- }(_namespace["default"]);
- exports["default"] = Universal;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/combinator.js
-var require_combinator = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _node$1 = _interopRequireDefault$7(require_node$1());
- var _types$3 = require_types();
- function _interopRequireDefault$7(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- function _inheritsLoose$1(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf$1(subClass, superClass);
- }
- function _setPrototypeOf$1(o, p) {
- _setPrototypeOf$1 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf$14(o$1, p$1) {
- o$1.__proto__ = p$1;
- return o$1;
- };
- return _setPrototypeOf$1(o, p);
- }
- var Combinator = /* @__PURE__ */ function(_Node) {
- _inheritsLoose$1(Combinator$1, _Node);
- function Combinator$1(opts) {
- var _this = _Node.call(this, opts) || this;
- _this.type = _types$3.COMBINATOR;
- return _this;
- }
- return Combinator$1;
- }(_node$1["default"]);
- exports["default"] = Combinator;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/nesting.js
-var require_nesting = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _node = _interopRequireDefault$6(require_node$1());
- var _types$2 = require_types();
- function _interopRequireDefault$6(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- function _inheritsLoose(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf(subClass, superClass);
- }
- function _setPrototypeOf(o, p) {
- _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf$14(o$1, p$1) {
- o$1.__proto__ = p$1;
- return o$1;
- };
- return _setPrototypeOf(o, p);
- }
- var Nesting = /* @__PURE__ */ function(_Node) {
- _inheritsLoose(Nesting$1, _Node);
- function Nesting$1(opts) {
- var _this = _Node.call(this, opts) || this;
- _this.type = _types$2.NESTING;
- _this.value = "&";
- return _this;
- }
- return Nesting$1;
- }(_node["default"]);
- exports["default"] = Nesting;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/sortAscending.js
-var require_sortAscending = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = sortAscending;
- function sortAscending(list) {
- return list.sort(function(a, b) {
- return a - b;
- });
- }
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/tokenTypes.js
-var require_tokenTypes = /* @__PURE__ */ __commonJSMin(((exports) => {
- exports.__esModule = true;
- exports.word = exports.tilde = exports.tab = exports.str = exports.space = exports.slash = exports.singleQuote = exports.semicolon = exports.plus = exports.pipe = exports.openSquare = exports.openParenthesis = exports.newline = exports.greaterThan = exports.feed = exports.equals = exports.doubleQuote = exports.dollar = exports.cr = exports.comment = exports.comma = exports.combinator = exports.colon = exports.closeSquare = exports.closeParenthesis = exports.caret = exports.bang = exports.backslash = exports.at = exports.asterisk = exports.ampersand = void 0;
- var ampersand = 38;
- exports.ampersand = ampersand;
- var asterisk = 42;
- exports.asterisk = asterisk;
- var at = 64;
- exports.at = at;
- var comma = 44;
- exports.comma = comma;
- var colon = 58;
- exports.colon = colon;
- var semicolon = 59;
- exports.semicolon = semicolon;
- var openParenthesis = 40;
- exports.openParenthesis = openParenthesis;
- var closeParenthesis = 41;
- exports.closeParenthesis = closeParenthesis;
- var openSquare = 91;
- exports.openSquare = openSquare;
- var closeSquare = 93;
- exports.closeSquare = closeSquare;
- var dollar = 36;
- exports.dollar = dollar;
- var tilde = 126;
- exports.tilde = tilde;
- var caret = 94;
- exports.caret = caret;
- var plus = 43;
- exports.plus = plus;
- var equals = 61;
- exports.equals = equals;
- var pipe = 124;
- exports.pipe = pipe;
- var greaterThan = 62;
- exports.greaterThan = greaterThan;
- var space = 32;
- exports.space = space;
- var singleQuote = 39;
- exports.singleQuote = singleQuote;
- var doubleQuote = 34;
- exports.doubleQuote = doubleQuote;
- var slash = 47;
- exports.slash = slash;
- var bang = 33;
- exports.bang = bang;
- var backslash = 92;
- exports.backslash = backslash;
- var cr = 13;
- exports.cr = cr;
- var feed = 12;
- exports.feed = feed;
- var newline = 10;
- exports.newline = newline;
- var tab = 9;
- exports.tab = tab;
- var str = singleQuote;
- exports.str = str;
- var comment$1 = -1;
- exports.comment = comment$1;
- var word = -2;
- exports.word = word;
- var combinator$1 = -3;
- exports.combinator = combinator$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/tokenize.js
-var require_tokenize = /* @__PURE__ */ __commonJSMin(((exports) => {
- exports.__esModule = true;
- exports.FIELDS = void 0;
- exports["default"] = tokenize;
- var t = _interopRequireWildcard$2(require_tokenTypes());
- var _unescapable, _wordDelimiters;
- function _getRequireWildcardCache$2(nodeInterop) {
- if (typeof WeakMap !== "function") return null;
- var cacheBabelInterop = /* @__PURE__ */ new WeakMap();
- var cacheNodeInterop = /* @__PURE__ */ new WeakMap();
- return (_getRequireWildcardCache$2 = function _getRequireWildcardCache$4(nodeInterop$1) {
- return nodeInterop$1 ? cacheNodeInterop : cacheBabelInterop;
- })(nodeInterop);
- }
- function _interopRequireWildcard$2(obj, nodeInterop) {
- if (!nodeInterop && obj && obj.__esModule) return obj;
- if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { "default": obj };
- var cache = _getRequireWildcardCache$2(nodeInterop);
- if (cache && cache.has(obj)) return cache.get(obj);
- var newObj = {};
- var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
- for (var key in obj) if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
- var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
- if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc);
- else newObj[key] = obj[key];
- }
- newObj["default"] = obj;
- if (cache) cache.set(obj, newObj);
- return newObj;
- }
- var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
- var wordDelimiters = (_wordDelimiters = {}, _wordDelimiters[t.space] = true, _wordDelimiters[t.tab] = true, _wordDelimiters[t.newline] = true, _wordDelimiters[t.cr] = true, _wordDelimiters[t.feed] = true, _wordDelimiters[t.ampersand] = true, _wordDelimiters[t.asterisk] = true, _wordDelimiters[t.bang] = true, _wordDelimiters[t.comma] = true, _wordDelimiters[t.colon] = true, _wordDelimiters[t.semicolon] = true, _wordDelimiters[t.openParenthesis] = true, _wordDelimiters[t.closeParenthesis] = true, _wordDelimiters[t.openSquare] = true, _wordDelimiters[t.closeSquare] = true, _wordDelimiters[t.singleQuote] = true, _wordDelimiters[t.doubleQuote] = true, _wordDelimiters[t.plus] = true, _wordDelimiters[t.pipe] = true, _wordDelimiters[t.tilde] = true, _wordDelimiters[t.greaterThan] = true, _wordDelimiters[t.equals] = true, _wordDelimiters[t.dollar] = true, _wordDelimiters[t.caret] = true, _wordDelimiters[t.slash] = true, _wordDelimiters);
- var hex = {};
- var hexChars = "0123456789abcdefABCDEF";
- for (var i = 0; i < hexChars.length; i++) hex[hexChars.charCodeAt(i)] = true;
- /**
- * Returns the last index of the bar css word
- * @param {string} css The string in which the word begins
- * @param {number} start The index into the string where word's first letter occurs
- */
- function consumeWord(css, start) {
- var next = start;
- var code;
- do {
- code = css.charCodeAt(next);
- if (wordDelimiters[code]) return next - 1;
- else if (code === t.backslash) next = consumeEscape(css, next) + 1;
- else next++;
- } while (next < css.length);
- return next - 1;
- }
- /**
- * Returns the last index of the escape sequence
- * @param {string} css The string in which the sequence begins
- * @param {number} start The index into the string where escape character (`\`) occurs.
- */
- function consumeEscape(css, start) {
- var next = start;
- var code = css.charCodeAt(next + 1);
- if (unescapable[code]) {} else if (hex[code]) {
- var hexDigits = 0;
- do {
- next++;
- hexDigits++;
- code = css.charCodeAt(next + 1);
- } while (hex[code] && hexDigits < 6);
- if (hexDigits < 6 && code === t.space) next++;
- } else next++;
- return next;
- }
- var FIELDS = {
- TYPE: 0,
- START_LINE: 1,
- START_COL: 2,
- END_LINE: 3,
- END_COL: 4,
- START_POS: 5,
- END_POS: 6
- };
- exports.FIELDS = FIELDS;
- function tokenize(input) {
- var tokens$1 = [];
- var css = input.css.valueOf();
- var length = css.length;
- var offset = -1;
- var line = 1;
- var start = 0;
- var end = 0;
- var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
- function unclosed(what, fix) {
- if (input.safe) {
- css += fix;
- next = css.length - 1;
- } else throw input.error("Unclosed " + what, line, start - offset, start);
- }
- while (start < length) {
- code = css.charCodeAt(start);
- if (code === t.newline) {
- offset = start;
- line += 1;
- }
- switch (code) {
- case t.space:
- case t.tab:
- case t.newline:
- case t.cr:
- case t.feed:
- next = start;
- do {
- next += 1;
- code = css.charCodeAt(next);
- if (code === t.newline) {
- offset = next;
- line += 1;
- }
- } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
- tokenType = t.space;
- endLine = line;
- endColumn = next - offset - 1;
- end = next;
- break;
- case t.plus:
- case t.greaterThan:
- case t.tilde:
- case t.pipe:
- next = start;
- do {
- next += 1;
- code = css.charCodeAt(next);
- } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
- tokenType = t.combinator;
- endLine = line;
- endColumn = start - offset;
- end = next;
- break;
- case t.asterisk:
- case t.ampersand:
- case t.bang:
- case t.comma:
- case t.equals:
- case t.dollar:
- case t.caret:
- case t.openSquare:
- case t.closeSquare:
- case t.colon:
- case t.semicolon:
- case t.openParenthesis:
- case t.closeParenthesis:
- next = start;
- tokenType = code;
- endLine = line;
- endColumn = start - offset;
- end = next + 1;
- break;
- case t.singleQuote:
- case t.doubleQuote:
- quote = code === t.singleQuote ? "'" : "\"";
- next = start;
- do {
- escaped = false;
- next = css.indexOf(quote, next + 1);
- if (next === -1) unclosed("quote", quote);
- escapePos = next;
- while (css.charCodeAt(escapePos - 1) === t.backslash) {
- escapePos -= 1;
- escaped = !escaped;
- }
- } while (escaped);
- tokenType = t.str;
- endLine = line;
- endColumn = start - offset;
- end = next + 1;
- break;
- default:
- if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
- next = css.indexOf("*/", start + 2) + 1;
- if (next === 0) unclosed("comment", "*/");
- content = css.slice(start, next + 1);
- lines = content.split("\n");
- last = lines.length - 1;
- if (last > 0) {
- nextLine = line + last;
- nextOffset = next - lines[last].length;
- } else {
- nextLine = line;
- nextOffset = offset;
- }
- tokenType = t.comment;
- line = nextLine;
- endLine = nextLine;
- endColumn = next - nextOffset;
- } else if (code === t.slash) {
- next = start;
- tokenType = code;
- endLine = line;
- endColumn = start - offset;
- end = next + 1;
- } else {
- next = consumeWord(css, start);
- tokenType = t.word;
- endLine = line;
- endColumn = next - offset;
- }
- end = next + 1;
- break;
- }
- tokens$1.push([
- tokenType,
- line,
- start - offset,
- endLine,
- endColumn,
- start,
- end
- ]);
- if (nextOffset) {
- offset = nextOffset;
- nextOffset = null;
- }
- start = end;
- }
- return tokens$1;
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/parser.js
-var require_parser = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _root$1 = _interopRequireDefault$5(require_root());
- var _selector$1 = _interopRequireDefault$5(require_selector());
- var _className$1 = _interopRequireDefault$5(require_className());
- var _comment$1 = _interopRequireDefault$5(require_comment());
- var _id$1 = _interopRequireDefault$5(require_id());
- var _tag$1 = _interopRequireDefault$5(require_tag());
- var _string$1 = _interopRequireDefault$5(require_string());
- var _pseudo$1 = _interopRequireDefault$5(require_pseudo());
- var _attribute$1 = _interopRequireWildcard$1(require_attribute());
- var _universal$1 = _interopRequireDefault$5(require_universal());
- var _combinator$1 = _interopRequireDefault$5(require_combinator());
- var _nesting$1 = _interopRequireDefault$5(require_nesting());
- var _sortAscending = _interopRequireDefault$5(require_sortAscending());
- var _tokenize = _interopRequireWildcard$1(require_tokenize());
- var tokens = _interopRequireWildcard$1(require_tokenTypes());
- var types = _interopRequireWildcard$1(require_types());
- var _util = require_util();
- var _WHITESPACE_TOKENS, _Object$assign;
- function _getRequireWildcardCache$1(nodeInterop) {
- if (typeof WeakMap !== "function") return null;
- var cacheBabelInterop = /* @__PURE__ */ new WeakMap();
- var cacheNodeInterop = /* @__PURE__ */ new WeakMap();
- return (_getRequireWildcardCache$1 = function _getRequireWildcardCache$4(nodeInterop$1) {
- return nodeInterop$1 ? cacheNodeInterop : cacheBabelInterop;
- })(nodeInterop);
- }
- function _interopRequireWildcard$1(obj, nodeInterop) {
- if (!nodeInterop && obj && obj.__esModule) return obj;
- if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { "default": obj };
- var cache = _getRequireWildcardCache$1(nodeInterop);
- if (cache && cache.has(obj)) return cache.get(obj);
- var newObj = {};
- var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
- for (var key in obj) if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
- var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
- if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc);
- else newObj[key] = obj[key];
- }
- newObj["default"] = obj;
- if (cache) cache.set(obj, newObj);
- return newObj;
- }
- function _interopRequireDefault$5(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- function _defineProperties(target, props) {
- for (var i$1 = 0; i$1 < props.length; i$1++) {
- var descriptor = props[i$1];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, descriptor.key, descriptor);
- }
- }
- function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- Object.defineProperty(Constructor, "prototype", { writable: false });
- return Constructor;
- }
- var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS);
- var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
- function tokenStart(token) {
- return {
- line: token[_tokenize.FIELDS.START_LINE],
- column: token[_tokenize.FIELDS.START_COL]
- };
- }
- function tokenEnd(token) {
- return {
- line: token[_tokenize.FIELDS.END_LINE],
- column: token[_tokenize.FIELDS.END_COL]
- };
- }
- function getSource(startLine, startColumn, endLine, endColumn) {
- return {
- start: {
- line: startLine,
- column: startColumn
- },
- end: {
- line: endLine,
- column: endColumn
- }
- };
- }
- function getTokenSource(token) {
- return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
- }
- function getTokenSourceSpan(startToken, endToken) {
- if (!startToken) return;
- return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
- }
- function unescapeProp(node, prop) {
- var value = node[prop];
- if (typeof value !== "string") return;
- if (value.indexOf("\\") !== -1) {
- (0, _util.ensureObject)(node, "raws");
- node[prop] = (0, _util.unesc)(value);
- if (node.raws[prop] === void 0) node.raws[prop] = value;
- }
- return node;
- }
- function indexesOf(array, item) {
- var i$1 = -1;
- var indexes = [];
- while ((i$1 = array.indexOf(item, i$1 + 1)) !== -1) indexes.push(i$1);
- return indexes;
- }
- function uniqs() {
- var list = Array.prototype.concat.apply([], arguments);
- return list.filter(function(item, i$1) {
- return i$1 === list.indexOf(item);
- });
- }
- var Parser = /* @__PURE__ */ function() {
- function Parser$2(rule, options) {
- if (options === void 0) options = {};
- this.rule = rule;
- this.options = Object.assign({
- lossy: false,
- safe: false
- }, options);
- this.position = 0;
- this.css = typeof this.rule === "string" ? this.rule : this.rule.selector;
- this.tokens = (0, _tokenize["default"])({
- css: this.css,
- error: this._errorGenerator(),
- safe: this.options.safe
- });
- var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
- this.root = new _root$1["default"]({ source: rootSource });
- this.root.errorGenerator = this._errorGenerator();
- var selector$1 = new _selector$1["default"]({
- source: { start: {
- line: 1,
- column: 1
- } },
- sourceIndex: 0
- });
- this.root.append(selector$1);
- this.current = selector$1;
- this.loop();
- }
- var _proto = Parser$2.prototype;
- _proto._errorGenerator = function _errorGenerator() {
- var _this = this;
- return function(message, errorOptions) {
- if (typeof _this.rule === "string") return new Error(message);
- return _this.rule.error(message, errorOptions);
- };
- };
- _proto.attribute = function attribute$1() {
- var attr = [];
- var startingToken = this.currToken;
- this.position++;
- while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
- attr.push(this.currToken);
- this.position++;
- }
- if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) return this.expected("closing square bracket", this.currToken[_tokenize.FIELDS.START_POS]);
- var len = attr.length;
- var node = {
- source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
- sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
- };
- if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) return this.expected("attribute", attr[0][_tokenize.FIELDS.START_POS]);
- var pos = 0;
- var spaceBefore = "";
- var commentBefore = "";
- var lastAdded = null;
- var spaceAfterMeaningfulToken = false;
- while (pos < len) {
- var token = attr[pos];
- var content = this.content(token);
- var next = attr[pos + 1];
- switch (token[_tokenize.FIELDS.TYPE]) {
- case tokens.space:
- spaceAfterMeaningfulToken = true;
- if (this.options.lossy) break;
- if (lastAdded) {
- (0, _util.ensureObject)(node, "spaces", lastAdded);
- var prevContent = node.spaces[lastAdded].after || "";
- node.spaces[lastAdded].after = prevContent + content;
- var existingComment = (0, _util.getProp)(node, "raws", "spaces", lastAdded, "after") || null;
- if (existingComment) node.raws.spaces[lastAdded].after = existingComment + content;
- } else {
- spaceBefore = spaceBefore + content;
- commentBefore = commentBefore + content;
- }
- break;
- case tokens.asterisk:
- if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
- node.operator = content;
- lastAdded = "operator";
- } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
- if (spaceBefore) {
- (0, _util.ensureObject)(node, "spaces", "attribute");
- node.spaces.attribute.before = spaceBefore;
- spaceBefore = "";
- }
- if (commentBefore) {
- (0, _util.ensureObject)(node, "raws", "spaces", "attribute");
- node.raws.spaces.attribute.before = spaceBefore;
- commentBefore = "";
- }
- node.namespace = (node.namespace || "") + content;
- if ((0, _util.getProp)(node, "raws", "namespace") || null) node.raws.namespace += content;
- lastAdded = "namespace";
- }
- spaceAfterMeaningfulToken = false;
- break;
- case tokens.dollar: if (lastAdded === "value") {
- var oldRawValue = (0, _util.getProp)(node, "raws", "value");
- node.value += "$";
- if (oldRawValue) node.raws.value = oldRawValue + "$";
- break;
- }
- case tokens.caret:
- if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
- node.operator = content;
- lastAdded = "operator";
- }
- spaceAfterMeaningfulToken = false;
- break;
- case tokens.combinator:
- if (content === "~" && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
- node.operator = content;
- lastAdded = "operator";
- }
- if (content !== "|") {
- spaceAfterMeaningfulToken = false;
- break;
- }
- if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
- node.operator = content;
- lastAdded = "operator";
- } else if (!node.namespace && !node.attribute) node.namespace = true;
- spaceAfterMeaningfulToken = false;
- break;
- case tokens.word:
- if (next && this.content(next) === "|" && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals && !node.operator && !node.namespace) {
- node.namespace = content;
- lastAdded = "namespace";
- } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
- if (spaceBefore) {
- (0, _util.ensureObject)(node, "spaces", "attribute");
- node.spaces.attribute.before = spaceBefore;
- spaceBefore = "";
- }
- if (commentBefore) {
- (0, _util.ensureObject)(node, "raws", "spaces", "attribute");
- node.raws.spaces.attribute.before = commentBefore;
- commentBefore = "";
- }
- node.attribute = (node.attribute || "") + content;
- if ((0, _util.getProp)(node, "raws", "attribute") || null) node.raws.attribute += content;
- lastAdded = "attribute";
- } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
- var _unescaped = (0, _util.unesc)(content);
- var _oldRawValue = (0, _util.getProp)(node, "raws", "value") || "";
- var oldValue = node.value || "";
- node.value = oldValue + _unescaped;
- node.quoteMark = null;
- if (_unescaped !== content || _oldRawValue) {
- (0, _util.ensureObject)(node, "raws");
- node.raws.value = (_oldRawValue || oldValue) + content;
- }
- lastAdded = "value";
- } else {
- var insensitive = content === "i" || content === "I";
- if ((node.value || node.value === "") && (node.quoteMark || spaceAfterMeaningfulToken)) {
- node.insensitive = insensitive;
- if (!insensitive || content === "I") {
- (0, _util.ensureObject)(node, "raws");
- node.raws.insensitiveFlag = content;
- }
- lastAdded = "insensitive";
- if (spaceBefore) {
- (0, _util.ensureObject)(node, "spaces", "insensitive");
- node.spaces.insensitive.before = spaceBefore;
- spaceBefore = "";
- }
- if (commentBefore) {
- (0, _util.ensureObject)(node, "raws", "spaces", "insensitive");
- node.raws.spaces.insensitive.before = commentBefore;
- commentBefore = "";
- }
- } else if (node.value || node.value === "") {
- lastAdded = "value";
- node.value += content;
- if (node.raws.value) node.raws.value += content;
- }
- }
- spaceAfterMeaningfulToken = false;
- break;
- case tokens.str:
- if (!node.attribute || !node.operator) return this.error("Expected an attribute followed by an operator preceding the string.", { index: token[_tokenize.FIELDS.START_POS] });
- var _unescapeValue = (0, _attribute$1.unescapeValue)(content), unescaped = _unescapeValue.unescaped, quoteMark = _unescapeValue.quoteMark;
- node.value = unescaped;
- node.quoteMark = quoteMark;
- lastAdded = "value";
- (0, _util.ensureObject)(node, "raws");
- node.raws.value = content;
- spaceAfterMeaningfulToken = false;
- break;
- case tokens.equals:
- if (!node.attribute) return this.expected("attribute", token[_tokenize.FIELDS.START_POS], content);
- if (node.value) return this.error("Unexpected \"=\" found; an operator was already defined.", { index: token[_tokenize.FIELDS.START_POS] });
- node.operator = node.operator ? node.operator + content : content;
- lastAdded = "operator";
- spaceAfterMeaningfulToken = false;
- break;
- case tokens.comment:
- if (lastAdded) if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === "insensitive") {
- var lastComment = (0, _util.getProp)(node, "spaces", lastAdded, "after") || "";
- var rawLastComment = (0, _util.getProp)(node, "raws", "spaces", lastAdded, "after") || lastComment;
- (0, _util.ensureObject)(node, "raws", "spaces", lastAdded);
- node.raws.spaces[lastAdded].after = rawLastComment + content;
- } else {
- var lastValue = node[lastAdded] || "";
- var rawLastValue = (0, _util.getProp)(node, "raws", lastAdded) || lastValue;
- (0, _util.ensureObject)(node, "raws");
- node.raws[lastAdded] = rawLastValue + content;
- }
- else commentBefore = commentBefore + content;
- break;
- default: return this.error("Unexpected \"" + content + "\" found.", { index: token[_tokenize.FIELDS.START_POS] });
- }
- pos++;
- }
- unescapeProp(node, "attribute");
- unescapeProp(node, "namespace");
- this.newNode(new _attribute$1["default"](node));
- this.position++;
- };
- _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
- if (stopPosition < 0) stopPosition = this.tokens.length;
- var startPosition = this.position;
- var nodes = [];
- var space$1 = "";
- var lastComment = void 0;
- do
- if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
- if (!this.options.lossy) space$1 += this.content();
- } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
- var spaces = {};
- if (space$1) {
- spaces.before = space$1;
- space$1 = "";
- }
- lastComment = new _comment$1["default"]({
- value: this.content(),
- source: getTokenSource(this.currToken),
- sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
- spaces
- });
- nodes.push(lastComment);
- }
- while (++this.position < stopPosition);
- if (space$1) {
- if (lastComment) lastComment.spaces.after = space$1;
- else if (!this.options.lossy) {
- var firstToken = this.tokens[startPosition];
- var lastToken = this.tokens[this.position - 1];
- nodes.push(new _string$1["default"]({
- value: "",
- source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
- sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
- spaces: {
- before: space$1,
- after: ""
- }
- }));
- }
- }
- return nodes;
- };
- _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
- var _this2 = this;
- if (requiredSpace === void 0) requiredSpace = false;
- var space$1 = "";
- var rawSpace = "";
- nodes.forEach(function(n) {
- var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
- var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
- space$1 += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
- rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
- });
- if (rawSpace === space$1) rawSpace = void 0;
- return {
- space: space$1,
- rawSpace
- };
- };
- _proto.isNamedCombinator = function isNamedCombinator(position) {
- if (position === void 0) position = this.position;
- return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash;
- };
- _proto.namedCombinator = function namedCombinator() {
- if (this.isNamedCombinator()) {
- var nameRaw = this.content(this.tokens[this.position + 1]);
- var name = (0, _util.unesc)(nameRaw).toLowerCase();
- var raws = {};
- if (name !== nameRaw) raws.value = "/" + nameRaw + "/";
- var node = new _combinator$1["default"]({
- value: "/" + name + "/",
- source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]),
- sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
- raws
- });
- this.position = this.position + 3;
- return node;
- } else this.unexpected();
- };
- _proto.combinator = function combinator$2() {
- var _this3 = this;
- if (this.content() === "|") return this.namespace();
- var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
- if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
- var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
- if (nodes.length > 0) {
- var last = this.current.last;
- if (last) {
- var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes), space$1 = _this$convertWhitespa.space, rawSpace = _this$convertWhitespa.rawSpace;
- if (rawSpace !== void 0) last.rawSpaceAfter += rawSpace;
- last.spaces.after += space$1;
- } else nodes.forEach(function(n) {
- return _this3.newNode(n);
- });
- }
- return;
- }
- var firstToken = this.currToken;
- var spaceOrDescendantSelectorNodes = void 0;
- if (nextSigTokenPos > this.position) spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
- var node;
- if (this.isNamedCombinator()) node = this.namedCombinator();
- else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
- node = new _combinator$1["default"]({
- value: this.content(),
- source: getTokenSource(this.currToken),
- sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
- });
- this.position++;
- } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {} else if (!spaceOrDescendantSelectorNodes) this.unexpected();
- if (node) {
- if (spaceOrDescendantSelectorNodes) {
- var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes), _space = _this$convertWhitespa2.space, _rawSpace = _this$convertWhitespa2.rawSpace;
- node.spaces.before = _space;
- node.rawSpaceBefore = _rawSpace;
- }
- } else {
- var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true), _space2 = _this$convertWhitespa3.space, _rawSpace2 = _this$convertWhitespa3.rawSpace;
- if (!_rawSpace2) _rawSpace2 = _space2;
- var spaces = {};
- var raws = { spaces: {} };
- if (_space2.endsWith(" ") && _rawSpace2.endsWith(" ")) {
- spaces.before = _space2.slice(0, _space2.length - 1);
- raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
- } else if (_space2.startsWith(" ") && _rawSpace2.startsWith(" ")) {
- spaces.after = _space2.slice(1);
- raws.spaces.after = _rawSpace2.slice(1);
- } else raws.value = _rawSpace2;
- node = new _combinator$1["default"]({
- value: " ",
- source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
- sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
- spaces,
- raws
- });
- }
- if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
- node.spaces.after = this.optionalSpace(this.content());
- this.position++;
- }
- return this.newNode(node);
- };
- _proto.comma = function comma$1() {
- if (this.position === this.tokens.length - 1) {
- this.root.trailingComma = true;
- this.position++;
- return;
- }
- this.current._inferEndPosition();
- var selector$1 = new _selector$1["default"]({
- source: { start: tokenStart(this.tokens[this.position + 1]) },
- sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
- });
- this.current.parent.append(selector$1);
- this.current = selector$1;
- this.position++;
- };
- _proto.comment = function comment$2() {
- var current = this.currToken;
- this.newNode(new _comment$1["default"]({
- value: this.content(),
- source: getTokenSource(current),
- sourceIndex: current[_tokenize.FIELDS.START_POS]
- }));
- this.position++;
- };
- _proto.error = function error(message, opts) {
- throw this.root.error(message, opts);
- };
- _proto.missingBackslash = function missingBackslash() {
- return this.error("Expected a backslash preceding the semicolon.", { index: this.currToken[_tokenize.FIELDS.START_POS] });
- };
- _proto.missingParenthesis = function missingParenthesis() {
- return this.expected("opening parenthesis", this.currToken[_tokenize.FIELDS.START_POS]);
- };
- _proto.missingSquareBracket = function missingSquareBracket() {
- return this.expected("opening square bracket", this.currToken[_tokenize.FIELDS.START_POS]);
- };
- _proto.unexpected = function unexpected() {
- return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
- };
- _proto.unexpectedPipe = function unexpectedPipe() {
- return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
- };
- _proto.namespace = function namespace() {
- var before = this.prevToken && this.content(this.prevToken) || true;
- if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
- this.position++;
- return this.word(before);
- } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
- this.position++;
- return this.universal(before);
- }
- this.unexpectedPipe();
- };
- _proto.nesting = function nesting$1() {
- if (this.nextToken) {
- if (this.content(this.nextToken) === "|") {
- this.position++;
- return;
- }
- }
- var current = this.currToken;
- this.newNode(new _nesting$1["default"]({
- value: this.content(),
- source: getTokenSource(current),
- sourceIndex: current[_tokenize.FIELDS.START_POS]
- }));
- this.position++;
- };
- _proto.parentheses = function parentheses() {
- var last = this.current.last;
- var unbalanced = 1;
- this.position++;
- if (last && last.type === types.PSEUDO) {
- var selector$1 = new _selector$1["default"]({
- source: { start: tokenStart(this.tokens[this.position]) },
- sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
- });
- var cache = this.current;
- last.append(selector$1);
- this.current = selector$1;
- while (this.position < this.tokens.length && unbalanced) {
- if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) unbalanced++;
- if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) unbalanced--;
- if (unbalanced) this.parse();
- else {
- this.current.source.end = tokenEnd(this.currToken);
- this.current.parent.source.end = tokenEnd(this.currToken);
- this.position++;
- }
- }
- this.current = cache;
- } else {
- var parenStart = this.currToken;
- var parenValue = "(";
- var parenEnd;
- while (this.position < this.tokens.length && unbalanced) {
- if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) unbalanced++;
- if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) unbalanced--;
- parenEnd = this.currToken;
- parenValue += this.parseParenthesisToken(this.currToken);
- this.position++;
- }
- if (last) last.appendToPropertyAndEscape("value", parenValue, parenValue);
- else this.newNode(new _string$1["default"]({
- value: parenValue,
- source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
- sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
- }));
- }
- if (unbalanced) return this.expected("closing parenthesis", this.currToken[_tokenize.FIELDS.START_POS]);
- };
- _proto.pseudo = function pseudo$1() {
- var _this4 = this;
- var pseudoStr = "";
- var startingToken = this.currToken;
- while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
- pseudoStr += this.content();
- this.position++;
- }
- if (!this.currToken) return this.expected(["pseudo-class", "pseudo-element"], this.position - 1);
- if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) this.splitWord(false, function(first, length) {
- pseudoStr += first;
- _this4.newNode(new _pseudo$1["default"]({
- value: pseudoStr,
- source: getTokenSourceSpan(startingToken, _this4.currToken),
- sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
- }));
- if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) _this4.error("Misplaced parenthesis.", { index: _this4.nextToken[_tokenize.FIELDS.START_POS] });
- });
- else return this.expected(["pseudo-class", "pseudo-element"], this.currToken[_tokenize.FIELDS.START_POS]);
- };
- _proto.space = function space$1() {
- var content = this.content();
- if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function(node) {
- return node.type === "comment";
- })) {
- this.spaces = this.optionalSpace(content);
- this.position++;
- } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
- this.current.last.spaces.after = this.optionalSpace(content);
- this.position++;
- } else this.combinator();
- };
- _proto.string = function string$1() {
- var current = this.currToken;
- this.newNode(new _string$1["default"]({
- value: this.content(),
- source: getTokenSource(current),
- sourceIndex: current[_tokenize.FIELDS.START_POS]
- }));
- this.position++;
- };
- _proto.universal = function universal$1(namespace) {
- var nextToken = this.nextToken;
- if (nextToken && this.content(nextToken) === "|") {
- this.position++;
- return this.namespace();
- }
- var current = this.currToken;
- this.newNode(new _universal$1["default"]({
- value: this.content(),
- source: getTokenSource(current),
- sourceIndex: current[_tokenize.FIELDS.START_POS]
- }), namespace);
- this.position++;
- };
- _proto.splitWord = function splitWord(namespace, firstCallback) {
- var _this5 = this;
- var nextToken = this.nextToken;
- var word$1 = this.content();
- while (nextToken && ~[
- tokens.dollar,
- tokens.caret,
- tokens.equals,
- tokens.word
- ].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
- this.position++;
- var current = this.content();
- word$1 += current;
- if (current.lastIndexOf("\\") === current.length - 1) {
- var next = this.nextToken;
- if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
- word$1 += this.requiredSpace(this.content(next));
- this.position++;
- }
- }
- nextToken = this.nextToken;
- }
- var hasClass = indexesOf(word$1, ".").filter(function(i$1) {
- var escapedDot = word$1[i$1 - 1] === "\\";
- var isKeyframesPercent = /^\d+\.\d+%$/.test(word$1);
- return !escapedDot && !isKeyframesPercent;
- });
- var hasId = indexesOf(word$1, "#").filter(function(i$1) {
- return word$1[i$1 - 1] !== "\\";
- });
- var interpolations = indexesOf(word$1, "#{");
- if (interpolations.length) hasId = hasId.filter(function(hashIndex) {
- return !~interpolations.indexOf(hashIndex);
- });
- var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
- indices.forEach(function(ind, i$1) {
- var index = indices[i$1 + 1] || word$1.length;
- var value = word$1.slice(ind, index);
- if (i$1 === 0 && firstCallback) return firstCallback.call(_this5, value, indices.length);
- var node;
- var current$1 = _this5.currToken;
- var sourceIndex = current$1[_tokenize.FIELDS.START_POS] + indices[i$1];
- var source = getSource(current$1[1], current$1[2] + ind, current$1[3], current$1[2] + (index - 1));
- if (~hasClass.indexOf(ind)) {
- var classNameOpts = {
- value: value.slice(1),
- source,
- sourceIndex
- };
- node = new _className$1["default"](unescapeProp(classNameOpts, "value"));
- } else if (~hasId.indexOf(ind)) {
- var idOpts = {
- value: value.slice(1),
- source,
- sourceIndex
- };
- node = new _id$1["default"](unescapeProp(idOpts, "value"));
- } else {
- var tagOpts = {
- value,
- source,
- sourceIndex
- };
- unescapeProp(tagOpts, "value");
- node = new _tag$1["default"](tagOpts);
- }
- _this5.newNode(node, namespace);
- namespace = null;
- });
- this.position++;
- };
- _proto.word = function word$1(namespace) {
- var nextToken = this.nextToken;
- if (nextToken && this.content(nextToken) === "|") {
- this.position++;
- return this.namespace();
- }
- return this.splitWord(namespace);
- };
- _proto.loop = function loop() {
- while (this.position < this.tokens.length) this.parse(true);
- this.current._inferEndPosition();
- return this.root;
- };
- _proto.parse = function parse(throwOnParenthesis) {
- switch (this.currToken[_tokenize.FIELDS.TYPE]) {
- case tokens.space:
- this.space();
- break;
- case tokens.comment:
- this.comment();
- break;
- case tokens.openParenthesis:
- this.parentheses();
- break;
- case tokens.closeParenthesis:
- if (throwOnParenthesis) this.missingParenthesis();
- break;
- case tokens.openSquare:
- this.attribute();
- break;
- case tokens.dollar:
- case tokens.caret:
- case tokens.equals:
- case tokens.word:
- this.word();
- break;
- case tokens.colon:
- this.pseudo();
- break;
- case tokens.comma:
- this.comma();
- break;
- case tokens.asterisk:
- this.universal();
- break;
- case tokens.ampersand:
- this.nesting();
- break;
- case tokens.slash:
- case tokens.combinator:
- this.combinator();
- break;
- case tokens.str:
- this.string();
- break;
- case tokens.closeSquare: this.missingSquareBracket();
- case tokens.semicolon: this.missingBackslash();
- default: this.unexpected();
- }
- };
- _proto.expected = function expected(description, index, found) {
- if (Array.isArray(description)) {
- var last = description.pop();
- description = description.join(", ") + " or " + last;
- }
- var an = /^[aeiou]/.test(description[0]) ? "an" : "a";
- if (!found) return this.error("Expected " + an + " " + description + ".", { index });
- return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", { index });
- };
- _proto.requiredSpace = function requiredSpace(space$1) {
- return this.options.lossy ? " " : space$1;
- };
- _proto.optionalSpace = function optionalSpace(space$1) {
- return this.options.lossy ? "" : space$1;
- };
- _proto.lossySpace = function lossySpace(space$1, required) {
- if (this.options.lossy) return required ? " " : "";
- else return space$1;
- };
- _proto.parseParenthesisToken = function parseParenthesisToken(token) {
- var content = this.content(token);
- if (token[_tokenize.FIELDS.TYPE] === tokens.space) return this.requiredSpace(content);
- else return content;
- };
- _proto.newNode = function newNode(node, namespace) {
- if (namespace) {
- if (/^ +$/.test(namespace)) {
- if (!this.options.lossy) this.spaces = (this.spaces || "") + namespace;
- namespace = true;
- }
- node.namespace = namespace;
- unescapeProp(node, "namespace");
- }
- if (this.spaces) {
- node.spaces.before = this.spaces;
- this.spaces = "";
- }
- return this.current.append(node);
- };
- _proto.content = function content(token) {
- if (token === void 0) token = this.currToken;
- return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
- };
- /**
- * returns the index of the next non-whitespace, non-comment token.
- * returns -1 if no meaningful token is found.
- */
- _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
- if (startPosition === void 0) startPosition = this.position + 1;
- var searchPosition = startPosition;
- while (searchPosition < this.tokens.length) if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
- searchPosition++;
- continue;
- } else return searchPosition;
- return -1;
- };
- _createClass(Parser$2, [
- {
- key: "currToken",
- get: function get() {
- return this.tokens[this.position];
- }
- },
- {
- key: "nextToken",
- get: function get() {
- return this.tokens[this.position + 1];
- }
- },
- {
- key: "prevToken",
- get: function get() {
- return this.tokens[this.position - 1];
- }
- }
- ]);
- return Parser$2;
- }();
- exports["default"] = Parser;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/processor.js
-var require_processor = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _parser = _interopRequireDefault$4(require_parser());
- function _interopRequireDefault$4(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- var Processor = /* @__PURE__ */ function() {
- function Processor$1(func, options) {
- this.func = func || function noop() {};
- this.funcRes = null;
- this.options = options;
- }
- var _proto = Processor$1.prototype;
- _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
- if (options === void 0) options = {};
- if (Object.assign({}, this.options, options).updateSelector === false) return false;
- else return typeof rule !== "string";
- };
- _proto._isLossy = function _isLossy(options) {
- if (options === void 0) options = {};
- if (Object.assign({}, this.options, options).lossless === false) return true;
- else return false;
- };
- _proto._root = function _root$2(rule, options) {
- if (options === void 0) options = {};
- return new _parser["default"](rule, this._parseOptions(options)).root;
- };
- _proto._parseOptions = function _parseOptions(options) {
- return { lossy: this._isLossy(options) };
- };
- _proto._run = function _run(rule, options) {
- var _this = this;
- if (options === void 0) options = {};
- return new Promise(function(resolve, reject) {
- try {
- var root$2 = _this._root(rule, options);
- Promise.resolve(_this.func(root$2)).then(function(transform) {
- var string$1 = void 0;
- if (_this._shouldUpdateSelector(rule, options)) {
- string$1 = root$2.toString();
- rule.selector = string$1;
- }
- return {
- transform,
- root: root$2,
- string: string$1
- };
- }).then(resolve, reject);
- } catch (e) {
- reject(e);
- return;
- }
- });
- };
- _proto._runSync = function _runSync(rule, options) {
- if (options === void 0) options = {};
- var root$2 = this._root(rule, options);
- var transform = this.func(root$2);
- if (transform && typeof transform.then === "function") throw new Error("Selector processor returned a promise to a synchronous call.");
- var string$1 = void 0;
- if (options.updateSelector && typeof rule !== "string") {
- string$1 = root$2.toString();
- rule.selector = string$1;
- }
- return {
- transform,
- root: root$2,
- string: string$1
- };
- };
- _proto.ast = function ast(rule, options) {
- return this._run(rule, options).then(function(result) {
- return result.root;
- });
- };
- _proto.astSync = function astSync(rule, options) {
- return this._runSync(rule, options).root;
- };
- _proto.transform = function transform(rule, options) {
- return this._run(rule, options).then(function(result) {
- return result.transform;
- });
- };
- _proto.transformSync = function transformSync(rule, options) {
- return this._runSync(rule, options).transform;
- };
- _proto.process = function process$1(rule, options) {
- return this._run(rule, options).then(function(result) {
- return result.string || result.root.toString();
- });
- };
- _proto.processSync = function processSync(rule, options) {
- var result = this._runSync(rule, options);
- return result.string || result.root.toString();
- };
- return Processor$1;
- }();
- exports["default"] = Processor;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/constructors.js
-var require_constructors = /* @__PURE__ */ __commonJSMin(((exports) => {
- exports.__esModule = true;
- exports.universal = exports.tag = exports.string = exports.selector = exports.root = exports.pseudo = exports.nesting = exports.id = exports.comment = exports.combinator = exports.className = exports.attribute = void 0;
- var _attribute = _interopRequireDefault$3(require_attribute());
- var _className = _interopRequireDefault$3(require_className());
- var _combinator = _interopRequireDefault$3(require_combinator());
- var _comment = _interopRequireDefault$3(require_comment());
- var _id = _interopRequireDefault$3(require_id());
- var _nesting = _interopRequireDefault$3(require_nesting());
- var _pseudo = _interopRequireDefault$3(require_pseudo());
- var _root = _interopRequireDefault$3(require_root());
- var _selector = _interopRequireDefault$3(require_selector());
- var _string = _interopRequireDefault$3(require_string());
- var _tag = _interopRequireDefault$3(require_tag());
- var _universal = _interopRequireDefault$3(require_universal());
- function _interopRequireDefault$3(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- var attribute = function attribute$1(opts) {
- return new _attribute["default"](opts);
- };
- exports.attribute = attribute;
- var className = function className$1(opts) {
- return new _className["default"](opts);
- };
- exports.className = className;
- var combinator = function combinator$2(opts) {
- return new _combinator["default"](opts);
- };
- exports.combinator = combinator;
- var comment = function comment$2(opts) {
- return new _comment["default"](opts);
- };
- exports.comment = comment;
- var id = function id$1(opts) {
- return new _id["default"](opts);
- };
- exports.id = id;
- var nesting = function nesting$1(opts) {
- return new _nesting["default"](opts);
- };
- exports.nesting = nesting;
- var pseudo = function pseudo$1(opts) {
- return new _pseudo["default"](opts);
- };
- exports.pseudo = pseudo;
- var root = function root$2(opts) {
- return new _root["default"](opts);
- };
- exports.root = root;
- var selector = function selector$1(opts) {
- return new _selector["default"](opts);
- };
- exports.selector = selector;
- var string = function string$1(opts) {
- return new _string["default"](opts);
- };
- exports.string = string;
- var tag = function tag$1(opts) {
- return new _tag["default"](opts);
- };
- exports.tag = tag;
- var universal = function universal$1(opts) {
- return new _universal["default"](opts);
- };
- exports.universal = universal;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/guards.js
-var require_guards = /* @__PURE__ */ __commonJSMin(((exports) => {
- exports.__esModule = true;
- exports.isComment = exports.isCombinator = exports.isClassName = exports.isAttribute = void 0;
- exports.isContainer = isContainer;
- exports.isIdentifier = void 0;
- exports.isNamespace = isNamespace;
- exports.isNesting = void 0;
- exports.isNode = isNode;
- exports.isPseudo = void 0;
- exports.isPseudoClass = isPseudoClass;
- exports.isPseudoElement = isPseudoElement;
- exports.isUniversal = exports.isTag = exports.isString = exports.isSelector = exports.isRoot = void 0;
- var _types$1 = require_types();
- var _IS_TYPE;
- var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types$1.ATTRIBUTE] = true, _IS_TYPE[_types$1.CLASS] = true, _IS_TYPE[_types$1.COMBINATOR] = true, _IS_TYPE[_types$1.COMMENT] = true, _IS_TYPE[_types$1.ID] = true, _IS_TYPE[_types$1.NESTING] = true, _IS_TYPE[_types$1.PSEUDO] = true, _IS_TYPE[_types$1.ROOT] = true, _IS_TYPE[_types$1.SELECTOR] = true, _IS_TYPE[_types$1.STRING] = true, _IS_TYPE[_types$1.TAG] = true, _IS_TYPE[_types$1.UNIVERSAL] = true, _IS_TYPE);
- function isNode(node) {
- return typeof node === "object" && IS_TYPE[node.type];
- }
- function isNodeType(type, node) {
- return isNode(node) && node.type === type;
- }
- var isAttribute = isNodeType.bind(null, _types$1.ATTRIBUTE);
- exports.isAttribute = isAttribute;
- var isClassName = isNodeType.bind(null, _types$1.CLASS);
- exports.isClassName = isClassName;
- var isCombinator = isNodeType.bind(null, _types$1.COMBINATOR);
- exports.isCombinator = isCombinator;
- var isComment = isNodeType.bind(null, _types$1.COMMENT);
- exports.isComment = isComment;
- var isIdentifier = isNodeType.bind(null, _types$1.ID);
- exports.isIdentifier = isIdentifier;
- var isNesting = isNodeType.bind(null, _types$1.NESTING);
- exports.isNesting = isNesting;
- var isPseudo = isNodeType.bind(null, _types$1.PSEUDO);
- exports.isPseudo = isPseudo;
- var isRoot = isNodeType.bind(null, _types$1.ROOT);
- exports.isRoot = isRoot;
- var isSelector = isNodeType.bind(null, _types$1.SELECTOR);
- exports.isSelector = isSelector;
- var isString = isNodeType.bind(null, _types$1.STRING);
- exports.isString = isString;
- var isTag = isNodeType.bind(null, _types$1.TAG);
- exports.isTag = isTag;
- var isUniversal = isNodeType.bind(null, _types$1.UNIVERSAL);
- exports.isUniversal = isUniversal;
- function isPseudoElement(node) {
- return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after" || node.value.toLowerCase() === ":first-letter" || node.value.toLowerCase() === ":first-line");
- }
- function isPseudoClass(node) {
- return isPseudo(node) && !isPseudoElement(node);
- }
- function isContainer(node) {
- return !!(isNode(node) && node.walk);
- }
- function isNamespace(node) {
- return isAttribute(node) || isTag(node);
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/selectors/index.js
-var require_selectors = /* @__PURE__ */ __commonJSMin(((exports) => {
- exports.__esModule = true;
- var _types = require_types();
- Object.keys(_types).forEach(function(key) {
- if (key === "default" || key === "__esModule") return;
- if (key in exports && exports[key] === _types[key]) return;
- exports[key] = _types[key];
- });
- var _constructors = require_constructors();
- Object.keys(_constructors).forEach(function(key) {
- if (key === "default" || key === "__esModule") return;
- if (key in exports && exports[key] === _constructors[key]) return;
- exports[key] = _constructors[key];
- });
- var _guards = require_guards();
- Object.keys(_guards).forEach(function(key) {
- if (key === "default" || key === "__esModule") return;
- if (key in exports && exports[key] === _guards[key]) return;
- exports[key] = _guards[key];
- });
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-selector-parser@7.1.0/node_modules/postcss-selector-parser/dist/index.js
-var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- exports.__esModule = true;
- exports["default"] = void 0;
- var _processor = _interopRequireDefault$2(require_processor());
- var selectors = _interopRequireWildcard(require_selectors());
- function _getRequireWildcardCache(nodeInterop) {
- if (typeof WeakMap !== "function") return null;
- var cacheBabelInterop = /* @__PURE__ */ new WeakMap();
- var cacheNodeInterop = /* @__PURE__ */ new WeakMap();
- return (_getRequireWildcardCache = function _getRequireWildcardCache$4(nodeInterop$1) {
- return nodeInterop$1 ? cacheNodeInterop : cacheBabelInterop;
- })(nodeInterop);
- }
- function _interopRequireWildcard(obj, nodeInterop) {
- if (!nodeInterop && obj && obj.__esModule) return obj;
- if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { "default": obj };
- var cache = _getRequireWildcardCache(nodeInterop);
- if (cache && cache.has(obj)) return cache.get(obj);
- var newObj = {};
- var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
- for (var key in obj) if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
- var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
- if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc);
- else newObj[key] = obj[key];
- }
- newObj["default"] = obj;
- if (cache) cache.set(obj, newObj);
- return newObj;
- }
- function _interopRequireDefault$2(obj) {
- return obj && obj.__esModule ? obj : { "default": obj };
- }
- var parser = function parser$1(processor) {
- return new _processor["default"](processor);
- };
- Object.assign(parser, selectors);
- var _default = parser;
- exports["default"] = _default;
- module.exports = exports.default;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-modules-local-by-default@4.2.0_postcss@8.5.6/node_modules/postcss-modules-local-by-default/src/index.js
-var require_src$2 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const selectorParser$1 = require_dist();
- const valueParser = require_lib();
- const { extractICSS } = require_src$4();
- const IGNORE_FILE_MARKER = "cssmodules-pure-no-check";
- const IGNORE_NEXT_LINE_MARKER = "cssmodules-pure-ignore";
- const isSpacing = (node) => node.type === "combinator" && node.value === " ";
- const isPureCheckDisabled = (root$2) => {
- for (const node of root$2.nodes) {
- if (node.type !== "comment") return false;
- if (node.text.trim().startsWith(IGNORE_FILE_MARKER)) return true;
- }
- return false;
- };
- function getIgnoreComment(node) {
- if (!node.parent) return;
- const indexInParent = node.parent.index(node);
- for (let i$1 = indexInParent - 1; i$1 >= 0; i$1--) {
- const prevNode = node.parent.nodes[i$1];
- if (prevNode.type === "comment") {
- if (prevNode.text.trimStart().startsWith(IGNORE_NEXT_LINE_MARKER)) return prevNode;
- } else break;
- }
- }
- function normalizeNodeArray(nodes) {
- const array = [];
- nodes.forEach((x) => {
- if (Array.isArray(x)) normalizeNodeArray(x).forEach((item) => {
- array.push(item);
- });
- else if (x) array.push(x);
- });
- if (array.length > 0 && isSpacing(array[array.length - 1])) array.pop();
- return array;
- }
- const isPureSelectorSymbol = Symbol("is-pure-selector");
- function localizeNode(rule, mode, localAliasMap) {
- const transform = (node, context) => {
- if (context.ignoreNextSpacing && !isSpacing(node)) throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
- if (context.enforceNoSpacing && isSpacing(node)) throw new Error("Missing whitespace before " + context.enforceNoSpacing);
- let newNodes;
- switch (node.type) {
- case "root": {
- let resultingGlobal;
- context.hasPureGlobals = false;
- newNodes = node.nodes.map((n) => {
- const nContext = {
- global: context.global,
- lastWasSpacing: true,
- hasLocals: false,
- explicit: false
- };
- n = transform(n, nContext);
- if (typeof resultingGlobal === "undefined") resultingGlobal = nContext.global;
- else if (resultingGlobal !== nContext.global) throw new Error("Inconsistent rule global/local result in rule \"" + node + "\" (multiple selectors must result in the same mode for the rule)");
- if (!nContext.hasLocals) context.hasPureGlobals = true;
- return n;
- });
- context.global = resultingGlobal;
- node.nodes = normalizeNodeArray(newNodes);
- break;
- }
- case "selector":
- newNodes = node.map((childNode) => transform(childNode, context));
- node = node.clone();
- node.nodes = normalizeNodeArray(newNodes);
- break;
- case "combinator":
- if (isSpacing(node)) {
- if (context.ignoreNextSpacing) {
- context.ignoreNextSpacing = false;
- context.lastWasSpacing = false;
- context.enforceNoSpacing = false;
- return null;
- }
- context.lastWasSpacing = true;
- return node;
- }
- break;
- case "pseudo": {
- let childContext;
- const isNested = !!node.length;
- const isScoped = node.value === ":local" || node.value === ":global";
- if (node.value === ":import" || node.value === ":export") context.hasLocals = true;
- else if (isNested) {
- if (isScoped) {
- if (node.nodes.length === 0) throw new Error(`${node.value}() can't be empty`);
- if (context.inside) throw new Error(`A ${node.value} is not allowed inside of a ${context.inside}(...)`);
- childContext = {
- global: node.value === ":global",
- inside: node.value,
- hasLocals: false,
- explicit: true
- };
- newNodes = node.map((childNode) => transform(childNode, childContext)).reduce((acc, next) => acc.concat(next.nodes), []);
- if (newNodes.length) {
- const { before, after } = node.spaces;
- const first = newNodes[0];
- const last = newNodes[newNodes.length - 1];
- first.spaces = {
- before,
- after: first.spaces.after
- };
- last.spaces = {
- before: last.spaces.before,
- after
- };
- }
- node = newNodes;
- break;
- } else {
- childContext = {
- global: context.global,
- inside: context.inside,
- lastWasSpacing: true,
- hasLocals: false,
- explicit: context.explicit
- };
- newNodes = node.map((childNode) => {
- const newContext = {
- ...childContext,
- enforceNoSpacing: false
- };
- const result = transform(childNode, newContext);
- childContext.global = newContext.global;
- childContext.hasLocals = newContext.hasLocals;
- return result;
- });
- node = node.clone();
- node.nodes = normalizeNodeArray(newNodes);
- if (childContext.hasLocals) context.hasLocals = true;
- }
- break;
- } else if (isScoped) {
- if (context.inside) throw new Error(`A ${node.value} is not allowed inside of a ${context.inside}(...)`);
- const addBackSpacing = !!node.spaces.before;
- context.ignoreNextSpacing = context.lastWasSpacing ? node.value : false;
- context.enforceNoSpacing = context.lastWasSpacing ? false : node.value;
- context.global = node.value === ":global";
- context.explicit = true;
- return addBackSpacing ? selectorParser$1.combinator({ value: " " }) : null;
- }
- break;
- }
- case "id":
- case "class": {
- if (!node.value) throw new Error("Invalid class or id selector syntax");
- if (context.global) break;
- const isImportedValue = localAliasMap.has(node.value);
- if (!isImportedValue || isImportedValue && context.explicit) {
- const innerNode = node.clone();
- innerNode.spaces = {
- before: "",
- after: ""
- };
- node = selectorParser$1.pseudo({
- value: ":local",
- nodes: [innerNode],
- spaces: node.spaces
- });
- context.hasLocals = true;
- }
- break;
- }
- case "nesting": if (node.value === "&") context.hasLocals = rule.parent[isPureSelectorSymbol];
- }
- context.lastWasSpacing = false;
- context.ignoreNextSpacing = false;
- context.enforceNoSpacing = false;
- return node;
- };
- const rootContext = {
- global: mode === "global",
- hasPureGlobals: false
- };
- rootContext.selector = selectorParser$1((root$2) => {
- transform(root$2, rootContext);
- }).processSync(rule, {
- updateSelector: false,
- lossless: true
- });
- return rootContext;
- }
- function localizeDeclNode(node, context) {
- switch (node.type) {
- case "word":
- if (context.localizeNextItem) {
- if (!context.localAliasMap.has(node.value)) {
- node.value = ":local(" + node.value + ")";
- context.localizeNextItem = false;
- }
- }
- break;
- case "function":
- if (context.options && context.options.rewriteUrl && node.value.toLowerCase() === "url") node.nodes.map((nestedNode) => {
- if (nestedNode.type !== "string" && nestedNode.type !== "word") return;
- let newUrl = context.options.rewriteUrl(context.global, nestedNode.value);
- switch (nestedNode.type) {
- case "string":
- if (nestedNode.quote === "'") newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
- if (nestedNode.quote === "\"") newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, "\\\"");
- break;
- case "word":
- newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
- break;
- }
- nestedNode.value = newUrl;
- });
- break;
- }
- return node;
- }
- const specialKeywords = [
- "none",
- "inherit",
- "initial",
- "revert",
- "revert-layer",
- "unset"
- ];
- function localizeDeclarationValues(localize, declaration, context) {
- const valueNodes = valueParser(declaration.value);
- valueNodes.walk((node, index, nodes) => {
- if (node.type === "function" && (node.value.toLowerCase() === "var" || node.value.toLowerCase() === "env")) return false;
- if (node.type === "word" && specialKeywords.includes(node.value.toLowerCase())) return;
- nodes[index] = localizeDeclNode(node, {
- options: context.options,
- global: context.global,
- localizeNextItem: localize && !context.global,
- localAliasMap: context.localAliasMap
- });
- });
- declaration.value = valueNodes.toString();
- }
- const validIdent = /^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
- const animationKeywords = {
- $normal: 1,
- $reverse: 1,
- $alternate: 1,
- "$alternate-reverse": 1,
- $forwards: 1,
- $backwards: 1,
- $both: 1,
- $infinite: 1,
- $paused: 1,
- $running: 1,
- $ease: 1,
- "$ease-in": 1,
- "$ease-out": 1,
- "$ease-in-out": 1,
- $linear: 1,
- "$step-end": 1,
- "$step-start": 1,
- $none: Infinity,
- $initial: Infinity,
- $inherit: Infinity,
- $unset: Infinity,
- $revert: Infinity,
- "$revert-layer": Infinity
- };
- function localizeDeclaration(declaration, context) {
- if (/animation(-name)?$/i.test(declaration.prop)) {
- let parsedAnimationKeywords = {};
- declaration.value = valueParser(declaration.value).walk((node) => {
- if (node.type === "div") {
- parsedAnimationKeywords = {};
- return;
- } else if (node.type === "function" && node.value.toLowerCase() === "local" && node.nodes.length === 1) {
- node.type = "word";
- node.value = node.nodes[0].value;
- return localizeDeclNode(node, {
- options: context.options,
- global: context.global,
- localizeNextItem: true,
- localAliasMap: context.localAliasMap
- });
- } else if (node.type === "function") {
- if (node.value.toLowerCase() === "global" && node.nodes.length === 1) {
- node.type = "word";
- node.value = node.nodes[0].value;
- }
- return false;
- } else if (node.type !== "word") return;
- const value = node.type === "word" ? node.value.toLowerCase() : null;
- let shouldParseAnimationName = false;
- if (value && validIdent.test(value)) if ("$" + value in animationKeywords) {
- parsedAnimationKeywords["$" + value] = "$" + value in parsedAnimationKeywords ? parsedAnimationKeywords["$" + value] + 1 : 0;
- shouldParseAnimationName = parsedAnimationKeywords["$" + value] >= animationKeywords["$" + value];
- } else shouldParseAnimationName = true;
- return localizeDeclNode(node, {
- options: context.options,
- global: context.global,
- localizeNextItem: shouldParseAnimationName && !context.global,
- localAliasMap: context.localAliasMap
- });
- }).toString();
- return;
- }
- if (/url\(/i.test(declaration.value)) return localizeDeclarationValues(false, declaration, context);
- }
- const isPureSelector = (context, rule) => {
- if (!rule.parent || rule.type === "root") return !context.hasPureGlobals;
- if (rule.type === "rule" && rule[isPureSelectorSymbol]) return rule[isPureSelectorSymbol] || isPureSelector(context, rule.parent);
- return !context.hasPureGlobals || isPureSelector(context, rule.parent);
- };
- const isNodeWithoutDeclarations = (rule) => {
- if (rule.nodes.length > 0) return !rule.nodes.every((item) => item.type === "rule" || item.type === "atrule" && !isNodeWithoutDeclarations(item));
- return true;
- };
- module.exports = (options = {}) => {
- if (options && options.mode && options.mode !== "global" && options.mode !== "local" && options.mode !== "pure") throw new Error("options.mode must be either \"global\", \"local\" or \"pure\" (default \"local\")");
- const pureMode = options && options.mode === "pure";
- const globalMode = options && options.mode === "global";
- return {
- postcssPlugin: "postcss-modules-local-by-default",
- prepare() {
- const localAliasMap = /* @__PURE__ */ new Map();
- return { Once(root$2) {
- const { icssImports } = extractICSS(root$2, false);
- const enforcePureMode = pureMode && !isPureCheckDisabled(root$2);
- Object.keys(icssImports).forEach((key) => {
- Object.keys(icssImports[key]).forEach((prop) => {
- localAliasMap.set(prop, icssImports[key][prop]);
- });
- });
- root$2.walkAtRules((atRule) => {
- if (/keyframes$/i.test(atRule.name)) {
- const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(atRule.params);
- const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(atRule.params);
- let globalKeyframes = globalMode;
- if (globalMatch) {
- if (enforcePureMode) {
- const ignoreComment = getIgnoreComment(atRule);
- if (!ignoreComment) throw atRule.error("@keyframes :global(...) is not allowed in pure mode");
- else ignoreComment.remove();
- }
- atRule.params = globalMatch[1];
- globalKeyframes = true;
- } else if (localMatch) {
- atRule.params = localMatch[0];
- globalKeyframes = false;
- } else if (atRule.params && !globalMode && !localAliasMap.has(atRule.params)) atRule.params = ":local(" + atRule.params + ")";
- atRule.walkDecls((declaration) => {
- localizeDeclaration(declaration, {
- localAliasMap,
- options,
- global: globalKeyframes
- });
- });
- } else if (/scope$/i.test(atRule.name)) {
- if (atRule.params) {
- const ignoreComment = pureMode ? getIgnoreComment(atRule) : void 0;
- if (ignoreComment) ignoreComment.remove();
- atRule.params = atRule.params.split("to").map((item) => {
- const selector$1 = item.trim().slice(1, -1).trim();
- const context = localizeNode(selector$1, options.mode, localAliasMap);
- context.options = options;
- context.localAliasMap = localAliasMap;
- if (enforcePureMode && context.hasPureGlobals && !ignoreComment) throw atRule.error("Selector in at-rule\"" + selector$1 + "\" is not pure (pure selectors must contain at least one local class or id)");
- return `(${context.selector})`;
- }).join(" to ");
- }
- atRule.nodes.forEach((declaration) => {
- if (declaration.type === "decl") localizeDeclaration(declaration, {
- localAliasMap,
- options,
- global: globalMode
- });
- });
- } else if (atRule.nodes) atRule.nodes.forEach((declaration) => {
- if (declaration.type === "decl") localizeDeclaration(declaration, {
- localAliasMap,
- options,
- global: globalMode
- });
- });
- });
- root$2.walkRules((rule) => {
- if (rule.parent && rule.parent.type === "atrule" && /keyframes$/i.test(rule.parent.name)) return;
- const context = localizeNode(rule, options.mode, localAliasMap);
- context.options = options;
- context.localAliasMap = localAliasMap;
- const ignoreComment = enforcePureMode ? getIgnoreComment(rule) : void 0;
- const isNotPure = enforcePureMode && !isPureSelector(context, rule);
- if (isNotPure && isNodeWithoutDeclarations(rule) && !ignoreComment) throw rule.error("Selector \"" + rule.selector + "\" is not pure (pure selectors must contain at least one local class or id)");
- else if (ignoreComment) ignoreComment.remove();
- if (pureMode) rule[isPureSelectorSymbol] = !isNotPure;
- rule.selector = context.selector;
- if (rule.nodes) rule.nodes.forEach((declaration) => localizeDeclaration(declaration, context));
- });
- } };
- }
- };
- };
- module.exports.postcss = true;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-modules-scope@3.2.1_postcss@8.5.6/node_modules/postcss-modules-scope/src/index.js
-var require_src$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const selectorParser = require_dist();
- const hasOwnProperty = Object.prototype.hasOwnProperty;
- function isNestedRule(rule) {
- if (!rule.parent || rule.parent.type === "root") return false;
- if (rule.parent.type === "rule") return true;
- return isNestedRule(rule.parent);
- }
- function getSingleLocalNamesForComposes(root$2, rule) {
- if (isNestedRule(rule)) throw new Error(`composition is not allowed in nested rule \n\n${rule}`);
- return root$2.nodes.map((node) => {
- if (node.type !== "selector" || node.nodes.length !== 1) throw new Error(`composition is only allowed when selector is single :local class name not in "${root$2}"`);
- node = node.nodes[0];
- if (node.type !== "pseudo" || node.value !== ":local" || node.nodes.length !== 1) throw new Error("composition is only allowed when selector is single :local class name not in \"" + root$2 + "\", \"" + node + "\" is weird");
- node = node.first;
- if (node.type !== "selector" || node.length !== 1) throw new Error("composition is only allowed when selector is single :local class name not in \"" + root$2 + "\", \"" + node + "\" is weird");
- node = node.first;
- if (node.type !== "class") throw new Error("composition is only allowed when selector is single :local class name not in \"" + root$2 + "\", \"" + node + "\" is weird");
- return node.value;
- });
- }
- const unescapeRegExp = new RegExp("\\\\([\\da-f]{1,6}[\\x20\\t\\r\\n\\f]?|([\\x20\\t\\r\\n\\f])|.)", "ig");
- function unescape(str$1) {
- return str$1.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
- const high = "0x" + escaped - 65536;
- return high !== high || escapedWhitespace ? escaped : high < 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high >> 10 | 55296, high & 1023 | 56320);
- });
- }
- const plugin = (options = {}) => {
- const generateScopedName = options && options.generateScopedName || plugin.generateScopedName;
- const generateExportEntry = options && options.generateExportEntry || plugin.generateExportEntry;
- const exportGlobals = options && options.exportGlobals;
- return {
- postcssPlugin: "postcss-modules-scope",
- Once(root$2, { rule }) {
- const exports$1 = Object.create(null);
- function exportScopedName(name, rawName, node) {
- const scopedName = generateScopedName(rawName ? rawName : name, root$2.source.input.from, root$2.source.input.css, node);
- const { key, value } = generateExportEntry(rawName ? rawName : name, scopedName, root$2.source.input.from, root$2.source.input.css, node);
- exports$1[key] = exports$1[key] || [];
- if (exports$1[key].indexOf(value) < 0) exports$1[key].push(value);
- return scopedName;
- }
- function localizeNode$1(node) {
- switch (node.type) {
- case "selector":
- node.nodes = node.map((item) => localizeNode$1(item));
- return node;
- case "class": return selectorParser.className({ value: exportScopedName(node.value, node.raws && node.raws.value ? node.raws.value : null, node) });
- case "id": return selectorParser.id({ value: exportScopedName(node.value, node.raws && node.raws.value ? node.raws.value : null, node) });
- case "attribute": if (node.attribute === "class" && node.operator === "=") return selectorParser.attribute({
- attribute: node.attribute,
- operator: node.operator,
- quoteMark: "'",
- value: exportScopedName(node.value, null, null)
- });
- }
- throw new Error(`${node.type} ("${node}") is not allowed in a :local block`);
- }
- function traverseNode(node) {
- switch (node.type) {
- case "pseudo": if (node.value === ":local") {
- if (node.nodes.length !== 1) throw new Error("Unexpected comma (\",\") in :local block");
- const selector$1 = localizeNode$1(node.first);
- selector$1.first.spaces = node.spaces;
- const nextNode = node.next();
- if (nextNode && nextNode.type === "combinator" && nextNode.value === " " && /\\[A-F0-9]{1,6}$/.test(selector$1.last.value)) selector$1.last.spaces.after = " ";
- node.replaceWith(selector$1);
- return;
- }
- case "root":
- case "selector":
- node.each((item) => traverseNode(item));
- break;
- case "id":
- case "class":
- if (exportGlobals) exports$1[node.value] = [node.value];
- break;
- }
- return node;
- }
- const importedNames = {};
- root$2.walkRules(/^:import\(.+\)$/, (rule$1) => {
- rule$1.walkDecls((decl) => {
- importedNames[decl.prop] = true;
- });
- });
- root$2.walkRules((rule$1) => {
- let parsedSelector = selectorParser().astSync(rule$1);
- rule$1.selector = traverseNode(parsedSelector.clone()).toString();
- rule$1.walkDecls(/^(composes|compose-with)$/i, (decl) => {
- const localNames = getSingleLocalNamesForComposes(parsedSelector, decl.parent);
- decl.value.split(",").forEach((value) => {
- value.trim().split(/\s+/).forEach((className$1) => {
- const global$1 = /^global\(([^)]+)\)$/.exec(className$1);
- if (global$1) localNames.forEach((exportedName) => {
- exports$1[exportedName].push(global$1[1]);
- });
- else if (hasOwnProperty.call(importedNames, className$1)) localNames.forEach((exportedName) => {
- exports$1[exportedName].push(className$1);
- });
- else if (hasOwnProperty.call(exports$1, className$1)) localNames.forEach((exportedName) => {
- exports$1[className$1].forEach((item) => {
- exports$1[exportedName].push(item);
- });
- });
- else throw decl.error(`referenced class name "${className$1}" in ${decl.prop} not found`);
- });
- });
- decl.remove();
- });
- rule$1.walkDecls((decl) => {
- if (!/:local\s*\((.+?)\)/.test(decl.value)) return;
- let tokens$1 = decl.value.split(/(,|'[^']*'|"[^"]*")/);
- tokens$1 = tokens$1.map((token, idx) => {
- if (idx === 0 || tokens$1[idx - 1] === ",") {
- let result = token;
- const localMatch = /:local\s*\((.+?)\)/.exec(token);
- if (localMatch) {
- const input = localMatch.input;
- const matchPattern = localMatch[0];
- const matchVal = localMatch[1];
- const newVal = exportScopedName(matchVal);
- result = input.replace(matchPattern, newVal);
- } else return token;
- return result;
- } else return token;
- });
- decl.value = tokens$1.join("");
- });
- });
- root$2.walkAtRules(/keyframes$/i, (atRule) => {
- const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params);
- if (!localMatch) return;
- atRule.params = exportScopedName(localMatch[1]);
- });
- root$2.walkAtRules(/scope$/i, (atRule) => {
- if (atRule.params) atRule.params = atRule.params.split("to").map((item) => {
- const selector$1 = item.trim().slice(1, -1).trim();
- if (!/^\s*:local\s*\((.+?)\)\s*$/.exec(selector$1)) return `(${selector$1})`;
- return `(${traverseNode(selectorParser().astSync(selector$1)).toString()})`;
- }).join(" to ");
- });
- const exportedNames = Object.keys(exports$1);
- if (exportedNames.length > 0) {
- const exportRule = rule({ selector: ":export" });
- exportedNames.forEach((exportedName) => exportRule.append({
- prop: exportedName,
- value: exports$1[exportedName].join(" "),
- raws: { before: "\n " }
- }));
- root$2.append(exportRule);
- }
- }
- };
- };
- plugin.postcss = true;
- plugin.generateScopedName = function(name, path$2) {
- return `_${path$2.replace(/\.[^./\\]+$/, "").replace(/[\W_]+/g, "_").replace(/^_|_$/g, "")}__${name}`.trim();
- };
- plugin.generateExportEntry = function(name, scopedName) {
- return {
- key: unescape(name),
- value: unescape(scopedName)
- };
- };
- module.exports = plugin;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/string-hash@1.1.3/node_modules/string-hash/index.js
-var require_string_hash = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- function hash(str$1) {
- var hash$1 = 5381, i$1 = str$1.length;
- while (i$1) hash$1 = hash$1 * 33 ^ str$1.charCodeAt(--i$1);
- return hash$1 >>> 0;
- }
- module.exports = hash;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-modules-values@4.0.0_postcss@8.5.6/node_modules/postcss-modules-values/src/index.js
-var require_src = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const ICSSUtils = require_src$4();
- const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
- const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/;
- const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
- module.exports = (options) => {
- let importIndex = 0;
- const createImportedName = options && options.createImportedName || ((importName) => `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`);
- return {
- postcssPlugin: "postcss-modules-values",
- prepare(result) {
- const importAliases = [];
- const definitions = {};
- return { Once(root$2, postcss) {
- root$2.walkAtRules(/value/i, (atRule) => {
- const matches = atRule.params.match(matchImports);
- if (matches) {
- let [, aliases, path$2] = matches;
- if (definitions[path$2]) path$2 = definitions[path$2];
- const imports = aliases.replace(/^\(\s*([\s\S]+)\s*\)$/, "$1").split(/\s*,\s*/).map((alias) => {
- const tokens$1 = matchImport.exec(alias);
- if (tokens$1) {
- const [, theirName, myName = theirName] = tokens$1;
- const importedName = createImportedName(myName);
- definitions[myName] = importedName;
- return {
- theirName,
- importedName
- };
- } else throw new Error(`@import statement "${alias}" is invalid!`);
- });
- importAliases.push({
- path: path$2,
- imports
- });
- atRule.remove();
- return;
- }
- if (atRule.params.indexOf("@value") !== -1) result.warn("Invalid value definition: " + atRule.params);
- let [, key, value] = `${atRule.params}${atRule.raws.between}`.match(matchValueDefinition);
- const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, "");
- if (normalizedValue.length === 0) {
- result.warn("Invalid value definition: " + atRule.params);
- atRule.remove();
- return;
- }
- if (!/^\s+$/.test(normalizedValue)) value = value.trim();
- definitions[key] = ICSSUtils.replaceValueSymbols(value, definitions);
- atRule.remove();
- });
- if (!Object.keys(definitions).length) return;
- ICSSUtils.replaceSymbols(root$2, definitions);
- const exportDeclarations = Object.keys(definitions).map((key) => postcss.decl({
- value: definitions[key],
- prop: key,
- raws: { before: "\n " }
- }));
- if (exportDeclarations.length > 0) {
- const exportRule = postcss.rule({
- selector: ":export",
- raws: { after: "\n" }
- });
- exportRule.append(exportDeclarations);
- root$2.prepend(exportRule);
- }
- importAliases.reverse().forEach(({ path: path$2, imports }) => {
- const importRule = postcss.rule({
- selector: `:import(${path$2})`,
- raws: { after: "\n" }
- });
- imports.forEach(({ theirName, importedName }) => {
- importRule.append({
- value: theirName,
- prop: importedName,
- raws: { before: "\n " }
- });
- });
- root$2.prepend(importRule);
- });
- } };
- }
- };
- };
- module.exports.postcss = true;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-modules@6.0.1_postcss@8.5.6/node_modules/postcss-modules/build/scoping.js
-var require_scoping = /* @__PURE__ */ __commonJSMin(((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.behaviours = void 0;
- exports.getDefaultPlugins = getDefaultPlugins;
- exports.getDefaultScopeBehaviour = getDefaultScopeBehaviour;
- exports.getScopedNameGenerator = getScopedNameGenerator;
- var _postcssModulesExtractImports = _interopRequireDefault$1(require_src$3());
- var _genericNames = _interopRequireDefault$1(require_generic_names());
- var _postcssModulesLocalByDefault = _interopRequireDefault$1(require_src$2());
- var _postcssModulesScope = _interopRequireDefault$1(require_src$1());
- var _stringHash = _interopRequireDefault$1(require_string_hash());
- var _postcssModulesValues = _interopRequireDefault$1(require_src());
- function _interopRequireDefault$1(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- const behaviours = {
- LOCAL: "local",
- GLOBAL: "global"
- };
- exports.behaviours = behaviours;
- function getDefaultPlugins({ behaviour, generateScopedName, exportGlobals }) {
- const scope = (0, _postcssModulesScope.default)({
- generateScopedName,
- exportGlobals
- });
- return {
- [behaviours.LOCAL]: [
- _postcssModulesValues.default,
- (0, _postcssModulesLocalByDefault.default)({ mode: "local" }),
- _postcssModulesExtractImports.default,
- scope
- ],
- [behaviours.GLOBAL]: [
- _postcssModulesValues.default,
- (0, _postcssModulesLocalByDefault.default)({ mode: "global" }),
- _postcssModulesExtractImports.default,
- scope
- ]
- }[behaviour];
- }
- function isValidBehaviour(behaviour) {
- return Object.keys(behaviours).map((key) => behaviours[key]).indexOf(behaviour) > -1;
- }
- function getDefaultScopeBehaviour(scopeBehaviour) {
- return scopeBehaviour && isValidBehaviour(scopeBehaviour) ? scopeBehaviour : behaviours.LOCAL;
- }
- function generateScopedNameDefault(name, filename, css) {
- const i$1 = css.indexOf(`.${name}`);
- const lineNumber = css.substr(0, i$1).split(/[\r\n]/).length;
- return `_${name}_${(0, _stringHash.default)(css).toString(36).substr(0, 5)}_${lineNumber}`;
- }
- function getScopedNameGenerator(generateScopedName, hashPrefix) {
- const scopedNameGenerator = generateScopedName || generateScopedNameDefault;
- if (typeof scopedNameGenerator === "function") return scopedNameGenerator;
- return (0, _genericNames.default)(scopedNameGenerator, {
- context: process.cwd(),
- hashPrefix
- });
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-modules@6.0.1_postcss@8.5.6/node_modules/postcss-modules/build/pluginFactory.js
-var require_pluginFactory = /* @__PURE__ */ __commonJSMin(((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.makePlugin = makePlugin;
- var _postcss = _interopRequireDefault(__require("postcss"));
- var _unquote = _interopRequireDefault(require_unquote());
- var _Parser = _interopRequireDefault(require_Parser());
- var _saveJSON = _interopRequireDefault(require_saveJSON());
- var _localsConvention = require_localsConvention();
- var _FileSystemLoader = _interopRequireDefault(require_FileSystemLoader());
- var _scoping = require_scoping();
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : { default: obj };
- }
- const PLUGIN_NAME = "postcss-modules";
- function isGlobalModule(globalModules, inputFile) {
- return globalModules.some((regex) => inputFile.match(regex));
- }
- function getDefaultPluginsList(opts, inputFile) {
- const globalModulesList = opts.globalModulePaths || null;
- const exportGlobals = opts.exportGlobals || false;
- const defaultBehaviour = (0, _scoping.getDefaultScopeBehaviour)(opts.scopeBehaviour);
- const generateScopedName = (0, _scoping.getScopedNameGenerator)(opts.generateScopedName, opts.hashPrefix);
- if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) return (0, _scoping.getDefaultPlugins)({
- behaviour: _scoping.behaviours.GLOBAL,
- generateScopedName,
- exportGlobals
- });
- return (0, _scoping.getDefaultPlugins)({
- behaviour: defaultBehaviour,
- generateScopedName,
- exportGlobals
- });
- }
- function getLoader(opts, plugins) {
- const root$2 = typeof opts.root === "undefined" ? "/" : opts.root;
- return typeof opts.Loader === "function" ? new opts.Loader(root$2, plugins, opts.resolve) : new _FileSystemLoader.default(root$2, plugins, opts.resolve);
- }
- function isOurPlugin(plugin$1) {
- return plugin$1.postcssPlugin === PLUGIN_NAME;
- }
- function makePlugin(opts) {
- return {
- postcssPlugin: PLUGIN_NAME,
- async OnceExit(css, { result }) {
- const getJSON = opts.getJSON || _saveJSON.default;
- const inputFile = css.source.input.file;
- const pluginList = getDefaultPluginsList(opts, inputFile);
- const resultPluginIndex = result.processor.plugins.findIndex((plugin$1) => isOurPlugin(plugin$1));
- if (resultPluginIndex === -1) throw new Error("Plugin missing from options.");
- const loader = getLoader(opts, [...result.processor.plugins.slice(0, resultPluginIndex), ...pluginList]);
- const fetcher = async (file, relativeTo, depTrace) => {
- const unquoteFile = (0, _unquote.default)(file);
- return loader.fetch.call(loader, unquoteFile, relativeTo, depTrace);
- };
- const parser$1 = new _Parser.default(fetcher);
- await (0, _postcss.default)([...pluginList, parser$1.plugin()]).process(css, { from: inputFile });
- const out = loader.finalSource;
- if (out) css.prepend(out);
- if (opts.localsConvention) {
- const reducer = (0, _localsConvention.makeLocalsConventionReducer)(opts.localsConvention, inputFile);
- parser$1.exportTokens = Object.entries(parser$1.exportTokens).reduce(reducer, {});
- }
- result.messages.push({
- type: "export",
- plugin: "postcss-modules",
- exportTokens: parser$1.exportTokens
- });
- return getJSON(css.source.input.file, parser$1.exportTokens, result.opts.to);
- }
- };
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-modules@6.0.1_postcss@8.5.6/node_modules/postcss-modules/build/index.js
-var require_build = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- var _fs = __require("fs");
- var _fs2 = require_fs();
- var _pluginFactory = require_pluginFactory();
- (0, _fs2.setFileSystem)({
- readFile: _fs.readFile,
- writeFile: _fs.writeFile
- });
- module.exports = (opts = {}) => (0, _pluginFactory.makePlugin)(opts);
- module.exports.postcss = true;
-}));
-
-//#endregion
-export default require_build();
-
-export { }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/chunks/chunk.js b/vanilla/node_modules/vite/dist/node/chunks/chunk.js
deleted file mode 100644
index f92a15e..0000000
--- a/vanilla/node_modules/vite/dist/node/chunks/chunk.js
+++ /dev/null
@@ -1,48 +0,0 @@
-import { createRequire } from "node:module";
-
-//#region rolldown:runtime
-var __create = Object.create;
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __getProtoOf = Object.getPrototypeOf;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __esmMin = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
-var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
-var __export = (all, symbols) => {
- let target = {};
- for (var name in all) {
- __defProp(target, name, {
- get: all[name],
- enumerable: true
- });
- }
- if (symbols) {
- __defProp(target, Symbol.toStringTag, { value: "Module" });
- }
- return target;
-};
-var __copyProps = (to, from, except, desc) => {
- if (from && typeof from === "object" || typeof from === "function") {
- for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
- key = keys[i];
- if (!__hasOwnProp.call(to, key) && key !== except) {
- __defProp(to, key, {
- get: ((k) => from[k]).bind(null, key),
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
- });
- }
- }
- }
- return to;
-};
-var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
- value: mod,
- enumerable: true
-}) : target, mod));
-var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
-var __toDynamicImportESM = (isNodeMode) => (mod) => __toESM(mod.default, isNodeMode);
-var __require = /* @__PURE__ */ createRequire(import.meta.url);
-
-//#endregion
-export { __toCommonJS as a, __require as i, __esmMin as n, __toDynamicImportESM as o, __export as r, __toESM as s, __commonJSMin as t }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/chunks/config.js b/vanilla/node_modules/vite/dist/node/chunks/config.js
deleted file mode 100644
index 2b39a20..0000000
--- a/vanilla/node_modules/vite/dist/node/chunks/config.js
+++ /dev/null
@@ -1,35978 +0,0 @@
-import { a as __toCommonJS, i as __require, n as __esmMin, o as __toDynamicImportESM, r as __export, s as __toESM, t as __commonJSMin } from "./chunk.js";
-import { A as OPTIMIZABLE_ENTRY_RE, C as ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR, D as JS_TYPES_RE, E as FS_PREFIX, F as defaultAllowedOrigins, I as loopbackHosts, L as wildcardHosts, M as SPECIAL_QUERY_RE, N as VERSION, O as KNOWN_ASSET_TYPES, P as VITE_PACKAGE_DIR, R as require_picocolors, S as ENV_PUBLIC_PATH, T as ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET, _ as DEFAULT_SERVER_CONDITIONS, a as CLIENT_ENTRY, b as DEV_PROD_CONDITION, c as DEFAULT_ASSETS_INLINE_LIMIT, d as DEFAULT_CLIENT_MAIN_FIELDS, f as DEFAULT_CONFIG_FILES, g as DEFAULT_PREVIEW_PORT, h as DEFAULT_EXTERNAL_CONDITIONS, i as CLIENT_DIR, j as ROLLUP_HOOKS, k as METADATA_FILENAME, l as DEFAULT_ASSETS_RE, m as DEFAULT_EXTENSIONS, n as createLogger, o as CLIENT_PUBLIC_PATH, p as DEFAULT_DEV_PORT, r as printServerUrls, s as CSS_LANGS_RE, t as LogLevels, u as DEFAULT_CLIENT_CONDITIONS, v as DEFAULT_SERVER_MAIN_FIELDS, w as ERR_OPTIMIZE_DEPS_PROCESSING_ERROR, x as ENV_ENTRY, y as DEP_VERSION_RE } from "./logger.js";
-import { builtinModules, createRequire } from "node:module";
-import { parseAst, parseAstAsync } from "rollup/parseAst";
-import * as fs$1 from "node:fs";
-import fs, { existsSync, promises, readFileSync } from "node:fs";
-import path, { basename, dirname, extname, isAbsolute, join, normalize, posix, relative, resolve, sep } from "node:path";
-import fsp, { constants } from "node:fs/promises";
-import { URL as URL$1, fileURLToPath, pathToFileURL } from "node:url";
-import { format, formatWithOptions, inspect, promisify, stripVTControlCharacters } from "node:util";
-import { performance as performance$1 } from "node:perf_hooks";
-import crypto from "node:crypto";
-import picomatch from "picomatch";
-import esbuild, { build, formatMessages, transform } from "esbuild";
-import os from "node:os";
-import net from "node:net";
-import childProcess, { exec, execFile, execSync } from "node:child_process";
-import { promises as promises$1 } from "node:dns";
-import { isatty } from "node:tty";
-import path$1, { basename as basename$1, dirname as dirname$1, extname as extname$1, isAbsolute as isAbsolute$1, join as join$1, posix as posix$1, relative as relative$1, resolve as resolve$1, sep as sep$1, win32 } from "path";
-import { existsSync as existsSync$1, readFileSync as readFileSync$1, readdirSync, statSync } from "fs";
-import { fdir } from "fdir";
-import { gzip } from "node:zlib";
-import readline from "node:readline";
-import { createRequire as createRequire$1 } from "module";
-import { MessageChannel, Worker } from "node:worker_threads";
-import isModuleSyncConditionEnabled from "#module-sync-enabled";
-import assert from "node:assert";
-import process$1 from "node:process";
-import v8 from "node:v8";
-import { escapePath, glob, globSync, isDynamicPattern } from "tinyglobby";
-import { Buffer as Buffer$1 } from "node:buffer";
-import { EventEmitter } from "node:events";
-import { STATUS_CODES, createServer, get } from "node:http";
-import { createServer as createServer$1, get as get$1 } from "node:https";
-import { ESModulesEvaluator, ModuleRunner, createNodeImportMeta } from "vite/module-runner";
-import zlib from "zlib";
-import * as qs from "node:querystring";
-
-//#region src/shared/constants.ts
-/**
-* Prefix for resolved Ids that are not valid browser import specifiers
-*/
-const VALID_ID_PREFIX = `/@id/`;
-/**
-* Plugins that use 'virtual modules' (e.g. for helper functions), prefix the
-* module ID with `\0`, a convention from the rollup ecosystem.
-* This prevents other plugins from trying to process the id (like node resolution),
-* and core features like sourcemaps can use this info to differentiate between
-* virtual modules and regular files.
-* `\0` is not a permitted char in import URLs so we have to replace them during
-* import analysis. The id will be decoded back before entering the plugins pipeline.
-* These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual
-* modules in the browser end up encoded as `/@id/__x00__{id}`
-*/
-const NULL_BYTE_PLACEHOLDER = `__x00__`;
-let SOURCEMAPPING_URL = "sourceMa";
-SOURCEMAPPING_URL += "ppingURL";
-const MODULE_RUNNER_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-generated";
-const ERR_OUTDATED_OPTIMIZED_DEP = "ERR_OUTDATED_OPTIMIZED_DEP";
-
-//#endregion
-//#region src/shared/utils.ts
-const isWindows = typeof process !== "undefined" && process.platform === "win32";
-/**
-* Prepend `/@id/` and replace null byte so the id is URL-safe.
-* This is prepended to resolved ids that are not valid browser
-* import specifiers by the importAnalysis plugin.
-*/
-function wrapId(id) {
- return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
-}
-/**
-* Undo {@link wrapId}'s `/@id/` and null byte replacements.
-*/
-function unwrapId(id) {
- return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id;
-}
-const windowsSlashRE = /\\/g;
-function slash(p) {
- return p.replace(windowsSlashRE, "/");
-}
-const postfixRE = /[?#].*$/;
-function cleanUrl(url$3) {
- return url$3.replace(postfixRE, "");
-}
-function splitFileAndPostfix(path$13) {
- const file = cleanUrl(path$13);
- return {
- file,
- postfix: path$13.slice(file.length)
- };
-}
-function withTrailingSlash(path$13) {
- if (path$13[path$13.length - 1] !== "/") return `${path$13}/`;
- return path$13;
-}
-function promiseWithResolvers() {
- let resolve$4;
- let reject;
- return {
- promise: new Promise((_resolve, _reject) => {
- resolve$4 = _resolve;
- reject = _reject;
- }),
- resolve: resolve$4,
- reject
- };
-}
-
-//#endregion
-//#region src/module-runner/importMetaResolver.ts
-const customizationHookNamespace = "vite-module-runner:import-meta-resolve/v1/";
-const customizationHooksModule = `
-
-export async function resolve(specifier, context, nextResolve) {
- if (specifier.startsWith(${JSON.stringify(customizationHookNamespace)})) {
- const data = specifier.slice(${JSON.stringify(customizationHookNamespace)}.length)
- const [parsedSpecifier, parsedImporter] = JSON.parse(data)
- specifier = parsedSpecifier
- context.parentURL = parsedImporter
- }
- return nextResolve(specifier, context)
-}
-
-`;
-function customizationHookResolve(specifier, context, nextResolve) {
- if (specifier.startsWith(customizationHookNamespace)) {
- const data = specifier.slice(42);
- const [parsedSpecifier, parsedImporter] = JSON.parse(data);
- specifier = parsedSpecifier;
- context.parentURL = parsedImporter;
- }
- return nextResolve(specifier, context);
-}
-async function createImportMetaResolver() {
- let module$1;
- try {
- module$1 = (await import("node:module")).Module;
- } catch {
- return;
- }
- if (!module$1) return;
- if (module$1.registerHooks) {
- module$1.registerHooks({ resolve: customizationHookResolve });
- return importMetaResolveWithCustomHook;
- }
- if (!module$1.register) return;
- try {
- const hookModuleContent = `data:text/javascript,${encodeURI(customizationHooksModule)}`;
- module$1.register(hookModuleContent);
- } catch (e$1) {
- if ("code" in e$1 && e$1.code === "ERR_NETWORK_IMPORT_DISALLOWED") return;
- throw e$1;
- }
- return importMetaResolveWithCustomHook;
-}
-function importMetaResolveWithCustomHook(specifier, importer) {
- return import.meta.resolve(`${customizationHookNamespace}${JSON.stringify([specifier, importer])}`);
-}
-const importMetaResolveWithCustomHookString = `
-
- (() => {
- const resolve = 'resolve'
- return (specifier, importer) =>
- import.meta[resolve](
- \`${customizationHookNamespace}\${JSON.stringify([specifier, importer])}\`,
- )
- })()
-
-`;
-
-//#endregion
-//#region ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
-var comma = ",".charCodeAt(0);
-var semicolon = ";".charCodeAt(0);
-var chars$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-var intToChar = new Uint8Array(64);
-var charToInt = new Uint8Array(128);
-for (let i$1 = 0; i$1 < chars$1.length; i$1++) {
- const c = chars$1.charCodeAt(i$1);
- intToChar[i$1] = c;
- charToInt[c] = i$1;
-}
-function decodeInteger(reader, relative$3) {
- let value$1 = 0;
- let shift = 0;
- let integer = 0;
- do {
- integer = charToInt[reader.next()];
- value$1 |= (integer & 31) << shift;
- shift += 5;
- } while (integer & 32);
- const shouldNegate = value$1 & 1;
- value$1 >>>= 1;
- if (shouldNegate) value$1 = -2147483648 | -value$1;
- return relative$3 + value$1;
-}
-function encodeInteger(builder, num, relative$3) {
- let delta = num - relative$3;
- delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
- do {
- let clamped = delta & 31;
- delta >>>= 5;
- if (delta > 0) clamped |= 32;
- builder.write(intToChar[clamped]);
- } while (delta > 0);
- return num;
-}
-function hasMoreVlq(reader, max) {
- if (reader.pos >= max) return false;
- return reader.peek() !== comma;
-}
-var bufLength = 1024 * 16;
-var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) {
- return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString();
-} } : { decode(buf) {
- let out = "";
- for (let i$1 = 0; i$1 < buf.length; i$1++) out += String.fromCharCode(buf[i$1]);
- return out;
-} };
-var StringWriter = class {
- constructor() {
- this.pos = 0;
- this.out = "";
- this.buffer = new Uint8Array(bufLength);
- }
- write(v) {
- const { buffer } = this;
- buffer[this.pos++] = v;
- if (this.pos === bufLength) {
- this.out += td.decode(buffer);
- this.pos = 0;
- }
- }
- flush() {
- const { buffer, out, pos } = this;
- return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
- }
-};
-var StringReader = class {
- constructor(buffer) {
- this.pos = 0;
- this.buffer = buffer;
- }
- next() {
- return this.buffer.charCodeAt(this.pos++);
- }
- peek() {
- return this.buffer.charCodeAt(this.pos);
- }
- indexOf(char) {
- const { buffer, pos } = this;
- const idx = buffer.indexOf(char, pos);
- return idx === -1 ? buffer.length : idx;
- }
-};
-function decode(mappings) {
- const { length } = mappings;
- const reader = new StringReader(mappings);
- const decoded = [];
- let genColumn = 0;
- let sourcesIndex = 0;
- let sourceLine = 0;
- let sourceColumn = 0;
- let namesIndex = 0;
- do {
- const semi = reader.indexOf(";");
- const line = [];
- let sorted = true;
- let lastCol = 0;
- genColumn = 0;
- while (reader.pos < semi) {
- let seg;
- genColumn = decodeInteger(reader, genColumn);
- if (genColumn < lastCol) sorted = false;
- lastCol = genColumn;
- if (hasMoreVlq(reader, semi)) {
- sourcesIndex = decodeInteger(reader, sourcesIndex);
- sourceLine = decodeInteger(reader, sourceLine);
- sourceColumn = decodeInteger(reader, sourceColumn);
- if (hasMoreVlq(reader, semi)) {
- namesIndex = decodeInteger(reader, namesIndex);
- seg = [
- genColumn,
- sourcesIndex,
- sourceLine,
- sourceColumn,
- namesIndex
- ];
- } else seg = [
- genColumn,
- sourcesIndex,
- sourceLine,
- sourceColumn
- ];
- } else seg = [genColumn];
- line.push(seg);
- reader.pos++;
- }
- if (!sorted) sort(line);
- decoded.push(line);
- reader.pos = semi + 1;
- } while (reader.pos <= length);
- return decoded;
-}
-function sort(line) {
- line.sort(sortComparator$1);
-}
-function sortComparator$1(a, b) {
- return a[0] - b[0];
-}
-function encode$1(decoded) {
- const writer = new StringWriter();
- let sourcesIndex = 0;
- let sourceLine = 0;
- let sourceColumn = 0;
- let namesIndex = 0;
- for (let i$1 = 0; i$1 < decoded.length; i$1++) {
- const line = decoded[i$1];
- if (i$1 > 0) writer.write(semicolon);
- if (line.length === 0) continue;
- let genColumn = 0;
- for (let j = 0; j < line.length; j++) {
- const segment = line[j];
- if (j > 0) writer.write(comma);
- genColumn = encodeInteger(writer, segment[0], genColumn);
- if (segment.length === 1) continue;
- sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
- sourceLine = encodeInteger(writer, segment[2], sourceLine);
- sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
- if (segment.length === 4) continue;
- namesIndex = encodeInteger(writer, segment[4], namesIndex);
- }
- }
- return writer.flush();
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs
-const schemeRegex = /^[\w+.-]+:\/\//;
-/**
-* Matches the parts of a URL:
-* 1. Scheme, including ":", guaranteed.
-* 2. User/password, including "@", optional.
-* 3. Host, guaranteed.
-* 4. Port, including ":", optional.
-* 5. Path, including "/", optional.
-* 6. Query, including "?", optional.
-* 7. Hash, including "#", optional.
-*/
-const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
-/**
-* File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
-* with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
-*
-* 1. Host, optional.
-* 2. Path, which may include "/", guaranteed.
-* 3. Query, including "?", optional.
-* 4. Hash, including "#", optional.
-*/
-const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
-function isAbsoluteUrl(input) {
- return schemeRegex.test(input);
-}
-function isSchemeRelativeUrl(input) {
- return input.startsWith("//");
-}
-function isAbsolutePath(input) {
- return input.startsWith("/");
-}
-function isFileUrl(input) {
- return input.startsWith("file:");
-}
-function isRelative(input) {
- return /^[.?#]/.test(input);
-}
-function parseAbsoluteUrl(input) {
- const match = urlRegex.exec(input);
- return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
-}
-function parseFileUrl(input) {
- const match = fileRegex.exec(input);
- const path$13 = match[2];
- return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path$13) ? path$13 : "/" + path$13, match[3] || "", match[4] || "");
-}
-function makeUrl(scheme, user, host, port, path$13, query, hash$1) {
- return {
- scheme,
- user,
- host,
- port,
- path: path$13,
- query,
- hash: hash$1,
- type: 7
- };
-}
-function parseUrl$3(input) {
- if (isSchemeRelativeUrl(input)) {
- const url$4 = parseAbsoluteUrl("http:" + input);
- url$4.scheme = "";
- url$4.type = 6;
- return url$4;
- }
- if (isAbsolutePath(input)) {
- const url$4 = parseAbsoluteUrl("http://foo.com" + input);
- url$4.scheme = "";
- url$4.host = "";
- url$4.type = 5;
- return url$4;
- }
- if (isFileUrl(input)) return parseFileUrl(input);
- if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);
- const url$3 = parseAbsoluteUrl("http://foo.com/" + input);
- url$3.scheme = "";
- url$3.host = "";
- url$3.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
- return url$3;
-}
-function stripPathFilename(path$13) {
- if (path$13.endsWith("/..")) return path$13;
- const index = path$13.lastIndexOf("/");
- return path$13.slice(0, index + 1);
-}
-function mergePaths(url$3, base) {
- normalizePath$4(base, base.type);
- if (url$3.path === "/") url$3.path = base.path;
- else url$3.path = stripPathFilename(base.path) + url$3.path;
-}
-/**
-* The path can have empty directories "//", unneeded parents "foo/..", or current directory
-* "foo/.". We need to normalize to a standard representation.
-*/
-function normalizePath$4(url$3, type) {
- const rel = type <= 4;
- const pieces = url$3.path.split("/");
- let pointer = 1;
- let positive = 0;
- let addTrailingSlash = false;
- for (let i$1 = 1; i$1 < pieces.length; i$1++) {
- const piece = pieces[i$1];
- if (!piece) {
- addTrailingSlash = true;
- continue;
- }
- addTrailingSlash = false;
- if (piece === ".") continue;
- if (piece === "..") {
- if (positive) {
- addTrailingSlash = true;
- positive--;
- pointer--;
- } else if (rel) pieces[pointer++] = piece;
- continue;
- }
- pieces[pointer++] = piece;
- positive++;
- }
- let path$13 = "";
- for (let i$1 = 1; i$1 < pointer; i$1++) path$13 += "/" + pieces[i$1];
- if (!path$13 || addTrailingSlash && !path$13.endsWith("/..")) path$13 += "/";
- url$3.path = path$13;
-}
-/**
-* Attempts to resolve `input` URL/path relative to `base`.
-*/
-function resolve$3(input, base) {
- if (!input && !base) return "";
- const url$3 = parseUrl$3(input);
- let inputType = url$3.type;
- if (base && inputType !== 7) {
- const baseUrl = parseUrl$3(base);
- const baseType = baseUrl.type;
- switch (inputType) {
- case 1: url$3.hash = baseUrl.hash;
- case 2: url$3.query = baseUrl.query;
- case 3:
- case 4: mergePaths(url$3, baseUrl);
- case 5:
- url$3.user = baseUrl.user;
- url$3.host = baseUrl.host;
- url$3.port = baseUrl.port;
- case 6: url$3.scheme = baseUrl.scheme;
- }
- if (baseType > inputType) inputType = baseType;
- }
- normalizePath$4(url$3, inputType);
- const queryHash = url$3.query + url$3.hash;
- switch (inputType) {
- case 2:
- case 3: return queryHash;
- case 4: {
- const path$13 = url$3.path.slice(1);
- if (!path$13) return queryHash || ".";
- if (isRelative(base || input) && !isRelative(path$13)) return "./" + path$13 + queryHash;
- return path$13 + queryHash;
- }
- case 5: return url$3.path + queryHash;
- default: return url$3.scheme + "//" + url$3.user + url$3.host + url$3.port + url$3.path + queryHash;
- }
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
-function stripFilename(path$13) {
- if (!path$13) return "";
- const index = path$13.lastIndexOf("/");
- return path$13.slice(0, index + 1);
-}
-function resolver(mapUrl, sourceRoot) {
- const from = stripFilename(mapUrl);
- const prefix = sourceRoot ? sourceRoot + "/" : "";
- return (source) => resolve$3(prefix + (source || ""), from);
-}
-var COLUMN$1 = 0;
-var SOURCES_INDEX$1 = 1;
-var SOURCE_LINE$1 = 2;
-var SOURCE_COLUMN$1 = 3;
-var NAMES_INDEX$1 = 4;
-function maybeSort(mappings, owned) {
- const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
- if (unsortedIndex === mappings.length) return mappings;
- if (!owned) mappings = mappings.slice();
- for (let i$1 = unsortedIndex; i$1 < mappings.length; i$1 = nextUnsortedSegmentLine(mappings, i$1 + 1)) mappings[i$1] = sortSegments(mappings[i$1], owned);
- return mappings;
-}
-function nextUnsortedSegmentLine(mappings, start) {
- for (let i$1 = start; i$1 < mappings.length; i$1++) if (!isSorted(mappings[i$1])) return i$1;
- return mappings.length;
-}
-function isSorted(line) {
- for (let j = 1; j < line.length; j++) if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) return false;
- return true;
-}
-function sortSegments(line, owned) {
- if (!owned) line = line.slice();
- return line.sort(sortComparator);
-}
-function sortComparator(a, b) {
- return a[COLUMN$1] - b[COLUMN$1];
-}
-var found = false;
-function binarySearch(haystack, needle, low, high) {
- while (low <= high) {
- const mid = low + (high - low >> 1);
- const cmp = haystack[mid][COLUMN$1] - needle;
- if (cmp === 0) {
- found = true;
- return mid;
- }
- if (cmp < 0) low = mid + 1;
- else high = mid - 1;
- }
- found = false;
- return low - 1;
-}
-function upperBound(haystack, needle, index) {
- for (let i$1 = index + 1; i$1 < haystack.length; index = i$1++) if (haystack[i$1][COLUMN$1] !== needle) break;
- return index;
-}
-function lowerBound(haystack, needle, index) {
- for (let i$1 = index - 1; i$1 >= 0; index = i$1--) if (haystack[i$1][COLUMN$1] !== needle) break;
- return index;
-}
-function memoizedState() {
- return {
- lastKey: -1,
- lastNeedle: -1,
- lastIndex: -1
- };
-}
-function memoizedBinarySearch(haystack, needle, state, key) {
- const { lastKey, lastNeedle, lastIndex } = state;
- let low = 0;
- let high = haystack.length - 1;
- if (key === lastKey) {
- if (needle === lastNeedle) {
- found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle;
- return lastIndex;
- }
- if (needle >= lastNeedle) low = lastIndex === -1 ? 0 : lastIndex;
- else high = lastIndex;
- }
- state.lastKey = key;
- state.lastNeedle = needle;
- return state.lastIndex = binarySearch(haystack, needle, low, high);
-}
-function parse$14(map$1) {
- return typeof map$1 === "string" ? JSON.parse(map$1) : map$1;
-}
-var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
-var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
-var LEAST_UPPER_BOUND = -1;
-var GREATEST_LOWER_BOUND = 1;
-var TraceMap = class {
- constructor(map$1, mapUrl) {
- const isString$1 = typeof map$1 === "string";
- if (!isString$1 && map$1._decodedMemo) return map$1;
- const parsed = parse$14(map$1);
- const { version: version$2, file, names, sourceRoot, sources, sourcesContent } = parsed;
- this.version = version$2;
- this.file = file;
- this.names = names || [];
- this.sourceRoot = sourceRoot;
- this.sources = sources;
- this.sourcesContent = sourcesContent;
- this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
- const resolve$4 = resolver(mapUrl, sourceRoot);
- this.resolvedSources = sources.map(resolve$4);
- const { mappings } = parsed;
- if (typeof mappings === "string") {
- this._encoded = mappings;
- this._decoded = void 0;
- } else if (Array.isArray(mappings)) {
- this._encoded = void 0;
- this._decoded = maybeSort(mappings, isString$1);
- } else if (parsed.sections) throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);
- else throw new Error(`invalid source map: ${JSON.stringify(parsed)}`);
- this._decodedMemo = memoizedState();
- this._bySources = void 0;
- this._bySourceMemos = void 0;
- }
-};
-function cast$1(map$1) {
- return map$1;
-}
-function encodedMappings(map$1) {
- var _a, _b;
- return (_b = (_a = cast$1(map$1))._encoded) != null ? _b : _a._encoded = encode$1(cast$1(map$1)._decoded);
-}
-function decodedMappings(map$1) {
- var _a;
- return (_a = cast$1(map$1))._decoded || (_a._decoded = decode(cast$1(map$1)._encoded));
-}
-function traceSegment(map$1, line, column) {
- const decoded = decodedMappings(map$1);
- if (line >= decoded.length) return null;
- const segments = decoded[line];
- const index = traceSegmentInternal(segments, cast$1(map$1)._decodedMemo, line, column, GREATEST_LOWER_BOUND);
- return index === -1 ? null : segments[index];
-}
-function originalPositionFor(map$1, needle) {
- let { line, column, bias } = needle;
- line--;
- if (line < 0) throw new Error(LINE_GTR_ZERO);
- if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
- const decoded = decodedMappings(map$1);
- if (line >= decoded.length) return OMapping(null, null, null, null);
- const segments = decoded[line];
- const index = traceSegmentInternal(segments, cast$1(map$1)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
- if (index === -1) return OMapping(null, null, null, null);
- const segment = segments[index];
- if (segment.length === 1) return OMapping(null, null, null, null);
- const { names, resolvedSources } = map$1;
- return OMapping(resolvedSources[segment[SOURCES_INDEX$1]], segment[SOURCE_LINE$1] + 1, segment[SOURCE_COLUMN$1], segment.length === 5 ? names[segment[NAMES_INDEX$1]] : null);
-}
-function decodedMap(map$1) {
- return clone(map$1, decodedMappings(map$1));
-}
-function encodedMap(map$1) {
- return clone(map$1, encodedMappings(map$1));
-}
-function clone(map$1, mappings) {
- return {
- version: map$1.version,
- file: map$1.file,
- names: map$1.names,
- sourceRoot: map$1.sourceRoot,
- sources: map$1.sources,
- sourcesContent: map$1.sourcesContent,
- mappings,
- ignoreList: map$1.ignoreList || map$1.x_google_ignoreList
- };
-}
-function OMapping(source, line, column, name) {
- return {
- source,
- line,
- column,
- name
- };
-}
-function traceSegmentInternal(segments, memo, line, column, bias) {
- let index = memoizedBinarySearch(segments, column, memo, line);
- if (found) index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
- else if (bias === LEAST_UPPER_BOUND) index++;
- if (index === -1 || index === segments.length) return -1;
- return index;
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/@jridgewell+gen-mapping@0.3.12/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs
-var SetArray = class {
- constructor() {
- this._indexes = { __proto__: null };
- this.array = [];
- }
-};
-function cast(set) {
- return set;
-}
-function get$2(setarr, key) {
- return cast(setarr)._indexes[key];
-}
-function put(setarr, key) {
- const index = get$2(setarr, key);
- if (index !== void 0) return index;
- const { array, _indexes: indexes } = cast(setarr);
- return indexes[key] = array.push(key) - 1;
-}
-function remove(setarr, key) {
- const index = get$2(setarr, key);
- if (index === void 0) return;
- const { array, _indexes: indexes } = cast(setarr);
- for (let i$1 = index + 1; i$1 < array.length; i$1++) {
- const k = array[i$1];
- array[i$1 - 1] = k;
- indexes[k]--;
- }
- indexes[key] = void 0;
- array.pop();
-}
-var COLUMN = 0;
-var SOURCES_INDEX = 1;
-var SOURCE_LINE = 2;
-var SOURCE_COLUMN = 3;
-var NAMES_INDEX = 4;
-var NO_NAME = -1;
-var GenMapping = class {
- constructor({ file, sourceRoot } = {}) {
- this._names = new SetArray();
- this._sources = new SetArray();
- this._sourcesContent = [];
- this._mappings = [];
- this.file = file;
- this.sourceRoot = sourceRoot;
- this._ignoreList = new SetArray();
- }
-};
-function cast2(map$1) {
- return map$1;
-}
-var maybeAddSegment = (map$1, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
- return addSegmentInternal(true, map$1, genLine, genColumn, source, sourceLine, sourceColumn, name, content);
-};
-function setSourceContent(map$1, source, content) {
- const { _sources: sources, _sourcesContent: sourcesContent } = cast2(map$1);
- const index = put(sources, source);
- sourcesContent[index] = content;
-}
-function setIgnore(map$1, source, ignore = true) {
- const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast2(map$1);
- const index = put(sources, source);
- if (index === sourcesContent.length) sourcesContent[index] = null;
- if (ignore) put(ignoreList, index);
- else remove(ignoreList, index);
-}
-function toDecodedMap(map$1) {
- const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList } = cast2(map$1);
- removeEmptyFinalLines(mappings);
- return {
- version: 3,
- file: map$1.file || void 0,
- names: names.array,
- sourceRoot: map$1.sourceRoot || void 0,
- sources: sources.array,
- sourcesContent,
- mappings,
- ignoreList: ignoreList.array
- };
-}
-function toEncodedMap(map$1) {
- const decoded = toDecodedMap(map$1);
- return Object.assign({}, decoded, { mappings: encode$1(decoded.mappings) });
-}
-function addSegmentInternal(skipable, map$1, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
- const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names } = cast2(map$1);
- const line = getIndex(mappings, genLine);
- const index = getColumnIndex(line, genColumn);
- if (!source) {
- if (skipable && skipSourceless(line, index)) return;
- return insert(line, index, [genColumn]);
- }
- assert$2(sourceLine);
- assert$2(sourceColumn);
- const sourcesIndex = put(sources, source);
- const namesIndex = name ? put(names, name) : NO_NAME;
- if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null;
- if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) return;
- return insert(line, index, name ? [
- genColumn,
- sourcesIndex,
- sourceLine,
- sourceColumn,
- namesIndex
- ] : [
- genColumn,
- sourcesIndex,
- sourceLine,
- sourceColumn
- ]);
-}
-function assert$2(_val) {}
-function getIndex(arr, index) {
- for (let i$1 = arr.length; i$1 <= index; i$1++) arr[i$1] = [];
- return arr[index];
-}
-function getColumnIndex(line, genColumn) {
- let index = line.length;
- for (let i$1 = index - 1; i$1 >= 0; index = i$1--) if (genColumn >= line[i$1][COLUMN]) break;
- return index;
-}
-function insert(array, index, value$1) {
- for (let i$1 = array.length; i$1 > index; i$1--) array[i$1] = array[i$1 - 1];
- array[index] = value$1;
-}
-function removeEmptyFinalLines(mappings) {
- const { length } = mappings;
- let len = length;
- for (let i$1 = len - 1; i$1 >= 0; len = i$1, i$1--) if (mappings[i$1].length > 0) break;
- if (len < length) mappings.length = len;
-}
-function skipSourceless(line, index) {
- if (index === 0) return true;
- return line[index - 1].length === 1;
-}
-function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
- if (index === 0) return false;
- const prev = line[index - 1];
- if (prev.length === 1) return false;
- return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME);
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/@jridgewell+remapping@2.3.5/node_modules/@jridgewell/remapping/dist/remapping.mjs
-var SOURCELESS_MAPPING = /* @__PURE__ */ SegmentObject("", -1, -1, "", null, false);
-var EMPTY_SOURCES = [];
-function SegmentObject(source, line, column, name, content, ignore) {
- return {
- source,
- line,
- column,
- name,
- content,
- ignore
- };
-}
-function Source(map$1, sources, source, content, ignore) {
- return {
- map: map$1,
- sources,
- source,
- content,
- ignore
- };
-}
-function MapSource(map$1, sources) {
- return Source(map$1, sources, "", null, false);
-}
-function OriginalSource(source, content, ignore) {
- return Source(null, EMPTY_SOURCES, source, content, ignore);
-}
-function traceMappings(tree) {
- const gen = new GenMapping({ file: tree.map.file });
- const { sources: rootSources, map: map$1 } = tree;
- const rootNames = map$1.names;
- const rootMappings = decodedMappings(map$1);
- for (let i$1 = 0; i$1 < rootMappings.length; i$1++) {
- const segments = rootMappings[i$1];
- for (let j = 0; j < segments.length; j++) {
- const segment = segments[j];
- const genCol = segment[0];
- let traced = SOURCELESS_MAPPING;
- if (segment.length !== 1) {
- const source2 = rootSources[segment[1]];
- traced = originalPositionFor$1(source2, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : "");
- if (traced == null) continue;
- }
- const { column, line, name, content, source, ignore } = traced;
- maybeAddSegment(gen, i$1, genCol, source, line, column, name);
- if (source && content != null) setSourceContent(gen, source, content);
- if (ignore) setIgnore(gen, source, true);
- }
- }
- return gen;
-}
-function originalPositionFor$1(source, line, column, name) {
- if (!source.map) return SegmentObject(source.source, line, column, name, source.content, source.ignore);
- const segment = traceSegment(source.map, line, column);
- if (segment == null) return null;
- if (segment.length === 1) return SOURCELESS_MAPPING;
- return originalPositionFor$1(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
-}
-function asArray(value$1) {
- if (Array.isArray(value$1)) return value$1;
- return [value$1];
-}
-function buildSourceMapTree(input, loader$1) {
- const maps = asArray(input).map((m) => new TraceMap(m, ""));
- const map$1 = maps.pop();
- for (let i$1 = 0; i$1 < maps.length; i$1++) if (maps[i$1].sources.length > 1) throw new Error(`Transformation map ${i$1} must have exactly one source file.
-Did you specify these with the most recent transformation maps first?`);
- let tree = build$2(map$1, loader$1, "", 0);
- for (let i$1 = maps.length - 1; i$1 >= 0; i$1--) tree = MapSource(maps[i$1], [tree]);
- return tree;
-}
-function build$2(map$1, loader$1, importer, importerDepth) {
- const { resolvedSources, sourcesContent, ignoreList } = map$1;
- const depth = importerDepth + 1;
- return MapSource(map$1, resolvedSources.map((sourceFile, i$1) => {
- const ctx = {
- importer,
- depth,
- source: sourceFile || "",
- content: void 0,
- ignore: void 0
- };
- const sourceMap = loader$1(ctx.source, ctx);
- const { source, content, ignore } = ctx;
- if (sourceMap) return build$2(new TraceMap(sourceMap, source), loader$1, source, depth);
- return OriginalSource(source, content !== void 0 ? content : sourcesContent ? sourcesContent[i$1] : null, ignore !== void 0 ? ignore : ignoreList ? ignoreList.includes(i$1) : false);
- }));
-}
-var SourceMap$1 = class {
- constructor(map$1, options$1) {
- const out = options$1.decodedMappings ? toDecodedMap(map$1) : toEncodedMap(map$1);
- this.version = out.version;
- this.file = out.file;
- this.mappings = out.mappings;
- this.names = out.names;
- this.ignoreList = out.ignoreList;
- this.sourceRoot = out.sourceRoot;
- this.sources = out.sources;
- if (!options$1.excludeContent) this.sourcesContent = out.sourcesContent;
- }
- toString() {
- return JSON.stringify(this);
- }
-};
-function remapping(input, loader$1, options$1) {
- const opts = typeof options$1 === "object" ? options$1 : {
- excludeContent: !!options$1,
- decodedMappings: false
- };
- return new SourceMap$1(traceMappings(buildSourceMapTree(input, loader$1)), opts);
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/obug@1.0.2_ms@2.1.3/node_modules/obug/dist/core.js
-function coerce(value$1) {
- if (value$1 instanceof Error) return value$1.stack || value$1.message;
- return value$1;
-}
-function selectColor(colors$36, namespace) {
- let hash$1 = 0;
- for (let i$1 = 0; i$1 < namespace.length; i$1++) {
- hash$1 = (hash$1 << 5) - hash$1 + namespace.charCodeAt(i$1);
- hash$1 |= 0;
- }
- return colors$36[Math.abs(hash$1) % colors$36.length];
-}
-function matchesTemplate(search, template) {
- let searchIndex = 0;
- let templateIndex = 0;
- let starIndex = -1;
- let matchIndex = 0;
- while (searchIndex < search.length) if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) if (template[templateIndex] === "*") {
- starIndex = templateIndex;
- matchIndex = searchIndex;
- templateIndex++;
- } else {
- searchIndex++;
- templateIndex++;
- }
- else if (starIndex !== -1) {
- templateIndex = starIndex + 1;
- matchIndex++;
- searchIndex = matchIndex;
- } else return false;
- while (templateIndex < template.length && template[templateIndex] === "*") templateIndex++;
- return templateIndex === template.length;
-}
-function humanize(value$1) {
- if (value$1 >= 1e3) return `${(value$1 / 1e3).toFixed(1)}s`;
- return `${value$1}ms`;
-}
-function setup(useColors$1, colors$36, log$3, load$2, save$1, formatArgs$1, init$2) {
- const createDebug$1 = (namespace) => {
- let prevTime;
- let enableOverride;
- let namespacesCache;
- let enabledCache;
- const debug$18 = (...args) => {
- if (!debug$18.enabled) return;
- const curr = Date.now();
- debug$18.diff = curr - (prevTime || curr);
- debug$18.prev = prevTime;
- debug$18.curr = curr;
- prevTime = curr;
- args[0] = coerce(args[0]);
- if (typeof args[0] !== "string") args.unshift("%O");
- let index = 0;
- args[0] = args[0].replace(/%([a-z%])/gi, (match, format$3) => {
- if (match === "%%") return "%";
- index++;
- const formatter = createDebug$1.formatters[format$3];
- if (typeof formatter === "function") {
- const value$1 = args[index];
- match = formatter.call(debug$18, value$1);
- args.splice(index, 1);
- index--;
- }
- return match;
- });
- createDebug$1.formatArgs.call(debug$18, args);
- (debug$18.log || createDebug$1.log).apply(debug$18, args);
- };
- function extend(namespace$1, delimiter = ":") {
- const newDebug = createDebug$1(this.namespace + delimiter + namespace$1);
- newDebug.log = this.log;
- return newDebug;
- }
- debug$18.namespace = namespace;
- debug$18.useColors = useColors$1;
- debug$18.color = selectColor(colors$36, namespace);
- debug$18.extend = extend;
- debug$18.log = log$3;
- Object.defineProperty(debug$18, "enabled", {
- enumerable: true,
- configurable: false,
- get: () => {
- if (enableOverride != null) return enableOverride;
- if (namespacesCache !== createDebug$1.namespaces) {
- namespacesCache = createDebug$1.namespaces;
- enabledCache = createDebug$1.enabled(namespace);
- }
- return enabledCache;
- },
- set: (v) => {
- enableOverride = v;
- }
- });
- init$2 && init$2(debug$18);
- return debug$18;
- };
- function enable(namespaces) {
- save$1(namespaces);
- createDebug$1.namespaces = namespaces;
- createDebug$1.names = [];
- createDebug$1.skips = [];
- const split = namespaces.trim().replace(/\s+/g, ",").split(",").filter(Boolean);
- for (const ns of split) if (ns[0] === "-") createDebug$1.skips.push(ns.slice(1));
- else createDebug$1.names.push(ns);
- }
- function disable() {
- const namespaces = [...createDebug$1.names, ...createDebug$1.skips.map((namespace) => `-${namespace}`)].join(",");
- createDebug$1.enable("");
- return namespaces;
- }
- function enabled(name) {
- for (const skip of createDebug$1.skips) if (matchesTemplate(name, skip)) return false;
- for (const ns of createDebug$1.names) if (matchesTemplate(name, ns)) return true;
- return false;
- }
- createDebug$1.namespaces = "";
- createDebug$1.formatters = {};
- createDebug$1.enable = enable;
- createDebug$1.disable = disable;
- createDebug$1.enabled = enabled;
- createDebug$1.names = [];
- createDebug$1.skips = [];
- createDebug$1.selectColor = (ns) => selectColor(colors$36, ns);
- createDebug$1.formatArgs = formatArgs$1;
- createDebug$1.log = log$3;
- createDebug$1.enable(load$2());
- return createDebug$1;
-}
-var init_core = __esmMin((() => {}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/obug@1.0.2_ms@2.1.3/node_modules/obug/dist/node.js
-var node_exports = /* @__PURE__ */ __export({
- createDebug: () => createDebug,
- default: () => node_default,
- formatArgs: () => formatArgs,
- log: () => log$2,
- "module.exports": () => createDebug
-});
-function log$2(...args) {
- process.stderr.write(`${formatWithOptions(inspectOpts, ...args)}\n`);
-}
-function load$1() {
- return process.env.DEBUG || "";
-}
-function save(namespaces) {
- if (namespaces) process.env.DEBUG = namespaces;
- else delete process.env.DEBUG;
-}
-function useColors() {
- return "colors" in inspectOpts ? Boolean(inspectOpts.colors) : isatty(process.stderr.fd);
-}
-function formatArgs(args) {
- const { namespace: name, useColors: useColors$1 } = this;
- if (useColors$1) {
- 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+${humanize$1(this.diff)}\u001B[0m`);
- } else args[0] = `${getDate()}${name} ${args[0]}`;
-}
-function getDate() {
- if (inspectOpts.hideDate) return "";
- return `${(/* @__PURE__ */ new Date()).toISOString()} `;
-}
-function init$1(debug$18) {
- debug$18.inspectOpts = Object.assign({}, inspectOpts);
-}
-var require$1, colors$35, inspectOpts, humanize$1, createDebug, node_default;
-var init_node = __esmMin((() => {
- init_core();
- require$1 = createRequire(import.meta.url);
- colors$35 = process.stderr.getColorDepth && process.stderr.getColorDepth() > 2 ? [
- 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
- ] : [
- 6,
- 2,
- 3,
- 4,
- 5,
- 1
- ];
- inspectOpts = Object.keys(process.env).filter((key) => {
- return /^debug_/i.test(key);
- }).reduce((obj, key) => {
- const prop = key.slice(6).toLowerCase().replace(/_([a-z])/g, (_, k) => k.toUpperCase());
- let value$1 = process.env[key];
- if (value$1 === "null") value$1 = null;
- else if (/^yes|on|true|enabled$/i.test(value$1)) value$1 = true;
- else if (/^no|off|false|disabled$/i.test(value$1)) value$1 = false;
- else value$1 = Number(value$1);
- obj[prop] = value$1;
- return obj;
- }, {});
- ;
- try {
- humanize$1 = require$1("ms");
- } catch (_unused) {
- humanize$1 = humanize;
- }
- createDebug = setup(useColors(), colors$35, log$2, load$1, save, formatArgs, init$1);
- createDebug.inspectOpts = inspectOpts;
- createDebug.formatters.o = function(v) {
- this.inspectOpts.colors = this.useColors;
- return inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
- };
- createDebug.formatters.O = function(v) {
- this.inspectOpts.colors = this.useColors;
- return inspect(v, this.inspectOpts);
- };
- node_default = createDebug;
- createDebug.default = createDebug;
- createDebug.debug = createDebug;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/estree-walker@2.0.2/node_modules/estree-walker/dist/esm/estree-walker.js
-/** @typedef { import('estree').BaseNode} BaseNode */
-/** @typedef {{
-skip: () => void;
-remove: () => void;
-replace: (node: BaseNode) => void;
-}} WalkerContext */
-var WalkerBase$1 = class {
- constructor() {
- /** @type {boolean} */
- this.should_skip = false;
- /** @type {boolean} */
- this.should_remove = false;
- /** @type {BaseNode | null} */
- this.replacement = null;
- /** @type {WalkerContext} */
- this.context = {
- skip: () => this.should_skip = true,
- remove: () => this.should_remove = true,
- replace: (node) => this.replacement = node
- };
- }
- /**
- *
- * @param {any} parent
- * @param {string} prop
- * @param {number} index
- * @param {BaseNode} node
- */
- replace(parent, prop, index, node) {
- if (parent) if (index !== null) parent[prop][index] = node;
- else parent[prop] = node;
- }
- /**
- *
- * @param {any} parent
- * @param {string} prop
- * @param {number} index
- */
- remove(parent, prop, index) {
- if (parent) if (index !== null) parent[prop].splice(index, 1);
- else delete parent[prop];
- }
-};
-/** @typedef { import('estree').BaseNode} BaseNode */
-/** @typedef { import('./walker.js').WalkerContext} WalkerContext */
-/** @typedef {(
-* this: WalkerContext,
-* node: BaseNode,
-* parent: BaseNode,
-* key: string,
-* index: number
-* ) => void} SyncHandler */
-var SyncWalker$1 = class extends WalkerBase$1 {
- /**
- *
- * @param {SyncHandler} enter
- * @param {SyncHandler} leave
- */
- constructor(enter, leave) {
- super();
- /** @type {SyncHandler} */
- this.enter = enter;
- /** @type {SyncHandler} */
- this.leave = leave;
- }
- /**
- *
- * @param {BaseNode} node
- * @param {BaseNode} parent
- * @param {string} [prop]
- * @param {number} [index]
- * @returns {BaseNode}
- */
- visit(node, parent, prop, index) {
- if (node) {
- if (this.enter) {
- const _should_skip = this.should_skip;
- const _should_remove = this.should_remove;
- const _replacement = this.replacement;
- this.should_skip = false;
- this.should_remove = false;
- this.replacement = null;
- this.enter.call(this.context, node, parent, prop, index);
- if (this.replacement) {
- node = this.replacement;
- this.replace(parent, prop, index, node);
- }
- if (this.should_remove) this.remove(parent, prop, index);
- const skipped = this.should_skip;
- const removed = this.should_remove;
- this.should_skip = _should_skip;
- this.should_remove = _should_remove;
- this.replacement = _replacement;
- if (skipped) return node;
- if (removed) return null;
- }
- for (const key in node) {
- const value$1 = node[key];
- if (typeof value$1 !== "object") continue;
- else if (Array.isArray(value$1)) {
- for (let i$1 = 0; i$1 < value$1.length; i$1 += 1) if (value$1[i$1] !== null && typeof value$1[i$1].type === "string") {
- if (!this.visit(value$1[i$1], node, key, i$1)) i$1--;
- }
- } else if (value$1 !== null && typeof value$1.type === "string") this.visit(value$1, node, key, null);
- }
- if (this.leave) {
- const _replacement = this.replacement;
- const _should_remove = this.should_remove;
- this.replacement = null;
- this.should_remove = false;
- this.leave.call(this.context, node, parent, prop, index);
- if (this.replacement) {
- node = this.replacement;
- this.replace(parent, prop, index, node);
- }
- if (this.should_remove) this.remove(parent, prop, index);
- const removed = this.should_remove;
- this.replacement = _replacement;
- this.should_remove = _should_remove;
- if (removed) return null;
- }
- }
- return node;
- }
-};
-/** @typedef { import('estree').BaseNode} BaseNode */
-/** @typedef { import('./sync.js').SyncHandler} SyncHandler */
-/** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
-/**
-*
-* @param {BaseNode} ast
-* @param {{
-* enter?: SyncHandler
-* leave?: SyncHandler
-* }} walker
-* @returns {BaseNode}
-*/
-function walk$2(ast, { enter, leave }) {
- return new SyncWalker$1(enter, leave).visit(ast, null);
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/@rollup+pluginutils@5.3.0_rollup@4.43.0/node_modules/@rollup/pluginutils/dist/es/index.js
-const extractors = {
- ArrayPattern(names, param) {
- for (const element of param.elements) if (element) extractors[element.type](names, element);
- },
- AssignmentPattern(names, param) {
- extractors[param.left.type](names, param.left);
- },
- Identifier(names, param) {
- names.push(param.name);
- },
- MemberExpression() {},
- ObjectPattern(names, param) {
- for (const prop of param.properties) if (prop.type === "RestElement") extractors.RestElement(names, prop);
- else extractors[prop.value.type](names, prop.value);
- },
- RestElement(names, param) {
- extractors[param.argument.type](names, param.argument);
- }
-};
-const extractAssignedNames = function extractAssignedNames$1(param) {
- const names = [];
- extractors[param.type](names, param);
- return names;
-};
-const blockDeclarations = {
- const: true,
- let: true
-};
-var Scope = class {
- constructor(options$1 = {}) {
- this.parent = options$1.parent;
- this.isBlockScope = !!options$1.block;
- this.declarations = Object.create(null);
- if (options$1.params) options$1.params.forEach((param) => {
- extractAssignedNames(param).forEach((name) => {
- this.declarations[name] = true;
- });
- });
- }
- addDeclaration(node, isBlockDeclaration, isVar) {
- if (!isBlockDeclaration && this.isBlockScope) this.parent.addDeclaration(node, isBlockDeclaration, isVar);
- else if (node.id) extractAssignedNames(node.id).forEach((name) => {
- this.declarations[name] = true;
- });
- }
- contains(name) {
- return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
- }
-};
-const attachScopes = function attachScopes$1(ast, propertyName = "scope") {
- let scope = new Scope();
- walk$2(ast, {
- enter(n$2, parent) {
- const node = n$2;
- if (/(?:Function|Class)Declaration/.test(node.type)) scope.addDeclaration(node, false, false);
- if (node.type === "VariableDeclaration") {
- const { kind } = node;
- const isBlockDeclaration = blockDeclarations[kind];
- node.declarations.forEach((declaration) => {
- scope.addDeclaration(declaration, isBlockDeclaration, true);
- });
- }
- let newScope;
- if (node.type.includes("Function")) {
- const func = node;
- newScope = new Scope({
- parent: scope,
- block: false,
- params: func.params
- });
- if (func.type === "FunctionExpression" && func.id) newScope.addDeclaration(func, false, false);
- }
- if (/For(?:In|Of)?Statement/.test(node.type)) newScope = new Scope({
- parent: scope,
- block: true
- });
- if (node.type === "BlockStatement" && !parent.type.includes("Function")) newScope = new Scope({
- parent: scope,
- block: true
- });
- if (node.type === "CatchClause") newScope = new Scope({
- parent: scope,
- params: node.param ? [node.param] : [],
- block: true
- });
- if (newScope) {
- Object.defineProperty(node, propertyName, {
- value: newScope,
- configurable: true
- });
- scope = newScope;
- }
- },
- leave(n$2) {
- if (n$2[propertyName]) scope = scope.parent;
- }
- });
- return scope;
-};
-function isArray(arg) {
- return Array.isArray(arg);
-}
-function ensureArray(thing) {
- if (isArray(thing)) return thing;
- if (thing == null) return [];
- return [thing];
-}
-const normalizePathRegExp = new RegExp(`\\${win32.sep}`, "g");
-const normalizePath$3 = function normalizePath$5(filename) {
- return filename.replace(normalizePathRegExp, posix$1.sep);
-};
-function getMatcherString$1(id, resolutionBase) {
- if (resolutionBase === false || isAbsolute$1(id) || id.startsWith("**")) return normalizePath$3(id);
- const basePath = normalizePath$3(resolve$1(resolutionBase || "")).replace(/[-^$*+?.()|[\]{}]/g, "\\$&");
- return posix$1.join(basePath, normalizePath$3(id));
-}
-const createFilter$2 = function createFilter$3(include, exclude, options$1) {
- const resolutionBase = options$1 && options$1.resolve;
- const getMatcher = (id) => id instanceof RegExp ? id : { test: (what) => {
- return picomatch(getMatcherString$1(id, resolutionBase), { dot: true })(what);
- } };
- const includeMatchers = ensureArray(include).map(getMatcher);
- const excludeMatchers = ensureArray(exclude).map(getMatcher);
- if (!includeMatchers.length && !excludeMatchers.length) return (id) => typeof id === "string" && !id.includes("\0");
- return function result(id) {
- if (typeof id !== "string") return false;
- if (id.includes("\0")) return false;
- const pathId = normalizePath$3(id);
- for (let i$1 = 0; i$1 < excludeMatchers.length; ++i$1) {
- const matcher = excludeMatchers[i$1];
- if (matcher instanceof RegExp) matcher.lastIndex = 0;
- if (matcher.test(pathId)) return false;
- }
- for (let i$1 = 0; i$1 < includeMatchers.length; ++i$1) {
- const matcher = includeMatchers[i$1];
- if (matcher instanceof RegExp) matcher.lastIndex = 0;
- if (matcher.test(pathId)) return true;
- }
- return !includeMatchers.length;
- };
-};
-const forbiddenIdentifiers = new Set(`break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl`.split(" "));
-forbiddenIdentifiers.add("");
-const makeLegalIdentifier = function makeLegalIdentifier$1(str) {
- let identifier = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(/[^$_a-zA-Z0-9]/g, "_");
- if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) identifier = `_${identifier}`;
- return identifier || "_";
-};
-function stringify$4(obj) {
- return (JSON.stringify(obj) || "undefined").replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
-}
-function serializeArray(arr, indent, baseIndent) {
- let output = "[";
- const separator = indent ? `\n${baseIndent}${indent}` : "";
- for (let i$1 = 0; i$1 < arr.length; i$1++) {
- const key = arr[i$1];
- output += `${i$1 > 0 ? "," : ""}${separator}${serialize(key, indent, baseIndent + indent)}`;
- }
- return `${output}${indent ? `\n${baseIndent}` : ""}]`;
-}
-function serializeObject(obj, indent, baseIndent) {
- let output = "{";
- const separator = indent ? `\n${baseIndent}${indent}` : "";
- const entries = Object.entries(obj);
- for (let i$1 = 0; i$1 < entries.length; i$1++) {
- const [key, value$1] = entries[i$1];
- const stringKey = makeLegalIdentifier(key) === key ? key : stringify$4(key);
- output += `${i$1 > 0 ? "," : ""}${separator}${stringKey}:${indent ? " " : ""}${serialize(value$1, indent, baseIndent + indent)}`;
- }
- return `${output}${indent ? `\n${baseIndent}` : ""}}`;
-}
-function serialize(obj, indent, baseIndent) {
- if (typeof obj === "object" && obj !== null) {
- if (Array.isArray(obj)) return serializeArray(obj, indent, baseIndent);
- if (obj instanceof Date) return `new Date(${obj.getTime()})`;
- if (obj instanceof RegExp) return obj.toString();
- return serializeObject(obj, indent, baseIndent);
- }
- if (typeof obj === "number") {
- if (obj === Infinity) return "Infinity";
- if (obj === -Infinity) return "-Infinity";
- if (obj === 0) return 1 / obj === Infinity ? "0" : "-0";
- if (obj !== obj) return "NaN";
- }
- if (typeof obj === "symbol") {
- const key = Symbol.keyFor(obj);
- if (key !== void 0) return `Symbol.for(${stringify$4(key)})`;
- }
- if (typeof obj === "bigint") return `${obj}n`;
- return stringify$4(obj);
-}
-const hasStringIsWellFormed = "isWellFormed" in String.prototype;
-function isWellFormedString(input) {
- if (hasStringIsWellFormed) return input.isWellFormed();
- return !/\p{Surrogate}/u.test(input);
-}
-const dataToEsm = function dataToEsm$1(data, options$1 = {}) {
- var _a, _b;
- const t$1 = options$1.compact ? "" : "indent" in options$1 ? options$1.indent : " ";
- const _ = options$1.compact ? "" : " ";
- const n$2 = options$1.compact ? "" : "\n";
- const declarationType = options$1.preferConst ? "const" : "var";
- if (options$1.namedExports === false || typeof data !== "object" || Array.isArray(data) || data instanceof Date || data instanceof RegExp || data === null) {
- const code = serialize(data, options$1.compact ? null : t$1, "");
- return `export default${_ || (/^[{[\-\/]/.test(code) ? "" : " ")}${code};`;
- }
- let maxUnderbarPrefixLength = 0;
- for (const key of Object.keys(data)) {
- const underbarPrefixLength = (_b = (_a = /^(_+)/.exec(key)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0;
- if (underbarPrefixLength > maxUnderbarPrefixLength) maxUnderbarPrefixLength = underbarPrefixLength;
- }
- const arbitraryNamePrefix = `${"_".repeat(maxUnderbarPrefixLength + 1)}arbitrary`;
- let namedExportCode = "";
- const defaultExportRows = [];
- const arbitraryNameExportRows = [];
- for (const [key, value$1] of Object.entries(data)) if (key === makeLegalIdentifier(key)) {
- if (options$1.objectShorthand) defaultExportRows.push(key);
- else defaultExportRows.push(`${key}:${_}${key}`);
- namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value$1, options$1.compact ? null : t$1, "")};${n$2}`;
- } else {
- defaultExportRows.push(`${stringify$4(key)}:${_}${serialize(value$1, options$1.compact ? null : t$1, "")}`);
- if (options$1.includeArbitraryNames && isWellFormedString(key)) {
- const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`;
- namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value$1, options$1.compact ? null : t$1, "")};${n$2}`;
- arbitraryNameExportRows.push(`${variableName} as ${JSON.stringify(key)}`);
- }
- }
- const arbitraryExportCode = arbitraryNameExportRows.length > 0 ? `export${_}{${n$2}${t$1}${arbitraryNameExportRows.join(`,${n$2}${t$1}`)}${n$2}};${n$2}` : "";
- const defaultExportCode = `export default${_}{${n$2}${t$1}${defaultExportRows.join(`,${n$2}${t$1}`)}${n$2}};${n$2}`;
- return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`;
-};
-
-//#endregion
-//#region src/shared/builtin.ts
-function createIsBuiltin(builtins) {
- const plainBuiltinsSet = new Set(builtins.filter((builtin) => typeof builtin === "string"));
- const regexBuiltins = builtins.filter((builtin) => typeof builtin !== "string");
- return (id) => plainBuiltinsSet.has(id) || regexBuiltins.some((regexp) => regexp.test(id));
-}
-
-//#endregion
-//#region src/node/packages.ts
-let pnp;
-if (process.versions.pnp) try {
- pnp = createRequire(
- /** #__KEEP__ */
- import.meta.url
- )("pnpapi");
-} catch {}
-function invalidatePackageData(packageCache, pkgPath) {
- const pkgDir = normalizePath(path.dirname(pkgPath));
- packageCache.forEach((pkg, cacheKey) => {
- if (pkg.dir === pkgDir) packageCache.delete(cacheKey);
- });
-}
-function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) {
- if (pnp) {
- const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
- if (packageCache?.has(cacheKey)) return packageCache.get(cacheKey);
- try {
- const pkg = pnp.resolveToUnqualified(pkgName, basedir, { considerBuiltins: false });
- if (!pkg) return null;
- const pkgData = loadPackageData(path.join(pkg, "package.json"));
- packageCache?.set(cacheKey, pkgData);
- return pkgData;
- } catch {
- return null;
- }
- }
- const originalBasedir = basedir;
- while (basedir) {
- if (packageCache) {
- const cached = getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks);
- if (cached) return cached;
- }
- const pkg = path.join(basedir, "node_modules", pkgName, "package.json");
- try {
- if (fs.existsSync(pkg)) {
- const pkgData = loadPackageData(preserveSymlinks ? pkg : safeRealpathSync(pkg));
- if (packageCache) setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks);
- return pkgData;
- }
- } catch {}
- const nextBasedir = path.dirname(basedir);
- if (nextBasedir === basedir) break;
- basedir = nextBasedir;
- }
- return null;
-}
-function findNearestPackageData(basedir, packageCache) {
- const originalBasedir = basedir;
- while (basedir) {
- if (packageCache) {
- const cached = getFnpdCache(packageCache, basedir, originalBasedir);
- if (cached) return cached;
- }
- const pkgPath = path.join(basedir, "package.json");
- if (tryStatSync(pkgPath)?.isFile()) try {
- const pkgData = loadPackageData(pkgPath);
- if (packageCache) setFnpdCache(packageCache, pkgData, basedir, originalBasedir);
- return pkgData;
- } catch {}
- const nextBasedir = path.dirname(basedir);
- if (nextBasedir === basedir) break;
- basedir = nextBasedir;
- }
- return null;
-}
-function findNearestMainPackageData(basedir, packageCache) {
- const nearestPackage = findNearestPackageData(basedir, packageCache);
- return nearestPackage && (nearestPackage.data.name ? nearestPackage : findNearestMainPackageData(path.dirname(nearestPackage.dir), packageCache));
-}
-function loadPackageData(pkgPath) {
- const data = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf-8")));
- const pkgDir = normalizePath(path.dirname(pkgPath));
- const { sideEffects } = data;
- let hasSideEffects;
- if (typeof sideEffects === "boolean") hasSideEffects = () => sideEffects;
- else if (Array.isArray(sideEffects)) if (sideEffects.length <= 0) hasSideEffects = () => false;
- else hasSideEffects = createFilter(sideEffects.map((sideEffect) => {
- if (sideEffect.includes("/")) return sideEffect;
- return `**/${sideEffect}`;
- }), null, { resolve: pkgDir });
- else hasSideEffects = () => null;
- const resolvedCache = {};
- return {
- dir: pkgDir,
- data,
- hasSideEffects,
- setResolvedCache(key, entry, options$1) {
- resolvedCache[getResolveCacheKey(key, options$1)] = entry;
- },
- getResolvedCache(key, options$1) {
- return resolvedCache[getResolveCacheKey(key, options$1)];
- }
- };
-}
-function getResolveCacheKey(key, options$1) {
- return [
- key,
- options$1.isRequire ? "1" : "0",
- options$1.conditions.join("_"),
- options$1.extensions.join("_"),
- options$1.mainFields.join("_")
- ].join("|");
-}
-function findNearestNodeModules(basedir) {
- while (basedir) {
- const pkgPath = path.join(basedir, "node_modules");
- if (tryStatSync(pkgPath)?.isDirectory()) return pkgPath;
- const nextBasedir = path.dirname(basedir);
- if (nextBasedir === basedir) break;
- basedir = nextBasedir;
- }
- return null;
-}
-function watchPackageDataPlugin(packageCache) {
- const watchQueue = /* @__PURE__ */ new Set();
- const watchedDirs = /* @__PURE__ */ new Set();
- const watchFileStub = (id) => {
- watchQueue.add(id);
- };
- let watchFile = watchFileStub;
- const setPackageData = packageCache.set.bind(packageCache);
- packageCache.set = (id, pkg) => {
- if (!isInNodeModules(pkg.dir) && !watchedDirs.has(pkg.dir)) {
- watchedDirs.add(pkg.dir);
- watchFile(path.join(pkg.dir, "package.json"));
- }
- return setPackageData(id, pkg);
- };
- return {
- name: "vite:watch-package-data",
- buildStart() {
- watchFile = this.addWatchFile.bind(this);
- watchQueue.forEach(watchFile);
- watchQueue.clear();
- },
- buildEnd() {
- watchFile = watchFileStub;
- },
- watchChange(id) {
- if (id.endsWith("/package.json")) invalidatePackageData(packageCache, path.normalize(id));
- }
- };
-}
-/**
-* Get cached `resolvePackageData` value based on `basedir`. When one is found,
-* and we've already traversed some directories between `basedir` and `originalBasedir`,
-* we cache the value for those in-between directories as well.
-*
-* This makes it so the fs is only read once for a shared `basedir`.
-*/
-function getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks) {
- const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
- const pkgData = packageCache.get(cacheKey);
- if (pkgData) {
- traverseBetweenDirs(originalBasedir, basedir, (dir) => {
- packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
- });
- return pkgData;
- }
-}
-function setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks) {
- packageCache.set(getRpdCacheKey(pkgName, basedir, preserveSymlinks), pkgData);
- traverseBetweenDirs(originalBasedir, basedir, (dir) => {
- packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
- });
-}
-function getRpdCacheKey(pkgName, basedir, preserveSymlinks) {
- return `rpd_${pkgName}_${basedir}_${preserveSymlinks}`;
-}
-/**
-* Get cached `findNearestPackageData` value based on `basedir`. When one is found,
-* and we've already traversed some directories between `basedir` and `originalBasedir`,
-* we cache the value for those in-between directories as well.
-*
-* This makes it so the fs is only read once for a shared `basedir`.
-*/
-function getFnpdCache(packageCache, basedir, originalBasedir) {
- const cacheKey = getFnpdCacheKey(basedir);
- const pkgData = packageCache.get(cacheKey);
- if (pkgData) {
- traverseBetweenDirs(originalBasedir, basedir, (dir) => {
- packageCache.set(getFnpdCacheKey(dir), pkgData);
- });
- return pkgData;
- }
-}
-function setFnpdCache(packageCache, pkgData, basedir, originalBasedir) {
- packageCache.set(getFnpdCacheKey(basedir), pkgData);
- traverseBetweenDirs(originalBasedir, basedir, (dir) => {
- packageCache.set(getFnpdCacheKey(dir), pkgData);
- });
-}
-function getFnpdCacheKey(basedir) {
- return `fnpd_${basedir}`;
-}
-/**
-* Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir.
-* @param longerDir Longer dir path, e.g. `/User/foo/bar/baz`
-* @param shorterDir Shorter dir path, e.g. `/User/foo`
-*/
-function traverseBetweenDirs(longerDir, shorterDir, cb) {
- while (longerDir !== shorterDir) {
- cb(longerDir);
- longerDir = path.dirname(longerDir);
- }
-}
-
-//#endregion
-//#region src/node/utils.ts
-var import_picocolors$33 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-init_node();
-const createFilter = createFilter$2;
-const replaceSlashOrColonRE = /[/:]/g;
-const replaceDotRE = /\./g;
-const replaceNestedIdRE = /\s*>\s*/g;
-const replaceHashRE = /#/g;
-const flattenId = (id) => {
- return limitFlattenIdLength(id.replace(replaceSlashOrColonRE, "_").replace(replaceDotRE, "__").replace(replaceNestedIdRE, "___").replace(replaceHashRE, "____"));
-};
-const FLATTEN_ID_HASH_LENGTH = 8;
-const FLATTEN_ID_MAX_FILE_LENGTH = 170;
-const limitFlattenIdLength = (id, limit = FLATTEN_ID_MAX_FILE_LENGTH) => {
- if (id.length <= limit) return id;
- return id.slice(0, limit - (FLATTEN_ID_HASH_LENGTH + 1)) + "_" + getHash(id);
-};
-const normalizeId = (id) => id.replace(replaceNestedIdRE, " > ");
-const NODE_BUILTIN_NAMESPACE = "node:";
-const BUN_BUILTIN_NAMESPACE = "bun:";
-const nodeBuiltins = builtinModules.filter((id) => !id.includes(":"));
-const isBuiltinCache = /* @__PURE__ */ new WeakMap();
-function isBuiltin(builtins, id) {
- let isBuiltin$1 = isBuiltinCache.get(builtins);
- if (!isBuiltin$1) {
- isBuiltin$1 = createIsBuiltin(builtins);
- isBuiltinCache.set(builtins, isBuiltin$1);
- }
- return isBuiltin$1(id);
-}
-const nodeLikeBuiltins = [
- ...nodeBuiltins,
- /* @__PURE__ */ new RegExp(`^${NODE_BUILTIN_NAMESPACE}`),
- /* @__PURE__ */ new RegExp(`^${BUN_BUILTIN_NAMESPACE}`)
-];
-function isNodeLikeBuiltin(id) {
- return isBuiltin(nodeLikeBuiltins, id);
-}
-function isNodeBuiltin(id) {
- if (id.startsWith(NODE_BUILTIN_NAMESPACE)) return true;
- return nodeBuiltins.includes(id);
-}
-function isInNodeModules(id) {
- return id.includes("node_modules");
-}
-function moduleListContains(moduleList, id) {
- return moduleList?.some((m) => m === id || id.startsWith(withTrailingSlash(m)));
-}
-function isOptimizable(id, optimizeDeps$1) {
- const { extensions: extensions$1 } = optimizeDeps$1;
- return OPTIMIZABLE_ENTRY_RE.test(id) || (extensions$1?.some((ext) => id.endsWith(ext)) ?? false);
-}
-const bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/;
-const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
-const _dirname = path.dirname(fileURLToPath(
- /** #__KEEP__ */
- import.meta.url
-));
-const rollupVersion = resolvePackageData("rollup", _dirname, true)?.data.version ?? "";
-const filter = process.env.VITE_DEBUG_FILTER;
-const DEBUG = process.env.DEBUG;
-function createDebugger(namespace, options$1 = {}) {
- const log$3 = node_default(namespace);
- const { onlyWhenFocused, depth } = options$1;
- if (depth && log$3.inspectOpts && log$3.inspectOpts.depth == null) log$3.inspectOpts.depth = options$1.depth;
- let enabled = log$3.enabled;
- if (enabled && onlyWhenFocused) enabled = !!DEBUG?.includes(typeof onlyWhenFocused === "string" ? onlyWhenFocused : namespace);
- if (enabled) return (...args) => {
- if (!filter || args.some((a) => a?.includes?.(filter))) log$3(...args);
- };
-}
-function testCaseInsensitiveFS() {
- if (!CLIENT_ENTRY.endsWith("client.mjs")) throw new Error(`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`);
- if (!fs.existsSync(CLIENT_ENTRY)) throw new Error("cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: " + CLIENT_ENTRY);
- return fs.existsSync(CLIENT_ENTRY.replace("client.mjs", "cLiEnT.mjs"));
-}
-const isCaseInsensitiveFS = testCaseInsensitiveFS();
-const VOLUME_RE = /^[A-Z]:/i;
-function normalizePath(id) {
- return path.posix.normalize(isWindows ? slash(id) : id);
-}
-function fsPathFromId(id) {
- const fsPath = normalizePath(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id);
- return fsPath[0] === "/" || VOLUME_RE.test(fsPath) ? fsPath : `/${fsPath}`;
-}
-function fsPathFromUrl(url$3) {
- return fsPathFromId(cleanUrl(url$3));
-}
-/**
-* Check if dir is a parent of file
-*
-* Warning: parameters are not validated, only works with normalized absolute paths
-*
-* @param dir - normalized absolute path
-* @param file - normalized absolute path
-* @returns true if dir is a parent of file
-*/
-function isParentDirectory(dir, file) {
- dir = withTrailingSlash(dir);
- return file.startsWith(dir) || isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase());
-}
-/**
-* Check if 2 file name are identical
-*
-* Warning: parameters are not validated, only works with normalized absolute paths
-*
-* @param file1 - normalized absolute path
-* @param file2 - normalized absolute path
-* @returns true if both files url are identical
-*/
-function isSameFilePath(file1, file2) {
- return file1 === file2 || isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase();
-}
-const externalRE = /^([a-z]+:)?\/\//;
-const isExternalUrl = (url$3) => externalRE.test(url$3);
-const dataUrlRE = /^\s*data:/i;
-const isDataUrl = (url$3) => dataUrlRE.test(url$3);
-const virtualModuleRE = /^virtual-module:.*/;
-const virtualModulePrefix = "virtual-module:";
-const knownJsSrcRE = /\.(?:[jt]sx?|m[jt]s|vue|marko|svelte|astro|imba|mdx)(?:$|\?)/;
-const isJSRequest = (url$3) => {
- url$3 = cleanUrl(url$3);
- if (knownJsSrcRE.test(url$3)) return true;
- if (!path.extname(url$3) && url$3[url$3.length - 1] !== "/") return true;
- return false;
-};
-const isCSSRequest = (request) => CSS_LANGS_RE.test(request);
-const importQueryRE = /(\?|&)import=?(?:&|$)/;
-const directRequestRE$1 = /(\?|&)direct=?(?:&|$)/;
-const internalPrefixes = [
- FS_PREFIX,
- VALID_ID_PREFIX,
- CLIENT_PUBLIC_PATH,
- ENV_PUBLIC_PATH
-];
-const InternalPrefixRE = /* @__PURE__ */ new RegExp(`^(?:${internalPrefixes.join("|")})`);
-const trailingSeparatorRE = /[?&]$/;
-const isImportRequest = (url$3) => importQueryRE.test(url$3);
-const isInternalRequest = (url$3) => InternalPrefixRE.test(url$3);
-function removeImportQuery(url$3) {
- return url$3.replace(importQueryRE, "$1").replace(trailingSeparatorRE, "");
-}
-function removeDirectQuery(url$3) {
- return url$3.replace(directRequestRE$1, "$1").replace(trailingSeparatorRE, "");
-}
-const urlRE = /(\?|&)url(?:&|$)/;
-const rawRE = /(\?|&)raw(?:&|$)/;
-function removeUrlQuery(url$3) {
- return url$3.replace(urlRE, "$1").replace(trailingSeparatorRE, "");
-}
-function injectQuery(url$3, queryToInject) {
- const { file, postfix } = splitFileAndPostfix(url$3);
- return `${isWindows ? slash(file) : file}?${queryToInject}${postfix[0] === "?" ? `&${postfix.slice(1)}` : postfix}`;
-}
-const timestampRE = /\bt=\d{13}&?\b/;
-function removeTimestampQuery(url$3) {
- return url$3.replace(timestampRE, "").replace(trailingSeparatorRE, "");
-}
-async function asyncReplace(input, re, replacer) {
- let match;
- let remaining = input;
- let rewritten = "";
- while (match = re.exec(remaining)) {
- rewritten += remaining.slice(0, match.index);
- rewritten += await replacer(match);
- remaining = remaining.slice(match.index + match[0].length);
- }
- rewritten += remaining;
- return rewritten;
-}
-function timeFrom(start, subtract = 0) {
- const time = performance$1.now() - start - subtract;
- const timeString = (time.toFixed(2) + `ms`).padEnd(5, " ");
- if (time < 10) return import_picocolors$33.default.green(timeString);
- else if (time < 50) return import_picocolors$33.default.yellow(timeString);
- else return import_picocolors$33.default.red(timeString);
-}
-/**
-* pretty url for logging.
-*/
-function prettifyUrl(url$3, root) {
- url$3 = removeTimestampQuery(url$3);
- const isAbsoluteFile = url$3.startsWith(root);
- if (isAbsoluteFile || url$3.startsWith(FS_PREFIX)) {
- const file = path.posix.relative(root, isAbsoluteFile ? url$3 : fsPathFromId(url$3));
- return import_picocolors$33.default.dim(file);
- } else return import_picocolors$33.default.dim(url$3);
-}
-function isObject(value$1) {
- return Object.prototype.toString.call(value$1) === "[object Object]";
-}
-function isDefined(value$1) {
- return value$1 != null;
-}
-function tryStatSync(file) {
- try {
- return fs.statSync(file, { throwIfNoEntry: false });
- } catch {}
-}
-function lookupFile(dir, fileNames) {
- while (dir) {
- for (const fileName of fileNames) {
- const fullPath = path.join(dir, fileName);
- if (tryStatSync(fullPath)?.isFile()) return fullPath;
- }
- const parentDir$1 = path.dirname(dir);
- if (parentDir$1 === dir) return;
- dir = parentDir$1;
- }
-}
-function isFilePathESM(filePath, packageCache) {
- if (/\.m[jt]s$/.test(filePath)) return true;
- else if (/\.c[jt]s$/.test(filePath)) return false;
- else try {
- return findNearestPackageData(path.dirname(filePath), packageCache)?.data.type === "module";
- } catch {
- return false;
- }
-}
-const splitRE = /\r?\n/g;
-const range = 2;
-function pad$1(source, n$2 = 2) {
- return source.split(splitRE).map((l) => ` `.repeat(n$2) + l).join(`\n`);
-}
-function posToNumber(source, pos) {
- if (typeof pos === "number") return pos;
- const lines = source.split(splitRE);
- const { line, column } = pos;
- let start = 0;
- for (let i$1 = 0; i$1 < line - 1 && i$1 < lines.length; i$1++) start += lines[i$1].length + 1;
- return start + column;
-}
-function numberToPos(source, offset$1) {
- if (typeof offset$1 !== "number") return offset$1;
- if (offset$1 > source.length) throw new Error(`offset is longer than source length! offset ${offset$1} > length ${source.length}`);
- const lines = source.slice(0, offset$1).split(splitRE);
- return {
- line: lines.length,
- column: lines[lines.length - 1].length
- };
-}
-const MAX_DISPLAY_LEN = 120;
-const ELLIPSIS = "...";
-function generateCodeFrame(source, start = 0, end) {
- start = Math.max(posToNumber(source, start), 0);
- end = Math.min(end !== void 0 ? posToNumber(source, end) : start, source.length);
- const lastPosLine = end !== void 0 ? numberToPos(source, end).line : numberToPos(source, start).line + range;
- const lineNumberWidth = Math.max(3, String(lastPosLine).length + 1);
- const lines = source.split(splitRE);
- let count = 0;
- const res = [];
- for (let i$1 = 0; i$1 < lines.length; i$1++) {
- count += lines[i$1].length;
- if (count >= start) {
- for (let j = i$1 - range; j <= i$1 + range || end > count; j++) {
- if (j < 0 || j >= lines.length) continue;
- const line = j + 1;
- const lineLength = lines[j].length;
- const pad$2 = Math.max(start - (count - lineLength), 0);
- const underlineLength = Math.max(1, end > count ? lineLength - pad$2 : end - start);
- let displayLine = lines[j];
- let underlinePad = pad$2;
- if (lineLength > MAX_DISPLAY_LEN) {
- let startIdx = 0;
- if (j === i$1) {
- if (underlineLength > MAX_DISPLAY_LEN) startIdx = pad$2;
- else {
- const center = pad$2 + Math.floor(underlineLength / 2);
- startIdx = Math.max(0, center - Math.floor(MAX_DISPLAY_LEN / 2));
- }
- underlinePad = Math.max(0, pad$2 - startIdx) + (startIdx > 0 ? 3 : 0);
- }
- const prefix = startIdx > 0 ? ELLIPSIS : "";
- const suffix = lineLength - startIdx > MAX_DISPLAY_LEN ? ELLIPSIS : "";
- const sliceLen = MAX_DISPLAY_LEN - prefix.length - suffix.length;
- displayLine = prefix + displayLine.slice(startIdx, startIdx + sliceLen) + suffix;
- }
- res.push(`${line}${" ".repeat(lineNumberWidth - String(line).length)}| ${displayLine}`);
- if (j === i$1) {
- const underline = "^".repeat(Math.min(underlineLength, MAX_DISPLAY_LEN));
- res.push(`${" ".repeat(lineNumberWidth)}| ` + " ".repeat(underlinePad) + underline);
- } else if (j > i$1) {
- if (end > count) {
- const length = Math.max(Math.min(end - count, lineLength), 1);
- const underline = "^".repeat(Math.min(length, MAX_DISPLAY_LEN));
- res.push(`${" ".repeat(lineNumberWidth)}| ` + underline);
- }
- count += lineLength + 1;
- }
- }
- break;
- }
- count++;
- }
- return res.join("\n");
-}
-function isFileReadable(filename) {
- if (!tryStatSync(filename)) return false;
- try {
- fs.accessSync(filename, fs.constants.R_OK);
- return true;
- } catch {
- return false;
- }
-}
-const splitFirstDirRE = /(.+?)[\\/](.+)/;
-/**
-* Delete every file and subdirectory. **The given directory must exist.**
-* Pass an optional `skip` array to preserve files under the root directory.
-*/
-function emptyDir(dir, skip) {
- const skipInDir = [];
- let nested = null;
- if (skip?.length) for (const file of skip) if (path.dirname(file) !== ".") {
- const matched = splitFirstDirRE.exec(file);
- if (matched) {
- nested ??= /* @__PURE__ */ new Map();
- const [, nestedDir, skipPath] = matched;
- let nestedSkip = nested.get(nestedDir);
- if (!nestedSkip) {
- nestedSkip = [];
- nested.set(nestedDir, nestedSkip);
- }
- if (!nestedSkip.includes(skipPath)) nestedSkip.push(skipPath);
- }
- } else skipInDir.push(file);
- for (const file of fs.readdirSync(dir)) {
- if (skipInDir.includes(file)) continue;
- if (nested?.has(file)) emptyDir(path.resolve(dir, file), nested.get(file));
- else fs.rmSync(path.resolve(dir, file), {
- recursive: true,
- force: true
- });
- }
-}
-function copyDir(srcDir, destDir) {
- fs.mkdirSync(destDir, { recursive: true });
- for (const file of fs.readdirSync(srcDir)) {
- const srcFile = path.resolve(srcDir, file);
- if (srcFile === destDir) continue;
- const destFile = path.resolve(destDir, file);
- if (fs.statSync(srcFile).isDirectory()) copyDir(srcFile, destFile);
- else fs.copyFileSync(srcFile, destFile);
- }
-}
-const ERR_SYMLINK_IN_RECURSIVE_READDIR = "ERR_SYMLINK_IN_RECURSIVE_READDIR";
-async function recursiveReaddir(dir) {
- if (!fs.existsSync(dir)) return [];
- let dirents;
- try {
- dirents = await fsp.readdir(dir, { withFileTypes: true });
- } catch (e$1) {
- if (e$1.code === "EACCES") return [];
- throw e$1;
- }
- if (dirents.some((dirent) => dirent.isSymbolicLink())) {
- const err$2 = /* @__PURE__ */ new Error("Symbolic links are not supported in recursiveReaddir");
- err$2.code = ERR_SYMLINK_IN_RECURSIVE_READDIR;
- throw err$2;
- }
- return (await Promise.all(dirents.map((dirent) => {
- const res = path.resolve(dir, dirent.name);
- return dirent.isDirectory() ? recursiveReaddir(res) : normalizePath(res);
- }))).flat(1);
-}
-let safeRealpathSync = isWindows ? windowsSafeRealPathSync : fs.realpathSync.native;
-const windowsNetworkMap = /* @__PURE__ */ new Map();
-function windowsMappedRealpathSync(path$13) {
- const realPath = fs.realpathSync.native(path$13);
- if (realPath.startsWith("\\\\")) {
- for (const [network, volume] of windowsNetworkMap) if (realPath.startsWith(network)) return realPath.replace(network, volume);
- }
- return realPath;
-}
-const parseNetUseRE = /^\w* +(\w:) +([^ ]+)\s/;
-let firstSafeRealPathSyncRun = false;
-function windowsSafeRealPathSync(path$13) {
- if (!firstSafeRealPathSyncRun) {
- optimizeSafeRealPathSync();
- firstSafeRealPathSyncRun = true;
- }
- return fs.realpathSync(path$13);
-}
-function optimizeSafeRealPathSync() {
- try {
- fs.realpathSync.native(path.resolve("./"));
- } catch (error$1) {
- if (error$1.message.includes("EISDIR: illegal operation on a directory")) {
- safeRealpathSync = fs.realpathSync;
- return;
- }
- }
- exec("net use", (error$1, stdout) => {
- if (error$1) return;
- const lines = stdout.split("\n");
- for (const line of lines) {
- const m = parseNetUseRE.exec(line);
- if (m) windowsNetworkMap.set(m[2], m[1]);
- }
- if (windowsNetworkMap.size === 0) safeRealpathSync = fs.realpathSync.native;
- else safeRealpathSync = windowsMappedRealpathSync;
- });
-}
-function ensureWatchedFile(watcher, file, root) {
- if (file && !file.startsWith(withTrailingSlash(root)) && !file.includes("\0") && fs.existsSync(file)) watcher.add(path.resolve(file));
-}
-function joinSrcset(ret) {
- return ret.map(({ url: url$3, descriptor }) => url$3 + (descriptor ? ` ${descriptor}` : "")).join(", ");
-}
-/**
-This regex represents a loose rule of an “image candidate string” and "image set options".
-
-@see https://html.spec.whatwg.org/multipage/images.html#srcset-attribute
-@see https://drafts.csswg.org/css-images-4/#image-set-notation
-
-The Regex has named capturing groups `url` and `descriptor`.
-The `url` group can be:
-* any CSS function
-* CSS string (single or double-quoted)
-* URL string (unquoted)
-The `descriptor` is anything after the space and before the comma.
-*/
-const imageCandidateRegex = /(?:^|\s|(?<=,))(?<url>[\w-]+\([^)]*\)|"[^"]*"|'[^']*'|[^,]\S*[^,])\s*(?:\s(?<descriptor>\w[^,]+))?(?:,|$)/g;
-const escapedSpaceCharacters = /(?: |\\t|\\n|\\f|\\r)+/g;
-function parseSrcset(string) {
- const matches$2 = string.trim().replace(escapedSpaceCharacters, " ").replace(/\r?\n/, "").replace(/,\s+/, ", ").replaceAll(/\s+/g, " ").matchAll(imageCandidateRegex);
- return Array.from(matches$2, ({ groups: groups$1 }) => ({
- url: groups$1?.url?.trim() ?? "",
- descriptor: groups$1?.descriptor?.trim() ?? ""
- })).filter(({ url: url$3 }) => !!url$3);
-}
-function processSrcSet(srcs, replacer) {
- return Promise.all(parseSrcset(srcs).map(async ({ url: url$3, descriptor }) => ({
- url: await replacer({
- url: url$3,
- descriptor
- }),
- descriptor
- }))).then(joinSrcset);
-}
-function processSrcSetSync(srcs, replacer) {
- return joinSrcset(parseSrcset(srcs).map(({ url: url$3, descriptor }) => ({
- url: replacer({
- url: url$3,
- descriptor
- }),
- descriptor
- })));
-}
-const windowsDriveRE = /^[A-Z]:/;
-const replaceWindowsDriveRE = /^([A-Z]):\//;
-const linuxAbsolutePathRE = /^\/[^/]/;
-function escapeToLinuxLikePath(path$13) {
- if (windowsDriveRE.test(path$13)) return path$13.replace(replaceWindowsDriveRE, "/windows/$1/");
- if (linuxAbsolutePathRE.test(path$13)) return `/linux${path$13}`;
- return path$13;
-}
-const revertWindowsDriveRE = /^\/windows\/([A-Z])\//;
-function unescapeToLinuxLikePath(path$13) {
- if (path$13.startsWith("/linux/")) return path$13.slice(6);
- if (path$13.startsWith("/windows/")) return path$13.replace(revertWindowsDriveRE, "$1:/");
- return path$13;
-}
-const nullSourceMap = {
- names: [],
- sources: [],
- mappings: "",
- version: 3
-};
-/**
-* Combines multiple sourcemaps into a single sourcemap.
-* Note that the length of sourcemapList must be 2.
-*/
-function combineSourcemaps(filename, sourcemapList) {
- if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) return { ...nullSourceMap };
- sourcemapList = sourcemapList.map((sourcemap) => {
- const newSourcemaps = { ...sourcemap };
- newSourcemaps.sources = sourcemap.sources.map((source) => source ? escapeToLinuxLikePath(source) : null);
- if (sourcemap.sourceRoot) newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot);
- return newSourcemaps;
- });
- const escapedFilename = escapeToLinuxLikePath(filename);
- let map$1;
- let mapIndex = 1;
- if (sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0) map$1 = remapping(sourcemapList, () => null);
- else map$1 = remapping(sourcemapList[0], function loader$1(sourcefile) {
- if (sourcefile === escapedFilename && sourcemapList[mapIndex]) return sourcemapList[mapIndex++];
- else return null;
- });
- if (!map$1.file) delete map$1.file;
- map$1.sources = map$1.sources.map((source) => source ? unescapeToLinuxLikePath(source) : source);
- map$1.file = filename;
- return map$1;
-}
-function unique(arr) {
- return Array.from(new Set(arr));
-}
-/**
-* Returns resolved localhost address when `dns.lookup` result differs from DNS
-*
-* `dns.lookup` result is same when defaultResultOrder is `verbatim`.
-* Even if defaultResultOrder is `ipv4first`, `dns.lookup` result maybe same.
-* For example, when IPv6 is not supported on that machine/network.
-*/
-async function getLocalhostAddressIfDiffersFromDNS() {
- const [nodeResult, dnsResult] = await Promise.all([promises$1.lookup("localhost"), promises$1.lookup("localhost", { verbatim: true })]);
- return nodeResult.family === dnsResult.family && nodeResult.address === dnsResult.address ? void 0 : nodeResult.address;
-}
-function diffDnsOrderChange(oldUrls, newUrls) {
- return !(oldUrls === newUrls || oldUrls && newUrls && arrayEqual(oldUrls.local, newUrls.local) && arrayEqual(oldUrls.network, newUrls.network));
-}
-async function resolveHostname(optionsHost) {
- let host;
- if (optionsHost === void 0 || optionsHost === false) host = "localhost";
- else if (optionsHost === true) host = void 0;
- else host = optionsHost;
- let name = host === void 0 || wildcardHosts.has(host) ? "localhost" : host;
- if (host === "localhost") {
- const localhostAddr = await getLocalhostAddressIfDiffersFromDNS();
- if (localhostAddr) name = localhostAddr;
- }
- return {
- host,
- name
- };
-}
-function extractHostnamesFromCerts(certs) {
- const certList = certs ? arraify(certs) : [];
- if (certList.length === 0) return [];
- return unique(certList.map((cert) => {
- try {
- return new crypto.X509Certificate(cert);
- } catch {
- return null;
- }
- }).flatMap((cert) => cert?.subjectAltName ? extractHostnamesFromSubjectAltName(cert.subjectAltName) : []));
-}
-function resolveServerUrls(server, options$1, hostname, httpsOptions, config$2) {
- const address = server.address();
- const isAddressInfo = (x) => x?.address;
- if (!isAddressInfo(address)) return {
- local: [],
- network: []
- };
- const local = [];
- const network = [];
- const protocol = options$1.https ? "https" : "http";
- const port = address.port;
- const base = config$2.rawBase === "./" || config$2.rawBase === "" ? "/" : config$2.rawBase;
- if (hostname.host !== void 0 && !wildcardHosts.has(hostname.host)) {
- let hostnameName = hostname.name;
- if (hostnameName.includes(":")) hostnameName = `[${hostnameName}]`;
- const address$1 = `${protocol}://${hostnameName}:${port}${base}`;
- if (loopbackHosts.has(hostname.host)) local.push(address$1);
- else network.push(address$1);
- } else Object.values(os.networkInterfaces()).flatMap((nInterface) => nInterface ?? []).filter((detail) => detail.address && detail.family === "IPv4").forEach((detail) => {
- let host = detail.address.replace("127.0.0.1", hostname.name);
- if (host.includes(":")) host = `[${host}]`;
- const url$3 = `${protocol}://${host}:${port}${base}`;
- if (detail.address.includes("127.0.0.1")) local.push(url$3);
- else network.push(url$3);
- });
- const hostnamesFromCert = extractHostnamesFromCerts(httpsOptions?.cert);
- if (hostnamesFromCert.length > 0) {
- const existings = new Set([...local, ...network]);
- local.push(...hostnamesFromCert.map((hostname$1) => `${protocol}://${hostname$1}:${port}${base}`).filter((url$3) => !existings.has(url$3)));
- }
- return {
- local,
- network
- };
-}
-function extractHostnamesFromSubjectAltName(subjectAltName) {
- const hostnames = [];
- let remaining = subjectAltName;
- while (remaining) {
- const nameEndIndex = remaining.indexOf(":");
- const name = remaining.slice(0, nameEndIndex);
- remaining = remaining.slice(nameEndIndex + 1);
- if (!remaining) break;
- const isQuoted = remaining[0] === "\"";
- let value$1;
- if (isQuoted) {
- const endQuoteIndex = remaining.indexOf("\"", 1);
- value$1 = JSON.parse(remaining.slice(0, endQuoteIndex + 1));
- remaining = remaining.slice(endQuoteIndex + 1);
- } else {
- const maybeEndIndex = remaining.indexOf(",");
- const endIndex = maybeEndIndex === -1 ? remaining.length : maybeEndIndex;
- value$1 = remaining.slice(0, endIndex);
- remaining = remaining.slice(endIndex);
- }
- remaining = remaining.slice(1).trimStart();
- if (name === "DNS" && value$1 !== "[::1]" && !(value$1.startsWith("*.") && net.isIPv4(value$1.slice(2)))) hostnames.push(value$1.replace("*", "vite"));
- }
- return hostnames;
-}
-function arraify(target) {
- return Array.isArray(target) ? target : [target];
-}
-const multilineCommentsRE = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g;
-const singlelineCommentsRE = /\/\/.*/g;
-const requestQuerySplitRE = /\?(?!.*[/|}])/;
-const requestQueryMaybeEscapedSplitRE = /\\?\?(?!.*[/|}])/;
-const blankReplacer = (match) => " ".repeat(match.length);
-function getHash(text, length = 8) {
- const h = crypto.hash("sha256", text, "hex").substring(0, length);
- if (length <= 64) return h;
- return h.padEnd(length, "_");
-}
-function emptyCssComments(raw) {
- return raw.replace(multilineCommentsRE, blankReplacer);
-}
-function backwardCompatibleWorkerPlugins(plugins$1) {
- if (Array.isArray(plugins$1)) return plugins$1;
- if (typeof plugins$1 === "function") return plugins$1();
- return [];
-}
-function deepClone(value$1) {
- if (Array.isArray(value$1)) return value$1.map((v) => deepClone(v));
- if (isObject(value$1)) {
- const cloned = {};
- for (const key in value$1) cloned[key] = deepClone(value$1[key]);
- return cloned;
- }
- if (typeof value$1 === "function") return value$1;
- if (value$1 instanceof RegExp) return new RegExp(value$1);
- if (typeof value$1 === "object" && value$1 != null) throw new Error("Cannot deep clone non-plain object");
- return value$1;
-}
-function mergeWithDefaultsRecursively(defaults, values) {
- const merged = defaults;
- for (const key in values) {
- const value$1 = values[key];
- if (value$1 === void 0) continue;
- const existing = merged[key];
- if (existing === void 0) {
- merged[key] = value$1;
- continue;
- }
- if (isObject(existing) && isObject(value$1)) {
- merged[key] = mergeWithDefaultsRecursively(existing, value$1);
- continue;
- }
- merged[key] = value$1;
- }
- return merged;
-}
-const environmentPathRE = /^environments\.[^.]+$/;
-function mergeWithDefaults(defaults, values) {
- return mergeWithDefaultsRecursively(deepClone(defaults), values);
-}
-function mergeConfigRecursively(defaults, overrides, rootPath) {
- const merged = { ...defaults };
- for (const key in overrides) {
- const value$1 = overrides[key];
- if (value$1 == null) continue;
- const existing = merged[key];
- if (existing == null) {
- merged[key] = value$1;
- continue;
- }
- if (key === "alias" && (rootPath === "resolve" || rootPath === "")) {
- merged[key] = mergeAlias(existing, value$1);
- continue;
- } else if (key === "assetsInclude" && rootPath === "") {
- merged[key] = [].concat(existing, value$1);
- continue;
- } else if (((key === "noExternal" || key === "external") && (rootPath === "ssr" || rootPath === "resolve") || key === "allowedHosts" && rootPath === "server") && (existing === true || value$1 === true)) {
- merged[key] = true;
- continue;
- } else if (key === "plugins" && rootPath === "worker") {
- merged[key] = () => [...backwardCompatibleWorkerPlugins(existing), ...backwardCompatibleWorkerPlugins(value$1)];
- continue;
- } else if (key === "server" && rootPath === "server.hmr") {
- merged[key] = value$1;
- continue;
- }
- if (Array.isArray(existing) || Array.isArray(value$1)) {
- merged[key] = [...arraify(existing), ...arraify(value$1)];
- continue;
- }
- if (isObject(existing) && isObject(value$1)) {
- merged[key] = mergeConfigRecursively(existing, value$1, rootPath && !environmentPathRE.test(rootPath) ? `${rootPath}.${key}` : key);
- continue;
- }
- merged[key] = value$1;
- }
- return merged;
-}
-function mergeConfig(defaults, overrides, isRoot = true) {
- if (typeof defaults === "function" || typeof overrides === "function") throw new Error(`Cannot merge config in form of callback`);
- return mergeConfigRecursively(defaults, overrides, isRoot ? "" : ".");
-}
-function mergeAlias(a, b) {
- if (!a) return b;
- if (!b) return a;
- if (isObject(a) && isObject(b)) return {
- ...a,
- ...b
- };
- return [...normalizeAlias(b), ...normalizeAlias(a)];
-}
-function normalizeAlias(o$1 = []) {
- return Array.isArray(o$1) ? o$1.map(normalizeSingleAlias) : Object.keys(o$1).map((find$1) => normalizeSingleAlias({
- find: find$1,
- replacement: o$1[find$1]
- }));
-}
-function normalizeSingleAlias({ find: find$1, replacement, customResolver }) {
- if (typeof find$1 === "string" && find$1.endsWith("/") && replacement.endsWith("/")) {
- find$1 = find$1.slice(0, find$1.length - 1);
- replacement = replacement.slice(0, replacement.length - 1);
- }
- const alias$2 = {
- find: find$1,
- replacement
- };
- if (customResolver) alias$2.customResolver = customResolver;
- return alias$2;
-}
-/**
-* Transforms transpiled code result where line numbers aren't altered,
-* so we can skip sourcemap generation during dev
-*/
-function transformStableResult(s, id, config$2) {
- return {
- code: s.toString(),
- map: config$2.command === "build" && config$2.build.sourcemap ? s.generateMap({
- hires: "boundary",
- source: id
- }) : null
- };
-}
-async function asyncFlatten(arr) {
- do
- arr = (await Promise.all(arr)).flat(Infinity);
- while (arr.some((v) => v?.then));
- return arr;
-}
-function stripBomTag(content) {
- if (content.charCodeAt(0) === 65279) return content.slice(1);
- return content;
-}
-const windowsDrivePathPrefixRE = /^[A-Za-z]:[/\\]/;
-/**
-* path.isAbsolute also returns true for drive relative paths on windows (e.g. /something)
-* this function returns false for them but true for absolute paths (e.g. C:/something)
-*/
-const isNonDriveRelativeAbsolutePath = (p) => {
- if (!isWindows) return p[0] === "/";
- return windowsDrivePathPrefixRE.test(p);
-};
-/**
-* Determine if a file is being requested with the correct case, to ensure
-* consistent behavior between dev and prod and across operating systems.
-*/
-function shouldServeFile(filePath, root) {
- if (!isCaseInsensitiveFS) return true;
- return hasCorrectCase(filePath, root);
-}
-/**
-* Note that we can't use realpath here, because we don't want to follow
-* symlinks.
-*/
-function hasCorrectCase(file, assets) {
- if (file === assets) return true;
- const parent = path.dirname(file);
- if (fs.readdirSync(parent).includes(path.basename(file))) return hasCorrectCase(parent, assets);
- return false;
-}
-function joinUrlSegments(a, b) {
- if (!a || !b) return a || b || "";
- if (a.endsWith("/")) a = a.substring(0, a.length - 1);
- if (b[0] !== "/") b = "/" + b;
- return a + b;
-}
-function removeLeadingSlash(str) {
- return str[0] === "/" ? str.slice(1) : str;
-}
-function stripBase(path$13, base) {
- if (path$13 === base) return "/";
- const devBase = withTrailingSlash(base);
- return path$13.startsWith(devBase) ? path$13.slice(devBase.length - 1) : path$13;
-}
-function arrayEqual(a, b) {
- if (a === b) return true;
- if (a.length !== b.length) return false;
- for (let i$1 = 0; i$1 < a.length; i$1++) if (a[i$1] !== b[i$1]) return false;
- return true;
-}
-function evalValue(rawValue) {
- return new Function(`
- var console, exports, global, module, process, require
- return (\n${rawValue}\n)
- `)();
-}
-function getNpmPackageName(importPath) {
- const parts = importPath.split("/");
- if (parts[0][0] === "@") {
- if (!parts[1]) return null;
- return `${parts[0]}/${parts[1]}`;
- } else return parts[0];
-}
-function getPkgName(name) {
- return name[0] === "@" ? name.split("/")[1] : name;
-}
-const escapeRegexRE$1 = /[-/\\^$*+?.()|[\]{}]/g;
-function escapeRegex(str) {
- return str.replace(escapeRegexRE$1, "\\$&");
-}
-function getPackageManagerCommand(type = "install") {
- const packageManager = process.env.npm_config_user_agent?.split(" ")[0].split("/")[0] || "npm";
- switch (type) {
- case "install": return packageManager === "npm" ? "npm install" : `${packageManager} add`;
- case "uninstall": return packageManager === "npm" ? "npm uninstall" : `${packageManager} remove`;
- case "update": return packageManager === "yarn" ? "yarn upgrade" : `${packageManager} update`;
- default: throw new TypeError(`Unknown command type: ${type}`);
- }
-}
-function isDevServer(server) {
- return "pluginContainer" in server;
-}
-function createSerialPromiseQueue() {
- let previousTask;
- return { async run(f$1) {
- const thisTask = f$1();
- const depTasks = Promise.all([previousTask, thisTask]);
- previousTask = depTasks;
- const [, result] = await depTasks;
- if (previousTask === depTasks) previousTask = void 0;
- return result;
- } };
-}
-function sortObjectKeys(obj) {
- const sorted = {};
- for (const key of Object.keys(obj).sort()) sorted[key] = obj[key];
- return sorted;
-}
-function displayTime(time) {
- if (time < 1e3) return `${time}ms`;
- time = time / 1e3;
- if (time < 60) return `${time.toFixed(2)}s`;
- const mins = Math.floor(time / 60);
- const seconds = Math.round(time % 60);
- if (seconds === 60) return `${mins + 1}m`;
- return `${mins}m${seconds < 1 ? "" : ` ${seconds}s`}`;
-}
-/**
-* Encodes the URI path portion (ignores part after ? or #)
-*/
-function encodeURIPath(uri) {
- if (uri.startsWith("data:")) return uri;
- const filePath = cleanUrl(uri);
- const postfix = filePath !== uri ? uri.slice(filePath.length) : "";
- return encodeURI(filePath) + postfix;
-}
-/**
-* Like `encodeURIPath`, but only replacing `%` as `%25`. This is useful for environments
-* that can handle un-encoded URIs, where `%` is the only ambiguous character.
-*/
-function partialEncodeURIPath(uri) {
- if (uri.startsWith("data:")) return uri;
- const filePath = cleanUrl(uri);
- const postfix = filePath !== uri ? uri.slice(filePath.length) : "";
- return filePath.replaceAll("%", "%25") + postfix;
-}
-function decodeURIIfPossible(input) {
- try {
- return decodeURI(input);
- } catch {
- return;
- }
-}
-const sigtermCallbacks = /* @__PURE__ */ new Set();
-const parentSigtermCallback = async (signal, exitCode) => {
- await Promise.all([...sigtermCallbacks].map((cb) => cb(signal, exitCode)));
-};
-const setupSIGTERMListener = (callback) => {
- if (sigtermCallbacks.size === 0) {
- process.once("SIGTERM", parentSigtermCallback);
- if (process.env.CI !== "true") process.stdin.on("end", parentSigtermCallback);
- }
- sigtermCallbacks.add(callback);
-};
-const teardownSIGTERMListener = (callback) => {
- sigtermCallbacks.delete(callback);
- if (sigtermCallbacks.size === 0) {
- process.off("SIGTERM", parentSigtermCallback);
- if (process.env.CI !== "true") process.stdin.off("end", parentSigtermCallback);
- }
-};
-function getServerUrlByHost(resolvedUrls, host) {
- if (typeof host === "string") {
- const matchedUrl = [...resolvedUrls?.local ?? [], ...resolvedUrls?.network ?? []].find((url$3) => url$3.includes(host));
- if (matchedUrl) return matchedUrl;
- }
- return resolvedUrls?.local[0] ?? resolvedUrls?.network[0];
-}
-let lastDateNow = 0;
-/**
-* Similar to `Date.now()`, but strictly monotonically increasing.
-*
-* This function will never return the same value.
-* Thus, the value may differ from the actual time.
-*
-* related: https://github.com/vitejs/vite/issues/19804
-*/
-function monotonicDateNow() {
- const now = Date.now();
- if (now > lastDateNow) {
- lastDateNow = now;
- return lastDateNow;
- }
- lastDateNow++;
- return lastDateNow;
-}
-
-//#endregion
-//#region src/node/plugin.ts
-async function resolveEnvironmentPlugins(environment) {
- const environmentPlugins = [];
- for (const plugin of environment.getTopLevelConfig().plugins) {
- if (plugin.applyToEnvironment) {
- const applied = await plugin.applyToEnvironment(environment);
- if (!applied) continue;
- if (applied !== true) {
- environmentPlugins.push(...(await asyncFlatten(arraify(applied))).filter(Boolean));
- continue;
- }
- }
- environmentPlugins.push(plugin);
- }
- return environmentPlugins;
-}
-/**
-* @experimental
-*/
-function perEnvironmentPlugin(name, applyToEnvironment) {
- return {
- name,
- applyToEnvironment
- };
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/commondir@1.0.1/node_modules/commondir/index.js
-var require_commondir = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- var path$12 = __require("path");
- module.exports = function(basedir, relfiles) {
- if (relfiles) var files = relfiles.map(function(r$1) {
- return path$12.resolve(basedir, r$1);
- });
- else var files = basedir;
- var res = files.slice(1).reduce(function(ps, file) {
- if (!file.match(/^([A-Za-z]:)?\/|\\/)) throw new Error("relative path without a basedir");
- var xs = file.split(/\/+|\\+/);
- for (var i$1 = 0; ps[i$1] === xs[i$1] && i$1 < Math.min(ps.length, xs.length); i$1++);
- return ps.slice(0, i$1);
- }, files[0].split(/\/+|\\+/));
- return res.length > 1 ? res.join("/") : "/";
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs
-var BitSet = class BitSet {
- constructor(arg) {
- this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
- }
- add(n$2) {
- this.bits[n$2 >> 5] |= 1 << (n$2 & 31);
- }
- has(n$2) {
- return !!(this.bits[n$2 >> 5] & 1 << (n$2 & 31));
- }
-};
-var Chunk = class Chunk {
- constructor(start, end, content) {
- this.start = start;
- this.end = end;
- this.original = content;
- this.intro = "";
- this.outro = "";
- this.content = content;
- this.storeName = false;
- this.edited = false;
- this.previous = null;
- this.next = null;
- }
- appendLeft(content) {
- this.outro += content;
- }
- appendRight(content) {
- this.intro = this.intro + content;
- }
- clone() {
- const chunk = new Chunk(this.start, this.end, this.original);
- chunk.intro = this.intro;
- chunk.outro = this.outro;
- chunk.content = this.content;
- chunk.storeName = this.storeName;
- chunk.edited = this.edited;
- return chunk;
- }
- contains(index) {
- return this.start < index && index < this.end;
- }
- eachNext(fn) {
- let chunk = this;
- while (chunk) {
- fn(chunk);
- chunk = chunk.next;
- }
- }
- eachPrevious(fn) {
- let chunk = this;
- while (chunk) {
- fn(chunk);
- chunk = chunk.previous;
- }
- }
- edit(content, storeName, contentOnly) {
- this.content = content;
- if (!contentOnly) {
- this.intro = "";
- this.outro = "";
- }
- this.storeName = storeName;
- this.edited = true;
- return this;
- }
- prependLeft(content) {
- this.outro = content + this.outro;
- }
- prependRight(content) {
- this.intro = content + this.intro;
- }
- reset() {
- this.intro = "";
- this.outro = "";
- if (this.edited) {
- this.content = this.original;
- this.storeName = false;
- this.edited = false;
- }
- }
- split(index) {
- const sliceIndex = index - this.start;
- const originalBefore = this.original.slice(0, sliceIndex);
- const originalAfter = this.original.slice(sliceIndex);
- this.original = originalBefore;
- const newChunk = new Chunk(index, this.end, originalAfter);
- newChunk.outro = this.outro;
- this.outro = "";
- this.end = index;
- if (this.edited) {
- newChunk.edit("", false);
- this.content = "";
- } else this.content = originalBefore;
- newChunk.next = this.next;
- if (newChunk.next) newChunk.next.previous = newChunk;
- newChunk.previous = this;
- this.next = newChunk;
- return newChunk;
- }
- toString() {
- return this.intro + this.content + this.outro;
- }
- trimEnd(rx) {
- this.outro = this.outro.replace(rx, "");
- if (this.outro.length) return true;
- const trimmed = this.content.replace(rx, "");
- if (trimmed.length) {
- if (trimmed !== this.content) {
- this.split(this.start + trimmed.length).edit("", void 0, true);
- if (this.edited) this.edit(trimmed, this.storeName, true);
- }
- return true;
- } else {
- this.edit("", void 0, true);
- this.intro = this.intro.replace(rx, "");
- if (this.intro.length) return true;
- }
- }
- trimStart(rx) {
- this.intro = this.intro.replace(rx, "");
- if (this.intro.length) return true;
- const trimmed = this.content.replace(rx, "");
- if (trimmed.length) {
- if (trimmed !== this.content) {
- const newChunk = this.split(this.end - trimmed.length);
- if (this.edited) newChunk.edit(trimmed, this.storeName, true);
- this.edit("", void 0, true);
- }
- return true;
- } else {
- this.edit("", void 0, true);
- this.outro = this.outro.replace(rx, "");
- if (this.outro.length) return true;
- }
- }
-};
-function getBtoa() {
- if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
- else if (typeof Buffer === "function") return (str) => Buffer.from(str, "utf-8").toString("base64");
- else return () => {
- throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
- };
-}
-const btoa$1 = /* @__PURE__ */ getBtoa();
-var SourceMap = class {
- constructor(properties) {
- this.version = 3;
- this.file = properties.file;
- this.sources = properties.sources;
- this.sourcesContent = properties.sourcesContent;
- this.names = properties.names;
- this.mappings = encode$1(properties.mappings);
- if (typeof properties.x_google_ignoreList !== "undefined") this.x_google_ignoreList = properties.x_google_ignoreList;
- if (typeof properties.debugId !== "undefined") this.debugId = properties.debugId;
- }
- toString() {
- return JSON.stringify(this);
- }
- toUrl() {
- return "data:application/json;charset=utf-8;base64," + btoa$1(this.toString());
- }
-};
-function guessIndent(code) {
- const lines = code.split("\n");
- const tabbed = lines.filter((line) => /^\t+/.test(line));
- const spaced = lines.filter((line) => /^ {2,}/.test(line));
- if (tabbed.length === 0 && spaced.length === 0) return null;
- if (tabbed.length >= spaced.length) return " ";
- const min$1 = spaced.reduce((previous, current) => {
- const numSpaces = /^ +/.exec(current)[0].length;
- return Math.min(numSpaces, previous);
- }, Infinity);
- return new Array(min$1 + 1).join(" ");
-}
-function getRelativePath(from, to) {
- const fromParts = from.split(/[/\\]/);
- const toParts = to.split(/[/\\]/);
- fromParts.pop();
- while (fromParts[0] === toParts[0]) {
- fromParts.shift();
- toParts.shift();
- }
- if (fromParts.length) {
- let i$1 = fromParts.length;
- while (i$1--) fromParts[i$1] = "..";
- }
- return fromParts.concat(toParts).join("/");
-}
-const toString$1 = Object.prototype.toString;
-function isObject$2(thing) {
- return toString$1.call(thing) === "[object Object]";
-}
-function getLocator(source) {
- const originalLines = source.split("\n");
- const lineOffsets = [];
- for (let i$1 = 0, pos = 0; i$1 < originalLines.length; i$1++) {
- lineOffsets.push(pos);
- pos += originalLines[i$1].length + 1;
- }
- return function locate(index) {
- let i$1 = 0;
- let j = lineOffsets.length;
- while (i$1 < j) {
- const m = i$1 + j >> 1;
- if (index < lineOffsets[m]) j = m;
- else i$1 = m + 1;
- }
- const line = i$1 - 1;
- return {
- line,
- column: index - lineOffsets[line]
- };
- };
-}
-const wordRegex = /\w/;
-var Mappings = class {
- constructor(hires) {
- this.hires = hires;
- this.generatedCodeLine = 0;
- this.generatedCodeColumn = 0;
- this.raw = [];
- this.rawSegments = this.raw[this.generatedCodeLine] = [];
- this.pending = null;
- }
- addEdit(sourceIndex, content, loc, nameIndex) {
- if (content.length) {
- const contentLengthMinusOne = content.length - 1;
- let contentLineEnd = content.indexOf("\n", 0);
- let previousContentLineEnd = -1;
- while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
- const segment$1 = [
- this.generatedCodeColumn,
- sourceIndex,
- loc.line,
- loc.column
- ];
- if (nameIndex >= 0) segment$1.push(nameIndex);
- this.rawSegments.push(segment$1);
- this.generatedCodeLine += 1;
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
- this.generatedCodeColumn = 0;
- previousContentLineEnd = contentLineEnd;
- contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
- }
- const segment = [
- this.generatedCodeColumn,
- sourceIndex,
- loc.line,
- loc.column
- ];
- if (nameIndex >= 0) segment.push(nameIndex);
- this.rawSegments.push(segment);
- this.advance(content.slice(previousContentLineEnd + 1));
- } else if (this.pending) {
- this.rawSegments.push(this.pending);
- this.advance(content);
- }
- this.pending = null;
- }
- addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
- let originalCharIndex = chunk.start;
- let first$2 = true;
- let charInHiresBoundary = false;
- while (originalCharIndex < chunk.end) {
- if (original[originalCharIndex] === "\n") {
- loc.line += 1;
- loc.column = 0;
- this.generatedCodeLine += 1;
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
- this.generatedCodeColumn = 0;
- first$2 = true;
- charInHiresBoundary = false;
- } else {
- if (this.hires || first$2 || sourcemapLocations.has(originalCharIndex)) {
- const segment = [
- this.generatedCodeColumn,
- sourceIndex,
- loc.line,
- loc.column
- ];
- if (this.hires === "boundary") if (wordRegex.test(original[originalCharIndex])) {
- if (!charInHiresBoundary) {
- this.rawSegments.push(segment);
- charInHiresBoundary = true;
- }
- } else {
- this.rawSegments.push(segment);
- charInHiresBoundary = false;
- }
- else this.rawSegments.push(segment);
- }
- loc.column += 1;
- this.generatedCodeColumn += 1;
- first$2 = false;
- }
- originalCharIndex += 1;
- }
- this.pending = null;
- }
- advance(str) {
- if (!str) return;
- const lines = str.split("\n");
- if (lines.length > 1) {
- for (let i$1 = 0; i$1 < lines.length - 1; i$1++) {
- this.generatedCodeLine++;
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
- }
- this.generatedCodeColumn = 0;
- }
- this.generatedCodeColumn += lines[lines.length - 1].length;
- }
-};
-const n$1 = "\n";
-const warned = {
- insertLeft: false,
- insertRight: false,
- storeName: false
-};
-var MagicString = class MagicString {
- constructor(string, options$1 = {}) {
- const chunk = new Chunk(0, string.length, string);
- Object.defineProperties(this, {
- original: {
- writable: true,
- value: string
- },
- outro: {
- writable: true,
- value: ""
- },
- intro: {
- writable: true,
- value: ""
- },
- firstChunk: {
- writable: true,
- value: chunk
- },
- lastChunk: {
- writable: true,
- value: chunk
- },
- lastSearchedChunk: {
- writable: true,
- value: chunk
- },
- byStart: {
- writable: true,
- value: {}
- },
- byEnd: {
- writable: true,
- value: {}
- },
- filename: {
- writable: true,
- value: options$1.filename
- },
- indentExclusionRanges: {
- writable: true,
- value: options$1.indentExclusionRanges
- },
- sourcemapLocations: {
- writable: true,
- value: new BitSet()
- },
- storedNames: {
- writable: true,
- value: {}
- },
- indentStr: {
- writable: true,
- value: void 0
- },
- ignoreList: {
- writable: true,
- value: options$1.ignoreList
- },
- offset: {
- writable: true,
- value: options$1.offset || 0
- }
- });
- this.byStart[0] = chunk;
- this.byEnd[string.length] = chunk;
- }
- addSourcemapLocation(char) {
- this.sourcemapLocations.add(char);
- }
- append(content) {
- if (typeof content !== "string") throw new TypeError("outro content must be a string");
- this.outro += content;
- return this;
- }
- appendLeft(index, content) {
- index = index + this.offset;
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
- this._split(index);
- const chunk = this.byEnd[index];
- if (chunk) chunk.appendLeft(content);
- else this.intro += content;
- return this;
- }
- appendRight(index, content) {
- index = index + this.offset;
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
- this._split(index);
- const chunk = this.byStart[index];
- if (chunk) chunk.appendRight(content);
- else this.outro += content;
- return this;
- }
- clone() {
- const cloned = new MagicString(this.original, {
- filename: this.filename,
- offset: this.offset
- });
- let originalChunk = this.firstChunk;
- let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
- while (originalChunk) {
- cloned.byStart[clonedChunk.start] = clonedChunk;
- cloned.byEnd[clonedChunk.end] = clonedChunk;
- const nextOriginalChunk = originalChunk.next;
- const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
- if (nextClonedChunk) {
- clonedChunk.next = nextClonedChunk;
- nextClonedChunk.previous = clonedChunk;
- clonedChunk = nextClonedChunk;
- }
- originalChunk = nextOriginalChunk;
- }
- cloned.lastChunk = clonedChunk;
- if (this.indentExclusionRanges) cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
- cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
- cloned.intro = this.intro;
- cloned.outro = this.outro;
- return cloned;
- }
- generateDecodedMap(options$1) {
- options$1 = options$1 || {};
- const sourceIndex = 0;
- const names = Object.keys(this.storedNames);
- const mappings = new Mappings(options$1.hires);
- const locate = getLocator(this.original);
- if (this.intro) mappings.advance(this.intro);
- this.firstChunk.eachNext((chunk) => {
- const loc = locate(chunk.start);
- if (chunk.intro.length) mappings.advance(chunk.intro);
- if (chunk.edited) mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
- else mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
- if (chunk.outro.length) mappings.advance(chunk.outro);
- });
- if (this.outro) mappings.advance(this.outro);
- return {
- file: options$1.file ? options$1.file.split(/[/\\]/).pop() : void 0,
- sources: [options$1.source ? getRelativePath(options$1.file || "", options$1.source) : options$1.file || ""],
- sourcesContent: options$1.includeContent ? [this.original] : void 0,
- names,
- mappings: mappings.raw,
- x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
- };
- }
- generateMap(options$1) {
- return new SourceMap(this.generateDecodedMap(options$1));
- }
- _ensureindentStr() {
- if (this.indentStr === void 0) this.indentStr = guessIndent(this.original);
- }
- _getRawIndentString() {
- this._ensureindentStr();
- return this.indentStr;
- }
- getIndentString() {
- this._ensureindentStr();
- return this.indentStr === null ? " " : this.indentStr;
- }
- indent(indentStr, options$1) {
- const pattern = /^[^\r\n]/gm;
- if (isObject$2(indentStr)) {
- options$1 = indentStr;
- indentStr = void 0;
- }
- if (indentStr === void 0) {
- this._ensureindentStr();
- indentStr = this.indentStr || " ";
- }
- if (indentStr === "") return this;
- options$1 = options$1 || {};
- const isExcluded = {};
- if (options$1.exclude) (typeof options$1.exclude[0] === "number" ? [options$1.exclude] : options$1.exclude).forEach((exclusion) => {
- for (let i$1 = exclusion[0]; i$1 < exclusion[1]; i$1 += 1) isExcluded[i$1] = true;
- });
- let shouldIndentNextCharacter = options$1.indentStart !== false;
- const replacer = (match) => {
- if (shouldIndentNextCharacter) return `${indentStr}${match}`;
- shouldIndentNextCharacter = true;
- return match;
- };
- this.intro = this.intro.replace(pattern, replacer);
- let charIndex = 0;
- let chunk = this.firstChunk;
- while (chunk) {
- const end = chunk.end;
- if (chunk.edited) {
- if (!isExcluded[charIndex]) {
- chunk.content = chunk.content.replace(pattern, replacer);
- if (chunk.content.length) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
- }
- } else {
- charIndex = chunk.start;
- while (charIndex < end) {
- if (!isExcluded[charIndex]) {
- const char = this.original[charIndex];
- if (char === "\n") shouldIndentNextCharacter = true;
- else if (char !== "\r" && shouldIndentNextCharacter) {
- shouldIndentNextCharacter = false;
- if (charIndex === chunk.start) chunk.prependRight(indentStr);
- else {
- this._splitChunk(chunk, charIndex);
- chunk = chunk.next;
- chunk.prependRight(indentStr);
- }
- }
- }
- charIndex += 1;
- }
- }
- charIndex = chunk.end;
- chunk = chunk.next;
- }
- this.outro = this.outro.replace(pattern, replacer);
- return this;
- }
- insert() {
- throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
- }
- insertLeft(index, content) {
- if (!warned.insertLeft) {
- console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");
- warned.insertLeft = true;
- }
- return this.appendLeft(index, content);
- }
- insertRight(index, content) {
- if (!warned.insertRight) {
- console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");
- warned.insertRight = true;
- }
- return this.prependRight(index, content);
- }
- move(start, end, index) {
- start = start + this.offset;
- end = end + this.offset;
- index = index + this.offset;
- if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
- this._split(start);
- this._split(end);
- this._split(index);
- const first$2 = this.byStart[start];
- const last = this.byEnd[end];
- const oldLeft = first$2.previous;
- const oldRight = last.next;
- const newRight = this.byStart[index];
- if (!newRight && last === this.lastChunk) return this;
- const newLeft = newRight ? newRight.previous : this.lastChunk;
- if (oldLeft) oldLeft.next = oldRight;
- if (oldRight) oldRight.previous = oldLeft;
- if (newLeft) newLeft.next = first$2;
- if (newRight) newRight.previous = last;
- if (!first$2.previous) this.firstChunk = last.next;
- if (!last.next) {
- this.lastChunk = first$2.previous;
- this.lastChunk.next = null;
- }
- first$2.previous = newLeft;
- last.next = newRight || null;
- if (!newLeft) this.firstChunk = first$2;
- if (!newRight) this.lastChunk = last;
- return this;
- }
- overwrite(start, end, content, options$1) {
- options$1 = options$1 || {};
- return this.update(start, end, content, {
- ...options$1,
- overwrite: !options$1.contentOnly
- });
- }
- update(start, end, content, options$1) {
- start = start + this.offset;
- end = end + this.offset;
- if (typeof content !== "string") throw new TypeError("replacement content must be a string");
- if (this.original.length !== 0) {
- while (start < 0) start += this.original.length;
- while (end < 0) end += this.original.length;
- }
- if (end > this.original.length) throw new Error("end is out of bounds");
- if (start === end) throw new Error("Cannot overwrite a zero-length range – use appendLeft or prependRight instead");
- this._split(start);
- this._split(end);
- if (options$1 === true) {
- if (!warned.storeName) {
- console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
- warned.storeName = true;
- }
- options$1 = { storeName: true };
- }
- const storeName = options$1 !== void 0 ? options$1.storeName : false;
- const overwrite = options$1 !== void 0 ? options$1.overwrite : false;
- if (storeName) {
- const original = this.original.slice(start, end);
- Object.defineProperty(this.storedNames, original, {
- writable: true,
- value: true,
- enumerable: true
- });
- }
- const first$2 = this.byStart[start];
- const last = this.byEnd[end];
- if (first$2) {
- let chunk = first$2;
- while (chunk !== last) {
- if (chunk.next !== this.byStart[chunk.end]) throw new Error("Cannot overwrite across a split point");
- chunk = chunk.next;
- chunk.edit("", false);
- }
- first$2.edit(content, storeName, !overwrite);
- } else {
- const newChunk = new Chunk(start, end, "").edit(content, storeName);
- last.next = newChunk;
- newChunk.previous = last;
- }
- return this;
- }
- prepend(content) {
- if (typeof content !== "string") throw new TypeError("outro content must be a string");
- this.intro = content + this.intro;
- return this;
- }
- prependLeft(index, content) {
- index = index + this.offset;
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
- this._split(index);
- const chunk = this.byEnd[index];
- if (chunk) chunk.prependLeft(content);
- else this.intro = content + this.intro;
- return this;
- }
- prependRight(index, content) {
- index = index + this.offset;
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
- this._split(index);
- const chunk = this.byStart[index];
- if (chunk) chunk.prependRight(content);
- else this.outro = content + this.outro;
- return this;
- }
- remove(start, end) {
- start = start + this.offset;
- end = end + this.offset;
- if (this.original.length !== 0) {
- while (start < 0) start += this.original.length;
- while (end < 0) end += this.original.length;
- }
- if (start === end) return this;
- if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
- if (start > end) throw new Error("end must be greater than start");
- this._split(start);
- this._split(end);
- let chunk = this.byStart[start];
- while (chunk) {
- chunk.intro = "";
- chunk.outro = "";
- chunk.edit("");
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
- }
- return this;
- }
- reset(start, end) {
- start = start + this.offset;
- end = end + this.offset;
- if (this.original.length !== 0) {
- while (start < 0) start += this.original.length;
- while (end < 0) end += this.original.length;
- }
- if (start === end) return this;
- if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
- if (start > end) throw new Error("end must be greater than start");
- this._split(start);
- this._split(end);
- let chunk = this.byStart[start];
- while (chunk) {
- chunk.reset();
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
- }
- return this;
- }
- lastChar() {
- if (this.outro.length) return this.outro[this.outro.length - 1];
- let chunk = this.lastChunk;
- do {
- if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
- if (chunk.content.length) return chunk.content[chunk.content.length - 1];
- if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
- } while (chunk = chunk.previous);
- if (this.intro.length) return this.intro[this.intro.length - 1];
- return "";
- }
- lastLine() {
- let lineIndex = this.outro.lastIndexOf(n$1);
- if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
- let lineStr = this.outro;
- let chunk = this.lastChunk;
- do {
- if (chunk.outro.length > 0) {
- lineIndex = chunk.outro.lastIndexOf(n$1);
- if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
- lineStr = chunk.outro + lineStr;
- }
- if (chunk.content.length > 0) {
- lineIndex = chunk.content.lastIndexOf(n$1);
- if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
- lineStr = chunk.content + lineStr;
- }
- if (chunk.intro.length > 0) {
- lineIndex = chunk.intro.lastIndexOf(n$1);
- if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
- lineStr = chunk.intro + lineStr;
- }
- } while (chunk = chunk.previous);
- lineIndex = this.intro.lastIndexOf(n$1);
- if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
- return this.intro + lineStr;
- }
- slice(start = 0, end = this.original.length - this.offset) {
- start = start + this.offset;
- end = end + this.offset;
- if (this.original.length !== 0) {
- while (start < 0) start += this.original.length;
- while (end < 0) end += this.original.length;
- }
- let result = "";
- let chunk = this.firstChunk;
- while (chunk && (chunk.start > start || chunk.end <= start)) {
- if (chunk.start < end && chunk.end >= end) return result;
- chunk = chunk.next;
- }
- if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
- const startChunk = chunk;
- while (chunk) {
- if (chunk.intro && (startChunk !== chunk || chunk.start === start)) result += chunk.intro;
- const containsEnd = chunk.start < end && chunk.end >= end;
- if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
- const sliceStart = startChunk === chunk ? start - chunk.start : 0;
- const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
- result += chunk.content.slice(sliceStart, sliceEnd);
- if (chunk.outro && (!containsEnd || chunk.end === end)) result += chunk.outro;
- if (containsEnd) break;
- chunk = chunk.next;
- }
- return result;
- }
- snip(start, end) {
- const clone$1 = this.clone();
- clone$1.remove(0, start);
- clone$1.remove(end, clone$1.original.length);
- return clone$1;
- }
- _split(index) {
- if (this.byStart[index] || this.byEnd[index]) return;
- let chunk = this.lastSearchedChunk;
- let previousChunk = chunk;
- const searchForward = index > chunk.end;
- while (chunk) {
- if (chunk.contains(index)) return this._splitChunk(chunk, index);
- chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
- if (chunk === previousChunk) return;
- previousChunk = chunk;
- }
- }
- _splitChunk(chunk, index) {
- if (chunk.edited && chunk.content.length) {
- const loc = getLocator(this.original)(index);
- throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`);
- }
- const newChunk = chunk.split(index);
- this.byEnd[index] = chunk;
- this.byStart[index] = newChunk;
- this.byEnd[newChunk.end] = newChunk;
- if (chunk === this.lastChunk) this.lastChunk = newChunk;
- this.lastSearchedChunk = chunk;
- return true;
- }
- toString() {
- let str = this.intro;
- let chunk = this.firstChunk;
- while (chunk) {
- str += chunk.toString();
- chunk = chunk.next;
- }
- return str + this.outro;
- }
- isEmpty() {
- let chunk = this.firstChunk;
- do
- if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) return false;
- while (chunk = chunk.next);
- return true;
- }
- length() {
- let chunk = this.firstChunk;
- let length = 0;
- do
- length += chunk.intro.length + chunk.content.length + chunk.outro.length;
- while (chunk = chunk.next);
- return length;
- }
- trimLines() {
- return this.trim("[\\r\\n]");
- }
- trim(charType) {
- return this.trimStart(charType).trimEnd(charType);
- }
- trimEndAborted(charType) {
- const rx = /* @__PURE__ */ new RegExp((charType || "\\s") + "+$");
- this.outro = this.outro.replace(rx, "");
- if (this.outro.length) return true;
- let chunk = this.lastChunk;
- do {
- const end = chunk.end;
- const aborted = chunk.trimEnd(rx);
- if (chunk.end !== end) {
- if (this.lastChunk === chunk) this.lastChunk = chunk.next;
- this.byEnd[chunk.end] = chunk;
- this.byStart[chunk.next.start] = chunk.next;
- this.byEnd[chunk.next.end] = chunk.next;
- }
- if (aborted) return true;
- chunk = chunk.previous;
- } while (chunk);
- return false;
- }
- trimEnd(charType) {
- this.trimEndAborted(charType);
- return this;
- }
- trimStartAborted(charType) {
- const rx = /* @__PURE__ */ new RegExp("^" + (charType || "\\s") + "+");
- this.intro = this.intro.replace(rx, "");
- if (this.intro.length) return true;
- let chunk = this.firstChunk;
- do {
- const end = chunk.end;
- const aborted = chunk.trimStart(rx);
- if (chunk.end !== end) {
- if (chunk === this.lastChunk) this.lastChunk = chunk.next;
- this.byEnd[chunk.end] = chunk;
- this.byStart[chunk.next.start] = chunk.next;
- this.byEnd[chunk.next.end] = chunk.next;
- }
- if (aborted) return true;
- chunk = chunk.next;
- } while (chunk);
- return false;
- }
- trimStart(charType) {
- this.trimStartAborted(charType);
- return this;
- }
- hasChanged() {
- return this.original !== this.toString();
- }
- _replaceRegexp(searchValue, replacement) {
- function getReplacement(match, str) {
- if (typeof replacement === "string") return replacement.replace(/\$(\$|&|\d+)/g, (_, i$1) => {
- if (i$1 === "$") return "$";
- if (i$1 === "&") return match[0];
- if (+i$1 < match.length) return match[+i$1];
- return `$${i$1}`;
- });
- else return replacement(...match, match.index, str, match.groups);
- }
- function matchAll$1(re, str) {
- let match;
- const matches$2 = [];
- while (match = re.exec(str)) matches$2.push(match);
- return matches$2;
- }
- if (searchValue.global) matchAll$1(searchValue, this.original).forEach((match) => {
- if (match.index != null) {
- const replacement$1 = getReplacement(match, this.original);
- if (replacement$1 !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement$1);
- }
- });
- else {
- const match = this.original.match(searchValue);
- if (match && match.index != null) {
- const replacement$1 = getReplacement(match, this.original);
- if (replacement$1 !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement$1);
- }
- }
- return this;
- }
- _replaceString(string, replacement) {
- const { original } = this;
- const index = original.indexOf(string);
- if (index !== -1) {
- if (typeof replacement === "function") replacement = replacement(string, index, original);
- if (string !== replacement) this.overwrite(index, index + string.length, replacement);
- }
- return this;
- }
- replace(searchValue, replacement) {
- if (typeof searchValue === "string") return this._replaceString(searchValue, replacement);
- return this._replaceRegexp(searchValue, replacement);
- }
- _replaceAllString(string, replacement) {
- const { original } = this;
- const stringLength = string.length;
- for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
- const previous = original.slice(index, index + stringLength);
- let _replacement = replacement;
- if (typeof replacement === "function") _replacement = replacement(previous, index, original);
- if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
- }
- return this;
- }
- replaceAll(searchValue, replacement) {
- if (typeof searchValue === "string") return this._replaceAllString(searchValue, replacement);
- if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
- return this._replaceRegexp(searchValue, replacement);
- }
-};
-
-//#endregion
-//#region ../../node_modules/.pnpm/is-reference@1.2.1/node_modules/is-reference/dist/is-reference.js
-var require_is_reference = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- (function(global$1, factory) {
- typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global$1 = global$1 || self, global$1.isReference = factory());
- })(exports, (function() {
- "use strict";
- function isReference$1(node, parent) {
- if (node.type === "MemberExpression") return !node.computed && isReference$1(node.object, node);
- if (node.type === "Identifier") {
- if (!parent) return true;
- switch (parent.type) {
- case "MemberExpression": return parent.computed || node === parent.object;
- case "MethodDefinition": return parent.computed;
- case "FieldDefinition": return parent.computed || node === parent.value;
- case "Property": return parent.computed || node === parent.value;
- case "ExportSpecifier":
- case "ImportSpecifier": return node === parent.local;
- case "LabeledStatement":
- case "BreakStatement":
- case "ContinueStatement": return false;
- default: return true;
- }
- }
- return false;
- }
- return isReference$1;
- }));
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/@rollup+plugin-commonjs@29.0.0_rollup@4.43.0/node_modules/@rollup/plugin-commonjs/dist/es/index.js
-var import_commondir = /* @__PURE__ */ __toESM(require_commondir(), 1);
-var import_is_reference = /* @__PURE__ */ __toESM(require_is_reference(), 1);
-var version$1 = "29.0.0";
-var peerDependencies = { rollup: "^2.68.0||^3.0.0||^4.0.0" };
-function tryParse(parse$15, code, id) {
- try {
- return parse$15(code, { allowReturnOutsideFunction: true });
- } catch (err$2) {
- err$2.message += ` in ${id}`;
- throw err$2;
- }
-}
-const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
-const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
-function hasCjsKeywords(code, ignoreGlobal) {
- return (ignoreGlobal ? firstpassNoGlobal : firstpassGlobal).test(code);
-}
-function analyzeTopLevelStatements(parse$15, code, id) {
- const ast = tryParse(parse$15, code, id);
- let isEsModule = false;
- let hasDefaultExport = false;
- let hasNamedExports = false;
- for (const node of ast.body) switch (node.type) {
- case "ExportDefaultDeclaration":
- isEsModule = true;
- hasDefaultExport = true;
- break;
- case "ExportNamedDeclaration":
- isEsModule = true;
- if (node.declaration) hasNamedExports = true;
- else for (const specifier of node.specifiers) if (specifier.exported.name === "default") hasDefaultExport = true;
- else hasNamedExports = true;
- break;
- case "ExportAllDeclaration":
- isEsModule = true;
- if (node.exported && node.exported.name === "default") hasDefaultExport = true;
- else hasNamedExports = true;
- break;
- case "ImportDeclaration":
- isEsModule = true;
- break;
- }
- return {
- isEsModule,
- hasDefaultExport,
- hasNamedExports,
- ast
- };
-}
-function deconflict(scopes, globals, identifier) {
- let i$1 = 1;
- let deconflicted = makeLegalIdentifier(identifier);
- const hasConflicts = () => scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);
- while (hasConflicts()) {
- deconflicted = makeLegalIdentifier(`${identifier}_${i$1}`);
- i$1 += 1;
- }
- for (const scope of scopes) scope.declarations[deconflicted] = true;
- return deconflicted;
-}
-function getName(id) {
- const name = makeLegalIdentifier(basename$1(id, extname$1(id)));
- if (name !== "index") return name;
- return makeLegalIdentifier(basename$1(dirname$1(id)));
-}
-function normalizePathSlashes(path$13) {
- return path$13.replace(/\\/g, "/");
-}
-const getVirtualPathForDynamicRequirePath = (path$13, commonDir) => `/${normalizePathSlashes(relative$1(commonDir, path$13))}`;
-function capitalize(name) {
- return name[0].toUpperCase() + name.slice(1);
-}
-function getStrictRequiresFilter({ strictRequires }) {
- switch (strictRequires) {
- case void 0:
- case true: return {
- strictRequiresFilter: () => true,
- detectCyclesAndConditional: false
- };
- case "auto":
- case "debug":
- case null: return {
- strictRequiresFilter: () => false,
- detectCyclesAndConditional: true
- };
- case false: return {
- strictRequiresFilter: () => false,
- detectCyclesAndConditional: false
- };
- default:
- if (typeof strictRequires === "string" || Array.isArray(strictRequires)) return {
- strictRequiresFilter: createFilter$2(strictRequires),
- detectCyclesAndConditional: false
- };
- throw new Error("Unexpected value for \"strictRequires\" option.");
- }
-}
-function getPackageEntryPoint(dirPath) {
- let entryPoint = "index.js";
- try {
- if (existsSync$1(join$1(dirPath, "package.json"))) entryPoint = JSON.parse(readFileSync$1(join$1(dirPath, "package.json"), { encoding: "utf8" })).main || entryPoint;
- } catch (ignored) {}
- return entryPoint;
-}
-function isDirectory$1(path$13) {
- try {
- if (statSync(path$13).isDirectory()) return true;
- } catch (ignored) {}
- return false;
-}
-function getDynamicRequireModules(patterns, dynamicRequireRoot) {
- const dynamicRequireModules = /* @__PURE__ */ new Map();
- const dirNames = /* @__PURE__ */ new Set();
- for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
- const isNegated = pattern.startsWith("!");
- const modifyMap = (targetPath, resolvedPath) => isNegated ? dynamicRequireModules.delete(targetPath) : dynamicRequireModules.set(targetPath, resolvedPath);
- for (const path$13 of new fdir().withBasePath().withDirs().glob(isNegated ? pattern.substr(1) : pattern).crawl(relative$1(".", dynamicRequireRoot)).sync().sort((a, b) => a.localeCompare(b, "en"))) {
- const resolvedPath = resolve$1(path$13);
- const requirePath = normalizePathSlashes(resolvedPath);
- if (isDirectory$1(resolvedPath)) {
- dirNames.add(resolvedPath);
- const modulePath = resolve$1(join$1(resolvedPath, getPackageEntryPoint(path$13)));
- modifyMap(requirePath, modulePath);
- modifyMap(normalizePathSlashes(modulePath), modulePath);
- } else {
- dirNames.add(dirname$1(resolvedPath));
- modifyMap(requirePath, resolvedPath);
- }
- }
- }
- return {
- commonDir: dirNames.size ? (0, import_commondir.default)([...dirNames, dynamicRequireRoot]) : null,
- dynamicRequireModules
- };
-}
-const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
-const COMMONJS_REQUIRE_EXPORT = "commonjsRequire";
-const CREATE_COMMONJS_REQUIRE_EXPORT = "createCommonjsRequire";
-function getDynamicModuleRegistry(isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ignoreDynamicRequires) {
- if (!isDynamicRequireModulesEnabled) return `export function ${COMMONJS_REQUIRE_EXPORT}(path) {
- ${FAILED_REQUIRE_ERROR}
-}`;
- return `${[...dynamicRequireModules.values()].map((id, index) => `import ${id.endsWith(".json") ? `json${index}` : `{ __require as require${index} }`} from ${JSON.stringify(id)};`).join("\n")}
-
-var dynamicModules;
-
-function getDynamicModules() {
- return dynamicModules || (dynamicModules = {
-${[...dynamicRequireModules.keys()].map((id, index) => `\t\t${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${id.endsWith(".json") ? `function () { return json${index}; }` : `require${index}`}`).join(",\n")}
- });
-}
-
-export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) {
- function handleRequire(path) {
- var resolvedPath = commonjsResolve(path, originalModuleDir);
- if (resolvedPath !== null) {
- return getDynamicModules()[resolvedPath]();
- }
- ${ignoreDynamicRequires ? "return require(path);" : FAILED_REQUIRE_ERROR}
- }
- handleRequire.resolve = function (path) {
- var resolvedPath = commonjsResolve(path, originalModuleDir);
- if (resolvedPath !== null) {
- return resolvedPath;
- }
- return require.resolve(path);
- }
- return handleRequire;
-}
-
-function commonjsResolve (path, originalModuleDir) {
- var shouldTryNodeModules = isPossibleNodeModulesPath(path);
- path = normalize(path);
- var relPath;
- if (path[0] === '/') {
- originalModuleDir = '';
- }
- var modules = getDynamicModules();
- var checkedExtensions = ['', '.js', '.json'];
- while (true) {
- if (!shouldTryNodeModules) {
- relPath = normalize(originalModuleDir + '/' + path);
- } else {
- relPath = normalize(originalModuleDir + '/node_modules/' + path);
- }
-
- if (relPath.endsWith('/..')) {
- break; // Travelled too far up, avoid infinite loop
- }
-
- for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {
- var resolvedPath = relPath + checkedExtensions[extensionIndex];
- if (modules[resolvedPath]) {
- return resolvedPath;
- }
- }
- if (!shouldTryNodeModules) break;
- var nextDir = normalize(originalModuleDir + '/..');
- if (nextDir === originalModuleDir) break;
- originalModuleDir = nextDir;
- }
- return null;
-}
-
-function isPossibleNodeModulesPath (modulePath) {
- var c0 = modulePath[0];
- if (c0 === '/' || c0 === '\\\\') return false;
- var c1 = modulePath[1], c2 = modulePath[2];
- if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
- (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
- if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;
- return true;
-}
-
-function normalize (path) {
- path = path.replace(/\\\\/g, '/');
- var parts = path.split('/');
- var slashed = parts[0] === '';
- for (var i = 1; i < parts.length; i++) {
- if (parts[i] === '.' || parts[i] === '') {
- parts.splice(i--, 1);
- }
- }
- for (var i = 1; i < parts.length; i++) {
- if (parts[i] !== '..') continue;
- if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
- parts.splice(--i, 2);
- i--;
- }
- }
- path = parts.join('/');
- if (slashed && path[0] !== '/') path = '/' + path;
- else if (path.length === 0) path = '.';
- return path;
-}`;
-}
-const isWrappedId = (id, suffix) => id.endsWith(suffix);
-const wrapId$1 = (id, suffix) => `\0${id}${suffix}`;
-const unwrapId$1 = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
-const PROXY_SUFFIX = "?commonjs-proxy";
-const WRAPPED_SUFFIX = "?commonjs-wrapped";
-const EXTERNAL_SUFFIX = "?commonjs-external";
-const EXPORTS_SUFFIX = "?commonjs-exports";
-const MODULE_SUFFIX = "?commonjs-module";
-const ENTRY_SUFFIX = "?commonjs-entry";
-const ES_IMPORT_SUFFIX = "?commonjs-es-import";
-const DYNAMIC_MODULES_ID = "\0commonjs-dynamic-modules";
-const HELPERS_ID = "\0commonjsHelpers.js";
-const IS_WRAPPED_COMMONJS = "withRequireFunction";
-const HELPERS = `
-export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
-
-export function getDefaultExportFromCjs (x) {
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
-}
-
-export function getDefaultExportFromNamespaceIfPresent (n) {
- return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
-}
-
-export function getDefaultExportFromNamespaceIfNotNamed (n) {
- return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
-}
-
-export function getAugmentedNamespace(n) {
- if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
- var f = n.default;
- if (typeof f == "function") {
- var a = function a () {
- var isInstance = false;
- try {
- isInstance = this instanceof a;
- } catch {}
- if (isInstance) {
- return Reflect.construct(f, arguments, this.constructor);
- }
- return f.apply(this, arguments);
- };
- a.prototype = f.prototype;
- } else a = {};
- Object.defineProperty(a, '__esModule', {value: true});
- Object.keys(n).forEach(function (k) {
- var d = Object.getOwnPropertyDescriptor(n, k);
- Object.defineProperty(a, k, d.get ? d : {
- enumerable: true,
- get: function () {
- return n[k];
- }
- });
- });
- return a;
-}
-`;
-function getHelpersModule() {
- return HELPERS;
-}
-function getUnknownRequireProxy(id, requireReturnsDefault) {
- if (requireReturnsDefault === true || id.endsWith(".json")) return `export { default } from ${JSON.stringify(id)};`;
- const name = getName(id);
- const exported = requireReturnsDefault === "auto" ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});` : requireReturnsDefault === "preferred" ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});` : !requireReturnsDefault ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});` : `export default ${name};`;
- return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
-}
-async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) {
- const name = getName(id);
- const { meta: { commonjs: commonjsMeta } } = await loadModule({ id });
- if (!commonjsMeta) return getUnknownRequireProxy(id, requireReturnsDefault);
- if (commonjsMeta.isCommonJS) return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
- if (!requireReturnsDefault) return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(id)}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
- if (requireReturnsDefault !== true && (requireReturnsDefault === "namespace" || !commonjsMeta.hasDefaultExport || requireReturnsDefault === "auto" && commonjsMeta.hasNamedExports)) return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
- return `export { default } from ${JSON.stringify(id)};`;
-}
-function getEntryProxy(id, defaultIsModuleExports, getModuleInfo, shebang) {
- const { meta: { commonjs: commonjsMeta }, hasDefaultExport } = getModuleInfo(id);
- if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) {
- const stringifiedId = JSON.stringify(id);
- let code = `export * from ${stringifiedId};`;
- if (hasDefaultExport) code += `export { default } from ${stringifiedId};`;
- return shebang + code;
- }
- const result = getEsImportProxy(id, defaultIsModuleExports, true);
- return {
- ...result,
- code: shebang + result.code
- };
-}
-function getEsImportProxy(id, defaultIsModuleExports, moduleSideEffects) {
- const name = getName(id);
- const exportsName = `${name}Exports`;
- const requireModule = `require${capitalize(name)}`;
- let code = `import { getDefaultExportFromCjs } from "${HELPERS_ID}";\nimport { __require as ${requireModule} } from ${JSON.stringify(id)};\nvar ${exportsName} = ${moduleSideEffects ? "" : "/*@__PURE__*/ "}${requireModule}();\nexport { ${exportsName} as __moduleExports };`;
- if (defaultIsModuleExports === true) code += `\nexport { ${exportsName} as default };`;
- else if (defaultIsModuleExports === false) code += `\nexport default ${exportsName}.default;`;
- else code += `\nexport default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`;
- return {
- code,
- syntheticNamedExports: "__moduleExports"
- };
-}
-function getExternalBuiltinRequireProxy(id) {
- return `import { createRequire } from 'node:module';
-const require = createRequire(import.meta.url);
-export function __require() { return require(${JSON.stringify(id)}); }`;
-}
-function getCandidatesForExtension(resolved, extension$1) {
- return [resolved + extension$1, `${resolved}${sep$1}index${extension$1}`];
-}
-function getCandidates(resolved, extensions$1) {
- return extensions$1.reduce((paths, extension$1) => paths.concat(getCandidatesForExtension(resolved, extension$1)), [resolved]);
-}
-function resolveExtensions(importee, importer, extensions$1) {
- if (importee[0] !== "." || !importer) return void 0;
- const candidates = getCandidates(resolve$1(dirname$1(importer), importee), extensions$1);
- for (let i$1 = 0; i$1 < candidates.length; i$1 += 1) try {
- if (statSync(candidates[i$1]).isFile()) return { id: candidates[i$1] };
- } catch (err$2) {}
-}
-function getResolveId(extensions$1, isPossibleCjsId) {
- const currentlyResolving = /* @__PURE__ */ new Map();
- return {
- currentlyResolving,
- async resolveId(importee, importer, resolveOptions) {
- if (resolveOptions.custom?.["node-resolve"]?.isRequire) return null;
- const currentlyResolvingForParent = currentlyResolving.get(importer);
- if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) {
- this.warn({
- code: "THIS_RESOLVE_WITHOUT_OPTIONS",
- message: "It appears a plugin has implemented a \"resolveId\" hook that uses \"this.resolve\" without forwarding the third \"options\" parameter of \"resolveId\". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.",
- url: "https://rollupjs.org/guide/en/#resolveid"
- });
- return null;
- }
- if (isWrappedId(importee, WRAPPED_SUFFIX)) return unwrapId$1(importee, WRAPPED_SUFFIX);
- if (importee.endsWith(ENTRY_SUFFIX) || isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX) || isWrappedId(importee, PROXY_SUFFIX) || isWrappedId(importee, ES_IMPORT_SUFFIX) || isWrappedId(importee, EXTERNAL_SUFFIX) || importee.startsWith(HELPERS_ID) || importee === DYNAMIC_MODULES_ID) return importee;
- if (importer) {
- if (importer === DYNAMIC_MODULES_ID || isWrappedId(importer, PROXY_SUFFIX) || isWrappedId(importer, ES_IMPORT_SUFFIX) || importer.endsWith(ENTRY_SUFFIX)) return importee;
- if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
- if (!await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions))) return null;
- return {
- id: importee,
- external: true
- };
- }
- }
- if (importee.startsWith("\0")) return null;
- const resolved = await this.resolve(importee, importer, Object.assign({ skipSelf: true }, resolveOptions)) || resolveExtensions(importee, importer, extensions$1);
- if (!resolved || resolved.external || resolved.id.endsWith(ENTRY_SUFFIX) || isWrappedId(resolved.id, ES_IMPORT_SUFFIX) || !isPossibleCjsId(resolved.id)) return resolved;
- const moduleInfo = await this.load(resolved);
- const { meta: { commonjs: commonjsMeta } } = moduleInfo;
- if (commonjsMeta) {
- const { isCommonJS } = commonjsMeta;
- if (isCommonJS) {
- if (resolveOptions.isEntry) {
- moduleInfo.moduleSideEffects = true;
- return resolved.id + ENTRY_SUFFIX;
- }
- if (isCommonJS === IS_WRAPPED_COMMONJS) return {
- id: wrapId$1(resolved.id, ES_IMPORT_SUFFIX),
- meta: { commonjs: { resolved } }
- };
- }
- }
- return resolved;
- }
- };
-}
-function getRequireResolver(extensions$1, detectCyclesAndConditional, currentlyResolving, requireNodeBuiltins) {
- const knownCjsModuleTypes = Object.create(null);
- const requiredIds = Object.create(null);
- const unconditionallyRequiredIds = Object.create(null);
- const dependencies = Object.create(null);
- const getDependencies = (id) => dependencies[id] || (dependencies[id] = /* @__PURE__ */ new Set());
- const isCyclic = (id) => {
- const dependenciesToCheck = new Set(getDependencies(id));
- for (const dependency of dependenciesToCheck) {
- if (dependency === id) return true;
- for (const childDependency of getDependencies(dependency)) dependenciesToCheck.add(childDependency);
- }
- return false;
- };
- const fullyAnalyzedModules = Object.create(null);
- const getTypeForFullyAnalyzedModule = (id) => {
- const knownType = knownCjsModuleTypes[id];
- if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) return knownType;
- if (isCyclic(id)) return knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
- return knownType;
- };
- const setInitialParentType = (id, initialCommonJSType) => {
- if (fullyAnalyzedModules[id]) return;
- knownCjsModuleTypes[id] = initialCommonJSType;
- if (detectCyclesAndConditional && knownCjsModuleTypes[id] === true && requiredIds[id] && !unconditionallyRequiredIds[id]) knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
- };
- const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => {
- const childId = resolved.id;
- requiredIds[childId] = true;
- if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) unconditionallyRequiredIds[childId] = true;
- getDependencies(parentId).add(childId);
- if (!isCyclic(childId)) await loadModule(resolved);
- };
- const getTypeForImportedModule = async (resolved, loadModule) => {
- if (resolved.id in knownCjsModuleTypes) return knownCjsModuleTypes[resolved.id];
- const { meta: { commonjs: commonjs$1 } } = await loadModule(resolved);
- return commonjs$1 && commonjs$1.isCommonJS || false;
- };
- return {
- getWrappedIds: () => Object.keys(knownCjsModuleTypes).filter((id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS),
- isRequiredId: (id) => requiredIds[id],
- async shouldTransformCachedModule({ id: parentId, resolvedSources, meta: { commonjs: parentMeta } }) {
- if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false;
- if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false;
- const parentRequires = parentMeta && parentMeta.requires;
- if (parentRequires) {
- setInitialParentType(parentId, parentMeta.initialCommonJSType);
- await Promise.all(parentRequires.map(({ resolved, isConditional }) => analyzeRequiredModule(parentId, resolved, isConditional, this.load)));
- if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) return true;
- for (const { resolved: { id } } of parentRequires) if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) return true;
- fullyAnalyzedModules[parentId] = true;
- for (const { resolved: { id } } of parentRequires) fullyAnalyzedModules[id] = true;
- }
- const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id));
- return (await Promise.all(Object.keys(resolvedSources).map((source) => resolvedSources[source]).filter(({ id, external }) => !(external || parentRequireSet.has(id))).map(async (resolved) => {
- if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) return await getTypeForImportedModule((await this.load(resolved)).meta.commonjs.resolved, this.load) !== IS_WRAPPED_COMMONJS;
- return await getTypeForImportedModule(resolved, this.load) === IS_WRAPPED_COMMONJS;
- }))).some((shouldTransform) => shouldTransform);
- },
- resolveRequireSourcesAndUpdateMeta: (rollupContext) => async (parentId, isParentCommonJS, parentMeta, sources) => {
- parentMeta.initialCommonJSType = isParentCommonJS;
- parentMeta.requires = [];
- parentMeta.isRequiredCommonJS = Object.create(null);
- setInitialParentType(parentId, isParentCommonJS);
- const currentlyResolvingForParent = currentlyResolving.get(parentId) || /* @__PURE__ */ new Set();
- currentlyResolving.set(parentId, currentlyResolvingForParent);
- const requireTargets = await Promise.all(sources.map(async ({ source, isConditional }) => {
- if (source.startsWith("\0")) return {
- id: source,
- allowProxy: false
- };
- currentlyResolvingForParent.add(source);
- const resolved = await rollupContext.resolve(source, parentId, {
- skipSelf: false,
- custom: { "node-resolve": { isRequire: true } }
- }) || resolveExtensions(source, parentId, extensions$1);
- currentlyResolvingForParent.delete(source);
- if (!resolved) return {
- id: wrapId$1(source, EXTERNAL_SUFFIX),
- allowProxy: false
- };
- const childId = resolved.id;
- if (resolved.external) return {
- id: wrapId$1(childId, EXTERNAL_SUFFIX),
- allowProxy: false
- };
- parentMeta.requires.push({
- resolved,
- isConditional
- });
- await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load);
- return {
- id: childId,
- allowProxy: true
- };
- }));
- parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
- fullyAnalyzedModules[parentId] = true;
- return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
- let isCommonJS = parentMeta.isRequiredCommonJS[dependencyId] = getTypeForFullyAnalyzedModule(dependencyId);
- const isExternalWrapped = isWrappedId(dependencyId, EXTERNAL_SUFFIX);
- let resolvedDependencyId = dependencyId;
- if (requireNodeBuiltins === true) {
- if (parentMeta.isCommonJS === IS_WRAPPED_COMMONJS && !allowProxy && isExternalWrapped) {
- if (unwrapId$1(dependencyId, EXTERNAL_SUFFIX).startsWith("node:")) {
- isCommonJS = IS_WRAPPED_COMMONJS;
- parentMeta.isRequiredCommonJS[dependencyId] = isCommonJS;
- }
- } else if (isExternalWrapped && !allowProxy) {
- const actualExternalId = unwrapId$1(dependencyId, EXTERNAL_SUFFIX);
- if (actualExternalId.startsWith("node:")) resolvedDependencyId = actualExternalId;
- }
- }
- const isWrappedCommonJS = isCommonJS === IS_WRAPPED_COMMONJS;
- fullyAnalyzedModules[dependencyId] = true;
- const moduleInfo = isWrappedCommonJS && !isExternalWrapped ? rollupContext.getModuleInfo(dependencyId) : null;
- return {
- wrappedModuleSideEffects: !isWrappedCommonJS ? false : moduleInfo?.moduleSideEffects ?? true,
- source: sources[index].source,
- id: allowProxy ? wrapId$1(resolvedDependencyId, isWrappedCommonJS ? WRAPPED_SUFFIX : PROXY_SUFFIX) : resolvedDependencyId,
- isCommonJS
- };
- });
- },
- isCurrentlyResolving(source, parentId) {
- const currentlyResolvingForParent = currentlyResolving.get(parentId);
- return currentlyResolvingForParent && currentlyResolvingForParent.has(source);
- }
- };
-}
-function validateVersion(actualVersion, peerDependencyVersion, name) {
- const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
- let minMajor = Infinity;
- let minMinor = Infinity;
- let minPatch = Infinity;
- let foundVersion;
- while (foundVersion = versionRegexp.exec(peerDependencyVersion)) {
- const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split(".").map(Number);
- if (foundMajor < minMajor) {
- minMajor = foundMajor;
- minMinor = foundMinor;
- minPatch = foundPatch;
- }
- }
- if (!actualVersion) throw new Error(`Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.`);
- const [major, minor, patch] = actualVersion.split(".").map(Number);
- if (major < minMajor || major === minMajor && (minor < minMinor || minor === minMinor && patch < minPatch)) throw new Error(`Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.`);
-}
-const operators = {
- "==": (x) => equals(x.left, x.right, false),
- "!=": (x) => not(operators["=="](x)),
- "===": (x) => equals(x.left, x.right, true),
- "!==": (x) => not(operators["==="](x)),
- "!": (x) => isFalsy(x.argument),
- "&&": (x) => isTruthy(x.left) && isTruthy(x.right),
- "||": (x) => isTruthy(x.left) || isTruthy(x.right)
-};
-function not(value$1) {
- return value$1 === null ? value$1 : !value$1;
-}
-function equals(a, b, strict) {
- if (a.type !== b.type) return null;
- if (a.type === "Literal") return strict ? a.value === b.value : a.value == b.value;
- return null;
-}
-function isTruthy(node) {
- if (!node) return false;
- if (node.type === "Literal") return !!node.value;
- if (node.type === "ParenthesizedExpression") return isTruthy(node.expression);
- if (node.operator in operators) return operators[node.operator](node);
- return null;
-}
-function isFalsy(node) {
- return not(isTruthy(node));
-}
-function getKeypath(node) {
- const parts = [];
- while (node.type === "MemberExpression") {
- if (node.computed) return null;
- parts.unshift(node.property.name);
- node = node.object;
- }
- if (node.type !== "Identifier") return null;
- const { name } = node;
- parts.unshift(name);
- return {
- name,
- keypath: parts.join(".")
- };
-}
-const KEY_COMPILED_ESM = "__esModule";
-function getDefineCompiledEsmType(node) {
- const definedPropertyWithExports = getDefinePropertyCallName(node, "exports");
- const definedProperty = definedPropertyWithExports || getDefinePropertyCallName(node, "module.exports");
- if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) return isTruthy(definedProperty.value) ? definedPropertyWithExports ? "exports" : "module" : false;
- return false;
-}
-function getDefinePropertyCallName(node, targetName) {
- const { callee: { object, property } } = node;
- if (!object || object.type !== "Identifier" || object.name !== "Object") return;
- if (!property || property.type !== "Identifier" || property.name !== "defineProperty") return;
- if (node.arguments.length !== 3) return;
- const targetNames = targetName.split(".");
- const [target, key, value$1] = node.arguments;
- if (targetNames.length === 1) {
- if (target.type !== "Identifier" || target.name !== targetNames[0]) return;
- }
- if (targetNames.length === 2) {
- if (target.type !== "MemberExpression" || target.object.name !== targetNames[0] || target.property.name !== targetNames[1]) return;
- }
- if (value$1.type !== "ObjectExpression" || !value$1.properties) return;
- const valueProperty = value$1.properties.find((p) => p.key && p.key.name === "value");
- if (!valueProperty || !valueProperty.value) return;
- return {
- key: key.value,
- value: valueProperty.value
- };
-}
-function isShorthandProperty(parent) {
- return parent && parent.type === "Property" && parent.shorthand;
-}
-function wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges) {
- const args = [];
- const passedArgs = [];
- if (uses.module) {
- args.push("module");
- passedArgs.push(moduleName);
- }
- if (uses.exports) {
- args.push("exports");
- passedArgs.push(uses.module ? `${moduleName}.exports` : exportsName);
- }
- magicString.trim().indent(" ", { exclude: indentExclusionRanges }).prepend(`(function (${args.join(", ")}) {\n`).append(` \n} (${passedArgs.join(", ")}));`);
-}
-function rewriteExportsAndGetExportsBlock(magicString, moduleName, exportsName, exportedExportsName, wrapped, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsAssignmentsByName, topLevelAssignments, defineCompiledEsmExpressions, deconflictedExportNames, code, HELPERS_NAME, exportMode, defaultIsModuleExports, usesRequireWrapper, requireName) {
- const exports$1 = [];
- const exportDeclarations = [];
- if (usesRequireWrapper) getExportsWhenUsingRequireWrapper(magicString, wrapped, exportMode, exports$1, moduleExportsAssignments, exportsAssignmentsByName, moduleName, exportsName, requireName, defineCompiledEsmExpressions);
- else if (exportMode === "replace") getExportsForReplacedModuleExports(magicString, exports$1, exportDeclarations, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsName, defaultIsModuleExports, HELPERS_NAME);
- else {
- if (exportMode === "module") {
- exportDeclarations.push(`var ${exportedExportsName} = ${moduleName}.exports`);
- exports$1.push(`${exportedExportsName} as __moduleExports`);
- } else exports$1.push(`${exportsName} as __moduleExports`);
- if (wrapped) exportDeclarations.push(getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME));
- else getExports(magicString, exports$1, exportDeclarations, moduleExportsAssignments, exportsAssignmentsByName, deconflictedExportNames, topLevelAssignments, moduleName, exportsName, exportedExportsName, defineCompiledEsmExpressions, HELPERS_NAME, defaultIsModuleExports, exportMode);
- }
- if (exports$1.length) exportDeclarations.push(`export { ${exports$1.join(", ")} }`);
- return `\n\n${exportDeclarations.join(";\n")};`;
-}
-function getExportsWhenUsingRequireWrapper(magicString, wrapped, exportMode, exports$1, moduleExportsAssignments, exportsAssignmentsByName, moduleName, exportsName, requireName, defineCompiledEsmExpressions) {
- exports$1.push(`${requireName} as __require`);
- if (wrapped) return;
- if (exportMode === "replace") rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName);
- else {
- rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, `${moduleName}.exports`);
- for (const [exportName, { nodes }] of exportsAssignmentsByName) for (const { node, type } of nodes) magicString.overwrite(node.start, node.left.end, `${exportMode === "module" && type === "module" ? `${moduleName}.exports` : exportsName}.${exportName}`);
- replaceDefineCompiledEsmExpressionsAndGetIfRestorable(defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName);
- }
-}
-function getExportsForReplacedModuleExports(magicString, exports$1, exportDeclarations, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsName, defaultIsModuleExports, HELPERS_NAME) {
- for (const { left } of moduleExportsAssignments) magicString.overwrite(left.start, left.end, exportsName);
- magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, "var ");
- exports$1.push(`${exportsName} as __moduleExports`);
- exportDeclarations.push(getDefaultExportDeclaration(exportsName, defaultIsModuleExports, HELPERS_NAME));
-}
-function getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) {
- return `export default ${defaultIsModuleExports === true ? exportedExportsName : defaultIsModuleExports === false ? `${exportedExportsName}.default` : `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportedExportsName})`}`;
-}
-function getExports(magicString, exports$1, exportDeclarations, moduleExportsAssignments, exportsAssignmentsByName, deconflictedExportNames, topLevelAssignments, moduleName, exportsName, exportedExportsName, defineCompiledEsmExpressions, HELPERS_NAME, defaultIsModuleExports, exportMode) {
- let deconflictedDefaultExportName;
- for (const { left } of moduleExportsAssignments) magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
- for (const [exportName, { nodes }] of exportsAssignmentsByName) {
- const deconflicted = deconflictedExportNames[exportName];
- let needsDeclaration = true;
- for (const { node, type } of nodes) {
- let replacement = `${deconflicted} = ${exportMode === "module" && type === "module" ? `${moduleName}.exports` : exportsName}.${exportName}`;
- if (needsDeclaration && topLevelAssignments.has(node)) {
- replacement = `var ${replacement}`;
- needsDeclaration = false;
- }
- magicString.overwrite(node.start, node.left.end, replacement);
- }
- if (needsDeclaration) magicString.prepend(`var ${deconflicted};\n`);
- if (exportName === "default") deconflictedDefaultExportName = deconflicted;
- else exports$1.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);
- }
- const isRestorableCompiledEsm = replaceDefineCompiledEsmExpressionsAndGetIfRestorable(defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName);
- if (defaultIsModuleExports === false || defaultIsModuleExports === "auto" && isRestorableCompiledEsm && moduleExportsAssignments.length === 0) exports$1.push(`${deconflictedDefaultExportName || exportedExportsName} as default`);
- else if (defaultIsModuleExports === true || !isRestorableCompiledEsm && moduleExportsAssignments.length === 0) exports$1.push(`${exportedExportsName} as default`);
- else exportDeclarations.push(getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME));
-}
-function rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName) {
- for (const { left } of moduleExportsAssignments) magicString.overwrite(left.start, left.end, exportsName);
-}
-function replaceDefineCompiledEsmExpressionsAndGetIfRestorable(defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName) {
- let isRestorableCompiledEsm = false;
- for (const { node, type } of defineCompiledEsmExpressions) {
- isRestorableCompiledEsm = true;
- const moduleExportsExpression = node.type === "CallExpression" ? node.arguments[0] : node.left.object;
- magicString.overwrite(moduleExportsExpression.start, moduleExportsExpression.end, exportMode === "module" && type === "module" ? `${moduleName}.exports` : exportsName);
- }
- return isRestorableCompiledEsm;
-}
-function isRequireExpression(node, scope) {
- if (!node) return false;
- if (node.type !== "CallExpression") return false;
- if (node.arguments.length === 0) return false;
- return isRequire(node.callee, scope);
-}
-function isRequire(node, scope) {
- return node.type === "Identifier" && node.name === "require" && !scope.contains("require") || node.type === "MemberExpression" && isModuleRequire(node, scope);
-}
-function isModuleRequire({ object, property }, scope) {
- return object.type === "Identifier" && object.name === "module" && property.type === "Identifier" && property.name === "require" && !scope.contains("module");
-}
-function hasDynamicArguments(node) {
- return node.arguments.length > 1 || node.arguments[0].type !== "Literal" && (node.arguments[0].type !== "TemplateLiteral" || node.arguments[0].expressions.length > 0);
-}
-const reservedMethod = {
- resolve: true,
- cache: true,
- main: true
-};
-function isNodeRequirePropertyAccess(parent) {
- return parent && parent.property && reservedMethod[parent.property.name];
-}
-function getRequireStringArg(node) {
- return node.arguments[0].type === "Literal" ? node.arguments[0].value : node.arguments[0].quasis[0].value.cooked;
-}
-function getRequireHandlers() {
- const requireExpressions = [];
- function addRequireExpression(sourceId, node, scope, usesReturnValue, isInsideTryBlock, isInsideConditional, toBeRemoved) {
- requireExpressions.push({
- sourceId,
- node,
- scope,
- usesReturnValue,
- isInsideTryBlock,
- isInsideConditional,
- toBeRemoved
- });
- }
- async function rewriteRequireExpressionsAndGetImportBlock(magicString, topLevelDeclarations, reassignedNames, helpersName, dynamicRequireName, moduleName, exportsName, id, exportMode, resolveRequireSourcesAndUpdateMeta, needsRequireWrapper, isEsModule, isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, commonjsMeta) {
- const imports = [];
- imports.push(`import * as ${helpersName} from "${HELPERS_ID}"`);
- if (dynamicRequireName) imports.push(`import { ${isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT} as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}"`);
- if (exportMode === "module") imports.push(`import { __module as ${moduleName} } from ${JSON.stringify(wrapId$1(id, MODULE_SUFFIX))}`, `var ${exportsName} = ${moduleName}.exports`);
- else if (exportMode === "exports") imports.push(`import { __exports as ${exportsName} } from ${JSON.stringify(wrapId$1(id, EXPORTS_SUFFIX))}`);
- const requiresBySource = collectSources(requireExpressions);
- processRequireExpressions(imports, await resolveRequireSourcesAndUpdateMeta(id, needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule, commonjsMeta, Object.keys(requiresBySource).map((source) => {
- return {
- source,
- isConditional: requiresBySource[source].every((require$2) => require$2.isInsideConditional)
- };
- })), requiresBySource, getIgnoreTryCatchRequireStatementMode, magicString);
- return imports.length ? `${imports.join(";\n")};\n\n` : "";
- }
- return {
- addRequireExpression,
- rewriteRequireExpressionsAndGetImportBlock
- };
-}
-function collectSources(requireExpressions) {
- const requiresBySource = Object.create(null);
- for (const requireExpression of requireExpressions) {
- const { sourceId } = requireExpression;
- if (!requiresBySource[sourceId]) requiresBySource[sourceId] = [];
- requiresBySource[sourceId].push(requireExpression);
- }
- return requiresBySource;
-}
-function processRequireExpressions(imports, requireTargets, requiresBySource, getIgnoreTryCatchRequireStatementMode, magicString) {
- const generateRequireName = getGenerateRequireName();
- for (const { source, id: resolvedId, isCommonJS, wrappedModuleSideEffects } of requireTargets) {
- const requires = requiresBySource[source];
- const name = generateRequireName(requires);
- let usesRequired = false;
- let needsImport = false;
- for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) {
- const { canConvertRequire, shouldRemoveRequire } = isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX) ? getIgnoreTryCatchRequireStatementMode(source) : {
- canConvertRequire: true,
- shouldRemoveRequire: false
- };
- if (shouldRemoveRequire) if (usesReturnValue) magicString.overwrite(node.start, node.end, "undefined");
- else magicString.remove(toBeRemoved.start, toBeRemoved.end);
- else if (canConvertRequire) {
- needsImport = true;
- if (isCommonJS === IS_WRAPPED_COMMONJS) magicString.overwrite(node.start, node.end, `${wrappedModuleSideEffects ? "" : "/*@__PURE__*/ "}${name}()`);
- else if (usesReturnValue) {
- usesRequired = true;
- magicString.overwrite(node.start, node.end, name);
- } else magicString.remove(toBeRemoved.start, toBeRemoved.end);
- }
- }
- if (needsImport) if (isCommonJS === IS_WRAPPED_COMMONJS) imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)}`);
- else imports.push(`import ${usesRequired ? `${name} from ` : ""}${JSON.stringify(resolvedId)}`);
- }
-}
-function getGenerateRequireName() {
- let uid = 0;
- return (requires) => {
- let name;
- const hasNameConflict = ({ scope }) => scope.contains(name);
- do {
- name = `require$$${uid}`;
- uid += 1;
- } while (requires.some(hasNameConflict));
- return name;
- };
-}
-const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
-const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
-async function transformCommonjs(parse$15, code, id, isEsModule, ignoreGlobal, ignoreRequire, ignoreDynamicRequires, getIgnoreTryCatchRequireStatementMode, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, astCache, defaultIsModuleExports, needsRequireWrapper, resolveRequireSourcesAndUpdateMeta, isRequired, checkDynamicRequire, commonjsMeta) {
- const ast = astCache || tryParse(parse$15, code, id);
- const magicString = new MagicString(code);
- const uses = {
- module: false,
- exports: false,
- global: false,
- require: false
- };
- const virtualDynamicRequirePath = isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname$1(id), commonDir);
- let scope = attachScopes(ast, "scope");
- let lexicalDepth = 0;
- let programDepth = 0;
- let classBodyDepth = 0;
- let currentTryBlockEnd = null;
- let shouldWrap = false;
- const globals = /* @__PURE__ */ new Set();
- let currentConditionalNodeEnd = null;
- const conditionalNodes = /* @__PURE__ */ new Set();
- const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
- const reassignedNames = /* @__PURE__ */ new Set();
- const topLevelDeclarations = [];
- const skippedNodes = /* @__PURE__ */ new Set();
- const moduleAccessScopes = new Set([scope]);
- const exportsAccessScopes = new Set([scope]);
- const moduleExportsAssignments = [];
- let firstTopLevelModuleExportsAssignment = null;
- const exportsAssignmentsByName = /* @__PURE__ */ new Map();
- const topLevelAssignments = /* @__PURE__ */ new Set();
- const topLevelDefineCompiledEsmExpressions = [];
- const replacedGlobal = [];
- const replacedThis = [];
- const replacedDynamicRequires = [];
- const importedVariables = /* @__PURE__ */ new Set();
- const indentExclusionRanges = [];
- walk$2(ast, {
- enter(node, parent) {
- if (skippedNodes.has(node)) {
- this.skip();
- return;
- }
- if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) currentTryBlockEnd = null;
- if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) currentConditionalNodeEnd = null;
- if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) currentConditionalNodeEnd = node.end;
- programDepth += 1;
- if (node.scope) ({scope} = node);
- if (functionType.test(node.type)) lexicalDepth += 1;
- if (sourceMap) {
- magicString.addSourcemapLocation(node.start);
- magicString.addSourcemapLocation(node.end);
- }
- switch (node.type) {
- case "AssignmentExpression":
- if (node.left.type === "MemberExpression") {
- const flattened = getKeypath(node.left);
- if (!flattened || scope.contains(flattened.name)) return;
- const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
- if (!exportsPatternMatch || flattened.keypath === "exports") return;
- const [, exportName] = exportsPatternMatch;
- uses[flattened.name] = true;
- if (flattened.keypath === "module.exports") {
- moduleExportsAssignments.push(node);
- if (programDepth > 3) moduleAccessScopes.add(scope);
- else if (!firstTopLevelModuleExportsAssignment) firstTopLevelModuleExportsAssignment = node;
- } else if (exportName === KEY_COMPILED_ESM) if (programDepth > 3) shouldWrap = true;
- else topLevelDefineCompiledEsmExpressions.push({
- node,
- type: flattened.name
- });
- else {
- const exportsAssignments = exportsAssignmentsByName.get(exportName) || {
- nodes: [],
- scopes: /* @__PURE__ */ new Set()
- };
- exportsAssignments.nodes.push({
- node,
- type: flattened.name
- });
- exportsAssignments.scopes.add(scope);
- exportsAccessScopes.add(scope);
- exportsAssignmentsByName.set(exportName, exportsAssignments);
- if (programDepth <= 3) topLevelAssignments.add(node);
- }
- skippedNodes.add(node.left);
- } else for (const name of extractAssignedNames(node.left)) reassignedNames.add(name);
- return;
- case "CallExpression": {
- const defineCompiledEsmType = getDefineCompiledEsmType(node);
- if (defineCompiledEsmType) {
- if (programDepth === 3 && parent.type === "ExpressionStatement") {
- skippedNodes.add(node.arguments[0]);
- topLevelDefineCompiledEsmExpressions.push({
- node,
- type: defineCompiledEsmType
- });
- } else shouldWrap = true;
- return;
- }
- if (isDynamicRequireModulesEnabled && node.callee.object && isRequire(node.callee.object, scope) && node.callee.property.name === "resolve") {
- checkDynamicRequire(node.start);
- uses.require = true;
- replacedDynamicRequires.push(node.callee.object);
- skippedNodes.add(node.callee);
- return;
- }
- if (!isRequireExpression(node, scope)) {
- const keypath = getKeypath(node.callee);
- if (keypath && importedVariables.has(keypath.name)) currentConditionalNodeEnd = Infinity;
- return;
- }
- skippedNodes.add(node.callee);
- uses.require = true;
- if (hasDynamicArguments(node)) {
- if (isDynamicRequireModulesEnabled) checkDynamicRequire(node.start);
- if (!ignoreDynamicRequires) replacedDynamicRequires.push(node.callee);
- return;
- }
- const requireStringArg = getRequireStringArg(node);
- if (!ignoreRequire(requireStringArg)) {
- addRequireExpression(requireStringArg, node, scope, parent.type !== "ExpressionStatement", currentTryBlockEnd !== null, currentConditionalNodeEnd !== null, parent.type === "ExpressionStatement" && (!currentConditionalNodeEnd || currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd) ? parent : node);
- if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier") for (const name of extractAssignedNames(parent.id)) importedVariables.add(name);
- }
- return;
- }
- case "ClassBody":
- classBodyDepth += 1;
- return;
- case "ConditionalExpression":
- case "IfStatement":
- if (isFalsy(node.test)) skippedNodes.add(node.consequent);
- else if (isTruthy(node.test)) {
- if (node.alternate) skippedNodes.add(node.alternate);
- } else {
- conditionalNodes.add(node.consequent);
- if (node.alternate) conditionalNodes.add(node.alternate);
- }
- return;
- case "ArrowFunctionExpression":
- case "FunctionDeclaration":
- case "FunctionExpression":
- if (currentConditionalNodeEnd === null && !(parent.type === "CallExpression" && parent.callee === node)) currentConditionalNodeEnd = node.end;
- return;
- case "Identifier": {
- const { name } = node;
- if (!(0, import_is_reference.default)(node, parent) || scope.contains(name) || parent.type === "PropertyDefinition" && parent.key === node) return;
- switch (name) {
- case "require":
- uses.require = true;
- if (isNodeRequirePropertyAccess(parent)) return;
- if (!ignoreDynamicRequires) {
- if (isShorthandProperty(parent)) {
- skippedNodes.add(parent.value);
- magicString.prependRight(node.start, "require: ");
- }
- replacedDynamicRequires.push(node);
- }
- return;
- case "module":
- case "exports":
- shouldWrap = true;
- uses[name] = true;
- return;
- case "global":
- uses.global = true;
- if (!ignoreGlobal) replacedGlobal.push(node);
- return;
- case "define":
- magicString.overwrite(node.start, node.end, "undefined", { storeName: true });
- return;
- default:
- globals.add(name);
- return;
- }
- }
- case "LogicalExpression":
- if (node.operator === "&&") {
- if (isFalsy(node.left)) skippedNodes.add(node.right);
- else if (!isTruthy(node.left)) conditionalNodes.add(node.right);
- } else if (node.operator === "||") {
- if (isTruthy(node.left)) skippedNodes.add(node.right);
- else if (!isFalsy(node.left)) conditionalNodes.add(node.right);
- }
- return;
- case "MemberExpression":
- if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
- uses.require = true;
- replacedDynamicRequires.push(node);
- skippedNodes.add(node.object);
- skippedNodes.add(node.property);
- }
- return;
- case "ReturnStatement":
- if (lexicalDepth === 0) shouldWrap = true;
- return;
- case "ThisExpression":
- if (lexicalDepth === 0 && !classBodyDepth) {
- uses.global = true;
- if (!ignoreGlobal) replacedThis.push(node);
- }
- return;
- case "TryStatement":
- if (currentTryBlockEnd === null) currentTryBlockEnd = node.block.end;
- if (currentConditionalNodeEnd === null) currentConditionalNodeEnd = node.end;
- return;
- case "UnaryExpression":
- if (node.operator === "typeof") {
- const flattened = getKeypath(node.argument);
- if (!flattened) return;
- if (scope.contains(flattened.name)) return;
- if (!isEsModule && (flattened.keypath === "module.exports" || flattened.keypath === "module" || flattened.keypath === "exports")) magicString.overwrite(node.start, node.end, `'object'`, { storeName: false });
- }
- return;
- case "VariableDeclaration":
- if (!scope.parent) topLevelDeclarations.push(node);
- return;
- case "TemplateElement": if (node.value.raw.includes("\n")) indentExclusionRanges.push([node.start, node.end]);
- }
- },
- leave(node) {
- programDepth -= 1;
- if (node.scope) scope = scope.parent;
- if (functionType.test(node.type)) lexicalDepth -= 1;
- if (node.type === "ClassBody") classBodyDepth -= 1;
- }
- });
- const nameBase = getName(id);
- const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
- const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
- const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
- const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
- const helpersName = deconflict([scope], globals, "commonjsHelpers");
- const dynamicRequireName = replacedDynamicRequires.length > 0 && deconflict([scope], globals, isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT);
- const deconflictedExportNames = Object.create(null);
- for (const [exportName, { scopes }] of exportsAssignmentsByName) deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
- for (const node of replacedGlobal) magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, { storeName: true });
- for (const node of replacedThis) magicString.overwrite(node.start, node.end, exportsName, { storeName: true });
- for (const node of replacedDynamicRequires) magicString.overwrite(node.start, node.end, isDynamicRequireModulesEnabled ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})` : dynamicRequireName, {
- contentOnly: true,
- storeName: true
- });
- shouldWrap = !isEsModule && (shouldWrap || uses.exports && moduleExportsAssignments.length > 0);
- if (!(shouldWrap || isRequired || needsRequireWrapper || uses.module || uses.exports || uses.require || topLevelDefineCompiledEsmExpressions.length > 0) && (ignoreGlobal || !uses.global)) return { meta: { commonjs: { isCommonJS: false } } };
- let leadingComment = "";
- if (code.startsWith("/*")) {
- const commentEnd = code.indexOf("*/", 2) + 2;
- leadingComment = `${code.slice(0, commentEnd)}\n`;
- magicString.remove(0, commentEnd).trim();
- }
- let shebang = "";
- if (code.startsWith("#!")) {
- const shebangEndPosition = code.indexOf("\n") + 1;
- shebang = code.slice(0, shebangEndPosition);
- magicString.remove(0, shebangEndPosition).trim();
- }
- const exportMode = isEsModule ? "none" : shouldWrap ? uses.module ? "module" : "exports" : firstTopLevelModuleExportsAssignment ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0 ? "replace" : "module" : moduleExportsAssignments.length === 0 ? "exports" : "module";
- const exportedExportsName = exportMode === "module" ? deconflict([], globals, `${nameBase}Exports`) : exportsName;
- const importBlock = await rewriteRequireExpressionsAndGetImportBlock(magicString, topLevelDeclarations, reassignedNames, helpersName, dynamicRequireName, moduleName, exportsName, id, exportMode, resolveRequireSourcesAndUpdateMeta, needsRequireWrapper, isEsModule, isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, commonjsMeta);
- const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS;
- const exportBlock = isEsModule ? "" : rewriteExportsAndGetExportsBlock(magicString, moduleName, exportsName, exportedExportsName, shouldWrap, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsAssignmentsByName, topLevelAssignments, topLevelDefineCompiledEsmExpressions, deconflictedExportNames, code, helpersName, exportMode, defaultIsModuleExports, usesRequireWrapper, requireName);
- if (shouldWrap) wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges);
- if (usesRequireWrapper) {
- magicString.trim().indent(" ", { exclude: indentExclusionRanges });
- const exported = exportMode === "module" ? `${moduleName}.exports` : exportsName;
- magicString.prepend(`var ${isRequiredName};
-
-function ${requireName} () {
-\tif (${isRequiredName}) return ${exported};
-\t${isRequiredName} = 1;
-`).append(`
-\treturn ${exported};
-}`);
- if (exportMode === "replace") magicString.prepend(`var ${exportsName};\n`);
- }
- magicString.trim().prepend(shebang + leadingComment + importBlock).append(exportBlock);
- return {
- code: magicString.toString(),
- map: sourceMap ? magicString.generateMap() : null,
- syntheticNamedExports: isEsModule || usesRequireWrapper ? false : "__moduleExports",
- meta: { commonjs: {
- ...commonjsMeta,
- shebang
- } }
- };
-}
-const PLUGIN_NAME = "commonjs";
-function commonjs(options$1 = {}) {
- const { ignoreGlobal, ignoreDynamicRequires, requireReturnsDefault: requireReturnsDefaultOption, defaultIsModuleExports: defaultIsModuleExportsOption, esmExternals, requireNodeBuiltins = false } = options$1;
- const extensions$1 = options$1.extensions || [".js"];
- const filter$1 = createFilter$2(options$1.include, options$1.exclude);
- const isPossibleCjsId = (id) => {
- const extName = extname$1(id);
- return extName === ".cjs" || extensions$1.includes(extName) && filter$1(id);
- };
- const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options$1);
- const getRequireReturnsDefault = typeof requireReturnsDefaultOption === "function" ? requireReturnsDefaultOption : () => requireReturnsDefaultOption;
- let esmExternalIds;
- const isEsmExternal = typeof esmExternals === "function" ? esmExternals : Array.isArray(esmExternals) ? (esmExternalIds = new Set(esmExternals), (id) => esmExternalIds.has(id)) : () => esmExternals;
- const getDefaultIsModuleExports = typeof defaultIsModuleExportsOption === "function" ? defaultIsModuleExportsOption : () => typeof defaultIsModuleExportsOption === "boolean" ? defaultIsModuleExportsOption : "auto";
- const dynamicRequireRoot = typeof options$1.dynamicRequireRoot === "string" ? resolve$1(options$1.dynamicRequireRoot) : process.cwd();
- const { commonDir, dynamicRequireModules } = getDynamicRequireModules(options$1.dynamicRequireTargets, dynamicRequireRoot);
- const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
- const ignoreRequire = typeof options$1.ignore === "function" ? options$1.ignore : Array.isArray(options$1.ignore) ? (id) => options$1.ignore.includes(id) : () => false;
- const getIgnoreTryCatchRequireStatementMode = (id) => {
- const mode = typeof options$1.ignoreTryCatch === "function" ? options$1.ignoreTryCatch(id) : Array.isArray(options$1.ignoreTryCatch) ? options$1.ignoreTryCatch.includes(id) : typeof options$1.ignoreTryCatch !== "undefined" ? options$1.ignoreTryCatch : true;
- return {
- canConvertRequire: mode !== "remove" && mode !== true,
- shouldRemoveRequire: mode === "remove"
- };
- };
- const { currentlyResolving, resolveId } = getResolveId(extensions$1, isPossibleCjsId);
- const sourceMap = options$1.sourceMap !== false;
- let requireResolver;
- function transformAndCheckExports(code, id) {
- const normalizedId = normalizePathSlashes(id);
- const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(this.parse, code, id);
- const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {};
- if (hasDefaultExport) commonjsMeta.hasDefaultExport = true;
- if (hasNamedExports) commonjsMeta.hasNamedExports = true;
- if (!dynamicRequireModules.has(normalizedId) && (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) || isEsModule && !options$1.transformMixedEsModules)) {
- commonjsMeta.isCommonJS = false;
- return { meta: { commonjs: commonjsMeta } };
- }
- const needsRequireWrapper = !isEsModule && (dynamicRequireModules.has(normalizedId) || strictRequiresFilter(id));
- const checkDynamicRequire = (position) => {
- const normalizedDynamicRequireRoot = normalizePathSlashes(dynamicRequireRoot);
- if (normalizedId.indexOf(normalizedDynamicRequireRoot) !== 0) this.error({
- code: "DYNAMIC_REQUIRE_OUTSIDE_ROOT",
- normalizedId,
- normalizedDynamicRequireRoot,
- message: `"${normalizedId}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${normalizedDynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname$1(normalizedId)}" or one of its parent directories.`
- }, position);
- };
- return transformCommonjs(this.parse, code, id, isEsModule, ignoreGlobal || isEsModule, ignoreRequire, ignoreDynamicRequires && !isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ast, getDefaultIsModuleExports(id), needsRequireWrapper, requireResolver.resolveRequireSourcesAndUpdateMeta(this), requireResolver.isRequiredId(id), checkDynamicRequire, commonjsMeta);
- }
- return {
- name: PLUGIN_NAME,
- version: version$1,
- options(rawOptions) {
- const plugins$1 = Array.isArray(rawOptions.plugins) ? [...rawOptions.plugins] : rawOptions.plugins ? [rawOptions.plugins] : [];
- plugins$1.unshift({
- name: "commonjs--resolver",
- resolveId
- });
- return {
- ...rawOptions,
- plugins: plugins$1
- };
- },
- buildStart({ plugins: plugins$1 }) {
- validateVersion(this.meta.rollupVersion, peerDependencies.rollup, "rollup");
- const nodeResolve = plugins$1.find(({ name }) => name === "node-resolve");
- if (nodeResolve) validateVersion(nodeResolve.version, "^13.0.6", "@rollup/plugin-node-resolve");
- if (options$1.namedExports != null) this.warn("The namedExports option from \"@rollup/plugin-commonjs\" is deprecated. Named exports are now handled automatically.");
- requireResolver = getRequireResolver(extensions$1, detectCyclesAndConditional, currentlyResolving, requireNodeBuiltins);
- },
- buildEnd() {
- if (options$1.strictRequires === "debug") {
- const wrappedIds = requireResolver.getWrappedIds();
- if (wrappedIds.length) this.warn({
- code: "WRAPPED_IDS",
- ids: wrappedIds,
- message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds.map((id) => `\t${JSON.stringify(relative$1(process.cwd(), id))}`).join(",\n")}\n]`
- });
- else this.warn({
- code: "WRAPPED_IDS",
- ids: wrappedIds,
- message: "The commonjs plugin did not wrap any files."
- });
- }
- },
- async load(id) {
- if (id === HELPERS_ID) return getHelpersModule();
- if (isWrappedId(id, MODULE_SUFFIX)) {
- const name = getName(unwrapId$1(id, MODULE_SUFFIX));
- return {
- code: `var ${name} = {exports: {}}; export {${name} as __module}`,
- meta: { commonjs: { isCommonJS: false } }
- };
- }
- if (isWrappedId(id, EXPORTS_SUFFIX)) {
- const name = getName(unwrapId$1(id, EXPORTS_SUFFIX));
- return {
- code: `var ${name} = {}; export {${name} as __exports}`,
- meta: { commonjs: { isCommonJS: false } }
- };
- }
- if (isWrappedId(id, EXTERNAL_SUFFIX)) {
- const actualId = unwrapId$1(id, EXTERNAL_SUFFIX);
- if (requireNodeBuiltins === true && actualId.startsWith("node:")) return getExternalBuiltinRequireProxy(actualId);
- return getUnknownRequireProxy(actualId, isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true);
- }
- if (id.endsWith(ENTRY_SUFFIX)) {
- const acutalId = id.slice(0, -15);
- const { meta: { commonjs: commonjsMeta } } = this.getModuleInfo(acutalId);
- const shebang = commonjsMeta?.shebang ?? "";
- return getEntryProxy(acutalId, getDefaultIsModuleExports(acutalId), this.getModuleInfo, shebang);
- }
- if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
- const actualId = unwrapId$1(id, ES_IMPORT_SUFFIX);
- return getEsImportProxy(actualId, getDefaultIsModuleExports(actualId), (await this.load({ id: actualId })).moduleSideEffects);
- }
- if (id === DYNAMIC_MODULES_ID) return getDynamicModuleRegistry(isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ignoreDynamicRequires);
- if (isWrappedId(id, PROXY_SUFFIX)) {
- const actualId = unwrapId$1(id, PROXY_SUFFIX);
- return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load);
- }
- return null;
- },
- shouldTransformCachedModule(...args) {
- return requireResolver.shouldTransformCachedModule.call(this, ...args);
- },
- transform(code, id) {
- if (!isPossibleCjsId(id)) return null;
- try {
- return transformAndCheckExports.call(this, code, id);
- } catch (err$2) {
- return this.error(err$2, err$2.pos);
- }
- }
- };
-}
-
-//#endregion
-//#region src/node/environment.ts
-/**
-* Creates a function that hides the complexities of a WeakMap with an initial value
-* to implement object metadata. Used by plugins to implement cross hooks per
-* environment metadata
-*
-* @experimental
-*/
-function perEnvironmentState(initial) {
- const stateMap = /* @__PURE__ */ new WeakMap();
- return function(context) {
- const { environment } = context;
- let state = stateMap.get(environment);
- if (!state) {
- state = initial(environment);
- stateMap.set(environment, state);
- }
- return state;
- };
-}
-
-//#endregion
-//#region src/node/plugins/reporter.ts
-var import_picocolors$32 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const groups = [
- {
- name: "Assets",
- color: import_picocolors$32.default.green
- },
- {
- name: "CSS",
- color: import_picocolors$32.default.magenta
- },
- {
- name: "JS",
- color: import_picocolors$32.default.cyan
- }
-];
-const COMPRESSIBLE_ASSETS_RE = /\.(?:html|json|svg|txt|xml|xhtml|wasm)$/;
-function buildReporterPlugin(config$2) {
- const compress = promisify(gzip);
- const numberFormatter = new Intl.NumberFormat("en", {
- maximumFractionDigits: 2,
- minimumFractionDigits: 2
- });
- const displaySize = (bytes) => {
- return `${numberFormatter.format(bytes / 1e3)} kB`;
- };
- const tty = process.stdout.isTTY && !process.env.CI;
- const shouldLogInfo = LogLevels[config$2.logLevel || "info"] >= LogLevels.info;
- const modulesReporter = shouldLogInfo ? perEnvironmentState((environment) => {
- let hasTransformed = false;
- let transformedCount = 0;
- const logTransform = throttle((id) => {
- writeLine(`transforming (${transformedCount}) ${import_picocolors$32.default.dim(path.relative(config$2.root, id))}`);
- });
- return {
- reset() {
- transformedCount = 0;
- },
- register(id) {
- transformedCount++;
- if (!tty) {
- if (!hasTransformed) config$2.logger.info(`transforming...`);
- } else {
- if (id.includes(`?`)) return;
- logTransform(id);
- }
- hasTransformed = true;
- },
- log() {
- if (tty) clearLine$1();
- environment.logger.info(`${import_picocolors$32.default.green(`✓`)} ${transformedCount} modules transformed.`);
- }
- };
- }) : void 0;
- const chunksReporter = perEnvironmentState((environment) => {
- let hasRenderedChunk = false;
- let hasCompressChunk = false;
- let chunkCount = 0;
- let compressedCount = 0;
- async function getCompressedSize(code) {
- if (environment.config.consumer !== "client" || !environment.config.build.reportCompressedSize) return null;
- if (shouldLogInfo && !hasCompressChunk) {
- if (!tty) config$2.logger.info("computing gzip size...");
- else writeLine("computing gzip size (0)...");
- hasCompressChunk = true;
- }
- const compressed = await compress(typeof code === "string" ? code : Buffer.from(code));
- compressedCount++;
- if (shouldLogInfo && tty) writeLine(`computing gzip size (${compressedCount})...`);
- return compressed.length;
- }
- return {
- reset() {
- chunkCount = 0;
- compressedCount = 0;
- },
- register() {
- chunkCount++;
- if (shouldLogInfo) {
- if (!tty) {
- if (!hasRenderedChunk) environment.logger.info("rendering chunks...");
- } else writeLine(`rendering chunks (${chunkCount})...`);
- hasRenderedChunk = true;
- }
- },
- async log(output, outDir) {
- const chunkLimit = environment.config.build.chunkSizeWarningLimit;
- let hasLargeChunks = false;
- if (shouldLogInfo) {
- const entries = (await Promise.all(Object.values(output).map(async (chunk) => {
- if (chunk.type === "chunk") return {
- name: chunk.fileName,
- group: "JS",
- size: Buffer.byteLength(chunk.code),
- compressedSize: await getCompressedSize(chunk.code),
- mapSize: chunk.map ? Buffer.byteLength(chunk.map.toString()) : null
- };
- else {
- if (chunk.fileName.endsWith(".map")) return null;
- const isCSS = chunk.fileName.endsWith(".css");
- const isCompressible = isCSS || COMPRESSIBLE_ASSETS_RE.test(chunk.fileName);
- return {
- name: chunk.fileName,
- group: isCSS ? "CSS" : "Assets",
- size: Buffer.byteLength(chunk.source),
- mapSize: null,
- compressedSize: isCompressible ? await getCompressedSize(chunk.source) : null
- };
- }
- }))).filter(isDefined);
- if (tty) clearLine$1();
- let longest = 0;
- let biggestSize = 0;
- let biggestMap = 0;
- let biggestCompressSize = 0;
- for (const entry of entries) {
- if (entry.name.length > longest) longest = entry.name.length;
- if (entry.size > biggestSize) biggestSize = entry.size;
- if (entry.mapSize && entry.mapSize > biggestMap) biggestMap = entry.mapSize;
- if (entry.compressedSize && entry.compressedSize > biggestCompressSize) biggestCompressSize = entry.compressedSize;
- }
- const sizePad = displaySize(biggestSize).length;
- const mapPad = displaySize(biggestMap).length;
- const compressPad = displaySize(biggestCompressSize).length;
- const relativeOutDir = normalizePath(path.relative(config$2.root, path.resolve(config$2.root, outDir ?? environment.config.build.outDir)));
- const assetsDir = path.join(environment.config.build.assetsDir, "/");
- for (const group of groups) {
- const filtered = entries.filter((e$1) => e$1.group === group.name);
- if (!filtered.length) continue;
- for (const entry of filtered.sort((a, z) => a.size - z.size)) {
- const isLarge = group.name === "JS" && entry.size / 1e3 > chunkLimit;
- if (isLarge) hasLargeChunks = true;
- const sizeColor = isLarge ? import_picocolors$32.default.yellow : import_picocolors$32.default.dim;
- let log$3 = import_picocolors$32.default.dim(withTrailingSlash(relativeOutDir));
- log$3 += !config$2.build.lib && entry.name.startsWith(withTrailingSlash(assetsDir)) ? import_picocolors$32.default.dim(assetsDir) + group.color(entry.name.slice(assetsDir.length).padEnd(longest + 2 - assetsDir.length)) : group.color(entry.name.padEnd(longest + 2));
- log$3 += import_picocolors$32.default.bold(sizeColor(displaySize(entry.size).padStart(sizePad)));
- if (entry.compressedSize) log$3 += import_picocolors$32.default.dim(` │ gzip: ${displaySize(entry.compressedSize).padStart(compressPad)}`);
- if (entry.mapSize) log$3 += import_picocolors$32.default.dim(` │ map: ${displaySize(entry.mapSize).padStart(mapPad)}`);
- config$2.logger.info(log$3);
- }
- }
- } else hasLargeChunks = Object.values(output).some((chunk) => {
- return chunk.type === "chunk" && chunk.code.length / 1e3 > chunkLimit;
- });
- if (hasLargeChunks && environment.config.build.minify && !config$2.build.lib && environment.config.consumer === "client") environment.logger.warn(import_picocolors$32.default.yellow(`\n(!) Some chunks are larger than ${chunkLimit} kB after minification. Consider:\n- Using dynamic import() to code-split the application\n- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks\n- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`));
- }
- };
- });
- return {
- name: "vite:reporter",
- sharedDuringBuild: true,
- perEnvironmentStartEndDuringDev: true,
- ...modulesReporter ? {
- transform(_, id) {
- modulesReporter(this).register(id);
- },
- buildStart() {
- modulesReporter(this).reset();
- },
- buildEnd() {
- modulesReporter(this).log();
- }
- } : {},
- renderStart() {
- chunksReporter(this).reset();
- },
- renderChunk(_, chunk, options$1) {
- if (!options$1.inlineDynamicImports) for (const id of chunk.moduleIds) {
- const module$1 = this.getModuleInfo(id);
- if (!module$1) continue;
- if (module$1.importers.length && module$1.dynamicImporters.length) {
- if (module$1.dynamicImporters.some((id$1) => !isInNodeModules(id$1) && chunk.moduleIds.includes(id$1))) this.warn(`\n(!) ${module$1.id} is dynamically imported by ${module$1.dynamicImporters.join(", ")} but also statically imported by ${module$1.importers.join(", ")}, dynamic import will not move module into another chunk.\n`);
- }
- }
- chunksReporter(this).register();
- },
- generateBundle() {
- if (shouldLogInfo && tty) clearLine$1();
- },
- async writeBundle({ dir }, output) {
- await chunksReporter(this).log(output, dir);
- }
- };
-}
-function writeLine(output) {
- clearLine$1();
- if (output.length < process.stdout.columns) process.stdout.write(output);
- else process.stdout.write(output.substring(0, process.stdout.columns - 1));
-}
-function clearLine$1() {
- process.stdout.clearLine(0);
- process.stdout.cursorTo(0);
-}
-function throttle(fn) {
- let timerHandle = null;
- return (...args) => {
- if (timerHandle) return;
- fn(...args);
- timerHandle = setTimeout(() => {
- timerHandle = null;
- }, 100);
- };
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.3/node_modules/tsconfck/src/util.js
-const POSIX_SEP_RE = new RegExp("\\" + path.posix.sep, "g");
-const NATIVE_SEP_RE = new RegExp("\\" + path.sep, "g");
-/** @type {Map<string,RegExp>}*/
-const PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map();
-const GLOB_ALL_PATTERN = `**/*`;
-const TS_EXTENSIONS = [
- ".ts",
- ".tsx",
- ".mts",
- ".cts"
-];
-const TSJS_EXTENSIONS = TS_EXTENSIONS.concat([
- ".js",
- ".jsx",
- ".mjs",
- ".cjs"
-]);
-const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext) => ext.substring(1)).join("|")})`;
-const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext) => ext.substring(1)).join("|")})`;
-const IS_POSIX = path.posix.sep === path.sep;
-/**
-* @template T
-* @returns {{resolve:(result:T)=>void, reject:(error:any)=>void, promise: Promise<T>}}
-*/
-function makePromise() {
- let resolve$4, reject;
- return {
- promise: new Promise((res, rej) => {
- resolve$4 = res;
- reject = rej;
- }),
- resolve: resolve$4,
- reject
- };
-}
-/**
-* @param {string} filename
-* @param {import('./cache.js').TSConfckCache} [cache]
-* @returns {Promise<string|void>}
-*/
-async function resolveTSConfigJson(filename, cache$1) {
- if (path.extname(filename) !== ".json") return;
- const tsconfig = path.resolve(filename);
- if (cache$1 && (cache$1.hasParseResult(tsconfig) || cache$1.hasParseResult(filename))) return tsconfig;
- return promises.stat(tsconfig).then((stat$4) => {
- if (stat$4.isFile() || stat$4.isFIFO()) return tsconfig;
- else throw new Error(`${filename} exists but is not a regular file.`);
- });
-}
-/**
-*
-* @param {string} dir an absolute directory path
-* @returns {boolean} if dir path includes a node_modules segment
-*/
-const isInNodeModules$1 = IS_POSIX ? (dir) => dir.includes("/node_modules/") : (dir) => dir.match(/[/\\]node_modules[/\\]/);
-/**
-* convert posix separator to native separator
-*
-* eg.
-* windows: C:/foo/bar -> c:\foo\bar
-* linux: /foo/bar -> /foo/bar
-*
-* @param {string} filename with posix separators
-* @returns {string} filename with native separators
-*/
-const posix2native = IS_POSIX ? (filename) => filename : (filename) => filename.replace(POSIX_SEP_RE, path.sep);
-/**
-* convert native separator to posix separator
-*
-* eg.
-* windows: C:\foo\bar -> c:/foo/bar
-* linux: /foo/bar -> /foo/bar
-*
-* @param {string} filename - filename with native separators
-* @returns {string} filename with posix separators
-*/
-const native2posix = IS_POSIX ? (filename) => filename : (filename) => filename.replace(NATIVE_SEP_RE, path.posix.sep);
-/**
-* converts params to native separator, resolves path and converts native back to posix
-*
-* needed on windows to handle posix paths in tsconfig
-*
-* @param dir {string|null} directory to resolve from
-* @param filename {string} filename or pattern to resolve
-* @returns string
-*/
-const resolve2posix = IS_POSIX ? (dir, filename) => dir ? path.resolve(dir, filename) : path.resolve(filename) : (dir, filename) => native2posix(dir ? path.resolve(posix2native(dir), posix2native(filename)) : path.resolve(posix2native(filename)));
-/**
-*
-* @param {import('./public.d.ts').TSConfckParseResult} result
-* @param {import('./public.d.ts').TSConfckParseOptions} [options]
-* @returns {string[]}
-*/
-function resolveReferencedTSConfigFiles(result, options$1) {
- const dir = path.dirname(result.tsconfigFile);
- return result.tsconfig.references.map((ref) => {
- return resolve2posix(dir, ref.path.endsWith(".json") ? ref.path : path.join(ref.path, options$1?.configName ?? "tsconfig.json"));
- });
-}
-/**
-* @param {string} filename
-* @param {import('./public.d.ts').TSConfckParseResult} result
-* @returns {import('./public.d.ts').TSConfckParseResult}
-*/
-function resolveSolutionTSConfig(filename, result) {
- if (result.referenced && (result.tsconfig.compilerOptions?.allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS).some((ext) => filename.endsWith(ext)) && !isIncluded(filename, result)) {
- const solutionTSConfig = result.referenced.find((referenced) => isIncluded(filename, referenced));
- if (solutionTSConfig) return solutionTSConfig;
- }
- return result;
-}
-/**
-*
-* @param {string} filename
-* @param {import('./public.d.ts').TSConfckParseResult} result
-* @returns {boolean}
-*/
-function isIncluded(filename, result) {
- const dir = native2posix(path.dirname(result.tsconfigFile));
- const files = (result.tsconfig.files || []).map((file) => resolve2posix(dir, file));
- const absoluteFilename = resolve2posix(null, filename);
- if (files.includes(filename)) return true;
- const allowJs = result.tsconfig.compilerOptions?.allowJs;
- if (isGlobMatch(absoluteFilename, dir, result.tsconfig.include || (result.tsconfig.files ? [] : [GLOB_ALL_PATTERN]), allowJs)) return !isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || [], allowJs);
- return false;
-}
-/**
-* test filenames agains glob patterns in tsconfig
-*
-* @param filename {string} posix style abolute path to filename to test
-* @param dir {string} posix style absolute path to directory of tsconfig containing patterns
-* @param patterns {string[]} glob patterns to match against
-* @param allowJs {boolean} allowJs setting in tsconfig to include js extensions in checks
-* @returns {boolean} true when at least one pattern matches filename
-*/
-function isGlobMatch(filename, dir, patterns, allowJs) {
- const extensions$1 = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
- return patterns.some((pattern) => {
- let lastWildcardIndex = pattern.length;
- let hasWildcard = false;
- let hasExtension = false;
- let hasSlash = false;
- let lastSlashIndex = -1;
- for (let i$1 = pattern.length - 1; i$1 > -1; i$1--) {
- const c = pattern[i$1];
- if (!hasWildcard) {
- if (c === "*" || c === "?") {
- lastWildcardIndex = i$1;
- hasWildcard = true;
- }
- }
- if (!hasSlash) {
- if (c === ".") hasExtension = true;
- else if (c === "/") {
- lastSlashIndex = i$1;
- hasSlash = true;
- }
- }
- if (hasWildcard && hasSlash) break;
- }
- if (!hasExtension && (!hasWildcard || lastWildcardIndex < lastSlashIndex)) {
- pattern += `${pattern.endsWith("/") ? "" : "/"}${GLOB_ALL_PATTERN}`;
- lastWildcardIndex = pattern.length - 1;
- hasWildcard = true;
- }
- if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) return false;
- if (pattern.endsWith("*") && !extensions$1.some((ext) => filename.endsWith(ext))) return false;
- if (pattern === GLOB_ALL_PATTERN) return filename.startsWith(`${dir}/`);
- const resolvedPattern = resolve2posix(dir, pattern);
- let firstWildcardIndex = -1;
- for (let i$1 = 0; i$1 < resolvedPattern.length; i$1++) if (resolvedPattern[i$1] === "*" || resolvedPattern[i$1] === "?") {
- firstWildcardIndex = i$1;
- hasWildcard = true;
- break;
- }
- if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) return false;
- if (!hasWildcard) return filename === resolvedPattern;
- else if (firstWildcardIndex + GLOB_ALL_PATTERN.length === resolvedPattern.length - (pattern.length - 1 - lastWildcardIndex) && resolvedPattern.slice(firstWildcardIndex, firstWildcardIndex + GLOB_ALL_PATTERN.length) === GLOB_ALL_PATTERN) return true;
- if (PATTERN_REGEX_CACHE.has(resolvedPattern)) return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
- const regex = pattern2regex(resolvedPattern, allowJs);
- PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
- return regex.test(filename);
- });
-}
-/**
-* @param {string} resolvedPattern
-* @param {boolean} allowJs
-* @returns {RegExp}
-*/
-function pattern2regex(resolvedPattern, allowJs) {
- let regexStr = "^";
- for (let i$1 = 0; i$1 < resolvedPattern.length; i$1++) {
- const char = resolvedPattern[i$1];
- if (char === "?") {
- regexStr += "[^\\/]";
- continue;
- }
- if (char === "*") {
- if (resolvedPattern[i$1 + 1] === "*" && resolvedPattern[i$1 + 2] === "/") {
- i$1 += 2;
- regexStr += "(?:[^\\/]*\\/)*";
- continue;
- }
- regexStr += "[^\\/]*";
- continue;
- }
- if ("/.+^${}()|[]\\".includes(char)) regexStr += `\\`;
- regexStr += char;
- }
- if (resolvedPattern.endsWith("*")) regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP;
- regexStr += "$";
- return new RegExp(regexStr);
-}
-/**
-* replace tokens like ${configDir}
-* @param {import('./public.d.ts').TSConfckParseResult} result
-*/
-function replaceTokens(result) {
- if (result.tsconfig) result.tsconfig = JSON.parse(JSON.stringify(result.tsconfig).replaceAll(/"\${configDir}/g, `"${native2posix(path.dirname(result.tsconfigFile))}`));
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.3/node_modules/tsconfck/src/find.js
-/**
-* find the closest tsconfig.json file
-*
-* @param {string} filename - path to file to find tsconfig for (absolute or relative to cwd)
-* @param {import('./public.d.ts').TSConfckFindOptions} [options] - options
-* @returns {Promise<string|null>} absolute path to closest tsconfig.json or null if not found
-*/
-async function find(filename, options$1) {
- let dir = path.dirname(path.resolve(filename));
- if (options$1?.ignoreNodeModules && isInNodeModules$1(dir)) return null;
- const cache$1 = options$1?.cache;
- const configName = options$1?.configName ?? "tsconfig.json";
- if (cache$1?.hasConfigPath(dir, configName)) return cache$1.getConfigPath(dir, configName);
- const { promise, resolve: resolve$4, reject } = makePromise();
- if (options$1?.root && !path.isAbsolute(options$1.root)) options$1.root = path.resolve(options$1.root);
- findUp(dir, {
- promise,
- resolve: resolve$4,
- reject
- }, options$1);
- return promise;
-}
-/**
-*
-* @param {string} dir
-* @param {{promise:Promise<string|null>,resolve:(result:string|null)=>void,reject:(err:any)=>void}} madePromise
-* @param {import('./public.d.ts').TSConfckFindOptions} [options] - options
-*/
-function findUp(dir, { resolve: resolve$4, reject, promise }, options$1) {
- const { cache: cache$1, root, configName } = options$1 ?? {};
- if (cache$1) if (cache$1.hasConfigPath(dir, configName)) {
- let cached;
- try {
- cached = cache$1.getConfigPath(dir, configName);
- } catch (e$1) {
- reject(e$1);
- return;
- }
- if (cached?.then) cached.then(resolve$4).catch(reject);
- else resolve$4(cached);
- } else cache$1.setConfigPath(dir, promise, configName);
- const tsconfig = path.join(dir, options$1?.configName ?? "tsconfig.json");
- fs.stat(tsconfig, (err$2, stats) => {
- if (stats && (stats.isFile() || stats.isFIFO())) resolve$4(tsconfig);
- else if (err$2?.code !== "ENOENT") reject(err$2);
- else {
- let parent;
- if (root === dir || (parent = path.dirname(dir)) === dir) resolve$4(null);
- else findUp(parent, {
- promise,
- resolve: resolve$4,
- reject
- }, options$1);
- }
- });
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.3/node_modules/tsconfck/src/to-json.js
-/**
-* convert content of tsconfig.json to regular json
-*
-* @param {string} tsconfigJson - content of tsconfig.json
-* @returns {string} content as regular json, comments and dangling commas have been replaced with whitespace
-*/
-function toJson(tsconfigJson) {
- const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson)));
- if (stripped.trim() === "") return "{}";
- else return stripped;
-}
-/**
-* replace dangling commas from pseudo-json string with single space
-* implementation heavily inspired by strip-json-comments
-*
-* @param {string} pseudoJson
-* @returns {string}
-*/
-function stripDanglingComma(pseudoJson) {
- let insideString = false;
- let offset$1 = 0;
- let result = "";
- let danglingCommaPos = null;
- for (let i$1 = 0; i$1 < pseudoJson.length; i$1++) {
- const currentCharacter = pseudoJson[i$1];
- if (currentCharacter === "\"") {
- if (!isEscaped(pseudoJson, i$1)) insideString = !insideString;
- }
- if (insideString) {
- danglingCommaPos = null;
- continue;
- }
- if (currentCharacter === ",") {
- danglingCommaPos = i$1;
- continue;
- }
- if (danglingCommaPos) {
- if (currentCharacter === "}" || currentCharacter === "]") {
- result += pseudoJson.slice(offset$1, danglingCommaPos) + " ";
- offset$1 = danglingCommaPos + 1;
- danglingCommaPos = null;
- } else if (!currentCharacter.match(/\s/)) danglingCommaPos = null;
- }
- }
- return result + pseudoJson.substring(offset$1);
-}
-/**
-*
-* @param {string} jsonString
-* @param {number} quotePosition
-* @returns {boolean}
-*/
-function isEscaped(jsonString, quotePosition) {
- let index = quotePosition - 1;
- let backslashCount = 0;
- while (jsonString[index] === "\\") {
- index -= 1;
- backslashCount += 1;
- }
- return Boolean(backslashCount % 2);
-}
-/**
-*
-* @param {string} string
-* @param {number?} start
-* @param {number?} end
-*/
-function strip(string, start, end) {
- return string.slice(start, end).replace(/\S/g, " ");
-}
-const singleComment = Symbol("singleComment");
-const multiComment = Symbol("multiComment");
-/**
-* @param {string} jsonString
-* @returns {string}
-*/
-function stripJsonComments(jsonString) {
- let isInsideString = false;
- /** @type {false | symbol} */
- let isInsideComment = false;
- let offset$1 = 0;
- let result = "";
- for (let index = 0; index < jsonString.length; index++) {
- const currentCharacter = jsonString[index];
- const nextCharacter = jsonString[index + 1];
- if (!isInsideComment && currentCharacter === "\"") {
- if (!isEscaped(jsonString, index)) isInsideString = !isInsideString;
- }
- if (isInsideString) continue;
- if (!isInsideComment && currentCharacter + nextCharacter === "//") {
- result += jsonString.slice(offset$1, index);
- offset$1 = index;
- isInsideComment = singleComment;
- index++;
- } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === "\r\n") {
- index++;
- isInsideComment = false;
- result += strip(jsonString, offset$1, index);
- offset$1 = index;
- } else if (isInsideComment === singleComment && currentCharacter === "\n") {
- isInsideComment = false;
- result += strip(jsonString, offset$1, index);
- offset$1 = index;
- } else if (!isInsideComment && currentCharacter + nextCharacter === "/*") {
- result += jsonString.slice(offset$1, index);
- offset$1 = index;
- isInsideComment = multiComment;
- index++;
- } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === "*/") {
- index++;
- isInsideComment = false;
- result += strip(jsonString, offset$1, index + 1);
- offset$1 = index + 1;
- }
- }
- return result + (isInsideComment ? strip(jsonString.slice(offset$1)) : jsonString.slice(offset$1));
-}
-/**
-* @param {string} string
-* @returns {string}
-*/
-function stripBom(string) {
- if (string.charCodeAt(0) === 65279) return string.slice(1);
- return string;
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.3/node_modules/tsconfck/src/parse.js
-const not_found_result = {
- tsconfigFile: null,
- tsconfig: {}
-};
-/**
-* parse the closest tsconfig.json file
-*
-* @param {string} filename - path to a tsconfig .json or a source file or directory (absolute or relative to cwd)
-* @param {import('./public.d.ts').TSConfckParseOptions} [options] - options
-* @returns {Promise<import('./public.d.ts').TSConfckParseResult>}
-* @throws {TSConfckParseError}
-*/
-async function parse$13(filename, options$1) {
- /** @type {import('./cache.js').TSConfckCache} */
- const cache$1 = options$1?.cache;
- if (cache$1?.hasParseResult(filename)) return getParsedDeep(filename, cache$1, options$1);
- const { resolve: resolve$4, reject, promise } = makePromise();
- cache$1?.setParseResult(filename, promise, true);
- try {
- let tsconfigFile = await resolveTSConfigJson(filename, cache$1) || await find(filename, options$1);
- if (!tsconfigFile) {
- resolve$4(not_found_result);
- return promise;
- }
- let result;
- if (filename !== tsconfigFile && cache$1?.hasParseResult(tsconfigFile)) result = await getParsedDeep(tsconfigFile, cache$1, options$1);
- else {
- result = await parseFile$1(tsconfigFile, cache$1, filename === tsconfigFile);
- await Promise.all([parseExtends(result, cache$1), parseReferences(result, options$1)]);
- }
- replaceTokens(result);
- resolve$4(resolveSolutionTSConfig(filename, result));
- } catch (e$1) {
- reject(e$1);
- }
- return promise;
-}
-/**
-* ensure extends and references are parsed
-*
-* @param {string} filename - cached file
-* @param {import('./cache.js').TSConfckCache} cache - cache
-* @param {import('./public.d.ts').TSConfckParseOptions} options - options
-*/
-async function getParsedDeep(filename, cache$1, options$1) {
- const result = await cache$1.getParseResult(filename);
- if (result.tsconfig.extends && !result.extended || result.tsconfig.references && !result.referenced) {
- const promise = Promise.all([parseExtends(result, cache$1), parseReferences(result, options$1)]).then(() => result);
- cache$1.setParseResult(filename, promise, true);
- return promise;
- }
- return result;
-}
-/**
-*
-* @param {string} tsconfigFile - path to tsconfig file
-* @param {import('./cache.js').TSConfckCache} [cache] - cache
-* @param {boolean} [skipCache] - skip cache
-* @returns {Promise<import('./public.d.ts').TSConfckParseResult>}
-*/
-async function parseFile$1(tsconfigFile, cache$1, skipCache) {
- if (!skipCache && cache$1?.hasParseResult(tsconfigFile) && !cache$1.getParseResult(tsconfigFile)._isRootFile_) return cache$1.getParseResult(tsconfigFile);
- const promise = promises.readFile(tsconfigFile, "utf-8").then(toJson).then((json) => {
- const parsed = JSON.parse(json);
- applyDefaults(parsed, tsconfigFile);
- return {
- tsconfigFile,
- tsconfig: normalizeTSConfig(parsed, path.dirname(tsconfigFile))
- };
- }).catch((e$1) => {
- throw new TSConfckParseError(`parsing ${tsconfigFile} failed: ${e$1}`, "PARSE_FILE", tsconfigFile, e$1);
- });
- if (!skipCache && (!cache$1?.hasParseResult(tsconfigFile) || !cache$1.getParseResult(tsconfigFile)._isRootFile_)) cache$1?.setParseResult(tsconfigFile, promise);
- return promise;
-}
-/**
-* normalize to match the output of ts.parseJsonConfigFileContent
-*
-* @param {any} tsconfig - typescript tsconfig output
-* @param {string} dir - directory
-*/
-function normalizeTSConfig(tsconfig, dir) {
- const baseUrl = tsconfig.compilerOptions?.baseUrl;
- if (baseUrl && !baseUrl.startsWith("${") && !path.isAbsolute(baseUrl)) tsconfig.compilerOptions.baseUrl = resolve2posix(dir, baseUrl);
- return tsconfig;
-}
-/**
-*
-* @param {import('./public.d.ts').TSConfckParseResult} result
-* @param {import('./public.d.ts').TSConfckParseOptions} [options]
-* @returns {Promise<void>}
-*/
-async function parseReferences(result, options$1) {
- if (!result.tsconfig.references) return;
- const referencedFiles = resolveReferencedTSConfigFiles(result, options$1);
- const referenced = await Promise.all(referencedFiles.map((file) => parseFile$1(file, options$1?.cache)));
- await Promise.all(referenced.map((ref) => parseExtends(ref, options$1?.cache)));
- referenced.forEach((ref) => {
- ref.solution = result;
- replaceTokens(ref);
- });
- result.referenced = referenced;
-}
-/**
-* @param {import('./public.d.ts').TSConfckParseResult} result
-* @param {import('./cache.js').TSConfckCache}[cache]
-* @returns {Promise<void>}
-*/
-async function parseExtends(result, cache$1) {
- if (!result.tsconfig.extends) return;
- /** @type {import('./public.d.ts').TSConfckParseResult[]} */
- const extended = [{
- tsconfigFile: result.tsconfigFile,
- tsconfig: JSON.parse(JSON.stringify(result.tsconfig))
- }];
- let pos = 0;
- /** @type {string[]} */
- const extendsPath = [];
- let currentBranchDepth = 0;
- while (pos < extended.length) {
- const extending = extended[pos];
- extendsPath.push(extending.tsconfigFile);
- if (extending.tsconfig.extends) {
- currentBranchDepth += 1;
- /** @type {string[]} */
- let resolvedExtends;
- if (!Array.isArray(extending.tsconfig.extends)) resolvedExtends = [resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)];
- else resolvedExtends = extending.tsconfig.extends.reverse().map((ex) => resolveExtends(ex, extending.tsconfigFile));
- const circularExtends = resolvedExtends.find((tsconfigFile) => extendsPath.includes(tsconfigFile));
- if (circularExtends) throw new TSConfckParseError(`Circular dependency in "extends": ${extendsPath.concat([circularExtends]).join(" -> ")}`, "EXTENDS_CIRCULAR", result.tsconfigFile);
- extended.splice(pos + 1, 0, ...await Promise.all(resolvedExtends.map((file) => parseFile$1(file, cache$1))));
- } else {
- extendsPath.splice(-currentBranchDepth);
- currentBranchDepth = 0;
- }
- pos = pos + 1;
- }
- result.extended = extended;
- for (const ext of result.extended.slice(1)) extendTSConfig(result, ext);
-}
-/**
-*
-* @param {string} extended
-* @param {string} from
-* @returns {string}
-*/
-function resolveExtends(extended, from) {
- if ([".", ".."].includes(extended)) extended = extended + "/tsconfig.json";
- const req$4 = createRequire$1(from);
- let error$1;
- try {
- return req$4.resolve(extended);
- } catch (e$1) {
- error$1 = e$1;
- }
- if (extended[0] !== "." && !path.isAbsolute(extended)) try {
- return req$4.resolve(`${extended}/tsconfig.json`);
- } catch (e$1) {
- error$1 = e$1;
- }
- throw new TSConfckParseError(`failed to resolve "extends":"${extended}" in ${from}`, "EXTENDS_RESOLVE", from, error$1);
-}
-const EXTENDABLE_KEYS = [
- "compilerOptions",
- "files",
- "include",
- "exclude",
- "watchOptions",
- "compileOnSave",
- "typeAcquisition",
- "buildOptions"
-];
-/**
-*
-* @param {import('./public.d.ts').TSConfckParseResult} extending
-* @param {import('./public.d.ts').TSConfckParseResult} extended
-* @returns void
-*/
-function extendTSConfig(extending, extended) {
- const extendingConfig = extending.tsconfig;
- const extendedConfig = extended.tsconfig;
- const relativePath = native2posix(path.relative(path.dirname(extending.tsconfigFile), path.dirname(extended.tsconfigFile)));
- for (const key of Object.keys(extendedConfig).filter((key$1) => EXTENDABLE_KEYS.includes(key$1))) if (key === "compilerOptions") {
- if (!extendingConfig.compilerOptions) extendingConfig.compilerOptions = {};
- for (const option of Object.keys(extendedConfig.compilerOptions)) {
- if (Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) continue;
- extendingConfig.compilerOptions[option] = rebaseRelative(option, extendedConfig.compilerOptions[option], relativePath);
- }
- } else if (extendingConfig[key] === void 0) if (key === "watchOptions") {
- extendingConfig.watchOptions = {};
- for (const option of Object.keys(extendedConfig.watchOptions)) extendingConfig.watchOptions[option] = rebaseRelative(option, extendedConfig.watchOptions[option], relativePath);
- } else extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath);
-}
-const REBASE_KEYS = [
- "files",
- "include",
- "exclude",
- "baseUrl",
- "rootDir",
- "rootDirs",
- "typeRoots",
- "outDir",
- "outFile",
- "declarationDir",
- "excludeDirectories",
- "excludeFiles"
-];
-/** @typedef {string | string[]} PathValue */
-/**
-*
-* @param {string} key
-* @param {PathValue} value
-* @param {string} prependPath
-* @returns {PathValue}
-*/
-function rebaseRelative(key, value$1, prependPath) {
- if (!REBASE_KEYS.includes(key)) return value$1;
- if (Array.isArray(value$1)) return value$1.map((x) => rebasePath(x, prependPath));
- else return rebasePath(value$1, prependPath);
-}
-/**
-*
-* @param {string} value
-* @param {string} prependPath
-* @returns {string}
-*/
-function rebasePath(value$1, prependPath) {
- if (path.isAbsolute(value$1) || value$1.startsWith("${configDir}")) return value$1;
- else return path.posix.normalize(path.posix.join(prependPath, value$1));
-}
-var TSConfckParseError = class TSConfckParseError extends Error {
- /**
- * error code
- * @type {string}
- */
- code;
- /**
- * error cause
- * @type { Error | undefined}
- */
- cause;
- /**
- * absolute path of tsconfig file where the error happened
- * @type {string}
- */
- tsconfigFile;
- /**
- *
- * @param {string} message - error message
- * @param {string} code - error code
- * @param {string} tsconfigFile - path to tsconfig file
- * @param {Error?} cause - cause of this error
- */
- constructor(message, code, tsconfigFile, cause) {
- super(message);
- Object.setPrototypeOf(this, TSConfckParseError.prototype);
- this.name = TSConfckParseError.name;
- this.code = code;
- this.cause = cause;
- this.tsconfigFile = tsconfigFile;
- }
-};
-/**
-*
-* @param {any} tsconfig
-* @param {string} tsconfigFile
-*/
-function applyDefaults(tsconfig, tsconfigFile) {
- if (isJSConfig(tsconfigFile)) tsconfig.compilerOptions = {
- ...DEFAULT_JSCONFIG_COMPILER_OPTIONS,
- ...tsconfig.compilerOptions
- };
-}
-const DEFAULT_JSCONFIG_COMPILER_OPTIONS = {
- allowJs: true,
- maxNodeModuleJsDepth: 2,
- allowSyntheticDefaultImports: true,
- skipLibCheck: true,
- noEmit: true
-};
-/**
-* @param {string} configFileName
-*/
-function isJSConfig(configFileName) {
- return path.basename(configFileName) === "jsconfig.json";
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.3/node_modules/tsconfck/src/parse-native.js
-/** @typedef TSDiagnosticError {
-code: number;
-category: number;
-messageText: string;
-start?: number;
-} TSDiagnosticError */
-
-//#endregion
-//#region ../../node_modules/.pnpm/tsconfck@3.1.6_typescript@5.9.3/node_modules/tsconfck/src/cache.js
-/** @template T */
-var TSConfckCache = class {
- /**
- * clear cache, use this if you have a long running process and tsconfig files have been added,changed or deleted
- */
- clear() {
- this.#configPaths.clear();
- this.#parsed.clear();
- }
- /**
- * has cached closest config for files in dir
- * @param {string} dir
- * @param {string} [configName=tsconfig.json]
- * @returns {boolean}
- */
- hasConfigPath(dir, configName = "tsconfig.json") {
- return this.#configPaths.has(`${dir}/${configName}`);
- }
- /**
- * get cached closest tsconfig for files in dir
- * @param {string} dir
- * @param {string} [configName=tsconfig.json]
- * @returns {Promise<string|null>|string|null}
- * @throws {unknown} if cached value is an error
- */
- getConfigPath(dir, configName = "tsconfig.json") {
- const key = `${dir}/${configName}`;
- const value$1 = this.#configPaths.get(key);
- if (value$1 == null || value$1.length || value$1.then) return value$1;
- else throw value$1;
- }
- /**
- * has parsed tsconfig for file
- * @param {string} file
- * @returns {boolean}
- */
- hasParseResult(file) {
- return this.#parsed.has(file);
- }
- /**
- * get parsed tsconfig for file
- * @param {string} file
- * @returns {Promise<T>|T}
- * @throws {unknown} if cached value is an error
- */
- getParseResult(file) {
- const value$1 = this.#parsed.get(file);
- if (value$1.then || value$1.tsconfig) return value$1;
- else throw value$1;
- }
- /**
- * @internal
- * @private
- * @param file
- * @param {boolean} isRootFile a flag to check if current file which involking the parse() api, used to distinguish the normal cache which only parsed by parseFile()
- * @param {Promise<T>} result
- */
- setParseResult(file, result, isRootFile = false) {
- Object.defineProperty(result, "_isRootFile_", {
- value: isRootFile,
- writable: false,
- enumerable: false,
- configurable: false
- });
- this.#parsed.set(file, result);
- result.then((parsed) => {
- if (this.#parsed.get(file) === result) this.#parsed.set(file, parsed);
- }).catch((e$1) => {
- if (this.#parsed.get(file) === result) this.#parsed.set(file, e$1);
- });
- }
- /**
- * @internal
- * @private
- * @param {string} dir
- * @param {Promise<string|null>} configPath
- * @param {string} [configName=tsconfig.json]
- */
- setConfigPath(dir, configPath, configName = "tsconfig.json") {
- const key = `${dir}/${configName}`;
- this.#configPaths.set(key, configPath);
- configPath.then((path$13) => {
- if (this.#configPaths.get(key) === configPath) this.#configPaths.set(key, path$13);
- }).catch((e$1) => {
- if (this.#configPaths.get(key) === configPath) this.#configPaths.set(key, e$1);
- });
- }
- /**
- * map directories to their closest tsconfig.json
- * @internal
- * @private
- * @type{Map<string,(Promise<string|null>|string|null)>}
- */
- #configPaths = /* @__PURE__ */ new Map();
- /**
- * map files to their parsed tsconfig result
- * @internal
- * @private
- * @type {Map<string,(Promise<T>|T)> }
- */
- #parsed = /* @__PURE__ */ new Map();
-};
-
-//#endregion
-//#region src/node/plugins/esbuild.ts
-var import_picocolors$31 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const debug$17 = createDebugger("vite:esbuild");
-const IIFE_BEGIN_RE = /(?:const|var)\s+\S+\s*=\s*\(?function\([^()]*\)\s*\{\s*"use strict";/;
-const validExtensionRE = /\.\w+$/;
-const jsxExtensionsRE = /\.(?:j|t)sx\b/;
-const defaultEsbuildSupported = {
- "dynamic-import": true,
- "import-meta": true
-};
-async function transformWithEsbuild(code, filename, options$1, inMap, config$2, watcher) {
- let loader$1 = options$1?.loader;
- if (!loader$1) {
- const ext = path.extname(validExtensionRE.test(filename) ? filename : cleanUrl(filename)).slice(1);
- if (ext === "cjs" || ext === "mjs") loader$1 = "js";
- else if (ext === "cts" || ext === "mts") loader$1 = "ts";
- else loader$1 = ext;
- }
- let tsconfigRaw = options$1?.tsconfigRaw;
- if (typeof tsconfigRaw !== "string") {
- const meaningfulFields = [
- "alwaysStrict",
- "experimentalDecorators",
- "importsNotUsedAsValues",
- "jsx",
- "jsxFactory",
- "jsxFragmentFactory",
- "jsxImportSource",
- "preserveValueImports",
- "target",
- "useDefineForClassFields",
- "verbatimModuleSyntax"
- ];
- const compilerOptionsForFile = {};
- if (loader$1 === "ts" || loader$1 === "tsx") try {
- const { tsconfig: loadedTsconfig, tsconfigFile } = await loadTsconfigJsonForFile(filename, config$2);
- if (watcher && tsconfigFile && config$2) ensureWatchedFile(watcher, tsconfigFile, config$2.root);
- const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {};
- for (const field of meaningfulFields) if (field in loadedCompilerOptions) compilerOptionsForFile[field] = loadedCompilerOptions[field];
- } catch (e$1) {
- if (e$1 instanceof TSConfckParseError) {
- if (watcher && e$1.tsconfigFile && config$2) ensureWatchedFile(watcher, e$1.tsconfigFile, config$2.root);
- }
- throw e$1;
- }
- const compilerOptions = {
- ...compilerOptionsForFile,
- ...tsconfigRaw?.compilerOptions
- };
- if (compilerOptions.useDefineForClassFields === void 0 && compilerOptions.target === void 0) compilerOptions.useDefineForClassFields = false;
- if (options$1) {
- if (options$1.jsx) compilerOptions.jsx = void 0;
- if (options$1.jsxFactory) compilerOptions.jsxFactory = void 0;
- if (options$1.jsxFragment) compilerOptions.jsxFragmentFactory = void 0;
- if (options$1.jsxImportSource) compilerOptions.jsxImportSource = void 0;
- }
- tsconfigRaw = {
- ...tsconfigRaw,
- compilerOptions
- };
- }
- const resolvedOptions = {
- sourcemap: true,
- sourcefile: filename,
- ...options$1,
- loader: loader$1,
- tsconfigRaw
- };
- delete resolvedOptions.include;
- delete resolvedOptions.exclude;
- delete resolvedOptions.jsxInject;
- try {
- const result = await transform(code, resolvedOptions);
- let map$1;
- if (inMap && resolvedOptions.sourcemap) {
- const nextMap = JSON.parse(result.map);
- nextMap.sourcesContent = [];
- map$1 = combineSourcemaps(filename, [nextMap, inMap]);
- } else map$1 = resolvedOptions.sourcemap && resolvedOptions.sourcemap !== "inline" ? JSON.parse(result.map) : { mappings: "" };
- return {
- ...result,
- map: map$1
- };
- } catch (e$1) {
- debug$17?.(`esbuild error with options used: `, resolvedOptions);
- if (e$1.errors) {
- e$1.frame = "";
- e$1.errors.forEach((m) => {
- if (m.text === "Experimental decorators are not currently enabled" || m.text === "Parameter decorators only work when experimental decorators are enabled") m.text += ". Vite 5 now uses esbuild 0.18 and you need to enable them by adding \"experimentalDecorators\": true in your \"tsconfig.json\" file.";
- e$1.frame += `\n` + prettifyMessage(m, code);
- });
- e$1.loc = e$1.errors[0].location;
- }
- throw e$1;
- }
-}
-function esbuildPlugin(config$2) {
- const { jsxInject, include, exclude, ...esbuildTransformOptions } = config$2.esbuild;
- const filter$1 = createFilter(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/);
- const transformOptions = {
- target: "esnext",
- ...esbuildTransformOptions,
- minify: false,
- minifyIdentifiers: false,
- minifySyntax: false,
- minifyWhitespace: false,
- treeShaking: false,
- keepNames: false,
- supported: {
- ...defaultEsbuildSupported,
- ...esbuildTransformOptions.supported
- }
- };
- let server;
- return {
- name: "vite:esbuild",
- configureServer(_server) {
- server = _server;
- },
- async transform(code, id) {
- if (filter$1(id) || filter$1(cleanUrl(id))) {
- const result = await transformWithEsbuild(code, id, transformOptions, void 0, config$2, server?.watcher);
- if (result.warnings.length) result.warnings.forEach((m) => {
- this.warn(prettifyMessage(m, code));
- });
- if (jsxInject && jsxExtensionsRE.test(id)) result.code = jsxInject + ";" + result.code;
- return {
- code: result.code,
- map: result.map
- };
- }
- }
- };
-}
-const rollupToEsbuildFormatMap = {
- es: "esm",
- cjs: "cjs",
- iife: void 0
-};
-const injectEsbuildHelpers = (esbuildCode, format$3) => {
- const contentIndex = format$3 === "iife" ? Math.max(esbuildCode.search(IIFE_BEGIN_RE), 0) : format$3 === "umd" ? esbuildCode.indexOf(`(function(`) : 0;
- if (contentIndex > 0) {
- const esbuildHelpers = esbuildCode.slice(0, contentIndex);
- return esbuildCode.slice(contentIndex).replace("\"use strict\";", (m) => m + esbuildHelpers);
- }
- return esbuildCode;
-};
-const buildEsbuildPlugin = () => {
- return {
- name: "vite:esbuild-transpile",
- applyToEnvironment(environment) {
- return environment.config.esbuild !== false;
- },
- async renderChunk(code, chunk, opts) {
- if (opts.__vite_skip_esbuild__) return null;
- const config$2 = this.environment.config;
- const options$1 = resolveEsbuildTranspileOptions(config$2, opts.format);
- if (!options$1) return null;
- const res = await transformWithEsbuild(code, chunk.fileName, options$1, void 0, config$2);
- if (config$2.build.lib) res.code = injectEsbuildHelpers(res.code, opts.format);
- return res;
- }
- };
-};
-function resolveEsbuildTranspileOptions(config$2, format$3) {
- const target = config$2.build.target;
- const minify = config$2.build.minify === "esbuild";
- if ((!target || target === "esnext") && !minify) return null;
- const isEsLibBuild = config$2.build.lib && format$3 === "es";
- const esbuildOptions = config$2.esbuild || {};
- const options$1 = {
- ...esbuildOptions,
- loader: "js",
- target: target || void 0,
- format: rollupToEsbuildFormatMap[format$3],
- supported: {
- ...defaultEsbuildSupported,
- ...esbuildOptions.supported
- }
- };
- if (!minify) return {
- ...options$1,
- minify: false,
- minifyIdentifiers: false,
- minifySyntax: false,
- minifyWhitespace: false,
- treeShaking: false
- };
- if (options$1.minifyIdentifiers != null || options$1.minifySyntax != null || options$1.minifyWhitespace != null) if (isEsLibBuild) return {
- ...options$1,
- minify: false,
- minifyIdentifiers: options$1.minifyIdentifiers ?? true,
- minifySyntax: options$1.minifySyntax ?? true,
- minifyWhitespace: false,
- treeShaking: true
- };
- else return {
- ...options$1,
- minify: false,
- minifyIdentifiers: options$1.minifyIdentifiers ?? true,
- minifySyntax: options$1.minifySyntax ?? true,
- minifyWhitespace: options$1.minifyWhitespace ?? true,
- treeShaking: true
- };
- if (isEsLibBuild) return {
- ...options$1,
- minify: false,
- minifyIdentifiers: true,
- minifySyntax: true,
- minifyWhitespace: false,
- treeShaking: true
- };
- else return {
- ...options$1,
- minify: true,
- treeShaking: true
- };
-}
-function prettifyMessage(m, code) {
- let res = import_picocolors$31.default.yellow(m.text);
- if (m.location) res += `\n` + generateCodeFrame(code, m.location);
- return res + `\n`;
-}
-let globalTSConfckCache;
-const tsconfckCacheMap = /* @__PURE__ */ new WeakMap();
-function getTSConfckCache(config$2) {
- if (!config$2) return globalTSConfckCache ??= new TSConfckCache();
- let cache$1 = tsconfckCacheMap.get(config$2);
- if (!cache$1) {
- cache$1 = new TSConfckCache();
- tsconfckCacheMap.set(config$2, cache$1);
- }
- return cache$1;
-}
-async function loadTsconfigJsonForFile(filename, config$2) {
- const { tsconfig, tsconfigFile } = await parse$13(filename, {
- cache: getTSConfckCache(config$2),
- ignoreNodeModules: true
- });
- return {
- tsconfigFile,
- tsconfig
- };
-}
-async function reloadOnTsconfigChange(server, changedFile) {
- if (changedFile.endsWith(".json")) {
- const cache$1 = getTSConfckCache(server.config);
- if (changedFile.endsWith("/tsconfig.json") || cache$1.hasParseResult(changedFile)) {
- server.config.logger.info(`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`, {
- clear: server.config.clearScreen,
- timestamp: true
- });
- for (const environment of Object.values(server.environments)) environment.moduleGraph.invalidateAll();
- cache$1.clear();
- for (const environment of Object.values(server.environments)) environment.hot.send({
- type: "full-reload",
- path: "*"
- });
- }
- }
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/artichokie@0.4.2/node_modules/artichokie/dist/index.js
-const AsyncFunction = async function() {}.constructor;
-const codeToDataUrl = (code) => `data:application/javascript,${encodeURIComponent(code + "\n//# sourceURL=[worker-eval(artichokie)]")}`;
-const viteSsrDynamicImport = "__vite_ssr_dynamic_import__";
-const stackBlitzImport = "𝐢𝐦𝐩𝐨𝐫𝐭";
-var Worker$1 = class {
- /** @internal */
- _isModule;
- /** @internal */
- _code;
- /** @internal */
- _parentFunctions;
- /** @internal */
- _max;
- /** @internal */
- _pool;
- /** @internal */
- _idlePool;
- /** @internal */
- _queue;
- constructor(fn, options$1 = {}) {
- this._isModule = options$1.type === "module";
- this._code = genWorkerCode(fn, this._isModule, 5 * 1e3, options$1.parentFunctions ?? {});
- this._parentFunctions = options$1.parentFunctions ?? {};
- const defaultMax = Math.max(1, (os.availableParallelism?.() ?? os.cpus().length) - 1);
- this._max = options$1.max || defaultMax;
- this._pool = [];
- this._idlePool = [];
- this._queue = [];
- }
- async run(...args) {
- const worker = await this._getAvailableWorker();
- return new Promise((resolve$4, reject) => {
- worker.currentResolve = resolve$4;
- worker.currentReject = reject;
- worker.postMessage({ args });
- });
- }
- stop() {
- this._pool.forEach((w) => w.unref());
- this._queue.forEach(([, reject]) => reject(/* @__PURE__ */ new Error("Main worker pool stopped before a worker was available.")));
- this._pool = [];
- this._idlePool = [];
- this._queue = [];
- }
- /** @internal */
- _createWorker(parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort, lockState) {
- const options$1 = {
- workerData: [
- parentFunctionSyncMessagePort,
- parentFunctionAsyncMessagePort,
- lockState
- ],
- transferList: [parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort]
- };
- if (this._isModule) return new Worker(new URL(codeToDataUrl(this._code)), options$1);
- return new Worker(this._code, {
- ...options$1,
- eval: true
- });
- }
- /** @internal */
- async _getAvailableWorker() {
- if (this._idlePool.length) return this._idlePool.shift();
- if (this._pool.length < this._max) {
- const parentFunctionResponder = createParentFunctionResponder(this._parentFunctions);
- const worker = this._createWorker(parentFunctionResponder.workerPorts.sync, parentFunctionResponder.workerPorts.async, parentFunctionResponder.lockState);
- worker.on("message", async (args) => {
- if ("result" in args) {
- worker.currentResolve?.(args.result);
- worker.currentResolve = null;
- } else {
- if (args.error instanceof ReferenceError) args.error.message += ". Maybe you forgot to pass the function to parentFunction?";
- worker.currentReject?.(args.error);
- worker.currentReject = null;
- }
- this._assignDoneWorker(worker);
- });
- worker.on("error", (err$2) => {
- worker.currentReject?.(err$2);
- worker.currentReject = null;
- parentFunctionResponder.close();
- });
- worker.on("exit", (code) => {
- const i$1 = this._pool.indexOf(worker);
- if (i$1 > -1) this._pool.splice(i$1, 1);
- if (code !== 0 && worker.currentReject) {
- worker.currentReject(/* @__PURE__ */ new Error(`Worker stopped with non-0 exit code ${code}`));
- worker.currentReject = null;
- parentFunctionResponder.close();
- }
- });
- this._pool.push(worker);
- return worker;
- }
- let resolve$4;
- let reject;
- const onWorkerAvailablePromise = new Promise((r$1, rj) => {
- resolve$4 = r$1;
- reject = rj;
- });
- this._queue.push([resolve$4, reject]);
- return onWorkerAvailablePromise;
- }
- /** @internal */
- _assignDoneWorker(worker) {
- if (this._queue.length) {
- const [resolve$4] = this._queue.shift();
- resolve$4(worker);
- return;
- }
- this._idlePool.push(worker);
- }
-};
-function createParentFunctionResponder(parentFunctions) {
- const lockState = new Int32Array(new SharedArrayBuffer(4));
- const unlock = () => {
- Atomics.store(lockState, 0, 0);
- Atomics.notify(lockState, 0);
- };
- const parentFunctionSyncMessageChannel = new MessageChannel();
- const parentFunctionAsyncMessageChannel = new MessageChannel();
- const parentFunctionSyncMessagePort = parentFunctionSyncMessageChannel.port1;
- const parentFunctionAsyncMessagePort = parentFunctionAsyncMessageChannel.port1;
- const syncResponse = (data) => {
- parentFunctionSyncMessagePort.postMessage(data);
- unlock();
- };
- parentFunctionSyncMessagePort.on("message", async (args) => {
- let syncResult;
- try {
- syncResult = parentFunctions[args.name](...args.args);
- } catch (error$1) {
- syncResponse({
- id: args.id,
- error: error$1
- });
- return;
- }
- if (!(typeof syncResult === "object" && syncResult !== null && "then" in syncResult && typeof syncResult.then === "function")) {
- syncResponse({
- id: args.id,
- result: syncResult
- });
- return;
- }
- syncResponse({
- id: args.id,
- isAsync: true
- });
- try {
- const result = await syncResult;
- parentFunctionAsyncMessagePort.postMessage({
- id: args.id,
- result
- });
- } catch (error$1) {
- parentFunctionAsyncMessagePort.postMessage({
- id: args.id,
- error: error$1
- });
- }
- });
- parentFunctionSyncMessagePort.unref();
- return {
- close: () => {
- parentFunctionSyncMessagePort.close();
- parentFunctionAsyncMessagePort.close();
- },
- lockState,
- workerPorts: {
- sync: parentFunctionSyncMessageChannel.port2,
- async: parentFunctionAsyncMessageChannel.port2
- }
- };
-}
-function genWorkerCode(fn, isModule, waitTimeout, parentFunctions) {
- const createLock = (performance$2, lockState) => {
- return {
- lock: () => {
- Atomics.store(lockState, 0, 1);
- },
- waitUnlock: () => {
- let utilizationBefore;
- while (true) {
- const status$1 = Atomics.wait(lockState, 0, 1, waitTimeout);
- if (status$1 === "timed-out") {
- if (utilizationBefore === void 0) {
- utilizationBefore = performance$2.eventLoopUtilization();
- continue;
- }
- utilizationBefore = performance$2.eventLoopUtilization(utilizationBefore);
- if (utilizationBefore.utilization > .9) continue;
- throw new Error(status$1);
- }
- break;
- }
- }
- };
- };
- const createParentFunctionRequester = (syncPort, asyncPort, receive, lock) => {
- let id = 0;
- const resolvers = /* @__PURE__ */ new Map();
- const call$1 = (key) => (...args) => {
- id++;
- lock.lock();
- syncPort.postMessage({
- id,
- name: key,
- args
- });
- lock.waitUnlock();
- const resArgs = receive(syncPort).message;
- if (resArgs.isAsync) {
- let resolve$4, reject;
- const promise = new Promise((res, rej) => {
- resolve$4 = res;
- reject = rej;
- });
- resolvers.set(id, {
- resolve: resolve$4,
- reject
- });
- return promise;
- }
- if ("error" in resArgs) throw resArgs.error;
- else return resArgs.result;
- };
- asyncPort.on("message", (args) => {
- const id$1 = args.id;
- if (resolvers.has(id$1)) {
- const { resolve: resolve$4, reject } = resolvers.get(id$1);
- resolvers.delete(id$1);
- if ("result" in args) resolve$4(args.result);
- else reject(args.error);
- }
- });
- return { call: call$1 };
- };
- const fnString = fn.toString().replaceAll(stackBlitzImport, "import").replaceAll(viteSsrDynamicImport, "import");
- return `
-${isModule ? "import { parentPort, receiveMessageOnPort, workerData } from 'worker_threads'" : "const { parentPort, receiveMessageOnPort, workerData } = require('worker_threads')"}
-${isModule ? "import { performance } from 'node:perf_hooks'" : "const { performance } = require('node:perf_hooks')"}
-const [parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort, lockState] = workerData
-const waitTimeout = ${waitTimeout}
-const createLock = ${createLock.toString()}
-const parentFunctionRequester = (${createParentFunctionRequester.toString()})(
- parentFunctionSyncMessagePort,
- parentFunctionAsyncMessagePort,
- receiveMessageOnPort,
- createLock(performance, lockState)
-)
-
-const doWorkPromise = (async () => {
- ${Object.keys(parentFunctions).map((key) => `const ${key} = parentFunctionRequester.call(${JSON.stringify(key)});`).join("\n")}
- return await (${fnString})()
-})()
-let doWork
-
-parentPort.on('message', async (args) => {
- doWork ||= await doWorkPromise
-
- try {
- const res = await doWork(...args.args)
- parentPort.postMessage({ result: res })
- } catch (e) {
- parentPort.postMessage({ error: e })
- }
-})
- `;
-}
-const importRe = /\bimport\s*\(/g;
-const internalImportName = "__artichokie_local_import__";
-var FakeWorker = class {
- /** @internal */
- _fn;
- constructor(fn, options$1 = {}) {
- const declareRequire = options$1.type !== "module";
- const argsAndCode = genFakeWorkerArgsAndCode(fn, declareRequire, options$1.parentFunctions ?? {});
- const localImport = (specifier) => import(specifier);
- const args = [
- ...declareRequire ? [createRequire(import.meta.url)] : [],
- localImport,
- options$1.parentFunctions
- ];
- this._fn = new AsyncFunction(...argsAndCode)(...args);
- }
- async run(...args) {
- try {
- return await (await this._fn)(...args);
- } catch (err$2) {
- if (err$2 instanceof ReferenceError) err$2.message += ". Maybe you forgot to pass the function to parentFunction?";
- throw err$2;
- }
- }
- stop() {}
-};
-function genFakeWorkerArgsAndCode(fn, declareRequire, parentFunctions) {
- const fnString = fn.toString().replace(importRe, `${internalImportName}(`).replaceAll(stackBlitzImport, internalImportName).replaceAll(viteSsrDynamicImport, internalImportName);
- return [
- ...declareRequire ? ["require"] : [],
- internalImportName,
- "parentFunctions",
- `
-${Object.keys(parentFunctions).map((key) => `const ${key} = parentFunctions[${JSON.stringify(key)}];`).join("\n")}
-return await (${fnString})()
- `
- ];
-}
-var WorkerWithFallback = class {
- /** @internal */
- _disableReal;
- /** @internal */
- _realWorker;
- /** @internal */
- _fakeWorker;
- /** @internal */
- _shouldUseFake;
- constructor(fn, options$1) {
- this._disableReal = options$1.max !== void 0 && options$1.max <= 0;
- this._realWorker = new Worker$1(fn, options$1);
- this._fakeWorker = new FakeWorker(fn, options$1);
- this._shouldUseFake = options$1.shouldUseFake;
- }
- async run(...args) {
- const useFake = this._disableReal || this._shouldUseFake(...args);
- return this[useFake ? "_fakeWorker" : "_realWorker"].run(...args);
- }
- stop() {
- this._realWorker.stop();
- this._fakeWorker.stop();
- }
-};
-
-//#endregion
-//#region ../../node_modules/.pnpm/resolve.exports@2.0.3/node_modules/resolve.exports/dist/index.mjs
-function e(e$1, n$2, r$1) {
- throw new Error(r$1 ? `No known conditions for "${n$2}" specifier in "${e$1}" package` : `Missing "${n$2}" specifier in "${e$1}" package`);
-}
-function n(n$2, i$1, o$1, f$1) {
- let s, u, l = r(n$2, o$1), c = function(e$1) {
- let n$3 = new Set(["default", ...e$1.conditions || []]);
- return e$1.unsafe || n$3.add(e$1.require ? "require" : "import"), e$1.unsafe || n$3.add(e$1.browser ? "browser" : "node"), n$3;
- }(f$1 || {}), a = i$1[l];
- if (void 0 === a) {
- let e$1, n$3, r$1, t$1;
- for (t$1 in i$1) n$3 && t$1.length < n$3.length || ("/" === t$1[t$1.length - 1] && l.startsWith(t$1) ? (u = l.substring(t$1.length), n$3 = t$1) : t$1.length > 1 && (r$1 = t$1.indexOf("*", 1), ~r$1 && (e$1 = RegExp("^" + t$1.substring(0, r$1) + "(.*)" + t$1.substring(1 + r$1) + "$").exec(l), e$1 && e$1[1] && (u = e$1[1], n$3 = t$1))));
- a = i$1[n$3];
- }
- return a || e(n$2, l), s = t(a, c), s || e(n$2, l, 1), u && function(e$1, n$3) {
- let r$1, t$1 = 0, i$2 = e$1.length, o$2 = /[*]/g, f$2 = /[/]$/;
- for (; t$1 < i$2; t$1++) e$1[t$1] = o$2.test(r$1 = e$1[t$1]) ? r$1.replace(o$2, n$3) : f$2.test(r$1) ? r$1 + n$3 : r$1;
- }(s, u), s;
-}
-function r(e$1, n$2, r$1) {
- if (e$1 === n$2 || "." === n$2) return ".";
- let t$1 = e$1 + "/", i$1 = t$1.length, o$1 = n$2.slice(0, i$1) === t$1, f$1 = o$1 ? n$2.slice(i$1) : n$2;
- return "#" === f$1[0] ? f$1 : o$1 || !r$1 ? "./" === f$1.slice(0, 2) ? f$1 : "./" + f$1 : f$1;
-}
-function t(e$1, n$2, r$1) {
- if (e$1) {
- if ("string" == typeof e$1) return r$1 && r$1.add(e$1), [e$1];
- let i$1, o$1;
- if (Array.isArray(e$1)) {
- for (o$1 = r$1 || /* @__PURE__ */ new Set(), i$1 = 0; i$1 < e$1.length; i$1++) t(e$1[i$1], n$2, o$1);
- if (!r$1 && o$1.size) return [...o$1];
- } else for (i$1 in e$1) if (n$2.has(i$1)) return t(e$1[i$1], n$2, r$1);
- }
-}
-function o(e$1, r$1, t$1) {
- let i$1, o$1 = e$1.exports;
- if (o$1) {
- if ("string" == typeof o$1) o$1 = { ".": o$1 };
- else for (i$1 in o$1) {
- "." !== i$1[0] && (o$1 = { ".": o$1 });
- break;
- }
- return n(e$1.name, o$1, r$1 || ".", t$1);
- }
-}
-function f(e$1, r$1, t$1) {
- if (e$1.imports) return n(e$1.name, e$1.imports, r$1, t$1);
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/ufo@1.6.1/node_modules/ufo/dist/index.mjs
-const HASH_RE = /#/g;
-const AMPERSAND_RE = /&/g;
-const SLASH_RE = /\//g;
-const EQUAL_RE = /=/g;
-const PLUS_RE = /\+/g;
-const ENC_CARET_RE = /%5e/gi;
-const ENC_BACKTICK_RE = /%60/gi;
-const ENC_PIPE_RE = /%7c/gi;
-const ENC_SPACE_RE = /%20/gi;
-function encode(text) {
- return encodeURI("" + text).replace(ENC_PIPE_RE, "|");
-}
-function encodeQueryValue(input) {
- return encode(typeof input === "string" ? input : JSON.stringify(input)).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CARET_RE, "^").replace(SLASH_RE, "%2F");
-}
-function encodeQueryKey(text) {
- return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
-}
-function encodeQueryItem(key, value$1) {
- if (typeof value$1 === "number" || typeof value$1 === "boolean") value$1 = String(value$1);
- if (!value$1) return encodeQueryKey(key);
- if (Array.isArray(value$1)) return value$1.map((_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&");
- return `${encodeQueryKey(key)}=${encodeQueryValue(value$1)}`;
-}
-function stringifyQuery(query) {
- return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&");
-}
-const protocolRelative = Symbol.for("ufo:protocolRelative");
-
-//#endregion
-//#region ../../node_modules/.pnpm/mlly@1.8.0/node_modules/mlly/dist/index.mjs
-const BUILTIN_MODULES = new Set(builtinModules);
-function clearImports(imports) {
- return (imports || "").replace(/\/\/[^\n]*\n|\/\*.*\*\//g, "").replace(/\s+/g, " ");
-}
-function getImportNames(cleanedImports) {
- const topLevelImports = cleanedImports.replace(/{[^}]*}/, "");
- return {
- namespacedImport: topLevelImports.match(/\* as \s*(\S*)/)?.[1],
- defaultImport: topLevelImports.split(",").find((index) => !/[*{}]/.test(index))?.trim() || void 0
- };
-}
-/**
-* @typedef ErrnoExceptionFields
-* @property {number | undefined} [errnode]
-* @property {string | undefined} [code]
-* @property {string | undefined} [path]
-* @property {string | undefined} [syscall]
-* @property {string | undefined} [url]
-*
-* @typedef {Error & ErrnoExceptionFields} ErrnoException
-*/
-const own$1 = {}.hasOwnProperty;
-const classRegExp = /^([A-Z][a-z\d]*)+$/;
-const kTypes = new Set([
- "string",
- "function",
- "number",
- "object",
- "Function",
- "Object",
- "boolean",
- "bigint",
- "symbol"
-]);
-const codes$1 = {};
-/**
-* Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
-* We cannot use Intl.ListFormat because it's not available in
-* --without-intl builds.
-*
-* @param {Array<string>} array
-* An array of strings.
-* @param {string} [type]
-* The list type to be inserted before the last element.
-* @returns {string}
-*/
-function formatList(array, type = "and") {
- return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(", ")}, ${type} ${array[array.length - 1]}`;
-}
-/** @type {Map<string, MessageFunction | string>} */
-const messages = /* @__PURE__ */ new Map();
-const nodeInternalPrefix = "__node_internal_";
-/** @type {number} */
-let userStackTraceLimit;
-codes$1.ERR_INVALID_ARG_TYPE = createError(
- "ERR_INVALID_ARG_TYPE",
- /**
- * @param {string} name
- * @param {Array<string> | string} expected
- * @param {unknown} actual
- */
- (name, expected, actual) => {
- assert(typeof name === "string", "'name' must be a string");
- if (!Array.isArray(expected)) expected = [expected];
- let message = "The ";
- if (name.endsWith(" argument")) message += `${name} `;
- else {
- const type = name.includes(".") ? "property" : "argument";
- message += `"${name}" ${type} `;
- }
- message += "must be ";
- /** @type {Array<string>} */
- const types = [];
- /** @type {Array<string>} */
- const instances = [];
- /** @type {Array<string>} */
- const other = [];
- for (const value$1 of expected) {
- assert(typeof value$1 === "string", "All expected entries have to be of type string");
- if (kTypes.has(value$1)) types.push(value$1.toLowerCase());
- else if (classRegExp.exec(value$1) === null) {
- assert(value$1 !== "object", "The value \"object\" should be written as \"Object\"");
- other.push(value$1);
- } else instances.push(value$1);
- }
- if (instances.length > 0) {
- const pos = types.indexOf("object");
- if (pos !== -1) {
- types.slice(pos, 1);
- instances.push("Object");
- }
- }
- if (types.length > 0) {
- message += `${types.length > 1 ? "one of type" : "of type"} ${formatList(types, "or")}`;
- if (instances.length > 0 || other.length > 0) message += " or ";
- }
- if (instances.length > 0) {
- message += `an instance of ${formatList(instances, "or")}`;
- if (other.length > 0) message += " or ";
- }
- if (other.length > 0) if (other.length > 1) message += `one of ${formatList(other, "or")}`;
- else {
- if (other[0].toLowerCase() !== other[0]) message += "an ";
- message += `${other[0]}`;
- }
- message += `. Received ${determineSpecificType(actual)}`;
- return message;
- },
- TypeError
-);
-codes$1.ERR_INVALID_MODULE_SPECIFIER = createError(
- "ERR_INVALID_MODULE_SPECIFIER",
- /**
- * @param {string} request
- * @param {string} reason
- * @param {string} [base]
- */
- (request, reason, base = void 0) => {
- return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`;
- },
- TypeError
-);
-codes$1.ERR_INVALID_PACKAGE_CONFIG = createError(
- "ERR_INVALID_PACKAGE_CONFIG",
- /**
- * @param {string} path
- * @param {string} [base]
- * @param {string} [message]
- */
- (path$13, base, message) => {
- return `Invalid package config ${path$13}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
- },
- Error
-);
-codes$1.ERR_INVALID_PACKAGE_TARGET = createError(
- "ERR_INVALID_PACKAGE_TARGET",
- /**
- * @param {string} packagePath
- * @param {string} key
- * @param {unknown} target
- * @param {boolean} [isImport=false]
- * @param {string} [base]
- */
- (packagePath, key, target, isImport = false, base = void 0) => {
- const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
- if (key === ".") {
- assert(isImport === false);
- return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? "; targets must start with \"./\"" : ""}`;
- }
- return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(target)} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? "; targets must start with \"./\"" : ""}`;
- },
- Error
-);
-codes$1.ERR_MODULE_NOT_FOUND = createError(
- "ERR_MODULE_NOT_FOUND",
- /**
- * @param {string} path
- * @param {string} base
- * @param {boolean} [exactUrl]
- */
- (path$13, base, exactUrl = false) => {
- return `Cannot find ${exactUrl ? "module" : "package"} '${path$13}' imported from ${base}`;
- },
- Error
-);
-codes$1.ERR_NETWORK_IMPORT_DISALLOWED = createError("ERR_NETWORK_IMPORT_DISALLOWED", "import of '%s' by %s is not supported: %s", Error);
-codes$1.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
- "ERR_PACKAGE_IMPORT_NOT_DEFINED",
- /**
- * @param {string} specifier
- * @param {string} packagePath
- * @param {string} base
- */
- (specifier, packagePath, base) => {
- return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ""} imported from ${base}`;
- },
- TypeError
-);
-codes$1.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
- "ERR_PACKAGE_PATH_NOT_EXPORTED",
- /**
- * @param {string} packagePath
- * @param {string} subpath
- * @param {string} [base]
- */
- (packagePath, subpath, base = void 0) => {
- if (subpath === ".") return `No "exports" main defined in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
- return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
- },
- Error
-);
-codes$1.ERR_UNSUPPORTED_DIR_IMPORT = createError("ERR_UNSUPPORTED_DIR_IMPORT", "Directory import '%s' is not supported resolving ES modules imported from %s", Error);
-codes$1.ERR_UNSUPPORTED_RESOLVE_REQUEST = createError("ERR_UNSUPPORTED_RESOLVE_REQUEST", "Failed to resolve module specifier \"%s\" from \"%s\": Invalid relative URL or base scheme is not hierarchical.", TypeError);
-codes$1.ERR_UNKNOWN_FILE_EXTENSION = createError(
- "ERR_UNKNOWN_FILE_EXTENSION",
- /**
- * @param {string} extension
- * @param {string} path
- */
- (extension$1, path$13) => {
- return `Unknown file extension "${extension$1}" for ${path$13}`;
- },
- TypeError
-);
-codes$1.ERR_INVALID_ARG_VALUE = createError(
- "ERR_INVALID_ARG_VALUE",
- /**
- * @param {string} name
- * @param {unknown} value
- * @param {string} [reason='is invalid']
- */
- (name, value$1, reason = "is invalid") => {
- let inspected = inspect(value$1);
- if (inspected.length > 128) inspected = `${inspected.slice(0, 128)}...`;
- return `The ${name.includes(".") ? "property" : "argument"} '${name}' ${reason}. Received ${inspected}`;
- },
- TypeError
-);
-/**
-* Utility function for registering the error codes. Only used here. Exported
-* *only* to allow for testing.
-* @param {string} sym
-* @param {MessageFunction | string} value
-* @param {ErrorConstructor} constructor
-* @returns {new (...parameters: Array<any>) => Error}
-*/
-function createError(sym, value$1, constructor) {
- messages.set(sym, value$1);
- return makeNodeErrorWithCode(constructor, sym);
-}
-/**
-* @param {ErrorConstructor} Base
-* @param {string} key
-* @returns {ErrorConstructor}
-*/
-function makeNodeErrorWithCode(Base, key) {
- return NodeError;
- /**
- * @param {Array<unknown>} parameters
- */
- function NodeError(...parameters) {
- const limit = Error.stackTraceLimit;
- if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
- const error$1 = new Base();
- if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
- const message = getMessage(key, parameters, error$1);
- Object.defineProperties(error$1, {
- message: {
- value: message,
- enumerable: false,
- writable: true,
- configurable: true
- },
- toString: {
- value() {
- return `${this.name} [${key}]: ${this.message}`;
- },
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- captureLargerStackTrace(error$1);
- error$1.code = key;
- return error$1;
- }
-}
-/**
-* @returns {boolean}
-*/
-function isErrorStackTraceLimitWritable() {
- try {
- if (v8.startupSnapshot.isBuildingSnapshot()) return false;
- } catch {}
- const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
- if (desc === void 0) return Object.isExtensible(Error);
- return own$1.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0;
-}
-/**
-* This function removes unnecessary frames from Node.js core errors.
-* @template {(...parameters: unknown[]) => unknown} T
-* @param {T} wrappedFunction
-* @returns {T}
-*/
-function hideStackFrames(wrappedFunction) {
- const hidden = nodeInternalPrefix + wrappedFunction.name;
- Object.defineProperty(wrappedFunction, "name", { value: hidden });
- return wrappedFunction;
-}
-const captureLargerStackTrace = hideStackFrames(
- /**
- * @param {Error} error
- * @returns {Error}
- */
- function(error$1) {
- const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
- if (stackTraceLimitIsWritable) {
- userStackTraceLimit = Error.stackTraceLimit;
- Error.stackTraceLimit = Number.POSITIVE_INFINITY;
- }
- Error.captureStackTrace(error$1);
- if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
- return error$1;
- }
-);
-/**
-* @param {string} key
-* @param {Array<unknown>} parameters
-* @param {Error} self
-* @returns {string}
-*/
-function getMessage(key, parameters, self$1) {
- const message = messages.get(key);
- assert(message !== void 0, "expected `message` to be found");
- if (typeof message === "function") {
- assert(message.length <= parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`);
- return Reflect.apply(message, self$1, parameters);
- }
- const regex = /%[dfijoOs]/g;
- let expectedLength = 0;
- while (regex.exec(message) !== null) expectedLength++;
- assert(expectedLength === parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`);
- if (parameters.length === 0) return message;
- parameters.unshift(message);
- return Reflect.apply(format, null, parameters);
-}
-/**
-* Determine the specific type of a value for type-mismatch errors.
-* @param {unknown} value
-* @returns {string}
-*/
-function determineSpecificType(value$1) {
- if (value$1 === null || value$1 === void 0) return String(value$1);
- if (typeof value$1 === "function" && value$1.name) return `function ${value$1.name}`;
- if (typeof value$1 === "object") {
- if (value$1.constructor && value$1.constructor.name) return `an instance of ${value$1.constructor.name}`;
- return `${inspect(value$1, { depth: -1 })}`;
- }
- let inspected = inspect(value$1, { colors: false });
- if (inspected.length > 28) inspected = `${inspected.slice(0, 25)}...`;
- return `type ${typeof value$1} (${inspected})`;
-}
-const ESM_STATIC_IMPORT_RE = /(?<=\s|^|;|\})import\s*(?:[\s"']*(?<imports>[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gmu;
-const TYPE_RE = /^\s*?type\s/;
-function parseStaticImport(matched) {
- const cleanedImports = clearImports(matched.imports);
- const namedImports = {};
- const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || [];
- for (const namedImport of _matches) {
- const _match = namedImport.match(/^\s*(\S*) as (\S*)\s*$/);
- const source = _match?.[1] || namedImport.trim();
- const importName = _match?.[2] || source;
- if (source && !TYPE_RE.test(source)) namedImports[source] = importName;
- }
- const { namespacedImport, defaultImport } = getImportNames(cleanedImports);
- return {
- ...matched,
- defaultImport,
- namespacedImport,
- namedImports
- };
-}
-const ESM_RE = /(?:[\s;]|^)(?:import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m;
-const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g;
-function hasESMSyntax(code, opts = {}) {
- if (opts.stripComments) code = code.replace(COMMENT_RE, "");
- return ESM_RE.test(code);
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/@rolldown+pluginutils@1.0.0-beta.52/node_modules/@rolldown/pluginutils/dist/simple-filters.js
-/**
-* Constructs a RegExp that matches the exact string specified.
-*
-* This is useful for plugin hook filters.
-*
-* @param str the string to match.
-* @param flags flags for the RegExp.
-*
-* @example
-* ```ts
-* import { exactRegex } from '@rolldown/pluginutils';
-* const plugin = {
-* name: 'plugin',
-* resolveId: {
-* filter: { id: exactRegex('foo') },
-* handler(id) {} // will only be called for `foo`
-* }
-* }
-* ```
-*/
-function exactRegex(str, flags) {
- return new RegExp(`^${escapeRegex$1(str)}$`, flags);
-}
-/**
-* Constructs a RegExp that matches a value that has the specified prefix.
-*
-* This is useful for plugin hook filters.
-*
-* @param str the string to match.
-* @param flags flags for the RegExp.
-*
-* @example
-* ```ts
-* import { prefixRegex } from '@rolldown/pluginutils';
-* const plugin = {
-* name: 'plugin',
-* resolveId: {
-* filter: { id: prefixRegex('foo') },
-* handler(id) {} // will only be called for IDs starting with `foo`
-* }
-* }
-* ```
-*/
-function prefixRegex(str, flags) {
- return new RegExp(`^${escapeRegex$1(str)}`, flags);
-}
-const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
-function escapeRegex$1(str) {
- return str.replace(escapeRegexRE, "\\$&");
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/es-module-lexer@1.7.0/node_modules/es-module-lexer/dist/lexer.js
-var ImportType;
-(function(A$1) {
- A$1[A$1.Static = 1] = "Static", A$1[A$1.Dynamic = 2] = "Dynamic", A$1[A$1.ImportMeta = 3] = "ImportMeta", A$1[A$1.StaticSourcePhase = 4] = "StaticSourcePhase", A$1[A$1.DynamicSourcePhase = 5] = "DynamicSourcePhase", A$1[A$1.StaticDeferPhase = 6] = "StaticDeferPhase", A$1[A$1.DynamicDeferPhase = 7] = "DynamicDeferPhase";
-})(ImportType || (ImportType = {}));
-const A = 1 === new Uint8Array(new Uint16Array([1]).buffer)[0];
-function parse(E$1, g = "@") {
- if (!C) return init.then((() => parse(E$1)));
- const I = E$1.length + 1, w = (C.__heap_base.value || C.__heap_base) + 4 * I - C.memory.buffer.byteLength;
- w > 0 && C.memory.grow(Math.ceil(w / 65536));
- const K = C.sa(I - 1);
- if ((A ? B : Q)(E$1, new Uint16Array(C.memory.buffer, K, I)), !C.parse()) throw Object.assign(/* @__PURE__ */ new Error(`Parse error ${g}:${E$1.slice(0, C.e()).split("\n").length}:${C.e() - E$1.lastIndexOf("\n", C.e() - 1)}`), { idx: C.e() });
- const o$1 = [], D = [];
- for (; C.ri();) {
- const A$1 = C.is(), Q$1 = C.ie(), B$1 = C.it(), g$1 = C.ai(), I$1 = C.id(), w$1 = C.ss(), K$1 = C.se();
- let D$1;
- C.ip() && (D$1 = k(E$1.slice(-1 === I$1 ? A$1 - 1 : A$1, -1 === I$1 ? Q$1 + 1 : Q$1))), o$1.push({
- n: D$1,
- t: B$1,
- s: A$1,
- e: Q$1,
- ss: w$1,
- se: K$1,
- d: I$1,
- a: g$1
- });
- }
- for (; C.re();) {
- const A$1 = C.es(), Q$1 = C.ee(), B$1 = C.els(), g$1 = C.ele(), I$1 = E$1.slice(A$1, Q$1), w$1 = I$1[0], K$1 = B$1 < 0 ? void 0 : E$1.slice(B$1, g$1), o$2 = K$1 ? K$1[0] : "";
- D.push({
- s: A$1,
- e: Q$1,
- ls: B$1,
- le: g$1,
- n: "\"" === w$1 || "'" === w$1 ? k(I$1) : I$1,
- ln: "\"" === o$2 || "'" === o$2 ? k(K$1) : K$1
- });
- }
- function k(A$1) {
- try {
- return (0, eval)(A$1);
- } catch (A$2) {}
- }
- return [
- o$1,
- D,
- !!C.f(),
- !!C.ms()
- ];
-}
-function Q(A$1, Q$1) {
- const B$1 = A$1.length;
- let C$1 = 0;
- for (; C$1 < B$1;) {
- const B$2 = A$1.charCodeAt(C$1);
- Q$1[C$1++] = (255 & B$2) << 8 | B$2 >>> 8;
- }
-}
-function B(A$1, Q$1) {
- const B$1 = A$1.length;
- let C$1 = 0;
- for (; C$1 < B$1;) Q$1[C$1] = A$1.charCodeAt(C$1++);
-}
-let C;
-const E = () => {
- return A$1 = "AGFzbQEAAAABKwhgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gA39/fwADMTAAAQECAgICAgICAgICAgICAgICAgIAAwMDBAQAAAUAAAAAAAMDAwAGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUHA8gALfwBBwPIACwd6FQZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAml0AAgCYWkACQJpZAAKAmlwAAsCZXMADAJlZQANA2VscwAOA2VsZQAPAnJpABACcmUAEQFmABICbXMAEwVwYXJzZQAUC19faGVhcF9iYXNlAwEKzkQwaAEBf0EAIAA2AoAKQQAoAtwJIgEgAEEBdGoiAEEAOwEAQQAgAEECaiIANgKECkEAIAA2AogKQQBBADYC4AlBAEEANgLwCUEAQQA2AugJQQBBADYC5AlBAEEANgL4CUEAQQA2AuwJIAEL0wEBA39BACgC8AkhBEEAQQAoAogKIgU2AvAJQQAgBDYC9AlBACAFQSRqNgKICiAEQSBqQeAJIAQbIAU2AgBBACgC1AkhBEEAKALQCSEGIAUgATYCACAFIAA2AgggBSACIAJBAmpBACAGIANGIgAbIAQgA0YiBBs2AgwgBSADNgIUIAVBADYCECAFIAI2AgQgBUEANgIgIAVBA0EBQQIgABsgBBs2AhwgBUEAKALQCSADRiICOgAYAkACQCACDQBBACgC1AkgA0cNAQtBAEEBOgCMCgsLXgEBf0EAKAL4CSIEQRBqQeQJIAQbQQAoAogKIgQ2AgBBACAENgL4CUEAIARBFGo2AogKQQBBAToAjAogBEEANgIQIAQgAzYCDCAEIAI2AgggBCABNgIEIAQgADYCAAsIAEEAKAKQCgsVAEEAKALoCSgCAEEAKALcCWtBAXULHgEBf0EAKALoCSgCBCIAQQAoAtwJa0EBdUF/IAAbCxUAQQAoAugJKAIIQQAoAtwJa0EBdQseAQF/QQAoAugJKAIMIgBBACgC3AlrQQF1QX8gABsLCwBBACgC6AkoAhwLHgEBf0EAKALoCSgCECIAQQAoAtwJa0EBdUF/IAAbCzsBAX8CQEEAKALoCSgCFCIAQQAoAtAJRw0AQX8PCwJAIABBACgC1AlHDQBBfg8LIABBACgC3AlrQQF1CwsAQQAoAugJLQAYCxUAQQAoAuwJKAIAQQAoAtwJa0EBdQsVAEEAKALsCSgCBEEAKALcCWtBAXULHgEBf0EAKALsCSgCCCIAQQAoAtwJa0EBdUF/IAAbCx4BAX9BACgC7AkoAgwiAEEAKALcCWtBAXVBfyAAGwslAQF/QQBBACgC6AkiAEEgakHgCSAAGygCACIANgLoCSAAQQBHCyUBAX9BAEEAKALsCSIAQRBqQeQJIAAbKAIAIgA2AuwJIABBAEcLCABBAC0AlAoLCABBAC0AjAoL3Q0BBX8jAEGA0ABrIgAkAEEAQQE6AJQKQQBBACgC2Ak2ApwKQQBBACgC3AlBfmoiATYCsApBACABQQAoAoAKQQF0aiICNgK0CkEAQQA6AIwKQQBBADsBlgpBAEEAOwGYCkEAQQA6AKAKQQBBADYCkApBAEEAOgD8CUEAIABBgBBqNgKkCkEAIAA2AqgKQQBBADoArAoCQAJAAkACQANAQQAgAUECaiIDNgKwCiABIAJPDQECQCADLwEAIgJBd2pBBUkNAAJAAkACQAJAAkAgAkGbf2oOBQEICAgCAAsgAkEgRg0EIAJBL0YNAyACQTtGDQIMBwtBAC8BmAoNASADEBVFDQEgAUEEakGCCEEKEC8NARAWQQAtAJQKDQFBAEEAKAKwCiIBNgKcCgwHCyADEBVFDQAgAUEEakGMCEEKEC8NABAXC0EAQQAoArAKNgKcCgwBCwJAIAEvAQQiA0EqRg0AIANBL0cNBBAYDAELQQEQGQtBACgCtAohAkEAKAKwCiEBDAALC0EAIQIgAyEBQQAtAPwJDQIMAQtBACABNgKwCkEAQQA6AJQKCwNAQQAgAUECaiIDNgKwCgJAAkACQAJAAkACQAJAIAFBACgCtApPDQAgAy8BACICQXdqQQVJDQYCQAJAAkACQAJAAkACQAJAAkACQCACQWBqDgoQDwYPDw8PBQECAAsCQAJAAkACQCACQaB/ag4KCxISAxIBEhISAgALIAJBhX9qDgMFEQYJC0EALwGYCg0QIAMQFUUNECABQQRqQYIIQQoQLw0QEBYMEAsgAxAVRQ0PIAFBBGpBjAhBChAvDQ8QFwwPCyADEBVFDQ4gASkABELsgISDsI7AOVINDiABLwEMIgNBd2oiAUEXSw0MQQEgAXRBn4CABHFFDQwMDQtBAEEALwGYCiIBQQFqOwGYCkEAKAKkCiABQQN0aiIBQQE2AgAgAUEAKAKcCjYCBAwNC0EALwGYCiIDRQ0JQQAgA0F/aiIDOwGYCkEALwGWCiICRQ0MQQAoAqQKIANB//8DcUEDdGooAgBBBUcNDAJAIAJBAnRBACgCqApqQXxqKAIAIgMoAgQNACADQQAoApwKQQJqNgIEC0EAIAJBf2o7AZYKIAMgAUEEajYCDAwMCwJAQQAoApwKIgEvAQBBKUcNAEEAKALwCSIDRQ0AIAMoAgQgAUcNAEEAQQAoAvQJIgM2AvAJAkAgA0UNACADQQA2AiAMAQtBAEEANgLgCQtBAEEALwGYCiIDQQFqOwGYCkEAKAKkCiADQQN0aiIDQQZBAkEALQCsChs2AgAgAyABNgIEQQBBADoArAoMCwtBAC8BmAoiAUUNB0EAIAFBf2oiATsBmApBACgCpAogAUH//wNxQQN0aigCAEEERg0EDAoLQScQGgwJC0EiEBoMCAsgAkEvRw0HAkACQCABLwEEIgFBKkYNACABQS9HDQEQGAwKC0EBEBkMCQsCQAJAAkACQEEAKAKcCiIBLwEAIgMQG0UNAAJAAkAgA0FVag4EAAkBAwkLIAFBfmovAQBBK0YNAwwICyABQX5qLwEAQS1GDQIMBwsgA0EpRw0BQQAoAqQKQQAvAZgKIgJBA3RqKAIEEBxFDQIMBgsgAUF+ai8BAEFQakH//wNxQQpPDQULQQAvAZgKIQILAkACQCACQf//A3EiAkUNACADQeYARw0AQQAoAqQKIAJBf2pBA3RqIgQoAgBBAUcNACABQX5qLwEAQe8ARw0BIAQoAgRBlghBAxAdRQ0BDAULIANB/QBHDQBBACgCpAogAkEDdGoiAigCBBAeDQQgAigCAEEGRg0ECyABEB8NAyADRQ0DIANBL0ZBAC0AoApBAEdxDQMCQEEAKAL4CSICRQ0AIAEgAigCAEkNACABIAIoAgRNDQQLIAFBfmohAUEAKALcCSECAkADQCABQQJqIgQgAk0NAUEAIAE2ApwKIAEvAQAhAyABQX5qIgQhASADECBFDQALIARBAmohBAsCQCADQf//A3EQIUUNACAEQX5qIQECQANAIAFBAmoiAyACTQ0BQQAgATYCnAogAS8BACEDIAFBfmoiBCEBIAMQIQ0ACyAEQQJqIQMLIAMQIg0EC0EAQQE6AKAKDAcLQQAoAqQKQQAvAZgKIgFBA3QiA2pBACgCnAo2AgRBACABQQFqOwGYCkEAKAKkCiADakEDNgIACxAjDAULQQAtAPwJQQAvAZYKQQAvAZgKcnJFIQIMBwsQJEEAQQA6AKAKDAMLECVBACECDAULIANBoAFHDQELQQBBAToArAoLQQBBACgCsAo2ApwKC0EAKAKwCiEBDAALCyAAQYDQAGokACACCxoAAkBBACgC3AkgAEcNAEEBDwsgAEF+ahAmC/4KAQZ/QQBBACgCsAoiAEEMaiIBNgKwCkEAKAL4CSECQQEQKSEDAkACQAJAAkACQAJAAkACQAJAQQAoArAKIgQgAUcNACADEChFDQELAkACQAJAAkACQAJAAkAgA0EqRg0AIANB+wBHDQFBACAEQQJqNgKwCkEBECkhA0EAKAKwCiEEA0ACQAJAIANB//8DcSIDQSJGDQAgA0EnRg0AIAMQLBpBACgCsAohAwwBCyADEBpBAEEAKAKwCkECaiIDNgKwCgtBARApGgJAIAQgAxAtIgNBLEcNAEEAQQAoArAKQQJqNgKwCkEBECkhAwsgA0H9AEYNA0EAKAKwCiIFIARGDQ8gBSEEIAVBACgCtApNDQAMDwsLQQAgBEECajYCsApBARApGkEAKAKwCiIDIAMQLRoMAgtBAEEAOgCUCgJAAkACQAJAAkACQCADQZ9/ag4MAgsEAQsDCwsLCwsFAAsgA0H2AEYNBAwKC0EAIARBDmoiAzYCsAoCQAJAAkBBARApQZ9/ag4GABICEhIBEgtBACgCsAoiBSkAAkLzgOSD4I3AMVINESAFLwEKECFFDRFBACAFQQpqNgKwCkEAECkaC0EAKAKwCiIFQQJqQbIIQQ4QLw0QIAUvARAiAkF3aiIBQRdLDQ1BASABdEGfgIAEcUUNDQwOC0EAKAKwCiIFKQACQuyAhIOwjsA5Ug0PIAUvAQoiAkF3aiIBQRdNDQYMCgtBACAEQQpqNgKwCkEAECkaQQAoArAKIQQLQQAgBEEQajYCsAoCQEEBECkiBEEqRw0AQQBBACgCsApBAmo2ArAKQQEQKSEEC0EAKAKwCiEDIAQQLBogA0EAKAKwCiIEIAMgBBACQQBBACgCsApBfmo2ArAKDwsCQCAEKQACQuyAhIOwjsA5Ug0AIAQvAQoQIEUNAEEAIARBCmo2ArAKQQEQKSEEQQAoArAKIQMgBBAsGiADQQAoArAKIgQgAyAEEAJBAEEAKAKwCkF+ajYCsAoPC0EAIARBBGoiBDYCsAoLQQAgBEEGajYCsApBAEEAOgCUCkEBECkhBEEAKAKwCiEDIAQQLCEEQQAoArAKIQIgBEHf/wNxIgFB2wBHDQNBACACQQJqNgKwCkEBECkhBUEAKAKwCiEDQQAhBAwEC0EAQQE6AIwKQQBBACgCsApBAmo2ArAKC0EBECkhBEEAKAKwCiEDAkAgBEHmAEcNACADQQJqQawIQQYQLw0AQQAgA0EIajYCsAogAEEBEClBABArIAJBEGpB5AkgAhshAwNAIAMoAgAiA0UNBSADQgA3AgggA0EQaiEDDAALC0EAIANBfmo2ArAKDAMLQQEgAXRBn4CABHFFDQMMBAtBASEECwNAAkACQCAEDgIAAQELIAVB//8DcRAsGkEBIQQMAQsCQAJAQQAoArAKIgQgA0YNACADIAQgAyAEEAJBARApIQQCQCABQdsARw0AIARBIHJB/QBGDQQLQQAoArAKIQMCQCAEQSxHDQBBACADQQJqNgKwCkEBECkhBUEAKAKwCiEDIAVBIHJB+wBHDQILQQAgA0F+ajYCsAoLIAFB2wBHDQJBACACQX5qNgKwCg8LQQAhBAwACwsPCyACQaABRg0AIAJB+wBHDQQLQQAgBUEKajYCsApBARApIgVB+wBGDQMMAgsCQCACQVhqDgMBAwEACyACQaABRw0CC0EAIAVBEGo2ArAKAkBBARApIgVBKkcNAEEAQQAoArAKQQJqNgKwCkEBECkhBQsgBUEoRg0BC0EAKAKwCiEBIAUQLBpBACgCsAoiBSABTQ0AIAQgAyABIAUQAkEAQQAoArAKQX5qNgKwCg8LIAQgA0EAQQAQAkEAIARBDGo2ArAKDwsQJQuFDAEKf0EAQQAoArAKIgBBDGoiATYCsApBARApIQJBACgCsAohAwJAAkACQAJAAkACQAJAAkAgAkEuRw0AQQAgA0ECajYCsAoCQEEBECkiAkHkAEYNAAJAIAJB8wBGDQAgAkHtAEcNB0EAKAKwCiICQQJqQZwIQQYQLw0HAkBBACgCnAoiAxAqDQAgAy8BAEEuRg0ICyAAIAAgAkEIakEAKALUCRABDwtBACgCsAoiAkECakGiCEEKEC8NBgJAQQAoApwKIgMQKg0AIAMvAQBBLkYNBwtBACEEQQAgAkEMajYCsApBASEFQQUhBkEBECkhAkEAIQdBASEIDAILQQAoArAKIgIpAAJC5YCYg9CMgDlSDQUCQEEAKAKcCiIDECoNACADLwEAQS5GDQYLQQAhBEEAIAJBCmo2ArAKQQIhCEEHIQZBASEHQQEQKSECQQEhBQwBCwJAAkACQAJAIAJB8wBHDQAgAyABTQ0AIANBAmpBoghBChAvDQACQCADLwEMIgRBd2oiB0EXSw0AQQEgB3RBn4CABHENAgsgBEGgAUYNAQtBACEHQQchBkEBIQQgAkHkAEYNAQwCC0EAIQRBACADQQxqIgI2ArAKQQEhBUEBECkhCQJAQQAoArAKIgYgAkYNAEHmACECAkAgCUHmAEYNAEEFIQZBACEHQQEhCCAJIQIMBAtBACEHQQEhCCAGQQJqQawIQQYQLw0EIAYvAQgQIEUNBAtBACEHQQAgAzYCsApBByEGQQEhBEEAIQVBACEIIAkhAgwCCyADIABBCmpNDQBBACEIQeQAIQICQCADKQACQuWAmIPQjIA5Ug0AAkACQCADLwEKIgRBd2oiB0EXSw0AQQEgB3RBn4CABHENAQtBACEIIARBoAFHDQELQQAhBUEAIANBCmo2ArAKQSohAkEBIQdBAiEIQQEQKSIJQSpGDQRBACADNgKwCkEBIQRBACEHQQAhCCAJIQIMAgsgAyEGQQAhBwwCC0EAIQVBACEICwJAIAJBKEcNAEEAKAKkCkEALwGYCiICQQN0aiIDQQAoArAKNgIEQQAgAkEBajsBmAogA0EFNgIAQQAoApwKLwEAQS5GDQRBAEEAKAKwCiIDQQJqNgKwCkEBECkhAiAAQQAoArAKQQAgAxABAkACQCAFDQBBACgC8AkhAQwBC0EAKALwCSIBIAY2AhwLQQBBAC8BlgoiA0EBajsBlgpBACgCqAogA0ECdGogATYCAAJAIAJBIkYNACACQSdGDQBBAEEAKAKwCkF+ajYCsAoPCyACEBpBAEEAKAKwCkECaiICNgKwCgJAAkACQEEBEClBV2oOBAECAgACC0EAQQAoArAKQQJqNgKwCkEBECkaQQAoAvAJIgMgAjYCBCADQQE6ABggA0EAKAKwCiICNgIQQQAgAkF+ajYCsAoPC0EAKALwCSIDIAI2AgQgA0EBOgAYQQBBAC8BmApBf2o7AZgKIANBACgCsApBAmo2AgxBAEEALwGWCkF/ajsBlgoPC0EAQQAoArAKQX5qNgKwCg8LAkAgBEEBcyACQfsAR3INAEEAKAKwCiECQQAvAZgKDQUDQAJAAkACQCACQQAoArQKTw0AQQEQKSICQSJGDQEgAkEnRg0BIAJB/QBHDQJBAEEAKAKwCkECajYCsAoLQQEQKSEDQQAoArAKIQICQCADQeYARw0AIAJBAmpBrAhBBhAvDQcLQQAgAkEIajYCsAoCQEEBECkiAkEiRg0AIAJBJ0cNBwsgACACQQAQKw8LIAIQGgtBAEEAKAKwCkECaiICNgKwCgwACwsCQAJAIAJBWWoOBAMBAQMACyACQSJGDQILQQAoArAKIQYLIAYgAUcNAEEAIABBCmo2ArAKDwsgAkEqRyAHcQ0DQQAvAZgKQf//A3ENA0EAKAKwCiECQQAoArQKIQEDQCACIAFPDQECQAJAIAIvAQAiA0EnRg0AIANBIkcNAQsgACADIAgQKw8LQQAgAkECaiICNgKwCgwACwsQJQsPC0EAIAJBfmo2ArAKDwtBAEEAKAKwCkF+ajYCsAoLRwEDf0EAKAKwCkECaiEAQQAoArQKIQECQANAIAAiAkF+aiABTw0BIAJBAmohACACLwEAQXZqDgQBAAABAAsLQQAgAjYCsAoLmAEBA39BAEEAKAKwCiIBQQJqNgKwCiABQQZqIQFBACgCtAohAgNAAkACQAJAIAFBfGogAk8NACABQX5qLwEAIQMCQAJAIAANACADQSpGDQEgA0F2ag4EAgQEAgQLIANBKkcNAwsgAS8BAEEvRw0CQQAgAUF+ajYCsAoMAQsgAUF+aiEBC0EAIAE2ArAKDwsgAUECaiEBDAALC4gBAQR/QQAoArAKIQFBACgCtAohAgJAAkADQCABIgNBAmohASADIAJPDQEgAS8BACIEIABGDQICQCAEQdwARg0AIARBdmoOBAIBAQIBCyADQQRqIQEgAy8BBEENRw0AIANBBmogASADLwEGQQpGGyEBDAALC0EAIAE2ArAKECUPC0EAIAE2ArAKC2wBAX8CQAJAIABBX2oiAUEFSw0AQQEgAXRBMXENAQsgAEFGakH//wNxQQZJDQAgAEEpRyAAQVhqQf//A3FBB0lxDQACQCAAQaV/ag4EAQAAAQALIABB/QBHIABBhX9qQf//A3FBBElxDwtBAQsuAQF/QQEhAQJAIABBpglBBRAdDQAgAEGWCEEDEB0NACAAQbAJQQIQHSEBCyABC0YBA39BACEDAkAgACACQQF0IgJrIgRBAmoiAEEAKALcCSIFSQ0AIAAgASACEC8NAAJAIAAgBUcNAEEBDwsgBBAmIQMLIAMLgwEBAn9BASEBAkACQAJAAkACQAJAIAAvAQAiAkFFag4EBQQEAQALAkAgAkGbf2oOBAMEBAIACyACQSlGDQQgAkH5AEcNAyAAQX5qQbwJQQYQHQ8LIABBfmovAQBBPUYPCyAAQX5qQbQJQQQQHQ8LIABBfmpByAlBAxAdDwtBACEBCyABC7QDAQJ/QQAhAQJAAkACQAJAAkACQAJAAkACQAJAIAAvAQBBnH9qDhQAAQIJCQkJAwkJBAUJCQYJBwkJCAkLAkACQCAAQX5qLwEAQZd/ag4EAAoKAQoLIABBfGpByghBAhAdDwsgAEF8akHOCEEDEB0PCwJAAkACQCAAQX5qLwEAQY1/ag4DAAECCgsCQCAAQXxqLwEAIgJB4QBGDQAgAkHsAEcNCiAAQXpqQeUAECcPCyAAQXpqQeMAECcPCyAAQXxqQdQIQQQQHQ8LIABBfGpB3AhBBhAdDwsgAEF+ai8BAEHvAEcNBiAAQXxqLwEAQeUARw0GAkAgAEF6ai8BACICQfAARg0AIAJB4wBHDQcgAEF4akHoCEEGEB0PCyAAQXhqQfQIQQIQHQ8LIABBfmpB+AhBBBAdDwtBASEBIABBfmoiAEHpABAnDQQgAEGACUEFEB0PCyAAQX5qQeQAECcPCyAAQX5qQYoJQQcQHQ8LIABBfmpBmAlBBBAdDwsCQCAAQX5qLwEAIgJB7wBGDQAgAkHlAEcNASAAQXxqQe4AECcPCyAAQXxqQaAJQQMQHSEBCyABCzQBAX9BASEBAkAgAEF3akH//wNxQQVJDQAgAEGAAXJBoAFGDQAgAEEuRyAAEChxIQELIAELMAEBfwJAAkAgAEF3aiIBQRdLDQBBASABdEGNgIAEcQ0BCyAAQaABRg0AQQAPC0EBC04BAn9BACEBAkACQCAALwEAIgJB5QBGDQAgAkHrAEcNASAAQX5qQfgIQQQQHQ8LIABBfmovAQBB9QBHDQAgAEF8akHcCEEGEB0hAQsgAQveAQEEf0EAKAKwCiEAQQAoArQKIQECQAJAAkADQCAAIgJBAmohACACIAFPDQECQAJAAkAgAC8BACIDQaR/ag4FAgMDAwEACyADQSRHDQIgAi8BBEH7AEcNAkEAIAJBBGoiADYCsApBAEEALwGYCiICQQFqOwGYCkEAKAKkCiACQQN0aiICQQQ2AgAgAiAANgIEDwtBACAANgKwCkEAQQAvAZgKQX9qIgA7AZgKQQAoAqQKIABB//8DcUEDdGooAgBBA0cNAwwECyACQQRqIQAMAAsLQQAgADYCsAoLECULC3ABAn8CQAJAA0BBAEEAKAKwCiIAQQJqIgE2ArAKIABBACgCtApPDQECQAJAAkAgAS8BACIBQaV/ag4CAQIACwJAIAFBdmoOBAQDAwQACyABQS9HDQIMBAsQLhoMAQtBACAAQQRqNgKwCgwACwsQJQsLNQEBf0EAQQE6APwJQQAoArAKIQBBAEEAKAK0CkECajYCsApBACAAQQAoAtwJa0EBdTYCkAoLQwECf0EBIQECQCAALwEAIgJBd2pB//8DcUEFSQ0AIAJBgAFyQaABRg0AQQAhASACEChFDQAgAkEuRyAAECpyDwsgAQs9AQJ/QQAhAgJAQQAoAtwJIgMgAEsNACAALwEAIAFHDQACQCADIABHDQBBAQ8LIABBfmovAQAQICECCyACC2gBAn9BASEBAkACQCAAQV9qIgJBBUsNAEEBIAJ0QTFxDQELIABB+P8DcUEoRg0AIABBRmpB//8DcUEGSQ0AAkAgAEGlf2oiAkEDSw0AIAJBAUcNAQsgAEGFf2pB//8DcUEESSEBCyABC5wBAQN/QQAoArAKIQECQANAAkACQCABLwEAIgJBL0cNAAJAIAEvAQIiAUEqRg0AIAFBL0cNBBAYDAILIAAQGQwBCwJAAkAgAEUNACACQXdqIgFBF0sNAUEBIAF0QZ+AgARxRQ0BDAILIAIQIUUNAwwBCyACQaABRw0CC0EAQQAoArAKIgNBAmoiATYCsAogA0EAKAK0CkkNAAsLIAILMQEBf0EAIQECQCAALwEAQS5HDQAgAEF+ai8BAEEuRw0AIABBfGovAQBBLkYhAQsgAQumBAEBfwJAIAFBIkYNACABQSdGDQAQJQ8LQQAoArAKIQMgARAaIAAgA0ECakEAKAKwCkEAKALQCRABAkAgAkEBSA0AQQAoAvAJQQRBBiACQQFGGzYCHAtBAEEAKAKwCkECajYCsAoCQAJAAkACQEEAECkiAUHhAEYNACABQfcARg0BQQAoArAKIQEMAgtBACgCsAoiAUECakHACEEKEC8NAUEGIQIMAgtBACgCsAoiAS8BAkHpAEcNACABLwEEQfQARw0AQQQhAiABLwEGQegARg0BC0EAIAFBfmo2ArAKDwtBACABIAJBAXRqNgKwCgJAQQEQKUH7AEYNAEEAIAE2ArAKDwtBACgCsAoiACECA0BBACACQQJqNgKwCgJAAkACQEEBECkiAkEiRg0AIAJBJ0cNAUEnEBpBAEEAKAKwCkECajYCsApBARApIQIMAgtBIhAaQQBBACgCsApBAmo2ArAKQQEQKSECDAELIAIQLCECCwJAIAJBOkYNAEEAIAE2ArAKDwtBAEEAKAKwCkECajYCsAoCQEEBECkiAkEiRg0AIAJBJ0YNAEEAIAE2ArAKDwsgAhAaQQBBACgCsApBAmo2ArAKAkACQEEBECkiAkEsRg0AIAJB/QBGDQFBACABNgKwCg8LQQBBACgCsApBAmo2ArAKQQEQKUH9AEYNAEEAKAKwCiECDAELC0EAKALwCSIBIAA2AhAgAUEAKAKwCkECajYCDAttAQJ/AkACQANAAkAgAEH//wNxIgFBd2oiAkEXSw0AQQEgAnRBn4CABHENAgsgAUGgAUYNASAAIQIgARAoDQJBACECQQBBACgCsAoiAEECajYCsAogAC8BAiIADQAMAgsLIAAhAgsgAkH//wNxC6sBAQR/AkACQEEAKAKwCiICLwEAIgNB4QBGDQAgASEEIAAhBQwBC0EAIAJBBGo2ArAKQQEQKSECQQAoArAKIQUCQAJAIAJBIkYNACACQSdGDQAgAhAsGkEAKAKwCiEEDAELIAIQGkEAQQAoArAKQQJqIgQ2ArAKC0EBECkhA0EAKAKwCiECCwJAIAIgBUYNACAFIARBACAAIAAgAUYiAhtBACABIAIbEAILIAMLcgEEf0EAKAKwCiEAQQAoArQKIQECQAJAA0AgAEECaiECIAAgAU8NAQJAAkAgAi8BACIDQaR/ag4CAQQACyACIQAgA0F2ag4EAgEBAgELIABBBGohAAwACwtBACACNgKwChAlQQAPC0EAIAI2ArAKQd0AC0kBA39BACEDAkAgAkUNAAJAA0AgAC0AACIEIAEtAAAiBUcNASABQQFqIQEgAEEBaiEAIAJBf2oiAg0ADAILCyAEIAVrIQMLIAMLC+wBAgBBgAgLzgEAAHgAcABvAHIAdABtAHAAbwByAHQAZgBvAHIAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AcwBzAGUAcgB0AHYAbwB5AGkAZQBkAGUAbABlAGMAbwBuAHQAaQBuAGkAbgBzAHQAYQBuAHQAeQBiAHIAZQBhAHIAZQB0AHUAcgBkAGUAYgB1AGcAZwBlAGEAdwBhAGkAdABoAHIAdwBoAGkAbABlAGkAZgBjAGEAdABjAGYAaQBuAGEAbABsAGUAbABzAABB0AkLEAEAAAACAAAAAAQAAEA5AAA=", "undefined" != typeof Buffer ? Buffer.from(A$1, "base64") : Uint8Array.from(atob(A$1), ((A$2) => A$2.charCodeAt(0)));
- var A$1;
-};
-const init = WebAssembly.compile(E()).then(WebAssembly.instantiate).then((({ exports: A$1 }) => {
- C = A$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/lilconfig@3.1.3/node_modules/lilconfig/src/index.js
-var require_src$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const path$11 = __require("path");
- const fs$11 = __require("fs");
- const os$4 = __require("os");
- const url$2 = __require("url");
- const fsReadFileAsync = fs$11.promises.readFile;
- /** @type {(name: string, sync: boolean) => string[]} */
- function getDefaultSearchPlaces(name, sync$3) {
- return [
- "package.json",
- `.${name}rc.json`,
- `.${name}rc.js`,
- `.${name}rc.cjs`,
- ...sync$3 ? [] : [`.${name}rc.mjs`],
- `.config/${name}rc`,
- `.config/${name}rc.json`,
- `.config/${name}rc.js`,
- `.config/${name}rc.cjs`,
- ...sync$3 ? [] : [`.config/${name}rc.mjs`],
- `${name}.config.js`,
- `${name}.config.cjs`,
- ...sync$3 ? [] : [`${name}.config.mjs`]
- ];
- }
- /**
- * @type {(p: string) => string}
- *
- * see #17
- * On *nix, if cwd is not under homedir,
- * the last path will be '', ('/build' -> '')
- * but it should be '/' actually.
- * And on Windows, this will never happen. ('C:\build' -> 'C:')
- */
- function parentDir(p) {
- return path$11.dirname(p) || path$11.sep;
- }
- /** @type {import('./index').LoaderSync} */
- const jsonLoader = (_, content) => JSON.parse(content);
- const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
- /** @type {import('./index').LoadersSync} */
- const defaultLoadersSync = Object.freeze({
- ".js": requireFunc,
- ".json": requireFunc,
- ".cjs": requireFunc,
- noExt: jsonLoader
- });
- module.exports.defaultLoadersSync = defaultLoadersSync;
- /** @type {import('./index').Loader} */
- const dynamicImport = async (id) => {
- try {
- return (await import(url$2.pathToFileURL(id).href)).default;
- } catch (e$1) {
- try {
- return requireFunc(id);
- } catch (requireE) {
- if (requireE.code === "ERR_REQUIRE_ESM" || requireE instanceof SyntaxError && requireE.toString().includes("Cannot use import statement outside a module")) throw e$1;
- throw requireE;
- }
- }
- };
- /** @type {import('./index').Loaders} */
- const defaultLoaders = Object.freeze({
- ".js": dynamicImport,
- ".mjs": dynamicImport,
- ".cjs": dynamicImport,
- ".json": jsonLoader,
- noExt: jsonLoader
- });
- module.exports.defaultLoaders = defaultLoaders;
- /**
- * @param {string} name
- * @param {import('./index').Options | import('./index').OptionsSync} options
- * @param {boolean} sync
- * @returns {Required<import('./index').Options | import('./index').OptionsSync>}
- */
- function getOptions(name, options$1, sync$3) {
- /** @type {Required<import('./index').Options>} */
- const conf = {
- stopDir: os$4.homedir(),
- searchPlaces: getDefaultSearchPlaces(name, sync$3),
- ignoreEmptySearchPlaces: true,
- cache: true,
- transform: (x) => x,
- packageProp: [name],
- ...options$1,
- loaders: {
- ...sync$3 ? defaultLoadersSync : defaultLoaders,
- ...options$1.loaders
- }
- };
- conf.searchPlaces.forEach((place) => {
- const key = path$11.extname(place) || "noExt";
- const loader$1 = conf.loaders[key];
- if (!loader$1) throw new Error(`Missing loader for extension "${place}"`);
- if (typeof loader$1 !== "function") throw new Error(`Loader for extension "${place}" is not a function: Received ${typeof loader$1}.`);
- });
- return conf;
- }
- /** @type {(props: string | string[], obj: Record<string, any>) => unknown} */
- function getPackageProp(props, obj) {
- if (typeof props === "string" && props in obj) return obj[props];
- return (Array.isArray(props) ? props : props.split(".")).reduce((acc, prop) => acc === void 0 ? acc : acc[prop], obj) || null;
- }
- /** @param {string} filepath */
- function validateFilePath(filepath) {
- if (!filepath) throw new Error("load must pass a non-empty string");
- }
- /** @type {(loader: import('./index').Loader, ext: string) => void} */
- function validateLoader(loader$1, ext) {
- if (!loader$1) throw new Error(`No loader specified for extension "${ext}"`);
- if (typeof loader$1 !== "function") throw new Error("loader is not a function");
- }
- /** @type {(enableCache: boolean) => <T>(c: Map<string, T>, filepath: string, res: T) => T} */
- const makeEmplace = (enableCache) => (c, filepath, res) => {
- if (enableCache) c.set(filepath, res);
- return res;
- };
- /** @type {import('./index').lilconfig} */
- module.exports.lilconfig = function lilconfig(name, options$1) {
- const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform: transform$2, cache: cache$1 } = getOptions(name, options$1 ?? {}, false);
- const searchCache = /* @__PURE__ */ new Map();
- const loadCache = /* @__PURE__ */ new Map();
- const emplace = makeEmplace(cache$1);
- return {
- async search(searchFrom = process.cwd()) {
- /** @type {import('./index').LilconfigResult} */
- const result = {
- config: null,
- filepath: ""
- };
- /** @type {Set<string>} */
- const visited = /* @__PURE__ */ new Set();
- let dir = searchFrom;
- dirLoop: while (true) {
- if (cache$1) {
- const r$1 = searchCache.get(dir);
- if (r$1 !== void 0) {
- for (const p of visited) searchCache.set(p, r$1);
- return r$1;
- }
- visited.add(dir);
- }
- for (const searchPlace of searchPlaces) {
- const filepath = path$11.join(dir, searchPlace);
- try {
- await fs$11.promises.access(filepath);
- } catch {
- continue;
- }
- const content = String(await fsReadFileAsync(filepath));
- const loaderKey = path$11.extname(searchPlace) || "noExt";
- const loader$1 = loaders[loaderKey];
- if (searchPlace === "package.json") {
- const maybeConfig = getPackageProp(packageProp, await loader$1(filepath, content));
- if (maybeConfig != null) {
- result.config = maybeConfig;
- result.filepath = filepath;
- break dirLoop;
- }
- continue;
- }
- const isEmpty = content.trim() === "";
- if (isEmpty && ignoreEmptySearchPlaces) continue;
- if (isEmpty) {
- result.isEmpty = true;
- result.config = void 0;
- } else {
- validateLoader(loader$1, loaderKey);
- result.config = await loader$1(filepath, content);
- }
- result.filepath = filepath;
- break dirLoop;
- }
- if (dir === stopDir || dir === parentDir(dir)) break dirLoop;
- dir = parentDir(dir);
- }
- const transformed = result.filepath === "" && result.config === null ? transform$2(null) : transform$2(result);
- if (cache$1) for (const p of visited) searchCache.set(p, transformed);
- return transformed;
- },
- async load(filepath) {
- validateFilePath(filepath);
- const absPath = path$11.resolve(process.cwd(), filepath);
- if (cache$1 && loadCache.has(absPath)) return loadCache.get(absPath);
- const { base, ext } = path$11.parse(absPath);
- const loaderKey = ext || "noExt";
- const loader$1 = loaders[loaderKey];
- validateLoader(loader$1, loaderKey);
- const content = String(await fsReadFileAsync(absPath));
- if (base === "package.json") return emplace(loadCache, absPath, transform$2({
- config: getPackageProp(packageProp, await loader$1(absPath, content)),
- filepath: absPath
- }));
- /** @type {import('./index').LilconfigResult} */
- const result = {
- config: null,
- filepath: absPath
- };
- const isEmpty = content.trim() === "";
- if (isEmpty && ignoreEmptySearchPlaces) return emplace(loadCache, absPath, transform$2({
- config: void 0,
- filepath: absPath,
- isEmpty: true
- }));
- result.config = isEmpty ? void 0 : await loader$1(absPath, content);
- return emplace(loadCache, absPath, transform$2(isEmpty ? {
- ...result,
- isEmpty,
- config: void 0
- } : result));
- },
- clearLoadCache() {
- if (cache$1) loadCache.clear();
- },
- clearSearchCache() {
- if (cache$1) searchCache.clear();
- },
- clearCaches() {
- if (cache$1) {
- loadCache.clear();
- searchCache.clear();
- }
- }
- };
- };
- /** @type {import('./index').lilconfigSync} */
- module.exports.lilconfigSync = function lilconfigSync(name, options$1) {
- const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform: transform$2, cache: cache$1 } = getOptions(name, options$1 ?? {}, true);
- const searchCache = /* @__PURE__ */ new Map();
- const loadCache = /* @__PURE__ */ new Map();
- const emplace = makeEmplace(cache$1);
- return {
- search(searchFrom = process.cwd()) {
- /** @type {import('./index').LilconfigResult} */
- const result = {
- config: null,
- filepath: ""
- };
- /** @type {Set<string>} */
- const visited = /* @__PURE__ */ new Set();
- let dir = searchFrom;
- dirLoop: while (true) {
- if (cache$1) {
- const r$1 = searchCache.get(dir);
- if (r$1 !== void 0) {
- for (const p of visited) searchCache.set(p, r$1);
- return r$1;
- }
- visited.add(dir);
- }
- for (const searchPlace of searchPlaces) {
- const filepath = path$11.join(dir, searchPlace);
- try {
- fs$11.accessSync(filepath);
- } catch {
- continue;
- }
- const loaderKey = path$11.extname(searchPlace) || "noExt";
- const loader$1 = loaders[loaderKey];
- const content = String(fs$11.readFileSync(filepath));
- if (searchPlace === "package.json") {
- const maybeConfig = getPackageProp(packageProp, loader$1(filepath, content));
- if (maybeConfig != null) {
- result.config = maybeConfig;
- result.filepath = filepath;
- break dirLoop;
- }
- continue;
- }
- const isEmpty = content.trim() === "";
- if (isEmpty && ignoreEmptySearchPlaces) continue;
- if (isEmpty) {
- result.isEmpty = true;
- result.config = void 0;
- } else {
- validateLoader(loader$1, loaderKey);
- result.config = loader$1(filepath, content);
- }
- result.filepath = filepath;
- break dirLoop;
- }
- if (dir === stopDir || dir === parentDir(dir)) break dirLoop;
- dir = parentDir(dir);
- }
- const transformed = result.filepath === "" && result.config === null ? transform$2(null) : transform$2(result);
- if (cache$1) for (const p of visited) searchCache.set(p, transformed);
- return transformed;
- },
- load(filepath) {
- validateFilePath(filepath);
- const absPath = path$11.resolve(process.cwd(), filepath);
- if (cache$1 && loadCache.has(absPath)) return loadCache.get(absPath);
- const { base, ext } = path$11.parse(absPath);
- const loaderKey = ext || "noExt";
- const loader$1 = loaders[loaderKey];
- validateLoader(loader$1, loaderKey);
- const content = String(fs$11.readFileSync(absPath));
- if (base === "package.json") return transform$2({
- config: getPackageProp(packageProp, loader$1(absPath, content)),
- filepath: absPath
- });
- const result = {
- config: null,
- filepath: absPath
- };
- const isEmpty = content.trim() === "";
- if (isEmpty && ignoreEmptySearchPlaces) return emplace(loadCache, absPath, transform$2({
- filepath: absPath,
- config: void 0,
- isEmpty: true
- }));
- result.config = isEmpty ? void 0 : loader$1(absPath, content);
- return emplace(loadCache, absPath, transform$2(isEmpty ? {
- ...result,
- isEmpty,
- config: void 0
- } : result));
- },
- clearLoadCache() {
- if (cache$1) loadCache.clear();
- },
- clearSearchCache() {
- if (cache$1) searchCache.clear();
- },
- clearCaches() {
- if (cache$1) {
- loadCache.clear();
- searchCache.clear();
- }
- }
- };
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_tsx@4.21.0_yaml@2.8.1/node_modules/postcss-load-config/src/req.js
-var require_req = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const { createRequire: createRequire$2 } = __require("node:module");
- const { fileURLToPath: fileURLToPath$1, pathToFileURL: pathToFileURL$1 } = __require("node:url");
- const TS_EXT_RE = /\.[mc]?ts$/;
- let tsx;
- let jiti;
- let importError = [];
- /**
- * @param {string} name
- * @param {string} rootFile
- * @returns {Promise<any>}
- */
- async function req$3(name, rootFile = fileURLToPath$1(import.meta.url)) {
- let url$3 = createRequire$2(rootFile).resolve(name);
- try {
- return (await import(`${pathToFileURL$1(url$3)}?t=${Date.now()}`)).default;
- } catch (err$2) {
- if (!TS_EXT_RE.test(url$3))
- /* c8 ignore start */
- throw err$2;
- }
- if (tsx === void 0) try {
- tsx = await import("tsx/cjs/api");
- } catch (error$1) {
- importError.push(error$1);
- }
- if (tsx) {
- let loaded = tsx.require(name, rootFile);
- return loaded && "__esModule" in loaded ? loaded.default : loaded;
- }
- if (jiti === void 0) try {
- jiti = (await import("jiti")).default;
- } catch (error$1) {
- importError.push(error$1);
- }
- if (jiti) return jiti(rootFile, { interopDefault: true })(name);
- throw new Error(`'tsx' or 'jiti' is required for the TypeScript configuration files. Make sure it is installed\nError: ${importError.map((error$1) => error$1.message).join("\n")}`);
- }
- module.exports = req$3;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_tsx@4.21.0_yaml@2.8.1/node_modules/postcss-load-config/src/options.js
-var require_options = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const req$2 = require_req();
- /**
- * Load Options
- *
- * @private
- * @method options
- *
- * @param {Object} config PostCSS Config
- *
- * @return {Promise<Object>} options PostCSS Options
- */
- async function options(config$2, file) {
- if (config$2.parser && typeof config$2.parser === "string") try {
- config$2.parser = await req$2(config$2.parser, file);
- } catch (err$2) {
- throw new Error(`Loading PostCSS Parser failed: ${err$2.message}\n\n(@${file})`);
- }
- if (config$2.syntax && typeof config$2.syntax === "string") try {
- config$2.syntax = await req$2(config$2.syntax, file);
- } catch (err$2) {
- throw new Error(`Loading PostCSS Syntax failed: ${err$2.message}\n\n(@${file})`);
- }
- if (config$2.stringifier && typeof config$2.stringifier === "string") try {
- config$2.stringifier = await req$2(config$2.stringifier, file);
- } catch (err$2) {
- throw new Error(`Loading PostCSS Stringifier failed: ${err$2.message}\n\n(@${file})`);
- }
- return config$2;
- }
- module.exports = options;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_tsx@4.21.0_yaml@2.8.1/node_modules/postcss-load-config/src/plugins.js
-var require_plugins = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const req$1 = require_req();
- /**
- * Plugin Loader
- *
- * @private
- * @method load
- *
- * @param {String} plugin PostCSS Plugin Name
- * @param {Object} options PostCSS Plugin Options
- *
- * @return {Promise<Function>} PostCSS Plugin
- */
- async function load(plugin, options$1, file) {
- try {
- if (options$1 === null || options$1 === void 0 || Object.keys(options$1).length === 0) return await req$1(plugin, file);
- else return (await req$1(plugin, file))(options$1);
- } catch (err$2) {
- throw new Error(`Loading PostCSS Plugin failed: ${err$2.message}\n\n(@${file})`);
- }
- }
- /**
- * Load Plugins
- *
- * @private
- * @method plugins
- *
- * @param {Object} config PostCSS Config Plugins
- *
- * @return {Promise<Array>} plugins PostCSS Plugins
- */
- async function plugins(config$2, file) {
- let list = [];
- if (Array.isArray(config$2.plugins)) list = config$2.plugins.filter(Boolean);
- else {
- list = Object.entries(config$2.plugins).filter(([, options$1]) => {
- return options$1 !== false;
- }).map(([plugin, options$1]) => {
- return load(plugin, options$1, file);
- });
- list = await Promise.all(list);
- }
- if (list.length && list.length > 0) list.forEach((plugin, i$1) => {
- if (plugin.default) plugin = plugin.default;
- if (plugin.postcss === true) plugin = plugin();
- else if (plugin.postcss) plugin = plugin.postcss;
- if (!(typeof plugin === "object" && Array.isArray(plugin.plugins) || typeof plugin === "object" && plugin.postcssPlugin || typeof plugin === "function")) throw new TypeError(`Invalid PostCSS Plugin found at: plugins[${i$1}]\n\n(@${file})`);
- });
- return list;
- }
- module.exports = plugins;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_tsx@4.21.0_yaml@2.8.1/node_modules/postcss-load-config/src/index.js
-var require_src = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const { resolve: resolve$2 } = __require("node:path");
- const config$1 = require_src$1();
- const loadOptions = require_options();
- const loadPlugins = require_plugins();
- const req = require_req();
- const interopRequireDefault = (obj) => obj && obj.__esModule ? obj : { default: obj };
- /**
- * Process the result from cosmiconfig
- *
- * @param {Object} ctx Config Context
- * @param {Object} result Cosmiconfig result
- *
- * @return {Promise<Object>} PostCSS Config
- */
- async function processResult(ctx, result) {
- let file = result.filepath || "";
- let projectConfig = interopRequireDefault(result.config).default || {};
- if (typeof projectConfig === "function") projectConfig = projectConfig(ctx);
- else projectConfig = Object.assign({}, projectConfig, ctx);
- if (!projectConfig.plugins) projectConfig.plugins = [];
- let res = {
- file,
- options: await loadOptions(projectConfig, file),
- plugins: await loadPlugins(projectConfig, file)
- };
- delete projectConfig.plugins;
- return res;
- }
- /**
- * Builds the Config Context
- *
- * @param {Object} ctx Config Context
- *
- * @return {Object} Config Context
- */
- function createContext(ctx) {
- /**
- * @type {Object}
- *
- * @prop {String} cwd=process.cwd() Config search start location
- * @prop {String} env=process.env.NODE_ENV Config Enviroment, will be set to `development` by `postcss-load-config` if `process.env.NODE_ENV` is `undefined`
- */
- ctx = Object.assign({
- cwd: process.cwd(),
- env: process.env.NODE_ENV
- }, ctx);
- if (!ctx.env) process.env.NODE_ENV = "development";
- return ctx;
- }
- async function loader(filepath) {
- return req(filepath);
- }
- let yaml;
- async function yamlLoader(_, content) {
- if (!yaml) try {
- yaml = await import("yaml");
- } catch (e$1) {
- /* c8 ignore start */
- throw new Error(`'yaml' is required for the YAML configuration files. Make sure it is installed\nError: ${e$1.message}`);
- }
- return yaml.parse(content);
- }
- /** @return {import('lilconfig').Options} */
- const withLoaders = (options$1 = {}) => {
- let moduleName = "postcss";
- return {
- ...options$1,
- loaders: {
- ...options$1.loaders,
- ".cjs": loader,
- ".cts": loader,
- ".js": loader,
- ".mjs": loader,
- ".mts": loader,
- ".ts": loader,
- ".yaml": yamlLoader,
- ".yml": yamlLoader
- },
- searchPlaces: [
- ...options$1.searchPlaces || [],
- "package.json",
- `.${moduleName}rc`,
- `.${moduleName}rc.json`,
- `.${moduleName}rc.yaml`,
- `.${moduleName}rc.yml`,
- `.${moduleName}rc.ts`,
- `.${moduleName}rc.cts`,
- `.${moduleName}rc.mts`,
- `.${moduleName}rc.js`,
- `.${moduleName}rc.cjs`,
- `.${moduleName}rc.mjs`,
- `${moduleName}.config.ts`,
- `${moduleName}.config.cts`,
- `${moduleName}.config.mts`,
- `${moduleName}.config.js`,
- `${moduleName}.config.cjs`,
- `${moduleName}.config.mjs`
- ]
- };
- };
- /**
- * Load Config
- *
- * @method rc
- *
- * @param {Object} ctx Config Context
- * @param {String} path Config Path
- * @param {Object} options Config Options
- *
- * @return {Promise} config PostCSS Config
- */
- function rc(ctx, path$13, options$1) {
- /**
- * @type {Object} The full Config Context
- */
- ctx = createContext(ctx);
- /**
- * @type {String} `process.cwd()`
- */
- path$13 = path$13 ? resolve$2(path$13) : process.cwd();
- return config$1.lilconfig("postcss", withLoaders(options$1)).search(path$13).then((result) => {
- if (!result) throw new Error(`No PostCSS Config found in: ${path$13}`);
- return processResult(ctx, result);
- });
- }
- /**
- * Autoload Config for PostCSS
- *
- * @author Michael Ciniawsky @michael-ciniawsky <michael.ciniawsky@gmail.com>
- * @license MIT
- *
- * @module postcss-load-config
- * @version 2.1.0
- *
- * @requires comsiconfig
- * @requires ./options
- * @requires ./plugins
- */
- module.exports = rc;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/convert-source-map@2.0.0/node_modules/convert-source-map/index.js
-var require_convert_source_map = /* @__PURE__ */ __commonJSMin(((exports) => {
- Object.defineProperty(exports, "commentRegex", { get: function getCommentRegex() {
- return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/gm;
- } });
- Object.defineProperty(exports, "mapFileCommentRegex", { get: function getMapFileCommentRegex() {
- return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/gm;
- } });
- var decodeBase64;
- if (typeof Buffer !== "undefined") if (typeof Buffer.from === "function") decodeBase64 = decodeBase64WithBufferFrom;
- else decodeBase64 = decodeBase64WithNewBuffer;
- else decodeBase64 = decodeBase64WithAtob;
- function decodeBase64WithBufferFrom(base64) {
- return Buffer.from(base64, "base64").toString();
- }
- function decodeBase64WithNewBuffer(base64) {
- if (typeof value === "number") throw new TypeError("The value to decode must not be of type number.");
- return new Buffer(base64, "base64").toString();
- }
- function decodeBase64WithAtob(base64) {
- return decodeURIComponent(escape(atob(base64)));
- }
- function stripComment(sm) {
- return sm.split(",").pop();
- }
- function readFromFileMap(sm, read) {
- var r$1 = exports.mapFileCommentRegex.exec(sm);
- var filename = r$1[1] || r$1[2];
- try {
- var sm = read(filename);
- if (sm != null && typeof sm.catch === "function") return sm.catch(throwError);
- else return sm;
- } catch (e$1) {
- throwError(e$1);
- }
- function throwError(e$1) {
- throw new Error("An error occurred while trying to read the map file at " + filename + "\n" + e$1.stack);
- }
- }
- function Converter(sm, opts) {
- opts = opts || {};
- if (opts.hasComment) sm = stripComment(sm);
- if (opts.encoding === "base64") sm = decodeBase64(sm);
- else if (opts.encoding === "uri") sm = decodeURIComponent(sm);
- if (opts.isJSON || opts.encoding) sm = JSON.parse(sm);
- this.sourcemap = sm;
- }
- Converter.prototype.toJSON = function(space) {
- return JSON.stringify(this.sourcemap, null, space);
- };
- if (typeof Buffer !== "undefined") if (typeof Buffer.from === "function") Converter.prototype.toBase64 = encodeBase64WithBufferFrom;
- else Converter.prototype.toBase64 = encodeBase64WithNewBuffer;
- else Converter.prototype.toBase64 = encodeBase64WithBtoa;
- function encodeBase64WithBufferFrom() {
- var json = this.toJSON();
- return Buffer.from(json, "utf8").toString("base64");
- }
- function encodeBase64WithNewBuffer() {
- var json = this.toJSON();
- if (typeof json === "number") throw new TypeError("The json to encode must not be of type number.");
- return new Buffer(json, "utf8").toString("base64");
- }
- function encodeBase64WithBtoa() {
- var json = this.toJSON();
- return btoa(unescape(encodeURIComponent(json)));
- }
- Converter.prototype.toURI = function() {
- var json = this.toJSON();
- return encodeURIComponent(json);
- };
- Converter.prototype.toComment = function(options$1) {
- var encoding, content, data;
- if (options$1 != null && options$1.encoding === "uri") {
- encoding = "";
- content = this.toURI();
- } else {
- encoding = ";base64";
- content = this.toBase64();
- }
- data = "sourceMappingURL=data:application/json;charset=utf-8" + encoding + "," + content;
- return options$1 != null && options$1.multiline ? "/*# " + data + " */" : "//# " + data;
- };
- Converter.prototype.toObject = function() {
- return JSON.parse(this.toJSON());
- };
- Converter.prototype.addProperty = function(key, value$1) {
- if (this.sourcemap.hasOwnProperty(key)) throw new Error("property \"" + key + "\" already exists on the sourcemap, use set property instead");
- return this.setProperty(key, value$1);
- };
- Converter.prototype.setProperty = function(key, value$1) {
- this.sourcemap[key] = value$1;
- return this;
- };
- Converter.prototype.getProperty = function(key) {
- return this.sourcemap[key];
- };
- exports.fromObject = function(obj) {
- return new Converter(obj);
- };
- exports.fromJSON = function(json) {
- return new Converter(json, { isJSON: true });
- };
- exports.fromURI = function(uri) {
- return new Converter(uri, { encoding: "uri" });
- };
- exports.fromBase64 = function(base64) {
- return new Converter(base64, { encoding: "base64" });
- };
- exports.fromComment = function(comment) {
- var m, encoding;
- comment = comment.replace(/^\/\*/g, "//").replace(/\*\/$/g, "");
- m = exports.commentRegex.exec(comment);
- encoding = m && m[4] || "uri";
- return new Converter(comment, {
- encoding,
- hasComment: true
- });
- };
- function makeConverter(sm) {
- return new Converter(sm, { isJSON: true });
- }
- exports.fromMapFileComment = function(comment, read) {
- if (typeof read === "string") throw new Error("String directory paths are no longer supported with `fromMapFileComment`\nPlease review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading");
- var sm = readFromFileMap(comment, read);
- if (sm != null && typeof sm.then === "function") return sm.then(makeConverter);
- else return makeConverter(sm);
- };
- exports.fromSource = function(content) {
- var m = content.match(exports.commentRegex);
- return m ? exports.fromComment(m.pop()) : null;
- };
- exports.fromMapFileSource = function(content, read) {
- if (typeof read === "string") throw new Error("String directory paths are no longer supported with `fromMapFileSource`\nPlease review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading");
- var m = content.match(exports.mapFileCommentRegex);
- return m ? exports.fromMapFileComment(m.pop(), read) : null;
- };
- exports.removeComments = function(src) {
- return src.replace(exports.commentRegex, "");
- };
- exports.removeMapFileComments = function(src) {
- return src.replace(exports.mapFileCommentRegex, "");
- };
- exports.generateMapFileComment = function(file, options$1) {
- var data = "sourceMappingURL=" + file;
- return options$1 && options$1.multiline ? "/*# " + data + " */" : "//# " + data;
- };
-}));
-
-//#endregion
-//#region src/node/server/sourcemap.ts
-var import_convert_source_map$2 = /* @__PURE__ */ __toESM(require_convert_source_map(), 1);
-const debug$16 = createDebugger("vite:sourcemap", { onlyWhenFocused: true });
-const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/;
-async function computeSourceRoute(map$1, file) {
- let sourceRoot;
- try {
- sourceRoot = await fsp.realpath(path.resolve(path.dirname(file), map$1.sourceRoot || ""));
- } catch {}
- return sourceRoot;
-}
-async function injectSourcesContent(map$1, file, logger) {
- let sourceRootPromise;
- const missingSources = [];
- const sourcesContent = map$1.sourcesContent || [];
- const sourcesContentPromises = [];
- for (let index = 0; index < map$1.sources.length; index++) {
- const sourcePath = map$1.sources[index];
- if (sourcesContent[index] == null && sourcePath && !virtualSourceRE.test(sourcePath)) sourcesContentPromises.push((async () => {
- sourceRootPromise ??= computeSourceRoute(map$1, file);
- const sourceRoot = await sourceRootPromise;
- let resolvedSourcePath = cleanUrl(decodeURI(sourcePath));
- if (sourceRoot) resolvedSourcePath = path.resolve(sourceRoot, resolvedSourcePath);
- sourcesContent[index] = await fsp.readFile(resolvedSourcePath, "utf-8").catch(() => {
- missingSources.push(resolvedSourcePath);
- return null;
- });
- })());
- }
- await Promise.all(sourcesContentPromises);
- map$1.sourcesContent = sourcesContent;
- if (missingSources.length) {
- logger.warnOnce(`Sourcemap for "${file}" points to missing source files`);
- debug$16?.(`Missing sources:\n ` + missingSources.join(`\n `));
- }
-}
-function genSourceMapUrl(map$1) {
- if (typeof map$1 !== "string") map$1 = JSON.stringify(map$1);
- return `data:application/json;base64,${Buffer.from(map$1).toString("base64")}`;
-}
-function getCodeWithSourcemap(type, code, map$1) {
- if (debug$16) code += `\n/*${JSON.stringify(map$1, null, 2).replace(/\*\//g, "*\\/")}*/\n`;
- if (type === "js") code += `\n//# sourceMappingURL=${genSourceMapUrl(map$1)}`;
- else if (type === "css") code += `\n/*# sourceMappingURL=${genSourceMapUrl(map$1)} */`;
- return code;
-}
-function applySourcemapIgnoreList(map$1, sourcemapPath, sourcemapIgnoreList, logger) {
- let { x_google_ignoreList } = map$1;
- if (x_google_ignoreList === void 0) x_google_ignoreList = [];
- for (let sourcesIndex = 0; sourcesIndex < map$1.sources.length; ++sourcesIndex) {
- const sourcePath = map$1.sources[sourcesIndex];
- if (!sourcePath) continue;
- const ignoreList = sourcemapIgnoreList(path.isAbsolute(sourcePath) ? sourcePath : path.resolve(path.dirname(sourcemapPath), sourcePath), sourcemapPath);
- if (logger && typeof ignoreList !== "boolean") logger.warn("sourcemapIgnoreList function must return a boolean.");
- if (ignoreList && !x_google_ignoreList.includes(sourcesIndex)) x_google_ignoreList.push(sourcesIndex);
- }
- if (x_google_ignoreList.length > 0) {
- if (!map$1.x_google_ignoreList) map$1.x_google_ignoreList = x_google_ignoreList;
- }
-}
-async function extractSourcemapFromFile(code, filePath) {
- const map$1 = (import_convert_source_map$2.fromSource(code) || await import_convert_source_map$2.fromMapFileSource(code, createConvertSourceMapReadMap(filePath)))?.toObject();
- if (map$1) return {
- code: code.replace(import_convert_source_map$2.default.mapFileCommentRegex, blankReplacer),
- map: map$1
- };
-}
-function createConvertSourceMapReadMap(originalFileName) {
- return (filename) => {
- return fsp.readFile(path.resolve(path.dirname(originalFileName), filename), "utf-8");
- };
-}
-
-//#endregion
-//#region src/node/publicDir.ts
-const publicFilesMap = /* @__PURE__ */ new WeakMap();
-async function initPublicFiles(config$2) {
- let fileNames;
- try {
- fileNames = await recursiveReaddir(config$2.publicDir);
- } catch (e$1) {
- if (e$1.code === ERR_SYMLINK_IN_RECURSIVE_READDIR) return;
- throw e$1;
- }
- const publicFiles = new Set(fileNames.map((fileName) => fileName.slice(config$2.publicDir.length)));
- publicFilesMap.set(config$2, publicFiles);
- return publicFiles;
-}
-function getPublicFiles(config$2) {
- return publicFilesMap.get(config$2);
-}
-function checkPublicFile(url$3, config$2) {
- const { publicDir } = config$2;
- if (!publicDir || url$3[0] !== "/") return;
- const fileName = cleanUrl(url$3);
- const publicFiles = getPublicFiles(config$2);
- if (publicFiles) return publicFiles.has(fileName) ? normalizePath(path.join(publicDir, fileName)) : void 0;
- const publicFile = normalizePath(path.join(publicDir, fileName));
- if (!publicFile.startsWith(withTrailingSlash(publicDir))) return;
- return tryStatSync(publicFile)?.isFile() ? publicFile : void 0;
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/@rollup+plugin-alias@5.1.1_rollup@4.43.0/node_modules/@rollup/plugin-alias/dist/es/index.js
-function matches$1(pattern, importee) {
- if (pattern instanceof RegExp) return pattern.test(importee);
- if (importee.length < pattern.length) return false;
- if (importee === pattern) return true;
- return importee.startsWith(pattern + "/");
-}
-function getEntries({ entries, customResolver }) {
- if (!entries) return [];
- const resolverFunctionFromOptions = resolveCustomResolver(customResolver);
- if (Array.isArray(entries)) return entries.map((entry) => {
- return {
- find: entry.find,
- replacement: entry.replacement,
- resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions
- };
- });
- return Object.entries(entries).map(([key, value$1]) => {
- return {
- find: key,
- replacement: value$1,
- resolverFunction: resolverFunctionFromOptions
- };
- });
-}
-function getHookFunction(hook) {
- if (typeof hook === "function") return hook;
- if (hook && "handler" in hook && typeof hook.handler === "function") return hook.handler;
- return null;
-}
-function resolveCustomResolver(customResolver) {
- if (typeof customResolver === "function") return customResolver;
- if (customResolver) return getHookFunction(customResolver.resolveId);
- return null;
-}
-function alias(options$1 = {}) {
- const entries = getEntries(options$1);
- if (entries.length === 0) return {
- name: "alias",
- resolveId: () => null
- };
- return {
- name: "alias",
- async buildStart(inputOptions) {
- await Promise.all([...Array.isArray(options$1.entries) ? options$1.entries : [], options$1].map(({ customResolver }) => {
- var _a;
- return customResolver && ((_a = getHookFunction(customResolver.buildStart)) === null || _a === void 0 ? void 0 : _a.call(this, inputOptions));
- }));
- },
- resolveId(importee, importer, resolveOptions) {
- const matchedEntry = entries.find((entry) => matches$1(entry.find, importee));
- if (!matchedEntry) return null;
- const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
- if (matchedEntry.resolverFunction) return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions);
- return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => {
- if (resolved) return resolved;
- if (!path$1.isAbsolute(updatedId)) this.warn(`rewrote ${importee} to ${updatedId} but was not an abolute path and was not handled by other plugins. This will lead to duplicated modules for the same path. To avoid duplicating modules, you should resolve to an absolute path.`);
- return { id: updatedId };
- });
- }
- };
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/mrmime@2.0.1/node_modules/mrmime/index.mjs
-const mimes = {
- "3g2": "video/3gpp2",
- "3gp": "video/3gpp",
- "3gpp": "video/3gpp",
- "3mf": "model/3mf",
- "aac": "audio/aac",
- "ac": "application/pkix-attr-cert",
- "adp": "audio/adpcm",
- "adts": "audio/aac",
- "ai": "application/postscript",
- "aml": "application/automationml-aml+xml",
- "amlx": "application/automationml-amlx+zip",
- "amr": "audio/amr",
- "apng": "image/apng",
- "appcache": "text/cache-manifest",
- "appinstaller": "application/appinstaller",
- "appx": "application/appx",
- "appxbundle": "application/appxbundle",
- "asc": "application/pgp-keys",
- "atom": "application/atom+xml",
- "atomcat": "application/atomcat+xml",
- "atomdeleted": "application/atomdeleted+xml",
- "atomsvc": "application/atomsvc+xml",
- "au": "audio/basic",
- "avci": "image/avci",
- "avcs": "image/avcs",
- "avif": "image/avif",
- "aw": "application/applixware",
- "bdoc": "application/bdoc",
- "bin": "application/octet-stream",
- "bmp": "image/bmp",
- "bpk": "application/octet-stream",
- "btf": "image/prs.btif",
- "btif": "image/prs.btif",
- "buffer": "application/octet-stream",
- "ccxml": "application/ccxml+xml",
- "cdfx": "application/cdfx+xml",
- "cdmia": "application/cdmi-capability",
- "cdmic": "application/cdmi-container",
- "cdmid": "application/cdmi-domain",
- "cdmio": "application/cdmi-object",
- "cdmiq": "application/cdmi-queue",
- "cer": "application/pkix-cert",
- "cgm": "image/cgm",
- "cjs": "application/node",
- "class": "application/java-vm",
- "coffee": "text/coffeescript",
- "conf": "text/plain",
- "cpl": "application/cpl+xml",
- "cpt": "application/mac-compactpro",
- "crl": "application/pkix-crl",
- "css": "text/css",
- "csv": "text/csv",
- "cu": "application/cu-seeme",
- "cwl": "application/cwl",
- "cww": "application/prs.cww",
- "davmount": "application/davmount+xml",
- "dbk": "application/docbook+xml",
- "deb": "application/octet-stream",
- "def": "text/plain",
- "deploy": "application/octet-stream",
- "dib": "image/bmp",
- "disposition-notification": "message/disposition-notification",
- "dist": "application/octet-stream",
- "distz": "application/octet-stream",
- "dll": "application/octet-stream",
- "dmg": "application/octet-stream",
- "dms": "application/octet-stream",
- "doc": "application/msword",
- "dot": "application/msword",
- "dpx": "image/dpx",
- "drle": "image/dicom-rle",
- "dsc": "text/prs.lines.tag",
- "dssc": "application/dssc+der",
- "dtd": "application/xml-dtd",
- "dump": "application/octet-stream",
- "dwd": "application/atsc-dwd+xml",
- "ear": "application/java-archive",
- "ecma": "application/ecmascript",
- "elc": "application/octet-stream",
- "emf": "image/emf",
- "eml": "message/rfc822",
- "emma": "application/emma+xml",
- "emotionml": "application/emotionml+xml",
- "eps": "application/postscript",
- "epub": "application/epub+zip",
- "exe": "application/octet-stream",
- "exi": "application/exi",
- "exp": "application/express",
- "exr": "image/aces",
- "ez": "application/andrew-inset",
- "fdf": "application/fdf",
- "fdt": "application/fdt+xml",
- "fits": "image/fits",
- "g3": "image/g3fax",
- "gbr": "application/rpki-ghostbusters",
- "geojson": "application/geo+json",
- "gif": "image/gif",
- "glb": "model/gltf-binary",
- "gltf": "model/gltf+json",
- "gml": "application/gml+xml",
- "gpx": "application/gpx+xml",
- "gram": "application/srgs",
- "grxml": "application/srgs+xml",
- "gxf": "application/gxf",
- "gz": "application/gzip",
- "h261": "video/h261",
- "h263": "video/h263",
- "h264": "video/h264",
- "heic": "image/heic",
- "heics": "image/heic-sequence",
- "heif": "image/heif",
- "heifs": "image/heif-sequence",
- "hej2": "image/hej2k",
- "held": "application/atsc-held+xml",
- "hjson": "application/hjson",
- "hlp": "application/winhlp",
- "hqx": "application/mac-binhex40",
- "hsj2": "image/hsj2",
- "htm": "text/html",
- "html": "text/html",
- "ics": "text/calendar",
- "ief": "image/ief",
- "ifb": "text/calendar",
- "iges": "model/iges",
- "igs": "model/iges",
- "img": "application/octet-stream",
- "in": "text/plain",
- "ini": "text/plain",
- "ink": "application/inkml+xml",
- "inkml": "application/inkml+xml",
- "ipfix": "application/ipfix",
- "iso": "application/octet-stream",
- "its": "application/its+xml",
- "jade": "text/jade",
- "jar": "application/java-archive",
- "jhc": "image/jphc",
- "jls": "image/jls",
- "jp2": "image/jp2",
- "jpe": "image/jpeg",
- "jpeg": "image/jpeg",
- "jpf": "image/jpx",
- "jpg": "image/jpeg",
- "jpg2": "image/jp2",
- "jpgm": "image/jpm",
- "jpgv": "video/jpeg",
- "jph": "image/jph",
- "jpm": "image/jpm",
- "jpx": "image/jpx",
- "js": "text/javascript",
- "json": "application/json",
- "json5": "application/json5",
- "jsonld": "application/ld+json",
- "jsonml": "application/jsonml+json",
- "jsx": "text/jsx",
- "jt": "model/jt",
- "jxl": "image/jxl",
- "jxr": "image/jxr",
- "jxra": "image/jxra",
- "jxrs": "image/jxrs",
- "jxs": "image/jxs",
- "jxsc": "image/jxsc",
- "jxsi": "image/jxsi",
- "jxss": "image/jxss",
- "kar": "audio/midi",
- "ktx": "image/ktx",
- "ktx2": "image/ktx2",
- "less": "text/less",
- "lgr": "application/lgr+xml",
- "list": "text/plain",
- "litcoffee": "text/coffeescript",
- "log": "text/plain",
- "lostxml": "application/lost+xml",
- "lrf": "application/octet-stream",
- "m1v": "video/mpeg",
- "m21": "application/mp21",
- "m2a": "audio/mpeg",
- "m2t": "video/mp2t",
- "m2ts": "video/mp2t",
- "m2v": "video/mpeg",
- "m3a": "audio/mpeg",
- "m4a": "audio/mp4",
- "m4p": "application/mp4",
- "m4s": "video/iso.segment",
- "ma": "application/mathematica",
- "mads": "application/mads+xml",
- "maei": "application/mmt-aei+xml",
- "man": "text/troff",
- "manifest": "text/cache-manifest",
- "map": "application/json",
- "mar": "application/octet-stream",
- "markdown": "text/markdown",
- "mathml": "application/mathml+xml",
- "mb": "application/mathematica",
- "mbox": "application/mbox",
- "md": "text/markdown",
- "mdx": "text/mdx",
- "me": "text/troff",
- "mesh": "model/mesh",
- "meta4": "application/metalink4+xml",
- "metalink": "application/metalink+xml",
- "mets": "application/mets+xml",
- "mft": "application/rpki-manifest",
- "mid": "audio/midi",
- "midi": "audio/midi",
- "mime": "message/rfc822",
- "mj2": "video/mj2",
- "mjp2": "video/mj2",
- "mjs": "text/javascript",
- "mml": "text/mathml",
- "mods": "application/mods+xml",
- "mov": "video/quicktime",
- "mp2": "audio/mpeg",
- "mp21": "application/mp21",
- "mp2a": "audio/mpeg",
- "mp3": "audio/mpeg",
- "mp4": "video/mp4",
- "mp4a": "audio/mp4",
- "mp4s": "application/mp4",
- "mp4v": "video/mp4",
- "mpd": "application/dash+xml",
- "mpe": "video/mpeg",
- "mpeg": "video/mpeg",
- "mpf": "application/media-policy-dataset+xml",
- "mpg": "video/mpeg",
- "mpg4": "video/mp4",
- "mpga": "audio/mpeg",
- "mpp": "application/dash-patch+xml",
- "mrc": "application/marc",
- "mrcx": "application/marcxml+xml",
- "ms": "text/troff",
- "mscml": "application/mediaservercontrol+xml",
- "msh": "model/mesh",
- "msi": "application/octet-stream",
- "msix": "application/msix",
- "msixbundle": "application/msixbundle",
- "msm": "application/octet-stream",
- "msp": "application/octet-stream",
- "mtl": "model/mtl",
- "mts": "video/mp2t",
- "musd": "application/mmt-usd+xml",
- "mxf": "application/mxf",
- "mxmf": "audio/mobile-xmf",
- "mxml": "application/xv+xml",
- "n3": "text/n3",
- "nb": "application/mathematica",
- "nq": "application/n-quads",
- "nt": "application/n-triples",
- "obj": "model/obj",
- "oda": "application/oda",
- "oga": "audio/ogg",
- "ogg": "audio/ogg",
- "ogv": "video/ogg",
- "ogx": "application/ogg",
- "omdoc": "application/omdoc+xml",
- "onepkg": "application/onenote",
- "onetmp": "application/onenote",
- "onetoc": "application/onenote",
- "onetoc2": "application/onenote",
- "opf": "application/oebps-package+xml",
- "opus": "audio/ogg",
- "otf": "font/otf",
- "owl": "application/rdf+xml",
- "oxps": "application/oxps",
- "p10": "application/pkcs10",
- "p7c": "application/pkcs7-mime",
- "p7m": "application/pkcs7-mime",
- "p7s": "application/pkcs7-signature",
- "p8": "application/pkcs8",
- "pdf": "application/pdf",
- "pfr": "application/font-tdpfr",
- "pgp": "application/pgp-encrypted",
- "pkg": "application/octet-stream",
- "pki": "application/pkixcmp",
- "pkipath": "application/pkix-pkipath",
- "pls": "application/pls+xml",
- "png": "image/png",
- "prc": "model/prc",
- "prf": "application/pics-rules",
- "provx": "application/provenance+xml",
- "ps": "application/postscript",
- "pskcxml": "application/pskc+xml",
- "pti": "image/prs.pti",
- "qt": "video/quicktime",
- "raml": "application/raml+yaml",
- "rapd": "application/route-apd+xml",
- "rdf": "application/rdf+xml",
- "relo": "application/p2p-overlay+xml",
- "rif": "application/reginfo+xml",
- "rl": "application/resource-lists+xml",
- "rld": "application/resource-lists-diff+xml",
- "rmi": "audio/midi",
- "rnc": "application/relax-ng-compact-syntax",
- "rng": "application/xml",
- "roa": "application/rpki-roa",
- "roff": "text/troff",
- "rq": "application/sparql-query",
- "rs": "application/rls-services+xml",
- "rsat": "application/atsc-rsat+xml",
- "rsd": "application/rsd+xml",
- "rsheet": "application/urc-ressheet+xml",
- "rss": "application/rss+xml",
- "rtf": "text/rtf",
- "rtx": "text/richtext",
- "rusd": "application/route-usd+xml",
- "s3m": "audio/s3m",
- "sbml": "application/sbml+xml",
- "scq": "application/scvp-cv-request",
- "scs": "application/scvp-cv-response",
- "sdp": "application/sdp",
- "senmlx": "application/senml+xml",
- "sensmlx": "application/sensml+xml",
- "ser": "application/java-serialized-object",
- "setpay": "application/set-payment-initiation",
- "setreg": "application/set-registration-initiation",
- "sgi": "image/sgi",
- "sgm": "text/sgml",
- "sgml": "text/sgml",
- "shex": "text/shex",
- "shf": "application/shf+xml",
- "shtml": "text/html",
- "sieve": "application/sieve",
- "sig": "application/pgp-signature",
- "sil": "audio/silk",
- "silo": "model/mesh",
- "siv": "application/sieve",
- "slim": "text/slim",
- "slm": "text/slim",
- "sls": "application/route-s-tsid+xml",
- "smi": "application/smil+xml",
- "smil": "application/smil+xml",
- "snd": "audio/basic",
- "so": "application/octet-stream",
- "spdx": "text/spdx",
- "spp": "application/scvp-vp-response",
- "spq": "application/scvp-vp-request",
- "spx": "audio/ogg",
- "sql": "application/sql",
- "sru": "application/sru+xml",
- "srx": "application/sparql-results+xml",
- "ssdl": "application/ssdl+xml",
- "ssml": "application/ssml+xml",
- "stk": "application/hyperstudio",
- "stl": "model/stl",
- "stpx": "model/step+xml",
- "stpxz": "model/step-xml+zip",
- "stpz": "model/step+zip",
- "styl": "text/stylus",
- "stylus": "text/stylus",
- "svg": "image/svg+xml",
- "svgz": "image/svg+xml",
- "swidtag": "application/swid+xml",
- "t": "text/troff",
- "t38": "image/t38",
- "td": "application/urc-targetdesc+xml",
- "tei": "application/tei+xml",
- "teicorpus": "application/tei+xml",
- "text": "text/plain",
- "tfi": "application/thraud+xml",
- "tfx": "image/tiff-fx",
- "tif": "image/tiff",
- "tiff": "image/tiff",
- "toml": "application/toml",
- "tr": "text/troff",
- "trig": "application/trig",
- "ts": "video/mp2t",
- "tsd": "application/timestamped-data",
- "tsv": "text/tab-separated-values",
- "ttc": "font/collection",
- "ttf": "font/ttf",
- "ttl": "text/turtle",
- "ttml": "application/ttml+xml",
- "txt": "text/plain",
- "u3d": "model/u3d",
- "u8dsn": "message/global-delivery-status",
- "u8hdr": "message/global-headers",
- "u8mdn": "message/global-disposition-notification",
- "u8msg": "message/global",
- "ubj": "application/ubjson",
- "uri": "text/uri-list",
- "uris": "text/uri-list",
- "urls": "text/uri-list",
- "vcard": "text/vcard",
- "vrml": "model/vrml",
- "vtt": "text/vtt",
- "vxml": "application/voicexml+xml",
- "war": "application/java-archive",
- "wasm": "application/wasm",
- "wav": "audio/wav",
- "weba": "audio/webm",
- "webm": "video/webm",
- "webmanifest": "application/manifest+json",
- "webp": "image/webp",
- "wgsl": "text/wgsl",
- "wgt": "application/widget",
- "wif": "application/watcherinfo+xml",
- "wmf": "image/wmf",
- "woff": "font/woff",
- "woff2": "font/woff2",
- "wrl": "model/vrml",
- "wsdl": "application/wsdl+xml",
- "wspolicy": "application/wspolicy+xml",
- "x3d": "model/x3d+xml",
- "x3db": "model/x3d+fastinfoset",
- "x3dbz": "model/x3d+binary",
- "x3dv": "model/x3d-vrml",
- "x3dvz": "model/x3d+vrml",
- "x3dz": "model/x3d+xml",
- "xaml": "application/xaml+xml",
- "xav": "application/xcap-att+xml",
- "xca": "application/xcap-caps+xml",
- "xcs": "application/calendar+xml",
- "xdf": "application/xcap-diff+xml",
- "xdssc": "application/dssc+xml",
- "xel": "application/xcap-el+xml",
- "xenc": "application/xenc+xml",
- "xer": "application/patch-ops-error+xml",
- "xfdf": "application/xfdf",
- "xht": "application/xhtml+xml",
- "xhtml": "application/xhtml+xml",
- "xhvml": "application/xv+xml",
- "xlf": "application/xliff+xml",
- "xm": "audio/xm",
- "xml": "text/xml",
- "xns": "application/xcap-ns+xml",
- "xop": "application/xop+xml",
- "xpl": "application/xproc+xml",
- "xsd": "application/xml",
- "xsf": "application/prs.xsf+xml",
- "xsl": "application/xml",
- "xslt": "application/xml",
- "xspf": "application/xspf+xml",
- "xvm": "application/xv+xml",
- "xvml": "application/xv+xml",
- "yaml": "text/yaml",
- "yang": "application/yang",
- "yin": "application/yin+xml",
- "yml": "text/yaml",
- "zip": "application/zip"
-};
-function lookup(extn) {
- let tmp = ("" + extn).trim().toLowerCase();
- let idx = tmp.lastIndexOf(".");
- return mimes[!~idx ? tmp : tmp.substring(++idx)];
-}
-
-//#endregion
-//#region src/node/plugins/asset.ts
-var import_picocolors$30 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g;
-const jsSourceMapRE = /\.[cm]?js\.map$/;
-const noInlineRE = /[?&]no-inline\b/;
-const inlineRE$3 = /[?&]inline\b/;
-const assetCache = /* @__PURE__ */ new WeakMap();
-/** a set of referenceId for entry CSS assets for each environment */
-const cssEntriesMap = /* @__PURE__ */ new WeakMap();
-function registerCustomMime() {
- mimes.ico = "image/x-icon";
- mimes.cur = "image/x-icon";
- mimes.flac = "audio/flac";
- mimes.eot = "application/vnd.ms-fontobject";
-}
-function renderAssetUrlInJS(pluginContext, chunk, opts, code) {
- const { environment } = pluginContext;
- const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, environment.config.isWorker);
- let match;
- let s;
- assetUrlRE.lastIndex = 0;
- while (match = assetUrlRE.exec(code)) {
- s ||= new MagicString(code);
- const [full, referenceId, postfix = ""] = match;
- const file = pluginContext.getFileName(referenceId);
- chunk.viteMetadata.importedAssets.add(cleanUrl(file));
- const replacement = toOutputFilePathInJS(environment, file + postfix, "asset", chunk.fileName, "js", toRelativeRuntime);
- const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
- s.update(match.index, match.index + full.length, replacementString);
- }
- const publicAssetUrlMap = publicAssetUrlCache.get(environment.getTopLevelConfig());
- publicAssetUrlRE.lastIndex = 0;
- while (match = publicAssetUrlRE.exec(code)) {
- s ||= new MagicString(code);
- const [full, hash$1] = match;
- const replacement = toOutputFilePathInJS(environment, publicAssetUrlMap.get(hash$1).slice(1), "public", chunk.fileName, "js", toRelativeRuntime);
- const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
- s.update(match.index, match.index + full.length, replacementString);
- }
- return s;
-}
-/**
-* Also supports loading plain strings with import text from './foo.txt?raw'
-*/
-function assetPlugin(config$2) {
- registerCustomMime();
- return {
- name: "vite:asset",
- perEnvironmentStartEndDuringDev: true,
- buildStart() {
- assetCache.set(this.environment, /* @__PURE__ */ new Map());
- cssEntriesMap.set(this.environment, /* @__PURE__ */ new Map());
- },
- resolveId: { handler(id) {
- if (!config$2.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) return;
- if (checkPublicFile(id, config$2)) return id;
- } },
- load: {
- filter: { id: { exclude: /^\0/ } },
- async handler(id) {
- if (rawRE.test(id)) {
- const file = checkPublicFile(id, config$2) || cleanUrl(id);
- this.addWatchFile(file);
- return `export default ${JSON.stringify(await fsp.readFile(file, "utf-8"))}`;
- }
- if (!urlRE.test(id) && !config$2.assetsInclude(cleanUrl(id))) return;
- id = removeUrlQuery(id);
- let url$3 = await fileToUrl$1(this, id);
- if (!url$3.startsWith("data:") && this.environment.mode === "dev") {
- const mod = this.environment.moduleGraph.getModuleById(id);
- if (mod && mod.lastHMRTimestamp > 0) url$3 = injectQuery(url$3, `t=${mod.lastHMRTimestamp}`);
- }
- return {
- code: `export default ${JSON.stringify(encodeURIPath(url$3))}`,
- moduleSideEffects: config$2.command === "build" && this.getModuleInfo(id)?.isEntry ? "no-treeshake" : false,
- meta: config$2.command === "build" ? { "vite:asset": true } : void 0
- };
- }
- },
- renderChunk(code, chunk, opts) {
- const s = renderAssetUrlInJS(this, chunk, opts, code);
- if (s) return {
- code: s.toString(),
- map: this.environment.config.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
- };
- else return null;
- },
- generateBundle(_, bundle) {
- let importedFiles;
- for (const file in bundle) {
- const chunk = bundle[file];
- if (chunk.type === "chunk" && chunk.isEntry && chunk.moduleIds.length === 1 && config$2.assetsInclude(chunk.moduleIds[0]) && this.getModuleInfo(chunk.moduleIds[0])?.meta["vite:asset"]) {
- if (!importedFiles) {
- importedFiles = /* @__PURE__ */ new Set();
- for (const file$1 in bundle) {
- const chunk$1 = bundle[file$1];
- if (chunk$1.type === "chunk") {
- for (const importedFile of chunk$1.imports) importedFiles.add(importedFile);
- for (const importedFile of chunk$1.dynamicImports) importedFiles.add(importedFile);
- }
- }
- }
- if (!importedFiles.has(file)) delete bundle[file];
- }
- }
- if (config$2.command === "build" && !this.environment.config.build.emitAssets) {
- for (const file in bundle) if (bundle[file].type === "asset" && !file.endsWith("ssr-manifest.json") && !jsSourceMapRE.test(file)) delete bundle[file];
- }
- }
- };
-}
-async function fileToUrl$1(pluginContext, id) {
- const { environment } = pluginContext;
- if (environment.config.command === "serve") return fileToDevUrl(environment, id);
- else return fileToBuiltUrl(pluginContext, id);
-}
-async function fileToDevUrl(environment, id, skipBase = false) {
- const config$2 = environment.getTopLevelConfig();
- const publicFile = checkPublicFile(id, config$2);
- if (inlineRE$3.test(id)) {
- const file = publicFile || cleanUrl(id);
- return assetToDataURL(environment, file, await fsp.readFile(file));
- }
- const cleanedId = cleanUrl(id);
- if (cleanedId.endsWith(".svg")) {
- const file = publicFile || cleanedId;
- const content = await fsp.readFile(file);
- if (shouldInline(environment, file, id, content, void 0, void 0)) return assetToDataURL(environment, file, content);
- }
- let rtn;
- if (publicFile) rtn = id;
- else if (id.startsWith(withTrailingSlash(config$2.root))) rtn = "/" + path.posix.relative(config$2.root, id);
- else rtn = path.posix.join(FS_PREFIX, id);
- if (skipBase) return rtn;
- return joinUrlSegments(joinUrlSegments(config$2.server.origin ?? "", config$2.decodedBase), removeLeadingSlash(rtn));
-}
-function getPublicAssetFilename(hash$1, config$2) {
- return publicAssetUrlCache.get(config$2)?.get(hash$1);
-}
-const publicAssetUrlCache = /* @__PURE__ */ new WeakMap();
-const publicAssetUrlRE = /__VITE_PUBLIC_ASSET__([a-z\d]{8})__/g;
-function publicFileToBuiltUrl(url$3, config$2) {
- if (config$2.command !== "build") return joinUrlSegments(config$2.decodedBase, url$3);
- const hash$1 = getHash(url$3);
- let cache$1 = publicAssetUrlCache.get(config$2);
- if (!cache$1) {
- cache$1 = /* @__PURE__ */ new Map();
- publicAssetUrlCache.set(config$2, cache$1);
- }
- if (!cache$1.get(hash$1)) cache$1.set(hash$1, url$3);
- return `__VITE_PUBLIC_ASSET__${hash$1}__`;
-}
-const GIT_LFS_PREFIX = Buffer$1.from("version https://git-lfs.github.com");
-function isGitLfsPlaceholder(content) {
- if (content.length < GIT_LFS_PREFIX.length) return false;
- return GIT_LFS_PREFIX.compare(content, 0, GIT_LFS_PREFIX.length) === 0;
-}
-/**
-* Register an asset to be emitted as part of the bundle (if necessary)
-* and returns the resolved public URL
-*/
-async function fileToBuiltUrl(pluginContext, id, skipPublicCheck = false, forceInline) {
- const environment = pluginContext.environment;
- const topLevelConfig = environment.getTopLevelConfig();
- if (!skipPublicCheck) {
- const publicFile = checkPublicFile(id, topLevelConfig);
- if (publicFile) if (inlineRE$3.test(id)) id = publicFile;
- else return publicFileToBuiltUrl(id, topLevelConfig);
- }
- const cache$1 = assetCache.get(environment);
- const cached = cache$1.get(id);
- if (cached) return cached;
- let { file, postfix } = splitFileAndPostfix(id);
- const content = await fsp.readFile(file);
- let url$3;
- if (shouldInline(environment, file, id, content, pluginContext, forceInline)) url$3 = assetToDataURL(environment, file, content);
- else {
- const originalFileName = normalizePath(path.relative(environment.config.root, file));
- const referenceId = pluginContext.emitFile({
- type: "asset",
- name: path.basename(file),
- originalFileName,
- source: content
- });
- if (environment.config.command === "build" && noInlineRE.test(postfix)) postfix = postfix.replace(noInlineRE, "").replace(/^&/, "?");
- url$3 = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}`;
- }
- cache$1.set(id, url$3);
- return url$3;
-}
-async function urlToBuiltUrl(pluginContext, url$3, importer, forceInline) {
- const topLevelConfig = pluginContext.environment.getTopLevelConfig();
- if (checkPublicFile(url$3, topLevelConfig)) return publicFileToBuiltUrl(url$3, topLevelConfig);
- return fileToBuiltUrl(pluginContext, normalizePath(url$3[0] === "/" ? path.join(topLevelConfig.root, url$3) : path.join(path.dirname(importer), url$3)), true, forceInline);
-}
-function shouldInline(environment, file, id, content, buildPluginContext, forceInline) {
- if (noInlineRE.test(id)) return false;
- if (inlineRE$3.test(id)) return true;
- if (buildPluginContext) {
- if (environment.config.build.lib) return true;
- if (buildPluginContext.getModuleInfo(id)?.isEntry) return false;
- }
- if (forceInline !== void 0) return forceInline;
- if (file.endsWith(".html")) return false;
- if (file.endsWith(".svg") && id.includes("#")) return false;
- let limit;
- const { assetsInlineLimit } = environment.config.build;
- if (typeof assetsInlineLimit === "function") {
- const userShouldInline = assetsInlineLimit(file, content);
- if (userShouldInline != null) return userShouldInline;
- limit = DEFAULT_ASSETS_INLINE_LIMIT;
- } else limit = Number(assetsInlineLimit);
- return content.length < limit && !isGitLfsPlaceholder(content);
-}
-function assetToDataURL(environment, file, content) {
- if (environment.config.build.lib && isGitLfsPlaceholder(content)) environment.logger.warn(import_picocolors$30.default.yellow(`Inlined file ${file} was not downloaded via Git LFS`));
- if (file.endsWith(".svg")) return svgToDataURL(content);
- else return `data:${lookup(file) ?? "application/octet-stream"};base64,${content.toString("base64")}`;
-}
-const nestedQuotesRE = /"[^"']*'[^"]*"|'[^'"]*"[^']*'/;
-function svgToDataURL(content) {
- const stringContent = content.toString();
- if (stringContent.includes("<text") || stringContent.includes("<foreignObject") || nestedQuotesRE.test(stringContent)) return `data:image/svg+xml;base64,${content.toString("base64")}`;
- else return "data:image/svg+xml," + stringContent.trim().replaceAll(/>\s+</g, "><").replaceAll("\"", "'").replaceAll("%", "%25").replaceAll("#", "%23").replaceAll("<", "%3c").replaceAll(">", "%3e").replaceAll(/\s+/g, "%20");
-}
-
-//#endregion
-//#region src/node/plugins/json.ts
-/**
-* https://github.com/rollup/plugins/blob/master/packages/json/src/index.js
-*
-* This source code is licensed under the MIT license found in the
-* LICENSE file at
-* https://github.com/rollup/plugins/blob/master/LICENSE
-*/
-const jsonExtRE = /\.json(?:$|\?)(?!commonjs-(?:proxy|external))/;
-const jsonObjRE = /^\s*\{/;
-const jsonLangRE = new RegExp(`\\.(?:json|json5)(?:$|\\?)`);
-const isJSONRequest = (request) => jsonLangRE.test(request);
-function jsonPlugin(options$1, isBuild) {
- return {
- name: "vite:json",
- transform: {
- filter: { id: {
- include: jsonExtRE,
- exclude: SPECIAL_QUERY_RE
- } },
- handler(json, id) {
- if (inlineRE$3.test(id) || noInlineRE.test(id)) this.warn("\nUsing ?inline or ?no-inline for JSON imports will have no effect.\nPlease use ?url&inline or ?url&no-inline to control JSON file inlining behavior.\n");
- json = stripBomTag(json);
- try {
- if (options$1.stringify !== false) {
- if (options$1.namedExports && jsonObjRE.test(json)) {
- const parsed = JSON.parse(json);
- const keys = Object.keys(parsed);
- let code = "";
- let defaultObjectCode = "{\n";
- for (const key of keys) if (key === makeLegalIdentifier(key)) {
- code += `export const ${key} = ${serializeValue(parsed[key])};\n`;
- defaultObjectCode += ` ${key},\n`;
- } else defaultObjectCode += ` ${JSON.stringify(key)}: ${serializeValue(parsed[key])},\n`;
- defaultObjectCode += "}";
- code += `export default ${defaultObjectCode};\n`;
- return {
- code,
- map: { mappings: "" }
- };
- }
- if (options$1.stringify === true || json.length > 10 * 1e3) {
- if (isBuild) json = JSON.stringify(JSON.parse(json));
- return {
- code: `export default /* #__PURE__ */ JSON.parse(${JSON.stringify(json)})`,
- map: { mappings: "" }
- };
- }
- }
- return {
- code: dataToEsm(JSON.parse(json), {
- preferConst: true,
- namedExports: options$1.namedExports
- }),
- map: { mappings: "" }
- };
- } catch (e$1) {
- const position = extractJsonErrorPosition(e$1.message, json.length);
- const msg = position ? `, invalid JSON syntax found at position ${position}` : `.`;
- this.error(`Failed to parse JSON file` + msg, position);
- }
- }
- }
- };
-}
-function serializeValue(value$1) {
- const valueAsString = JSON.stringify(value$1);
- if (typeof value$1 === "object" && value$1 != null && valueAsString.length > 10 * 1e3) return `/* #__PURE__ */ JSON.parse(${JSON.stringify(valueAsString)})`;
- return valueAsString;
-}
-function extractJsonErrorPosition(errorMessage, inputLength) {
- if (errorMessage.startsWith("Unexpected end of JSON input")) return inputLength - 1;
- const errorMessageList = /at position (\d+)/.exec(errorMessage);
- return errorMessageList ? Math.max(parseInt(errorMessageList[1], 10) - 1, 0) : void 0;
-}
-
-//#endregion
-//#region src/node/plugins/optimizedDeps.ts
-var import_picocolors$29 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const debug$15 = createDebugger("vite:optimize-deps");
-function optimizedDepsPlugin() {
- return {
- name: "vite:optimized-deps",
- applyToEnvironment(environment) {
- return !isDepOptimizationDisabled(environment.config.optimizeDeps);
- },
- resolveId(id) {
- if (this.environment.depsOptimizer?.isOptimizedDepFile(id)) return id;
- },
- async load(id) {
- const environment = this.environment;
- const depsOptimizer = environment.depsOptimizer;
- if (depsOptimizer?.isOptimizedDepFile(id)) {
- const metadata = depsOptimizer.metadata;
- const file = cleanUrl(id);
- const versionMatch = DEP_VERSION_RE.exec(id);
- const browserHash = versionMatch ? versionMatch[1].split("=")[1] : void 0;
- const info = optimizedDepInfoFromFile(metadata, file);
- if (info) {
- if (browserHash && info.browserHash !== browserHash && !environment.config.optimizeDeps.ignoreOutdatedRequests) throwOutdatedRequest(id);
- try {
- await info.processing;
- } catch {
- throwProcessingError(id);
- }
- const newMetadata = depsOptimizer.metadata;
- if (metadata !== newMetadata) {
- const currentInfo = optimizedDepInfoFromFile(newMetadata, file);
- if (info.browserHash !== currentInfo?.browserHash && !environment.config.optimizeDeps.ignoreOutdatedRequests) throwOutdatedRequest(id);
- }
- }
- debug$15?.(`load ${import_picocolors$29.default.cyan(file)}`);
- try {
- return await fsp.readFile(file, "utf-8");
- } catch {
- if (browserHash && !environment.config.optimizeDeps.ignoreOutdatedRequests) throwOutdatedRequest(id);
- throwFileNotFoundInOptimizedDep(id);
- }
- }
- }
- };
-}
-function throwProcessingError(id) {
- const err$2 = /* @__PURE__ */ new Error(`Something unexpected happened while optimizing "${id}". The current page should have reloaded by now`);
- err$2.code = ERR_OPTIMIZE_DEPS_PROCESSING_ERROR;
- throw err$2;
-}
-function throwOutdatedRequest(id) {
- const err$2 = /* @__PURE__ */ new Error(`There is a new version of the pre-bundle for "${id}", a page reload is going to ask for it.`);
- err$2.code = ERR_OUTDATED_OPTIMIZED_DEP;
- throw err$2;
-}
-function throwFileNotFoundInOptimizedDep(id) {
- const err$2 = /* @__PURE__ */ new Error(`The file does not exist at "${id}" which is in the optimize deps directory. The dependency might be incompatible with the dep optimizer. Try adding it to \`optimizeDeps.exclude\`.`);
- err$2.code = ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR;
- throw err$2;
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/dotenv@17.2.3/node_modules/dotenv/package.json
-var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = {
- "name": "dotenv",
- "version": "17.2.3",
- "description": "Loads environment variables from .env file",
- "main": "lib/main.js",
- "types": "lib/main.d.ts",
- "exports": {
- ".": {
- "types": "./lib/main.d.ts",
- "require": "./lib/main.js",
- "default": "./lib/main.js"
- },
- "./config": "./config.js",
- "./config.js": "./config.js",
- "./lib/env-options": "./lib/env-options.js",
- "./lib/env-options.js": "./lib/env-options.js",
- "./lib/cli-options": "./lib/cli-options.js",
- "./lib/cli-options.js": "./lib/cli-options.js",
- "./package.json": "./package.json"
- },
- "scripts": {
- "dts-check": "tsc --project tests/types/tsconfig.json",
- "lint": "standard",
- "pretest": "npm run lint && npm run dts-check",
- "test": "tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000",
- "test:coverage": "tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",
- "prerelease": "npm test",
- "release": "standard-version"
- },
- "repository": {
- "type": "git",
- "url": "git://github.com/motdotla/dotenv.git"
- },
- "homepage": "https://github.com/motdotla/dotenv#readme",
- "funding": "https://dotenvx.com",
- "keywords": [
- "dotenv",
- "env",
- ".env",
- "environment",
- "variables",
- "config",
- "settings"
- ],
- "readmeFilename": "README.md",
- "license": "BSD-2-Clause",
- "devDependencies": {
- "@types/node": "^18.11.3",
- "decache": "^4.6.2",
- "sinon": "^14.0.1",
- "standard": "^17.0.0",
- "standard-version": "^9.5.0",
- "tap": "^19.2.0",
- "typescript": "^4.8.4"
- },
- "engines": { "node": ">=12" },
- "browser": { "fs": false }
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/dotenv@17.2.3/node_modules/dotenv/lib/main.js
-var require_main$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const fs$10 = __require("fs");
- const path$10 = __require("path");
- const os$3 = __require("os");
- const crypto$2 = __require("crypto");
- const version = require_package().version;
- const TIPS = [
- "🔐 encrypt with Dotenvx: https://dotenvx.com",
- "🔐 prevent committing .env to code: https://dotenvx.com/precommit",
- "🔐 prevent building .env in docker: https://dotenvx.com/prebuild",
- "📡 add observability to secrets: https://dotenvx.com/ops",
- "👥 sync secrets across teammates & machines: https://dotenvx.com/ops",
- "🗂️ backup and recover secrets: https://dotenvx.com/ops",
- "✅ audit secrets and track compliance: https://dotenvx.com/ops",
- "🔄 add secrets lifecycle management: https://dotenvx.com/ops",
- "🔑 add access controls to secrets: https://dotenvx.com/ops",
- "🛠️ run anywhere with `dotenvx run -- yourcommand`",
- "⚙️ specify custom .env file path with { path: '/custom/path/.env' }",
- "⚙️ enable debug logging with { debug: true }",
- "⚙️ override existing env vars with { override: true }",
- "⚙️ suppress all logs with { quiet: true }",
- "⚙️ write to custom object with { processEnv: myObject }",
- "⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"
- ];
- function _getRandomTip() {
- return TIPS[Math.floor(Math.random() * TIPS.length)];
- }
- function parseBoolean(value$1) {
- if (typeof value$1 === "string") return ![
- "false",
- "0",
- "no",
- "off",
- ""
- ].includes(value$1.toLowerCase());
- return Boolean(value$1);
- }
- function supportsAnsi() {
- return process.stdout.isTTY;
- }
- function dim(text) {
- return supportsAnsi() ? `\x1b[2m${text}\x1b[0m` : text;
- }
- const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
- function parse$12(src) {
- const obj = {};
- let lines = src.toString();
- lines = lines.replace(/\r\n?/gm, "\n");
- let match;
- while ((match = LINE.exec(lines)) != null) {
- const key = match[1];
- let value$1 = match[2] || "";
- value$1 = value$1.trim();
- const maybeQuote = value$1[0];
- value$1 = value$1.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
- if (maybeQuote === "\"") {
- value$1 = value$1.replace(/\\n/g, "\n");
- value$1 = value$1.replace(/\\r/g, "\r");
- }
- obj[key] = value$1;
- }
- return obj;
- }
- function _parseVault(options$1) {
- options$1 = options$1 || {};
- const vaultPath = _vaultPath(options$1);
- options$1.path = vaultPath;
- const result = DotenvModule.configDotenv(options$1);
- if (!result.parsed) {
- const err$2 = /* @__PURE__ */ new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
- err$2.code = "MISSING_DATA";
- throw err$2;
- }
- const keys = _dotenvKey(options$1).split(",");
- const length = keys.length;
- let decrypted;
- for (let i$1 = 0; i$1 < length; i$1++) try {
- const attrs = _instructions(result, keys[i$1].trim());
- decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
- break;
- } catch (error$1) {
- if (i$1 + 1 >= length) throw error$1;
- }
- return DotenvModule.parse(decrypted);
- }
- function _warn(message) {
- console.error(`[dotenv@${version}][WARN] ${message}`);
- }
- function _debug(message) {
- console.log(`[dotenv@${version}][DEBUG] ${message}`);
- }
- function _log(message) {
- console.log(`[dotenv@${version}] ${message}`);
- }
- function _dotenvKey(options$1) {
- if (options$1 && options$1.DOTENV_KEY && options$1.DOTENV_KEY.length > 0) return options$1.DOTENV_KEY;
- if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) return process.env.DOTENV_KEY;
- return "";
- }
- function _instructions(result, dotenvKey) {
- let uri;
- try {
- uri = new URL(dotenvKey);
- } catch (error$1) {
- if (error$1.code === "ERR_INVALID_URL") {
- const err$2 = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
- err$2.code = "INVALID_DOTENV_KEY";
- throw err$2;
- }
- throw error$1;
- }
- const key = uri.password;
- if (!key) {
- const err$2 = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing key part");
- err$2.code = "INVALID_DOTENV_KEY";
- throw err$2;
- }
- const environment = uri.searchParams.get("environment");
- if (!environment) {
- const err$2 = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing environment part");
- err$2.code = "INVALID_DOTENV_KEY";
- throw err$2;
- }
- const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
- const ciphertext = result.parsed[environmentKey];
- if (!ciphertext) {
- const err$2 = /* @__PURE__ */ new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
- err$2.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
- throw err$2;
- }
- return {
- ciphertext,
- key
- };
- }
- function _vaultPath(options$1) {
- let possibleVaultPath = null;
- if (options$1 && options$1.path && options$1.path.length > 0) if (Array.isArray(options$1.path)) {
- for (const filepath of options$1.path) if (fs$10.existsSync(filepath)) possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
- } else possibleVaultPath = options$1.path.endsWith(".vault") ? options$1.path : `${options$1.path}.vault`;
- else possibleVaultPath = path$10.resolve(process.cwd(), ".env.vault");
- if (fs$10.existsSync(possibleVaultPath)) return possibleVaultPath;
- return null;
- }
- function _resolveHome(envPath) {
- return envPath[0] === "~" ? path$10.join(os$3.homedir(), envPath.slice(1)) : envPath;
- }
- function _configVault(options$1) {
- const debug$18 = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || options$1 && options$1.debug);
- const quiet = parseBoolean(process.env.DOTENV_CONFIG_QUIET || options$1 && options$1.quiet);
- if (debug$18 || !quiet) _log("Loading env from encrypted .env.vault");
- const parsed = DotenvModule._parseVault(options$1);
- let processEnv = process.env;
- if (options$1 && options$1.processEnv != null) processEnv = options$1.processEnv;
- DotenvModule.populate(processEnv, parsed, options$1);
- return { parsed };
- }
- function configDotenv(options$1) {
- const dotenvPath = path$10.resolve(process.cwd(), ".env");
- let encoding = "utf8";
- let processEnv = process.env;
- if (options$1 && options$1.processEnv != null) processEnv = options$1.processEnv;
- let debug$18 = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || options$1 && options$1.debug);
- let quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || options$1 && options$1.quiet);
- if (options$1 && options$1.encoding) encoding = options$1.encoding;
- else if (debug$18) _debug("No encoding is specified. UTF-8 is used by default");
- let optionPaths = [dotenvPath];
- if (options$1 && options$1.path) if (!Array.isArray(options$1.path)) optionPaths = [_resolveHome(options$1.path)];
- else {
- optionPaths = [];
- for (const filepath of options$1.path) optionPaths.push(_resolveHome(filepath));
- }
- let lastError;
- const parsedAll = {};
- for (const path$13 of optionPaths) try {
- const parsed = DotenvModule.parse(fs$10.readFileSync(path$13, { encoding }));
- DotenvModule.populate(parsedAll, parsed, options$1);
- } catch (e$1) {
- if (debug$18) _debug(`Failed to load ${path$13} ${e$1.message}`);
- lastError = e$1;
- }
- const populated = DotenvModule.populate(processEnv, parsedAll, options$1);
- debug$18 = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug$18);
- quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet);
- if (debug$18 || !quiet) {
- const keysCount = Object.keys(populated).length;
- const shortPaths = [];
- for (const filePath of optionPaths) try {
- const relative$3 = path$10.relative(process.cwd(), filePath);
- shortPaths.push(relative$3);
- } catch (e$1) {
- if (debug$18) _debug(`Failed to load ${filePath} ${e$1.message}`);
- lastError = e$1;
- }
- _log(`injecting env (${keysCount}) from ${shortPaths.join(",")} ${dim(`-- tip: ${_getRandomTip()}`)}`);
- }
- if (lastError) return {
- parsed: parsedAll,
- error: lastError
- };
- else return { parsed: parsedAll };
- }
- function config(options$1) {
- if (_dotenvKey(options$1).length === 0) return DotenvModule.configDotenv(options$1);
- const vaultPath = _vaultPath(options$1);
- if (!vaultPath) {
- _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
- return DotenvModule.configDotenv(options$1);
- }
- return DotenvModule._configVault(options$1);
- }
- function decrypt(encrypted, keyStr) {
- const key = Buffer.from(keyStr.slice(-64), "hex");
- let ciphertext = Buffer.from(encrypted, "base64");
- const nonce = ciphertext.subarray(0, 12);
- const authTag = ciphertext.subarray(-16);
- ciphertext = ciphertext.subarray(12, -16);
- try {
- const aesgcm = crypto$2.createDecipheriv("aes-256-gcm", key, nonce);
- aesgcm.setAuthTag(authTag);
- return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
- } catch (error$1) {
- const isRange = error$1 instanceof RangeError;
- const invalidKeyLength = error$1.message === "Invalid key length";
- const decryptionFailed = error$1.message === "Unsupported state or unable to authenticate data";
- if (isRange || invalidKeyLength) {
- const err$2 = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
- err$2.code = "INVALID_DOTENV_KEY";
- throw err$2;
- } else if (decryptionFailed) {
- const err$2 = /* @__PURE__ */ new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
- err$2.code = "DECRYPTION_FAILED";
- throw err$2;
- } else throw error$1;
- }
- }
- function populate(processEnv, parsed, options$1 = {}) {
- const debug$18 = Boolean(options$1 && options$1.debug);
- const override = Boolean(options$1 && options$1.override);
- const populated = {};
- if (typeof parsed !== "object") {
- const err$2 = /* @__PURE__ */ new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
- err$2.code = "OBJECT_REQUIRED";
- throw err$2;
- }
- for (const key of Object.keys(parsed)) if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
- if (override === true) {
- processEnv[key] = parsed[key];
- populated[key] = parsed[key];
- }
- if (debug$18) if (override === true) _debug(`"${key}" is already defined and WAS overwritten`);
- else _debug(`"${key}" is already defined and was NOT overwritten`);
- } else {
- processEnv[key] = parsed[key];
- populated[key] = parsed[key];
- }
- return populated;
- }
- const DotenvModule = {
- configDotenv,
- _configVault,
- _parseVault,
- config,
- decrypt,
- parse: parse$12,
- populate
- };
- module.exports.configDotenv = DotenvModule.configDotenv;
- module.exports._configVault = DotenvModule._configVault;
- module.exports._parseVault = DotenvModule._parseVault;
- module.exports.config = DotenvModule.config;
- module.exports.decrypt = DotenvModule.decrypt;
- module.exports.parse = DotenvModule.parse;
- module.exports.populate = DotenvModule.populate;
- module.exports = DotenvModule;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/dotenv-expand@12.0.3_patch_hash=49330a663821151418e003e822a82a6a61d2f0f8a6e3cab00c1c94815a112889/node_modules/dotenv-expand/lib/main.js
-var require_main = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- function _resolveEscapeSequences(value$1) {
- return value$1.replace(/\\\$/g, "$");
- }
- function expandValue(value$1, processEnv, runningParsed) {
- const env$1 = {
- ...runningParsed,
- ...processEnv
- };
- const regex = /(?<!\\)\${([^{}]+)}|(?<!\\)\$([A-Za-z_][A-Za-z0-9_]*)/g;
- let result = value$1;
- let match;
- const seen$1 = /* @__PURE__ */ new Set();
- while ((match = regex.exec(result)) !== null) {
- seen$1.add(result);
- const [template, bracedExpression, unbracedExpression] = match;
- const expression = bracedExpression || unbracedExpression;
- const opMatch = expression.match(/(:\+|\+|:-|-)/);
- const splitter = opMatch ? opMatch[0] : null;
- const r$1 = expression.split(splitter);
- let defaultValue;
- let value$2;
- const key = r$1.shift();
- if ([":+", "+"].includes(splitter)) {
- defaultValue = env$1[key] ? r$1.join(splitter) : "";
- value$2 = null;
- } else {
- defaultValue = r$1.join(splitter);
- value$2 = env$1[key];
- }
- if (value$2) if (seen$1.has(value$2)) result = result.replace(template, defaultValue);
- else result = result.replace(template, value$2);
- else result = result.replace(template, defaultValue);
- if (result === runningParsed[key]) break;
- regex.lastIndex = 0;
- }
- return result;
- }
- function expand$3(options$1) {
- let processEnv = process.env;
- if (options$1 && options$1.processEnv != null) processEnv = options$1.processEnv;
- for (const key in options$1.parsed) {
- let value$1 = options$1.parsed[key];
- if (processEnv[key] && processEnv[key] !== value$1) value$1 = processEnv[key];
- else value$1 = expandValue(value$1, processEnv, options$1.parsed);
- options$1.parsed[key] = _resolveEscapeSequences(value$1);
- }
- for (const processKey in options$1.parsed) processEnv[processKey] = options$1.parsed[processKey];
- return options$1;
- }
- module.exports.expand = expand$3;
-}));
-
-//#endregion
-//#region src/node/env.ts
-var import_main = require_main$1();
-var import_main$1 = require_main();
-const debug$14 = createDebugger("vite:env");
-function getEnvFilesForMode(mode, envDir) {
- if (envDir !== false) return [
- `.env`,
- `.env.local`,
- `.env.${mode}`,
- `.env.${mode}.local`
- ].map((file) => normalizePath(path.join(envDir, file)));
- return [];
-}
-function loadEnv(mode, envDir, prefixes = "VITE_") {
- const start = performance.now();
- const getTime = () => `${(performance.now() - start).toFixed(2)}ms`;
- if (mode === "local") throw new Error("\"local\" cannot be used as a mode name because it conflicts with the .local postfix for .env files.");
- prefixes = arraify(prefixes);
- const env$1 = {};
- const envFiles = getEnvFilesForMode(mode, envDir);
- debug$14?.(`loading env files: %O`, envFiles);
- const parsed = Object.fromEntries(envFiles.flatMap((filePath) => {
- if (!tryStatSync(filePath)?.isFile()) return [];
- return Object.entries((0, import_main.parse)(fs.readFileSync(filePath)));
- }));
- debug$14?.(`env files loaded in ${getTime()}`);
- if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === void 0) process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV;
- if (parsed.BROWSER && process.env.BROWSER === void 0) process.env.BROWSER = parsed.BROWSER;
- if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === void 0) process.env.BROWSER_ARGS = parsed.BROWSER_ARGS;
- (0, import_main$1.expand)({
- parsed,
- processEnv: { ...process.env }
- });
- for (const [key, value$1] of Object.entries(parsed)) if (prefixes.some((prefix) => key.startsWith(prefix))) env$1[key] = value$1;
- for (const key in process.env) if (prefixes.some((prefix) => key.startsWith(prefix))) env$1[key] = process.env[key];
- debug$14?.(`using resolved env: %O`, env$1);
- return env$1;
-}
-function resolveEnvPrefix({ envPrefix = "VITE_" }) {
- envPrefix = arraify(envPrefix);
- if (envPrefix.includes("")) throw new Error(`envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`);
- return envPrefix;
-}
-
-//#endregion
-//#region src/node/deprecations.ts
-var import_picocolors$28 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const docsURL = "https://vite.dev";
-const deprecationCode = {
- removePluginHookSsrArgument: "changes/this-environment-in-hooks",
- removePluginHookHandleHotUpdate: "changes/hotupdate-hook",
- removeServerModuleGraph: "changes/per-environment-apis",
- removeServerReloadModule: "changes/per-environment-apis",
- removeServerPluginContainer: "changes/per-environment-apis",
- removeServerHot: "changes/per-environment-apis",
- removeServerTransformRequest: "changes/per-environment-apis",
- removeServerWarmupRequest: "changes/per-environment-apis",
- removeSsrLoadModule: "changes/ssr-using-modulerunner"
-};
-const deprecationMessages = {
- removePluginHookSsrArgument: "Plugin hook `options.ssr` is replaced with `this.environment.config.consumer === 'server'`.",
- removePluginHookHandleHotUpdate: "Plugin hook `handleHotUpdate()` is replaced with `hotUpdate()`.",
- removeServerModuleGraph: "The `server.moduleGraph` is replaced with `this.environment.moduleGraph`.",
- removeServerReloadModule: "The `server.reloadModule` is replaced with `environment.reloadModule`.",
- removeServerPluginContainer: "The `server.pluginContainer` is replaced with `this.environment.pluginContainer`.",
- removeServerHot: "The `server.hot` is replaced with `this.environment.hot`.",
- removeServerTransformRequest: "The `server.transformRequest` is replaced with `this.environment.transformRequest`.",
- removeServerWarmupRequest: "The `server.warmupRequest` is replaced with `this.environment.warmupRequest`.",
- removeSsrLoadModule: "The `server.ssrLoadModule` is replaced with Environment Runner."
-};
-let _ignoreDeprecationWarnings = false;
-function isFutureDeprecationEnabled(config$2, type) {
- return !!config$2.future?.[type];
-}
-/**
-* Warn about future deprecations.
-*/
-function warnFutureDeprecation(config$2, type, extraMessage, stacktrace = true) {
- if (_ignoreDeprecationWarnings || !config$2.future || config$2.future[type] !== "warn") return;
- let msg = `[vite future] ${deprecationMessages[type]}`;
- if (extraMessage) msg += ` ${extraMessage}`;
- msg = import_picocolors$28.default.yellow(msg);
- const docs = `${docsURL}/changes/${deprecationCode[type].toLowerCase()}`;
- msg += import_picocolors$28.default.gray(`\n ${stacktrace ? "├" : "└"}─── `) + import_picocolors$28.default.underline(docs) + "\n";
- if (stacktrace) {
- const stack = (/* @__PURE__ */ new Error()).stack;
- if (stack) {
- let stacks = stack.split("\n").slice(3).filter((i$1) => !i$1.includes("/node_modules/vite/dist/"));
- if (stacks.length === 0) stacks.push("No stack trace found.");
- stacks = stacks.map((i$1, idx) => ` ${idx === stacks.length - 1 ? "└" : "│"} ${i$1.trim()}`);
- msg += import_picocolors$28.default.dim(stacks.join("\n")) + "\n";
- }
- }
- config$2.logger.warnOnce(msg);
-}
-function ignoreDeprecationWarnings(fn) {
- const before = _ignoreDeprecationWarnings;
- _ignoreDeprecationWarnings = true;
- const ret = fn();
- _ignoreDeprecationWarnings = before;
- return ret;
-}
-
-//#endregion
-//#region src/node/server/middlewares/error.ts
-var import_picocolors$27 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-function prepareError(err$2) {
- return {
- message: stripVTControlCharacters(err$2.message),
- stack: stripVTControlCharacters(cleanStack(err$2.stack || "")),
- id: err$2.id,
- frame: stripVTControlCharacters(err$2.frame || ""),
- plugin: err$2.plugin,
- pluginCode: err$2.pluginCode?.toString(),
- loc: err$2.loc
- };
-}
-function buildErrorMessage(err$2, args = [], includeStack = true) {
- if (err$2.plugin) args.push(` Plugin: ${import_picocolors$27.default.magenta(err$2.plugin)}`);
- const loc = err$2.loc ? `:${err$2.loc.line}:${err$2.loc.column}` : "";
- if (err$2.id) args.push(` File: ${import_picocolors$27.default.cyan(err$2.id)}${loc}`);
- if (err$2.frame) args.push(import_picocolors$27.default.yellow(pad$1(err$2.frame)));
- if (includeStack && err$2.stack) args.push(pad$1(cleanStack(err$2.stack)));
- return args.join("\n");
-}
-function cleanStack(stack) {
- return stack.split(/\n/).filter((l) => /^\s*at/.test(l)).join("\n");
-}
-function logError(server, err$2) {
- const msg = buildErrorMessage(err$2, [import_picocolors$27.default.red(`Internal server error: ${err$2.message}`)]);
- server.config.logger.error(msg, {
- clear: true,
- timestamp: true,
- error: err$2
- });
- server.environments.client.hot.send({
- type: "error",
- err: prepareError(err$2)
- });
-}
-function errorMiddleware(server, allowNext = false) {
- return function viteErrorMiddleware(err$2, _req, res, next) {
- logError(server, err$2);
- if (allowNext) next();
- else {
- res.statusCode = 500;
- res.end(`
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <title>Error</title>
- <script type="module">
- const error = ${JSON.stringify(prepareError(err$2)).replace(/</g, "\\u003c")}
- try {
- const { ErrorOverlay } = await import(${JSON.stringify(path.posix.join(server.config.base, CLIENT_PUBLIC_PATH))})
- document.body.appendChild(new ErrorOverlay(error))
- } catch {
- const h = (tag, text) => {
- const el = document.createElement(tag)
- el.textContent = text
- return el
- }
- document.body.appendChild(h('h1', 'Internal Server Error'))
- document.body.appendChild(h('h2', error.message))
- document.body.appendChild(h('pre', error.stack))
- document.body.appendChild(h('p', '(Error overlay failed to load)'))
- }
- <\/script>
- </head>
- <body>
- </body>
- </html>
- `);
- }
- };
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/encodeurl@1.0.2/node_modules/encodeurl/index.js
-/*!
-* encodeurl
-* Copyright(c) 2016 Douglas Christopher Wilson
-* MIT Licensed
-*/
-var require_encodeurl = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /**
- * Module exports.
- * @public
- */
- module.exports = encodeUrl$1;
- /**
- * RegExp to match non-URL code points, *after* encoding (i.e. not including "%")
- * and including invalid escape sequences.
- * @private
- */
- var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g;
- /**
- * RegExp to match unmatched surrogate pair.
- * @private
- */
- var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g;
- /**
- * String to replace unmatched surrogate pair with.
- * @private
- */
- var UNMATCHED_SURROGATE_PAIR_REPLACE = "$1�$2";
- /**
- * Encode a URL to a percent-encoded form, excluding already-encoded sequences.
- *
- * This function will take an already-encoded URL and encode all the non-URL
- * code points. This function will not encode the "%" character unless it is
- * not part of a valid sequence (`%20` will be left as-is, but `%foo` will
- * be encoded as `%25foo`).
- *
- * This encode is meant to be "safe" and does not throw errors. It will try as
- * hard as it can to properly encode the given URL, including replacing any raw,
- * unpaired surrogate pairs with the Unicode replacement character prior to
- * encoding.
- *
- * @param {string} url
- * @return {string}
- * @public
- */
- function encodeUrl$1(url$3) {
- return String(url$3).replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE).replace(ENCODE_CHARS_REGEXP, encodeURI);
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/escape-html@1.0.3/node_modules/escape-html/index.js
-/*!
-* escape-html
-* Copyright(c) 2012-2013 TJ Holowaychuk
-* Copyright(c) 2015 Andreas Lubbe
-* Copyright(c) 2015 Tiancheng "Timothy" Gu
-* MIT Licensed
-*/
-var require_escape_html = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /**
- * Module variables.
- * @private
- */
- var matchHtmlRegExp = /["'&<>]/;
- /**
- * Module exports.
- * @public
- */
- module.exports = escapeHtml$3;
- /**
- * Escape special characters in the given string of html.
- *
- * @param {string} string The string to escape for inserting into HTML
- * @return {string}
- * @public
- */
- function escapeHtml$3(string) {
- var str = "" + string;
- var match = matchHtmlRegExp.exec(str);
- if (!match) return str;
- var escape$2;
- var html = "";
- var index = 0;
- var lastIndex = 0;
- for (index = match.index; index < str.length; index++) {
- switch (str.charCodeAt(index)) {
- case 34:
- escape$2 = "&quot;";
- break;
- case 38:
- escape$2 = "&amp;";
- break;
- case 39:
- escape$2 = "&#39;";
- break;
- case 60:
- escape$2 = "&lt;";
- break;
- case 62:
- escape$2 = "&gt;";
- break;
- default: continue;
- }
- if (lastIndex !== index) html += str.substring(lastIndex, index);
- lastIndex = index + 1;
- html += escape$2;
- }
- return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/ee-first@1.1.1/node_modules/ee-first/index.js
-/*!
-* ee-first
-* Copyright(c) 2014 Jonathan Ong
-* MIT Licensed
-*/
-var require_ee_first = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /**
- * Module exports.
- * @public
- */
- module.exports = first$1;
- /**
- * Get the first event in a set of event emitters and event pairs.
- *
- * @param {array} stuff
- * @param {function} done
- * @public
- */
- function first$1(stuff, done) {
- if (!Array.isArray(stuff)) throw new TypeError("arg must be an array of [ee, events...] arrays");
- var cleanups = [];
- for (var i$1 = 0; i$1 < stuff.length; i$1++) {
- var arr = stuff[i$1];
- if (!Array.isArray(arr) || arr.length < 2) throw new TypeError("each array member must be [ee, events...]");
- var ee = arr[0];
- for (var j = 1; j < arr.length; j++) {
- var event = arr[j];
- var fn = listener(event, callback);
- ee.on(event, fn);
- cleanups.push({
- ee,
- event,
- fn
- });
- }
- }
- function callback() {
- cleanup();
- done.apply(null, arguments);
- }
- function cleanup() {
- var x;
- for (var i$2 = 0; i$2 < cleanups.length; i$2++) {
- x = cleanups[i$2];
- x.ee.removeListener(x.event, x.fn);
- }
- }
- function thunk(fn$1) {
- done = fn$1;
- }
- thunk.cancel = cleanup;
- return thunk;
- }
- /**
- * Create the event listener.
- * @private
- */
- function listener(event, done) {
- return function onevent(arg1) {
- var args = new Array(arguments.length);
- var ee = this;
- var err$2 = event === "error" ? arg1 : null;
- for (var i$1 = 0; i$1 < args.length; i$1++) args[i$1] = arguments[i$1];
- done(err$2, ee, event, args);
- };
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/on-finished@2.3.0/node_modules/on-finished/index.js
-/*!
-* on-finished
-* Copyright(c) 2013 Jonathan Ong
-* Copyright(c) 2014 Douglas Christopher Wilson
-* MIT Licensed
-*/
-var require_on_finished = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /**
- * Module exports.
- * @public
- */
- module.exports = onFinished$1;
- module.exports.isFinished = isFinished$1;
- /**
- * Module dependencies.
- * @private
- */
- var first = require_ee_first();
- /**
- * Variables.
- * @private
- */
- /* istanbul ignore next */
- var defer$2 = typeof setImmediate === "function" ? setImmediate : function(fn) {
- process.nextTick(fn.bind.apply(fn, arguments));
- };
- /**
- * Invoke callback when the response has finished, useful for
- * cleaning up resources afterwards.
- *
- * @param {object} msg
- * @param {function} listener
- * @return {object}
- * @public
- */
- function onFinished$1(msg, listener$1) {
- if (isFinished$1(msg) !== false) {
- defer$2(listener$1, null, msg);
- return msg;
- }
- attachListener(msg, listener$1);
- return msg;
- }
- /**
- * Determine if message is already finished.
- *
- * @param {object} msg
- * @return {boolean}
- * @public
- */
- function isFinished$1(msg) {
- var socket = msg.socket;
- if (typeof msg.finished === "boolean") return Boolean(msg.finished || socket && !socket.writable);
- if (typeof msg.complete === "boolean") return Boolean(msg.upgrade || !socket || !socket.readable || msg.complete && !msg.readable);
- }
- /**
- * Attach a finished listener to the message.
- *
- * @param {object} msg
- * @param {function} callback
- * @private
- */
- function attachFinishedListener(msg, callback) {
- var eeMsg;
- var eeSocket;
- var finished = false;
- function onFinish(error$1) {
- eeMsg.cancel();
- eeSocket.cancel();
- finished = true;
- callback(error$1);
- }
- eeMsg = eeSocket = first([[
- msg,
- "end",
- "finish"
- ]], onFinish);
- function onSocket(socket) {
- msg.removeListener("socket", onSocket);
- if (finished) return;
- if (eeMsg !== eeSocket) return;
- eeSocket = first([[
- socket,
- "error",
- "close"
- ]], onFinish);
- }
- if (msg.socket) {
- onSocket(msg.socket);
- return;
- }
- msg.on("socket", onSocket);
- if (msg.socket === void 0) patchAssignSocket(msg, onSocket);
- }
- /**
- * Attach the listener to the message.
- *
- * @param {object} msg
- * @return {function}
- * @private
- */
- function attachListener(msg, listener$1) {
- var attached = msg.__onFinished;
- if (!attached || !attached.queue) {
- attached = msg.__onFinished = createListener(msg);
- attachFinishedListener(msg, attached);
- }
- attached.queue.push(listener$1);
- }
- /**
- * Create listener on message.
- *
- * @param {object} msg
- * @return {function}
- * @private
- */
- function createListener(msg) {
- function listener$1(err$2) {
- if (msg.__onFinished === listener$1) msg.__onFinished = null;
- if (!listener$1.queue) return;
- var queue = listener$1.queue;
- listener$1.queue = null;
- for (var i$1 = 0; i$1 < queue.length; i$1++) queue[i$1](err$2, msg);
- }
- listener$1.queue = [];
- return listener$1;
- }
- /**
- * Patch ServerResponse.prototype.assignSocket for node.js 0.8.
- *
- * @param {ServerResponse} res
- * @param {function} callback
- * @private
- */
- function patchAssignSocket(res, callback) {
- var assignSocket = res.assignSocket;
- if (typeof assignSocket !== "function") return;
- res.assignSocket = function _assignSocket(socket) {
- assignSocket.call(this, socket);
- callback(socket);
- };
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/parseurl@1.3.3/node_modules/parseurl/index.js
-/*!
-* parseurl
-* Copyright(c) 2014 Jonathan Ong
-* Copyright(c) 2014-2017 Douglas Christopher Wilson
-* MIT Licensed
-*/
-var require_parseurl = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /**
- * Module dependencies.
- * @private
- */
- var url$1 = __require("url");
- var parse$10 = url$1.parse;
- var Url = url$1.Url;
- /**
- * Module exports.
- * @public
- */
- module.exports = parseurl;
- module.exports.original = originalurl;
- /**
- * Parse the `req` url with memoization.
- *
- * @param {ServerRequest} req
- * @return {Object}
- * @public
- */
- function parseurl(req$4) {
- var url$3 = req$4.url;
- if (url$3 === void 0) return;
- var parsed = req$4._parsedUrl;
- if (fresh(url$3, parsed)) return parsed;
- parsed = fastparse(url$3);
- parsed._raw = url$3;
- return req$4._parsedUrl = parsed;
- }
- /**
- * Parse the `req` original url with fallback and memoization.
- *
- * @param {ServerRequest} req
- * @return {Object}
- * @public
- */
- function originalurl(req$4) {
- var url$3 = req$4.originalUrl;
- if (typeof url$3 !== "string") return parseurl(req$4);
- var parsed = req$4._parsedOriginalUrl;
- if (fresh(url$3, parsed)) return parsed;
- parsed = fastparse(url$3);
- parsed._raw = url$3;
- return req$4._parsedOriginalUrl = parsed;
- }
- /**
- * Parse the `str` url with fast-path short-cut.
- *
- * @param {string} str
- * @return {Object}
- * @private
- */
- function fastparse(str) {
- if (typeof str !== "string" || str.charCodeAt(0) !== 47) return parse$10(str);
- var pathname = str;
- var query = null;
- var search = null;
- for (var i$1 = 1; i$1 < str.length; i$1++) switch (str.charCodeAt(i$1)) {
- case 63:
- if (search === null) {
- pathname = str.substring(0, i$1);
- query = str.substring(i$1 + 1);
- search = str.substring(i$1);
- }
- break;
- case 9:
- case 10:
- case 12:
- case 13:
- case 32:
- case 35:
- case 160:
- case 65279: return parse$10(str);
- }
- var url$3 = Url !== void 0 ? new Url() : {};
- url$3.path = str;
- url$3.href = str;
- url$3.pathname = pathname;
- if (search !== null) {
- url$3.query = query;
- url$3.search = search;
- }
- return url$3;
- }
- /**
- * Determine if parsed is still fresh for url.
- *
- * @param {string} url
- * @param {object} parsedUrl
- * @return {boolean}
- * @private
- */
- function fresh(url$3, parsedUrl) {
- return typeof parsedUrl === "object" && parsedUrl !== null && (Url === void 0 || parsedUrl instanceof Url) && parsedUrl._raw === url$3;
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/statuses@1.5.0/node_modules/statuses/codes.json
-var require_codes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = {
- "100": "Continue",
- "101": "Switching Protocols",
- "102": "Processing",
- "103": "Early Hints",
- "200": "OK",
- "201": "Created",
- "202": "Accepted",
- "203": "Non-Authoritative Information",
- "204": "No Content",
- "205": "Reset Content",
- "206": "Partial Content",
- "207": "Multi-Status",
- "208": "Already Reported",
- "226": "IM Used",
- "300": "Multiple Choices",
- "301": "Moved Permanently",
- "302": "Found",
- "303": "See Other",
- "304": "Not Modified",
- "305": "Use Proxy",
- "306": "(Unused)",
- "307": "Temporary Redirect",
- "308": "Permanent Redirect",
- "400": "Bad Request",
- "401": "Unauthorized",
- "402": "Payment Required",
- "403": "Forbidden",
- "404": "Not Found",
- "405": "Method Not Allowed",
- "406": "Not Acceptable",
- "407": "Proxy Authentication Required",
- "408": "Request Timeout",
- "409": "Conflict",
- "410": "Gone",
- "411": "Length Required",
- "412": "Precondition Failed",
- "413": "Payload Too Large",
- "414": "URI Too Long",
- "415": "Unsupported Media Type",
- "416": "Range Not Satisfiable",
- "417": "Expectation Failed",
- "418": "I'm a teapot",
- "421": "Misdirected Request",
- "422": "Unprocessable Entity",
- "423": "Locked",
- "424": "Failed Dependency",
- "425": "Unordered Collection",
- "426": "Upgrade Required",
- "428": "Precondition Required",
- "429": "Too Many Requests",
- "431": "Request Header Fields Too Large",
- "451": "Unavailable For Legal Reasons",
- "500": "Internal Server Error",
- "501": "Not Implemented",
- "502": "Bad Gateway",
- "503": "Service Unavailable",
- "504": "Gateway Timeout",
- "505": "HTTP Version Not Supported",
- "506": "Variant Also Negotiates",
- "507": "Insufficient Storage",
- "508": "Loop Detected",
- "509": "Bandwidth Limit Exceeded",
- "510": "Not Extended",
- "511": "Network Authentication Required"
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/statuses@1.5.0/node_modules/statuses/index.js
-/*!
-* statuses
-* Copyright(c) 2014 Jonathan Ong
-* Copyright(c) 2016 Douglas Christopher Wilson
-* MIT Licensed
-*/
-var require_statuses = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /**
- * Module dependencies.
- * @private
- */
- var codes = require_codes();
- /**
- * Module exports.
- * @public
- */
- module.exports = status;
- status.STATUS_CODES = codes;
- status.codes = populateStatusesMap(status, codes);
- status.redirect = {
- 300: true,
- 301: true,
- 302: true,
- 303: true,
- 305: true,
- 307: true,
- 308: true
- };
- status.empty = {
- 204: true,
- 205: true,
- 304: true
- };
- status.retry = {
- 502: true,
- 503: true,
- 504: true
- };
- /**
- * Populate the statuses map for given codes.
- * @private
- */
- function populateStatusesMap(statuses$1, codes$2) {
- var arr = [];
- Object.keys(codes$2).forEach(function forEachCode(code) {
- var message = codes$2[code];
- var status$1 = Number(code);
- statuses$1[status$1] = message;
- statuses$1[message] = status$1;
- statuses$1[message.toLowerCase()] = status$1;
- arr.push(status$1);
- });
- return arr;
- }
- /**
- * Get the status code.
- *
- * Given a number, this will throw if it is not a known status
- * code, otherwise the code will be returned. Given a string,
- * the string will be parsed for a number and return the code
- * if valid, otherwise will lookup the code assuming this is
- * the status message.
- *
- * @param {string|number} code
- * @returns {number}
- * @public
- */
- function status(code) {
- if (typeof code === "number") {
- if (!status[code]) throw new Error("invalid status code: " + code);
- return code;
- }
- if (typeof code !== "string") throw new TypeError("code must be a number or string");
- var n$2 = parseInt(code, 10);
- if (!isNaN(n$2)) {
- if (!status[n$2]) throw new Error("invalid status code: " + n$2);
- return n$2;
- }
- n$2 = status[code.toLowerCase()];
- if (!n$2) throw new Error("invalid status message: \"" + code + "\"");
- return n$2;
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/unpipe@1.0.0/node_modules/unpipe/index.js
-/*!
-* unpipe
-* Copyright(c) 2015 Douglas Christopher Wilson
-* MIT Licensed
-*/
-var require_unpipe = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /**
- * Module exports.
- * @public
- */
- module.exports = unpipe$1;
- /**
- * Determine if there are Node.js pipe-like data listeners.
- * @private
- */
- function hasPipeDataListeners(stream$2) {
- var listeners = stream$2.listeners("data");
- for (var i$1 = 0; i$1 < listeners.length; i$1++) if (listeners[i$1].name === "ondata") return true;
- return false;
- }
- /**
- * Unpipe a stream from all destinations.
- *
- * @param {object} stream
- * @public
- */
- function unpipe$1(stream$2) {
- if (!stream$2) throw new TypeError("argument stream is required");
- if (typeof stream$2.unpipe === "function") {
- stream$2.unpipe();
- return;
- }
- if (!hasPipeDataListeners(stream$2)) return;
- var listener$1;
- var listeners = stream$2.listeners("close");
- for (var i$1 = 0; i$1 < listeners.length; i$1++) {
- listener$1 = listeners[i$1];
- if (listener$1.name !== "cleanup" && listener$1.name !== "onclose") continue;
- listener$1.call(stream$2);
- }
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/finalhandler@1.1.2_ms@2.1.3/node_modules/finalhandler/index.js
-/*!
-* finalhandler
-* Copyright(c) 2014-2017 Douglas Christopher Wilson
-* MIT Licensed
-*/
-var require_finalhandler = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /**
- * Module dependencies.
- * @private
- */
- var debug$13 = (init_node(), __toCommonJS(node_exports))("finalhandler");
- var encodeUrl = require_encodeurl();
- var escapeHtml$2 = require_escape_html();
- var onFinished = require_on_finished();
- var parseUrl$2 = require_parseurl();
- var statuses = require_statuses();
- var unpipe = require_unpipe();
- /**
- * Module variables.
- * @private
- */
- var DOUBLE_SPACE_REGEXP = /\x20{2}/g;
- var NEWLINE_REGEXP = /\n/g;
- /* istanbul ignore next */
- var defer$1 = typeof setImmediate === "function" ? setImmediate : function(fn) {
- process.nextTick(fn.bind.apply(fn, arguments));
- };
- var isFinished = onFinished.isFinished;
- /**
- * Create a minimal HTML document.
- *
- * @param {string} message
- * @private
- */
- function createHtmlDocument(message) {
- return "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>" + escapeHtml$2(message).replace(NEWLINE_REGEXP, "<br>").replace(DOUBLE_SPACE_REGEXP, " &nbsp;") + "</pre>\n</body>\n</html>\n";
- }
- /**
- * Module exports.
- * @public
- */
- module.exports = finalhandler$1;
- /**
- * Create a function to handle the final response.
- *
- * @param {Request} req
- * @param {Response} res
- * @param {Object} [options]
- * @return {Function}
- * @public
- */
- function finalhandler$1(req$4, res, options$1) {
- var opts = options$1 || {};
- var env$1 = opts.env || process.env.NODE_ENV || "development";
- var onerror = opts.onerror;
- return function(err$2) {
- var headers;
- var msg;
- var status$1;
- if (!err$2 && headersSent(res)) {
- debug$13("cannot 404 after headers sent");
- return;
- }
- if (err$2) {
- status$1 = getErrorStatusCode(err$2);
- if (status$1 === void 0) status$1 = getResponseStatusCode(res);
- else headers = getErrorHeaders(err$2);
- msg = getErrorMessage(err$2, status$1, env$1);
- } else {
- status$1 = 404;
- msg = "Cannot " + req$4.method + " " + encodeUrl(getResourceName(req$4));
- }
- debug$13("default %s", status$1);
- if (err$2 && onerror) defer$1(onerror, err$2, req$4, res);
- if (headersSent(res)) {
- debug$13("cannot %d after headers sent", status$1);
- req$4.socket.destroy();
- return;
- }
- send$2(req$4, res, status$1, headers, msg);
- };
- }
- /**
- * Get headers from Error object.
- *
- * @param {Error} err
- * @return {object}
- * @private
- */
- function getErrorHeaders(err$2) {
- if (!err$2.headers || typeof err$2.headers !== "object") return;
- var headers = Object.create(null);
- var keys = Object.keys(err$2.headers);
- for (var i$1 = 0; i$1 < keys.length; i$1++) {
- var key = keys[i$1];
- headers[key] = err$2.headers[key];
- }
- return headers;
- }
- /**
- * Get message from Error object, fallback to status message.
- *
- * @param {Error} err
- * @param {number} status
- * @param {string} env
- * @return {string}
- * @private
- */
- function getErrorMessage(err$2, status$1, env$1) {
- var msg;
- if (env$1 !== "production") {
- msg = err$2.stack;
- if (!msg && typeof err$2.toString === "function") msg = err$2.toString();
- }
- return msg || statuses[status$1];
- }
- /**
- * Get status code from Error object.
- *
- * @param {Error} err
- * @return {number}
- * @private
- */
- function getErrorStatusCode(err$2) {
- if (typeof err$2.status === "number" && err$2.status >= 400 && err$2.status < 600) return err$2.status;
- if (typeof err$2.statusCode === "number" && err$2.statusCode >= 400 && err$2.statusCode < 600) return err$2.statusCode;
- }
- /**
- * Get resource name for the request.
- *
- * This is typically just the original pathname of the request
- * but will fallback to "resource" is that cannot be determined.
- *
- * @param {IncomingMessage} req
- * @return {string}
- * @private
- */
- function getResourceName(req$4) {
- try {
- return parseUrl$2.original(req$4).pathname;
- } catch (e$1) {
- return "resource";
- }
- }
- /**
- * Get status code from response.
- *
- * @param {OutgoingMessage} res
- * @return {number}
- * @private
- */
- function getResponseStatusCode(res) {
- var status$1 = res.statusCode;
- if (typeof status$1 !== "number" || status$1 < 400 || status$1 > 599) status$1 = 500;
- return status$1;
- }
- /**
- * Determine if the response headers have been sent.
- *
- * @param {object} res
- * @returns {boolean}
- * @private
- */
- function headersSent(res) {
- return typeof res.headersSent !== "boolean" ? Boolean(res._header) : res.headersSent;
- }
- /**
- * Send response.
- *
- * @param {IncomingMessage} req
- * @param {OutgoingMessage} res
- * @param {number} status
- * @param {object} headers
- * @param {string} message
- * @private
- */
- function send$2(req$4, res, status$1, headers, message) {
- function write() {
- var body = createHtmlDocument(message);
- res.statusCode = status$1;
- res.statusMessage = statuses[status$1];
- setHeaders(res, headers);
- res.setHeader("Content-Security-Policy", "default-src 'none'");
- res.setHeader("X-Content-Type-Options", "nosniff");
- res.setHeader("Content-Type", "text/html; charset=utf-8");
- res.setHeader("Content-Length", Buffer.byteLength(body, "utf8"));
- if (req$4.method === "HEAD") {
- res.end();
- return;
- }
- res.end(body, "utf8");
- }
- if (isFinished(req$4)) {
- write();
- return;
- }
- unpipe(req$4);
- onFinished(req$4, write);
- req$4.resume();
- }
- /**
- * Set response headers from an object.
- *
- * @param {OutgoingMessage} res
- * @param {object} headers
- * @private
- */
- function setHeaders(res, headers) {
- if (!headers) return;
- var keys = Object.keys(headers);
- for (var i$1 = 0; i$1 < keys.length; i$1++) {
- var key = keys[i$1];
- res.setHeader(key, headers[key]);
- }
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/utils-merge@1.0.1/node_modules/utils-merge/index.js
-var require_utils_merge = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /**
- * Merge object b with object a.
- *
- * var a = { foo: 'bar' }
- * , b = { bar: 'baz' };
- *
- * merge(a, b);
- * // => { foo: 'bar', bar: 'baz' }
- *
- * @param {Object} a
- * @param {Object} b
- * @return {Object}
- * @api public
- */
- exports = module.exports = function(a, b) {
- if (a && b) for (var key in b) a[key] = b[key];
- return a;
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/connect@3.7.0_ms@2.1.3/node_modules/connect/index.js
-/*!
-* connect
-* Copyright(c) 2010 Sencha Inc.
-* Copyright(c) 2011 TJ Holowaychuk
-* Copyright(c) 2015 Douglas Christopher Wilson
-* MIT Licensed
-*/
-var require_connect = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /**
- * Module dependencies.
- * @private
- */
- var debug$12 = (init_node(), __toCommonJS(node_exports))("connect:dispatcher");
- var EventEmitter$4 = __require("events").EventEmitter;
- var finalhandler = require_finalhandler();
- var http$6 = __require("http");
- var merge = require_utils_merge();
- var parseUrl$1 = require_parseurl();
- /**
- * Module exports.
- * @public
- */
- module.exports = createServer$3;
- /**
- * Module variables.
- * @private
- */
- var env = process.env.NODE_ENV || "development";
- var proto = {};
- /* istanbul ignore next */
- var defer = typeof setImmediate === "function" ? setImmediate : function(fn) {
- process.nextTick(fn.bind.apply(fn, arguments));
- };
- /**
- * Create a new connect server.
- *
- * @return {function}
- * @public
- */
- function createServer$3() {
- function app(req$4, res, next) {
- app.handle(req$4, res, next);
- }
- merge(app, proto);
- merge(app, EventEmitter$4.prototype);
- app.route = "/";
- app.stack = [];
- return app;
- }
- /**
- * Utilize the given middleware `handle` to the given `route`,
- * defaulting to _/_. This "route" is the mount-point for the
- * middleware, when given a value other than _/_ the middleware
- * is only effective when that segment is present in the request's
- * pathname.
- *
- * For example if we were to mount a function at _/admin_, it would
- * be invoked on _/admin_, and _/admin/settings_, however it would
- * not be invoked for _/_, or _/posts_.
- *
- * @param {String|Function|Server} route, callback or server
- * @param {Function|Server} callback or server
- * @return {Server} for chaining
- * @public
- */
- proto.use = function use(route, fn) {
- var handle = fn;
- var path$13 = route;
- if (typeof route !== "string") {
- handle = route;
- path$13 = "/";
- }
- if (typeof handle.handle === "function") {
- var server = handle;
- server.route = path$13;
- handle = function(req$4, res, next) {
- server.handle(req$4, res, next);
- };
- }
- if (handle instanceof http$6.Server) handle = handle.listeners("request")[0];
- if (path$13[path$13.length - 1] === "/") path$13 = path$13.slice(0, -1);
- debug$12("use %s %s", path$13 || "/", handle.name || "anonymous");
- this.stack.push({
- route: path$13,
- handle
- });
- return this;
- };
- /**
- * Handle server requests, punting them down
- * the middleware stack.
- *
- * @private
- */
- proto.handle = function handle(req$4, res, out) {
- var index = 0;
- var protohost = getProtohost(req$4.url) || "";
- var removed = "";
- var slashAdded = false;
- var stack = this.stack;
- var done = out || finalhandler(req$4, res, {
- env,
- onerror: logerror
- });
- req$4.originalUrl = req$4.originalUrl || req$4.url;
- function next(err$2) {
- if (slashAdded) {
- req$4.url = req$4.url.substr(1);
- slashAdded = false;
- }
- if (removed.length !== 0) {
- req$4.url = protohost + removed + req$4.url.substr(protohost.length);
- removed = "";
- }
- var layer = stack[index++];
- if (!layer) {
- defer(done, err$2);
- return;
- }
- var path$13 = parseUrl$1(req$4).pathname || "/";
- var route = layer.route;
- if (path$13.toLowerCase().substr(0, route.length) !== route.toLowerCase()) return next(err$2);
- var c = path$13.length > route.length && path$13[route.length];
- if (c && c !== "/" && c !== ".") return next(err$2);
- if (route.length !== 0 && route !== "/") {
- removed = route;
- req$4.url = protohost + req$4.url.substr(protohost.length + removed.length);
- if (!protohost && req$4.url[0] !== "/") {
- req$4.url = "/" + req$4.url;
- slashAdded = true;
- }
- }
- call(layer.handle, route, err$2, req$4, res, next);
- }
- next();
- };
- /**
- * Listen for connections.
- *
- * This method takes the same arguments
- * as node's `http.Server#listen()`.
- *
- * HTTP and HTTPS:
- *
- * If you run your application both as HTTP
- * and HTTPS you may wrap them individually,
- * since your Connect "server" is really just
- * a JavaScript `Function`.
- *
- * var connect = require('connect')
- * , http = require('http')
- * , https = require('https');
- *
- * var app = connect();
- *
- * http.createServer(app).listen(80);
- * https.createServer(options, app).listen(443);
- *
- * @return {http.Server}
- * @api public
- */
- proto.listen = function listen() {
- var server = http$6.createServer(this);
- return server.listen.apply(server, arguments);
- };
- /**
- * Invoke a route handle.
- * @private
- */
- function call(handle, route, err$2, req$4, res, next) {
- var arity = handle.length;
- var error$1 = err$2;
- var hasError = Boolean(err$2);
- debug$12("%s %s : %s", handle.name || "<anonymous>", route, req$4.originalUrl);
- try {
- if (hasError && arity === 4) {
- handle(err$2, req$4, res, next);
- return;
- } else if (!hasError && arity < 4) {
- handle(req$4, res, next);
- return;
- }
- } catch (e$1) {
- error$1 = e$1;
- }
- next(error$1);
- }
- /**
- * Log error using console.error.
- *
- * @param {Error} err
- * @private
- */
- function logerror(err$2) {
- if (env !== "test") console.error(err$2.stack || err$2.toString());
- }
- /**
- * Get get protocol + host for a URL.
- *
- * @param {string} url
- * @private
- */
- function getProtohost(url$3) {
- if (url$3.length === 0 || url$3[0] === "/") return;
- var fqdnIndex = url$3.indexOf("://");
- return fqdnIndex !== -1 && url$3.lastIndexOf("?", fqdnIndex) === -1 ? url$3.substr(0, url$3.indexOf("/", 3 + fqdnIndex)) : void 0;
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/object-assign@4.1.1/node_modules/object-assign/index.js
-/*
-object-assign
-(c) Sindre Sorhus
-@license MIT
-*/
-var require_object_assign = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- var getOwnPropertySymbols = Object.getOwnPropertySymbols;
- var hasOwnProperty = Object.prototype.hasOwnProperty;
- var propIsEnumerable = Object.prototype.propertyIsEnumerable;
- function toObject(val) {
- if (val === null || val === void 0) throw new TypeError("Object.assign cannot be called with null or undefined");
- return Object(val);
- }
- function shouldUseNative() {
- try {
- if (!Object.assign) return false;
- var test1 = /* @__PURE__ */ new String("abc");
- test1[5] = "de";
- if (Object.getOwnPropertyNames(test1)[0] === "5") return false;
- var test2 = {};
- for (var i$1 = 0; i$1 < 10; i$1++) test2["_" + String.fromCharCode(i$1)] = i$1;
- if (Object.getOwnPropertyNames(test2).map(function(n$2) {
- return test2[n$2];
- }).join("") !== "0123456789") return false;
- var test3 = {};
- "abcdefghijklmnopqrst".split("").forEach(function(letter) {
- test3[letter] = letter;
- });
- if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") return false;
- return true;
- } catch (err$2) {
- return false;
- }
- }
- module.exports = shouldUseNative() ? Object.assign : function(target, source) {
- var from;
- var to = toObject(target);
- var symbols;
- for (var s = 1; s < arguments.length; s++) {
- from = Object(arguments[s]);
- for (var key in from) if (hasOwnProperty.call(from, key)) to[key] = from[key];
- if (getOwnPropertySymbols) {
- symbols = getOwnPropertySymbols(from);
- for (var i$1 = 0; i$1 < symbols.length; i$1++) if (propIsEnumerable.call(from, symbols[i$1])) to[symbols[i$1]] = from[symbols[i$1]];
- }
- }
- return to;
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/vary@1.1.2/node_modules/vary/index.js
-/*!
-* vary
-* Copyright(c) 2014-2017 Douglas Christopher Wilson
-* MIT Licensed
-*/
-var require_vary = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /**
- * Module exports.
- */
- module.exports = vary;
- module.exports.append = append$1;
- /**
- * RegExp to match field-name in RFC 7230 sec 3.2
- *
- * field-name = token
- * token = 1*tchar
- * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
- * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
- * / DIGIT / ALPHA
- * ; any VCHAR, except delimiters
- */
- var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
- /**
- * Append a field to a vary header.
- *
- * @param {String} header
- * @param {String|Array} field
- * @return {String}
- * @public
- */
- function append$1(header, field) {
- if (typeof header !== "string") throw new TypeError("header argument is required");
- if (!field) throw new TypeError("field argument is required");
- var fields = !Array.isArray(field) ? parse$9(String(field)) : field;
- for (var j = 0; j < fields.length; j++) if (!FIELD_NAME_REGEXP.test(fields[j])) throw new TypeError("field argument contains an invalid header name");
- if (header === "*") return header;
- var val = header;
- var vals = parse$9(header.toLowerCase());
- if (fields.indexOf("*") !== -1 || vals.indexOf("*") !== -1) return "*";
- for (var i$1 = 0; i$1 < fields.length; i$1++) {
- var fld = fields[i$1].toLowerCase();
- if (vals.indexOf(fld) === -1) {
- vals.push(fld);
- val = val ? val + ", " + fields[i$1] : fields[i$1];
- }
- }
- return val;
- }
- /**
- * Parse a vary header into an array.
- *
- * @param {String} header
- * @return {Array}
- * @private
- */
- function parse$9(header) {
- var end = 0;
- var list = [];
- var start = 0;
- for (var i$1 = 0, len = header.length; i$1 < len; i$1++) switch (header.charCodeAt(i$1)) {
- case 32:
- if (start === end) start = end = i$1 + 1;
- break;
- case 44:
- list.push(header.substring(start, end));
- start = end = i$1 + 1;
- break;
- default:
- end = i$1 + 1;
- break;
- }
- list.push(header.substring(start, end));
- return list;
- }
- /**
- * Mark that a request is varied on a header field.
- *
- * @param {Object} res
- * @param {String|Array} field
- * @public
- */
- function vary(res, field) {
- if (!res || !res.getHeader || !res.setHeader) throw new TypeError("res argument is required");
- var val = res.getHeader("Vary") || "";
- if (val = append$1(Array.isArray(val) ? val.join(", ") : String(val), field)) res.setHeader("Vary", val);
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/cors@2.8.5/node_modules/cors/lib/index.js
-var require_lib$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- (function() {
- "use strict";
- var assign = require_object_assign();
- var vary$1 = require_vary();
- var defaults = {
- origin: "*",
- methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
- preflightContinue: false,
- optionsSuccessStatus: 204
- };
- function isString$1(s) {
- return typeof s === "string" || s instanceof String;
- }
- function isOriginAllowed(origin, allowedOrigin) {
- if (Array.isArray(allowedOrigin)) {
- for (var i$1 = 0; i$1 < allowedOrigin.length; ++i$1) if (isOriginAllowed(origin, allowedOrigin[i$1])) return true;
- return false;
- } else if (isString$1(allowedOrigin)) return origin === allowedOrigin;
- else if (allowedOrigin instanceof RegExp) return allowedOrigin.test(origin);
- else return !!allowedOrigin;
- }
- function configureOrigin(options$1, req$4) {
- var requestOrigin = req$4.headers.origin, headers = [], isAllowed;
- if (!options$1.origin || options$1.origin === "*") headers.push([{
- key: "Access-Control-Allow-Origin",
- value: "*"
- }]);
- else if (isString$1(options$1.origin)) {
- headers.push([{
- key: "Access-Control-Allow-Origin",
- value: options$1.origin
- }]);
- headers.push([{
- key: "Vary",
- value: "Origin"
- }]);
- } else {
- isAllowed = isOriginAllowed(requestOrigin, options$1.origin);
- headers.push([{
- key: "Access-Control-Allow-Origin",
- value: isAllowed ? requestOrigin : false
- }]);
- headers.push([{
- key: "Vary",
- value: "Origin"
- }]);
- }
- return headers;
- }
- function configureMethods(options$1) {
- var methods = options$1.methods;
- if (methods.join) methods = options$1.methods.join(",");
- return {
- key: "Access-Control-Allow-Methods",
- value: methods
- };
- }
- function configureCredentials(options$1) {
- if (options$1.credentials === true) return {
- key: "Access-Control-Allow-Credentials",
- value: "true"
- };
- return null;
- }
- function configureAllowedHeaders(options$1, req$4) {
- var allowedHeaders = options$1.allowedHeaders || options$1.headers;
- var headers = [];
- if (!allowedHeaders) {
- allowedHeaders = req$4.headers["access-control-request-headers"];
- headers.push([{
- key: "Vary",
- value: "Access-Control-Request-Headers"
- }]);
- } else if (allowedHeaders.join) allowedHeaders = allowedHeaders.join(",");
- if (allowedHeaders && allowedHeaders.length) headers.push([{
- key: "Access-Control-Allow-Headers",
- value: allowedHeaders
- }]);
- return headers;
- }
- function configureExposedHeaders(options$1) {
- var headers = options$1.exposedHeaders;
- if (!headers) return null;
- else if (headers.join) headers = headers.join(",");
- if (headers && headers.length) return {
- key: "Access-Control-Expose-Headers",
- value: headers
- };
- return null;
- }
- function configureMaxAge(options$1) {
- var maxAge = (typeof options$1.maxAge === "number" || options$1.maxAge) && options$1.maxAge.toString();
- if (maxAge && maxAge.length) return {
- key: "Access-Control-Max-Age",
- value: maxAge
- };
- return null;
- }
- function applyHeaders(headers, res) {
- for (var i$1 = 0, n$2 = headers.length; i$1 < n$2; i$1++) {
- var header = headers[i$1];
- if (header) {
- if (Array.isArray(header)) applyHeaders(header, res);
- else if (header.key === "Vary" && header.value) vary$1(res, header.value);
- else if (header.value) res.setHeader(header.key, header.value);
- }
- }
- }
- function cors(options$1, req$4, res, next) {
- var headers = [];
- if ((req$4.method && req$4.method.toUpperCase && req$4.method.toUpperCase()) === "OPTIONS") {
- headers.push(configureOrigin(options$1, req$4));
- headers.push(configureCredentials(options$1, req$4));
- headers.push(configureMethods(options$1, req$4));
- headers.push(configureAllowedHeaders(options$1, req$4));
- headers.push(configureMaxAge(options$1, req$4));
- headers.push(configureExposedHeaders(options$1, req$4));
- applyHeaders(headers, res);
- if (options$1.preflightContinue) next();
- else {
- res.statusCode = options$1.optionsSuccessStatus;
- res.setHeader("Content-Length", "0");
- res.end();
- }
- } else {
- headers.push(configureOrigin(options$1, req$4));
- headers.push(configureCredentials(options$1, req$4));
- headers.push(configureExposedHeaders(options$1, req$4));
- applyHeaders(headers, res);
- next();
- }
- }
- function middlewareWrapper(o$1) {
- var optionsCallback = null;
- if (typeof o$1 === "function") optionsCallback = o$1;
- else optionsCallback = function(req$4, cb) {
- cb(null, o$1);
- };
- return function corsMiddleware$2(req$4, res, next) {
- optionsCallback(req$4, function(err$2, options$1) {
- if (err$2) next(err$2);
- else {
- var corsOptions = assign({}, defaults, options$1);
- var originCallback = null;
- if (corsOptions.origin && typeof corsOptions.origin === "function") originCallback = corsOptions.origin;
- else if (corsOptions.origin) originCallback = function(origin, cb) {
- cb(null, corsOptions.origin);
- };
- if (originCallback) originCallback(req$4.headers.origin, function(err2, origin) {
- if (err2 || !origin) next(err2);
- else {
- corsOptions.origin = origin;
- cors(corsOptions, req$4, res, next);
- }
- });
- else next();
- }
- });
- };
- }
- module.exports = middlewareWrapper;
- })();
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/readdirp@3.6.0/node_modules/readdirp/index.js
-var require_readdirp = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const fs$9 = __require("fs");
- const { Readable: Readable$1 } = __require("stream");
- const sysPath$3 = __require("path");
- const { promisify: promisify$4 } = __require("util");
- const picomatch$2 = __require("picomatch");
- const readdir$1 = promisify$4(fs$9.readdir);
- const stat$3 = promisify$4(fs$9.stat);
- const lstat$2 = promisify$4(fs$9.lstat);
- const realpath$1 = promisify$4(fs$9.realpath);
- /**
- * @typedef {Object} EntryInfo
- * @property {String} path
- * @property {String} fullPath
- * @property {fs.Stats=} stats
- * @property {fs.Dirent=} dirent
- * @property {String} basename
- */
- const BANG$2 = "!";
- const RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
- const NORMAL_FLOW_ERRORS = new Set([
- "ENOENT",
- "EPERM",
- "EACCES",
- "ELOOP",
- RECURSIVE_ERROR_CODE
- ]);
- const FILE_TYPE = "files";
- const DIR_TYPE = "directories";
- const FILE_DIR_TYPE = "files_directories";
- const EVERYTHING_TYPE = "all";
- const ALL_TYPES = [
- FILE_TYPE,
- DIR_TYPE,
- FILE_DIR_TYPE,
- EVERYTHING_TYPE
- ];
- const isNormalFlowError = (error$1) => NORMAL_FLOW_ERRORS.has(error$1.code);
- const [maj, min] = process.versions.node.split(".").slice(0, 2).map((n$2) => Number.parseInt(n$2, 10));
- const wantBigintFsStats = process.platform === "win32" && (maj > 10 || maj === 10 && min >= 5);
- const normalizeFilter$1 = (filter$1) => {
- if (filter$1 === void 0) return;
- if (typeof filter$1 === "function") return filter$1;
- if (typeof filter$1 === "string") {
- const glob$1 = picomatch$2(filter$1.trim());
- return (entry) => glob$1(entry.basename);
- }
- if (Array.isArray(filter$1)) {
- const positive = [];
- const negative = [];
- for (const item of filter$1) {
- const trimmed = item.trim();
- if (trimmed.charAt(0) === BANG$2) negative.push(picomatch$2(trimmed.slice(1)));
- else positive.push(picomatch$2(trimmed));
- }
- if (negative.length > 0) {
- if (positive.length > 0) return (entry) => positive.some((f$1) => f$1(entry.basename)) && !negative.some((f$1) => f$1(entry.basename));
- return (entry) => !negative.some((f$1) => f$1(entry.basename));
- }
- return (entry) => positive.some((f$1) => f$1(entry.basename));
- }
- };
- var ReaddirpStream = class ReaddirpStream extends Readable$1 {
- static get defaultOptions() {
- return {
- root: ".",
- fileFilter: (path$13) => true,
- directoryFilter: (path$13) => true,
- type: FILE_TYPE,
- lstat: false,
- depth: 2147483648,
- alwaysStat: false
- };
- }
- constructor(options$1 = {}) {
- super({
- objectMode: true,
- autoDestroy: true,
- highWaterMark: options$1.highWaterMark || 4096
- });
- const opts = {
- ...ReaddirpStream.defaultOptions,
- ...options$1
- };
- const { root, type } = opts;
- this._fileFilter = normalizeFilter$1(opts.fileFilter);
- this._directoryFilter = normalizeFilter$1(opts.directoryFilter);
- const statMethod = opts.lstat ? lstat$2 : stat$3;
- if (wantBigintFsStats) this._stat = (path$13) => statMethod(path$13, { bigint: true });
- else this._stat = statMethod;
- this._maxDepth = opts.depth;
- this._wantsDir = [
- DIR_TYPE,
- FILE_DIR_TYPE,
- EVERYTHING_TYPE
- ].includes(type);
- this._wantsFile = [
- FILE_TYPE,
- FILE_DIR_TYPE,
- EVERYTHING_TYPE
- ].includes(type);
- this._wantsEverything = type === EVERYTHING_TYPE;
- this._root = sysPath$3.resolve(root);
- this._isDirent = "Dirent" in fs$9 && !opts.alwaysStat;
- this._statsProp = this._isDirent ? "dirent" : "stats";
- this._rdOptions = {
- encoding: "utf8",
- withFileTypes: this._isDirent
- };
- this.parents = [this._exploreDir(root, 1)];
- this.reading = false;
- this.parent = void 0;
- }
- async _read(batch) {
- if (this.reading) return;
- this.reading = true;
- try {
- while (!this.destroyed && batch > 0) {
- const { path: path$13, depth, files = [] } = this.parent || {};
- if (files.length > 0) {
- const slice = files.splice(0, batch).map((dirent) => this._formatEntry(dirent, path$13));
- for (const entry of await Promise.all(slice)) {
- if (this.destroyed) return;
- const entryType = await this._getEntryType(entry);
- if (entryType === "directory" && this._directoryFilter(entry)) {
- if (depth <= this._maxDepth) this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
- if (this._wantsDir) {
- this.push(entry);
- batch--;
- }
- } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
- if (this._wantsFile) {
- this.push(entry);
- batch--;
- }
- }
- }
- } else {
- const parent = this.parents.pop();
- if (!parent) {
- this.push(null);
- break;
- }
- this.parent = await parent;
- if (this.destroyed) return;
- }
- }
- } catch (error$1) {
- this.destroy(error$1);
- } finally {
- this.reading = false;
- }
- }
- async _exploreDir(path$13, depth) {
- let files;
- try {
- files = await readdir$1(path$13, this._rdOptions);
- } catch (error$1) {
- this._onError(error$1);
- }
- return {
- files,
- depth,
- path: path$13
- };
- }
- async _formatEntry(dirent, path$13) {
- let entry;
- try {
- const basename$3 = this._isDirent ? dirent.name : dirent;
- const fullPath = sysPath$3.resolve(sysPath$3.join(path$13, basename$3));
- entry = {
- path: sysPath$3.relative(this._root, fullPath),
- fullPath,
- basename: basename$3
- };
- entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
- } catch (err$2) {
- this._onError(err$2);
- }
- return entry;
- }
- _onError(err$2) {
- if (isNormalFlowError(err$2) && !this.destroyed) this.emit("warn", err$2);
- else this.destroy(err$2);
- }
- async _getEntryType(entry) {
- const stats = entry && entry[this._statsProp];
- if (!stats) return;
- if (stats.isFile()) return "file";
- if (stats.isDirectory()) return "directory";
- if (stats && stats.isSymbolicLink()) {
- const full = entry.fullPath;
- try {
- const entryRealPath = await realpath$1(full);
- const entryRealPathStats = await lstat$2(entryRealPath);
- if (entryRealPathStats.isFile()) return "file";
- if (entryRealPathStats.isDirectory()) {
- const len = entryRealPath.length;
- if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
- const recursiveError = /* @__PURE__ */ new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
- recursiveError.code = RECURSIVE_ERROR_CODE;
- return this._onError(recursiveError);
- }
- return "directory";
- }
- } catch (error$1) {
- this._onError(error$1);
- }
- }
- }
- _includeAsFile(entry) {
- const stats = entry && entry[this._statsProp];
- return stats && this._wantsEverything && !stats.isDirectory();
- }
- };
- /**
- * @typedef {Object} ReaddirpArguments
- * @property {Function=} fileFilter
- * @property {Function=} directoryFilter
- * @property {String=} type
- * @property {Number=} depth
- * @property {String=} root
- * @property {Boolean=} lstat
- * @property {Boolean=} bigint
- */
- /**
- * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
- * @param {String} root Root directory
- * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
- */
- const readdirp$1 = (root, options$1 = {}) => {
- let type = options$1.entryType || options$1.type;
- if (type === "both") type = FILE_DIR_TYPE;
- if (type) options$1.type = type;
- if (!root) throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
- else if (typeof root !== "string") throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
- else if (type && !ALL_TYPES.includes(type)) throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
- options$1.root = root;
- return new ReaddirpStream(options$1);
- };
- const readdirpPromise = (root, options$1 = {}) => {
- return new Promise((resolve$4, reject) => {
- const files = [];
- readdirp$1(root, options$1).on("data", (entry) => files.push(entry)).on("end", () => resolve$4(files)).on("error", (error$1) => reject(error$1));
- });
- };
- readdirp$1.promise = readdirpPromise;
- readdirp$1.ReaddirpStream = ReaddirpStream;
- readdirp$1.default = readdirp$1;
- module.exports = readdirp$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/normalize-path@3.0.0/node_modules/normalize-path/index.js
-var require_normalize_path = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /*!
- * normalize-path <https://github.com/jonschlinkert/normalize-path>
- *
- * Copyright (c) 2014-2018, Jon Schlinkert.
- * Released under the MIT License.
- */
- module.exports = function(path$13, stripTrailing) {
- if (typeof path$13 !== "string") throw new TypeError("expected path to be a string");
- if (path$13 === "\\" || path$13 === "/") return "/";
- var len = path$13.length;
- if (len <= 1) return path$13;
- var prefix = "";
- if (len > 4 && path$13[3] === "\\") {
- var ch = path$13[2];
- if ((ch === "?" || ch === ".") && path$13.slice(0, 2) === "\\\\") {
- path$13 = path$13.slice(2);
- prefix = "//";
- }
- }
- var segs = path$13.split(/[/\\]+/);
- if (stripTrailing !== false && segs[segs.length - 1] === "") segs.pop();
- return prefix + segs.join("/");
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/anymatch@3.1.3/node_modules/anymatch/index.js
-var require_anymatch = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- const picomatch$1 = __require("picomatch");
- const normalizePath$2 = require_normalize_path();
- /**
- * @typedef {(testString: string) => boolean} AnymatchFn
- * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
- * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
- */
- const BANG$1 = "!";
- const DEFAULT_OPTIONS = { returnIndex: false };
- const arrify$1 = (item) => Array.isArray(item) ? item : [item];
- /**
- * @param {AnymatchPattern} matcher
- * @param {object} options
- * @returns {AnymatchFn}
- */
- const createPattern = (matcher, options$1) => {
- if (typeof matcher === "function") return matcher;
- if (typeof matcher === "string") {
- const glob$1 = picomatch$1(matcher, options$1);
- return (string) => matcher === string || glob$1(string);
- }
- if (matcher instanceof RegExp) return (string) => matcher.test(string);
- return (string) => false;
- };
- /**
- * @param {Array<Function>} patterns
- * @param {Array<Function>} negPatterns
- * @param {String|Array} args
- * @param {Boolean} returnIndex
- * @returns {boolean|number}
- */
- const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
- const isList = Array.isArray(args);
- const _path = isList ? args[0] : args;
- if (!isList && typeof _path !== "string") throw new TypeError("anymatch: second argument must be a string: got " + Object.prototype.toString.call(_path));
- const path$13 = normalizePath$2(_path, false);
- for (let index = 0; index < negPatterns.length; index++) {
- const nglob = negPatterns[index];
- if (nglob(path$13)) return returnIndex ? -1 : false;
- }
- const applied = isList && [path$13].concat(args.slice(1));
- for (let index = 0; index < patterns.length; index++) {
- const pattern = patterns[index];
- if (isList ? pattern(...applied) : pattern(path$13)) return returnIndex ? index : true;
- }
- return returnIndex ? -1 : false;
- };
- /**
- * @param {AnymatchMatcher} matchers
- * @param {Array|string} testString
- * @param {object} options
- * @returns {boolean|number|Function}
- */
- const anymatch$1 = (matchers, testString, options$1 = DEFAULT_OPTIONS) => {
- if (matchers == null) throw new TypeError("anymatch: specify first argument");
- const opts = typeof options$1 === "boolean" ? { returnIndex: options$1 } : options$1;
- const returnIndex = opts.returnIndex || false;
- const mtchers = arrify$1(matchers);
- const negatedGlobs = mtchers.filter((item) => typeof item === "string" && item.charAt(0) === BANG$1).map((item) => item.slice(1)).map((item) => picomatch$1(item, opts));
- const patterns = mtchers.filter((item) => typeof item !== "string" || typeof item === "string" && item.charAt(0) !== BANG$1).map((matcher) => createPattern(matcher, opts));
- if (testString == null) return (testString$1, ri = false) => {
- return matchPatterns(patterns, negatedGlobs, testString$1, typeof ri === "boolean" ? ri : false);
- };
- return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
- };
- anymatch$1.default = anymatch$1;
- module.exports = anymatch$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/is-extglob@2.1.1/node_modules/is-extglob/index.js
-var require_is_extglob = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /*!
- * is-extglob <https://github.com/jonschlinkert/is-extglob>
- *
- * Copyright (c) 2014-2016, Jon Schlinkert.
- * Licensed under the MIT License.
- */
- module.exports = function isExtglob$1(str) {
- if (typeof str !== "string" || str === "") return false;
- var match;
- while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
- if (match[2]) return true;
- str = str.slice(match.index + match[0].length);
- }
- return false;
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/is-glob@4.0.3/node_modules/is-glob/index.js
-var require_is_glob = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /*!
- * is-glob <https://github.com/jonschlinkert/is-glob>
- *
- * Copyright (c) 2014-2017, Jon Schlinkert.
- * Released under the MIT License.
- */
- var isExtglob = require_is_extglob();
- var chars = {
- "{": "}",
- "(": ")",
- "[": "]"
- };
- var strictCheck = function(str) {
- if (str[0] === "!") return true;
- var index = 0;
- var pipeIndex = -2;
- var closeSquareIndex = -2;
- var closeCurlyIndex = -2;
- var closeParenIndex = -2;
- var backSlashIndex = -2;
- while (index < str.length) {
- if (str[index] === "*") return true;
- if (str[index + 1] === "?" && /[\].+)]/.test(str[index])) return true;
- if (closeSquareIndex !== -1 && str[index] === "[" && str[index + 1] !== "]") {
- if (closeSquareIndex < index) closeSquareIndex = str.indexOf("]", index);
- if (closeSquareIndex > index) {
- if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) return true;
- backSlashIndex = str.indexOf("\\", index);
- if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) return true;
- }
- }
- if (closeCurlyIndex !== -1 && str[index] === "{" && str[index + 1] !== "}") {
- closeCurlyIndex = str.indexOf("}", index);
- if (closeCurlyIndex > index) {
- backSlashIndex = str.indexOf("\\", index);
- if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) return true;
- }
- }
- if (closeParenIndex !== -1 && str[index] === "(" && str[index + 1] === "?" && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ")") {
- closeParenIndex = str.indexOf(")", index);
- if (closeParenIndex > index) {
- backSlashIndex = str.indexOf("\\", index);
- if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) return true;
- }
- }
- if (pipeIndex !== -1 && str[index] === "(" && str[index + 1] !== "|") {
- if (pipeIndex < index) pipeIndex = str.indexOf("|", index);
- if (pipeIndex !== -1 && str[pipeIndex + 1] !== ")") {
- closeParenIndex = str.indexOf(")", pipeIndex);
- if (closeParenIndex > pipeIndex) {
- backSlashIndex = str.indexOf("\\", pipeIndex);
- if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) return true;
- }
- }
- }
- if (str[index] === "\\") {
- var open$2 = str[index + 1];
- index += 2;
- var close$1 = chars[open$2];
- if (close$1) {
- var n$2 = str.indexOf(close$1, index);
- if (n$2 !== -1) index = n$2 + 1;
- }
- if (str[index] === "!") return true;
- } else index++;
- }
- return false;
- };
- var relaxedCheck = function(str) {
- if (str[0] === "!") return true;
- var index = 0;
- while (index < str.length) {
- if (/[*?{}()[\]]/.test(str[index])) return true;
- if (str[index] === "\\") {
- var open$2 = str[index + 1];
- index += 2;
- var close$1 = chars[open$2];
- if (close$1) {
- var n$2 = str.indexOf(close$1, index);
- if (n$2 !== -1) index = n$2 + 1;
- }
- if (str[index] === "!") return true;
- } else index++;
- }
- return false;
- };
- module.exports = function isGlob$2(str, options$1) {
- if (typeof str !== "string" || str === "") return false;
- if (isExtglob(str)) return true;
- var check = strictCheck;
- if (options$1 && options$1.strict === false) check = relaxedCheck;
- return check(str);
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/glob-parent@5.1.2/node_modules/glob-parent/index.js
-var require_glob_parent = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- var isGlob$1 = require_is_glob();
- var pathPosixDirname = __require("path").posix.dirname;
- var isWin32 = __require("os").platform() === "win32";
- var slash$1 = "/";
- var backslash = /\\/g;
- var enclosure = /[\{\[].*[\}\]]$/;
- var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
- var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
- /**
- * @param {string} str
- * @param {Object} opts
- * @param {boolean} [opts.flipBackslashes=true]
- * @returns {string}
- */
- module.exports = function globParent$1(str, opts) {
- if (Object.assign({ flipBackslashes: true }, opts).flipBackslashes && isWin32 && str.indexOf(slash$1) < 0) str = str.replace(backslash, slash$1);
- if (enclosure.test(str)) str += slash$1;
- str += "a";
- do
- str = pathPosixDirname(str);
- while (isGlob$1(str) || globby.test(str));
- return str.replace(escaped, "$1");
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/utils.js
-var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
- 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$1) => node$1.type === type);
- /**
- * Find a node of the given type
- */
- exports.exceedsLimit = (min$1, max, step = 1, limit) => {
- if (limit === false) return false;
- if (!exports.isInteger(min$1) || !exports.isInteger(max)) return false;
- return (Number(max) - Number(min$1)) / Number(step) >= limit;
- };
- /**
- * Escape the given node with '\\' before node.value
- */
- exports.escapeNode = (block, n$2 = 0, type) => {
- const node = block.nodes[n$2];
- 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$1 = 0; i$1 < arr.length; i$1++) {
- const ele = arr[i$1];
- if (Array.isArray(ele)) {
- flat(ele);
- continue;
- }
- if (ele !== void 0) result.push(ele);
- }
- return result;
- };
- flat(args);
- return result;
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/stringify.js
-var require_stringify = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const utils$2 = require_utils();
- module.exports = (ast, options$1 = {}) => {
- const stringify$5 = (node, parent = {}) => {
- const invalidBlock = options$1.escapeInvalid && utils$2.isInvalidBrace(parent);
- const invalidNode = node.invalid === true && options$1.escapeInvalid === true;
- let output = "";
- if (node.value) {
- if ((invalidBlock || invalidNode) && utils$2.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$5(child);
- return output;
- };
- return stringify$5(ast);
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/is-number@7.0.0/node_modules/is-number/index.js
-/*!
-* is-number <https://github.com/jonschlinkert/is-number>
-*
-* Copyright (c) 2014-present, Jon Schlinkert.
-* Released under the MIT License.
-*/
-var require_is_number = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = function(num) {
- if (typeof num === "number") return num - num === 0;
- if (typeof num === "string" && num.trim() !== "") return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
- return false;
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/to-regex-range@5.0.1/node_modules/to-regex-range/index.js
-/*!
-* to-regex-range <https://github.com/micromatch/to-regex-range>
-*
-* Copyright (c) 2015-present, Jon Schlinkert.
-* Released under the MIT License.
-*/
-var require_to_regex_range = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const isNumber$1 = require_is_number();
- const toRegexRange$1 = (min$1, max, options$1) => {
- if (isNumber$1(min$1) === false) throw new TypeError("toRegexRange: expected the first argument to be a number");
- if (max === void 0 || min$1 === max) return String(min$1);
- if (isNumber$1(max) === false) throw new TypeError("toRegexRange: expected the second argument to be a number.");
- let opts = {
- relaxZeros: true,
- ...options$1
- };
- 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$1 = String(opts.wrap);
- let cacheKey = min$1 + ":" + max + "=" + relax + shorthand + capture + wrap$1;
- if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) return toRegexRange$1.cache[cacheKey].result;
- let a = Math.min(min$1, max);
- let b = Math.max(min$1, max);
- if (Math.abs(a - b) === 1) {
- let result = min$1 + "|" + max;
- if (opts.capture) return `(${result})`;
- if (opts.wrap === false) return result;
- return `(?:${result})`;
- }
- let isPadded = hasPadding(min$1) || hasPadding(max);
- let state = {
- min: min$1,
- max,
- a,
- b
- };
- let positives = [];
- let negatives = [];
- if (isPadded) {
- state.isPadded = isPadded;
- state.maxLen = String(state.max).length;
- }
- if (a < 0) {
- negatives = splitToPatterns(b < 0 ? Math.abs(b) : 1, 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$1.cache[cacheKey] = state;
- return state.result;
- };
- function collatePatterns(neg, pos, options$1) {
- let onlyNegative = filterPatterns(neg, pos, "-", false, options$1) || [];
- let onlyPositive = filterPatterns(pos, neg, "", false, options$1) || [];
- let intersected = filterPatterns(neg, pos, "-?", true, options$1) || [];
- return onlyNegative.concat(intersected).concat(onlyPositive).join("|");
- }
- function splitToRanges(min$1, max) {
- let nines = 1;
- let zeros$1 = 1;
- let stop = countNines(min$1, nines);
- let stops = new Set([max]);
- while (min$1 <= stop && stop <= max) {
- stops.add(stop);
- nines += 1;
- stop = countNines(min$1, nines);
- }
- stop = countZeros(max + 1, zeros$1) - 1;
- while (min$1 < stop && stop <= max) {
- stops.add(stop);
- zeros$1 += 1;
- stop = countZeros(max + 1, zeros$1) - 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$1) {
- 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$1 = 0; i$1 < digits; i$1++) {
- let [startDigit, stopDigit] = zipped[i$1];
- if (startDigit === stopDigit) pattern += startDigit;
- else if (startDigit !== "0" || stopDigit !== "9") pattern += toCharacterClass(startDigit, stopDigit, options$1);
- else count++;
- }
- if (count) pattern += options$1.shorthand === true ? "\\d" : "[0-9]";
- return {
- pattern,
- count: [count],
- digits
- };
- }
- function splitToPatterns(min$1, max, tok, options$1) {
- let ranges = splitToRanges(min$1, max);
- let tokens = [];
- let start = min$1;
- let prev;
- for (let i$1 = 0; i$1 < ranges.length; i$1++) {
- let max$1 = ranges[i$1];
- let obj = rangeToPattern(String(start), String(max$1), options$1);
- let zeros$1 = "";
- 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 + 1;
- continue;
- }
- if (tok.isPadded) zeros$1 = padZeros(max$1, tok, options$1);
- obj.string = zeros$1 + obj.pattern + toQuantifier(obj.count);
- tokens.push(obj);
- start = max$1 + 1;
- prev = obj;
- }
- return tokens;
- }
- function filterPatterns(arr, comparison, prefix, intersection, options$1) {
- let result = [];
- for (let ele of arr) {
- let { string } = ele;
- if (!intersection && !contains(comparison, "string", string)) result.push(prefix + string);
- if (intersection && contains(comparison, "string", string)) result.push(prefix + string);
- }
- return result;
- }
- /**
- * Zip strings
- */
- function zip(a, b) {
- let arr = [];
- for (let i$1 = 0; i$1 < a.length; i$1++) arr.push([a[i$1], b[i$1]]);
- 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$1, len) {
- return Number(String(min$1).slice(0, -len) + "9".repeat(len));
- }
- function countZeros(integer, zeros$1) {
- return integer - integer % Math.pow(10, zeros$1);
- }
- function toQuantifier(digits) {
- let [start = 0, stop = ""] = digits;
- if (stop || start > 1) return `{${start + (stop ? "," + stop : "")}}`;
- return "";
- }
- function toCharacterClass(a, b, options$1) {
- return `[${a}${b - a === 1 ? "" : "-"}${b}]`;
- }
- function hasPadding(str) {
- return /^-?(0+)\d/.test(str);
- }
- function padZeros(value$1, tok, options$1) {
- if (!tok.isPadded) return value$1;
- let diff = Math.abs(tok.maxLen - String(value$1).length);
- let relax = options$1.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$1.cache = {};
- toRegexRange$1.clearCache = () => toRegexRange$1.cache = {};
- /**
- * Expose `toRegexRange`
- */
- module.exports = toRegexRange$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/fill-range@7.1.1/node_modules/fill-range/index.js
-/*!
-* fill-range <https://github.com/jonschlinkert/fill-range>
-*
-* Copyright (c) 2014-present, Jon Schlinkert.
-* Licensed under the MIT License.
-*/
-var require_fill_range = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const util = __require("util");
- const toRegexRange = require_to_regex_range();
- const isObject$1 = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
- const transform$1 = (toNumber) => {
- return (value$1) => toNumber === true ? Number(value$1) : String(value$1);
- };
- const isValidValue = (value$1) => {
- return typeof value$1 === "number" || typeof value$1 === "string" && value$1 !== "";
- };
- const isNumber = (num) => Number.isInteger(+num);
- const zeros = (input) => {
- let value$1 = `${input}`;
- let index = -1;
- if (value$1[0] === "-") value$1 = value$1.slice(1);
- if (value$1 === "0") return false;
- while (value$1[++index] === "0");
- return index > 0;
- };
- const stringify$3 = (start, end, options$1) => {
- if (typeof start === "string" || typeof end === "string") return true;
- return options$1.stringify === true;
- };
- const pad = (input, maxLength, toNumber) => {
- if (maxLength > 0) {
- let dash = input[0] === "-" ? "-" : "";
- if (dash) input = input.slice(1);
- input = dash + input.padStart(dash ? maxLength - 1 : maxLength, "0");
- }
- if (toNumber === false) return String(input);
- return input;
- };
- const toMaxLen = (input, maxLength) => {
- let negative = input[0] === "-" ? "-" : "";
- if (negative) {
- input = input.slice(1);
- maxLength--;
- }
- while (input.length < maxLength) input = "0" + input;
- return negative ? "-" + input : input;
- };
- const toSequence = (parts, options$1, maxLen) => {
- parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
- parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
- let prefix = options$1.capture ? "" : "?:";
- let positives = "";
- let negatives = "";
- let result;
- if (parts.positives.length) positives = parts.positives.map((v) => toMaxLen(String(v), maxLen)).join("|");
- if (parts.negatives.length) negatives = `-(${prefix}${parts.negatives.map((v) => toMaxLen(String(v), maxLen)).join("|")})`;
- if (positives && negatives) result = `${positives}|${negatives}`;
- else result = positives || negatives;
- if (options$1.wrap) return `(${prefix}${result})`;
- return result;
- };
- const toRange = (a, b, isNumbers, options$1) => {
- if (isNumbers) return toRegexRange(a, b, {
- wrap: false,
- ...options$1
- });
- let start = String.fromCharCode(a);
- if (a === b) return start;
- return `[${start}-${String.fromCharCode(b)}]`;
- };
- const toRegex = (start, end, options$1) => {
- if (Array.isArray(start)) return options$1.wrap === true ? `(${options$1.capture ? "" : "?:"}${start.join("|")})` : start.join("|");
- return toRegexRange(start, end, options$1);
- };
- const rangeError = (...args) => {
- return /* @__PURE__ */ new RangeError("Invalid range arguments: " + util.inspect(...args));
- };
- const invalidRange = (start, end, options$1) => {
- if (options$1.strictRanges === true) throw rangeError([start, end]);
- return [];
- };
- const invalidStep = (step, options$1) => {
- if (options$1.strictRanges === true) throw new TypeError(`Expected step "${step}" to be a number`);
- return [];
- };
- const fillNumbers = (start, end, step = 1, options$1 = {}) => {
- let a = Number(start);
- let b = Number(end);
- if (!Number.isInteger(a) || !Number.isInteger(b)) {
- if (options$1.strictRanges === true) throw rangeError([start, end]);
- return [];
- }
- if (a === 0) a = 0;
- if (b === 0) b = 0;
- let descending = a > b;
- let startString = String(start);
- let endString = String(end);
- let stepString = String(step);
- step = Math.max(Math.abs(step), 1);
- let padded = zeros(startString) || zeros(endString) || zeros(stepString);
- let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
- let toNumber = padded === false && stringify$3(start, end, options$1) === false;
- let format$3 = options$1.transform || transform$1(toNumber);
- if (options$1.toRegex && step === 1) return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options$1);
- let parts = {
- negatives: [],
- positives: []
- };
- let push$1 = (num) => parts[num < 0 ? "negatives" : "positives"].push(Math.abs(num));
- let range$1 = [];
- let index = 0;
- while (descending ? a >= b : a <= b) {
- if (options$1.toRegex === true && step > 1) push$1(a);
- else range$1.push(pad(format$3(a, index), maxLen, toNumber));
- a = descending ? a - step : a + step;
- index++;
- }
- if (options$1.toRegex === true) return step > 1 ? toSequence(parts, options$1, maxLen) : toRegex(range$1, null, {
- wrap: false,
- ...options$1
- });
- return range$1;
- };
- const fillLetters = (start, end, step = 1, options$1 = {}) => {
- if (!isNumber(start) && start.length > 1 || !isNumber(end) && end.length > 1) return invalidRange(start, end, options$1);
- let format$3 = options$1.transform || ((val) => String.fromCharCode(val));
- let a = `${start}`.charCodeAt(0);
- let b = `${end}`.charCodeAt(0);
- let descending = a > b;
- let min$1 = Math.min(a, b);
- let max = Math.max(a, b);
- if (options$1.toRegex && step === 1) return toRange(min$1, max, false, options$1);
- let range$1 = [];
- let index = 0;
- while (descending ? a >= b : a <= b) {
- range$1.push(format$3(a, index));
- a = descending ? a - step : a + step;
- index++;
- }
- if (options$1.toRegex === true) return toRegex(range$1, null, {
- wrap: false,
- options: options$1
- });
- return range$1;
- };
- const fill$2 = (start, end, step, options$1 = {}) => {
- if (end == null && isValidValue(start)) return [start];
- if (!isValidValue(start) || !isValidValue(end)) return invalidRange(start, end, options$1);
- if (typeof step === "function") return fill$2(start, end, 1, { transform: step });
- if (isObject$1(step)) return fill$2(start, end, 0, step);
- let opts = { ...options$1 };
- if (opts.capture === true) opts.wrap = true;
- step = step || opts.step || 1;
- if (!isNumber(step)) {
- if (step != null && !isObject$1(step)) return invalidStep(step, opts);
- return fill$2(start, end, 1, step);
- }
- if (isNumber(start) && isNumber(end)) return fillNumbers(start, end, step, opts);
- return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
- };
- module.exports = fill$2;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/compile.js
-var require_compile = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const fill$1 = require_fill_range();
- const utils$1 = require_utils();
- const compile$1 = (ast, options$1 = {}) => {
- const walk$3 = (node, parent = {}) => {
- const invalid = utils$1.isInvalidBrace(parent) === true || (node.invalid === true && options$1.escapeInvalid === true) === true;
- const prefix = options$1.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$1.reduce(node.nodes);
- const range$1 = fill$1(...args, {
- ...options$1,
- wrap: false,
- toRegex: true,
- strictZeros: true
- });
- if (range$1.length !== 0) return args.length > 1 && range$1.length > 1 ? `(${range$1})` : range$1;
- }
- if (node.nodes) for (const child of node.nodes) output += walk$3(child, node);
- return output;
- };
- return walk$3(ast);
- };
- module.exports = compile$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/expand.js
-var require_expand = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const fill = require_fill_range();
- const stringify$2 = require_stringify();
- const utils = require_utils();
- 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$1 of item) result.push(append(value$1, 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$1 = (ast, options$1 = {}) => {
- const rangeLimit = options$1.rangeLimit === void 0 ? 1e3 : options$1.rangeLimit;
- const walk$3 = (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$2(node, options$1)));
- 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$1.step, rangeLimit)) throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");
- let range$1 = fill(...args, options$1);
- if (range$1.length === 0) range$1 = stringify$2(node, options$1);
- q.push(append(q.pop(), range$1));
- 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$1 = 0; i$1 < node.nodes.length; i$1++) {
- const child = node.nodes[i$1];
- if (child.type === "comma" && node.type === "brace") {
- if (i$1 === 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$3(child, node);
- }
- return queue;
- };
- return utils.flatten(walk$3(ast));
- };
- module.exports = expand$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/constants.js
-var require_constants$2 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = {
- MAX_LENGTH: 1e4,
- CHAR_0: "0",
- CHAR_9: "9",
- CHAR_UPPERCASE_A: "A",
- CHAR_LOWERCASE_A: "a",
- CHAR_UPPERCASE_Z: "Z",
- CHAR_LOWERCASE_Z: "z",
- CHAR_LEFT_PARENTHESES: "(",
- CHAR_RIGHT_PARENTHESES: ")",
- CHAR_ASTERISK: "*",
- CHAR_AMPERSAND: "&",
- CHAR_AT: "@",
- CHAR_BACKSLASH: "\\",
- CHAR_BACKTICK: "`",
- CHAR_CARRIAGE_RETURN: "\r",
- CHAR_CIRCUMFLEX_ACCENT: "^",
- CHAR_COLON: ":",
- CHAR_COMMA: ",",
- CHAR_DOLLAR: "$",
- CHAR_DOT: ".",
- CHAR_DOUBLE_QUOTE: "\"",
- CHAR_EQUAL: "=",
- CHAR_EXCLAMATION_MARK: "!",
- CHAR_FORM_FEED: "\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",
- CHAR_NO_BREAK_SPACE: "\xA0",
- 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: " ",
- CHAR_UNDERSCORE: "_",
- CHAR_VERTICAL_LINE: "|",
- CHAR_ZERO_WIDTH_NOBREAK_SPACE: ""
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/parse.js
-var require_parse$2 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const stringify$1 = require_stringify();
- /**
- * 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 } = require_constants$2();
- /**
- * parse
- */
- const parse$8 = (input, options$1 = {}) => {
- if (typeof input !== "string") throw new TypeError("Expected a string");
- const opts = options$1 || {};
- 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$1;
- /**
- * Helpers
- */
- const advance = () => input[index++];
- const push$1 = (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$1({ type: "bos" });
- while (index < length) {
- block = stack[stack.length - 1];
- value$1 = advance();
- /**
- * Invalid chars
- */
- if (value$1 === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value$1 === CHAR_NO_BREAK_SPACE) continue;
- /**
- * Escaped chars
- */
- if (value$1 === CHAR_BACKSLASH) {
- push$1({
- type: "text",
- value: (options$1.keepEscaping ? value$1 : "") + advance()
- });
- continue;
- }
- /**
- * Right square bracket (literal): ']'
- */
- if (value$1 === CHAR_RIGHT_SQUARE_BRACKET) {
- push$1({
- type: "text",
- value: "\\" + value$1
- });
- continue;
- }
- /**
- * Left square bracket: '['
- */
- if (value$1 === CHAR_LEFT_SQUARE_BRACKET) {
- brackets++;
- let next;
- while (index < length && (next = advance())) {
- value$1 += next;
- if (next === CHAR_LEFT_SQUARE_BRACKET) {
- brackets++;
- continue;
- }
- if (next === CHAR_BACKSLASH) {
- value$1 += advance();
- continue;
- }
- if (next === CHAR_RIGHT_SQUARE_BRACKET) {
- brackets--;
- if (brackets === 0) break;
- }
- }
- push$1({
- type: "text",
- value: value$1
- });
- continue;
- }
- /**
- * Parentheses
- */
- if (value$1 === CHAR_LEFT_PARENTHESES) {
- block = push$1({
- type: "paren",
- nodes: []
- });
- stack.push(block);
- push$1({
- type: "text",
- value: value$1
- });
- continue;
- }
- if (value$1 === CHAR_RIGHT_PARENTHESES) {
- if (block.type !== "paren") {
- push$1({
- type: "text",
- value: value$1
- });
- continue;
- }
- block = stack.pop();
- push$1({
- type: "text",
- value: value$1
- });
- block = stack[stack.length - 1];
- continue;
- }
- /**
- * Quotes: '|"|`
- */
- if (value$1 === CHAR_DOUBLE_QUOTE || value$1 === CHAR_SINGLE_QUOTE || value$1 === CHAR_BACKTICK) {
- const open$2 = value$1;
- let next;
- if (options$1.keepQuotes !== true) value$1 = "";
- while (index < length && (next = advance())) {
- if (next === CHAR_BACKSLASH) {
- value$1 += next + advance();
- continue;
- }
- if (next === open$2) {
- if (options$1.keepQuotes === true) value$1 += next;
- break;
- }
- value$1 += next;
- }
- push$1({
- type: "text",
- value: value$1
- });
- continue;
- }
- /**
- * Left curly brace: '{'
- */
- if (value$1 === CHAR_LEFT_CURLY_BRACE) {
- depth++;
- block = push$1({
- type: "brace",
- open: true,
- close: false,
- dollar: prev.value && prev.value.slice(-1) === "$" || block.dollar === true,
- depth,
- commas: 0,
- ranges: 0,
- nodes: []
- });
- stack.push(block);
- push$1({
- type: "open",
- value: value$1
- });
- continue;
- }
- /**
- * Right curly brace: '}'
- */
- if (value$1 === CHAR_RIGHT_CURLY_BRACE) {
- if (block.type !== "brace") {
- push$1({
- type: "text",
- value: value$1
- });
- continue;
- }
- const type = "close";
- block = stack.pop();
- block.close = true;
- push$1({
- type,
- value: value$1
- });
- depth--;
- block = stack[stack.length - 1];
- continue;
- }
- /**
- * Comma: ','
- */
- if (value$1 === CHAR_COMMA && depth > 0) {
- if (block.ranges > 0) {
- block.ranges = 0;
- block.nodes = [block.nodes.shift(), {
- type: "text",
- value: stringify$1(block)
- }];
- }
- push$1({
- type: "comma",
- value: value$1
- });
- block.commas++;
- continue;
- }
- /**
- * Dot: '.'
- */
- if (value$1 === CHAR_DOT && depth > 0 && block.commas === 0) {
- const siblings = block.nodes;
- if (depth === 0 || siblings.length === 0) {
- push$1({
- type: "text",
- value: value$1
- });
- continue;
- }
- if (prev.type === "dot") {
- block.range = [];
- prev.value += value$1;
- 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$1;
- prev = before;
- block.ranges--;
- continue;
- }
- push$1({
- type: "dot",
- value: value$1
- });
- continue;
- }
- /**
- * Text
- */
- push$1({
- type: "text",
- value: value$1
- });
- }
- 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;
- }
- });
- const parent = stack[stack.length - 1];
- const index$1 = parent.nodes.indexOf(block);
- parent.nodes.splice(index$1, 1, ...block.nodes);
- }
- } while (stack.length > 0);
- push$1({ type: "eos" });
- return ast;
- };
- module.exports = parse$8;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/index.js
-var require_braces = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const stringify = require_stringify();
- const compile = require_compile();
- const expand = require_expand();
- const parse$7 = require_parse$2();
- /**
- * 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$1 = (input, options$1 = {}) => {
- let output = [];
- if (Array.isArray(input)) for (const pattern of input) {
- const result = braces$1.create(pattern, options$1);
- if (Array.isArray(result)) output.push(...result);
- else output.push(result);
- }
- else output = [].concat(braces$1.create(input, options$1));
- if (options$1 && options$1.expand === true && options$1.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$1.parse = (input, options$1 = {}) => parse$7(input, options$1);
- /**
- * 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$1.stringify = (input, options$1 = {}) => {
- if (typeof input === "string") return stringify(braces$1.parse(input, options$1), options$1);
- return stringify(input, options$1);
- };
- /**
- * 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$1.compile = (input, options$1 = {}) => {
- if (typeof input === "string") input = braces$1.parse(input, options$1);
- return compile(input, options$1);
- };
- /**
- * 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$1.expand = (input, options$1 = {}) => {
- if (typeof input === "string") input = braces$1.parse(input, options$1);
- let result = expand(input, options$1);
- if (options$1.noempty === true) result = result.filter(Boolean);
- if (options$1.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$1.create = (input, options$1 = {}) => {
- if (input === "" || input.length < 3) return [input];
- return options$1.expand !== true ? braces$1.compile(input, options$1) : braces$1.expand(input, options$1);
- };
- /**
- * Expose "braces"
- */
- module.exports = braces$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/binary-extensions@2.3.0/node_modules/binary-extensions/binary-extensions.json
-var require_binary_extensions$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = [
- "3dm",
- "3ds",
- "3g2",
- "3gp",
- "7z",
- "a",
- "aac",
- "adp",
- "afdesign",
- "afphoto",
- "afpub",
- "ai",
- "aif",
- "aiff",
- "alz",
- "ape",
- "apk",
- "appimage",
- "ar",
- "arj",
- "asf",
- "au",
- "avi",
- "bak",
- "baml",
- "bh",
- "bin",
- "bk",
- "bmp",
- "btif",
- "bz2",
- "bzip2",
- "cab",
- "caf",
- "cgm",
- "class",
- "cmx",
- "cpio",
- "cr2",
- "cur",
- "dat",
- "dcm",
- "deb",
- "dex",
- "djvu",
- "dll",
- "dmg",
- "dng",
- "doc",
- "docm",
- "docx",
- "dot",
- "dotm",
- "dra",
- "DS_Store",
- "dsk",
- "dts",
- "dtshd",
- "dvb",
- "dwg",
- "dxf",
- "ecelp4800",
- "ecelp7470",
- "ecelp9600",
- "egg",
- "eol",
- "eot",
- "epub",
- "exe",
- "f4v",
- "fbs",
- "fh",
- "fla",
- "flac",
- "flatpak",
- "fli",
- "flv",
- "fpx",
- "fst",
- "fvt",
- "g3",
- "gh",
- "gif",
- "graffle",
- "gz",
- "gzip",
- "h261",
- "h263",
- "h264",
- "icns",
- "ico",
- "ief",
- "img",
- "ipa",
- "iso",
- "jar",
- "jpeg",
- "jpg",
- "jpgv",
- "jpm",
- "jxr",
- "key",
- "ktx",
- "lha",
- "lib",
- "lvp",
- "lz",
- "lzh",
- "lzma",
- "lzo",
- "m3u",
- "m4a",
- "m4v",
- "mar",
- "mdi",
- "mht",
- "mid",
- "midi",
- "mj2",
- "mka",
- "mkv",
- "mmr",
- "mng",
- "mobi",
- "mov",
- "movie",
- "mp3",
- "mp4",
- "mp4a",
- "mpeg",
- "mpg",
- "mpga",
- "mxu",
- "nef",
- "npx",
- "numbers",
- "nupkg",
- "o",
- "odp",
- "ods",
- "odt",
- "oga",
- "ogg",
- "ogv",
- "otf",
- "ott",
- "pages",
- "pbm",
- "pcx",
- "pdb",
- "pdf",
- "pea",
- "pgm",
- "pic",
- "png",
- "pnm",
- "pot",
- "potm",
- "potx",
- "ppa",
- "ppam",
- "ppm",
- "pps",
- "ppsm",
- "ppsx",
- "ppt",
- "pptm",
- "pptx",
- "psd",
- "pya",
- "pyc",
- "pyo",
- "pyv",
- "qt",
- "rar",
- "ras",
- "raw",
- "resources",
- "rgb",
- "rip",
- "rlc",
- "rmf",
- "rmvb",
- "rpm",
- "rtf",
- "rz",
- "s3m",
- "s7z",
- "scpt",
- "sgi",
- "shar",
- "snap",
- "sil",
- "sketch",
- "slk",
- "smv",
- "snk",
- "so",
- "stl",
- "suo",
- "sub",
- "swf",
- "tar",
- "tbz",
- "tbz2",
- "tga",
- "tgz",
- "thmx",
- "tif",
- "tiff",
- "tlz",
- "ttc",
- "ttf",
- "txz",
- "udf",
- "uvh",
- "uvi",
- "uvm",
- "uvp",
- "uvs",
- "uvu",
- "viv",
- "vob",
- "war",
- "wav",
- "wax",
- "wbmp",
- "wdp",
- "weba",
- "webm",
- "webp",
- "whl",
- "wim",
- "wm",
- "wma",
- "wmv",
- "wmx",
- "woff",
- "woff2",
- "wrm",
- "wvx",
- "xbm",
- "xif",
- "xla",
- "xlam",
- "xls",
- "xlsb",
- "xlsm",
- "xlsx",
- "xlt",
- "xltm",
- "xltx",
- "xm",
- "xmind",
- "xpi",
- "xpm",
- "xwd",
- "xz",
- "z",
- "zip",
- "zipx"
- ];
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/binary-extensions@2.3.0/node_modules/binary-extensions/index.js
-var require_binary_extensions = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = require_binary_extensions$1();
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/is-binary-path@2.1.0/node_modules/is-binary-path/index.js
-var require_is_binary_path = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const path$9 = __require("path");
- const binaryExtensions = require_binary_extensions();
- const extensions = new Set(binaryExtensions);
- module.exports = (filePath) => extensions.has(path$9.extname(filePath).slice(1).toLowerCase());
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/chokidar@3.6.0_patch_hash=8a4f9e2b397e6034b91a0508faae3cecb97f222313faa129d7cb0eb71e9d0e84/node_modules/chokidar/lib/constants.js
-var require_constants$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
- const { sep: sep$2 } = __require("path");
- const { platform: platform$1 } = process;
- const os$2 = __require("os");
- exports.EV_ALL = "all";
- exports.EV_READY = "ready";
- exports.EV_ADD = "add";
- exports.EV_CHANGE = "change";
- exports.EV_ADD_DIR = "addDir";
- exports.EV_UNLINK = "unlink";
- exports.EV_UNLINK_DIR = "unlinkDir";
- exports.EV_RAW = "raw";
- exports.EV_ERROR = "error";
- exports.STR_DATA = "data";
- exports.STR_END = "end";
- exports.STR_CLOSE = "close";
- exports.FSEVENT_CREATED = "created";
- exports.FSEVENT_MODIFIED = "modified";
- exports.FSEVENT_DELETED = "deleted";
- exports.FSEVENT_MOVED = "moved";
- exports.FSEVENT_CLONED = "cloned";
- exports.FSEVENT_UNKNOWN = "unknown";
- exports.FSEVENT_FLAG_MUST_SCAN_SUBDIRS = 1;
- exports.FSEVENT_TYPE_FILE = "file";
- exports.FSEVENT_TYPE_DIRECTORY = "directory";
- exports.FSEVENT_TYPE_SYMLINK = "symlink";
- exports.KEY_LISTENERS = "listeners";
- exports.KEY_ERR = "errHandlers";
- exports.KEY_RAW = "rawEmitters";
- exports.HANDLER_KEYS = [
- exports.KEY_LISTENERS,
- exports.KEY_ERR,
- exports.KEY_RAW
- ];
- exports.DOT_SLASH = `.${sep$2}`;
- exports.BACK_SLASH_RE = /\\/g;
- exports.DOUBLE_SLASH_RE = /\/\//;
- exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
- exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
- exports.REPLACER_RE = /^\.[/\\]/;
- exports.SLASH = "/";
- exports.SLASH_SLASH = "//";
- exports.BRACE_START = "{";
- exports.BANG = "!";
- exports.ONE_DOT = ".";
- exports.TWO_DOTS = "..";
- exports.STAR = "*";
- exports.GLOBSTAR = "**";
- exports.ROOT_GLOBSTAR = "/**/*";
- exports.SLASH_GLOBSTAR = "/**";
- exports.DIR_SUFFIX = "Dir";
- exports.ANYMATCH_OPTS = { dot: true };
- exports.STRING_TYPE = "string";
- exports.FUNCTION_TYPE = "function";
- exports.EMPTY_STR = "";
- exports.EMPTY_FN = () => {};
- exports.IDENTITY_FN = (val) => val;
- exports.isWindows = platform$1 === "win32";
- exports.isMacos = platform$1 === "darwin";
- exports.isLinux = platform$1 === "linux";
- exports.isIBMi = os$2.type() === "OS400";
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/chokidar@3.6.0_patch_hash=8a4f9e2b397e6034b91a0508faae3cecb97f222313faa129d7cb0eb71e9d0e84/node_modules/chokidar/lib/nodefs-handler.js
-var require_nodefs_handler = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const fs$8 = __require("fs");
- const sysPath$2 = __require("path");
- const { promisify: promisify$3 } = __require("util");
- const isBinaryPath = require_is_binary_path();
- const { isWindows: isWindows$3, isLinux, EMPTY_FN: EMPTY_FN$2, EMPTY_STR: EMPTY_STR$1, KEY_LISTENERS, KEY_ERR, KEY_RAW, HANDLER_KEYS, EV_CHANGE: EV_CHANGE$2, EV_ADD: EV_ADD$2, EV_ADD_DIR: EV_ADD_DIR$2, EV_ERROR: EV_ERROR$2, STR_DATA: STR_DATA$1, STR_END: STR_END$2, BRACE_START: BRACE_START$1, STAR } = require_constants$1();
- const THROTTLE_MODE_WATCH = "watch";
- const open$1 = promisify$3(fs$8.open);
- const stat$2 = promisify$3(fs$8.stat);
- const lstat$1 = promisify$3(fs$8.lstat);
- const close = promisify$3(fs$8.close);
- const fsrealpath = promisify$3(fs$8.realpath);
- const statMethods$1 = {
- lstat: lstat$1,
- stat: stat$2
- };
- const foreach = (val, fn) => {
- if (val instanceof Set) val.forEach(fn);
- else fn(val);
- };
- const addAndConvert = (main, prop, item) => {
- let container = main[prop];
- if (!(container instanceof Set)) main[prop] = container = new Set([container]);
- container.add(item);
- };
- const clearItem = (cont) => (key) => {
- const set = cont[key];
- if (set instanceof Set) set.clear();
- else delete cont[key];
- };
- const delFromSet = (main, prop, item) => {
- const container = main[prop];
- if (container instanceof Set) container.delete(item);
- else if (container === item) delete main[prop];
- };
- const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
- /**
- * @typedef {String} Path
- */
- /**
- * @typedef {Object} FsWatchContainer
- * @property {Set} listeners
- * @property {Set} errHandlers
- * @property {Set} rawEmitters
- * @property {fs.FSWatcher=} watcher
- * @property {Boolean=} watcherUnusable
- */
- /**
- * @type {Map<String,FsWatchContainer>}
- */
- const FsWatchInstances = /* @__PURE__ */ new Map();
- /**
- * Instantiates the fs_watch interface
- * @param {String} path to be watched
- * @param {Object} options to be passed to fs_watch
- * @param {Function} listener main event handler
- * @param {Function} errHandler emits info about errors
- * @param {Function} emitRaw emits raw event data
- * @returns {fs.FSWatcher} new fsevents instance
- */
- function createFsWatchInstance(path$13, options$1, listener$1, errHandler, emitRaw) {
- const handleEvent = (rawEvent, evPath) => {
- listener$1(path$13);
- emitRaw(rawEvent, evPath, { watchedPath: path$13 });
- if (evPath && path$13 !== evPath) fsWatchBroadcast(sysPath$2.resolve(path$13, evPath), KEY_LISTENERS, sysPath$2.join(path$13, evPath));
- };
- try {
- return fs$8.watch(path$13, options$1, handleEvent);
- } catch (error$1) {
- errHandler(error$1);
- }
- }
- /**
- * Helper for passing fs_watch event data to a collection of listeners
- * @param {Path} fullPath absolute path bound to fs_watch instance
- * @param {String} type listener type
- * @param {*=} val1 arguments to be passed to listeners
- * @param {*=} val2
- * @param {*=} val3
- */
- const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
- const cont = FsWatchInstances.get(fullPath);
- if (!cont) return;
- foreach(cont[type], (listener$1) => {
- listener$1(val1, val2, val3);
- });
- };
- /**
- * Instantiates the fs_watch interface or binds listeners
- * to an existing one covering the same file system entry
- * @param {String} path
- * @param {String} fullPath absolute path
- * @param {Object} options to be passed to fs_watch
- * @param {Object} handlers container for event listener functions
- */
- const setFsWatchListener = (path$13, fullPath, options$1, handlers) => {
- const { listener: listener$1, errHandler, rawEmitter } = handlers;
- let cont = FsWatchInstances.get(fullPath);
- /** @type {fs.FSWatcher=} */
- let watcher;
- if (!options$1.persistent) {
- watcher = createFsWatchInstance(path$13, options$1, listener$1, errHandler, rawEmitter);
- return watcher.close.bind(watcher);
- }
- if (cont) {
- addAndConvert(cont, KEY_LISTENERS, listener$1);
- addAndConvert(cont, KEY_ERR, errHandler);
- addAndConvert(cont, KEY_RAW, rawEmitter);
- } else {
- watcher = createFsWatchInstance(path$13, options$1, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, fsWatchBroadcast.bind(null, fullPath, KEY_RAW));
- if (!watcher) return;
- watcher.on(EV_ERROR$2, async (error$1) => {
- const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
- cont.watcherUnusable = true;
- if (isWindows$3 && error$1.code === "EPERM") try {
- await close(await open$1(path$13, "r"));
- broadcastErr(error$1);
- } catch (err$2) {}
- else broadcastErr(error$1);
- });
- cont = {
- listeners: listener$1,
- errHandlers: errHandler,
- rawEmitters: rawEmitter,
- watcher
- };
- FsWatchInstances.set(fullPath, cont);
- }
- return () => {
- delFromSet(cont, KEY_LISTENERS, listener$1);
- delFromSet(cont, KEY_ERR, errHandler);
- delFromSet(cont, KEY_RAW, rawEmitter);
- if (isEmptySet(cont.listeners)) {
- cont.watcher.close();
- FsWatchInstances.delete(fullPath);
- HANDLER_KEYS.forEach(clearItem(cont));
- cont.watcher = void 0;
- Object.freeze(cont);
- }
- };
- };
- const FsWatchFileInstances = /* @__PURE__ */ new Map();
- /**
- * Instantiates the fs_watchFile interface or binds listeners
- * to an existing one covering the same file system entry
- * @param {String} path to be watched
- * @param {String} fullPath absolute path
- * @param {Object} options options to be passed to fs_watchFile
- * @param {Object} handlers container for event listener functions
- * @returns {Function} closer
- */
- const setFsWatchFileListener = (path$13, fullPath, options$1, handlers) => {
- const { listener: listener$1, rawEmitter } = handlers;
- let cont = FsWatchFileInstances.get(fullPath);
- const copts = cont && cont.options;
- if (copts && (copts.persistent < options$1.persistent || copts.interval > options$1.interval)) {
- fs$8.unwatchFile(fullPath);
- cont = void 0;
- }
- if (cont) {
- addAndConvert(cont, KEY_LISTENERS, listener$1);
- addAndConvert(cont, KEY_RAW, rawEmitter);
- } else {
- cont = {
- listeners: listener$1,
- rawEmitters: rawEmitter,
- options: options$1,
- watcher: fs$8.watchFile(fullPath, options$1, (curr, prev) => {
- foreach(cont.rawEmitters, (rawEmitter$1) => {
- rawEmitter$1(EV_CHANGE$2, fullPath, {
- curr,
- prev
- });
- });
- const currmtime = curr.mtimeMs;
- if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) foreach(cont.listeners, (listener$2) => listener$2(path$13, curr));
- })
- };
- FsWatchFileInstances.set(fullPath, cont);
- }
- return () => {
- delFromSet(cont, KEY_LISTENERS, listener$1);
- delFromSet(cont, KEY_RAW, rawEmitter);
- if (isEmptySet(cont.listeners)) {
- FsWatchFileInstances.delete(fullPath);
- fs$8.unwatchFile(fullPath);
- cont.options = cont.watcher = void 0;
- Object.freeze(cont);
- }
- };
- };
- /**
- * @mixin
- */
- var NodeFsHandler$1 = class {
- /**
- * @param {import("../index").FSWatcher} fsW
- */
- constructor(fsW) {
- this.fsw = fsW;
- this._boundHandleError = (error$1) => fsW._handleError(error$1);
- }
- /**
- * Watch file for changes with fs_watchFile or fs_watch.
- * @param {String} path to file or dir
- * @param {Function} listener on fs change
- * @returns {Function} closer for the watcher instance
- */
- _watchWithNodeFs(path$13, listener$1) {
- const opts = this.fsw.options;
- const directory = sysPath$2.dirname(path$13);
- const basename$3 = sysPath$2.basename(path$13);
- this.fsw._getWatchedDir(directory).add(basename$3);
- const absolutePath = sysPath$2.resolve(path$13);
- const options$1 = { persistent: opts.persistent };
- if (!listener$1) listener$1 = EMPTY_FN$2;
- let closer;
- if (opts.usePolling) {
- options$1.interval = opts.enableBinaryInterval && isBinaryPath(basename$3) ? opts.binaryInterval : opts.interval;
- closer = setFsWatchFileListener(path$13, absolutePath, options$1, {
- listener: listener$1,
- rawEmitter: this.fsw._emitRaw
- });
- } else closer = setFsWatchListener(path$13, absolutePath, options$1, {
- listener: listener$1,
- errHandler: this._boundHandleError,
- rawEmitter: this.fsw._emitRaw
- });
- return closer;
- }
- /**
- * Watch a file and emit add event if warranted.
- * @param {Path} file Path
- * @param {fs.Stats} stats result of fs_stat
- * @param {Boolean} initialAdd was the file added at watch instantiation?
- * @returns {Function} closer for the watcher instance
- */
- _handleFile(file, stats, initialAdd) {
- if (this.fsw.closed) return;
- const dirname$3 = sysPath$2.dirname(file);
- const basename$3 = sysPath$2.basename(file);
- const parent = this.fsw._getWatchedDir(dirname$3);
- let prevStats = stats;
- if (parent.has(basename$3)) return;
- const listener$1 = async (path$13, newStats) => {
- if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
- if (!newStats || newStats.mtimeMs === 0) try {
- const newStats$1 = await stat$2(file);
- if (this.fsw.closed) return;
- const at = newStats$1.atimeMs;
- const mt = newStats$1.mtimeMs;
- if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV_CHANGE$2, file, newStats$1);
- if (isLinux && prevStats.ino !== newStats$1.ino) {
- this.fsw._closeFile(path$13);
- prevStats = newStats$1;
- this.fsw._addPathCloser(path$13, this._watchWithNodeFs(file, listener$1));
- } else prevStats = newStats$1;
- } catch (error$1) {
- this.fsw._remove(dirname$3, basename$3);
- }
- else if (parent.has(basename$3)) {
- const at = newStats.atimeMs;
- const mt = newStats.mtimeMs;
- if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV_CHANGE$2, file, newStats);
- prevStats = newStats;
- }
- };
- const closer = this._watchWithNodeFs(file, listener$1);
- if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
- if (!this.fsw._throttle(EV_ADD$2, file, 0)) return;
- this.fsw._emit(EV_ADD$2, file, stats);
- }
- return closer;
- }
- /**
- * Handle symlinks encountered while reading a dir.
- * @param {Object} entry returned by readdirp
- * @param {String} directory path of dir being read
- * @param {String} path of this item
- * @param {String} item basename of this item
- * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
- */
- async _handleSymlink(entry, directory, path$13, item) {
- if (this.fsw.closed) return;
- const full = entry.fullPath;
- const dir = this.fsw._getWatchedDir(directory);
- if (!this.fsw.options.followSymlinks) {
- this.fsw._incrReadyCount();
- let linkPath;
- try {
- linkPath = await fsrealpath(path$13);
- } catch (e$1) {
- this.fsw._emitReady();
- return true;
- }
- if (this.fsw.closed) return;
- if (dir.has(item)) {
- if (this.fsw._symlinkPaths.get(full) !== linkPath) {
- this.fsw._symlinkPaths.set(full, linkPath);
- this.fsw._emit(EV_CHANGE$2, path$13, entry.stats);
- }
- } else {
- dir.add(item);
- this.fsw._symlinkPaths.set(full, linkPath);
- this.fsw._emit(EV_ADD$2, path$13, entry.stats);
- }
- this.fsw._emitReady();
- return true;
- }
- if (this.fsw._symlinkPaths.has(full)) return true;
- this.fsw._symlinkPaths.set(full, true);
- }
- _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
- directory = sysPath$2.join(directory, EMPTY_STR$1);
- if (!wh.hasGlob) {
- throttler = this.fsw._throttle("readdir", directory, 1e3);
- if (!throttler) return;
- }
- const previous = this.fsw._getWatchedDir(wh.path);
- const current = /* @__PURE__ */ new Set();
- let stream$2 = this.fsw._readdirp(directory, {
- fileFilter: (entry) => wh.filterPath(entry),
- directoryFilter: (entry) => wh.filterDir(entry),
- depth: 0
- }).on(STR_DATA$1, async (entry) => {
- if (this.fsw.closed) {
- stream$2 = void 0;
- return;
- }
- const item = entry.path;
- let path$13 = sysPath$2.join(directory, item);
- current.add(item);
- if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path$13, item)) return;
- if (this.fsw.closed) {
- stream$2 = void 0;
- return;
- }
- if (item === target || !target && !previous.has(item)) {
- this.fsw._incrReadyCount();
- path$13 = sysPath$2.join(dir, sysPath$2.relative(dir, path$13));
- this._addToNodeFs(path$13, initialAdd, wh, depth + 1);
- }
- }).on(EV_ERROR$2, this._boundHandleError);
- return new Promise((resolve$4) => stream$2.once(STR_END$2, () => {
- if (this.fsw.closed) {
- stream$2 = void 0;
- return;
- }
- const wasThrottled = throttler ? throttler.clear() : false;
- resolve$4();
- previous.getChildren().filter((item) => {
- return item !== directory && !current.has(item) && (!wh.hasGlob || wh.filterPath({ fullPath: sysPath$2.resolve(directory, item) }));
- }).forEach((item) => {
- this.fsw._remove(directory, item);
- });
- stream$2 = void 0;
- if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
- }));
- }
- /**
- * Read directory to add / remove files from `@watched` list and re-read it on change.
- * @param {String} dir fs path
- * @param {fs.Stats} stats
- * @param {Boolean} initialAdd
- * @param {Number} depth relative to user-supplied path
- * @param {String} target child path targeted for watch
- * @param {Object} wh Common watch helpers for this path
- * @param {String} realpath
- * @returns {Promise<Function>} closer for the watcher instance.
- */
- async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath$2) {
- const parentDir$1 = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
- const tracked = parentDir$1.has(sysPath$2.basename(dir));
- if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
- if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats);
- }
- parentDir$1.add(sysPath$2.basename(dir));
- this.fsw._getWatchedDir(dir);
- let throttler;
- let closer;
- const oDepth = this.fsw.options.depth;
- if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath$2)) {
- if (!target) {
- await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
- if (this.fsw.closed) return;
- }
- closer = this._watchWithNodeFs(dir, (dirPath, stats$1) => {
- if (stats$1 && stats$1.mtimeMs === 0) return;
- this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
- });
- }
- return closer;
- }
- /**
- * Handle added file, directory, or glob pattern.
- * Delegates call to _handleFile / _handleDir after checks.
- * @param {String} path to file or ir
- * @param {Boolean} initialAdd was the file added at watch instantiation?
- * @param {Object} priorWh depth relative to user-supplied path
- * @param {Number} depth Child path actually targeted for watch
- * @param {String=} target Child path actually targeted for watch
- * @returns {Promise}
- */
- async _addToNodeFs(path$13, initialAdd, priorWh, depth, target) {
- const ready = this.fsw._emitReady;
- if (this.fsw._isIgnored(path$13) || this.fsw.closed) {
- ready();
- return false;
- }
- const wh = this.fsw._getWatchHelpers(path$13, depth);
- if (!wh.hasGlob && priorWh) {
- wh.hasGlob = priorWh.hasGlob;
- wh.globFilter = priorWh.globFilter;
- wh.filterPath = (entry) => priorWh.filterPath(entry);
- wh.filterDir = (entry) => priorWh.filterDir(entry);
- }
- try {
- const stats = await statMethods$1[wh.statMethod](wh.watchPath);
- if (this.fsw.closed) return;
- if (this.fsw._isIgnored(wh.watchPath, stats)) {
- ready();
- return false;
- }
- const follow = this.fsw.options.followSymlinks && !path$13.includes(STAR) && !path$13.includes(BRACE_START$1);
- let closer;
- if (stats.isDirectory()) {
- const absPath = sysPath$2.resolve(path$13);
- const targetPath = follow ? await fsrealpath(path$13) : path$13;
- if (this.fsw.closed) return;
- closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
- if (this.fsw.closed) return;
- if (absPath !== targetPath && targetPath !== void 0) this.fsw._symlinkPaths.set(absPath, targetPath);
- } else if (stats.isSymbolicLink()) {
- const targetPath = follow ? await fsrealpath(path$13) : path$13;
- if (this.fsw.closed) return;
- const parent = sysPath$2.dirname(wh.watchPath);
- this.fsw._getWatchedDir(parent).add(wh.watchPath);
- this.fsw._emit(EV_ADD$2, wh.watchPath, stats);
- closer = await this._handleDir(parent, stats, initialAdd, depth, path$13, wh, targetPath);
- if (this.fsw.closed) return;
- if (targetPath !== void 0) this.fsw._symlinkPaths.set(sysPath$2.resolve(path$13), targetPath);
- } else closer = this._handleFile(wh.watchPath, stats, initialAdd);
- ready();
- this.fsw._addPathCloser(path$13, closer);
- return false;
- } catch (error$1) {
- if (this.fsw._handleError(error$1)) {
- ready();
- return path$13;
- }
- }
- }
- };
- module.exports = NodeFsHandler$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/chokidar@3.6.0_patch_hash=8a4f9e2b397e6034b91a0508faae3cecb97f222313faa129d7cb0eb71e9d0e84/node_modules/chokidar/lib/fsevents-handler.js
-var require_fsevents_handler = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const fs$7 = __require("fs");
- const sysPath$1 = __require("path");
- const { promisify: promisify$2 } = __require("util");
- let fsevents;
- try {
- fsevents = __require("fsevents");
- } catch (error$1) {
- if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error$1);
- }
- if (fsevents) {
- const mtch = process.version.match(/v(\d+)\.(\d+)/);
- if (mtch && mtch[1] && mtch[2]) {
- if (Number.parseInt(mtch[1], 10) === 8 && Number.parseInt(mtch[2], 10) < 16) fsevents = void 0;
- }
- }
- const { EV_ADD: EV_ADD$1, EV_CHANGE: EV_CHANGE$1, EV_ADD_DIR: EV_ADD_DIR$1, EV_UNLINK: EV_UNLINK$1, EV_ERROR: EV_ERROR$1, STR_DATA, STR_END: STR_END$1, FSEVENT_CREATED, FSEVENT_MODIFIED, FSEVENT_DELETED, FSEVENT_MOVED, FSEVENT_UNKNOWN, FSEVENT_FLAG_MUST_SCAN_SUBDIRS, FSEVENT_TYPE_FILE, FSEVENT_TYPE_DIRECTORY, FSEVENT_TYPE_SYMLINK, ROOT_GLOBSTAR, DIR_SUFFIX, DOT_SLASH, FUNCTION_TYPE: FUNCTION_TYPE$1, EMPTY_FN: EMPTY_FN$1, IDENTITY_FN } = require_constants$1();
- const Depth = (value$1) => isNaN(value$1) ? {} : { depth: value$1 };
- const stat$1 = promisify$2(fs$7.stat);
- const lstat = promisify$2(fs$7.lstat);
- const realpath = promisify$2(fs$7.realpath);
- const statMethods = {
- stat: stat$1,
- lstat
- };
- /**
- * @typedef {String} Path
- */
- /**
- * @typedef {Object} FsEventsWatchContainer
- * @property {Set<Function>} listeners
- * @property {Function} rawEmitter
- * @property {{stop: Function}} watcher
- */
- /**
- * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
- * @type {Map<Path,FsEventsWatchContainer>}
- */
- const FSEventsWatchers = /* @__PURE__ */ new Map();
- const consolidateThreshhold = 10;
- const wrongEventFlags = new Set([
- 69888,
- 70400,
- 71424,
- 72704,
- 73472,
- 131328,
- 131840,
- 262912
- ]);
- /**
- * Instantiates the fsevents interface
- * @param {Path} path path to be watched
- * @param {Function} callback called when fsevents is bound and ready
- * @returns {{stop: Function}} new fsevents instance
- */
- const createFSEventsInstance = (path$13, callback) => {
- return { stop: fsevents.watch(path$13, callback) };
- };
- /**
- * Instantiates the fsevents interface or binds listeners to an existing one covering
- * the same file tree.
- * @param {Path} path - to be watched
- * @param {Path} realPath - real path for symlinks
- * @param {Function} listener - called when fsevents emits events
- * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
- * @returns {Function} closer
- */
- function setFSEventsListener(path$13, realPath, listener$1, rawEmitter) {
- let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath;
- const parentPath = sysPath$1.dirname(watchPath);
- let cont = FSEventsWatchers.get(watchPath);
- if (couldConsolidate(parentPath)) watchPath = parentPath;
- const resolvedPath = sysPath$1.resolve(path$13);
- const hasSymlink = resolvedPath !== realPath;
- const filteredListener = (fullPath, flags, info) => {
- if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
- if (fullPath === resolvedPath || !fullPath.indexOf(resolvedPath + sysPath$1.sep)) listener$1(fullPath, flags, info);
- };
- let watchedParent = false;
- for (const watchedPath of FSEventsWatchers.keys()) if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
- watchPath = watchedPath;
- cont = FSEventsWatchers.get(watchPath);
- watchedParent = true;
- break;
- }
- if (cont || watchedParent) cont.listeners.add(filteredListener);
- else {
- cont = {
- listeners: new Set([filteredListener]),
- rawEmitter,
- watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
- if (!cont.listeners.size) return;
- if (flags & FSEVENT_FLAG_MUST_SCAN_SUBDIRS) return;
- const info = fsevents.getInfo(fullPath, flags);
- cont.listeners.forEach((list) => {
- list(fullPath, flags, info);
- });
- cont.rawEmitter(info.event, fullPath, info);
- })
- };
- FSEventsWatchers.set(watchPath, cont);
- }
- return () => {
- const lst = cont.listeners;
- lst.delete(filteredListener);
- if (!lst.size) {
- FSEventsWatchers.delete(watchPath);
- if (cont.watcher) return cont.watcher.stop().then(() => {
- cont.rawEmitter = cont.watcher = void 0;
- Object.freeze(cont);
- });
- }
- };
- }
- const couldConsolidate = (path$13) => {
- let count = 0;
- for (const watchPath of FSEventsWatchers.keys()) if (watchPath.indexOf(path$13) === 0) {
- count++;
- if (count >= consolidateThreshhold) return true;
- }
- return false;
- };
- const canUse = () => fsevents && FSEventsWatchers.size < 128;
- const calcDepth = (path$13, root) => {
- let i$1 = 0;
- while (!path$13.indexOf(root) && (path$13 = sysPath$1.dirname(path$13)) !== root) i$1++;
- return i$1;
- };
- const sameTypes = (info, stats) => info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() || info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() || info.type === FSEVENT_TYPE_FILE && stats.isFile();
- /**
- * @mixin
- */
- var FsEventsHandler$1 = class {
- /**
- * @param {import('../index').FSWatcher} fsw
- */
- constructor(fsw) {
- this.fsw = fsw;
- }
- checkIgnored(path$13, stats) {
- const ipaths = this.fsw._ignoredPaths;
- if (this.fsw._isIgnored(path$13, stats)) {
- ipaths.add(path$13);
- if (stats && stats.isDirectory()) ipaths.add(path$13 + ROOT_GLOBSTAR);
- return true;
- }
- ipaths.delete(path$13);
- ipaths.delete(path$13 + ROOT_GLOBSTAR);
- }
- addOrChange(path$13, fullPath, realPath, parent, watchedDir, item, info, opts) {
- const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;
- this.handleEvent(event, path$13, fullPath, realPath, parent, watchedDir, item, info, opts);
- }
- async checkExists(path$13, fullPath, realPath, parent, watchedDir, item, info, opts) {
- try {
- const stats = await stat$1(path$13);
- if (this.fsw.closed) return;
- if (sameTypes(info, stats)) this.addOrChange(path$13, fullPath, realPath, parent, watchedDir, item, info, opts);
- else this.handleEvent(EV_UNLINK$1, path$13, fullPath, realPath, parent, watchedDir, item, info, opts);
- } catch (error$1) {
- if (error$1.code === "EACCES") this.addOrChange(path$13, fullPath, realPath, parent, watchedDir, item, info, opts);
- else this.handleEvent(EV_UNLINK$1, path$13, fullPath, realPath, parent, watchedDir, item, info, opts);
- }
- }
- handleEvent(event, path$13, fullPath, realPath, parent, watchedDir, item, info, opts) {
- if (this.fsw.closed || this.checkIgnored(path$13)) return;
- if (event === EV_UNLINK$1) {
- const isDirectory$2 = info.type === FSEVENT_TYPE_DIRECTORY;
- if (isDirectory$2 || watchedDir.has(item)) this.fsw._remove(parent, item, isDirectory$2);
- } else {
- if (event === EV_ADD$1) {
- if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path$13);
- if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
- const curDepth = opts.depth === void 0 ? void 0 : calcDepth(fullPath, realPath) + 1;
- return this._addToFsEvents(path$13, false, true, curDepth);
- }
- this.fsw._getWatchedDir(parent).add(item);
- }
- /**
- * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
- */
- const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
- this.fsw._emit(eventName, path$13);
- if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path$13, false, true);
- }
- }
- /**
- * Handle symlinks encountered during directory scan
- * @param {String} watchPath - file/dir path to be watched with fsevents
- * @param {String} realPath - real path (in case of symlinks)
- * @param {Function} transform - path transformer
- * @param {Function} globFilter - path filter in case a glob pattern was provided
- * @returns {Function} closer for the watcher instance
- */
- _watchWithFsEvents(watchPath, realPath, transform$2, globFilter) {
- if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
- const opts = this.fsw.options;
- const watchCallback = async (fullPath, flags, info) => {
- if (this.fsw.closed || this.fsw._isIgnored(fullPath)) return;
- if (opts.depth !== void 0 && calcDepth(fullPath, realPath) > opts.depth) return;
- const path$13 = transform$2(sysPath$1.join(watchPath, sysPath$1.relative(watchPath, fullPath)));
- if (globFilter && !globFilter(path$13)) return;
- const parent = sysPath$1.dirname(path$13);
- const item = sysPath$1.basename(path$13);
- const watchedDir = this.fsw._getWatchedDir(info.type === FSEVENT_TYPE_DIRECTORY ? path$13 : parent);
- if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) if (typeof opts.ignored === FUNCTION_TYPE$1) {
- let stats;
- try {
- stats = await stat$1(path$13);
- } catch (error$1) {}
- if (this.fsw.closed) return;
- if (this.checkIgnored(path$13, stats)) return;
- if (sameTypes(info, stats)) this.addOrChange(path$13, fullPath, realPath, parent, watchedDir, item, info, opts);
- else this.handleEvent(EV_UNLINK$1, path$13, fullPath, realPath, parent, watchedDir, item, info, opts);
- } else this.checkExists(path$13, fullPath, realPath, parent, watchedDir, item, info, opts);
- else switch (info.event) {
- case FSEVENT_CREATED:
- case FSEVENT_MODIFIED: return this.addOrChange(path$13, fullPath, realPath, parent, watchedDir, item, info, opts);
- case FSEVENT_DELETED:
- case FSEVENT_MOVED: return this.checkExists(path$13, fullPath, realPath, parent, watchedDir, item, info, opts);
- }
- };
- const closer = setFSEventsListener(watchPath, realPath, watchCallback, this.fsw._emitRaw);
- this.fsw._emitReady();
- return closer;
- }
- /**
- * Handle symlinks encountered during directory scan
- * @param {String} linkPath path to symlink
- * @param {String} fullPath absolute path to the symlink
- * @param {Function} transform pre-existing path transformer
- * @param {Number} curDepth level of subdirectories traversed to where symlink is
- * @returns {Promise<void>}
- */
- async _handleFsEventsSymlink(linkPath, fullPath, transform$2, curDepth) {
- if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
- this.fsw._symlinkPaths.set(fullPath, true);
- this.fsw._incrReadyCount();
- try {
- const linkTarget = await realpath(linkPath);
- if (this.fsw.closed) return;
- if (this.fsw._isIgnored(linkTarget)) return this.fsw._emitReady();
- this.fsw._incrReadyCount();
- this._addToFsEvents(linkTarget || linkPath, (path$13) => {
- let aliasedPath = linkPath;
- if (linkTarget && linkTarget !== DOT_SLASH) aliasedPath = path$13.replace(linkTarget, linkPath);
- else if (path$13 !== DOT_SLASH) aliasedPath = sysPath$1.join(linkPath, path$13);
- return transform$2(aliasedPath);
- }, false, curDepth);
- } catch (error$1) {
- if (this.fsw._handleError(error$1)) return this.fsw._emitReady();
- }
- }
- /**
- *
- * @param {Path} newPath
- * @param {fs.Stats} stats
- */
- emitAdd(newPath, stats, processPath, opts, forceAdd) {
- const pp = processPath(newPath);
- const isDir = stats.isDirectory();
- const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
- const base = sysPath$1.basename(pp);
- if (isDir) this.fsw._getWatchedDir(pp);
- if (dirObj.has(base)) return;
- dirObj.add(base);
- if (!opts.ignoreInitial || forceAdd === true) this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);
- }
- initWatch(realPath, path$13, wh, processPath) {
- if (this.fsw.closed) return;
- const closer = this._watchWithFsEvents(wh.watchPath, sysPath$1.resolve(realPath || wh.watchPath), processPath, wh.globFilter);
- this.fsw._addPathCloser(path$13, closer);
- }
- /**
- * Handle added path with fsevents
- * @param {String} path file/dir path or glob pattern
- * @param {Function|Boolean=} transform converts working path to what the user expects
- * @param {Boolean=} forceAdd ensure add is emitted
- * @param {Number=} priorDepth Level of subdirectories already traversed.
- * @returns {Promise<void>}
- */
- async _addToFsEvents(path$13, transform$2, forceAdd, priorDepth) {
- if (this.fsw.closed) return;
- const opts = this.fsw.options;
- const processPath = typeof transform$2 === FUNCTION_TYPE$1 ? transform$2 : IDENTITY_FN;
- const wh = this.fsw._getWatchHelpers(path$13);
- try {
- const stats = await statMethods[wh.statMethod](wh.watchPath);
- if (this.fsw.closed) return;
- if (this.fsw._isIgnored(wh.watchPath, stats)) throw null;
- if (stats.isDirectory()) {
- if (!wh.globFilter) this.emitAdd(processPath(path$13), stats, processPath, opts, forceAdd);
- if (priorDepth && priorDepth > opts.depth) return;
- this.fsw._readdirp(wh.watchPath, {
- fileFilter: (entry) => wh.filterPath(entry),
- directoryFilter: (entry) => wh.filterDir(entry),
- ...Depth(opts.depth - (priorDepth || 0))
- }).on(STR_DATA, (entry) => {
- if (this.fsw.closed) return;
- if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
- const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
- const { fullPath } = entry;
- if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
- const curDepth = opts.depth === void 0 ? void 0 : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
- this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
- } else this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
- }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {
- this.fsw._emitReady();
- });
- } else {
- this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
- this.fsw._emitReady();
- }
- } catch (error$1) {
- if (!error$1 || this.fsw._handleError(error$1)) {
- this.fsw._emitReady();
- this.fsw._emitReady();
- }
- }
- if (opts.persistent && forceAdd !== true) if (typeof transform$2 === FUNCTION_TYPE$1) this.initWatch(void 0, path$13, wh, processPath);
- else {
- let realPath;
- try {
- realPath = await realpath(wh.watchPath);
- } catch (e$1) {}
- this.initWatch(realPath, path$13, wh, processPath);
- }
- }
- };
- module.exports = FsEventsHandler$1;
- module.exports.canUse = canUse;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/chokidar@3.6.0_patch_hash=8a4f9e2b397e6034b91a0508faae3cecb97f222313faa129d7cb0eb71e9d0e84/node_modules/chokidar/index.js
-var require_chokidar = /* @__PURE__ */ __commonJSMin(((exports) => {
- const { EventEmitter: EventEmitter$3 } = __require("events");
- const fs$6 = __require("fs");
- const sysPath = __require("path");
- const { promisify: promisify$1 } = __require("util");
- const readdirp = require_readdirp();
- const anymatch = require_anymatch().default;
- const globParent = require_glob_parent();
- const isGlob = require_is_glob();
- const braces = require_braces();
- const normalizePath$1 = require_normalize_path();
- const NodeFsHandler = require_nodefs_handler();
- const FsEventsHandler = require_fsevents_handler();
- const { EV_ALL, EV_READY, EV_ADD, EV_CHANGE, EV_UNLINK, EV_ADD_DIR, EV_UNLINK_DIR, EV_RAW, EV_ERROR, STR_CLOSE, STR_END, BACK_SLASH_RE, DOUBLE_SLASH_RE, SLASH_OR_BACK_SLASH_RE, DOT_RE, REPLACER_RE, SLASH, SLASH_SLASH, BRACE_START, BANG, ONE_DOT, TWO_DOTS, GLOBSTAR, SLASH_GLOBSTAR, ANYMATCH_OPTS, STRING_TYPE, FUNCTION_TYPE, EMPTY_STR, EMPTY_FN, isWindows: isWindows$2, isMacos, isIBMi } = require_constants$1();
- const stat = promisify$1(fs$6.stat);
- const readdir = promisify$1(fs$6.readdir);
- /**
- * @typedef {String} Path
- * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
- * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
- */
- /**
- *
- * @typedef {Object} WatchHelpers
- * @property {Boolean} followSymlinks
- * @property {'stat'|'lstat'} statMethod
- * @property {Path} path
- * @property {Path} watchPath
- * @property {Function} entryPath
- * @property {Boolean} hasGlob
- * @property {Object} globFilter
- * @property {Function} filterPath
- * @property {Function} filterDir
- */
- const arrify = (value$1 = []) => Array.isArray(value$1) ? value$1 : [value$1];
- const flatten = (list, result = []) => {
- list.forEach((item) => {
- if (Array.isArray(item)) flatten(item, result);
- else result.push(item);
- });
- return result;
- };
- const unifyPaths = (paths_) => {
- /**
- * @type {Array<String>}
- */
- const paths = flatten(arrify(paths_));
- if (!paths.every((p) => typeof p === STRING_TYPE)) throw new TypeError(`Non-string provided as watch path: ${paths}`);
- return paths.map(normalizePathToUnix);
- };
- const toUnix = (string) => {
- let str = string.replace(BACK_SLASH_RE, SLASH);
- let prepend = false;
- if (str.startsWith(SLASH_SLASH)) prepend = true;
- while (str.match(DOUBLE_SLASH_RE)) str = str.replace(DOUBLE_SLASH_RE, SLASH);
- if (prepend) str = SLASH + str;
- return str;
- };
- const normalizePathToUnix = (path$13) => toUnix(sysPath.normalize(toUnix(path$13)));
- const normalizeIgnored = (cwd = EMPTY_STR) => (path$13) => {
- if (typeof path$13 !== STRING_TYPE) return path$13;
- return normalizePathToUnix(sysPath.isAbsolute(path$13) ? path$13 : sysPath.join(cwd, path$13));
- };
- const getAbsolutePath = (path$13, cwd) => {
- if (sysPath.isAbsolute(path$13)) return path$13;
- if (path$13.startsWith(BANG)) return BANG + sysPath.join(cwd, path$13.slice(1));
- return sysPath.join(cwd, path$13);
- };
- const undef = (opts, key) => opts[key] === void 0;
- /**
- * Directory entry.
- * @property {Path} path
- * @property {Set<Path>} items
- */
- var DirEntry = class {
- /**
- * @param {Path} dir
- * @param {Function} removeWatcher
- */
- constructor(dir, removeWatcher) {
- this.path = dir;
- this._removeWatcher = removeWatcher;
- /** @type {Set<Path>} */
- this.items = /* @__PURE__ */ new Set();
- }
- add(item) {
- const { items } = this;
- if (!items) return;
- if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
- }
- async remove(item) {
- const { items } = this;
- if (!items) return;
- items.delete(item);
- if (items.size > 0) return;
- const dir = this.path;
- try {
- await readdir(dir);
- } catch (err$2) {
- if (this._removeWatcher) this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
- }
- }
- has(item) {
- const { items } = this;
- if (!items) return;
- return items.has(item);
- }
- /**
- * @returns {Array<String>}
- */
- getChildren() {
- const { items } = this;
- if (!items) return;
- return [...items.values()];
- }
- dispose() {
- this.items.clear();
- delete this.path;
- delete this._removeWatcher;
- delete this.items;
- Object.freeze(this);
- }
- };
- const STAT_METHOD_F = "stat";
- const STAT_METHOD_L = "lstat";
- var WatchHelper = class {
- constructor(path$13, watchPath, follow, fsw) {
- this.fsw = fsw;
- this.path = path$13 = path$13.replace(REPLACER_RE, EMPTY_STR);
- this.watchPath = watchPath;
- this.fullWatchPath = sysPath.resolve(watchPath);
- this.hasGlob = watchPath !== path$13;
- /** @type {object|boolean} */
- if (path$13 === EMPTY_STR) this.hasGlob = false;
- this.globSymlink = this.hasGlob && follow ? void 0 : false;
- this.globFilter = this.hasGlob ? anymatch(path$13, void 0, ANYMATCH_OPTS) : false;
- this.dirParts = this.getDirParts(path$13);
- this.dirParts.forEach((parts) => {
- if (parts.length > 1) parts.pop();
- });
- this.followSymlinks = follow;
- this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
- }
- checkGlobSymlink(entry) {
- if (this.globSymlink === void 0) this.globSymlink = entry.fullParentDir === this.fullWatchPath ? false : {
- realPath: entry.fullParentDir,
- linkPath: this.fullWatchPath
- };
- if (this.globSymlink) return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
- return entry.fullPath;
- }
- entryPath(entry) {
- return sysPath.join(this.watchPath, sysPath.relative(this.watchPath, this.checkGlobSymlink(entry)));
- }
- filterPath(entry) {
- const { stats } = entry;
- if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
- const resolvedPath = this.entryPath(entry);
- return (this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ? this.globFilter(resolvedPath) : true) && this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
- }
- getDirParts(path$13) {
- if (!this.hasGlob) return [];
- const parts = [];
- (path$13.includes(BRACE_START) ? braces.expand(path$13) : [path$13]).forEach((path$14) => {
- parts.push(sysPath.relative(this.watchPath, path$14).split(SLASH_OR_BACK_SLASH_RE));
- });
- return parts;
- }
- filterDir(entry) {
- if (this.hasGlob) {
- const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
- let globstar = false;
- this.unmatchedGlob = !this.dirParts.some((parts) => {
- return parts.every((part, i$1) => {
- if (part === GLOBSTAR) globstar = true;
- return globstar || !entryParts[0][i$1] || anymatch(part, entryParts[0][i$1], ANYMATCH_OPTS);
- });
- });
- }
- return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
- }
- };
- /**
- * Watches files & directories for changes. Emitted events:
- * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
- *
- * new FSWatcher()
- * .add(directories)
- * .on('add', path => log('File', path, 'was added'))
- */
- var FSWatcher = class extends EventEmitter$3 {
- constructor(_opts) {
- super();
- const opts = {};
- if (_opts) Object.assign(opts, _opts);
- /** @type {Map<String, DirEntry>} */
- this._watched = /* @__PURE__ */ new Map();
- /** @type {Map<String, Array>} */
- this._closers = /* @__PURE__ */ new Map();
- /** @type {Set<String>} */
- this._ignoredPaths = /* @__PURE__ */ new Set();
- /** @type {Map<ThrottleType, Map>} */
- this._throttled = /* @__PURE__ */ new Map();
- /** @type {Map<Path, String|Boolean>} */
- this._symlinkPaths = /* @__PURE__ */ new Map();
- this._streams = /* @__PURE__ */ new Set();
- this.closed = false;
- if (undef(opts, "persistent")) opts.persistent = true;
- if (undef(opts, "ignoreInitial")) opts.ignoreInitial = false;
- if (undef(opts, "ignorePermissionErrors")) opts.ignorePermissionErrors = false;
- if (undef(opts, "interval")) opts.interval = 100;
- if (undef(opts, "binaryInterval")) opts.binaryInterval = 300;
- if (undef(opts, "disableGlobbing")) opts.disableGlobbing = false;
- opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
- if (undef(opts, "useFsEvents")) opts.useFsEvents = !opts.usePolling;
- if (!FsEventsHandler.canUse()) opts.useFsEvents = false;
- if (undef(opts, "usePolling") && !opts.useFsEvents) opts.usePolling = isMacos;
- if (isIBMi) opts.usePolling = true;
- const envPoll = process.env.CHOKIDAR_USEPOLLING;
- if (envPoll !== void 0) {
- const envLower = envPoll.toLowerCase();
- if (envLower === "false" || envLower === "0") opts.usePolling = false;
- else if (envLower === "true" || envLower === "1") opts.usePolling = true;
- else opts.usePolling = !!envLower;
- }
- const envInterval = process.env.CHOKIDAR_INTERVAL;
- if (envInterval) opts.interval = Number.parseInt(envInterval, 10);
- if (undef(opts, "atomic")) opts.atomic = !opts.usePolling && !opts.useFsEvents;
- if (opts.atomic) this._pendingUnlinks = /* @__PURE__ */ new Map();
- if (undef(opts, "followSymlinks")) opts.followSymlinks = true;
- if (undef(opts, "awaitWriteFinish")) opts.awaitWriteFinish = false;
- if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
- const awf = opts.awaitWriteFinish;
- if (awf) {
- if (!awf.stabilityThreshold) awf.stabilityThreshold = 2e3;
- if (!awf.pollInterval) awf.pollInterval = 100;
- this._pendingWrites = /* @__PURE__ */ new Map();
- }
- if (opts.ignored) opts.ignored = arrify(opts.ignored);
- let readyCalls = 0;
- this._emitReady = () => {
- readyCalls++;
- if (readyCalls >= this._readyCount) {
- this._emitReady = EMPTY_FN;
- this._readyEmitted = true;
- process.nextTick(() => this.emit(EV_READY));
- }
- };
- this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
- this._readyEmitted = false;
- this.options = opts;
- if (opts.useFsEvents) this._fsEventsHandler = new FsEventsHandler(this);
- else this._nodeFsHandler = new NodeFsHandler(this);
- Object.freeze(opts);
- }
- /**
- * Adds paths to be watched on an existing FSWatcher instance
- * @param {Path|Array<Path>} paths_
- * @param {String=} _origAdd private; for handling non-existent paths to be watched
- * @param {Boolean=} _internal private; indicates a non-user add
- * @returns {FSWatcher} for chaining
- */
- add(paths_, _origAdd, _internal) {
- const { cwd, disableGlobbing } = this.options;
- this.closed = false;
- let paths = unifyPaths(paths_);
- if (cwd) paths = paths.map((path$13) => {
- const absPath = getAbsolutePath(path$13, cwd);
- if (disableGlobbing || !isGlob(path$13)) return absPath;
- return normalizePath$1(absPath);
- });
- paths = paths.filter((path$13) => {
- if (path$13.startsWith(BANG)) {
- this._ignoredPaths.add(path$13.slice(1));
- return false;
- }
- this._ignoredPaths.delete(path$13);
- this._ignoredPaths.delete(path$13 + SLASH_GLOBSTAR);
- this._userIgnored = void 0;
- return true;
- });
- if (this.options.useFsEvents && this._fsEventsHandler) {
- if (!this._readyCount) this._readyCount = paths.length;
- if (this.options.persistent) this._readyCount += paths.length;
- paths.forEach((path$13) => this._fsEventsHandler._addToFsEvents(path$13));
- } else {
- if (!this._readyCount) this._readyCount = 0;
- this._readyCount += paths.length;
- Promise.all(paths.map(async (path$13) => {
- const res = await this._nodeFsHandler._addToNodeFs(path$13, !_internal, 0, 0, _origAdd);
- if (res) this._emitReady();
- return res;
- })).then((results) => {
- if (this.closed) return;
- results.filter((item) => item).forEach((item) => {
- this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
- });
- });
- }
- return this;
- }
- /**
- * Close watchers or start ignoring events from specified paths.
- * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
- * @returns {FSWatcher} for chaining
- */
- unwatch(paths_) {
- if (this.closed) return this;
- const paths = unifyPaths(paths_);
- const { cwd } = this.options;
- paths.forEach((path$13) => {
- if (!sysPath.isAbsolute(path$13) && !this._closers.has(path$13)) {
- if (cwd) path$13 = sysPath.join(cwd, path$13);
- path$13 = sysPath.resolve(path$13);
- }
- this._closePath(path$13);
- this._ignoredPaths.add(path$13);
- if (this._watched.has(path$13)) this._ignoredPaths.add(path$13 + SLASH_GLOBSTAR);
- this._userIgnored = void 0;
- });
- return this;
- }
- /**
- * Close watchers and remove all listeners from watched paths.
- * @returns {Promise<void>}.
- */
- close() {
- if (this.closed) return this._closePromise;
- this.closed = true;
- this.removeAllListeners();
- const closers = [];
- this._closers.forEach((closerList) => closerList.forEach((closer) => {
- const promise = closer();
- if (promise instanceof Promise) closers.push(promise);
- }));
- this._streams.forEach((stream$2) => stream$2.destroy());
- this._userIgnored = void 0;
- this._readyCount = 0;
- this._readyEmitted = false;
- this._watched.forEach((dirent) => dirent.dispose());
- [
- "closers",
- "watched",
- "streams",
- "symlinkPaths",
- "throttled"
- ].forEach((key) => {
- this[`_${key}`].clear();
- });
- this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
- return this._closePromise;
- }
- /**
- * Expose list of watched paths
- * @returns {Object} for chaining
- */
- getWatched() {
- const watchList = {};
- this._watched.forEach((entry, dir) => {
- const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
- watchList[key || ONE_DOT] = entry.getChildren().sort();
- });
- return watchList;
- }
- emitWithAll(event, args) {
- this.emit(...args);
- if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
- }
- /**
- * Normalize and emit events.
- * Calling _emit DOES NOT MEAN emit() would be called!
- * @param {EventName} event Type of event
- * @param {Path} path File or directory path
- * @param {*=} val1 arguments to be passed with event
- * @param {*=} val2
- * @param {*=} val3
- * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
- */
- async _emit(event, path$13, val1, val2, val3) {
- if (this.closed) return;
- const opts = this.options;
- if (isWindows$2) path$13 = sysPath.normalize(path$13);
- if (opts.cwd) path$13 = sysPath.relative(opts.cwd, path$13);
- /** @type Array<any> */
- const args = [event, path$13];
- if (val3 !== void 0) args.push(val1, val2, val3);
- else if (val2 !== void 0) args.push(val1, val2);
- else if (val1 !== void 0) args.push(val1);
- const awf = opts.awaitWriteFinish;
- let pw;
- if (awf && (pw = this._pendingWrites.get(path$13))) {
- pw.lastChange = /* @__PURE__ */ new Date();
- return this;
- }
- if (opts.atomic) {
- if (event === EV_UNLINK) {
- this._pendingUnlinks.set(path$13, args);
- setTimeout(() => {
- this._pendingUnlinks.forEach((entry, path$14) => {
- this.emit(...entry);
- this.emit(EV_ALL, ...entry);
- this._pendingUnlinks.delete(path$14);
- });
- }, typeof opts.atomic === "number" ? opts.atomic : 100);
- return this;
- }
- if (event === EV_ADD && this._pendingUnlinks.has(path$13)) {
- event = args[0] = EV_CHANGE;
- this._pendingUnlinks.delete(path$13);
- }
- }
- if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
- const awfEmit = (err$2, stats) => {
- if (err$2) {
- event = args[0] = EV_ERROR;
- args[1] = err$2;
- this.emitWithAll(event, args);
- } else if (stats) {
- if (args.length > 2) args[2] = stats;
- else args.push(stats);
- this.emitWithAll(event, args);
- }
- };
- this._awaitWriteFinish(path$13, awf.stabilityThreshold, event, awfEmit);
- return this;
- }
- if (event === EV_CHANGE) {
- if (!this._throttle(EV_CHANGE, path$13, 50)) return this;
- }
- if (opts.alwaysStat && val1 === void 0 && (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)) {
- const fullPath = opts.cwd ? sysPath.join(opts.cwd, path$13) : path$13;
- let stats;
- try {
- stats = await stat(fullPath);
- } catch (err$2) {}
- if (!stats || this.closed) return;
- args.push(stats);
- }
- this.emitWithAll(event, args);
- return this;
- }
- /**
- * Common handler for errors
- * @param {Error} error
- * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
- */
- _handleError(error$1) {
- const code = error$1 && error$1.code;
- if (error$1 && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) this.emit(EV_ERROR, error$1);
- return error$1 || this.closed;
- }
- /**
- * Helper utility for throttling
- * @param {ThrottleType} actionType type being throttled
- * @param {Path} path being acted upon
- * @param {Number} timeout duration of time to suppress duplicate actions
- * @returns {Object|false} tracking object or false if action should be suppressed
- */
- _throttle(actionType, path$13, timeout$1) {
- if (!this._throttled.has(actionType)) this._throttled.set(actionType, /* @__PURE__ */ new Map());
- /** @type {Map<Path, Object>} */
- const action = this._throttled.get(actionType);
- /** @type {Object} */
- const actionPath = action.get(path$13);
- if (actionPath) {
- actionPath.count++;
- return false;
- }
- let timeoutObject;
- const clear = () => {
- const item = action.get(path$13);
- const count = item ? item.count : 0;
- action.delete(path$13);
- clearTimeout(timeoutObject);
- if (item) clearTimeout(item.timeoutObject);
- return count;
- };
- timeoutObject = setTimeout(clear, timeout$1);
- const thr = {
- timeoutObject,
- clear,
- count: 0
- };
- action.set(path$13, thr);
- return thr;
- }
- _incrReadyCount() {
- return this._readyCount++;
- }
- /**
- * Awaits write operation to finish.
- * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
- * @param {Path} path being acted upon
- * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
- * @param {EventName} event
- * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
- */
- _awaitWriteFinish(path$13, threshold, event, awfEmit) {
- let timeoutHandler;
- let fullPath = path$13;
- if (this.options.cwd && !sysPath.isAbsolute(path$13)) fullPath = sysPath.join(this.options.cwd, path$13);
- const now = /* @__PURE__ */ new Date();
- const awaitWriteFinish = (prevStat) => {
- fs$6.stat(fullPath, (err$2, curStat) => {
- if (err$2 || !this._pendingWrites.has(path$13)) {
- if (err$2 && err$2.code !== "ENOENT") awfEmit(err$2);
- return;
- }
- const now$1 = Number(/* @__PURE__ */ new Date());
- if (prevStat && curStat.size !== prevStat.size) this._pendingWrites.get(path$13).lastChange = now$1;
- if (now$1 - this._pendingWrites.get(path$13).lastChange >= threshold) {
- this._pendingWrites.delete(path$13);
- awfEmit(void 0, curStat);
- } else timeoutHandler = setTimeout(awaitWriteFinish, this.options.awaitWriteFinish.pollInterval, curStat);
- });
- };
- if (!this._pendingWrites.has(path$13)) {
- this._pendingWrites.set(path$13, {
- lastChange: now,
- cancelWait: () => {
- this._pendingWrites.delete(path$13);
- clearTimeout(timeoutHandler);
- return event;
- }
- });
- timeoutHandler = setTimeout(awaitWriteFinish, this.options.awaitWriteFinish.pollInterval);
- }
- }
- _getGlobIgnored() {
- return [...this._ignoredPaths.values()];
- }
- /**
- * Determines whether user has asked to ignore this path.
- * @param {Path} path filepath or dir
- * @param {fs.Stats=} stats result of fs.stat
- * @returns {Boolean}
- */
- _isIgnored(path$13, stats) {
- if (this.options.atomic && DOT_RE.test(path$13)) return true;
- if (!this._userIgnored) {
- const { cwd } = this.options;
- const ign = this.options.ignored;
- const ignored = ign && ign.map(normalizeIgnored(cwd));
- const paths = arrify(ignored).filter((path$14) => typeof path$14 === STRING_TYPE && !isGlob(path$14)).map((path$14) => path$14 + SLASH_GLOBSTAR);
- this._userIgnored = anymatch(this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths), void 0, ANYMATCH_OPTS);
- }
- return this._userIgnored([path$13, stats]);
- }
- _isntIgnored(path$13, stat$4) {
- return !this._isIgnored(path$13, stat$4);
- }
- /**
- * Provides a set of common helpers and properties relating to symlink and glob handling.
- * @param {Path} path file, directory, or glob pattern being watched
- * @param {Number=} depth at any depth > 0, this isn't a glob
- * @returns {WatchHelper} object containing helpers for this path
- */
- _getWatchHelpers(path$13, depth) {
- const watchPath = depth || this.options.disableGlobbing || !isGlob(path$13) ? path$13 : globParent(path$13);
- const follow = this.options.followSymlinks;
- return new WatchHelper(path$13, watchPath, follow, this);
- }
- /**
- * Provides directory tracking objects
- * @param {String} directory path of the directory
- * @returns {DirEntry} the directory's tracking object
- */
- _getWatchedDir(directory) {
- if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
- const dir = sysPath.resolve(directory);
- if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
- return this._watched.get(dir);
- }
- /**
- * Check for read permissions.
- * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
- * @param {fs.Stats} stats - object, result of fs_stat
- * @returns {Boolean} indicates whether the file can be read
- */
- _hasReadPermissions(stats) {
- if (this.options.ignorePermissionErrors) return true;
- const st = (stats && Number.parseInt(stats.mode, 10)) & 511;
- const it = Number.parseInt(st.toString(8)[0], 10);
- return Boolean(4 & it);
- }
- /**
- * Handles emitting unlink events for
- * files and directories, and via recursion, for
- * files and directories within directories that are unlinked
- * @param {String} directory within which the following item is located
- * @param {String} item base path of item/directory
- * @returns {void}
- */
- _remove(directory, item, isDirectory$2) {
- const path$13 = sysPath.join(directory, item);
- const fullPath = sysPath.resolve(path$13);
- isDirectory$2 = isDirectory$2 != null ? isDirectory$2 : this._watched.has(path$13) || this._watched.has(fullPath);
- if (!this._throttle("remove", path$13, 100)) return;
- if (!isDirectory$2 && !this.options.useFsEvents && this._watched.size === 1) this.add(directory, item, true);
- this._getWatchedDir(path$13).getChildren().forEach((nested) => this._remove(path$13, nested));
- const parent = this._getWatchedDir(directory);
- const wasTracked = parent.has(item);
- parent.remove(item);
- if (this._symlinkPaths.has(fullPath)) this._symlinkPaths.delete(fullPath);
- let relPath = path$13;
- if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path$13);
- if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
- if (this._pendingWrites.get(relPath).cancelWait() === EV_ADD) return;
- }
- this._watched.delete(path$13);
- this._watched.delete(fullPath);
- const eventName = isDirectory$2 ? EV_UNLINK_DIR : EV_UNLINK;
- if (wasTracked && !this._isIgnored(path$13)) this._emit(eventName, path$13);
- if (!this.options.useFsEvents) this._closePath(path$13);
- }
- /**
- * Closes all watchers for a path
- * @param {Path} path
- */
- _closePath(path$13) {
- this._closeFile(path$13);
- const dir = sysPath.dirname(path$13);
- this._getWatchedDir(dir).remove(sysPath.basename(path$13));
- }
- /**
- * Closes only file-specific watchers
- * @param {Path} path
- */
- _closeFile(path$13) {
- const closers = this._closers.get(path$13);
- if (!closers) return;
- closers.forEach((closer) => closer());
- this._closers.delete(path$13);
- }
- /**
- *
- * @param {Path} path
- * @param {Function} closer
- */
- _addPathCloser(path$13, closer) {
- if (!closer) return;
- let list = this._closers.get(path$13);
- if (!list) {
- list = [];
- this._closers.set(path$13, list);
- }
- list.push(closer);
- }
- _readdirp(root, opts) {
- if (this.closed) return;
- let stream$2 = readdirp(root, {
- type: EV_ALL,
- alwaysStat: true,
- lstat: true,
- ...opts
- });
- this._streams.add(stream$2);
- stream$2.once(STR_CLOSE, () => {
- stream$2 = void 0;
- });
- stream$2.once(STR_END, () => {
- if (stream$2) {
- this._streams.delete(stream$2);
- stream$2 = void 0;
- }
- });
- return stream$2;
- }
- };
- /**
- * Instantiates watcher with paths to be tracked.
- * @param {String|Array<String>} paths file/directory paths and/or globs
- * @param {Object=} options chokidar opts
- * @returns an instance of FSWatcher for chaining.
- */
- const watch = (paths, options$1) => {
- const watcher = new FSWatcher(options$1);
- watcher.add(paths);
- return watcher;
- };
- exports.watch = watch;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/shell-quote@1.8.3/node_modules/shell-quote/quote.js
-var require_quote = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = function quote(xs) {
- return xs.map(function(s) {
- if (s === "") return "''";
- if (s && typeof s === "object") return s.op.replace(/(.)/g, "\\$1");
- if (/["\s\\]/.test(s) && !/'/.test(s)) return "'" + s.replace(/(['])/g, "\\$1") + "'";
- if (/["'\s]/.test(s)) return "\"" + s.replace(/(["\\$`!])/g, "\\$1") + "\"";
- return String(s).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g, "$1\\$2");
- }).join(" ");
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/shell-quote@1.8.3/node_modules/shell-quote/parse.js
-var require_parse$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- var CONTROL = "(?:" + [
- "\\|\\|",
- "\\&\\&",
- ";;",
- "\\|\\&",
- "\\<\\(",
- "\\<\\<\\<",
- ">>",
- ">\\&",
- "<\\&",
- "[&;()|<>]"
- ].join("|") + ")";
- var controlRE = /* @__PURE__ */ new RegExp("^" + CONTROL + "$");
- var META = "|&;()<> \\t";
- var SINGLE_QUOTE = "\"((\\\\\"|[^\"])*?)\"";
- var DOUBLE_QUOTE = "'((\\\\'|[^'])*?)'";
- var hash = /^#$/;
- var SQ = "'";
- var DQ = "\"";
- var DS = "$";
- var TOKEN = "";
- var mult = 4294967296;
- for (var i = 0; i < 4; i++) TOKEN += (mult * Math.random()).toString(16);
- var startsWithToken = /* @__PURE__ */ new RegExp("^" + TOKEN);
- function matchAll(s, r$1) {
- var origIndex = r$1.lastIndex;
- var matches$2 = [];
- var matchObj;
- while (matchObj = r$1.exec(s)) {
- matches$2.push(matchObj);
- if (r$1.lastIndex === matchObj.index) r$1.lastIndex += 1;
- }
- r$1.lastIndex = origIndex;
- return matches$2;
- }
- function getVar(env$1, pre, key) {
- var r$1 = typeof env$1 === "function" ? env$1(key) : env$1[key];
- if (typeof r$1 === "undefined" && key != "") r$1 = "";
- else if (typeof r$1 === "undefined") r$1 = "$";
- if (typeof r$1 === "object") return pre + TOKEN + JSON.stringify(r$1) + TOKEN;
- return pre + r$1;
- }
- function parseInternal(string, env$1, opts) {
- if (!opts) opts = {};
- var BS = opts.escape || "\\";
- var BAREWORD = "(\\" + BS + "['\"" + META + "]|[^\\s'\"" + META + "])+";
- var matches$2 = matchAll(string, new RegExp(["(" + CONTROL + ")", "(" + BAREWORD + "|" + SINGLE_QUOTE + "|" + DOUBLE_QUOTE + ")+"].join("|"), "g"));
- if (matches$2.length === 0) return [];
- if (!env$1) env$1 = {};
- var commented = false;
- return matches$2.map(function(match) {
- var s = match[0];
- if (!s || commented) return;
- if (controlRE.test(s)) return { op: s };
- var quote = false;
- var esc = false;
- var out = "";
- var isGlob$2 = false;
- var i$1;
- function parseEnvVar() {
- i$1 += 1;
- var varend;
- var varname;
- var char = s.charAt(i$1);
- if (char === "{") {
- i$1 += 1;
- if (s.charAt(i$1) === "}") throw new Error("Bad substitution: " + s.slice(i$1 - 2, i$1 + 1));
- varend = s.indexOf("}", i$1);
- if (varend < 0) throw new Error("Bad substitution: " + s.slice(i$1));
- varname = s.slice(i$1, varend);
- i$1 = varend;
- } else if (/[*@#?$!_-]/.test(char)) {
- varname = char;
- i$1 += 1;
- } else {
- var slicedFromI = s.slice(i$1);
- varend = slicedFromI.match(/[^\w\d_]/);
- if (!varend) {
- varname = slicedFromI;
- i$1 = s.length;
- } else {
- varname = slicedFromI.slice(0, varend.index);
- i$1 += varend.index - 1;
- }
- }
- return getVar(env$1, "", varname);
- }
- for (i$1 = 0; i$1 < s.length; i$1++) {
- var c = s.charAt(i$1);
- isGlob$2 = isGlob$2 || !quote && (c === "*" || c === "?");
- if (esc) {
- out += c;
- esc = false;
- } else if (quote) if (c === quote) quote = false;
- else if (quote == SQ) out += c;
- else if (c === BS) {
- i$1 += 1;
- c = s.charAt(i$1);
- if (c === DQ || c === BS || c === DS) out += c;
- else out += BS + c;
- } else if (c === DS) out += parseEnvVar();
- else out += c;
- else if (c === DQ || c === SQ) quote = c;
- else if (controlRE.test(c)) return { op: s };
- else if (hash.test(c)) {
- commented = true;
- var commentObj = { comment: string.slice(match.index + i$1 + 1) };
- if (out.length) return [out, commentObj];
- return [commentObj];
- } else if (c === BS) esc = true;
- else if (c === DS) out += parseEnvVar();
- else out += c;
- }
- if (isGlob$2) return {
- op: "glob",
- pattern: out
- };
- return out;
- }).reduce(function(prev, arg) {
- return typeof arg === "undefined" ? prev : prev.concat(arg);
- }, []);
- }
- module.exports = function parse$15(s, env$1, opts) {
- var mapped = parseInternal(s, env$1, opts);
- if (typeof env$1 !== "function") return mapped;
- return mapped.reduce(function(acc, s$1) {
- if (typeof s$1 === "object") return acc.concat(s$1);
- var xs = s$1.split(RegExp("(" + TOKEN + ".*?" + TOKEN + ")", "g"));
- if (xs.length === 1) return acc.concat(xs[0]);
- return acc.concat(xs.filter(Boolean).map(function(x) {
- if (startsWithToken.test(x)) return JSON.parse(x.split(TOKEN)[1]);
- return x;
- }));
- }, []);
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/shell-quote@1.8.3/node_modules/shell-quote/index.js
-var require_shell_quote = /* @__PURE__ */ __commonJSMin(((exports) => {
- exports.quote = require_quote();
- exports.parse = require_parse$1();
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/launch-editor@2.12.0/node_modules/launch-editor/editor-info/macos.js
-var require_macos = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = {
- "/Applications/Atom.app/Contents/MacOS/Atom": "atom",
- "/Applications/Atom Beta.app/Contents/MacOS/Atom Beta": "/Applications/Atom Beta.app/Contents/MacOS/Atom Beta",
- "/Applications/Brackets.app/Contents/MacOS/Brackets": "brackets",
- "/Applications/Sublime Text.app/Contents/MacOS/Sublime Text": "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl",
- "/Applications/Sublime Text.app/Contents/MacOS/sublime_text": "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl",
- "/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2": "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl",
- "/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text": "/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl",
- "/Applications/Visual Studio Code.app/Contents/MacOS/Electron": "code",
- "/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron": "code-insiders",
- "/Applications/VSCodium.app/Contents/MacOS/Electron": "codium",
- "/Applications/Cursor.app/Contents/MacOS/Cursor": "cursor",
- "/Applications/Trae.app/Contents/MacOS/Electron": "trae",
- "/Applications/AppCode.app/Contents/MacOS/appcode": "/Applications/AppCode.app/Contents/MacOS/appcode",
- "/Applications/CLion.app/Contents/MacOS/clion": "/Applications/CLion.app/Contents/MacOS/clion",
- "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea": "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea",
- "/Applications/IntelliJ IDEA Ultimate.app/Contents/MacOS/idea": "/Applications/IntelliJ IDEA Ultimate.app/Contents/MacOS/idea",
- "/Applications/IntelliJ IDEA Community Edition.app/Contents/MacOS/idea": "/Applications/IntelliJ IDEA Community Edition.app/Contents/MacOS/idea",
- "/Applications/PhpStorm.app/Contents/MacOS/phpstorm": "/Applications/PhpStorm.app/Contents/MacOS/phpstorm",
- "/Applications/PyCharm.app/Contents/MacOS/pycharm": "/Applications/PyCharm.app/Contents/MacOS/pycharm",
- "/Applications/PyCharm CE.app/Contents/MacOS/pycharm": "/Applications/PyCharm CE.app/Contents/MacOS/pycharm",
- "/Applications/RubyMine.app/Contents/MacOS/rubymine": "/Applications/RubyMine.app/Contents/MacOS/rubymine",
- "/Applications/WebStorm.app/Contents/MacOS/webstorm": "/Applications/WebStorm.app/Contents/MacOS/webstorm",
- "/Applications/MacVim.app/Contents/MacOS/MacVim": "mvim",
- "/Applications/GoLand.app/Contents/MacOS/goland": "/Applications/GoLand.app/Contents/MacOS/goland",
- "/Applications/Rider.app/Contents/MacOS/rider": "/Applications/Rider.app/Contents/MacOS/rider",
- "/Applications/Zed.app/Contents/MacOS/zed": "zed"
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/launch-editor@2.12.0/node_modules/launch-editor/editor-info/linux.js
-var require_linux = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = {
- atom: "atom",
- Brackets: "brackets",
- "code-insiders": "code-insiders",
- code: "code",
- vscodium: "vscodium",
- codium: "codium",
- cursor: "cursor",
- trae: "trae",
- emacs: "emacs",
- gvim: "gvim",
- idea: "idea",
- "idea.sh": "idea",
- phpstorm: "phpstorm",
- "phpstorm.sh": "phpstorm",
- pycharm: "pycharm",
- "pycharm.sh": "pycharm",
- rubymine: "rubymine",
- "rubymine.sh": "rubymine",
- sublime_text: "subl",
- vim: "vim",
- webstorm: "webstorm",
- "webstorm.sh": "webstorm",
- goland: "goland",
- "goland.sh": "goland",
- rider: "rider",
- "rider.sh": "rider",
- zed: "zed"
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/launch-editor@2.12.0/node_modules/launch-editor/editor-info/windows.js
-var require_windows$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = [
- "Brackets.exe",
- "Code.exe",
- "Code - Insiders.exe",
- "VSCodium.exe",
- "Cursor.exe",
- "atom.exe",
- "sublime_text.exe",
- "notepad++.exe",
- "clion.exe",
- "clion64.exe",
- "idea.exe",
- "idea64.exe",
- "phpstorm.exe",
- "phpstorm64.exe",
- "pycharm.exe",
- "pycharm64.exe",
- "rubymine.exe",
- "rubymine64.exe",
- "webstorm.exe",
- "webstorm64.exe",
- "goland.exe",
- "goland64.exe",
- "rider.exe",
- "rider64.exe",
- "trae.exe"
- ];
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/launch-editor@2.12.0/node_modules/launch-editor/guess.js
-var require_guess = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const path$8 = __require("path");
- const shellQuote = require_shell_quote();
- const childProcess$2 = __require("child_process");
- const COMMON_EDITORS_MACOS = require_macos();
- const COMMON_EDITORS_LINUX = require_linux();
- const COMMON_EDITORS_WIN = require_windows$1();
- module.exports = function guessEditor$1(specifiedEditor) {
- if (specifiedEditor) return shellQuote.parse(specifiedEditor);
- if (process.env.LAUNCH_EDITOR) return [process.env.LAUNCH_EDITOR];
- if (process.versions.webcontainer) return [process.env.EDITOR || "code"];
- try {
- if (process.platform === "darwin") {
- const output = childProcess$2.execSync("ps x -o comm=", { stdio: [
- "pipe",
- "pipe",
- "ignore"
- ] }).toString();
- const processNames = Object.keys(COMMON_EDITORS_MACOS);
- const processList = output.split("\n");
- for (let i$1 = 0; i$1 < processNames.length; i$1++) {
- const processName = processNames[i$1];
- if (processList.includes(processName)) return [COMMON_EDITORS_MACOS[processName]];
- const processNameWithoutApplications = processName.replace("/Applications", "");
- if (output.indexOf(processNameWithoutApplications) !== -1) {
- if (processName !== COMMON_EDITORS_MACOS[processName]) return [COMMON_EDITORS_MACOS[processName]];
- const runningProcess = processList.find((procName) => procName.endsWith(processNameWithoutApplications));
- if (runningProcess !== void 0) return [runningProcess];
- }
- }
- } else if (process.platform === "win32") {
- const runningProcesses = childProcess$2.execSync("powershell -NoProfile -Command \"[Console]::OutputEncoding=[Text.Encoding]::UTF8;Get-CimInstance -Query \\\"select executablepath from win32_process where executablepath is not null\\\" | % { $_.ExecutablePath }\"", { stdio: [
- "pipe",
- "pipe",
- "ignore"
- ] }).toString().split("\r\n");
- for (let i$1 = 0; i$1 < runningProcesses.length; i$1++) {
- const fullProcessPath = runningProcesses[i$1].trim();
- const shortProcessName = path$8.basename(fullProcessPath);
- if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) return [fullProcessPath];
- }
- } else if (process.platform === "linux") {
- const output = childProcess$2.execSync("ps x --no-heading -o comm --sort=comm", { stdio: [
- "pipe",
- "pipe",
- "ignore"
- ] }).toString();
- const processNames = Object.keys(COMMON_EDITORS_LINUX);
- for (let i$1 = 0; i$1 < processNames.length; i$1++) {
- const processName = processNames[i$1];
- if (output.indexOf(processName) !== -1) return [COMMON_EDITORS_LINUX[processName]];
- }
- }
- } catch (ignoreError) {}
- if (process.env.VISUAL) return [process.env.VISUAL];
- else if (process.env.EDITOR) return [process.env.EDITOR];
- return [null];
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/launch-editor@2.12.0/node_modules/launch-editor/get-args.js
-var require_get_args = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const path$7 = __require("path");
- module.exports = function getArgumentsForPosition$1(editor, fileName, lineNumber, columnNumber = 1) {
- switch (path$7.basename(editor).replace(/\.(exe|cmd|bat)$/i, "")) {
- case "atom":
- case "Atom":
- case "Atom Beta":
- case "subl":
- case "sublime":
- case "sublime_text":
- case "wstorm":
- case "charm":
- case "zed": return [`${fileName}:${lineNumber}:${columnNumber}`];
- case "notepad++": return [
- "-n" + lineNumber,
- "-c" + columnNumber,
- fileName
- ];
- case "vim":
- case "mvim": return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName];
- case "joe":
- case "gvim": return [`+${lineNumber}`, fileName];
- case "emacs":
- case "emacsclient": return [`+${lineNumber}:${columnNumber}`, fileName];
- case "rmate":
- case "mate":
- case "mine": return [
- "--line",
- lineNumber,
- fileName
- ];
- case "code":
- case "Code":
- case "code-insiders":
- case "Code - Insiders":
- case "codium":
- case "trae":
- case "cursor":
- case "vscodium":
- case "VSCodium": return [
- "-r",
- "-g",
- `${fileName}:${lineNumber}:${columnNumber}`
- ];
- case "appcode":
- case "clion":
- case "clion64":
- case "idea":
- case "idea64":
- case "phpstorm":
- case "phpstorm64":
- case "pycharm":
- case "pycharm64":
- case "rubymine":
- case "rubymine64":
- case "webstorm":
- case "webstorm64":
- case "goland":
- case "goland64":
- case "rider":
- case "rider64": return [
- "--line",
- lineNumber,
- "--column",
- columnNumber,
- fileName
- ];
- }
- if (process.env.LAUNCH_EDITOR) return [
- fileName,
- lineNumber,
- columnNumber
- ];
- return [fileName];
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/launch-editor@2.12.0/node_modules/launch-editor/index.js
-var require_launch_editor = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file at
- * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE
- *
- * Modified by Yuxi Evan You
- */
- const fs$5 = __require("fs");
- const os$1 = __require("os");
- const path$6 = __require("path");
- const colors$27 = require_picocolors();
- const childProcess$1 = __require("child_process");
- const guessEditor = require_guess();
- const getArgumentsForPosition = require_get_args();
- function wrapErrorCallback(cb) {
- return (fileName, errorMessage) => {
- console.log();
- console.log(colors$27.red("Could not open " + path$6.basename(fileName) + " in the editor."));
- if (errorMessage) {
- if (errorMessage[errorMessage.length - 1] !== ".") errorMessage += ".";
- console.log(colors$27.red("The editor process exited with an error: " + errorMessage));
- }
- console.log();
- if (cb) cb(fileName, errorMessage);
- };
- }
- function isTerminalEditor(editor) {
- switch (editor) {
- case "vim":
- case "emacs":
- case "nano": return true;
- }
- return false;
- }
- const positionRE = /:(\d+)(:(\d+))?$/;
- function parseFile(file) {
- if (file.startsWith("file://")) file = __require("url").fileURLToPath(file);
- const fileName = file.replace(positionRE, "");
- const match = file.match(positionRE);
- return {
- fileName,
- lineNumber: match && match[1],
- columnNumber: match && match[3]
- };
- }
- let _childProcess = null;
- function launchEditor(file, specifiedEditor, onErrorCallback) {
- const parsed = parseFile(file);
- let { fileName } = parsed;
- const { lineNumber, columnNumber } = parsed;
- if (!fs$5.existsSync(fileName)) return;
- if (typeof specifiedEditor === "function") {
- onErrorCallback = specifiedEditor;
- specifiedEditor = void 0;
- }
- onErrorCallback = wrapErrorCallback(onErrorCallback);
- const [editor, ...args] = guessEditor(specifiedEditor);
- if (!editor) {
- onErrorCallback(fileName, null);
- return;
- }
- if (process.platform === "linux" && fileName.startsWith("/mnt/") && /Microsoft/i.test(os$1.release())) fileName = path$6.relative("", fileName);
- if (lineNumber) {
- const extraArgs = getArgumentsForPosition(editor, fileName, lineNumber, columnNumber);
- args.push.apply(args, extraArgs);
- } else args.push(fileName);
- if (_childProcess && isTerminalEditor(editor)) _childProcess.kill("SIGKILL");
- if (process.platform === "win32") {
- function escapeCmdArgs(cmdArgs) {
- return cmdArgs.replace(/([&|<>,;=^])/g, "^$1");
- }
- function doubleQuoteIfNeeded(str) {
- if (str.includes("^")) return `^"${str}^"`;
- else if (str.includes(" ")) return `"${str}"`;
- return str;
- }
- const launchCommand = [editor, ...args.map(escapeCmdArgs)].map(doubleQuoteIfNeeded).join(" ");
- _childProcess = childProcess$1.exec(launchCommand, {
- stdio: "inherit",
- shell: true
- });
- } else _childProcess = childProcess$1.spawn(editor, args, { stdio: "inherit" });
- _childProcess.on("exit", function(errorCode) {
- _childProcess = null;
- if (errorCode) onErrorCallback(fileName, "(code " + errorCode + ")");
- });
- _childProcess.on("error", function(error$1) {
- let { code, message } = error$1;
- if ("ENOENT" === code) message = `${message} ('${editor}' command does not exist in 'PATH')`;
- onErrorCallback(fileName, message);
- });
- }
- module.exports = launchEditor;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/launch-editor-middleware@2.12.0/node_modules/launch-editor-middleware/index.js
-var require_launch_editor_middleware = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const path$5 = __require("path");
- const launch = require_launch_editor();
- module.exports = (specifiedEditor, srcRoot, onErrorCallback) => {
- if (typeof specifiedEditor === "function") {
- onErrorCallback = specifiedEditor;
- specifiedEditor = void 0;
- }
- if (typeof srcRoot === "function") {
- onErrorCallback = srcRoot;
- srcRoot = void 0;
- }
- srcRoot = srcRoot || process.cwd();
- return function launchEditorMiddleware$1(req$4, res) {
- let url$3;
- try {
- const fullUrl = req$4.url.startsWith("http") ? req$4.url : `http://localhost${req$4.url}`;
- url$3 = new URL(fullUrl);
- } catch (_err) {
- res.statusCode = 500;
- res.end(`launch-editor-middleware: invalid URL.`);
- return;
- }
- const file = url$3.searchParams.get("file");
- if (!file) {
- res.statusCode = 500;
- res.end(`launch-editor-middleware: required query param "file" is missing.`);
- } else {
- launch(file.startsWith("file://") ? file : path$5.resolve(srcRoot, file), specifiedEditor, onErrorCallback);
- res.end();
- }
- };
- };
-}));
-
-//#endregion
-//#region src/node/http.ts
-var import_picocolors$26 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-async function resolveHttpServer(app, httpsOptions) {
- if (!httpsOptions) {
- const { createServer: createServer$4 } = await import("node:http");
- return createServer$4(app);
- }
- const { createSecureServer } = await import("node:http2");
- return createSecureServer({
- maxSessionMemory: 1e3,
- streamResetBurst: 1e5,
- streamResetRate: 33,
- ...httpsOptions,
- allowHTTP1: true
- }, app);
-}
-async function resolveHttpsConfig(https$4) {
- if (!https$4) return void 0;
- const [ca, cert, key, pfx] = await Promise.all([
- readFileIfExists(https$4.ca),
- readFileIfExists(https$4.cert),
- readFileIfExists(https$4.key),
- readFileIfExists(https$4.pfx)
- ]);
- return {
- ...https$4,
- ca,
- cert,
- key,
- pfx
- };
-}
-async function readFileIfExists(value$1) {
- if (typeof value$1 === "string") return fsp.readFile(path.resolve(value$1)).catch(() => value$1);
- return value$1;
-}
-async function httpServerStart(httpServer, serverOptions) {
- let { port, strictPort, host, logger } = serverOptions;
- return new Promise((resolve$4, reject) => {
- const onError$1 = (e$1) => {
- if (e$1.code === "EADDRINUSE") if (strictPort) {
- httpServer.removeListener("error", onError$1);
- reject(/* @__PURE__ */ new Error(`Port ${port} is already in use`));
- } else {
- logger.info(`Port ${port} is in use, trying another one...`);
- httpServer.listen(++port, host);
- }
- else {
- httpServer.removeListener("error", onError$1);
- reject(e$1);
- }
- };
- httpServer.on("error", onError$1);
- httpServer.listen(port, host, () => {
- httpServer.removeListener("error", onError$1);
- resolve$4(port);
- });
- });
-}
-function setClientErrorHandler(server, logger) {
- server.on("clientError", (err$2, socket) => {
- let msg = "400 Bad Request";
- if (err$2.code === "HPE_HEADER_OVERFLOW") {
- msg = "431 Request Header Fields Too Large";
- logger.warn(import_picocolors$26.default.yellow("Server responded with status code 431. See https://vite.dev/guide/troubleshooting.html#_431-request-header-fields-too-large."));
- }
- if (err$2.code === "ECONNRESET" || !socket.writable) return;
- socket.end(`HTTP/1.1 ${msg}\r\n\r\n`);
- });
-}
-
-//#endregion
-//#region src/node/ssr/ssrStacktrace.ts
-let offset;
-function calculateOffsetOnce() {
- if (offset !== void 0) return;
- try {
- new Function("throw new Error(1)")();
- } catch (e$1) {
- const match = /:(\d+):\d+\)$/.exec(e$1.stack.split("\n")[1]);
- offset = match ? +match[1] - 1 : 0;
- }
-}
-function ssrRewriteStacktrace(stack, moduleGraph) {
- calculateOffsetOnce();
- return stack.split("\n").map((line) => {
- return line.replace(/^ {4}at (?:(\S.*?)\s\()?(.+?):(\d+)(?::(\d+))?\)?/, (input, varName, id, line$1, column) => {
- if (!id) return input;
- const rawSourceMap = moduleGraph.getModuleById(id)?.transformResult?.map;
- if (!rawSourceMap) return input;
- const pos = originalPositionFor(new TraceMap(rawSourceMap), {
- line: Number(line$1) - offset,
- column: Number(column) - 1
- });
- if (!pos.source) return input;
- const trimmedVarName = varName?.trim();
- const source = `${path.resolve(path.dirname(id), pos.source)}:${pos.line}:${pos.column + 1}`;
- if (!trimmedVarName || trimmedVarName === "eval") return ` at ${source}`;
- else return ` at ${trimmedVarName} (${source})`;
- });
- }).join("\n");
-}
-function rebindErrorStacktrace(e$1, stacktrace) {
- const { configurable, writable } = Object.getOwnPropertyDescriptor(e$1, "stack");
- if (configurable) Object.defineProperty(e$1, "stack", {
- value: stacktrace,
- enumerable: true,
- configurable: true,
- writable: true
- });
- else if (writable) e$1.stack = stacktrace;
-}
-const rewroteStacktraces = /* @__PURE__ */ new WeakSet();
-function ssrFixStacktrace(e$1, moduleGraph) {
- if (!e$1.stack) return;
- if (rewroteStacktraces.has(e$1)) return;
- rebindErrorStacktrace(e$1, ssrRewriteStacktrace(e$1.stack, moduleGraph));
- rewroteStacktraces.add(e$1);
-}
-
-//#endregion
-//#region src/node/ssr/runtime/serverModuleRunner.ts
-function createHMROptions(environment, options$1) {
- if (environment.config.server.hmr === false || options$1.hmr === false) return false;
- if (!("api" in environment.hot)) return false;
- return { logger: options$1.hmr?.logger };
-}
-const prepareStackTrace = { retrieveFile(id) {
- if (existsSync(id)) return readFileSync(id, "utf-8");
-} };
-function resolveSourceMapOptions(options$1) {
- if (options$1.sourcemapInterceptor != null) {
- if (options$1.sourcemapInterceptor === "prepareStackTrace") return prepareStackTrace;
- if (typeof options$1.sourcemapInterceptor === "object") return {
- ...prepareStackTrace,
- ...options$1.sourcemapInterceptor
- };
- return options$1.sourcemapInterceptor;
- }
- if (typeof process !== "undefined" && "setSourceMapsEnabled" in process) return "node";
- return prepareStackTrace;
-}
-const createServerModuleRunnerTransport = (options$1) => {
- const hmrClient = { send: (payload) => {
- if (payload.type !== "custom") throw new Error("Cannot send non-custom events from the client to the server.");
- options$1.channel.send(payload);
- } };
- let handler;
- return {
- connect({ onMessage }) {
- options$1.channel.api.outsideEmitter.on("send", onMessage);
- options$1.channel.api.innerEmitter.emit("vite:client:connect", void 0, hmrClient);
- onMessage({ type: "connected" });
- handler = onMessage;
- },
- disconnect() {
- if (handler) options$1.channel.api.outsideEmitter.off("send", handler);
- options$1.channel.api.innerEmitter.emit("vite:client:disconnect", void 0, hmrClient);
- },
- send(payload) {
- if (payload.type !== "custom") throw new Error("Cannot send non-custom events from the server to the client.");
- options$1.channel.api.innerEmitter.emit(payload.event, payload.data, hmrClient);
- }
- };
-};
-/**
-* Create an instance of the Vite SSR runtime that support HMR.
-* @experimental
-*/
-function createServerModuleRunner(environment, options$1 = {}) {
- const hmr = createHMROptions(environment, options$1);
- return new ModuleRunner({
- ...options$1,
- transport: createServerModuleRunnerTransport({ channel: environment.hot }),
- hmr,
- createImportMeta: createNodeImportMeta,
- sourcemapInterceptor: resolveSourceMapOptions(options$1)
- }, options$1.evaluator);
-}
-
-//#endregion
-//#region src/node/ssr/ssrModuleLoader.ts
-var import_picocolors$25 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-async function ssrLoadModule(url$3, server, fixStacktrace) {
- const environment = server.environments.ssr;
- server._ssrCompatModuleRunner ||= new SSRCompatModuleRunner(environment);
- url$3 = unwrapId(url$3);
- return instantiateModule(url$3, server._ssrCompatModuleRunner, environment, fixStacktrace);
-}
-async function instantiateModule(url$3, runner, environment, fixStacktrace) {
- const mod = await environment.moduleGraph.ensureEntryFromUrl(url$3);
- if (mod.ssrError) throw mod.ssrError;
- try {
- return await runner.import(url$3);
- } catch (e$1) {
- if (e$1.stack && fixStacktrace) ssrFixStacktrace(e$1, environment.moduleGraph);
- environment.logger.error(buildErrorMessage(e$1, [import_picocolors$25.default.red(`Error when evaluating SSR module ${url$3}: ${e$1.message}`)]), {
- timestamp: true,
- clear: environment.config.clearScreen,
- error: e$1
- });
- throw e$1;
- }
-}
-var SSRCompatModuleRunner = class extends ModuleRunner {
- constructor(environment) {
- super({
- transport: createServerModuleRunnerTransport({ channel: environment.hot }),
- createImportMeta: createNodeImportMeta,
- sourcemapInterceptor: false,
- hmr: false
- }, new ESModulesEvaluator());
- this.environment = environment;
- }
- async directRequest(url$3, mod, callstack) {
- const id = mod.meta && "id" in mod.meta && mod.meta.id;
- if (!id) return super.directRequest(url$3, mod, callstack);
- const viteMod = this.environment.moduleGraph.getModuleById(id);
- if (!viteMod) return super.directRequest(id, mod, callstack);
- try {
- const exports$1 = await super.directRequest(id, mod, callstack);
- viteMod.ssrModule = exports$1;
- return exports$1;
- } catch (err$2) {
- viteMod.ssrError = err$2;
- throw err$2;
- }
- }
-};
-
-//#endregion
-//#region ../../node_modules/.pnpm/periscopic@4.0.2/node_modules/periscopic/src/index.js
-/**
-* @param {import('estree').Node} param
-* @returns {string[]}
-*/
-function extract_names(param) {
- return extract_identifiers(param).map((node) => node.name);
-}
-/**
-* @param {import('estree').Node} param
-* @param {import('estree').Identifier[]} nodes
-* @returns {import('estree').Identifier[]}
-*/
-function extract_identifiers(param, nodes = []) {
- switch (param.type) {
- case "Identifier":
- nodes.push(param);
- break;
- case "MemberExpression":
- let object = param;
- while (object.type === "MemberExpression") object = object.object;
- nodes.push(object);
- break;
- case "ObjectPattern":
- for (const prop of param.properties) if (prop.type === "RestElement") extract_identifiers(prop.argument, nodes);
- else extract_identifiers(prop.value, nodes);
- break;
- case "ArrayPattern":
- for (const element of param.elements) if (element) extract_identifiers(element, nodes);
- break;
- case "RestElement":
- extract_identifiers(param.argument, nodes);
- break;
- case "AssignmentPattern":
- extract_identifiers(param.left, nodes);
- break;
- }
- return nodes;
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/walker.js
-/**
-* @typedef { import('estree').Node} Node
-* @typedef {{
-* skip: () => void;
-* remove: () => void;
-* replace: (node: Node) => void;
-* }} WalkerContext
-*/
-var WalkerBase = class {
- constructor() {
- /** @type {boolean} */
- this.should_skip = false;
- /** @type {boolean} */
- this.should_remove = false;
- /** @type {Node | null} */
- this.replacement = null;
- /** @type {WalkerContext} */
- this.context = {
- skip: () => this.should_skip = true,
- remove: () => this.should_remove = true,
- replace: (node) => this.replacement = node
- };
- }
- /**
- * @template {Node} Parent
- * @param {Parent | null | undefined} parent
- * @param {keyof Parent | null | undefined} prop
- * @param {number | null | undefined} index
- * @param {Node} node
- */
- replace(parent, prop, index, node) {
- if (parent && prop) if (index != null)
- /** @type {Array<Node>} */ parent[prop][index] = node;
- else
- /** @type {Node} */ parent[prop] = node;
- }
- /**
- * @template {Node} Parent
- * @param {Parent | null | undefined} parent
- * @param {keyof Parent | null | undefined} prop
- * @param {number | null | undefined} index
- */
- remove(parent, prop, index) {
- if (parent && prop) if (index !== null && index !== void 0)
- /** @type {Array<Node>} */ parent[prop].splice(index, 1);
- else delete parent[prop];
- }
-};
-
-//#endregion
-//#region ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/sync.js
-/**
-* @typedef { import('estree').Node} Node
-* @typedef { import('./walker.js').WalkerContext} WalkerContext
-* @typedef {(
-* this: WalkerContext,
-* node: Node,
-* parent: Node | null,
-* key: string | number | symbol | null | undefined,
-* index: number | null | undefined
-* ) => void} SyncHandler
-*/
-var SyncWalker = class extends WalkerBase {
- /**
- *
- * @param {SyncHandler} [enter]
- * @param {SyncHandler} [leave]
- */
- constructor(enter, leave) {
- super();
- /** @type {boolean} */
- this.should_skip = false;
- /** @type {boolean} */
- this.should_remove = false;
- /** @type {Node | null} */
- this.replacement = null;
- /** @type {WalkerContext} */
- this.context = {
- skip: () => this.should_skip = true,
- remove: () => this.should_remove = true,
- replace: (node) => this.replacement = node
- };
- /** @type {SyncHandler | undefined} */
- this.enter = enter;
- /** @type {SyncHandler | undefined} */
- this.leave = leave;
- }
- /**
- * @template {Node} Parent
- * @param {Node} node
- * @param {Parent | null} parent
- * @param {keyof Parent} [prop]
- * @param {number | null} [index]
- * @returns {Node | null}
- */
- visit(node, parent, prop, index) {
- if (node) {
- if (this.enter) {
- const _should_skip = this.should_skip;
- const _should_remove = this.should_remove;
- const _replacement = this.replacement;
- this.should_skip = false;
- this.should_remove = false;
- this.replacement = null;
- this.enter.call(this.context, node, parent, prop, index);
- if (this.replacement) {
- node = this.replacement;
- this.replace(parent, prop, index, node);
- }
- if (this.should_remove) this.remove(parent, prop, index);
- const skipped = this.should_skip;
- const removed = this.should_remove;
- this.should_skip = _should_skip;
- this.should_remove = _should_remove;
- this.replacement = _replacement;
- if (skipped) return node;
- if (removed) return null;
- }
- /** @type {keyof Node} */
- let key;
- for (key in node) {
- /** @type {unknown} */
- const value$1 = node[key];
- if (value$1 && typeof value$1 === "object") {
- if (Array.isArray(value$1)) {
- const nodes = value$1;
- for (let i$1 = 0; i$1 < nodes.length; i$1 += 1) {
- const item = nodes[i$1];
- if (isNode(item)) {
- if (!this.visit(item, node, key, i$1)) i$1--;
- }
- }
- } else if (isNode(value$1)) this.visit(value$1, node, key, null);
- }
- }
- if (this.leave) {
- const _replacement = this.replacement;
- const _should_remove = this.should_remove;
- this.replacement = null;
- this.should_remove = false;
- this.leave.call(this.context, node, parent, prop, index);
- if (this.replacement) {
- node = this.replacement;
- this.replace(parent, prop, index, node);
- }
- if (this.should_remove) this.remove(parent, prop, index);
- const removed = this.should_remove;
- this.replacement = _replacement;
- this.should_remove = _should_remove;
- if (removed) return null;
- }
- }
- return node;
- }
-};
-/**
-* Ducktype a node.
-*
-* @param {unknown} value
-* @returns {value is Node}
-*/
-function isNode(value$1) {
- return value$1 !== null && typeof value$1 === "object" && "type" in value$1 && typeof value$1.type === "string";
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/index.js
-/**
-* @typedef {import('estree').Node} Node
-* @typedef {import('./sync.js').SyncHandler} SyncHandler
-* @typedef {import('./async.js').AsyncHandler} AsyncHandler
-*/
-/**
-* @param {Node} ast
-* @param {{
-* enter?: SyncHandler
-* leave?: SyncHandler
-* }} walker
-* @returns {Node | null}
-*/
-function walk(ast, { enter, leave }) {
- return new SyncWalker(enter, leave).visit(ast, null);
-}
-
-//#endregion
-//#region src/node/ssr/ssrTransform.ts
-const ssrModuleExportsKey = `__vite_ssr_exports__`;
-const ssrImportKey = `__vite_ssr_import__`;
-const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`;
-const ssrExportAllKey = `__vite_ssr_exportAll__`;
-const ssrExportNameKey = `__vite_ssr_exportName__`;
-const ssrImportMetaKey = `__vite_ssr_import_meta__`;
-const hashbangRE = /^#!.*\n/;
-async function ssrTransform(code, inMap, url$3, originalCode, options$1) {
- if (options$1?.json?.stringify && isJSONRequest(url$3)) return ssrTransformJSON(code, inMap);
- return ssrTransformScript(code, inMap, url$3, originalCode);
-}
-async function ssrTransformJSON(code, inMap) {
- return {
- code: code.replace("export default", `${ssrModuleExportsKey}.default =`),
- map: inMap,
- deps: [],
- dynamicDeps: [],
- ssr: true
- };
-}
-async function ssrTransformScript(code, inMap, url$3, originalCode) {
- const s = new MagicString(code);
- let ast;
- try {
- ast = await parseAstAsync(code);
- } catch (err$2) {
- if (err$2.code === "PARSE_ERROR") {
- err$2.message = `Parse failure: ${err$2.message}\n`;
- err$2.id = url$3;
- if (typeof err$2.pos === "number") {
- err$2.loc = numberToPos(code, err$2.pos);
- err$2.loc.file = url$3;
- err$2.frame = generateCodeFrame(code, err$2.pos);
- err$2.message += `At file: ${url$3}:${err$2.loc.line}:${err$2.loc.column}`;
- } else err$2.message += `At file: ${url$3}`;
- }
- throw err$2;
- }
- let uid = 0;
- const deps = /* @__PURE__ */ new Set();
- const dynamicDeps = /* @__PURE__ */ new Set();
- const idToImportMap = /* @__PURE__ */ new Map();
- const declaredConst = /* @__PURE__ */ new Set();
- const fileStartIndex = hashbangRE.exec(code)?.[0].length ?? 0;
- let hoistIndex = fileStartIndex;
- function defineImport(index, importNode, metadata) {
- const source = importNode.source.value;
- deps.add(source);
- const metadataArg = (metadata?.importedNames?.length ?? 0) > 0 ? `, ${JSON.stringify(metadata)}` : "";
- const importId = `__vite_ssr_import_${uid++}__`;
- const transformedImport = `const ${importId} = await ${ssrImportKey}(${JSON.stringify(source)}${metadataArg});\n`;
- s.update(importNode.start, importNode.end, transformedImport);
- if (importNode.start === index) hoistIndex = importNode.end;
- else s.move(importNode.start, importNode.end, index);
- return importId;
- }
- function defineExport(name, local = name) {
- s.appendLeft(fileStartIndex, `${ssrExportNameKey}(${JSON.stringify(name)}, () => { try { return ${local} } catch {} });\n`);
- }
- const imports = [];
- const exports$1 = [];
- const reExportImportIdMap = /* @__PURE__ */ new Map();
- for (const node of ast.body) if (node.type === "ImportDeclaration") imports.push(node);
- else if (node.type === "ExportDefaultDeclaration") exports$1.push(node);
- else if (node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") {
- imports.push(node);
- exports$1.push(node);
- }
- for (const node of imports) {
- if (node.type === "ExportNamedDeclaration") {
- if (node.source) {
- const importId$1 = defineImport(hoistIndex, node, { importedNames: node.specifiers.map((s$1) => getIdentifierNameOrLiteralValue$1(s$1.local)) });
- reExportImportIdMap.set(node, importId$1);
- }
- continue;
- }
- if (node.type === "ExportAllDeclaration") {
- if (node.source) {
- const importId$1 = defineImport(hoistIndex, node);
- reExportImportIdMap.set(node, importId$1);
- }
- continue;
- }
- const importId = defineImport(hoistIndex, node, { importedNames: node.specifiers.map((s$1) => {
- if (s$1.type === "ImportSpecifier") return getIdentifierNameOrLiteralValue$1(s$1.imported);
- else if (s$1.type === "ImportDefaultSpecifier") return "default";
- }).filter(isDefined) });
- for (const spec of node.specifiers) if (spec.type === "ImportSpecifier") if (spec.imported.type === "Identifier") idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`);
- else idToImportMap.set(spec.local.name, `${importId}[${JSON.stringify(spec.imported.value)}]`);
- else if (spec.type === "ImportDefaultSpecifier") idToImportMap.set(spec.local.name, `${importId}.default`);
- else idToImportMap.set(spec.local.name, importId);
- }
- for (const node of exports$1) {
- if (node.type === "ExportNamedDeclaration") if (node.declaration) {
- if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") defineExport(node.declaration.id.name);
- else for (const declaration of node.declaration.declarations) {
- const names = extract_names(declaration.id);
- for (const name of names) defineExport(name);
- }
- s.remove(node.start, node.declaration.start);
- } else if (node.source) {
- const importId = reExportImportIdMap.get(node);
- for (const spec of node.specifiers) {
- const exportedAs = getIdentifierNameOrLiteralValue$1(spec.exported);
- if (spec.local.type === "Identifier") defineExport(exportedAs, `${importId}.${spec.local.name}`);
- else defineExport(exportedAs, `${importId}[${JSON.stringify(spec.local.value)}]`);
- }
- } else {
- s.remove(node.start, node.end);
- for (const spec of node.specifiers) {
- const local = spec.local.name;
- const binding = idToImportMap.get(local);
- defineExport(getIdentifierNameOrLiteralValue$1(spec.exported), binding || local);
- }
- }
- if (node.type === "ExportDefaultDeclaration") if ("id" in node.declaration && node.declaration.id && !["FunctionExpression", "ClassExpression"].includes(node.declaration.type)) {
- const { name } = node.declaration.id;
- s.remove(node.start, node.start + 15);
- defineExport("default", name);
- } else {
- const name = `__vite_ssr_export_default__`;
- s.update(node.start, node.start + 14, `const ${name} =`);
- defineExport("default", name);
- }
- if (node.type === "ExportAllDeclaration") {
- const importId = reExportImportIdMap.get(node);
- if (node.exported) defineExport(getIdentifierNameOrLiteralValue$1(node.exported), `${importId}`);
- else s.appendLeft(node.end, `${ssrExportAllKey}(${importId});\n`);
- }
- }
- walk$1(ast, {
- onStatements(statements) {
- for (let i$1 = 0; i$1 < statements.length - 1; i$1++) {
- const stmt = statements[i$1];
- if (code[stmt.end - 1] !== ";" && stmt.type !== "FunctionDeclaration" && stmt.type !== "ClassDeclaration" && stmt.type !== "BlockStatement" && stmt.type !== "ImportDeclaration") s.appendLeft(stmt.end, ";");
- }
- },
- onIdentifier(id, parent, parentStack) {
- const grandparent = parentStack[1];
- const binding = idToImportMap.get(id.name);
- if (!binding) return;
- if (isStaticProperty(parent) && parent.shorthand) {
- if (!isNodeInPattern(parent) || isInDestructuringAssignment(parent, parentStack)) s.appendLeft(id.end, `: ${binding}`);
- } else if (parent.type === "PropertyDefinition" && grandparent?.type === "ClassBody" || parent.type === "ClassDeclaration" && id === parent.superClass) {
- if (!declaredConst.has(id.name)) {
- declaredConst.add(id.name);
- const topNode = parentStack[parentStack.length - 2];
- s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`);
- }
- } else if (parent.type === "CallExpression") {
- s.update(id.start, id.end, binding);
- s.prependRight(id.start, `(0,`);
- s.appendLeft(id.end, `)`);
- } else if (!(parent.type === "ClassExpression" && id === parent.id)) s.update(id.start, id.end, binding);
- },
- onImportMeta(node) {
- s.update(node.start, node.end, ssrImportMetaKey);
- },
- onDynamicImport(node) {
- s.update(node.start, node.start + 6, ssrDynamicImportKey);
- if (node.type === "ImportExpression" && node.source.type === "Literal") dynamicDeps.add(node.source.value);
- }
- });
- let map$1;
- if (inMap?.mappings === "") map$1 = inMap;
- else {
- map$1 = s.generateMap({ hires: "boundary" });
- map$1.sources = [path.basename(url$3)];
- map$1.sourcesContent = [originalCode];
- if (inMap && inMap.mappings && "sources" in inMap && inMap.sources.length > 0) map$1 = combineSourcemaps(url$3, [map$1, inMap]);
- }
- return {
- code: s.toString(),
- map: map$1,
- ssr: true,
- deps: [...deps],
- dynamicDeps: [...dynamicDeps]
- };
-}
-function getIdentifierNameOrLiteralValue$1(node) {
- return node.type === "Identifier" ? node.name : node.value;
-}
-const isNodeInPatternWeakSet = /* @__PURE__ */ new WeakSet();
-const setIsNodeInPattern = (node) => isNodeInPatternWeakSet.add(node);
-const isNodeInPattern = (node) => isNodeInPatternWeakSet.has(node);
-/**
-* Same logic from \@vue/compiler-core & \@vue/compiler-sfc
-* Except this is using acorn AST
-*/
-function walk$1(root, { onIdentifier, onImportMeta, onDynamicImport, onStatements }) {
- const parentStack = [];
- const varKindStack = [];
- const scopeMap = /* @__PURE__ */ new WeakMap();
- const identifiers = [];
- const setScope = (node, name) => {
- let scopeIds = scopeMap.get(node);
- if (scopeIds && scopeIds.has(name)) return;
- if (!scopeIds) {
- scopeIds = /* @__PURE__ */ new Set();
- scopeMap.set(node, scopeIds);
- }
- scopeIds.add(name);
- };
- function isInScope(name, parents) {
- return parents.some((node) => scopeMap.get(node)?.has(name));
- }
- function handlePattern(p, parentScope) {
- if (p.type === "Identifier") setScope(parentScope, p.name);
- else if (p.type === "RestElement") handlePattern(p.argument, parentScope);
- else if (p.type === "ObjectPattern") p.properties.forEach((property) => {
- if (property.type === "RestElement") setScope(parentScope, property.argument.name);
- else handlePattern(property.value, parentScope);
- });
- else if (p.type === "ArrayPattern") p.elements.forEach((element) => {
- if (element) handlePattern(element, parentScope);
- });
- else if (p.type === "AssignmentPattern") handlePattern(p.left, parentScope);
- else setScope(parentScope, p.name);
- }
- walk(root, {
- enter(node, parent) {
- if (node.type === "ImportDeclaration") return this.skip();
- if (node.type === "Program" || node.type === "BlockStatement" || node.type === "StaticBlock") onStatements(node.body);
- else if (node.type === "SwitchCase") onStatements(node.consequent);
- if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) parentStack.unshift(parent);
- if (node.type === "VariableDeclaration") varKindStack.unshift(node.kind);
- if (node.type === "MetaProperty" && node.meta.name === "import") onImportMeta(node);
- else if (node.type === "ImportExpression") onDynamicImport(node);
- if (node.type === "Identifier") {
- if (!isInScope(node.name, parentStack) && isRefIdentifier(node, parent, parentStack)) identifiers.push([node, parentStack.slice(0)]);
- } else if (isFunction$1(node)) {
- if (node.type === "FunctionDeclaration") {
- const parentScope = findParentScope(parentStack);
- if (parentScope) setScope(parentScope, node.id.name);
- }
- if (node.type === "FunctionExpression" && node.id) setScope(node, node.id.name);
- node.params.forEach((p) => {
- if (p.type === "ObjectPattern" || p.type === "ArrayPattern") {
- handlePattern(p, node);
- return;
- }
- walk(p.type === "AssignmentPattern" ? p.left : p, { enter(child, parent$1) {
- if (parent$1?.type === "AssignmentPattern" && parent$1.right === child) return this.skip();
- if (child.type !== "Identifier") return;
- if (isStaticPropertyKey(child, parent$1)) return;
- if (parent$1?.type === "TemplateLiteral" && parent$1.expressions.includes(child) || parent$1?.type === "CallExpression" && parent$1.callee === child) return;
- setScope(node, child.name);
- } });
- });
- } else if (node.type === "ClassDeclaration") {
- const parentScope = findParentScope(parentStack);
- if (parentScope) setScope(parentScope, node.id.name);
- } else if (node.type === "ClassExpression" && node.id) setScope(node, node.id.name);
- else if (node.type === "Property" && parent.type === "ObjectPattern") setIsNodeInPattern(node);
- else if (node.type === "VariableDeclarator") {
- const parentFunction = findParentScope(parentStack, varKindStack[0] === "var");
- if (parentFunction) handlePattern(node.id, parentFunction);
- } else if (node.type === "CatchClause" && node.param) handlePattern(node.param, node);
- },
- leave(node, parent) {
- if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) parentStack.shift();
- if (node.type === "VariableDeclaration") varKindStack.shift();
- }
- });
- identifiers.forEach(([node, stack]) => {
- if (!isInScope(node.name, stack)) onIdentifier(node, stack[0], stack);
- });
-}
-function isRefIdentifier(id, parent, parentStack) {
- if (parent.type === "CatchClause" || (parent.type === "VariableDeclarator" || parent.type === "ClassDeclaration") && parent.id === id) return false;
- if (isFunction$1(parent)) {
- if (parent.id === id) return false;
- if (parent.params.includes(id)) return false;
- }
- if (parent.type === "MethodDefinition" && !parent.computed) return false;
- if (isStaticPropertyKey(id, parent)) return false;
- if (isNodeInPattern(parent) && parent.value === id) return false;
- if (parent.type === "ArrayPattern" && !isInDestructuringAssignment(parent, parentStack)) return false;
- if (parent.type === "MemberExpression" && parent.property === id && !parent.computed) return false;
- if (parent.type === "ExportSpecifier" || parent.type === "ExportAllDeclaration") return false;
- if (id.name === "arguments") return false;
- return true;
-}
-const isStaticProperty = (node) => node.type === "Property" && !node.computed;
-const isStaticPropertyKey = (node, parent) => parent && isStaticProperty(parent) && parent.key === node;
-const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/;
-function isFunction$1(node) {
- return functionNodeTypeRE.test(node.type);
-}
-const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/;
-function isBlock(node) {
- return blockNodeTypeRE.test(node.type);
-}
-function findParentScope(parentStack, isVar = false) {
- return parentStack.find(isVar ? isFunction$1 : isBlock);
-}
-function isInDestructuringAssignment(parent, parentStack) {
- if (parent.type === "Property" || parent.type === "ArrayPattern") return parentStack.some((i$1) => i$1.type === "AssignmentExpression");
- return false;
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js
-let isDockerCached;
-function hasDockerEnv() {
- try {
- fs.statSync("/.dockerenv");
- return true;
- } catch {
- return false;
- }
-}
-function hasDockerCGroup() {
- try {
- return fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
- } catch {
- return false;
- }
-}
-function isDocker() {
- if (isDockerCached === void 0) isDockerCached = hasDockerEnv() || hasDockerCGroup();
- return isDockerCached;
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
-let cachedResult;
-const hasContainerEnv = () => {
- try {
- fs.statSync("/run/.containerenv");
- return true;
- } catch {
- return false;
- }
-};
-function isInsideContainer() {
- if (cachedResult === void 0) cachedResult = hasContainerEnv() || isDocker();
- return cachedResult;
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js
-const isWsl = () => {
- if (process$1.platform !== "linux") return false;
- if (os.release().toLowerCase().includes("microsoft")) {
- if (isInsideContainer()) return false;
- return true;
- }
- try {
- return fs.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isInsideContainer() : false;
- } catch {
- return false;
- }
-};
-var is_wsl_default = process$1.env.__IS_WSL_TEST__ ? isWsl : isWsl();
-
-//#endregion
-//#region ../../node_modules/.pnpm/wsl-utils@0.1.0/node_modules/wsl-utils/index.js
-const wslDrivesMountPoint = (() => {
- const defaultMountPoint = "/mnt/";
- let mountPoint;
- return async function() {
- if (mountPoint) return mountPoint;
- const configFilePath = "/etc/wsl.conf";
- let isConfigFileExists = false;
- try {
- await fsp.access(configFilePath, constants.F_OK);
- isConfigFileExists = true;
- } catch {}
- if (!isConfigFileExists) return defaultMountPoint;
- const configContent = await fsp.readFile(configFilePath, { encoding: "utf8" });
- const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
- if (!configMountPoint) return defaultMountPoint;
- mountPoint = configMountPoint.groups.mountPoint.trim();
- mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
- return mountPoint;
- };
-})();
-const powerShellPathFromWsl = async () => {
- return `${await wslDrivesMountPoint()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
-};
-const powerShellPath = async () => {
- if (is_wsl_default) return powerShellPathFromWsl();
- return `${process$1.env.SYSTEMROOT || process$1.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
-};
-
-//#endregion
-//#region ../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js
-function defineLazyProperty(object, propertyName, valueGetter) {
- const define$1 = (value$1) => Object.defineProperty(object, propertyName, {
- value: value$1,
- enumerable: true,
- writable: true
- });
- Object.defineProperty(object, propertyName, {
- configurable: true,
- enumerable: true,
- get() {
- const result = valueGetter();
- define$1(result);
- return result;
- },
- set(value$1) {
- define$1(value$1);
- }
- });
- return object;
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/default-browser-id@5.0.0/node_modules/default-browser-id/index.js
-const execFileAsync$3 = promisify(execFile);
-async function defaultBrowserId() {
- if (process$1.platform !== "darwin") throw new Error("macOS only");
- const { stdout } = await execFileAsync$3("defaults", [
- "read",
- "com.apple.LaunchServices/com.apple.launchservices.secure",
- "LSHandlers"
- ]);
- return /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout)?.groups.id ?? "com.apple.Safari";
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/run-applescript@7.0.0/node_modules/run-applescript/index.js
-const execFileAsync$2 = promisify(execFile);
-async function runAppleScript(script, { humanReadableOutput = true } = {}) {
- if (process$1.platform !== "darwin") throw new Error("macOS only");
- const { stdout } = await execFileAsync$2("osascript", [
- "-e",
- script,
- humanReadableOutput ? [] : ["-ss"]
- ]);
- return stdout.trim();
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
-async function bundleName(bundleId) {
- return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/default-browser@5.2.1/node_modules/default-browser/windows.js
-const execFileAsync$1 = promisify(execFile);
-const windowsBrowserProgIds = {
- AppXq0fevzme2pys62n3e0fbqa7peapykr8v: {
- name: "Edge",
- id: "com.microsoft.edge.old"
- },
- MSEdgeDHTML: {
- name: "Edge",
- id: "com.microsoft.edge"
- },
- MSEdgeHTM: {
- name: "Edge",
- id: "com.microsoft.edge"
- },
- "IE.HTTP": {
- name: "Internet Explorer",
- id: "com.microsoft.ie"
- },
- FirefoxURL: {
- name: "Firefox",
- id: "org.mozilla.firefox"
- },
- ChromeHTML: {
- name: "Chrome",
- id: "com.google.chrome"
- },
- BraveHTML: {
- name: "Brave",
- id: "com.brave.Browser"
- },
- BraveBHTML: {
- name: "Brave Beta",
- id: "com.brave.Browser.beta"
- },
- BraveSSHTM: {
- name: "Brave Nightly",
- id: "com.brave.Browser.nightly"
- }
-};
-var UnknownBrowserError = class extends Error {};
-async function defaultBrowser$1(_execFileAsync = execFileAsync$1) {
- const { stdout } = await _execFileAsync("reg", [
- "QUERY",
- " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
- "/v",
- "ProgId"
- ]);
- const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
- if (!match) throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
- const { id } = match.groups;
- const browser = windowsBrowserProgIds[id];
- if (!browser) throw new UnknownBrowserError(`Unknown browser ID: ${id}`);
- return browser;
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/default-browser@5.2.1/node_modules/default-browser/index.js
-const execFileAsync = promisify(execFile);
-const titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
-async function defaultBrowser() {
- if (process$1.platform === "darwin") {
- const id = await defaultBrowserId();
- return {
- name: await bundleName(id),
- id
- };
- }
- if (process$1.platform === "linux") {
- const { stdout } = await execFileAsync("xdg-mime", [
- "query",
- "default",
- "x-scheme-handler/http"
- ]);
- const id = stdout.trim();
- return {
- name: titleize(id.replace(/.desktop$/, "").replace("-", " ")),
- id
- };
- }
- if (process$1.platform === "win32") return defaultBrowser$1();
- throw new Error("Only macOS, Linux, and Windows are supported");
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/open@10.2.0/node_modules/open/index.js
-const execFile$1 = promisify(childProcess.execFile);
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const localXdgOpenPath = path.join(__dirname, "xdg-open");
-const { platform, arch } = process$1;
-/**
-Get the default browser name in Windows from WSL.
-
-@returns {Promise<string>} Browser name.
-*/
-async function getWindowsDefaultBrowserFromWsl() {
- const powershellPath = await powerShellPath();
- const rawCommand = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
- const { stdout } = await execFile$1(powershellPath, [
- "-NoProfile",
- "-NonInteractive",
- "-ExecutionPolicy",
- "Bypass",
- "-EncodedCommand",
- Buffer$1.from(rawCommand, "utf16le").toString("base64")
- ], { encoding: "utf8" });
- const progId = stdout.trim();
- const browserMap = {
- ChromeHTML: "com.google.chrome",
- BraveHTML: "com.brave.Browser",
- MSEdgeHTM: "com.microsoft.edge",
- FirefoxURL: "org.mozilla.firefox"
- };
- return browserMap[progId] ? { id: browserMap[progId] } : {};
-}
-const pTryEach = async (array, mapper) => {
- let latestError;
- for (const item of array) try {
- return await mapper(item);
- } catch (error$1) {
- latestError = error$1;
- }
- throw latestError;
-};
-const baseOpen = async (options$1) => {
- options$1 = {
- wait: false,
- background: false,
- newInstance: false,
- allowNonzeroExitCode: false,
- ...options$1
- };
- if (Array.isArray(options$1.app)) return pTryEach(options$1.app, (singleApp) => baseOpen({
- ...options$1,
- app: singleApp
- }));
- let { name: app, arguments: appArguments = [] } = options$1.app ?? {};
- appArguments = [...appArguments];
- if (Array.isArray(app)) return pTryEach(app, (appName) => baseOpen({
- ...options$1,
- app: {
- name: appName,
- arguments: appArguments
- }
- }));
- if (app === "browser" || app === "browserPrivate") {
- const ids = {
- "com.google.chrome": "chrome",
- "google-chrome.desktop": "chrome",
- "com.brave.Browser": "brave",
- "org.mozilla.firefox": "firefox",
- "firefox.desktop": "firefox",
- "com.microsoft.msedge": "edge",
- "com.microsoft.edge": "edge",
- "com.microsoft.edgemac": "edge",
- "microsoft-edge.desktop": "edge"
- };
- const flags = {
- chrome: "--incognito",
- brave: "--incognito",
- firefox: "--private-window",
- edge: "--inPrivate"
- };
- const browser = is_wsl_default ? await getWindowsDefaultBrowserFromWsl() : await defaultBrowser();
- if (browser.id in ids) {
- const browserName = ids[browser.id];
- if (app === "browserPrivate") appArguments.push(flags[browserName]);
- return baseOpen({
- ...options$1,
- app: {
- name: apps[browserName],
- arguments: appArguments
- }
- });
- }
- throw new Error(`${browser.name} is not supported as a default browser`);
- }
- let command;
- const cliArguments = [];
- const childProcessOptions = {};
- if (platform === "darwin") {
- command = "open";
- if (options$1.wait) cliArguments.push("--wait-apps");
- if (options$1.background) cliArguments.push("--background");
- if (options$1.newInstance) cliArguments.push("--new");
- if (app) cliArguments.push("-a", app);
- } else if (platform === "win32" || is_wsl_default && !isInsideContainer() && !app) {
- command = await powerShellPath();
- cliArguments.push("-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand");
- if (!is_wsl_default) childProcessOptions.windowsVerbatimArguments = true;
- const encodedArguments = ["Start"];
- if (options$1.wait) encodedArguments.push("-Wait");
- if (app) {
- encodedArguments.push(`"\`"${app}\`""`);
- if (options$1.target) appArguments.push(options$1.target);
- } else if (options$1.target) encodedArguments.push(`"${options$1.target}"`);
- if (appArguments.length > 0) {
- appArguments = appArguments.map((argument) => `"\`"${argument}\`""`);
- encodedArguments.push("-ArgumentList", appArguments.join(","));
- }
- options$1.target = Buffer$1.from(encodedArguments.join(" "), "utf16le").toString("base64");
- } else {
- if (app) command = app;
- else {
- const isBundled = !__dirname || __dirname === "/";
- let exeLocalXdgOpen = false;
- try {
- await fsp.access(localXdgOpenPath, constants.X_OK);
- exeLocalXdgOpen = true;
- } catch {}
- command = process$1.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen) ? "xdg-open" : localXdgOpenPath;
- }
- if (appArguments.length > 0) cliArguments.push(...appArguments);
- if (!options$1.wait) {
- childProcessOptions.stdio = "ignore";
- childProcessOptions.detached = true;
- }
- }
- if (platform === "darwin" && appArguments.length > 0) cliArguments.push("--args", ...appArguments);
- if (options$1.target) cliArguments.push(options$1.target);
- const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
- if (options$1.wait) return new Promise((resolve$4, reject) => {
- subprocess.once("error", reject);
- subprocess.once("close", (exitCode) => {
- if (!options$1.allowNonzeroExitCode && exitCode > 0) {
- reject(/* @__PURE__ */ new Error(`Exited with code ${exitCode}`));
- return;
- }
- resolve$4(subprocess);
- });
- });
- subprocess.unref();
- return subprocess;
-};
-const open = (target, options$1) => {
- if (typeof target !== "string") throw new TypeError("Expected a `target`");
- return baseOpen({
- ...options$1,
- target
- });
-};
-function detectArchBinary(binary) {
- if (typeof binary === "string" || Array.isArray(binary)) return binary;
- const { [arch]: archBinary } = binary;
- if (!archBinary) throw new Error(`${arch} is not supported`);
- return archBinary;
-}
-function detectPlatformBinary({ [platform]: platformBinary }, { wsl }) {
- if (wsl && is_wsl_default) return detectArchBinary(wsl);
- if (!platformBinary) throw new Error(`${platform} is not supported`);
- return detectArchBinary(platformBinary);
-}
-const apps = {};
-defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
- darwin: "google chrome",
- win32: "chrome",
- linux: [
- "google-chrome",
- "google-chrome-stable",
- "chromium"
- ]
-}, { wsl: {
- ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
- x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
-} }));
-defineLazyProperty(apps, "brave", () => detectPlatformBinary({
- darwin: "brave browser",
- win32: "brave",
- linux: ["brave-browser", "brave"]
-}, { wsl: {
- ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
- x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
-} }));
-defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
- darwin: "firefox",
- win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
- linux: "firefox"
-}, { wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe" }));
-defineLazyProperty(apps, "edge", () => detectPlatformBinary({
- darwin: "microsoft edge",
- win32: "msedge",
- linux: ["microsoft-edge", "microsoft-edge-dev"]
-}, { wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" }));
-defineLazyProperty(apps, "browser", () => "browser");
-defineLazyProperty(apps, "browserPrivate", () => "browserPrivate");
-var open_default = open;
-
-//#endregion
-//#region ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js
-var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = isexe$3;
- isexe$3.sync = sync$2;
- var fs$4 = __require("fs");
- function checkPathExt(path$13, options$1) {
- var pathext = options$1.pathExt !== void 0 ? options$1.pathExt : process.env.PATHEXT;
- if (!pathext) return true;
- pathext = pathext.split(";");
- if (pathext.indexOf("") !== -1) return true;
- for (var i$1 = 0; i$1 < pathext.length; i$1++) {
- var p = pathext[i$1].toLowerCase();
- if (p && path$13.substr(-p.length).toLowerCase() === p) return true;
- }
- return false;
- }
- function checkStat$1(stat$4, path$13, options$1) {
- if (!stat$4.isSymbolicLink() && !stat$4.isFile()) return false;
- return checkPathExt(path$13, options$1);
- }
- function isexe$3(path$13, options$1, cb) {
- fs$4.stat(path$13, function(er, stat$4) {
- cb(er, er ? false : checkStat$1(stat$4, path$13, options$1));
- });
- }
- function sync$2(path$13, options$1) {
- return checkStat$1(fs$4.statSync(path$13), path$13, options$1);
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js
-var require_mode = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = isexe$2;
- isexe$2.sync = sync$1;
- var fs$3 = __require("fs");
- function isexe$2(path$13, options$1, cb) {
- fs$3.stat(path$13, function(er, stat$4) {
- cb(er, er ? false : checkStat(stat$4, options$1));
- });
- }
- function sync$1(path$13, options$1) {
- return checkStat(fs$3.statSync(path$13), options$1);
- }
- function checkStat(stat$4, options$1) {
- return stat$4.isFile() && checkMode(stat$4, options$1);
- }
- function checkMode(stat$4, options$1) {
- var mod = stat$4.mode;
- var uid = stat$4.uid;
- var gid = stat$4.gid;
- var myUid = options$1.uid !== void 0 ? options$1.uid : process.getuid && process.getuid();
- var myGid = options$1.gid !== void 0 ? options$1.gid : process.getgid && process.getgid();
- var u = parseInt("100", 8);
- var g = parseInt("010", 8);
- var o$1 = parseInt("001", 8);
- var ug = u | g;
- return mod & o$1 || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js
-var require_isexe = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- __require("fs");
- var core;
- if (process.platform === "win32" || global.TESTING_WINDOWS) core = require_windows();
- else core = require_mode();
- module.exports = isexe$1;
- isexe$1.sync = sync;
- function isexe$1(path$13, options$1, cb) {
- if (typeof options$1 === "function") {
- cb = options$1;
- options$1 = {};
- }
- if (!cb) {
- if (typeof Promise !== "function") throw new TypeError("callback not provided");
- return new Promise(function(resolve$4, reject) {
- isexe$1(path$13, options$1 || {}, function(er, is) {
- if (er) reject(er);
- else resolve$4(is);
- });
- });
- }
- core(path$13, options$1 || {}, function(er, is) {
- if (er) {
- if (er.code === "EACCES" || options$1 && options$1.ignoreErrors) {
- er = null;
- is = false;
- }
- }
- cb(er, is);
- });
- }
- function sync(path$13, options$1) {
- try {
- return core.sync(path$13, options$1 || {});
- } catch (er) {
- if (options$1 && options$1.ignoreErrors || er.code === "EACCES") return false;
- else throw er;
- }
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js
-var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const isWindows$1 = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
- const path$4 = __require("path");
- const COLON = isWindows$1 ? ";" : ":";
- const isexe = require_isexe();
- const getNotFoundError = (cmd) => Object.assign(/* @__PURE__ */ new Error(`not found: ${cmd}`), { code: "ENOENT" });
- const getPathInfo = (cmd, opt) => {
- const colon = opt.colon || COLON;
- const pathEnv = cmd.match(/\//) || isWindows$1 && cmd.match(/\\/) ? [""] : [...isWindows$1 ? [process.cwd()] : [], ...(opt.path || process.env.PATH || "").split(colon)];
- const pathExtExe = isWindows$1 ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
- const pathExt = isWindows$1 ? pathExtExe.split(colon) : [""];
- if (isWindows$1) {
- if (cmd.indexOf(".") !== -1 && pathExt[0] !== "") pathExt.unshift("");
- }
- return {
- pathEnv,
- pathExt,
- pathExtExe
- };
- };
- const which$1 = (cmd, opt, cb) => {
- if (typeof opt === "function") {
- cb = opt;
- opt = {};
- }
- if (!opt) opt = {};
- const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
- const found$1 = [];
- const step = (i$1) => new Promise((resolve$4, reject) => {
- if (i$1 === pathEnv.length) return opt.all && found$1.length ? resolve$4(found$1) : reject(getNotFoundError(cmd));
- const ppRaw = pathEnv[i$1];
- const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
- const pCmd = path$4.join(pathPart, cmd);
- resolve$4(subStep(!pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd, i$1, 0));
- });
- const subStep = (p, i$1, ii) => new Promise((resolve$4, reject) => {
- if (ii === pathExt.length) return resolve$4(step(i$1 + 1));
- const ext = pathExt[ii];
- isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
- if (!er && is) if (opt.all) found$1.push(p + ext);
- else return resolve$4(p + ext);
- return resolve$4(subStep(p, i$1, 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$1 = [];
- for (let i$1 = 0; i$1 < pathEnv.length; i$1++) {
- const ppRaw = pathEnv[i$1];
- const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
- const pCmd = path$4.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 {
- if (isexe.sync(cur, { pathExt: pathExtExe })) if (opt.all) found$1.push(cur);
- else return cur;
- } catch (ex) {}
- }
- }
- if (opt.all && found$1.length) return found$1;
- if (opt.nothrow) return null;
- throw getNotFoundError(cmd);
- };
- module.exports = which$1;
- which$1.sync = whichSync;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js
-var require_path_key = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const pathKey = (options$1 = {}) => {
- const environment = options$1.env || process.env;
- if ((options$1.platform || process.platform) !== "win32") return "PATH";
- return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
- };
- module.exports = pathKey;
- module.exports.default = pathKey;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js
-var require_resolveCommand = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const path$3 = __require("path");
- const which = require_which();
- const getPathKey = require_path_key();
- function resolveCommandAttempt(parsed, withoutPathExt) {
- const env$1 = parsed.options.env || process.env;
- const cwd = process.cwd();
- const hasCustomCwd = parsed.options.cwd != null;
- const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
- if (shouldSwitchCwd) try {
- process.chdir(parsed.options.cwd);
- } catch (err$2) {}
- let resolved;
- try {
- resolved = which.sync(parsed.command, {
- path: env$1[getPathKey({ env: env$1 })],
- pathExt: withoutPathExt ? path$3.delimiter : void 0
- });
- } catch (e$1) {} finally {
- if (shouldSwitchCwd) process.chdir(cwd);
- }
- if (resolved) resolved = path$3.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
- return resolved;
- }
- function resolveCommand$1(parsed) {
- return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
- }
- module.exports = resolveCommand$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js
-var require_escape = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
- function escapeCommand(arg) {
- arg = arg.replace(metaCharsRegExp, "^$1");
- return arg;
- }
- function escapeArgument(arg, doubleEscapeMetaChars) {
- arg = `${arg}`;
- arg = arg.replace(/(?=(\\+?)?)\1"/g, "$1$1\\\"");
- arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
- arg = `"${arg}"`;
- arg = arg.replace(metaCharsRegExp, "^$1");
- if (doubleEscapeMetaChars) arg = arg.replace(metaCharsRegExp, "^$1");
- return arg;
- }
- module.exports.command = escapeCommand;
- module.exports.argument = escapeArgument;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js
-var require_shebang_regex = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = /^#!(.*)/;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js
-var require_shebang_command = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const shebangRegex = require_shebang_regex();
- module.exports = (string = "") => {
- const match = string.match(shebangRegex);
- if (!match) return null;
- const [path$13, argument] = match[0].replace(/#! ?/, "").split(" ");
- const binary = path$13.split("/").pop();
- if (binary === "env") return argument;
- return argument ? `${binary} ${argument}` : binary;
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js
-var require_readShebang = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const fs$2 = __require("fs");
- const shebangCommand = require_shebang_command();
- function readShebang$1(command) {
- const size = 150;
- const buffer = Buffer.alloc(size);
- let fd;
- try {
- fd = fs$2.openSync(command, "r");
- fs$2.readSync(fd, buffer, 0, size, 0);
- fs$2.closeSync(fd);
- } catch (e$1) {}
- return shebangCommand(buffer.toString());
- }
- module.exports = readShebang$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js
-var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const path$2 = __require("path");
- const resolveCommand = require_resolveCommand();
- const escape$1 = require_escape();
- const readShebang = require_readShebang();
- const isWin$1 = 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$1) return parsed;
- const commandFile = detectShebang(parsed);
- const needsShell = !isExecutableRegExp.test(commandFile);
- if (parsed.options.forceShell || needsShell) {
- const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
- parsed.command = path$2.normalize(parsed.command);
- parsed.command = escape$1.command(parsed.command);
- parsed.args = parsed.args.map((arg) => escape$1.argument(arg, needsDoubleEscapeMetaChars));
- parsed.args = [
- "/d",
- "/s",
- "/c",
- `"${[parsed.command].concat(parsed.args).join(" ")}"`
- ];
- parsed.command = process.env.comspec || "cmd.exe";
- parsed.options.windowsVerbatimArguments = true;
- }
- return parsed;
- }
- function parse$6(command, args, options$1) {
- if (args && !Array.isArray(args)) {
- options$1 = args;
- args = null;
- }
- args = args ? args.slice(0) : [];
- options$1 = Object.assign({}, options$1);
- const parsed = {
- command,
- args,
- options: options$1,
- file: void 0,
- original: {
- command,
- args
- }
- };
- return options$1.shell ? parsed : parseNonShell(parsed);
- }
- module.exports = parse$6;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js
-var require_enoent = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const isWin = process.platform === "win32";
- function notFoundError(original, syscall) {
- return Object.assign(/* @__PURE__ */ new Error(`${syscall} ${original.command} ENOENT`), {
- code: "ENOENT",
- errno: "ENOENT",
- syscall: `${syscall} ${original.command}`,
- path: original.command,
- spawnargs: original.args
- });
- }
- function hookChildProcess(cp$1, parsed) {
- if (!isWin) return;
- const originalEmit = cp$1.emit;
- cp$1.emit = function(name, arg1) {
- if (name === "exit") {
- const err$2 = verifyENOENT(arg1, parsed);
- if (err$2) return originalEmit.call(cp$1, "error", err$2);
- }
- return originalEmit.apply(cp$1, arguments);
- };
- }
- function verifyENOENT(status$1, parsed) {
- if (isWin && status$1 === 1 && !parsed.file) return notFoundError(parsed.original, "spawn");
- return null;
- }
- function verifyENOENTSync(status$1, parsed) {
- if (isWin && status$1 === 1 && !parsed.file) return notFoundError(parsed.original, "spawnSync");
- return null;
- }
- module.exports = {
- hookChildProcess,
- verifyENOENT,
- verifyENOENTSync,
- notFoundError
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js
-var require_cross_spawn = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const cp = __require("child_process");
- const parse$5 = require_parse();
- const enoent = require_enoent();
- function spawn$1(command, args, options$1) {
- const parsed = parse$5(command, args, options$1);
- const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
- enoent.hookChildProcess(spawned, parsed);
- return spawned;
- }
- function spawnSync(command, args, options$1) {
- const parsed = parse$5(command, args, options$1);
- const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
- result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
- return result;
- }
- module.exports = spawn$1;
- module.exports.spawn = spawn$1;
- module.exports.sync = spawnSync;
- module.exports._parse = parse$5;
- module.exports._enoent = enoent;
-}));
-
-//#endregion
-//#region src/node/server/openBrowser.ts
-/**
-* The following is modified based on source found in
-* https://github.com/facebook/create-react-app
-*
-* MIT Licensed
-* Copyright (c) 2015-present, Facebook, Inc.
-* https://github.com/facebook/create-react-app/blob/main/LICENSE
-*
-*/
-var import_cross_spawn = /* @__PURE__ */ __toESM(require_cross_spawn(), 1);
-var import_picocolors$24 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-/**
-* Reads the BROWSER environment variable and decides what to do with it.
-*/
-function openBrowser(url$3, opt, logger) {
- const browser = typeof opt === "string" ? opt : process.env.BROWSER || "";
- if (browser.toLowerCase().endsWith(".js")) executeNodeScript(browser, url$3, logger);
- else if (browser.toLowerCase() !== "none") startBrowserProcess(browser, process.env.BROWSER_ARGS ? process.env.BROWSER_ARGS.split(" ") : [], url$3, logger);
-}
-function executeNodeScript(scriptPath, url$3, logger) {
- const extraArgs = process.argv.slice(2);
- (0, import_cross_spawn.default)(process.execPath, [
- scriptPath,
- ...extraArgs,
- url$3
- ], { stdio: "inherit" }).on("close", (code) => {
- if (code !== 0) logger.error(import_picocolors$24.default.red(`\nThe script specified as BROWSER environment variable failed.\n\n${import_picocolors$24.default.cyan(scriptPath)} exited with code ${code}.`), { error: null });
- });
-}
-const supportedChromiumBrowsers = [
- "Google Chrome Canary",
- "Google Chrome Dev",
- "Google Chrome Beta",
- "Google Chrome",
- "Microsoft Edge",
- "Brave Browser",
- "Vivaldi",
- "Chromium"
-];
-async function startBrowserProcess(browser, browserArgs, url$3, logger) {
- const preferredOSXBrowser = browser === "google chrome" ? "Google Chrome" : browser;
- if (process.platform === "darwin" && (!preferredOSXBrowser || supportedChromiumBrowsers.includes(preferredOSXBrowser))) try {
- const ps = await execAsync("ps cax");
- const openedBrowser = preferredOSXBrowser && ps.includes(preferredOSXBrowser) ? preferredOSXBrowser : supportedChromiumBrowsers.find((b) => ps.includes(b));
- if (openedBrowser) {
- await execAsync(`osascript openChrome.js "${url$3}" "${openedBrowser}"`, { cwd: join(VITE_PACKAGE_DIR, "bin") });
- return true;
- }
- } catch {}
- if (process.platform === "darwin" && browser === "open") browser = void 0;
- try {
- const options$1 = browser ? { app: {
- name: browser,
- arguments: browserArgs
- } } : {};
- new Promise((_, reject) => {
- open_default(url$3, options$1).then((subprocess) => {
- subprocess.on("error", reject);
- }).catch(reject);
- }).catch((err$2) => {
- logger.error(err$2.stack || err$2.message);
- });
- return true;
- } catch {
- return false;
- }
-}
-function execAsync(command, options$1) {
- return new Promise((resolve$4, reject) => {
- exec(command, options$1, (error$1, stdout) => {
- if (error$1) reject(error$1);
- else resolve$4(stdout.toString());
- });
- });
-}
-
-//#endregion
-//#region src/node/shortcuts.ts
-var import_picocolors$23 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-function bindCLIShortcuts(server, opts, enabled = process.stdin.isTTY && !process.env.CI) {
- if (!server.httpServer || !enabled) return;
- const isDev = isDevServer(server);
- const previousShortcuts = server._shortcutsState?.options.customShortcuts ?? [];
- const newShortcuts = opts?.customShortcuts ?? [];
- const previousKeys = new Set(previousShortcuts.map((s) => s.key));
- const customShortcuts = [...newShortcuts.filter((s) => !previousKeys.has(s.key)), ...previousShortcuts.map((s) => newShortcuts.find((n$2) => n$2.key === s.key) ?? s)];
- const newOptions = {
- ...opts,
- customShortcuts
- };
- if (opts?.print) server.config.logger.info(import_picocolors$23.default.dim(import_picocolors$23.default.green(" ➜")) + import_picocolors$23.default.dim(" press ") + import_picocolors$23.default.bold("h + enter") + import_picocolors$23.default.dim(" to show help"));
- const shortcuts = customShortcuts.concat(isDev ? BASE_DEV_SHORTCUTS : BASE_PREVIEW_SHORTCUTS);
- let actionRunning = false;
- const onInput = async (input) => {
- if (actionRunning) return;
- if (input === "h") {
- const loggedKeys = /* @__PURE__ */ new Set();
- server.config.logger.info("\n Shortcuts");
- for (const shortcut$1 of shortcuts) {
- if (loggedKeys.has(shortcut$1.key)) continue;
- loggedKeys.add(shortcut$1.key);
- if (shortcut$1.action == null) continue;
- server.config.logger.info(import_picocolors$23.default.dim(" press ") + import_picocolors$23.default.bold(`${shortcut$1.key} + enter`) + import_picocolors$23.default.dim(` to ${shortcut$1.description}`));
- }
- return;
- }
- const shortcut = shortcuts.find((shortcut$1) => shortcut$1.key === input);
- if (!shortcut || shortcut.action == null) return;
- actionRunning = true;
- await shortcut.action(server);
- actionRunning = false;
- };
- if (!server._shortcutsState) {
- server._shortcutsState = {
- rl: readline.createInterface({ input: process.stdin }),
- options: newOptions
- };
- server.httpServer.on("close", () => {
- if (server._shortcutsState) server._shortcutsState.rl.close();
- });
- } else {
- server._shortcutsState.rl.removeAllListeners("line");
- server._shortcutsState.options = newOptions;
- }
- server._shortcutsState.rl.on("line", onInput);
-}
-const BASE_DEV_SHORTCUTS = [
- {
- key: "r",
- description: "restart the server",
- async action(server) {
- await restartServerWithUrls(server);
- }
- },
- {
- key: "u",
- description: "show server url",
- action(server) {
- server.config.logger.info("");
- server.printUrls();
- }
- },
- {
- key: "o",
- description: "open in browser",
- action(server) {
- server.openBrowser();
- }
- },
- {
- key: "c",
- description: "clear console",
- action(server) {
- server.config.logger.clearScreen("error");
- }
- },
- {
- key: "q",
- description: "quit",
- async action(server) {
- try {
- await server.close();
- } finally {
- process.exit();
- }
- }
- }
-];
-const BASE_PREVIEW_SHORTCUTS = [{
- key: "o",
- description: "open in browser",
- action(server) {
- const url$3 = server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0];
- if (url$3) openBrowser(url$3, true, server.config.logger);
- else server.config.logger.warn("No URL available to open in browser");
- }
-}, {
- key: "q",
- description: "quit",
- async action(server) {
- try {
- await server.close();
- } finally {
- process.exit();
- }
- }
-}];
-
-//#endregion
-//#region src/node/watch.ts
-var import_picocolors$22 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-function getResolvedOutDirs(root, outDir, outputOptions) {
- const resolvedOutDir = path.resolve(root, outDir);
- if (!outputOptions) return new Set([resolvedOutDir]);
- return new Set(arraify(outputOptions).map(({ dir }) => dir ? path.resolve(root, dir) : resolvedOutDir));
-}
-function resolveEmptyOutDir(emptyOutDir, root, outDirs, logger) {
- if (emptyOutDir != null) return emptyOutDir;
- for (const outDir of outDirs) if (!normalizePath(outDir).startsWith(withTrailingSlash(root))) {
- logger?.warn(import_picocolors$22.default.yellow(`\n${import_picocolors$22.default.bold(`(!)`)} outDir ${import_picocolors$22.default.white(import_picocolors$22.default.dim(outDir))} is not inside project root and will not be emptied.\nUse --emptyOutDir to override.\n`));
- return false;
- }
- return true;
-}
-function resolveChokidarOptions(options$1, resolvedOutDirs, emptyOutDir, cacheDir) {
- const { ignored: ignoredList, ...otherOptions } = options$1 ?? {};
- const ignored = [
- "**/.git/**",
- "**/node_modules/**",
- "**/test-results/**",
- escapePath(cacheDir) + "/**",
- ...arraify(ignoredList || [])
- ];
- if (emptyOutDir) ignored.push(...[...resolvedOutDirs].map((outDir) => escapePath(outDir) + "/**"));
- return {
- ignored,
- ignoreInitial: true,
- ignorePermissionErrors: true,
- ...otherOptions
- };
-}
-var NoopWatcher = class extends EventEmitter {
- constructor(options$1) {
- super();
- this.options = options$1;
- }
- add() {
- return this;
- }
- unwatch() {
- return this;
- }
- getWatched() {
- return {};
- }
- ref() {
- return this;
- }
- unref() {
- return this;
- }
- async close() {}
-};
-function createNoopWatcher(options$1) {
- return new NoopWatcher(options$1);
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/constants.js
-var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const BINARY_TYPES$2 = [
- "nodebuffer",
- "arraybuffer",
- "fragments"
- ];
- const hasBlob$1 = typeof Blob !== "undefined";
- if (hasBlob$1) BINARY_TYPES$2.push("blob");
- module.exports = {
- BINARY_TYPES: BINARY_TYPES$2,
- EMPTY_BUFFER: Buffer.alloc(0),
- GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
- hasBlob: hasBlob$1,
- kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
- kListener: Symbol("kListener"),
- kStatusCode: Symbol("status-code"),
- kWebSocket: Symbol("websocket"),
- NOOP: () => {}
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/buffer-util.js
-var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const { EMPTY_BUFFER: EMPTY_BUFFER$3 } = require_constants();
- const FastBuffer$2 = Buffer[Symbol.species];
- /**
- * Merges an array of buffers into a new buffer.
- *
- * @param {Buffer[]} list The array of buffers to concat
- * @param {Number} totalLength The total length of buffers in the list
- * @return {Buffer} The resulting buffer
- * @public
- */
- function concat$1(list, totalLength) {
- if (list.length === 0) return EMPTY_BUFFER$3;
- if (list.length === 1) return list[0];
- const target = Buffer.allocUnsafe(totalLength);
- let offset$1 = 0;
- for (let i$1 = 0; i$1 < list.length; i$1++) {
- const buf = list[i$1];
- target.set(buf, offset$1);
- offset$1 += buf.length;
- }
- if (offset$1 < totalLength) return new FastBuffer$2(target.buffer, target.byteOffset, offset$1);
- return target;
- }
- /**
- * Masks a buffer using the given mask.
- *
- * @param {Buffer} source The buffer to mask
- * @param {Buffer} mask The mask to use
- * @param {Buffer} output The buffer where to store the result
- * @param {Number} offset The offset at which to start writing
- * @param {Number} length The number of bytes to mask.
- * @public
- */
- function _mask(source, mask, output, offset$1, length) {
- for (let i$1 = 0; i$1 < length; i$1++) output[offset$1 + i$1] = source[i$1] ^ mask[i$1 & 3];
- }
- /**
- * Unmasks a buffer using the given mask.
- *
- * @param {Buffer} buffer The buffer to unmask
- * @param {Buffer} mask The mask to use
- * @public
- */
- function _unmask(buffer, mask) {
- for (let i$1 = 0; i$1 < buffer.length; i$1++) buffer[i$1] ^= mask[i$1 & 3];
- }
- /**
- * Converts a buffer to an `ArrayBuffer`.
- *
- * @param {Buffer} buf The buffer to convert
- * @return {ArrayBuffer} Converted buffer
- * @public
- */
- function toArrayBuffer$1(buf) {
- if (buf.length === buf.buffer.byteLength) return buf.buffer;
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
- }
- /**
- * Converts `data` to a `Buffer`.
- *
- * @param {*} data The data to convert
- * @return {Buffer} The buffer
- * @throws {TypeError}
- * @public
- */
- function toBuffer$2(data) {
- toBuffer$2.readOnly = true;
- if (Buffer.isBuffer(data)) return data;
- let buf;
- if (data instanceof ArrayBuffer) buf = new FastBuffer$2(data);
- else if (ArrayBuffer.isView(data)) buf = new FastBuffer$2(data.buffer, data.byteOffset, data.byteLength);
- else {
- buf = Buffer.from(data);
- toBuffer$2.readOnly = false;
- }
- return buf;
- }
- module.exports = {
- concat: concat$1,
- mask: _mask,
- toArrayBuffer: toArrayBuffer$1,
- toBuffer: toBuffer$2,
- unmask: _unmask
- };
- /* istanbul ignore else */
- if (!process.env.WS_NO_BUFFER_UTIL) try {
- const bufferUtil$1 = __require("bufferutil");
- module.exports.mask = function(source, mask, output, offset$1, length) {
- if (length < 48) _mask(source, mask, output, offset$1, length);
- else bufferUtil$1.mask(source, mask, output, offset$1, length);
- };
- module.exports.unmask = function(buffer, mask) {
- if (buffer.length < 32) _unmask(buffer, mask);
- else bufferUtil$1.unmask(buffer, mask);
- };
- } catch (e$1) {}
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/limiter.js
-var require_limiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const kDone = Symbol("kDone");
- const kRun = Symbol("kRun");
- /**
- * A very simple job queue with adjustable concurrency. Adapted from
- * https://github.com/STRML/async-limiter
- */
- var Limiter$1 = class {
- /**
- * Creates a new `Limiter`.
- *
- * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
- * to run concurrently
- */
- constructor(concurrency) {
- this[kDone] = () => {
- this.pending--;
- this[kRun]();
- };
- this.concurrency = concurrency || Infinity;
- this.jobs = [];
- this.pending = 0;
- }
- /**
- * Adds a job to the queue.
- *
- * @param {Function} job The job to run
- * @public
- */
- add(job) {
- this.jobs.push(job);
- this[kRun]();
- }
- /**
- * Removes a job from the queue and runs it if possible.
- *
- * @private
- */
- [kRun]() {
- if (this.pending === this.concurrency) return;
- if (this.jobs.length) {
- const job = this.jobs.shift();
- this.pending++;
- job(this[kDone]);
- }
- }
- };
- module.exports = Limiter$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/permessage-deflate.js
-var require_permessage_deflate = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const zlib$1 = __require("zlib");
- const bufferUtil = require_buffer_util();
- const Limiter = require_limiter();
- const { kStatusCode: kStatusCode$2 } = require_constants();
- const FastBuffer$1 = Buffer[Symbol.species];
- const TRAILER = Buffer.from([
- 0,
- 0,
- 255,
- 255
- ]);
- const kPerMessageDeflate = Symbol("permessage-deflate");
- const kTotalLength = Symbol("total-length");
- const kCallback = Symbol("callback");
- const kBuffers = Symbol("buffers");
- const kError$1 = Symbol("error");
- let zlibLimiter;
- /**
- * permessage-deflate implementation.
- */
- var PerMessageDeflate$4 = class {
- /**
- * Creates a PerMessageDeflate instance.
- *
- * @param {Object} [options] Configuration options
- * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
- * for, or request, a custom client window size
- * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
- * acknowledge disabling of client context takeover
- * @param {Number} [options.concurrencyLimit=10] The number of concurrent
- * calls to zlib
- * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
- * use of a custom server window size
- * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
- * disabling of server context takeover
- * @param {Number} [options.threshold=1024] Size (in bytes) below which
- * messages should not be compressed if context takeover is disabled
- * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
- * deflate
- * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
- * inflate
- * @param {Boolean} [isServer=false] Create the instance in either server or
- * client mode
- * @param {Number} [maxPayload=0] The maximum allowed message length
- */
- constructor(options$1, isServer, maxPayload) {
- this._maxPayload = maxPayload | 0;
- this._options = options$1 || {};
- this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
- this._isServer = !!isServer;
- this._deflate = null;
- this._inflate = null;
- this.params = null;
- if (!zlibLimiter) zlibLimiter = new Limiter(this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10);
- }
- /**
- * @type {String}
- */
- static get extensionName() {
- return "permessage-deflate";
- }
- /**
- * Create an extension negotiation offer.
- *
- * @return {Object} Extension parameters
- * @public
- */
- offer() {
- const params = {};
- if (this._options.serverNoContextTakeover) params.server_no_context_takeover = true;
- if (this._options.clientNoContextTakeover) params.client_no_context_takeover = true;
- if (this._options.serverMaxWindowBits) params.server_max_window_bits = this._options.serverMaxWindowBits;
- if (this._options.clientMaxWindowBits) params.client_max_window_bits = this._options.clientMaxWindowBits;
- else if (this._options.clientMaxWindowBits == null) params.client_max_window_bits = true;
- return params;
- }
- /**
- * Accept an extension negotiation offer/response.
- *
- * @param {Array} configurations The extension negotiation offers/reponse
- * @return {Object} Accepted configuration
- * @public
- */
- accept(configurations) {
- configurations = this.normalizeParams(configurations);
- this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
- return this.params;
- }
- /**
- * Releases all resources used by the extension.
- *
- * @public
- */
- cleanup() {
- if (this._inflate) {
- this._inflate.close();
- this._inflate = null;
- }
- if (this._deflate) {
- const callback = this._deflate[kCallback];
- this._deflate.close();
- this._deflate = null;
- if (callback) callback(/* @__PURE__ */ new Error("The deflate stream was closed while data was being processed"));
- }
- }
- /**
- * Accept an extension negotiation offer.
- *
- * @param {Array} offers The extension negotiation offers
- * @return {Object} Accepted configuration
- * @private
- */
- acceptAsServer(offers) {
- const opts = this._options;
- const accepted = offers.find((params) => {
- if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) return false;
- return true;
- });
- if (!accepted) throw new Error("None of the extension offers can be accepted");
- if (opts.serverNoContextTakeover) accepted.server_no_context_takeover = true;
- if (opts.clientNoContextTakeover) accepted.client_no_context_takeover = true;
- if (typeof opts.serverMaxWindowBits === "number") accepted.server_max_window_bits = opts.serverMaxWindowBits;
- if (typeof opts.clientMaxWindowBits === "number") accepted.client_max_window_bits = opts.clientMaxWindowBits;
- else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) delete accepted.client_max_window_bits;
- return accepted;
- }
- /**
- * Accept the extension negotiation response.
- *
- * @param {Array} response The extension negotiation response
- * @return {Object} Accepted configuration
- * @private
- */
- acceptAsClient(response) {
- const params = response[0];
- if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) throw new Error("Unexpected parameter \"client_no_context_takeover\"");
- if (!params.client_max_window_bits) {
- if (typeof this._options.clientMaxWindowBits === "number") params.client_max_window_bits = this._options.clientMaxWindowBits;
- } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) throw new Error("Unexpected or invalid parameter \"client_max_window_bits\"");
- return params;
- }
- /**
- * Normalize parameters.
- *
- * @param {Array} configurations The extension negotiation offers/reponse
- * @return {Array} The offers/response with normalized parameters
- * @private
- */
- normalizeParams(configurations) {
- configurations.forEach((params) => {
- Object.keys(params).forEach((key) => {
- let value$1 = params[key];
- if (value$1.length > 1) throw new Error(`Parameter "${key}" must have only a single value`);
- value$1 = value$1[0];
- if (key === "client_max_window_bits") {
- if (value$1 !== true) {
- const num = +value$1;
- if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value$1}`);
- value$1 = num;
- } else if (!this._isServer) throw new TypeError(`Invalid value for parameter "${key}": ${value$1}`);
- } else if (key === "server_max_window_bits") {
- const num = +value$1;
- if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value$1}`);
- value$1 = num;
- } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
- if (value$1 !== true) throw new TypeError(`Invalid value for parameter "${key}": ${value$1}`);
- } else throw new Error(`Unknown parameter "${key}"`);
- params[key] = value$1;
- });
- });
- return configurations;
- }
- /**
- * Decompress data. Concurrency limited.
- *
- * @param {Buffer} data Compressed data
- * @param {Boolean} fin Specifies whether or not this is the last fragment
- * @param {Function} callback Callback
- * @public
- */
- decompress(data, fin, callback) {
- zlibLimiter.add((done) => {
- this._decompress(data, fin, (err$2, result) => {
- done();
- callback(err$2, result);
- });
- });
- }
- /**
- * Compress data. Concurrency limited.
- *
- * @param {(Buffer|String)} data Data to compress
- * @param {Boolean} fin Specifies whether or not this is the last fragment
- * @param {Function} callback Callback
- * @public
- */
- compress(data, fin, callback) {
- zlibLimiter.add((done) => {
- this._compress(data, fin, (err$2, result) => {
- done();
- callback(err$2, result);
- });
- });
- }
- /**
- * Decompress data.
- *
- * @param {Buffer} data Compressed data
- * @param {Boolean} fin Specifies whether or not this is the last fragment
- * @param {Function} callback Callback
- * @private
- */
- _decompress(data, fin, callback) {
- const endpoint = this._isServer ? "client" : "server";
- if (!this._inflate) {
- const key = `${endpoint}_max_window_bits`;
- const windowBits = typeof this.params[key] !== "number" ? zlib$1.Z_DEFAULT_WINDOWBITS : this.params[key];
- this._inflate = zlib$1.createInflateRaw({
- ...this._options.zlibInflateOptions,
- windowBits
- });
- this._inflate[kPerMessageDeflate] = this;
- this._inflate[kTotalLength] = 0;
- this._inflate[kBuffers] = [];
- this._inflate.on("error", inflateOnError);
- this._inflate.on("data", inflateOnData);
- }
- this._inflate[kCallback] = callback;
- this._inflate.write(data);
- if (fin) this._inflate.write(TRAILER);
- this._inflate.flush(() => {
- const err$2 = this._inflate[kError$1];
- if (err$2) {
- this._inflate.close();
- this._inflate = null;
- callback(err$2);
- return;
- }
- const data$1 = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
- if (this._inflate._readableState.endEmitted) {
- this._inflate.close();
- this._inflate = null;
- } else {
- this._inflate[kTotalLength] = 0;
- this._inflate[kBuffers] = [];
- if (fin && this.params[`${endpoint}_no_context_takeover`]) this._inflate.reset();
- }
- callback(null, data$1);
- });
- }
- /**
- * Compress data.
- *
- * @param {(Buffer|String)} data Data to compress
- * @param {Boolean} fin Specifies whether or not this is the last fragment
- * @param {Function} callback Callback
- * @private
- */
- _compress(data, fin, callback) {
- const endpoint = this._isServer ? "server" : "client";
- if (!this._deflate) {
- const key = `${endpoint}_max_window_bits`;
- const windowBits = typeof this.params[key] !== "number" ? zlib$1.Z_DEFAULT_WINDOWBITS : this.params[key];
- this._deflate = zlib$1.createDeflateRaw({
- ...this._options.zlibDeflateOptions,
- windowBits
- });
- this._deflate[kTotalLength] = 0;
- this._deflate[kBuffers] = [];
- this._deflate.on("data", deflateOnData);
- }
- this._deflate[kCallback] = callback;
- this._deflate.write(data);
- this._deflate.flush(zlib$1.Z_SYNC_FLUSH, () => {
- if (!this._deflate) return;
- let data$1 = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
- if (fin) data$1 = new FastBuffer$1(data$1.buffer, data$1.byteOffset, data$1.length - 4);
- this._deflate[kCallback] = null;
- this._deflate[kTotalLength] = 0;
- this._deflate[kBuffers] = [];
- if (fin && this.params[`${endpoint}_no_context_takeover`]) this._deflate.reset();
- callback(null, data$1);
- });
- }
- };
- module.exports = PerMessageDeflate$4;
- /**
- * The listener of the `zlib.DeflateRaw` stream `'data'` event.
- *
- * @param {Buffer} chunk A chunk of data
- * @private
- */
- function deflateOnData(chunk) {
- this[kBuffers].push(chunk);
- this[kTotalLength] += chunk.length;
- }
- /**
- * The listener of the `zlib.InflateRaw` stream `'data'` event.
- *
- * @param {Buffer} chunk A chunk of data
- * @private
- */
- function inflateOnData(chunk) {
- this[kTotalLength] += chunk.length;
- if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
- this[kBuffers].push(chunk);
- return;
- }
- this[kError$1] = /* @__PURE__ */ new RangeError("Max payload size exceeded");
- this[kError$1].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
- this[kError$1][kStatusCode$2] = 1009;
- this.removeListener("data", inflateOnData);
- this.reset();
- }
- /**
- * The listener of the `zlib.InflateRaw` stream `'error'` event.
- *
- * @param {Error} err The emitted error
- * @private
- */
- function inflateOnError(err$2) {
- this[kPerMessageDeflate]._inflate = null;
- if (this[kError$1]) {
- this[kCallback](this[kError$1]);
- return;
- }
- err$2[kStatusCode$2] = 1007;
- this[kCallback](err$2);
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/validation.js
-var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const { isUtf8 } = __require("buffer");
- const { hasBlob } = require_constants();
- const tokenChars$2 = [
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 1,
- 0,
- 1,
- 1,
- 1,
- 1,
- 1,
- 0,
- 0,
- 1,
- 1,
- 0,
- 1,
- 1,
- 0,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 0,
- 0,
- 0,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 1,
- 0,
- 1,
- 0,
- 1,
- 0
- ];
- /**
- * Checks if a status code is allowed in a close frame.
- *
- * @param {Number} code The status code
- * @return {Boolean} `true` if the status code is valid, else `false`
- * @public
- */
- function isValidStatusCode$2(code) {
- return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
- }
- /**
- * Checks if a given buffer contains only correct UTF-8.
- * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
- * Markus Kuhn.
- *
- * @param {Buffer} buf The buffer to check
- * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
- * @public
- */
- function _isValidUTF8(buf) {
- const len = buf.length;
- let i$1 = 0;
- while (i$1 < len) if ((buf[i$1] & 128) === 0) i$1++;
- else if ((buf[i$1] & 224) === 192) {
- if (i$1 + 1 === len || (buf[i$1 + 1] & 192) !== 128 || (buf[i$1] & 254) === 192) return false;
- i$1 += 2;
- } else if ((buf[i$1] & 240) === 224) {
- if (i$1 + 2 >= len || (buf[i$1 + 1] & 192) !== 128 || (buf[i$1 + 2] & 192) !== 128 || buf[i$1] === 224 && (buf[i$1 + 1] & 224) === 128 || buf[i$1] === 237 && (buf[i$1 + 1] & 224) === 160) return false;
- i$1 += 3;
- } else if ((buf[i$1] & 248) === 240) {
- if (i$1 + 3 >= len || (buf[i$1 + 1] & 192) !== 128 || (buf[i$1 + 2] & 192) !== 128 || (buf[i$1 + 3] & 192) !== 128 || buf[i$1] === 240 && (buf[i$1 + 1] & 240) === 128 || buf[i$1] === 244 && buf[i$1 + 1] > 143 || buf[i$1] > 244) return false;
- i$1 += 4;
- } else return false;
- return true;
- }
- /**
- * Determines whether a value is a `Blob`.
- *
- * @param {*} value The value to be tested
- * @return {Boolean} `true` if `value` is a `Blob`, else `false`
- * @private
- */
- function isBlob$2(value$1) {
- return hasBlob && typeof value$1 === "object" && typeof value$1.arrayBuffer === "function" && typeof value$1.type === "string" && typeof value$1.stream === "function" && (value$1[Symbol.toStringTag] === "Blob" || value$1[Symbol.toStringTag] === "File");
- }
- module.exports = {
- isBlob: isBlob$2,
- isValidStatusCode: isValidStatusCode$2,
- isValidUTF8: _isValidUTF8,
- tokenChars: tokenChars$2
- };
- if (isUtf8) module.exports.isValidUTF8 = function(buf) {
- return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
- };
- else if (!process.env.WS_NO_UTF_8_VALIDATE) try {
- const isValidUTF8$1 = __require("utf-8-validate");
- module.exports.isValidUTF8 = function(buf) {
- return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8$1(buf);
- };
- } catch (e$1) {}
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/receiver.js
-var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const { Writable: Writable$1 } = __require("stream");
- const PerMessageDeflate$3 = require_permessage_deflate();
- const { BINARY_TYPES: BINARY_TYPES$1, EMPTY_BUFFER: EMPTY_BUFFER$2, kStatusCode: kStatusCode$1, kWebSocket: kWebSocket$3 } = require_constants();
- const { concat, toArrayBuffer, unmask } = require_buffer_util();
- const { isValidStatusCode: isValidStatusCode$1, isValidUTF8 } = require_validation();
- const FastBuffer = Buffer[Symbol.species];
- const GET_INFO = 0;
- const GET_PAYLOAD_LENGTH_16 = 1;
- const GET_PAYLOAD_LENGTH_64 = 2;
- const GET_MASK = 3;
- const GET_DATA = 4;
- const INFLATING = 5;
- const DEFER_EVENT = 6;
- /**
- * HyBi Receiver implementation.
- *
- * @extends Writable
- */
- var Receiver$2 = class extends Writable$1 {
- /**
- * Creates a Receiver instance.
- *
- * @param {Object} [options] Options object
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
- * multiple times in the same tick
- * @param {String} [options.binaryType=nodebuffer] The type for binary data
- * @param {Object} [options.extensions] An object containing the negotiated
- * extensions
- * @param {Boolean} [options.isServer=false] Specifies whether to operate in
- * client or server mode
- * @param {Number} [options.maxPayload=0] The maximum allowed message length
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
- * not to skip UTF-8 validation for text and close messages
- */
- constructor(options$1 = {}) {
- super();
- this._allowSynchronousEvents = options$1.allowSynchronousEvents !== void 0 ? options$1.allowSynchronousEvents : true;
- this._binaryType = options$1.binaryType || BINARY_TYPES$1[0];
- this._extensions = options$1.extensions || {};
- this._isServer = !!options$1.isServer;
- this._maxPayload = options$1.maxPayload | 0;
- this._skipUTF8Validation = !!options$1.skipUTF8Validation;
- this[kWebSocket$3] = void 0;
- this._bufferedBytes = 0;
- this._buffers = [];
- this._compressed = false;
- this._payloadLength = 0;
- this._mask = void 0;
- this._fragmented = 0;
- this._masked = false;
- this._fin = false;
- this._opcode = 0;
- this._totalPayloadLength = 0;
- this._messageLength = 0;
- this._fragments = [];
- this._errored = false;
- this._loop = false;
- this._state = GET_INFO;
- }
- /**
- * Implements `Writable.prototype._write()`.
- *
- * @param {Buffer} chunk The chunk of data to write
- * @param {String} encoding The character encoding of `chunk`
- * @param {Function} cb Callback
- * @private
- */
- _write(chunk, encoding, cb) {
- if (this._opcode === 8 && this._state == GET_INFO) return cb();
- this._bufferedBytes += chunk.length;
- this._buffers.push(chunk);
- this.startLoop(cb);
- }
- /**
- * Consumes `n` bytes from the buffered data.
- *
- * @param {Number} n The number of bytes to consume
- * @return {Buffer} The consumed bytes
- * @private
- */
- consume(n$2) {
- this._bufferedBytes -= n$2;
- if (n$2 === this._buffers[0].length) return this._buffers.shift();
- if (n$2 < this._buffers[0].length) {
- const buf = this._buffers[0];
- this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n$2, buf.length - n$2);
- return new FastBuffer(buf.buffer, buf.byteOffset, n$2);
- }
- const dst = Buffer.allocUnsafe(n$2);
- do {
- const buf = this._buffers[0];
- const offset$1 = dst.length - n$2;
- if (n$2 >= buf.length) dst.set(this._buffers.shift(), offset$1);
- else {
- dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n$2), offset$1);
- this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n$2, buf.length - n$2);
- }
- n$2 -= buf.length;
- } while (n$2 > 0);
- return dst;
- }
- /**
- * Starts the parsing loop.
- *
- * @param {Function} cb Callback
- * @private
- */
- startLoop(cb) {
- this._loop = true;
- do
- switch (this._state) {
- case GET_INFO:
- this.getInfo(cb);
- break;
- case GET_PAYLOAD_LENGTH_16:
- this.getPayloadLength16(cb);
- break;
- case GET_PAYLOAD_LENGTH_64:
- this.getPayloadLength64(cb);
- break;
- case GET_MASK:
- this.getMask();
- break;
- case GET_DATA:
- this.getData(cb);
- break;
- case INFLATING:
- case DEFER_EVENT:
- this._loop = false;
- return;
- }
- while (this._loop);
- if (!this._errored) cb();
- }
- /**
- * Reads the first two bytes of a frame.
- *
- * @param {Function} cb Callback
- * @private
- */
- getInfo(cb) {
- if (this._bufferedBytes < 2) {
- this._loop = false;
- return;
- }
- const buf = this.consume(2);
- if ((buf[0] & 48) !== 0) {
- cb(this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3"));
- return;
- }
- const compressed = (buf[0] & 64) === 64;
- if (compressed && !this._extensions[PerMessageDeflate$3.extensionName]) {
- cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
- return;
- }
- this._fin = (buf[0] & 128) === 128;
- this._opcode = buf[0] & 15;
- this._payloadLength = buf[1] & 127;
- if (this._opcode === 0) {
- if (compressed) {
- cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
- return;
- }
- if (!this._fragmented) {
- cb(this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE"));
- return;
- }
- this._opcode = this._fragmented;
- } else if (this._opcode === 1 || this._opcode === 2) {
- if (this._fragmented) {
- cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
- return;
- }
- this._compressed = compressed;
- } else if (this._opcode > 7 && this._opcode < 11) {
- if (!this._fin) {
- cb(this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN"));
- return;
- }
- if (compressed) {
- cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
- return;
- }
- if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
- cb(this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"));
- return;
- }
- } else {
- cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
- return;
- }
- if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
- this._masked = (buf[1] & 128) === 128;
- if (this._isServer) {
- if (!this._masked) {
- cb(this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK"));
- return;
- }
- } else if (this._masked) {
- cb(this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK"));
- return;
- }
- if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
- else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
- else this.haveLength(cb);
- }
- /**
- * Gets extended payload length (7+16).
- *
- * @param {Function} cb Callback
- * @private
- */
- getPayloadLength16(cb) {
- if (this._bufferedBytes < 2) {
- this._loop = false;
- return;
- }
- this._payloadLength = this.consume(2).readUInt16BE(0);
- this.haveLength(cb);
- }
- /**
- * Gets extended payload length (7+64).
- *
- * @param {Function} cb Callback
- * @private
- */
- getPayloadLength64(cb) {
- if (this._bufferedBytes < 8) {
- this._loop = false;
- return;
- }
- const buf = this.consume(8);
- const num = buf.readUInt32BE(0);
- if (num > Math.pow(2, 21) - 1) {
- cb(this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"));
- return;
- }
- this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
- this.haveLength(cb);
- }
- /**
- * Payload length has been read.
- *
- * @param {Function} cb Callback
- * @private
- */
- haveLength(cb) {
- if (this._payloadLength && this._opcode < 8) {
- this._totalPayloadLength += this._payloadLength;
- if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
- cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
- return;
- }
- }
- if (this._masked) this._state = GET_MASK;
- else this._state = GET_DATA;
- }
- /**
- * Reads mask bytes.
- *
- * @private
- */
- getMask() {
- if (this._bufferedBytes < 4) {
- this._loop = false;
- return;
- }
- this._mask = this.consume(4);
- this._state = GET_DATA;
- }
- /**
- * Reads data bytes.
- *
- * @param {Function} cb Callback
- * @private
- */
- getData(cb) {
- let data = EMPTY_BUFFER$2;
- if (this._payloadLength) {
- if (this._bufferedBytes < this._payloadLength) {
- this._loop = false;
- return;
- }
- data = this.consume(this._payloadLength);
- if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) unmask(data, this._mask);
- }
- if (this._opcode > 7) {
- this.controlMessage(data, cb);
- return;
- }
- if (this._compressed) {
- this._state = INFLATING;
- this.decompress(data, cb);
- return;
- }
- if (data.length) {
- this._messageLength = this._totalPayloadLength;
- this._fragments.push(data);
- }
- this.dataMessage(cb);
- }
- /**
- * Decompresses data.
- *
- * @param {Buffer} data Compressed data
- * @param {Function} cb Callback
- * @private
- */
- decompress(data, cb) {
- this._extensions[PerMessageDeflate$3.extensionName].decompress(data, this._fin, (err$2, buf) => {
- if (err$2) return cb(err$2);
- if (buf.length) {
- this._messageLength += buf.length;
- if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
- cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
- return;
- }
- this._fragments.push(buf);
- }
- this.dataMessage(cb);
- if (this._state === GET_INFO) this.startLoop(cb);
- });
- }
- /**
- * Handles a data message.
- *
- * @param {Function} cb Callback
- * @private
- */
- dataMessage(cb) {
- if (!this._fin) {
- this._state = GET_INFO;
- return;
- }
- const messageLength = this._messageLength;
- const fragments = this._fragments;
- this._totalPayloadLength = 0;
- this._messageLength = 0;
- this._fragmented = 0;
- this._fragments = [];
- if (this._opcode === 2) {
- let data;
- if (this._binaryType === "nodebuffer") data = concat(fragments, messageLength);
- else if (this._binaryType === "arraybuffer") data = toArrayBuffer(concat(fragments, messageLength));
- else if (this._binaryType === "blob") data = new Blob(fragments);
- else data = fragments;
- if (this._allowSynchronousEvents) {
- this.emit("message", data, true);
- this._state = GET_INFO;
- } else {
- this._state = DEFER_EVENT;
- setImmediate(() => {
- this.emit("message", data, true);
- this._state = GET_INFO;
- this.startLoop(cb);
- });
- }
- } else {
- const buf = concat(fragments, messageLength);
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
- cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
- return;
- }
- if (this._state === INFLATING || this._allowSynchronousEvents) {
- this.emit("message", buf, false);
- this._state = GET_INFO;
- } else {
- this._state = DEFER_EVENT;
- setImmediate(() => {
- this.emit("message", buf, false);
- this._state = GET_INFO;
- this.startLoop(cb);
- });
- }
- }
- }
- /**
- * Handles a control message.
- *
- * @param {Buffer} data Data to handle
- * @return {(Error|RangeError|undefined)} A possible error
- * @private
- */
- controlMessage(data, cb) {
- if (this._opcode === 8) {
- if (data.length === 0) {
- this._loop = false;
- this.emit("conclude", 1005, EMPTY_BUFFER$2);
- this.end();
- } else {
- const code = data.readUInt16BE(0);
- if (!isValidStatusCode$1(code)) {
- cb(this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE"));
- return;
- }
- const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
- cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
- return;
- }
- this._loop = false;
- this.emit("conclude", code, buf);
- this.end();
- }
- this._state = GET_INFO;
- return;
- }
- if (this._allowSynchronousEvents) {
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
- this._state = GET_INFO;
- } else {
- this._state = DEFER_EVENT;
- setImmediate(() => {
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
- this._state = GET_INFO;
- this.startLoop(cb);
- });
- }
- }
- /**
- * Builds an error object.
- *
- * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
- * @param {String} message The error message
- * @param {Boolean} prefix Specifies whether or not to add a default prefix to
- * `message`
- * @param {Number} statusCode The status code
- * @param {String} errorCode The exposed error code
- * @return {(Error|RangeError)} The error
- * @private
- */
- createError(ErrorCtor, message, prefix, statusCode, errorCode) {
- this._loop = false;
- this._errored = true;
- const err$2 = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
- Error.captureStackTrace(err$2, this.createError);
- err$2.code = errorCode;
- err$2[kStatusCode$1] = statusCode;
- return err$2;
- }
- };
- module.exports = Receiver$2;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/sender.js
-var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const { Duplex: Duplex$3 } = __require("stream");
- const { randomFillSync } = __require("crypto");
- const PerMessageDeflate$2 = require_permessage_deflate();
- const { EMPTY_BUFFER: EMPTY_BUFFER$1, kWebSocket: kWebSocket$2, NOOP: NOOP$2 } = require_constants();
- const { isBlob: isBlob$1, isValidStatusCode } = require_validation();
- const { mask: applyMask, toBuffer: toBuffer$1 } = require_buffer_util();
- const kByteLength = Symbol("kByteLength");
- const maskBuffer = Buffer.alloc(4);
- const RANDOM_POOL_SIZE = 8 * 1024;
- let randomPool;
- let randomPoolPointer = RANDOM_POOL_SIZE;
- const DEFAULT = 0;
- const DEFLATING = 1;
- const GET_BLOB_DATA = 2;
- /**
- * HyBi Sender implementation.
- */
- var Sender$2 = class Sender$2 {
- /**
- * Creates a Sender instance.
- *
- * @param {Duplex} socket The connection socket
- * @param {Object} [extensions] An object containing the negotiated extensions
- * @param {Function} [generateMask] The function used to generate the masking
- * key
- */
- constructor(socket, extensions$1, generateMask) {
- this._extensions = extensions$1 || {};
- if (generateMask) {
- this._generateMask = generateMask;
- this._maskBuffer = Buffer.alloc(4);
- }
- this._socket = socket;
- this._firstFragment = true;
- this._compress = false;
- this._bufferedBytes = 0;
- this._queue = [];
- this._state = DEFAULT;
- this.onerror = NOOP$2;
- this[kWebSocket$2] = void 0;
- }
- /**
- * Frames a piece of data according to the HyBi WebSocket protocol.
- *
- * @param {(Buffer|String)} data The data to frame
- * @param {Object} options Options object
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
- * FIN bit
- * @param {Function} [options.generateMask] The function used to generate the
- * masking key
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
- * `data`
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
- * key
- * @param {Number} options.opcode The opcode
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
- * modified
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
- * RSV1 bit
- * @return {(Buffer|String)[]} The framed data
- * @public
- */
- static frame(data, options$1) {
- let mask;
- let merge$1 = false;
- let offset$1 = 2;
- let skipMasking = false;
- if (options$1.mask) {
- mask = options$1.maskBuffer || maskBuffer;
- if (options$1.generateMask) options$1.generateMask(mask);
- else {
- if (randomPoolPointer === RANDOM_POOL_SIZE) {
- /* istanbul ignore else */
- if (randomPool === void 0) randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
- randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
- randomPoolPointer = 0;
- }
- mask[0] = randomPool[randomPoolPointer++];
- mask[1] = randomPool[randomPoolPointer++];
- mask[2] = randomPool[randomPoolPointer++];
- mask[3] = randomPool[randomPoolPointer++];
- }
- skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
- offset$1 = 6;
- }
- let dataLength;
- if (typeof data === "string") if ((!options$1.mask || skipMasking) && options$1[kByteLength] !== void 0) dataLength = options$1[kByteLength];
- else {
- data = Buffer.from(data);
- dataLength = data.length;
- }
- else {
- dataLength = data.length;
- merge$1 = options$1.mask && options$1.readOnly && !skipMasking;
- }
- let payloadLength = dataLength;
- if (dataLength >= 65536) {
- offset$1 += 8;
- payloadLength = 127;
- } else if (dataLength > 125) {
- offset$1 += 2;
- payloadLength = 126;
- }
- const target = Buffer.allocUnsafe(merge$1 ? dataLength + offset$1 : offset$1);
- target[0] = options$1.fin ? options$1.opcode | 128 : options$1.opcode;
- if (options$1.rsv1) target[0] |= 64;
- target[1] = payloadLength;
- if (payloadLength === 126) target.writeUInt16BE(dataLength, 2);
- else if (payloadLength === 127) {
- target[2] = target[3] = 0;
- target.writeUIntBE(dataLength, 4, 6);
- }
- if (!options$1.mask) return [target, data];
- target[1] |= 128;
- target[offset$1 - 4] = mask[0];
- target[offset$1 - 3] = mask[1];
- target[offset$1 - 2] = mask[2];
- target[offset$1 - 1] = mask[3];
- if (skipMasking) return [target, data];
- if (merge$1) {
- applyMask(data, mask, target, offset$1, dataLength);
- return [target];
- }
- applyMask(data, mask, data, 0, dataLength);
- return [target, data];
- }
- /**
- * Sends a close message to the other peer.
- *
- * @param {Number} [code] The status code component of the body
- * @param {(String|Buffer)} [data] The message component of the body
- * @param {Boolean} [mask=false] Specifies whether or not to mask the message
- * @param {Function} [cb] Callback
- * @public
- */
- close(code, data, mask, cb) {
- let buf;
- if (code === void 0) buf = EMPTY_BUFFER$1;
- else if (typeof code !== "number" || !isValidStatusCode(code)) throw new TypeError("First argument must be a valid error code number");
- else if (data === void 0 || !data.length) {
- buf = Buffer.allocUnsafe(2);
- buf.writeUInt16BE(code, 0);
- } else {
- const length = Buffer.byteLength(data);
- if (length > 123) throw new RangeError("The message must not be greater than 123 bytes");
- buf = Buffer.allocUnsafe(2 + length);
- buf.writeUInt16BE(code, 0);
- if (typeof data === "string") buf.write(data, 2);
- else buf.set(data, 2);
- }
- const options$1 = {
- [kByteLength]: buf.length,
- fin: true,
- generateMask: this._generateMask,
- mask,
- maskBuffer: this._maskBuffer,
- opcode: 8,
- readOnly: false,
- rsv1: false
- };
- if (this._state !== DEFAULT) this.enqueue([
- this.dispatch,
- buf,
- false,
- options$1,
- cb
- ]);
- else this.sendFrame(Sender$2.frame(buf, options$1), cb);
- }
- /**
- * Sends a ping message to the other peer.
- *
- * @param {*} data The message to send
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
- * @param {Function} [cb] Callback
- * @public
- */
- ping(data, mask, cb) {
- let byteLength;
- let readOnly;
- if (typeof data === "string") {
- byteLength = Buffer.byteLength(data);
- readOnly = false;
- } else if (isBlob$1(data)) {
- byteLength = data.size;
- readOnly = false;
- } else {
- data = toBuffer$1(data);
- byteLength = data.length;
- readOnly = toBuffer$1.readOnly;
- }
- if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
- const options$1 = {
- [kByteLength]: byteLength,
- fin: true,
- generateMask: this._generateMask,
- mask,
- maskBuffer: this._maskBuffer,
- opcode: 9,
- readOnly,
- rsv1: false
- };
- if (isBlob$1(data)) if (this._state !== DEFAULT) this.enqueue([
- this.getBlobData,
- data,
- false,
- options$1,
- cb
- ]);
- else this.getBlobData(data, false, options$1, cb);
- else if (this._state !== DEFAULT) this.enqueue([
- this.dispatch,
- data,
- false,
- options$1,
- cb
- ]);
- else this.sendFrame(Sender$2.frame(data, options$1), cb);
- }
- /**
- * Sends a pong message to the other peer.
- *
- * @param {*} data The message to send
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
- * @param {Function} [cb] Callback
- * @public
- */
- pong(data, mask, cb) {
- let byteLength;
- let readOnly;
- if (typeof data === "string") {
- byteLength = Buffer.byteLength(data);
- readOnly = false;
- } else if (isBlob$1(data)) {
- byteLength = data.size;
- readOnly = false;
- } else {
- data = toBuffer$1(data);
- byteLength = data.length;
- readOnly = toBuffer$1.readOnly;
- }
- if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
- const options$1 = {
- [kByteLength]: byteLength,
- fin: true,
- generateMask: this._generateMask,
- mask,
- maskBuffer: this._maskBuffer,
- opcode: 10,
- readOnly,
- rsv1: false
- };
- if (isBlob$1(data)) if (this._state !== DEFAULT) this.enqueue([
- this.getBlobData,
- data,
- false,
- options$1,
- cb
- ]);
- else this.getBlobData(data, false, options$1, cb);
- else if (this._state !== DEFAULT) this.enqueue([
- this.dispatch,
- data,
- false,
- options$1,
- cb
- ]);
- else this.sendFrame(Sender$2.frame(data, options$1), cb);
- }
- /**
- * Sends a data message to the other peer.
- *
- * @param {*} data The message to send
- * @param {Object} options Options object
- * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
- * or text
- * @param {Boolean} [options.compress=false] Specifies whether or not to
- * compress `data`
- * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
- * last one
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
- * `data`
- * @param {Function} [cb] Callback
- * @public
- */
- send(data, options$1, cb) {
- const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
- let opcode = options$1.binary ? 2 : 1;
- let rsv1 = options$1.compress;
- let byteLength;
- let readOnly;
- if (typeof data === "string") {
- byteLength = Buffer.byteLength(data);
- readOnly = false;
- } else if (isBlob$1(data)) {
- byteLength = data.size;
- readOnly = false;
- } else {
- data = toBuffer$1(data);
- byteLength = data.length;
- readOnly = toBuffer$1.readOnly;
- }
- if (this._firstFragment) {
- this._firstFragment = false;
- if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) rsv1 = byteLength >= perMessageDeflate._threshold;
- this._compress = rsv1;
- } else {
- rsv1 = false;
- opcode = 0;
- }
- if (options$1.fin) this._firstFragment = true;
- const opts = {
- [kByteLength]: byteLength,
- fin: options$1.fin,
- generateMask: this._generateMask,
- mask: options$1.mask,
- maskBuffer: this._maskBuffer,
- opcode,
- readOnly,
- rsv1
- };
- if (isBlob$1(data)) if (this._state !== DEFAULT) this.enqueue([
- this.getBlobData,
- data,
- this._compress,
- opts,
- cb
- ]);
- else this.getBlobData(data, this._compress, opts, cb);
- else if (this._state !== DEFAULT) this.enqueue([
- this.dispatch,
- data,
- this._compress,
- opts,
- cb
- ]);
- else this.dispatch(data, this._compress, opts, cb);
- }
- /**
- * Gets the contents of a blob as binary data.
- *
- * @param {Blob} blob The blob
- * @param {Boolean} [compress=false] Specifies whether or not to compress
- * the data
- * @param {Object} options Options object
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
- * FIN bit
- * @param {Function} [options.generateMask] The function used to generate the
- * masking key
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
- * `data`
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
- * key
- * @param {Number} options.opcode The opcode
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
- * modified
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
- * RSV1 bit
- * @param {Function} [cb] Callback
- * @private
- */
- getBlobData(blob, compress, options$1, cb) {
- this._bufferedBytes += options$1[kByteLength];
- this._state = GET_BLOB_DATA;
- blob.arrayBuffer().then((arrayBuffer) => {
- if (this._socket.destroyed) {
- const err$2 = /* @__PURE__ */ new Error("The socket was closed while the blob was being read");
- process.nextTick(callCallbacks, this, err$2, cb);
- return;
- }
- this._bufferedBytes -= options$1[kByteLength];
- const data = toBuffer$1(arrayBuffer);
- if (!compress) {
- this._state = DEFAULT;
- this.sendFrame(Sender$2.frame(data, options$1), cb);
- this.dequeue();
- } else this.dispatch(data, compress, options$1, cb);
- }).catch((err$2) => {
- process.nextTick(onError, this, err$2, cb);
- });
- }
- /**
- * Dispatches a message.
- *
- * @param {(Buffer|String)} data The message to send
- * @param {Boolean} [compress=false] Specifies whether or not to compress
- * `data`
- * @param {Object} options Options object
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
- * FIN bit
- * @param {Function} [options.generateMask] The function used to generate the
- * masking key
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
- * `data`
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
- * key
- * @param {Number} options.opcode The opcode
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
- * modified
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
- * RSV1 bit
- * @param {Function} [cb] Callback
- * @private
- */
- dispatch(data, compress, options$1, cb) {
- if (!compress) {
- this.sendFrame(Sender$2.frame(data, options$1), cb);
- return;
- }
- const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
- this._bufferedBytes += options$1[kByteLength];
- this._state = DEFLATING;
- perMessageDeflate.compress(data, options$1.fin, (_, buf) => {
- if (this._socket.destroyed) {
- callCallbacks(this, /* @__PURE__ */ new Error("The socket was closed while data was being compressed"), cb);
- return;
- }
- this._bufferedBytes -= options$1[kByteLength];
- this._state = DEFAULT;
- options$1.readOnly = false;
- this.sendFrame(Sender$2.frame(buf, options$1), cb);
- this.dequeue();
- });
- }
- /**
- * Executes queued send operations.
- *
- * @private
- */
- dequeue() {
- while (this._state === DEFAULT && this._queue.length) {
- const params = this._queue.shift();
- this._bufferedBytes -= params[3][kByteLength];
- Reflect.apply(params[0], this, params.slice(1));
- }
- }
- /**
- * Enqueues a send operation.
- *
- * @param {Array} params Send operation parameters.
- * @private
- */
- enqueue(params) {
- this._bufferedBytes += params[3][kByteLength];
- this._queue.push(params);
- }
- /**
- * Sends a frame.
- *
- * @param {(Buffer | String)[]} list The frame to send
- * @param {Function} [cb] Callback
- * @private
- */
- sendFrame(list, cb) {
- if (list.length === 2) {
- this._socket.cork();
- this._socket.write(list[0]);
- this._socket.write(list[1], cb);
- this._socket.uncork();
- } else this._socket.write(list[0], cb);
- }
- };
- module.exports = Sender$2;
- /**
- * Calls queued callbacks with an error.
- *
- * @param {Sender} sender The `Sender` instance
- * @param {Error} err The error to call the callbacks with
- * @param {Function} [cb] The first callback
- * @private
- */
- function callCallbacks(sender, err$2, cb) {
- if (typeof cb === "function") cb(err$2);
- for (let i$1 = 0; i$1 < sender._queue.length; i$1++) {
- const params = sender._queue[i$1];
- const callback = params[params.length - 1];
- if (typeof callback === "function") callback(err$2);
- }
- }
- /**
- * Handles a `Sender` error.
- *
- * @param {Sender} sender The `Sender` instance
- * @param {Error} err The error
- * @param {Function} [cb] The first pending callback
- * @private
- */
- function onError(sender, err$2, cb) {
- callCallbacks(sender, err$2, cb);
- sender.onerror(err$2);
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/event-target.js
-var require_event_target = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const { kForOnEventAttribute: kForOnEventAttribute$1, kListener: kListener$1 } = require_constants();
- const kCode = Symbol("kCode");
- const kData = Symbol("kData");
- const kError = Symbol("kError");
- const kMessage = Symbol("kMessage");
- const kReason = Symbol("kReason");
- const kTarget = Symbol("kTarget");
- const kType = Symbol("kType");
- const kWasClean = Symbol("kWasClean");
- /**
- * Class representing an event.
- */
- var Event$1 = class {
- /**
- * Create a new `Event`.
- *
- * @param {String} type The name of the event
- * @throws {TypeError} If the `type` argument is not specified
- */
- constructor(type) {
- this[kTarget] = null;
- this[kType] = type;
- }
- /**
- * @type {*}
- */
- get target() {
- return this[kTarget];
- }
- /**
- * @type {String}
- */
- get type() {
- return this[kType];
- }
- };
- Object.defineProperty(Event$1.prototype, "target", { enumerable: true });
- Object.defineProperty(Event$1.prototype, "type", { enumerable: true });
- /**
- * Class representing a close event.
- *
- * @extends Event
- */
- var CloseEvent = class extends Event$1 {
- /**
- * Create a new `CloseEvent`.
- *
- * @param {String} type The name of the event
- * @param {Object} [options] A dictionary object that allows for setting
- * attributes via object members of the same name
- * @param {Number} [options.code=0] The status code explaining why the
- * connection was closed
- * @param {String} [options.reason=''] A human-readable string explaining why
- * the connection was closed
- * @param {Boolean} [options.wasClean=false] Indicates whether or not the
- * connection was cleanly closed
- */
- constructor(type, options$1 = {}) {
- super(type);
- this[kCode] = options$1.code === void 0 ? 0 : options$1.code;
- this[kReason] = options$1.reason === void 0 ? "" : options$1.reason;
- this[kWasClean] = options$1.wasClean === void 0 ? false : options$1.wasClean;
- }
- /**
- * @type {Number}
- */
- get code() {
- return this[kCode];
- }
- /**
- * @type {String}
- */
- get reason() {
- return this[kReason];
- }
- /**
- * @type {Boolean}
- */
- get wasClean() {
- return this[kWasClean];
- }
- };
- Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
- Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
- Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
- /**
- * Class representing an error event.
- *
- * @extends Event
- */
- var ErrorEvent = class extends Event$1 {
- /**
- * Create a new `ErrorEvent`.
- *
- * @param {String} type The name of the event
- * @param {Object} [options] A dictionary object that allows for setting
- * attributes via object members of the same name
- * @param {*} [options.error=null] The error that generated this event
- * @param {String} [options.message=''] The error message
- */
- constructor(type, options$1 = {}) {
- super(type);
- this[kError] = options$1.error === void 0 ? null : options$1.error;
- this[kMessage] = options$1.message === void 0 ? "" : options$1.message;
- }
- /**
- * @type {*}
- */
- get error() {
- return this[kError];
- }
- /**
- * @type {String}
- */
- get message() {
- return this[kMessage];
- }
- };
- Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
- Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
- /**
- * Class representing a message event.
- *
- * @extends Event
- */
- var MessageEvent = class extends Event$1 {
- /**
- * Create a new `MessageEvent`.
- *
- * @param {String} type The name of the event
- * @param {Object} [options] A dictionary object that allows for setting
- * attributes via object members of the same name
- * @param {*} [options.data=null] The message content
- */
- constructor(type, options$1 = {}) {
- super(type);
- this[kData] = options$1.data === void 0 ? null : options$1.data;
- }
- /**
- * @type {*}
- */
- get data() {
- return this[kData];
- }
- };
- Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
- /**
- * This provides methods for emulating the `EventTarget` interface. It's not
- * meant to be used directly.
- *
- * @mixin
- */
- const EventTarget = {
- addEventListener(type, handler, options$1 = {}) {
- for (const listener$1 of this.listeners(type)) if (!options$1[kForOnEventAttribute$1] && listener$1[kListener$1] === handler && !listener$1[kForOnEventAttribute$1]) return;
- let wrapper;
- if (type === "message") wrapper = function onMessage(data, isBinary) {
- const event = new MessageEvent("message", { data: isBinary ? data : data.toString() });
- event[kTarget] = this;
- callListener(handler, this, event);
- };
- else if (type === "close") wrapper = function onClose(code, message) {
- const event = new CloseEvent("close", {
- code,
- reason: message.toString(),
- wasClean: this._closeFrameReceived && this._closeFrameSent
- });
- event[kTarget] = this;
- callListener(handler, this, event);
- };
- else if (type === "error") wrapper = function onError$1(error$1) {
- const event = new ErrorEvent("error", {
- error: error$1,
- message: error$1.message
- });
- event[kTarget] = this;
- callListener(handler, this, event);
- };
- else if (type === "open") wrapper = function onOpen() {
- const event = new Event$1("open");
- event[kTarget] = this;
- callListener(handler, this, event);
- };
- else return;
- wrapper[kForOnEventAttribute$1] = !!options$1[kForOnEventAttribute$1];
- wrapper[kListener$1] = handler;
- if (options$1.once) this.once(type, wrapper);
- else this.on(type, wrapper);
- },
- removeEventListener(type, handler) {
- for (const listener$1 of this.listeners(type)) if (listener$1[kListener$1] === handler && !listener$1[kForOnEventAttribute$1]) {
- this.removeListener(type, listener$1);
- break;
- }
- }
- };
- module.exports = {
- CloseEvent,
- ErrorEvent,
- Event: Event$1,
- EventTarget,
- MessageEvent
- };
- /**
- * Call an event listener
- *
- * @param {(Function|Object)} listener The listener to call
- * @param {*} thisArg The value to use as `this`` when calling the listener
- * @param {Event} event The event to pass to the listener
- * @private
- */
- function callListener(listener$1, thisArg, event) {
- if (typeof listener$1 === "object" && listener$1.handleEvent) listener$1.handleEvent.call(listener$1, event);
- else listener$1.call(thisArg, event);
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/extension.js
-var require_extension = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const { tokenChars: tokenChars$1 } = require_validation();
- /**
- * Adds an offer to the map of extension offers or a parameter to the map of
- * parameters.
- *
- * @param {Object} dest The map of extension offers or parameters
- * @param {String} name The extension or parameter name
- * @param {(Object|Boolean|String)} elem The extension parameters or the
- * parameter value
- * @private
- */
- function push(dest, name, elem) {
- if (dest[name] === void 0) dest[name] = [elem];
- else dest[name].push(elem);
- }
- /**
- * Parses the `Sec-WebSocket-Extensions` header into an object.
- *
- * @param {String} header The field value of the header
- * @return {Object} The parsed object
- * @public
- */
- function parse$4(header) {
- const offers = Object.create(null);
- let params = Object.create(null);
- let mustUnescape = false;
- let isEscaping = false;
- let inQuotes = false;
- let extensionName;
- let paramName;
- let start = -1;
- let code = -1;
- let end = -1;
- let i$1 = 0;
- for (; i$1 < header.length; i$1++) {
- code = header.charCodeAt(i$1);
- if (extensionName === void 0) if (end === -1 && tokenChars$1[code] === 1) {
- if (start === -1) start = i$1;
- } else if (i$1 !== 0 && (code === 32 || code === 9)) {
- if (end === -1 && start !== -1) end = i$1;
- } else if (code === 59 || code === 44) {
- if (start === -1) throw new SyntaxError(`Unexpected character at index ${i$1}`);
- if (end === -1) end = i$1;
- const name = header.slice(start, end);
- if (code === 44) {
- push(offers, name, params);
- params = Object.create(null);
- } else extensionName = name;
- start = end = -1;
- } else throw new SyntaxError(`Unexpected character at index ${i$1}`);
- else if (paramName === void 0) if (end === -1 && tokenChars$1[code] === 1) {
- if (start === -1) start = i$1;
- } else if (code === 32 || code === 9) {
- if (end === -1 && start !== -1) end = i$1;
- } else if (code === 59 || code === 44) {
- if (start === -1) throw new SyntaxError(`Unexpected character at index ${i$1}`);
- if (end === -1) end = i$1;
- push(params, header.slice(start, end), true);
- if (code === 44) {
- push(offers, extensionName, params);
- params = Object.create(null);
- extensionName = void 0;
- }
- start = end = -1;
- } else if (code === 61 && start !== -1 && end === -1) {
- paramName = header.slice(start, i$1);
- start = end = -1;
- } else throw new SyntaxError(`Unexpected character at index ${i$1}`);
- else if (isEscaping) {
- if (tokenChars$1[code] !== 1) throw new SyntaxError(`Unexpected character at index ${i$1}`);
- if (start === -1) start = i$1;
- else if (!mustUnescape) mustUnescape = true;
- isEscaping = false;
- } else if (inQuotes) if (tokenChars$1[code] === 1) {
- if (start === -1) start = i$1;
- } else if (code === 34 && start !== -1) {
- inQuotes = false;
- end = i$1;
- } else if (code === 92) isEscaping = true;
- else throw new SyntaxError(`Unexpected character at index ${i$1}`);
- else if (code === 34 && header.charCodeAt(i$1 - 1) === 61) inQuotes = true;
- else if (end === -1 && tokenChars$1[code] === 1) {
- if (start === -1) start = i$1;
- } else if (start !== -1 && (code === 32 || code === 9)) {
- if (end === -1) end = i$1;
- } else if (code === 59 || code === 44) {
- if (start === -1) throw new SyntaxError(`Unexpected character at index ${i$1}`);
- if (end === -1) end = i$1;
- let value$1 = header.slice(start, end);
- if (mustUnescape) {
- value$1 = value$1.replace(/\\/g, "");
- mustUnescape = false;
- }
- push(params, paramName, value$1);
- if (code === 44) {
- push(offers, extensionName, params);
- params = Object.create(null);
- extensionName = void 0;
- }
- paramName = void 0;
- start = end = -1;
- } else throw new SyntaxError(`Unexpected character at index ${i$1}`);
- }
- if (start === -1 || inQuotes || code === 32 || code === 9) throw new SyntaxError("Unexpected end of input");
- if (end === -1) end = i$1;
- const token = header.slice(start, end);
- if (extensionName === void 0) push(offers, token, params);
- else {
- if (paramName === void 0) push(params, token, true);
- else if (mustUnescape) push(params, paramName, token.replace(/\\/g, ""));
- else push(params, paramName, token);
- push(offers, extensionName, params);
- }
- return offers;
- }
- /**
- * Builds the `Sec-WebSocket-Extensions` header field value.
- *
- * @param {Object} extensions The map of extensions and parameters to format
- * @return {String} A string representing the given object
- * @public
- */
- function format$2(extensions$1) {
- return Object.keys(extensions$1).map((extension$1) => {
- let configurations = extensions$1[extension$1];
- if (!Array.isArray(configurations)) configurations = [configurations];
- return configurations.map((params) => {
- return [extension$1].concat(Object.keys(params).map((k) => {
- let values = params[k];
- if (!Array.isArray(values)) values = [values];
- return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
- })).join("; ");
- }).join(", ");
- }).join(", ");
- }
- module.exports = {
- format: format$2,
- parse: parse$4
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/websocket.js
-var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const EventEmitter$2 = __require("events");
- const https$3 = __require("https");
- const http$5 = __require("http");
- const net$1 = __require("net");
- const tls = __require("tls");
- const { randomBytes, createHash: createHash$1 } = __require("crypto");
- const { Duplex: Duplex$2, Readable } = __require("stream");
- const { URL: URL$3 } = __require("url");
- const PerMessageDeflate$1 = require_permessage_deflate();
- const Receiver$1 = require_receiver();
- const Sender$1 = require_sender();
- const { isBlob } = require_validation();
- const { BINARY_TYPES, EMPTY_BUFFER, GUID: GUID$1, kForOnEventAttribute, kListener, kStatusCode, kWebSocket: kWebSocket$1, NOOP: NOOP$1 } = require_constants();
- const { EventTarget: { addEventListener, removeEventListener } } = require_event_target();
- const { format: format$1, parse: parse$3 } = require_extension();
- const { toBuffer } = require_buffer_util();
- const closeTimeout = 30 * 1e3;
- const kAborted = Symbol("kAborted");
- const protocolVersions = [8, 13];
- const readyStates = [
- "CONNECTING",
- "OPEN",
- "CLOSING",
- "CLOSED"
- ];
- const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
- /**
- * Class representing a WebSocket.
- *
- * @extends EventEmitter
- */
- var WebSocket$2 = class WebSocket$2 extends EventEmitter$2 {
- /**
- * Create a new `WebSocket`.
- *
- * @param {(String|URL)} address The URL to which to connect
- * @param {(String|String[])} [protocols] The subprotocols
- * @param {Object} [options] Connection options
- */
- constructor(address, protocols, options$1) {
- super();
- this._binaryType = BINARY_TYPES[0];
- this._closeCode = 1006;
- this._closeFrameReceived = false;
- this._closeFrameSent = false;
- this._closeMessage = EMPTY_BUFFER;
- this._closeTimer = null;
- this._errorEmitted = false;
- this._extensions = {};
- this._paused = false;
- this._protocol = "";
- this._readyState = WebSocket$2.CONNECTING;
- this._receiver = null;
- this._sender = null;
- this._socket = null;
- if (address !== null) {
- this._bufferedAmount = 0;
- this._isServer = false;
- this._redirects = 0;
- if (protocols === void 0) protocols = [];
- else if (!Array.isArray(protocols)) if (typeof protocols === "object" && protocols !== null) {
- options$1 = protocols;
- protocols = [];
- } else protocols = [protocols];
- initAsClient(this, address, protocols, options$1);
- } else {
- this._autoPong = options$1.autoPong;
- this._isServer = true;
- }
- }
- /**
- * For historical reasons, the custom "nodebuffer" type is used by the default
- * instead of "blob".
- *
- * @type {String}
- */
- get binaryType() {
- return this._binaryType;
- }
- set binaryType(type) {
- if (!BINARY_TYPES.includes(type)) return;
- this._binaryType = type;
- if (this._receiver) this._receiver._binaryType = type;
- }
- /**
- * @type {Number}
- */
- get bufferedAmount() {
- if (!this._socket) return this._bufferedAmount;
- return this._socket._writableState.length + this._sender._bufferedBytes;
- }
- /**
- * @type {String}
- */
- get extensions() {
- return Object.keys(this._extensions).join();
- }
- /**
- * @type {Boolean}
- */
- get isPaused() {
- return this._paused;
- }
- /**
- * @type {Function}
- */
- /* istanbul ignore next */
- get onclose() {
- return null;
- }
- /**
- * @type {Function}
- */
- /* istanbul ignore next */
- get onerror() {
- return null;
- }
- /**
- * @type {Function}
- */
- /* istanbul ignore next */
- get onopen() {
- return null;
- }
- /**
- * @type {Function}
- */
- /* istanbul ignore next */
- get onmessage() {
- return null;
- }
- /**
- * @type {String}
- */
- get protocol() {
- return this._protocol;
- }
- /**
- * @type {Number}
- */
- get readyState() {
- return this._readyState;
- }
- /**
- * @type {String}
- */
- get url() {
- return this._url;
- }
- /**
- * Set up the socket and the internal resources.
- *
- * @param {Duplex} socket The network socket between the server and client
- * @param {Buffer} head The first packet of the upgraded stream
- * @param {Object} options Options object
- * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
- * multiple times in the same tick
- * @param {Function} [options.generateMask] The function used to generate the
- * masking key
- * @param {Number} [options.maxPayload=0] The maximum allowed message size
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
- * not to skip UTF-8 validation for text and close messages
- * @private
- */
- setSocket(socket, head, options$1) {
- const receiver = new Receiver$1({
- allowSynchronousEvents: options$1.allowSynchronousEvents,
- binaryType: this.binaryType,
- extensions: this._extensions,
- isServer: this._isServer,
- maxPayload: options$1.maxPayload,
- skipUTF8Validation: options$1.skipUTF8Validation
- });
- const sender = new Sender$1(socket, this._extensions, options$1.generateMask);
- this._receiver = receiver;
- this._sender = sender;
- this._socket = socket;
- receiver[kWebSocket$1] = this;
- sender[kWebSocket$1] = this;
- socket[kWebSocket$1] = this;
- receiver.on("conclude", receiverOnConclude);
- receiver.on("drain", receiverOnDrain);
- receiver.on("error", receiverOnError);
- receiver.on("message", receiverOnMessage);
- receiver.on("ping", receiverOnPing);
- receiver.on("pong", receiverOnPong);
- sender.onerror = senderOnError;
- if (socket.setTimeout) socket.setTimeout(0);
- if (socket.setNoDelay) socket.setNoDelay();
- if (head.length > 0) socket.unshift(head);
- socket.on("close", socketOnClose);
- socket.on("data", socketOnData);
- socket.on("end", socketOnEnd);
- socket.on("error", socketOnError$1);
- this._readyState = WebSocket$2.OPEN;
- this.emit("open");
- }
- /**
- * Emit the `'close'` event.
- *
- * @private
- */
- emitClose() {
- if (!this._socket) {
- this._readyState = WebSocket$2.CLOSED;
- this.emit("close", this._closeCode, this._closeMessage);
- return;
- }
- if (this._extensions[PerMessageDeflate$1.extensionName]) this._extensions[PerMessageDeflate$1.extensionName].cleanup();
- this._receiver.removeAllListeners();
- this._readyState = WebSocket$2.CLOSED;
- this.emit("close", this._closeCode, this._closeMessage);
- }
- /**
- * Start a closing handshake.
- *
- * +----------+ +-----------+ +----------+
- * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
- * | +----------+ +-----------+ +----------+ |
- * +----------+ +-----------+ |
- * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
- * +----------+ +-----------+ |
- * | | | +---+ |
- * +------------------------+-->|fin| - - - -
- * | +---+ | +---+
- * - - - - -|fin|<---------------------+
- * +---+
- *
- * @param {Number} [code] Status code explaining why the connection is closing
- * @param {(String|Buffer)} [data] The reason why the connection is
- * closing
- * @public
- */
- close(code, data) {
- if (this.readyState === WebSocket$2.CLOSED) return;
- if (this.readyState === WebSocket$2.CONNECTING) {
- abortHandshake$1(this, this._req, "WebSocket was closed before the connection was established");
- return;
- }
- if (this.readyState === WebSocket$2.CLOSING) {
- if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) this._socket.end();
- return;
- }
- this._readyState = WebSocket$2.CLOSING;
- this._sender.close(code, data, !this._isServer, (err$2) => {
- if (err$2) return;
- this._closeFrameSent = true;
- if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) this._socket.end();
- });
- setCloseTimer(this);
- }
- /**
- * Pause the socket.
- *
- * @public
- */
- pause() {
- if (this.readyState === WebSocket$2.CONNECTING || this.readyState === WebSocket$2.CLOSED) return;
- this._paused = true;
- this._socket.pause();
- }
- /**
- * Send a ping.
- *
- * @param {*} [data] The data to send
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
- * @param {Function} [cb] Callback which is executed when the ping is sent
- * @public
- */
- ping(data, mask, cb) {
- if (this.readyState === WebSocket$2.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
- if (typeof data === "function") {
- cb = data;
- data = mask = void 0;
- } else if (typeof mask === "function") {
- cb = mask;
- mask = void 0;
- }
- if (typeof data === "number") data = data.toString();
- if (this.readyState !== WebSocket$2.OPEN) {
- sendAfterClose(this, data, cb);
- return;
- }
- if (mask === void 0) mask = !this._isServer;
- this._sender.ping(data || EMPTY_BUFFER, mask, cb);
- }
- /**
- * Send a pong.
- *
- * @param {*} [data] The data to send
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
- * @param {Function} [cb] Callback which is executed when the pong is sent
- * @public
- */
- pong(data, mask, cb) {
- if (this.readyState === WebSocket$2.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
- if (typeof data === "function") {
- cb = data;
- data = mask = void 0;
- } else if (typeof mask === "function") {
- cb = mask;
- mask = void 0;
- }
- if (typeof data === "number") data = data.toString();
- if (this.readyState !== WebSocket$2.OPEN) {
- sendAfterClose(this, data, cb);
- return;
- }
- if (mask === void 0) mask = !this._isServer;
- this._sender.pong(data || EMPTY_BUFFER, mask, cb);
- }
- /**
- * Resume the socket.
- *
- * @public
- */
- resume() {
- if (this.readyState === WebSocket$2.CONNECTING || this.readyState === WebSocket$2.CLOSED) return;
- this._paused = false;
- if (!this._receiver._writableState.needDrain) this._socket.resume();
- }
- /**
- * Send a data message.
- *
- * @param {*} data The message to send
- * @param {Object} [options] Options object
- * @param {Boolean} [options.binary] Specifies whether `data` is binary or
- * text
- * @param {Boolean} [options.compress] Specifies whether or not to compress
- * `data`
- * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
- * last one
- * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
- * @param {Function} [cb] Callback which is executed when data is written out
- * @public
- */
- send(data, options$1, cb) {
- if (this.readyState === WebSocket$2.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
- if (typeof options$1 === "function") {
- cb = options$1;
- options$1 = {};
- }
- if (typeof data === "number") data = data.toString();
- if (this.readyState !== WebSocket$2.OPEN) {
- sendAfterClose(this, data, cb);
- return;
- }
- const opts = {
- binary: typeof data !== "string",
- mask: !this._isServer,
- compress: true,
- fin: true,
- ...options$1
- };
- if (!this._extensions[PerMessageDeflate$1.extensionName]) opts.compress = false;
- this._sender.send(data || EMPTY_BUFFER, opts, cb);
- }
- /**
- * Forcibly close the connection.
- *
- * @public
- */
- terminate() {
- if (this.readyState === WebSocket$2.CLOSED) return;
- if (this.readyState === WebSocket$2.CONNECTING) {
- abortHandshake$1(this, this._req, "WebSocket was closed before the connection was established");
- return;
- }
- if (this._socket) {
- this._readyState = WebSocket$2.CLOSING;
- this._socket.destroy();
- }
- }
- };
- /**
- * @constant {Number} CONNECTING
- * @memberof WebSocket
- */
- Object.defineProperty(WebSocket$2, "CONNECTING", {
- enumerable: true,
- value: readyStates.indexOf("CONNECTING")
- });
- /**
- * @constant {Number} CONNECTING
- * @memberof WebSocket.prototype
- */
- Object.defineProperty(WebSocket$2.prototype, "CONNECTING", {
- enumerable: true,
- value: readyStates.indexOf("CONNECTING")
- });
- /**
- * @constant {Number} OPEN
- * @memberof WebSocket
- */
- Object.defineProperty(WebSocket$2, "OPEN", {
- enumerable: true,
- value: readyStates.indexOf("OPEN")
- });
- /**
- * @constant {Number} OPEN
- * @memberof WebSocket.prototype
- */
- Object.defineProperty(WebSocket$2.prototype, "OPEN", {
- enumerable: true,
- value: readyStates.indexOf("OPEN")
- });
- /**
- * @constant {Number} CLOSING
- * @memberof WebSocket
- */
- Object.defineProperty(WebSocket$2, "CLOSING", {
- enumerable: true,
- value: readyStates.indexOf("CLOSING")
- });
- /**
- * @constant {Number} CLOSING
- * @memberof WebSocket.prototype
- */
- Object.defineProperty(WebSocket$2.prototype, "CLOSING", {
- enumerable: true,
- value: readyStates.indexOf("CLOSING")
- });
- /**
- * @constant {Number} CLOSED
- * @memberof WebSocket
- */
- Object.defineProperty(WebSocket$2, "CLOSED", {
- enumerable: true,
- value: readyStates.indexOf("CLOSED")
- });
- /**
- * @constant {Number} CLOSED
- * @memberof WebSocket.prototype
- */
- Object.defineProperty(WebSocket$2.prototype, "CLOSED", {
- enumerable: true,
- value: readyStates.indexOf("CLOSED")
- });
- [
- "binaryType",
- "bufferedAmount",
- "extensions",
- "isPaused",
- "protocol",
- "readyState",
- "url"
- ].forEach((property) => {
- Object.defineProperty(WebSocket$2.prototype, property, { enumerable: true });
- });
- [
- "open",
- "error",
- "close",
- "message"
- ].forEach((method) => {
- Object.defineProperty(WebSocket$2.prototype, `on${method}`, {
- enumerable: true,
- get() {
- for (const listener$1 of this.listeners(method)) if (listener$1[kForOnEventAttribute]) return listener$1[kListener];
- return null;
- },
- set(handler) {
- for (const listener$1 of this.listeners(method)) if (listener$1[kForOnEventAttribute]) {
- this.removeListener(method, listener$1);
- break;
- }
- if (typeof handler !== "function") return;
- this.addEventListener(method, handler, { [kForOnEventAttribute]: true });
- }
- });
- });
- WebSocket$2.prototype.addEventListener = addEventListener;
- WebSocket$2.prototype.removeEventListener = removeEventListener;
- module.exports = WebSocket$2;
- /**
- * Initialize a WebSocket client.
- *
- * @param {WebSocket} websocket The client to initialize
- * @param {(String|URL)} address The URL to which to connect
- * @param {Array} protocols The subprotocols
- * @param {Object} [options] Connection options
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any
- * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple
- * times in the same tick
- * @param {Boolean} [options.autoPong=true] Specifies whether or not to
- * automatically send a pong in response to a ping
- * @param {Function} [options.finishRequest] A function which can be used to
- * customize the headers of each http request before it is sent
- * @param {Boolean} [options.followRedirects=false] Whether or not to follow
- * redirects
- * @param {Function} [options.generateMask] The function used to generate the
- * masking key
- * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
- * handshake request
- * @param {Number} [options.maxPayload=104857600] The maximum allowed message
- * size
- * @param {Number} [options.maxRedirects=10] The maximum number of redirects
- * allowed
- * @param {String} [options.origin] Value of the `Origin` or
- * `Sec-WebSocket-Origin` header
- * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
- * permessage-deflate
- * @param {Number} [options.protocolVersion=13] Value of the
- * `Sec-WebSocket-Version` header
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
- * not to skip UTF-8 validation for text and close messages
- * @private
- */
- function initAsClient(websocket, address, protocols, options$1) {
- const opts = {
- allowSynchronousEvents: true,
- autoPong: true,
- protocolVersion: protocolVersions[1],
- maxPayload: 100 * 1024 * 1024,
- skipUTF8Validation: false,
- perMessageDeflate: true,
- followRedirects: false,
- maxRedirects: 10,
- ...options$1,
- socketPath: void 0,
- hostname: void 0,
- protocol: void 0,
- timeout: void 0,
- method: "GET",
- host: void 0,
- path: void 0,
- port: void 0
- };
- websocket._autoPong = opts.autoPong;
- if (!protocolVersions.includes(opts.protocolVersion)) throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);
- let parsedUrl;
- if (address instanceof URL$3) parsedUrl = address;
- else try {
- parsedUrl = new URL$3(address);
- } catch (e$1) {
- throw new SyntaxError(`Invalid URL: ${address}`);
- }
- if (parsedUrl.protocol === "http:") parsedUrl.protocol = "ws:";
- else if (parsedUrl.protocol === "https:") parsedUrl.protocol = "wss:";
- websocket._url = parsedUrl.href;
- const isSecure = parsedUrl.protocol === "wss:";
- const isIpcUrl = parsedUrl.protocol === "ws+unix:";
- let invalidUrlMessage;
- if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) invalidUrlMessage = "The URL's protocol must be one of \"ws:\", \"wss:\", \"http:\", \"https:\", or \"ws+unix:\"";
- else if (isIpcUrl && !parsedUrl.pathname) invalidUrlMessage = "The URL's pathname is empty";
- else if (parsedUrl.hash) invalidUrlMessage = "The URL contains a fragment identifier";
- if (invalidUrlMessage) {
- const err$2 = new SyntaxError(invalidUrlMessage);
- if (websocket._redirects === 0) throw err$2;
- else {
- emitErrorAndClose(websocket, err$2);
- return;
- }
- }
- const defaultPort = isSecure ? 443 : 80;
- const key = randomBytes(16).toString("base64");
- const request = isSecure ? https$3.request : http$5.request;
- const protocolSet = /* @__PURE__ */ new Set();
- let perMessageDeflate;
- opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
- opts.defaultPort = opts.defaultPort || defaultPort;
- opts.port = parsedUrl.port || defaultPort;
- opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
- opts.headers = {
- ...opts.headers,
- "Sec-WebSocket-Version": opts.protocolVersion,
- "Sec-WebSocket-Key": key,
- Connection: "Upgrade",
- Upgrade: "websocket"
- };
- opts.path = parsedUrl.pathname + parsedUrl.search;
- opts.timeout = opts.handshakeTimeout;
- if (opts.perMessageDeflate) {
- perMessageDeflate = new PerMessageDeflate$1(opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, false, opts.maxPayload);
- opts.headers["Sec-WebSocket-Extensions"] = format$1({ [PerMessageDeflate$1.extensionName]: perMessageDeflate.offer() });
- }
- if (protocols.length) {
- for (const protocol of protocols) {
- if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) throw new SyntaxError("An invalid or duplicated subprotocol was specified");
- protocolSet.add(protocol);
- }
- opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
- }
- if (opts.origin) if (opts.protocolVersion < 13) opts.headers["Sec-WebSocket-Origin"] = opts.origin;
- else opts.headers.Origin = opts.origin;
- if (parsedUrl.username || parsedUrl.password) opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
- if (isIpcUrl) {
- const parts = opts.path.split(":");
- opts.socketPath = parts[0];
- opts.path = parts[1];
- }
- let req$4;
- if (opts.followRedirects) {
- if (websocket._redirects === 0) {
- websocket._originalIpc = isIpcUrl;
- websocket._originalSecure = isSecure;
- websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
- const headers = options$1 && options$1.headers;
- options$1 = {
- ...options$1,
- headers: {}
- };
- if (headers) for (const [key$1, value$1] of Object.entries(headers)) options$1.headers[key$1.toLowerCase()] = value$1;
- } else if (websocket.listenerCount("redirect") === 0) {
- const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
- if (!isSameHost || websocket._originalSecure && !isSecure) {
- delete opts.headers.authorization;
- delete opts.headers.cookie;
- if (!isSameHost) delete opts.headers.host;
- opts.auth = void 0;
- }
- }
- if (opts.auth && !options$1.headers.authorization) options$1.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
- req$4 = websocket._req = request(opts);
- if (websocket._redirects) websocket.emit("redirect", websocket.url, req$4);
- } else req$4 = websocket._req = request(opts);
- if (opts.timeout) req$4.on("timeout", () => {
- abortHandshake$1(websocket, req$4, "Opening handshake has timed out");
- });
- req$4.on("error", (err$2) => {
- if (req$4 === null || req$4[kAborted]) return;
- req$4 = websocket._req = null;
- emitErrorAndClose(websocket, err$2);
- });
- req$4.on("response", (res) => {
- const location$1 = res.headers.location;
- const statusCode = res.statusCode;
- if (location$1 && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
- if (++websocket._redirects > opts.maxRedirects) {
- abortHandshake$1(websocket, req$4, "Maximum redirects exceeded");
- return;
- }
- req$4.abort();
- let addr;
- try {
- addr = new URL$3(location$1, address);
- } catch (e$1) {
- emitErrorAndClose(websocket, /* @__PURE__ */ new SyntaxError(`Invalid URL: ${location$1}`));
- return;
- }
- initAsClient(websocket, addr, protocols, options$1);
- } else if (!websocket.emit("unexpected-response", req$4, res)) abortHandshake$1(websocket, req$4, `Unexpected server response: ${res.statusCode}`);
- });
- req$4.on("upgrade", (res, socket, head) => {
- websocket.emit("upgrade", res);
- if (websocket.readyState !== WebSocket$2.CONNECTING) return;
- req$4 = websocket._req = null;
- const upgrade = res.headers.upgrade;
- if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
- abortHandshake$1(websocket, socket, "Invalid Upgrade header");
- return;
- }
- const digest = createHash$1("sha1").update(key + GUID$1).digest("base64");
- if (res.headers["sec-websocket-accept"] !== digest) {
- abortHandshake$1(websocket, socket, "Invalid Sec-WebSocket-Accept header");
- return;
- }
- const serverProt = res.headers["sec-websocket-protocol"];
- let protError;
- if (serverProt !== void 0) {
- if (!protocolSet.size) protError = "Server sent a subprotocol but none was requested";
- else if (!protocolSet.has(serverProt)) protError = "Server sent an invalid subprotocol";
- } else if (protocolSet.size) protError = "Server sent no subprotocol";
- if (protError) {
- abortHandshake$1(websocket, socket, protError);
- return;
- }
- if (serverProt) websocket._protocol = serverProt;
- const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
- if (secWebSocketExtensions !== void 0) {
- if (!perMessageDeflate) {
- abortHandshake$1(websocket, socket, "Server sent a Sec-WebSocket-Extensions header but no extension was requested");
- return;
- }
- let extensions$1;
- try {
- extensions$1 = parse$3(secWebSocketExtensions);
- } catch (err$2) {
- abortHandshake$1(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
- return;
- }
- const extensionNames = Object.keys(extensions$1);
- if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate$1.extensionName) {
- abortHandshake$1(websocket, socket, "Server indicated an extension that was not requested");
- return;
- }
- try {
- perMessageDeflate.accept(extensions$1[PerMessageDeflate$1.extensionName]);
- } catch (err$2) {
- abortHandshake$1(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
- return;
- }
- websocket._extensions[PerMessageDeflate$1.extensionName] = perMessageDeflate;
- }
- websocket.setSocket(socket, head, {
- allowSynchronousEvents: opts.allowSynchronousEvents,
- generateMask: opts.generateMask,
- maxPayload: opts.maxPayload,
- skipUTF8Validation: opts.skipUTF8Validation
- });
- });
- if (opts.finishRequest) opts.finishRequest(req$4, websocket);
- else req$4.end();
- }
- /**
- * Emit the `'error'` and `'close'` events.
- *
- * @param {WebSocket} websocket The WebSocket instance
- * @param {Error} The error to emit
- * @private
- */
- function emitErrorAndClose(websocket, err$2) {
- websocket._readyState = WebSocket$2.CLOSING;
- websocket._errorEmitted = true;
- websocket.emit("error", err$2);
- websocket.emitClose();
- }
- /**
- * Create a `net.Socket` and initiate a connection.
- *
- * @param {Object} options Connection options
- * @return {net.Socket} The newly created socket used to start the connection
- * @private
- */
- function netConnect(options$1) {
- options$1.path = options$1.socketPath;
- return net$1.connect(options$1);
- }
- /**
- * Create a `tls.TLSSocket` and initiate a connection.
- *
- * @param {Object} options Connection options
- * @return {tls.TLSSocket} The newly created socket used to start the connection
- * @private
- */
- function tlsConnect(options$1) {
- options$1.path = void 0;
- if (!options$1.servername && options$1.servername !== "") options$1.servername = net$1.isIP(options$1.host) ? "" : options$1.host;
- return tls.connect(options$1);
- }
- /**
- * Abort the handshake and emit an error.
- *
- * @param {WebSocket} websocket The WebSocket instance
- * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
- * abort or the socket to destroy
- * @param {String} message The error message
- * @private
- */
- function abortHandshake$1(websocket, stream$2, message) {
- websocket._readyState = WebSocket$2.CLOSING;
- const err$2 = new Error(message);
- Error.captureStackTrace(err$2, abortHandshake$1);
- if (stream$2.setHeader) {
- stream$2[kAborted] = true;
- stream$2.abort();
- if (stream$2.socket && !stream$2.socket.destroyed) stream$2.socket.destroy();
- process.nextTick(emitErrorAndClose, websocket, err$2);
- } else {
- stream$2.destroy(err$2);
- stream$2.once("error", websocket.emit.bind(websocket, "error"));
- stream$2.once("close", websocket.emitClose.bind(websocket));
- }
- }
- /**
- * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
- * when the `readyState` attribute is `CLOSING` or `CLOSED`.
- *
- * @param {WebSocket} websocket The WebSocket instance
- * @param {*} [data] The data to send
- * @param {Function} [cb] Callback
- * @private
- */
- function sendAfterClose(websocket, data, cb) {
- if (data) {
- const length = isBlob(data) ? data.size : toBuffer(data).length;
- if (websocket._socket) websocket._sender._bufferedBytes += length;
- else websocket._bufferedAmount += length;
- }
- if (cb) {
- const err$2 = /* @__PURE__ */ new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);
- process.nextTick(cb, err$2);
- }
- }
- /**
- * The listener of the `Receiver` `'conclude'` event.
- *
- * @param {Number} code The status code
- * @param {Buffer} reason The reason for closing
- * @private
- */
- function receiverOnConclude(code, reason) {
- const websocket = this[kWebSocket$1];
- websocket._closeFrameReceived = true;
- websocket._closeMessage = reason;
- websocket._closeCode = code;
- if (websocket._socket[kWebSocket$1] === void 0) return;
- websocket._socket.removeListener("data", socketOnData);
- process.nextTick(resume, websocket._socket);
- if (code === 1005) websocket.close();
- else websocket.close(code, reason);
- }
- /**
- * The listener of the `Receiver` `'drain'` event.
- *
- * @private
- */
- function receiverOnDrain() {
- const websocket = this[kWebSocket$1];
- if (!websocket.isPaused) websocket._socket.resume();
- }
- /**
- * The listener of the `Receiver` `'error'` event.
- *
- * @param {(RangeError|Error)} err The emitted error
- * @private
- */
- function receiverOnError(err$2) {
- const websocket = this[kWebSocket$1];
- if (websocket._socket[kWebSocket$1] !== void 0) {
- websocket._socket.removeListener("data", socketOnData);
- process.nextTick(resume, websocket._socket);
- websocket.close(err$2[kStatusCode]);
- }
- if (!websocket._errorEmitted) {
- websocket._errorEmitted = true;
- websocket.emit("error", err$2);
- }
- }
- /**
- * The listener of the `Receiver` `'finish'` event.
- *
- * @private
- */
- function receiverOnFinish() {
- this[kWebSocket$1].emitClose();
- }
- /**
- * The listener of the `Receiver` `'message'` event.
- *
- * @param {Buffer|ArrayBuffer|Buffer[])} data The message
- * @param {Boolean} isBinary Specifies whether the message is binary or not
- * @private
- */
- function receiverOnMessage(data, isBinary) {
- this[kWebSocket$1].emit("message", data, isBinary);
- }
- /**
- * The listener of the `Receiver` `'ping'` event.
- *
- * @param {Buffer} data The data included in the ping frame
- * @private
- */
- function receiverOnPing(data) {
- const websocket = this[kWebSocket$1];
- if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP$1);
- websocket.emit("ping", data);
- }
- /**
- * The listener of the `Receiver` `'pong'` event.
- *
- * @param {Buffer} data The data included in the pong frame
- * @private
- */
- function receiverOnPong(data) {
- this[kWebSocket$1].emit("pong", data);
- }
- /**
- * Resume a readable stream
- *
- * @param {Readable} stream The readable stream
- * @private
- */
- function resume(stream$2) {
- stream$2.resume();
- }
- /**
- * The `Sender` error event handler.
- *
- * @param {Error} The error
- * @private
- */
- function senderOnError(err$2) {
- const websocket = this[kWebSocket$1];
- if (websocket.readyState === WebSocket$2.CLOSED) return;
- if (websocket.readyState === WebSocket$2.OPEN) {
- websocket._readyState = WebSocket$2.CLOSING;
- setCloseTimer(websocket);
- }
- this._socket.end();
- if (!websocket._errorEmitted) {
- websocket._errorEmitted = true;
- websocket.emit("error", err$2);
- }
- }
- /**
- * Set a timer to destroy the underlying raw socket of a WebSocket.
- *
- * @param {WebSocket} websocket The WebSocket instance
- * @private
- */
- function setCloseTimer(websocket) {
- websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), closeTimeout);
- }
- /**
- * The listener of the socket `'close'` event.
- *
- * @private
- */
- function socketOnClose() {
- const websocket = this[kWebSocket$1];
- this.removeListener("close", socketOnClose);
- this.removeListener("data", socketOnData);
- this.removeListener("end", socketOnEnd);
- websocket._readyState = WebSocket$2.CLOSING;
- let chunk;
- if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) websocket._receiver.write(chunk);
- websocket._receiver.end();
- this[kWebSocket$1] = void 0;
- clearTimeout(websocket._closeTimer);
- if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) websocket.emitClose();
- else {
- websocket._receiver.on("error", receiverOnFinish);
- websocket._receiver.on("finish", receiverOnFinish);
- }
- }
- /**
- * The listener of the socket `'data'` event.
- *
- * @param {Buffer} chunk A chunk of data
- * @private
- */
- function socketOnData(chunk) {
- if (!this[kWebSocket$1]._receiver.write(chunk)) this.pause();
- }
- /**
- * The listener of the socket `'end'` event.
- *
- * @private
- */
- function socketOnEnd() {
- const websocket = this[kWebSocket$1];
- websocket._readyState = WebSocket$2.CLOSING;
- websocket._receiver.end();
- this.end();
- }
- /**
- * The listener of the socket `'error'` event.
- *
- * @private
- */
- function socketOnError$1() {
- const websocket = this[kWebSocket$1];
- this.removeListener("error", socketOnError$1);
- this.on("error", NOOP$1);
- if (websocket) {
- websocket._readyState = WebSocket$2.CLOSING;
- this.destroy();
- }
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/stream.js
-var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- require_websocket();
- const { Duplex: Duplex$1 } = __require("stream");
- /**
- * Emits the `'close'` event on a stream.
- *
- * @param {Duplex} stream The stream.
- * @private
- */
- function emitClose$1(stream$2) {
- stream$2.emit("close");
- }
- /**
- * The listener of the `'end'` event.
- *
- * @private
- */
- function duplexOnEnd() {
- if (!this.destroyed && this._writableState.finished) this.destroy();
- }
- /**
- * The listener of the `'error'` event.
- *
- * @param {Error} err The error
- * @private
- */
- function duplexOnError(err$2) {
- this.removeListener("error", duplexOnError);
- this.destroy();
- if (this.listenerCount("error") === 0) this.emit("error", err$2);
- }
- /**
- * Wraps a `WebSocket` in a duplex stream.
- *
- * @param {WebSocket} ws The `WebSocket` to wrap
- * @param {Object} [options] The options for the `Duplex` constructor
- * @return {Duplex} The duplex stream
- * @public
- */
- function createWebSocketStream$1(ws, options$1) {
- let terminateOnDestroy = true;
- const duplex = new Duplex$1({
- ...options$1,
- autoDestroy: false,
- emitClose: false,
- objectMode: false,
- writableObjectMode: false
- });
- ws.on("message", function message(msg, isBinary) {
- const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
- if (!duplex.push(data)) ws.pause();
- });
- ws.once("error", function error$1(err$2) {
- if (duplex.destroyed) return;
- terminateOnDestroy = false;
- duplex.destroy(err$2);
- });
- ws.once("close", function close$1() {
- if (duplex.destroyed) return;
- duplex.push(null);
- });
- duplex._destroy = function(err$2, callback) {
- if (ws.readyState === ws.CLOSED) {
- callback(err$2);
- process.nextTick(emitClose$1, duplex);
- return;
- }
- let called = false;
- ws.once("error", function error$1(err$3) {
- called = true;
- callback(err$3);
- });
- ws.once("close", function close$1() {
- if (!called) callback(err$2);
- process.nextTick(emitClose$1, duplex);
- });
- if (terminateOnDestroy) ws.terminate();
- };
- duplex._final = function(callback) {
- if (ws.readyState === ws.CONNECTING) {
- ws.once("open", function open$2() {
- duplex._final(callback);
- });
- return;
- }
- if (ws._socket === null) return;
- if (ws._socket._writableState.finished) {
- callback();
- if (duplex._readableState.endEmitted) duplex.destroy();
- } else {
- ws._socket.once("finish", function finish() {
- callback();
- });
- ws.close();
- }
- };
- duplex._read = function() {
- if (ws.isPaused) ws.resume();
- };
- duplex._write = function(chunk, encoding, callback) {
- if (ws.readyState === ws.CONNECTING) {
- ws.once("open", function open$2() {
- duplex._write(chunk, encoding, callback);
- });
- return;
- }
- ws.send(chunk, callback);
- };
- duplex.on("end", duplexOnEnd);
- duplex.on("error", duplexOnError);
- return duplex;
- }
- module.exports = createWebSocketStream$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/subprotocol.js
-var require_subprotocol = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const { tokenChars } = require_validation();
- /**
- * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
- *
- * @param {String} header The field value of the header
- * @return {Set} The subprotocol names
- * @public
- */
- function parse$2(header) {
- const protocols = /* @__PURE__ */ new Set();
- let start = -1;
- let end = -1;
- let i$1 = 0;
- for (; i$1 < header.length; i$1++) {
- const code = header.charCodeAt(i$1);
- if (end === -1 && tokenChars[code] === 1) {
- if (start === -1) start = i$1;
- } else if (i$1 !== 0 && (code === 32 || code === 9)) {
- if (end === -1 && start !== -1) end = i$1;
- } else if (code === 44) {
- if (start === -1) throw new SyntaxError(`Unexpected character at index ${i$1}`);
- if (end === -1) end = i$1;
- const protocol$1 = header.slice(start, end);
- if (protocols.has(protocol$1)) throw new SyntaxError(`The "${protocol$1}" subprotocol is duplicated`);
- protocols.add(protocol$1);
- start = end = -1;
- } else throw new SyntaxError(`Unexpected character at index ${i$1}`);
- }
- if (start === -1 || end !== -1) throw new SyntaxError("Unexpected end of input");
- const protocol = header.slice(start, i$1);
- if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
- protocols.add(protocol);
- return protocols;
- }
- module.exports = { parse: parse$2 };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/websocket-server.js
-var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const EventEmitter$1 = __require("events");
- const http$4 = __require("http");
- const { Duplex } = __require("stream");
- const { createHash } = __require("crypto");
- const extension = require_extension();
- const PerMessageDeflate = require_permessage_deflate();
- const subprotocol = require_subprotocol();
- const WebSocket$1 = require_websocket();
- const { GUID, kWebSocket } = require_constants();
- const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
- const RUNNING = 0;
- const CLOSING = 1;
- const CLOSED = 2;
- /**
- * Class representing a WebSocket server.
- *
- * @extends EventEmitter
- */
- var WebSocketServer$1 = class extends EventEmitter$1 {
- /**
- * Create a `WebSocketServer` instance.
- *
- * @param {Object} options Configuration options
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
- * multiple times in the same tick
- * @param {Boolean} [options.autoPong=true] Specifies whether or not to
- * automatically send a pong in response to a ping
- * @param {Number} [options.backlog=511] The maximum length of the queue of
- * pending connections
- * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
- * track clients
- * @param {Function} [options.handleProtocols] A hook to handle protocols
- * @param {String} [options.host] The hostname where to bind the server
- * @param {Number} [options.maxPayload=104857600] The maximum allowed message
- * size
- * @param {Boolean} [options.noServer=false] Enable no server mode
- * @param {String} [options.path] Accept only connections matching this path
- * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
- * permessage-deflate
- * @param {Number} [options.port] The port where to bind the server
- * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
- * server to use
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
- * not to skip UTF-8 validation for text and close messages
- * @param {Function} [options.verifyClient] A hook to reject connections
- * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
- * class to use. It must be the `WebSocket` class or class that extends it
- * @param {Function} [callback] A listener for the `listening` event
- */
- constructor(options$1, callback) {
- super();
- options$1 = {
- allowSynchronousEvents: true,
- autoPong: true,
- maxPayload: 100 * 1024 * 1024,
- skipUTF8Validation: false,
- perMessageDeflate: false,
- handleProtocols: null,
- clientTracking: true,
- verifyClient: null,
- noServer: false,
- backlog: null,
- server: null,
- host: null,
- path: null,
- port: null,
- WebSocket: WebSocket$1,
- ...options$1
- };
- if (options$1.port == null && !options$1.server && !options$1.noServer || options$1.port != null && (options$1.server || options$1.noServer) || options$1.server && options$1.noServer) throw new TypeError("One and only one of the \"port\", \"server\", or \"noServer\" options must be specified");
- if (options$1.port != null) {
- this._server = http$4.createServer((req$4, res) => {
- const body = http$4.STATUS_CODES[426];
- res.writeHead(426, {
- "Content-Length": body.length,
- "Content-Type": "text/plain"
- });
- res.end(body);
- });
- this._server.listen(options$1.port, options$1.host, options$1.backlog, callback);
- } else if (options$1.server) this._server = options$1.server;
- if (this._server) {
- const emitConnection = this.emit.bind(this, "connection");
- this._removeListeners = addListeners(this._server, {
- listening: this.emit.bind(this, "listening"),
- error: this.emit.bind(this, "error"),
- upgrade: (req$4, socket, head) => {
- this.handleUpgrade(req$4, socket, head, emitConnection);
- }
- });
- }
- if (options$1.perMessageDeflate === true) options$1.perMessageDeflate = {};
- if (options$1.clientTracking) {
- this.clients = /* @__PURE__ */ new Set();
- this._shouldEmitClose = false;
- }
- this.options = options$1;
- this._state = RUNNING;
- }
- /**
- * Returns the bound address, the address family name, and port of the server
- * as reported by the operating system if listening on an IP socket.
- * If the server is listening on a pipe or UNIX domain socket, the name is
- * returned as a string.
- *
- * @return {(Object|String|null)} The address of the server
- * @public
- */
- address() {
- if (this.options.noServer) throw new Error("The server is operating in \"noServer\" mode");
- if (!this._server) return null;
- return this._server.address();
- }
- /**
- * Stop the server from accepting new connections and emit the `'close'` event
- * when all existing connections are closed.
- *
- * @param {Function} [cb] A one-time listener for the `'close'` event
- * @public
- */
- close(cb) {
- if (this._state === CLOSED) {
- if (cb) this.once("close", () => {
- cb(/* @__PURE__ */ new Error("The server is not running"));
- });
- process.nextTick(emitClose, this);
- return;
- }
- if (cb) this.once("close", cb);
- if (this._state === CLOSING) return;
- this._state = CLOSING;
- if (this.options.noServer || this.options.server) {
- if (this._server) {
- this._removeListeners();
- this._removeListeners = this._server = null;
- }
- if (this.clients) if (!this.clients.size) process.nextTick(emitClose, this);
- else this._shouldEmitClose = true;
- else process.nextTick(emitClose, this);
- } else {
- const server = this._server;
- this._removeListeners();
- this._removeListeners = this._server = null;
- server.close(() => {
- emitClose(this);
- });
- }
- }
- /**
- * See if a given request should be handled by this server instance.
- *
- * @param {http.IncomingMessage} req Request object to inspect
- * @return {Boolean} `true` if the request is valid, else `false`
- * @public
- */
- shouldHandle(req$4) {
- if (this.options.path) {
- const index = req$4.url.indexOf("?");
- if ((index !== -1 ? req$4.url.slice(0, index) : req$4.url) !== this.options.path) return false;
- }
- return true;
- }
- /**
- * Handle a HTTP Upgrade request.
- *
- * @param {http.IncomingMessage} req The request object
- * @param {Duplex} socket The network socket between the server and client
- * @param {Buffer} head The first packet of the upgraded stream
- * @param {Function} cb Callback
- * @public
- */
- handleUpgrade(req$4, socket, head, cb) {
- socket.on("error", socketOnError);
- const key = req$4.headers["sec-websocket-key"];
- const upgrade = req$4.headers.upgrade;
- const version$2 = +req$4.headers["sec-websocket-version"];
- if (req$4.method !== "GET") {
- abortHandshakeOrEmitwsClientError(this, req$4, socket, 405, "Invalid HTTP method");
- return;
- }
- if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
- abortHandshakeOrEmitwsClientError(this, req$4, socket, 400, "Invalid Upgrade header");
- return;
- }
- if (key === void 0 || !keyRegex.test(key)) {
- abortHandshakeOrEmitwsClientError(this, req$4, socket, 400, "Missing or invalid Sec-WebSocket-Key header");
- return;
- }
- if (version$2 !== 13 && version$2 !== 8) {
- abortHandshakeOrEmitwsClientError(this, req$4, socket, 400, "Missing or invalid Sec-WebSocket-Version header", { "Sec-WebSocket-Version": "13, 8" });
- return;
- }
- if (!this.shouldHandle(req$4)) {
- abortHandshake(socket, 400);
- return;
- }
- const secWebSocketProtocol = req$4.headers["sec-websocket-protocol"];
- let protocols = /* @__PURE__ */ new Set();
- if (secWebSocketProtocol !== void 0) try {
- protocols = subprotocol.parse(secWebSocketProtocol);
- } catch (err$2) {
- abortHandshakeOrEmitwsClientError(this, req$4, socket, 400, "Invalid Sec-WebSocket-Protocol header");
- return;
- }
- const secWebSocketExtensions = req$4.headers["sec-websocket-extensions"];
- const extensions$1 = {};
- if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
- const perMessageDeflate = new PerMessageDeflate(this.options.perMessageDeflate, true, this.options.maxPayload);
- try {
- const offers = extension.parse(secWebSocketExtensions);
- if (offers[PerMessageDeflate.extensionName]) {
- perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
- extensions$1[PerMessageDeflate.extensionName] = perMessageDeflate;
- }
- } catch (err$2) {
- abortHandshakeOrEmitwsClientError(this, req$4, socket, 400, "Invalid or unacceptable Sec-WebSocket-Extensions header");
- return;
- }
- }
- if (this.options.verifyClient) {
- const info = {
- origin: req$4.headers[`${version$2 === 8 ? "sec-websocket-origin" : "origin"}`],
- secure: !!(req$4.socket.authorized || req$4.socket.encrypted),
- req: req$4
- };
- if (this.options.verifyClient.length === 2) {
- this.options.verifyClient(info, (verified, code, message, headers) => {
- if (!verified) return abortHandshake(socket, code || 401, message, headers);
- this.completeUpgrade(extensions$1, key, protocols, req$4, socket, head, cb);
- });
- return;
- }
- if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
- }
- this.completeUpgrade(extensions$1, key, protocols, req$4, socket, head, cb);
- }
- /**
- * Upgrade the connection to WebSocket.
- *
- * @param {Object} extensions The accepted extensions
- * @param {String} key The value of the `Sec-WebSocket-Key` header
- * @param {Set} protocols The subprotocols
- * @param {http.IncomingMessage} req The request object
- * @param {Duplex} socket The network socket between the server and client
- * @param {Buffer} head The first packet of the upgraded stream
- * @param {Function} cb Callback
- * @throws {Error} If called more than once with the same socket
- * @private
- */
- completeUpgrade(extensions$1, key, protocols, req$4, socket, head, cb) {
- if (!socket.readable || !socket.writable) return socket.destroy();
- if (socket[kWebSocket]) throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");
- if (this._state > RUNNING) return abortHandshake(socket, 503);
- const headers = [
- "HTTP/1.1 101 Switching Protocols",
- "Upgrade: websocket",
- "Connection: Upgrade",
- `Sec-WebSocket-Accept: ${createHash("sha1").update(key + GUID).digest("base64")}`
- ];
- const ws = new this.options.WebSocket(null, void 0, this.options);
- if (protocols.size) {
- const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req$4) : protocols.values().next().value;
- if (protocol) {
- headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
- ws._protocol = protocol;
- }
- }
- if (extensions$1[PerMessageDeflate.extensionName]) {
- const params = extensions$1[PerMessageDeflate.extensionName].params;
- const value$1 = extension.format({ [PerMessageDeflate.extensionName]: [params] });
- headers.push(`Sec-WebSocket-Extensions: ${value$1}`);
- ws._extensions = extensions$1;
- }
- this.emit("headers", headers, req$4);
- socket.write(headers.concat("\r\n").join("\r\n"));
- socket.removeListener("error", socketOnError);
- ws.setSocket(socket, head, {
- allowSynchronousEvents: this.options.allowSynchronousEvents,
- maxPayload: this.options.maxPayload,
- skipUTF8Validation: this.options.skipUTF8Validation
- });
- if (this.clients) {
- this.clients.add(ws);
- ws.on("close", () => {
- this.clients.delete(ws);
- if (this._shouldEmitClose && !this.clients.size) process.nextTick(emitClose, this);
- });
- }
- cb(ws, req$4);
- }
- };
- module.exports = WebSocketServer$1;
- /**
- * Add event listeners on an `EventEmitter` using a map of <event, listener>
- * pairs.
- *
- * @param {EventEmitter} server The event emitter
- * @param {Object.<String, Function>} map The listeners to add
- * @return {Function} A function that will remove the added listeners when
- * called
- * @private
- */
- function addListeners(server, map$1) {
- for (const event of Object.keys(map$1)) server.on(event, map$1[event]);
- return function removeListeners() {
- for (const event of Object.keys(map$1)) server.removeListener(event, map$1[event]);
- };
- }
- /**
- * Emit a `'close'` event on an `EventEmitter`.
- *
- * @param {EventEmitter} server The event emitter
- * @private
- */
- function emitClose(server) {
- server._state = CLOSED;
- server.emit("close");
- }
- /**
- * Handle socket errors.
- *
- * @private
- */
- function socketOnError() {
- this.destroy();
- }
- /**
- * Close the connection when preconditions are not fulfilled.
- *
- * @param {Duplex} socket The socket of the upgrade request
- * @param {Number} code The HTTP response status code
- * @param {String} [message] The HTTP response body
- * @param {Object} [headers] Additional HTTP response headers
- * @private
- */
- function abortHandshake(socket, code, message, headers) {
- message = message || http$4.STATUS_CODES[code];
- headers = {
- Connection: "close",
- "Content-Type": "text/html",
- "Content-Length": Buffer.byteLength(message),
- ...headers
- };
- socket.once("finish", socket.destroy);
- socket.end(`HTTP/1.1 ${code} ${http$4.STATUS_CODES[code]}\r\n` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message);
- }
- /**
- * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
- * one listener for it, otherwise call `abortHandshake()`.
- *
- * @param {WebSocketServer} server The WebSocket server
- * @param {http.IncomingMessage} req The request object
- * @param {Duplex} socket The socket of the upgrade request
- * @param {Number} code The HTTP response status code
- * @param {String} message The HTTP response body
- * @param {Object} [headers] The HTTP response headers
- * @private
- */
- function abortHandshakeOrEmitwsClientError(server, req$4, socket, code, message, headers) {
- if (server.listenerCount("wsClientError")) {
- const err$2 = new Error(message);
- Error.captureStackTrace(err$2, abortHandshakeOrEmitwsClientError);
- server.emit("wsClientError", err$2, socket, req$4);
- } else abortHandshake(socket, code, message, headers);
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/wrapper.mjs
-var import_stream = /* @__PURE__ */ __toESM(require_stream(), 1);
-var import_receiver = /* @__PURE__ */ __toESM(require_receiver(), 1);
-var import_sender = /* @__PURE__ */ __toESM(require_sender(), 1);
-var import_websocket = /* @__PURE__ */ __toESM(require_websocket(), 1);
-var import_websocket_server = /* @__PURE__ */ __toESM(require_websocket_server(), 1);
-
-//#endregion
-//#region ../../node_modules/.pnpm/host-validation-middleware@0.1.2/node_modules/host-validation-middleware/dist/index.js
-/**
-* This function assumes that the input is not malformed.
-* This is because we only care about browser requests.
-* Non-browser clients can send any value they want anyway.
-*/
-function extractHostNameFromHostHeader(hostHeader) {
- const trimmedHost = hostHeader.trim();
- if (trimmedHost[0] === "[") {
- const endIpv6 = trimmedHost.indexOf("]");
- if (endIpv6 < 0) return { type: "invalid" };
- return net.isIP(trimmedHost.slice(1, endIpv6)) === 6 ? { type: "ipv6" } : { type: "invalid" };
- }
- const colonPos = trimmedHost.indexOf(":");
- const hostname = colonPos === -1 ? trimmedHost : trimmedHost.slice(0, colonPos);
- if (net.isIP(hostname) === 4) return { type: "ipv4" };
- return {
- type: "hostname",
- value: hostname
- };
-}
-const isFileOrExtensionProtocolRE = /^(?:file|.+-extension):/i;
-function isHostAllowedInternal(hostHeader, allowedHosts) {
- if (isFileOrExtensionProtocolRE.test(hostHeader)) return true;
- const extracted = extractHostNameFromHostHeader(hostHeader);
- if (extracted.type === "invalid") return false;
- if (extracted.type === "ipv4" || extracted.type === "ipv6") return true;
- const hostname = extracted.value;
- if (hostname === "localhost" || hostname.endsWith(".localhost")) return true;
- for (const allowedHost of allowedHosts) {
- if (allowedHost === hostname) return true;
- if (allowedHost[0] === "." && (allowedHost.slice(1) === hostname || hostname.endsWith(allowedHost))) return true;
- }
- return false;
-}
-const cache = /* @__PURE__ */ new WeakMap();
-/**
-* Check if the host contained in the host header is allowed.
-*
-* This function will cache the result if the `allowedHosts` array is frozen.
-*
-* @param hostHeader - The value of host header. See [RFC 9110 7.2](https://datatracker.ietf.org/doc/html/rfc9110#name-host-and-authority).
-* @param allowedHosts - The allowed host patterns. See the README for more details.
-*/
-function isHostAllowed(hostHeader, allowedHosts) {
- if (hostHeader === void 0) return true;
- let cachedAllowedHosts;
- if (Object.isFrozen(allowedHosts)) {
- if (!cache.has(allowedHosts)) cache.set(allowedHosts, /* @__PURE__ */ new Set());
- cachedAllowedHosts = cache.get(allowedHosts);
- if (cachedAllowedHosts.has(hostHeader)) return true;
- }
- const result = isHostAllowedInternal(hostHeader, allowedHosts);
- if (cachedAllowedHosts && result) cachedAllowedHosts.add(hostHeader);
- return result;
-}
-/**
-* Middleware to validate the host header of incoming requests.
-*
-* If the host header is not in the allowed hosts list, a 403 Forbidden response
-* is sent.
-*/
-function hostValidationMiddleware$1(options$1) {
- return async function hostValidationMiddleware$1$1(req$4, res, next) {
- const hostHeader = req$4.headers.host;
- if (!isHostAllowed(hostHeader, options$1.allowedHosts)) {
- const hostname = hostHeader?.replace(/:\d+$/, "") ?? "";
- const errorMessage = options$1.generateErrorMessage?.(hostname) ?? generateDefaultErrorMessage(hostname);
- res.writeHead(403, { "Content-Type": options$1.errorResponseContentType ?? "text/plain" });
- res.end(errorMessage);
- return;
- }
- next();
- };
-}
-function generateDefaultErrorMessage(hostname) {
- return `Blocked request. This host (${JSON.stringify(hostname)}) is not allowed.`;
-}
-
-//#endregion
-//#region src/node/server/ws.ts
-var import_picocolors$21 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const WebSocketServerRaw = process.versions.bun ? import.meta.require("ws").WebSocketServer : import_websocket_server.default;
-const HMR_HEADER = "vite-hmr";
-const isWebSocketServer = Symbol("isWebSocketServer");
-const wsServerEvents = [
- "connection",
- "error",
- "headers",
- "listening",
- "message"
-];
-function noop$2() {}
-function hasValidToken(config$2, url$3) {
- const token = url$3.searchParams.get("token");
- if (!token) return false;
- try {
- return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(config$2.webSocketToken));
- } catch {}
- return false;
-}
-function createWebSocketServer(server, config$2, httpsOptions) {
- if (config$2.server.ws === false) return {
- [isWebSocketServer]: true,
- get clients() {
- return /* @__PURE__ */ new Set();
- },
- async close() {},
- on: noop$2,
- off: noop$2,
- setInvokeHandler: noop$2,
- handleInvoke: async () => ({ error: {
- name: "TransportError",
- message: "handleInvoke not implemented",
- stack: (/* @__PURE__ */ new Error()).stack
- } }),
- listen: noop$2,
- send: noop$2
- };
- let wsHttpServer = void 0;
- const hmr = isObject(config$2.server.hmr) && config$2.server.hmr;
- const hmrServer = hmr && hmr.server;
- const hmrPort = hmr && hmr.port;
- const wsServer = hmrServer || (!hmrPort || hmrPort === config$2.server.port) && server;
- let hmrServerWsListener;
- const customListeners = /* @__PURE__ */ new Map();
- const clientsMap = /* @__PURE__ */ new WeakMap();
- const port = hmrPort || 24678;
- const host = hmr && hmr.host || void 0;
- const allowedHosts = config$2.server.allowedHosts === true ? config$2.server.allowedHosts : Object.freeze([...config$2.server.allowedHosts]);
- const shouldHandle = (req$4) => {
- if (req$4.headers["sec-websocket-protocol"] === "vite-ping") return true;
- if (allowedHosts !== true && !isHostAllowed(req$4.headers.host, allowedHosts)) return false;
- if (config$2.legacy?.skipWebSocketTokenCheck) return true;
- if (req$4.headers.origin) return hasValidToken(config$2, new URL(`http://example.com${req$4.url}`));
- return true;
- };
- const handleUpgrade = (req$4, socket, head, isPing) => {
- wss.handleUpgrade(req$4, socket, head, (ws) => {
- if (isPing) {
- ws.close(1e3);
- return;
- }
- wss.emit("connection", ws, req$4);
- });
- };
- const wss = new WebSocketServerRaw({ noServer: true });
- wss.shouldHandle = shouldHandle;
- if (wsServer) {
- let hmrBase = config$2.base;
- const hmrPath = hmr ? hmr.path : void 0;
- if (hmrPath) hmrBase = path.posix.join(hmrBase, hmrPath);
- hmrServerWsListener = (req$4, socket, head) => {
- const protocol = req$4.headers["sec-websocket-protocol"];
- const parsedUrl = new URL(`http://example.com${req$4.url}`);
- if ([HMR_HEADER, "vite-ping"].includes(protocol) && parsedUrl.pathname === hmrBase) handleUpgrade(req$4, socket, head, protocol === "vite-ping");
- };
- wsServer.on("upgrade", hmrServerWsListener);
- } else {
- const route = ((_, res) => {
- const statusCode = 426;
- const body = STATUS_CODES[statusCode];
- if (!body) throw new Error(`No body text found for the ${statusCode} status code`);
- res.writeHead(statusCode, {
- "Content-Length": body.length,
- "Content-Type": "text/plain"
- });
- res.end(body);
- });
- if (httpsOptions) wsHttpServer = createServer$1(httpsOptions, route);
- else wsHttpServer = createServer(route);
- wsHttpServer.on("upgrade", (req$4, socket, head) => {
- const protocol = req$4.headers["sec-websocket-protocol"];
- if (protocol === "vite-ping" && server && !server.listening) {
- req$4.destroy();
- return;
- }
- handleUpgrade(req$4, socket, head, protocol === "vite-ping");
- });
- wsHttpServer.on("error", (e$1) => {
- if (e$1.code === "EADDRINUSE") config$2.logger.error(import_picocolors$21.default.red(`WebSocket server error: Port ${e$1.port} is already in use`), { error: e$1 });
- else config$2.logger.error(import_picocolors$21.default.red(`WebSocket server error:\n${e$1.stack || e$1.message}`), { error: e$1 });
- });
- }
- const emitCustomEvent = (event, data, socket) => {
- const listeners = customListeners.get(event);
- if (!listeners?.size) return;
- const client = getSocketClient(socket);
- for (const listener$1 of listeners) listener$1(data, client);
- };
- wss.on("connection", (socket) => {
- socket.on("message", (raw) => {
- if (!customListeners.size) return;
- let parsed;
- try {
- parsed = JSON.parse(String(raw));
- } catch {}
- if (!parsed || parsed.type !== "custom" || !parsed.event) return;
- emitCustomEvent(parsed.event, parsed.data, socket);
- });
- socket.on("error", (err$2) => {
- config$2.logger.error(`${import_picocolors$21.default.red(`ws error:`)}\n${err$2.stack}`, {
- timestamp: true,
- error: err$2
- });
- });
- socket.on("close", () => {
- emitCustomEvent("vite:client:disconnect", void 0, socket);
- });
- emitCustomEvent("vite:client:connect", void 0, socket);
- socket.send(JSON.stringify({ type: "connected" }));
- if (bufferedError) {
- socket.send(JSON.stringify(bufferedError));
- bufferedError = null;
- }
- });
- wss.on("error", (e$1) => {
- if (e$1.code === "EADDRINUSE") config$2.logger.error(import_picocolors$21.default.red(`WebSocket server error: Port ${e$1.port} is already in use`), { error: e$1 });
- else config$2.logger.error(import_picocolors$21.default.red(`WebSocket server error:\n${e$1.stack || e$1.message}`), { error: e$1 });
- });
- function getSocketClient(socket) {
- if (!clientsMap.has(socket)) clientsMap.set(socket, {
- send: (...args) => {
- let payload;
- if (typeof args[0] === "string") payload = {
- type: "custom",
- event: args[0],
- data: args[1]
- };
- else payload = args[0];
- socket.send(JSON.stringify(payload));
- },
- socket
- });
- return clientsMap.get(socket);
- }
- let bufferedError = null;
- const normalizedHotChannel = normalizeHotChannel({
- send(payload) {
- if (payload.type === "error" && !wss.clients.size) {
- bufferedError = payload;
- return;
- }
- const stringified = JSON.stringify(payload);
- wss.clients.forEach((client) => {
- if (client.readyState === 1) client.send(stringified);
- });
- },
- on(event, fn) {
- if (!customListeners.has(event)) customListeners.set(event, /* @__PURE__ */ new Set());
- customListeners.get(event).add(fn);
- },
- off(event, fn) {
- customListeners.get(event)?.delete(fn);
- },
- listen() {
- wsHttpServer?.listen(port, host);
- },
- close() {
- if (hmrServerWsListener && wsServer) wsServer.off("upgrade", hmrServerWsListener);
- return new Promise((resolve$4, reject) => {
- wss.clients.forEach((client) => {
- client.terminate();
- });
- wss.close((err$2) => {
- if (err$2) reject(err$2);
- else if (wsHttpServer) wsHttpServer.close((err$3) => {
- if (err$3) reject(err$3);
- else resolve$4();
- });
- else resolve$4();
- });
- });
- }
- }, config$2.server.hmr !== false, false);
- return {
- ...normalizedHotChannel,
- on: ((event, fn) => {
- if (wsServerEvents.includes(event)) {
- wss.on(event, fn);
- return;
- }
- normalizedHotChannel.on(event, fn);
- }),
- off: ((event, fn) => {
- if (wsServerEvents.includes(event)) {
- wss.off(event, fn);
- return;
- }
- normalizedHotChannel.off(event, fn);
- }),
- async close() {
- await normalizedHotChannel.close();
- },
- [isWebSocketServer]: true,
- get clients() {
- return new Set(Array.from(wss.clients).map(getSocketClient));
- }
- };
-}
-
-//#endregion
-//#region src/node/server/middlewares/base.ts
-function baseMiddleware(rawBase, middlewareMode) {
- return function viteBaseMiddleware(req$4, res, next) {
- const url$3 = req$4.url;
- const pathname = cleanUrl(url$3);
- const base = rawBase;
- if (pathname.startsWith(base)) {
- req$4.url = stripBase(url$3, base);
- return next();
- }
- if (middlewareMode) return next();
- if (pathname === "/" || pathname === "/index.html") {
- res.writeHead(302, { Location: base + url$3.slice(pathname.length) });
- res.end();
- return;
- }
- const redirectPath = withTrailingSlash(url$3) !== base ? joinUrlSegments(base, url$3) : base;
- if (req$4.headers.accept?.includes("text/html")) {
- res.writeHead(404, { "Content-Type": "text/html" });
- res.end(`The server is configured with a public base URL of ${base} - did you mean to visit <a href="${redirectPath}">${redirectPath}</a> instead?`);
- return;
- } else {
- res.writeHead(404, { "Content-Type": "text/plain" });
- res.end(`The server is configured with a public base URL of ${base} - did you mean to visit ${redirectPath} instead?`);
- return;
- }
- };
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/http-proxy-3@1.22.0_patch_hash=d89dff5a0afc2cb277080ad056a3baf7feeeeac19144878abc17f4c91ad89095_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/common.js
-var require_common = /* @__PURE__ */ __commonJSMin(((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.isSSL = void 0;
- exports.setupOutgoing = setupOutgoing;
- exports.setupSocket = setupSocket;
- exports.getPort = getPort;
- exports.hasEncryptedConnection = hasEncryptedConnection;
- exports.urlJoin = urlJoin;
- exports.rewriteCookieProperty = rewriteCookieProperty;
- exports.toURL = toURL;
- const node_tls_1 = __require("node:tls");
- const upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i;
- exports.isSSL = /^https|wss/;
- const HEADER_BLACKLIST = "trailer";
- const HTTP2_HEADER_BLACKLIST = [
- ":method",
- ":path",
- ":scheme",
- ":authority"
- ];
- function setupOutgoing(outgoing, options$1, req$4, forward) {
- const target = options$1[forward || "target"];
- outgoing.port = +(target.port ?? (target.protocol !== void 0 && exports.isSSL.test(target.protocol) ? 443 : 80));
- for (const e$1 of [
- "host",
- "hostname",
- "socketPath",
- "pfx",
- "key",
- "passphrase",
- "cert",
- "ca",
- "ciphers",
- "secureProtocol"
- ]) outgoing[e$1] = target[e$1];
- outgoing.method = options$1.method || req$4.method;
- outgoing.headers = { ...req$4.headers };
- if (req$4.headers[":authority"]) outgoing.headers.host = req$4.headers[":authority"];
- if (options$1.headers) outgoing.headers = {
- ...outgoing.headers,
- ...options$1.headers
- };
- for (const header in outgoing.headers) if (HEADER_BLACKLIST == header.toLowerCase()) {
- delete outgoing.headers[header];
- break;
- }
- if (req$4.httpVersionMajor > 1) for (const header of HTTP2_HEADER_BLACKLIST) delete outgoing.headers[header];
- if (options$1.auth) {
- delete outgoing.headers.authorization;
- outgoing.auth = options$1.auth;
- }
- if (options$1.ca) outgoing.ca = options$1.ca;
- if (target.protocol !== void 0 && exports.isSSL.test(target.protocol)) outgoing.rejectUnauthorized = typeof options$1.secure === "undefined" ? true : options$1.secure;
- outgoing.agent = options$1.agent || false;
- outgoing.localAddress = options$1.localAddress;
- if (!outgoing.agent) {
- outgoing.headers = outgoing.headers || {};
- if (typeof outgoing.headers.connection !== "string" || !upgradeHeader.test(outgoing.headers.connection)) outgoing.headers.connection = "close";
- }
- const targetPath = target && options$1.prependPath !== false && "pathname" in target ? getPath(`${target.pathname}${target.search ?? ""}`) : "/";
- let outgoingPath = options$1.toProxy ? req$4.url : getPath(req$4.url);
- outgoingPath = !options$1.ignorePath ? outgoingPath : "";
- outgoing.path = urlJoin(targetPath, outgoingPath ?? "");
- if (options$1.changeOrigin) outgoing.headers.host = target.protocol !== void 0 && required(outgoing.port, target.protocol) && !hasPort(outgoing.host) ? outgoing.host + ":" + outgoing.port : outgoing.host;
- return outgoing;
- }
- function setupSocket(socket) {
- socket.setTimeout(0);
- socket.setNoDelay(true);
- socket.setKeepAlive(true, 0);
- return socket;
- }
- function getPort(req$4) {
- const hostHeader = req$4.headers[":authority"] || req$4.headers.host;
- const res = hostHeader ? hostHeader.match(/:(\d+)/) : "";
- return res ? res[1] : hasEncryptedConnection(req$4) ? "443" : "80";
- }
- function hasEncryptedConnection(req$4) {
- const conn = req$4.connection;
- return conn instanceof node_tls_1.TLSSocket && conn.encrypted || Boolean(conn.pair);
- }
- function urlJoin(...args) {
- const queryParams = [];
- let queryParamRaw = "";
- args.forEach((url$3, index) => {
- const qpStart = url$3.indexOf("?");
- if (qpStart !== -1) {
- queryParams.push(url$3.substring(qpStart + 1));
- args[index] = url$3.substring(0, qpStart);
- }
- });
- queryParamRaw = queryParams.filter(Boolean).join("&");
- let retSegs = "";
- for (const seg of args) {
- if (!seg) continue;
- if (retSegs.endsWith("/")) if (seg.startsWith("/")) retSegs += seg.slice(1);
- else retSegs += seg;
- else if (seg.startsWith("/")) retSegs += seg;
- else retSegs += "/" + seg;
- }
- return queryParamRaw ? retSegs + "?" + queryParamRaw : retSegs;
- }
- function rewriteCookieProperty(header, config$2, property) {
- if (Array.isArray(header)) return header.map((headerElement) => {
- return rewriteCookieProperty(headerElement, config$2, property);
- });
- return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", "i"), (match, prefix, previousValue) => {
- let newValue;
- if (previousValue in config$2) newValue = config$2[previousValue];
- else if ("*" in config$2) newValue = config$2["*"];
- else return match;
- if (newValue) return prefix + newValue;
- else return "";
- });
- }
- function hasPort(host) {
- return !!~host.indexOf(":");
- }
- function getPath(url$3) {
- if (url$3 === "" || url$3?.startsWith("?")) return url$3;
- const u = toURL(url$3);
- return `${u.pathname ?? ""}${u.search ?? ""}`;
- }
- function toURL(url$3) {
- if (url$3 instanceof URL) return url$3;
- else if (typeof url$3 === "object" && "href" in url$3 && typeof url$3.href === "string") url$3 = url$3.href;
- if (!url$3) url$3 = "";
- if (typeof url$3 != "string") url$3 = `${url$3}`;
- if (url$3.startsWith("//")) url$3 = `http://base.invalid${url$3}`;
- return new URL(url$3, "http://base.invalid");
- }
- function required(port, protocol) {
- protocol = protocol.split(":")[0];
- port = +port;
- if (!port) return false;
- switch (protocol) {
- case "http":
- case "ws": return port !== 80;
- case "https":
- case "wss": return port !== 443;
- }
- return port !== 0;
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/http-proxy-3@1.22.0_patch_hash=d89dff5a0afc2cb277080ad056a3baf7feeeeac19144878abc17f4c91ad89095_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/passes/web-outgoing.js
-var require_web_outgoing = /* @__PURE__ */ __commonJSMin(((exports) => {
- var __createBinding$3 = exports && exports.__createBinding || (Object.create ? (function(o$1, m, k, k2) {
- if (k2 === void 0) 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$1, k2, desc);
- }) : (function(o$1, m, k, k2) {
- if (k2 === void 0) k2 = k;
- o$1[k2] = m[k];
- }));
- var __setModuleDefault$3 = exports && exports.__setModuleDefault || (Object.create ? (function(o$1, v) {
- Object.defineProperty(o$1, "default", {
- enumerable: true,
- value: v
- });
- }) : function(o$1, v) {
- o$1["default"] = v;
- });
- var __importStar$3 = exports && exports.__importStar || (function() {
- var ownKeys = function(o$1) {
- ownKeys = Object.getOwnPropertyNames || function(o$2) {
- var ar = [];
- for (var k in o$2) if (Object.prototype.hasOwnProperty.call(o$2, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o$1);
- };
- return function(mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) {
- for (var k = ownKeys(mod), i$1 = 0; i$1 < k.length; i$1++) if (k[i$1] !== "default") __createBinding$3(result, mod, k[i$1]);
- }
- __setModuleDefault$3(result, mod);
- return result;
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.OUTGOING_PASSES = void 0;
- exports.removeChunked = removeChunked;
- exports.setConnection = setConnection;
- exports.setRedirectHostRewrite = setRedirectHostRewrite;
- exports.writeHeaders = writeHeaders;
- exports.writeStatusCode = writeStatusCode;
- const common$2 = __importStar$3(require_common());
- const redirectRegex = /^201|30(1|2|7|8)$/;
- function removeChunked(_req, _res, proxyRes) {
- delete proxyRes.headers["transfer-encoding"];
- }
- function setConnection(req$4, _res, proxyRes) {
- if (req$4.httpVersion === "1.0") proxyRes.headers["connection"] = req$4.headers["connection"] || "close";
- else if (req$4.httpVersion !== "2.0" && !proxyRes.headers["connection"]) proxyRes.headers["connection"] = req$4.headers["connection"] || "keep-alive";
- }
- function setRedirectHostRewrite(req$4, _res, proxyRes, options$1) {
- if ((options$1.hostRewrite || options$1.autoRewrite || options$1.protocolRewrite) && proxyRes.headers["location"] && redirectRegex.test(`${proxyRes.statusCode}`)) {
- const target = common$2.toURL(options$1.target);
- const location$1 = proxyRes.headers["location"];
- if (typeof location$1 != "string") return;
- const u = common$2.toURL(location$1);
- if (target.host != u.host) return;
- if (options$1.hostRewrite) u.host = options$1.hostRewrite;
- else if (options$1.autoRewrite) u.host = req$4.headers[":authority"] ?? req$4.headers["host"] ?? "";
- if (options$1.protocolRewrite) u.protocol = options$1.protocolRewrite;
- proxyRes.headers["location"] = u.toString();
- }
- }
- function writeHeaders(_req, res, proxyRes, options$1) {
- const rewriteCookieDomainConfig = typeof options$1.cookieDomainRewrite === "string" ? { "*": options$1.cookieDomainRewrite } : options$1.cookieDomainRewrite;
- const rewriteCookiePathConfig = typeof options$1.cookiePathRewrite === "string" ? { "*": options$1.cookiePathRewrite } : options$1.cookiePathRewrite;
- const preserveHeaderKeyCase = options$1.preserveHeaderKeyCase;
- const setHeader = (key, header) => {
- if (header == void 0) return;
- if (rewriteCookieDomainConfig && key.toLowerCase() === "set-cookie") header = common$2.rewriteCookieProperty(header, rewriteCookieDomainConfig, "domain");
- if (rewriteCookiePathConfig && key.toLowerCase() === "set-cookie") header = common$2.rewriteCookieProperty(header, rewriteCookiePathConfig, "path");
- res.setHeader(String(key).trim(), header);
- };
- let rawHeaderKeyMap;
- if (preserveHeaderKeyCase && proxyRes.rawHeaders != void 0) {
- rawHeaderKeyMap = {};
- for (let i$1 = 0; i$1 < proxyRes.rawHeaders.length; i$1 += 2) {
- const key = proxyRes.rawHeaders[i$1];
- rawHeaderKeyMap[key.toLowerCase()] = key;
- }
- }
- for (const key0 in proxyRes.headers) {
- let key = key0;
- if (_req.httpVersionMajor > 1 && key === "connection") continue;
- const header = proxyRes.headers[key];
- if (preserveHeaderKeyCase && rawHeaderKeyMap) key = rawHeaderKeyMap[key] ?? key;
- setHeader(key, header);
- }
- }
- function writeStatusCode(_req, res, proxyRes) {
- res.statusCode = proxyRes.statusCode;
- if (proxyRes.statusMessage && _req.httpVersionMajor === 1) res.statusMessage = proxyRes.statusMessage;
- }
- exports.OUTGOING_PASSES = {
- removeChunked,
- setConnection,
- setRedirectHostRewrite,
- writeHeaders,
- writeStatusCode
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/follow-redirects@1.15.11_obug@1.0.2_ms@2.1.3_/node_modules/follow-redirects/debug.js
-var require_debug = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- var debug$11;
- module.exports = function() {
- if (!debug$11) {
- try {
- debug$11 = (init_node(), __toCommonJS(node_exports))("follow-redirects");
- } catch (error$1) {}
- if (typeof debug$11 !== "function") debug$11 = function() {};
- }
- debug$11.apply(null, arguments);
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/follow-redirects@1.15.11_obug@1.0.2_ms@2.1.3_/node_modules/follow-redirects/index.js
-var require_follow_redirects = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- var url = __require("url");
- var URL$2 = url.URL;
- var http$3 = __require("http");
- var https$2 = __require("https");
- var Writable = __require("stream").Writable;
- var assert$1 = __require("assert");
- var debug$10 = require_debug();
- // istanbul ignore next
- (function detectUnsupportedEnvironment() {
- var looksLikeNode = typeof process !== "undefined";
- var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined";
- var looksLikeV8 = isFunction(Error.captureStackTrace);
- if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) console.warn("The follow-redirects package should be excluded from browser builds.");
- })();
- var useNativeURL = false;
- try {
- assert$1(new URL$2(""));
- } catch (error$1) {
- useNativeURL = error$1.code === "ERR_INVALID_URL";
- }
- var preservedUrlFields = [
- "auth",
- "host",
- "hostname",
- "href",
- "path",
- "pathname",
- "port",
- "protocol",
- "query",
- "search",
- "hash"
- ];
- var events = [
- "abort",
- "aborted",
- "connect",
- "error",
- "socket",
- "timeout"
- ];
- var eventHandlers = Object.create(null);
- events.forEach(function(event) {
- eventHandlers[event] = function(arg1, arg2, arg3) {
- this._redirectable.emit(event, arg1, arg2, arg3);
- };
- });
- var InvalidUrlError = createErrorType("ERR_INVALID_URL", "Invalid URL", TypeError);
- var RedirectionError = createErrorType("ERR_FR_REDIRECTION_FAILURE", "Redirected request failed");
- var TooManyRedirectsError = createErrorType("ERR_FR_TOO_MANY_REDIRECTS", "Maximum number of redirects exceeded", RedirectionError);
- var MaxBodyLengthExceededError = createErrorType("ERR_FR_MAX_BODY_LENGTH_EXCEEDED", "Request body larger than maxBodyLength limit");
- var WriteAfterEndError = createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end");
- // istanbul ignore next
- var destroy = Writable.prototype.destroy || noop$1;
- function RedirectableRequest(options$1, responseCallback) {
- Writable.call(this);
- this._sanitizeOptions(options$1);
- this._options = options$1;
- this._ended = false;
- this._ending = false;
- this._redirectCount = 0;
- this._redirects = [];
- this._requestBodyLength = 0;
- this._requestBodyBuffers = [];
- if (responseCallback) this.on("response", responseCallback);
- var self$1 = this;
- this._onNativeResponse = function(response) {
- try {
- self$1._processResponse(response);
- } catch (cause) {
- self$1.emit("error", cause instanceof RedirectionError ? cause : new RedirectionError({ cause }));
- }
- };
- this._performRequest();
- }
- RedirectableRequest.prototype = Object.create(Writable.prototype);
- RedirectableRequest.prototype.abort = function() {
- destroyRequest(this._currentRequest);
- this._currentRequest.abort();
- this.emit("abort");
- };
- RedirectableRequest.prototype.destroy = function(error$1) {
- destroyRequest(this._currentRequest, error$1);
- destroy.call(this, error$1);
- return this;
- };
- RedirectableRequest.prototype.write = function(data, encoding, callback) {
- if (this._ending) throw new WriteAfterEndError();
- if (!isString(data) && !isBuffer(data)) throw new TypeError("data should be a string, Buffer or Uint8Array");
- if (isFunction(encoding)) {
- callback = encoding;
- encoding = null;
- }
- if (data.length === 0) {
- if (callback) callback();
- return;
- }
- if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
- this._requestBodyLength += data.length;
- this._requestBodyBuffers.push({
- data,
- encoding
- });
- this._currentRequest.write(data, encoding, callback);
- } else {
- this.emit("error", new MaxBodyLengthExceededError());
- this.abort();
- }
- };
- RedirectableRequest.prototype.end = function(data, encoding, callback) {
- if (isFunction(data)) {
- callback = data;
- data = encoding = null;
- } else if (isFunction(encoding)) {
- callback = encoding;
- encoding = null;
- }
- if (!data) {
- this._ended = this._ending = true;
- this._currentRequest.end(null, null, callback);
- } else {
- var self$1 = this;
- var currentRequest = this._currentRequest;
- this.write(data, encoding, function() {
- self$1._ended = true;
- currentRequest.end(null, null, callback);
- });
- this._ending = true;
- }
- };
- RedirectableRequest.prototype.setHeader = function(name, value$1) {
- this._options.headers[name] = value$1;
- this._currentRequest.setHeader(name, value$1);
- };
- RedirectableRequest.prototype.removeHeader = function(name) {
- delete this._options.headers[name];
- this._currentRequest.removeHeader(name);
- };
- RedirectableRequest.prototype.setTimeout = function(msecs, callback) {
- var self$1 = this;
- function destroyOnTimeout(socket) {
- socket.setTimeout(msecs);
- socket.removeListener("timeout", socket.destroy);
- socket.addListener("timeout", socket.destroy);
- }
- function startTimer(socket) {
- if (self$1._timeout) clearTimeout(self$1._timeout);
- self$1._timeout = setTimeout(function() {
- self$1.emit("timeout");
- clearTimer();
- }, msecs);
- destroyOnTimeout(socket);
- }
- function clearTimer() {
- if (self$1._timeout) {
- clearTimeout(self$1._timeout);
- self$1._timeout = null;
- }
- self$1.removeListener("abort", clearTimer);
- self$1.removeListener("error", clearTimer);
- self$1.removeListener("response", clearTimer);
- self$1.removeListener("close", clearTimer);
- if (callback) self$1.removeListener("timeout", callback);
- if (!self$1.socket) self$1._currentRequest.removeListener("socket", startTimer);
- }
- if (callback) this.on("timeout", callback);
- if (this.socket) startTimer(this.socket);
- else this._currentRequest.once("socket", startTimer);
- this.on("socket", destroyOnTimeout);
- this.on("abort", clearTimer);
- this.on("error", clearTimer);
- this.on("response", clearTimer);
- this.on("close", clearTimer);
- return this;
- };
- [
- "flushHeaders",
- "getHeader",
- "setNoDelay",
- "setSocketKeepAlive"
- ].forEach(function(method) {
- RedirectableRequest.prototype[method] = function(a, b) {
- return this._currentRequest[method](a, b);
- };
- });
- [
- "aborted",
- "connection",
- "socket"
- ].forEach(function(property) {
- Object.defineProperty(RedirectableRequest.prototype, property, { get: function() {
- return this._currentRequest[property];
- } });
- });
- RedirectableRequest.prototype._sanitizeOptions = function(options$1) {
- if (!options$1.headers) options$1.headers = {};
- if (options$1.host) {
- if (!options$1.hostname) options$1.hostname = options$1.host;
- delete options$1.host;
- }
- if (!options$1.pathname && options$1.path) {
- var searchPos = options$1.path.indexOf("?");
- if (searchPos < 0) options$1.pathname = options$1.path;
- else {
- options$1.pathname = options$1.path.substring(0, searchPos);
- options$1.search = options$1.path.substring(searchPos);
- }
- }
- };
- RedirectableRequest.prototype._performRequest = function() {
- var protocol = this._options.protocol;
- var nativeProtocol = this._options.nativeProtocols[protocol];
- if (!nativeProtocol) throw new TypeError("Unsupported protocol " + protocol);
- if (this._options.agents) {
- var scheme = protocol.slice(0, -1);
- this._options.agent = this._options.agents[scheme];
- }
- var request = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse);
- request._redirectable = this;
- for (var event of events) request.on(event, eventHandlers[event]);
- this._currentUrl = /^\//.test(this._options.path) ? url.format(this._options) : this._options.path;
- if (this._isRedirect) {
- var i$1 = 0;
- var self$1 = this;
- var buffers = this._requestBodyBuffers;
- (function writeNext(error$1) {
- // istanbul ignore else
- if (request === self$1._currentRequest) {
- // istanbul ignore if
- if (error$1) self$1.emit("error", error$1);
- else if (i$1 < buffers.length) {
- var buffer = buffers[i$1++];
- // istanbul ignore else
- if (!request.finished) request.write(buffer.data, buffer.encoding, writeNext);
- } else if (self$1._ended) request.end();
- }
- })();
- }
- };
- RedirectableRequest.prototype._processResponse = function(response) {
- var statusCode = response.statusCode;
- if (this._options.trackRedirects) this._redirects.push({
- url: this._currentUrl,
- headers: response.headers,
- statusCode
- });
- var location$1 = response.headers.location;
- if (!location$1 || this._options.followRedirects === false || statusCode < 300 || statusCode >= 400) {
- response.responseUrl = this._currentUrl;
- response.redirects = this._redirects;
- this.emit("response", response);
- this._requestBodyBuffers = [];
- return;
- }
- destroyRequest(this._currentRequest);
- response.destroy();
- if (++this._redirectCount > this._options.maxRedirects) throw new TooManyRedirectsError();
- var requestHeaders;
- var beforeRedirect = this._options.beforeRedirect;
- if (beforeRedirect) requestHeaders = Object.assign({ Host: response.req.getHeader("host") }, this._options.headers);
- var method = this._options.method;
- if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._options.method)) {
- this._options.method = "GET";
- this._requestBodyBuffers = [];
- removeMatchingHeaders(/^content-/i, this._options.headers);
- }
- var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
- var currentUrlParts = parseUrl(this._currentUrl);
- var currentHost = currentHostHeader || currentUrlParts.host;
- var currentUrl = /^\w+:/.test(location$1) ? this._currentUrl : url.format(Object.assign(currentUrlParts, { host: currentHost }));
- var redirectUrl = resolveUrl(location$1, currentUrl);
- debug$10("redirecting to", redirectUrl.href);
- this._isRedirect = true;
- spreadUrlObject(redirectUrl, this._options);
- if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== "https:" || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers);
- if (isFunction(beforeRedirect)) {
- beforeRedirect(this._options, {
- headers: response.headers,
- statusCode
- }, {
- url: currentUrl,
- method,
- headers: requestHeaders
- });
- this._sanitizeOptions(this._options);
- }
- this._performRequest();
- };
- function wrap(protocols) {
- var exports$1 = {
- maxRedirects: 21,
- maxBodyLength: 10 * 1024 * 1024
- };
- var nativeProtocols = {};
- Object.keys(protocols).forEach(function(scheme) {
- var protocol = scheme + ":";
- var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
- var wrappedProtocol = exports$1[scheme] = Object.create(nativeProtocol);
- function request(input, options$1, callback) {
- if (isURL(input)) input = spreadUrlObject(input);
- else if (isString(input)) input = spreadUrlObject(parseUrl(input));
- else {
- callback = options$1;
- options$1 = validateUrl(input);
- input = { protocol };
- }
- if (isFunction(options$1)) {
- callback = options$1;
- options$1 = null;
- }
- options$1 = Object.assign({
- maxRedirects: exports$1.maxRedirects,
- maxBodyLength: exports$1.maxBodyLength
- }, input, options$1);
- options$1.nativeProtocols = nativeProtocols;
- if (!isString(options$1.host) && !isString(options$1.hostname)) options$1.hostname = "::1";
- assert$1.equal(options$1.protocol, protocol, "protocol mismatch");
- debug$10("options", options$1);
- return new RedirectableRequest(options$1, callback);
- }
- function get$3(input, options$1, callback) {
- var wrappedRequest = wrappedProtocol.request(input, options$1, callback);
- wrappedRequest.end();
- return wrappedRequest;
- }
- Object.defineProperties(wrappedProtocol, {
- request: {
- value: request,
- configurable: true,
- enumerable: true,
- writable: true
- },
- get: {
- value: get$3,
- configurable: true,
- enumerable: true,
- writable: true
- }
- });
- });
- return exports$1;
- }
- function noop$1() {}
- function parseUrl(input) {
- var parsed;
- // istanbul ignore else
- if (useNativeURL) parsed = new URL$2(input);
- else {
- parsed = validateUrl(url.parse(input));
- if (!isString(parsed.protocol)) throw new InvalidUrlError({ input });
- }
- return parsed;
- }
- function resolveUrl(relative$3, base) {
- // istanbul ignore next
- return useNativeURL ? new URL$2(relative$3, base) : parseUrl(url.resolve(base, relative$3));
- }
- function validateUrl(input) {
- if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) throw new InvalidUrlError({ input: input.href || input });
- if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) throw new InvalidUrlError({ input: input.href || input });
- return input;
- }
- function spreadUrlObject(urlObject, target) {
- var spread = target || {};
- for (var key of preservedUrlFields) spread[key] = urlObject[key];
- if (spread.hostname.startsWith("[")) spread.hostname = spread.hostname.slice(1, -1);
- if (spread.port !== "") spread.port = Number(spread.port);
- spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;
- return spread;
- }
- function removeMatchingHeaders(regex, headers) {
- var lastValue;
- for (var header in headers) if (regex.test(header)) {
- lastValue = headers[header];
- delete headers[header];
- }
- return lastValue === null || typeof lastValue === "undefined" ? void 0 : String(lastValue).trim();
- }
- function createErrorType(code, message, baseClass) {
- function CustomError(properties) {
- // istanbul ignore else
- if (isFunction(Error.captureStackTrace)) Error.captureStackTrace(this, this.constructor);
- Object.assign(this, properties || {});
- this.code = code;
- this.message = this.cause ? message + ": " + this.cause.message : message;
- }
- CustomError.prototype = new (baseClass || Error)();
- Object.defineProperties(CustomError.prototype, {
- constructor: {
- value: CustomError,
- enumerable: false
- },
- name: {
- value: "Error [" + code + "]",
- enumerable: false
- }
- });
- return CustomError;
- }
- function destroyRequest(request, error$1) {
- for (var event of events) request.removeListener(event, eventHandlers[event]);
- request.on("error", noop$1);
- request.destroy(error$1);
- }
- function isSubdomain(subdomain, domain) {
- assert$1(isString(subdomain) && isString(domain));
- var dot = subdomain.length - domain.length - 1;
- return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
- }
- function isString(value$1) {
- return typeof value$1 === "string" || value$1 instanceof String;
- }
- function isFunction(value$1) {
- return typeof value$1 === "function";
- }
- function isBuffer(value$1) {
- return typeof value$1 === "object" && "length" in value$1;
- }
- function isURL(value$1) {
- return URL$2 && value$1 instanceof URL$2;
- }
- module.exports = wrap({
- http: http$3,
- https: https$2
- });
- module.exports.wrap = wrap;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/http-proxy-3@1.22.0_patch_hash=d89dff5a0afc2cb277080ad056a3baf7feeeeac19144878abc17f4c91ad89095_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/passes/web-incoming.js
-var require_web_incoming = /* @__PURE__ */ __commonJSMin(((exports) => {
- var __createBinding$2 = exports && exports.__createBinding || (Object.create ? (function(o$1, m, k, k2) {
- if (k2 === void 0) 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$1, k2, desc);
- }) : (function(o$1, m, k, k2) {
- if (k2 === void 0) k2 = k;
- o$1[k2] = m[k];
- }));
- var __setModuleDefault$2 = exports && exports.__setModuleDefault || (Object.create ? (function(o$1, v) {
- Object.defineProperty(o$1, "default", {
- enumerable: true,
- value: v
- });
- }) : function(o$1, v) {
- o$1["default"] = v;
- });
- var __importStar$2 = exports && exports.__importStar || (function() {
- var ownKeys = function(o$1) {
- ownKeys = Object.getOwnPropertyNames || function(o$2) {
- var ar = [];
- for (var k in o$2) if (Object.prototype.hasOwnProperty.call(o$2, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o$1);
- };
- return function(mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) {
- for (var k = ownKeys(mod), i$1 = 0; i$1 < k.length; i$1++) if (k[i$1] !== "default") __createBinding$2(result, mod, k[i$1]);
- }
- __setModuleDefault$2(result, mod);
- return result;
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.WEB_PASSES = void 0;
- exports.deleteLength = deleteLength;
- exports.timeout = timeout;
- exports.XHeaders = XHeaders$1;
- exports.stream = stream$1;
- const http$2 = __importStar$2(__require("node:http"));
- const https$1 = __importStar$2(__require("node:https"));
- const web_outgoing_1$1 = require_web_outgoing();
- const common$1 = __importStar$2(require_common());
- const followRedirects = __importStar$2(require_follow_redirects());
- const web_o$1 = Object.values(web_outgoing_1$1.OUTGOING_PASSES);
- const nativeAgents = {
- http: http$2,
- https: https$1
- };
- function deleteLength(req$4) {
- if ((req$4.method === "DELETE" || req$4.method === "OPTIONS") && !req$4.headers["content-length"]) {
- req$4.headers["content-length"] = "0";
- delete req$4.headers["transfer-encoding"];
- }
- }
- function timeout(req$4, _res, options$1) {
- if (options$1.timeout) req$4.socket.setTimeout(options$1.timeout);
- }
- function XHeaders$1(req$4, _res, options$1) {
- if (!options$1.xfwd) return;
- const encrypted = common$1.hasEncryptedConnection(req$4);
- const values = {
- for: req$4.connection.remoteAddress || req$4.socket.remoteAddress,
- port: common$1.getPort(req$4),
- proto: encrypted ? "https" : "http"
- };
- for (const header of [
- "for",
- "port",
- "proto"
- ]) req$4.headers["x-forwarded-" + header] = (req$4.headers["x-forwarded-" + header] || "") + (req$4.headers["x-forwarded-" + header] ? "," : "") + values[header];
- req$4.headers["x-forwarded-host"] = req$4.headers["x-forwarded-host"] || req$4.headers[":authority"] || req$4.headers["host"] || "";
- }
- function stream$1(req$4, res, options$1, _, server, cb) {
- server.emit("start", req$4, res, options$1.target || options$1.forward);
- const agents = options$1.followRedirects ? followRedirects : nativeAgents;
- const http$7 = agents.http;
- const https$4 = agents.https;
- if (options$1.forward) {
- const proto$2 = options$1.forward.protocol === "https:" ? https$4 : http$7;
- const outgoingOptions$1 = common$1.setupOutgoing(options$1.ssl || {}, options$1, req$4, "forward");
- const forwardReq = proto$2.request(outgoingOptions$1);
- const forwardError = createErrorHandler(forwardReq, options$1.forward);
- req$4.on("error", forwardError);
- forwardReq.on("error", forwardError);
- (options$1.buffer || req$4).pipe(forwardReq);
- if (!options$1.target) return res.end();
- }
- const proto$1 = options$1.target.protocol === "https:" ? https$4 : http$7;
- const outgoingOptions = common$1.setupOutgoing(options$1.ssl || {}, options$1, req$4);
- const proxyReq = proto$1.request(outgoingOptions);
- proxyReq.on("socket", (socket) => {
- if (server && !proxyReq.getHeader("expect")) server.emit("proxyReq", proxyReq, req$4, res, options$1, socket);
- });
- if (options$1.proxyTimeout) proxyReq.setTimeout(options$1.proxyTimeout, () => {
- proxyReq.destroy();
- });
- res.on("close", () => {
- if (!res.writableFinished) proxyReq.destroy();
- });
- const proxyError = createErrorHandler(proxyReq, options$1.target);
- req$4.on("error", proxyError);
- proxyReq.on("error", proxyError);
- function createErrorHandler(proxyReq$1, url$3) {
- return (err$2) => {
- if (req$4.socket.destroyed && err$2.code === "ECONNRESET") {
- server.emit("econnreset", err$2, req$4, res, url$3);
- proxyReq$1.destroy();
- return;
- }
- if (cb) cb(err$2, req$4, res, url$3);
- else server.emit("error", err$2, req$4, res, url$3);
- };
- }
- (options$1.buffer || req$4).pipe(proxyReq);
- proxyReq.on("response", (proxyRes) => {
- server?.emit("proxyRes", proxyRes, req$4, res);
- if (!res.headersSent && !options$1.selfHandleResponse) for (const pass of web_o$1) pass(req$4, res, proxyRes, options$1);
- if (!res.finished) {
- proxyRes.on("end", () => {
- server?.emit("end", req$4, res, proxyRes);
- });
- if (!options$1.selfHandleResponse) proxyRes.pipe(res);
- } else server?.emit("end", req$4, res, proxyRes);
- });
- }
- exports.WEB_PASSES = {
- deleteLength,
- timeout,
- XHeaders: XHeaders$1,
- stream: stream$1
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/http-proxy-3@1.22.0_patch_hash=d89dff5a0afc2cb277080ad056a3baf7feeeeac19144878abc17f4c91ad89095_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/passes/ws-incoming.js
-var require_ws_incoming = /* @__PURE__ */ __commonJSMin(((exports) => {
- var __createBinding$1 = exports && exports.__createBinding || (Object.create ? (function(o$1, m, k, k2) {
- if (k2 === void 0) 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$1, k2, desc);
- }) : (function(o$1, m, k, k2) {
- if (k2 === void 0) k2 = k;
- o$1[k2] = m[k];
- }));
- var __setModuleDefault$1 = exports && exports.__setModuleDefault || (Object.create ? (function(o$1, v) {
- Object.defineProperty(o$1, "default", {
- enumerable: true,
- value: v
- });
- }) : function(o$1, v) {
- o$1["default"] = v;
- });
- var __importStar$1 = exports && exports.__importStar || (function() {
- var ownKeys = function(o$1) {
- ownKeys = Object.getOwnPropertyNames || function(o$2) {
- var ar = [];
- for (var k in o$2) if (Object.prototype.hasOwnProperty.call(o$2, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o$1);
- };
- return function(mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) {
- for (var k = ownKeys(mod), i$1 = 0; i$1 < k.length; i$1++) if (k[i$1] !== "default") __createBinding$1(result, mod, k[i$1]);
- }
- __setModuleDefault$1(result, mod);
- return result;
- };
- })();
- var __importDefault$1 = exports && exports.__importDefault || function(mod) {
- return mod && mod.__esModule ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.WS_PASSES = void 0;
- exports.numOpenSockets = numOpenSockets;
- exports.checkMethodAndHeader = checkMethodAndHeader;
- exports.XHeaders = XHeaders;
- exports.stream = stream;
- const http$1 = __importStar$1(__require("node:http"));
- const https = __importStar$1(__require("node:https"));
- const common = __importStar$1(require_common());
- const web_outgoing_1 = require_web_outgoing();
- const log$1 = (0, __importDefault$1((init_node(), __toCommonJS(node_exports))).default)("http-proxy-3:ws-incoming");
- const web_o = Object.values(web_outgoing_1.OUTGOING_PASSES);
- function createSocketCounter(name) {
- let sockets = /* @__PURE__ */ new Set();
- return ({ add, rm } = {}) => {
- if (add) {
- if (!add.id) add.id = Math.random();
- if (!sockets.has(add.id)) sockets.add(add.id);
- }
- if (rm) {
- if (!rm.id) rm.id = Math.random();
- if (sockets.has(rm.id)) sockets.delete(rm.id);
- }
- log$1("socket counter:", { [name]: sockets.size }, add ? "add" : rm ? "rm" : "");
- return sockets.size;
- };
- }
- const socketCounter = createSocketCounter("socket");
- const proxySocketCounter = createSocketCounter("proxySocket");
- var MockResponse = class {
- constructor() {
- this.headers = {};
- this.statusCode = 200;
- this.statusMessage = "";
- }
- setHeader(key, value$1) {
- this.headers[key] = value$1;
- return this;
- }
- };
- function numOpenSockets() {
- return socketCounter() + proxySocketCounter();
- }
- function checkMethodAndHeader(req$4, socket) {
- log$1("websocket: checkMethodAndHeader");
- if (req$4.method !== "GET" || !req$4.headers.upgrade) {
- socket.destroy();
- return true;
- }
- if (req$4.headers.upgrade.toLowerCase() !== "websocket") {
- socket.destroy();
- return true;
- }
- }
- function XHeaders(req$4, _socket, options$1) {
- if (!options$1.xfwd) return;
- log$1("websocket: XHeaders");
- const values = {
- for: req$4.connection.remoteAddress || req$4.socket.remoteAddress,
- port: common.getPort(req$4),
- proto: common.hasEncryptedConnection(req$4) ? "wss" : "ws"
- };
- for (const header of [
- "for",
- "port",
- "proto"
- ]) req$4.headers["x-forwarded-" + header] = (req$4.headers["x-forwarded-" + header] || "") + (req$4.headers["x-forwarded-" + header] ? "," : "") + values[header];
- }
- function stream(req$4, socket, options$1, head, server, cb) {
- log$1("websocket: new stream");
- const proxySockets = [];
- socketCounter({ add: socket });
- const cleanUpProxySockets = () => {
- for (const p of proxySockets) p.end();
- };
- socket.on("close", () => {
- socketCounter({ rm: socket });
- cleanUpProxySockets();
- });
- socket.on("error", cleanUpProxySockets);
- const createHttpHeader = (line, headers) => {
- return Object.keys(headers).reduce((head$1, key) => {
- const value$1 = headers[key];
- if (!Array.isArray(value$1)) {
- head$1.push(key + ": " + value$1);
- return head$1;
- }
- for (let i$1 = 0; i$1 < value$1.length; i$1++) head$1.push(key + ": " + value$1[i$1]);
- return head$1;
- }, [line]).join("\r\n") + "\r\n\r\n";
- };
- common.setupSocket(socket);
- if (head && head.length) socket.unshift(head);
- const proto$1 = common.isSSL.test(options$1.target.protocol) ? https : http$1;
- const outgoingOptions = common.setupOutgoing(options$1.ssl || {}, options$1, req$4);
- const proxyReq = proto$1.request(outgoingOptions);
- if (server) server.emit("proxyReqWs", proxyReq, req$4, socket, options$1, head);
- proxyReq.on("error", onOutgoingError);
- proxyReq.on("upgrade", (proxyRes, proxySocket, proxyHead) => {
- log$1("upgrade");
- proxySocketCounter({ add: proxySocket });
- proxySockets.push(proxySocket);
- proxySocket.on("close", () => {
- proxySocketCounter({ rm: proxySocket });
- });
- proxySocket.on("error", onOutgoingError);
- proxySocket.on("end", () => {
- server.emit("close", proxyRes, proxySocket, proxyHead);
- });
- proxySocket.on("close", () => {
- socket.end();
- });
- common.setupSocket(proxySocket);
- if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead);
- socket.write(createHttpHeader("HTTP/1.1 101 Switching Protocols", proxyRes.headers));
- proxySocket.pipe(socket).pipe(proxySocket);
- server.emit("open", proxySocket);
- });
- function onOutgoingError(err$2) {
- if (cb) cb(err$2, req$4, socket);
- else server.emit("error", err$2, req$4, socket);
- socket.destroySoon();
- }
- proxyReq.on("response", (proxyRes) => {
- log$1("got non-ws HTTP response", {
- statusCode: proxyRes.statusCode,
- statusMessage: proxyRes.statusMessage
- });
- const res = new MockResponse();
- for (const pass of web_o) pass(req$4, res, proxyRes, options$1);
- let writeChunk = (chunk) => {
- socket.write(chunk);
- };
- if (req$4.httpVersion === "1.1" && proxyRes.headers["content-length"] === void 0) {
- res.headers["transfer-encoding"] = "chunked";
- writeChunk = (chunk) => {
- socket.write(chunk.length.toString(16));
- socket.write("\r\n");
- socket.write(chunk);
- socket.write("\r\n");
- };
- }
- const proxyHead = createHttpHeader(`HTTP/${req$4.httpVersion} ${proxyRes.statusCode} ${proxyRes.statusMessage}`, res.headers);
- if (!socket.destroyed) {
- socket.write(proxyHead);
- proxyRes.on("data", (chunk) => {
- writeChunk(chunk);
- });
- proxyRes.on("end", () => {
- writeChunk("");
- socket.destroySoon();
- });
- } else proxyRes.resume();
- });
- proxyReq.end();
- }
- exports.WS_PASSES = {
- checkMethodAndHeader,
- XHeaders,
- stream
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/http-proxy-3@1.22.0_patch_hash=d89dff5a0afc2cb277080ad056a3baf7feeeeac19144878abc17f4c91ad89095_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/index.js
-var require_http_proxy = /* @__PURE__ */ __commonJSMin(((exports) => {
- var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o$1, m, k, k2) {
- if (k2 === void 0) 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$1, k2, desc);
- }) : (function(o$1, m, k, k2) {
- if (k2 === void 0) k2 = k;
- o$1[k2] = m[k];
- }));
- var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o$1, v) {
- Object.defineProperty(o$1, "default", {
- enumerable: true,
- value: v
- });
- }) : function(o$1, v) {
- o$1["default"] = v;
- });
- var __importStar = exports && exports.__importStar || (function() {
- var ownKeys = function(o$1) {
- ownKeys = Object.getOwnPropertyNames || function(o$2) {
- var ar = [];
- for (var k in o$2) if (Object.prototype.hasOwnProperty.call(o$2, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o$1);
- };
- return function(mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) {
- for (var k = ownKeys(mod), i$1 = 0; i$1 < k.length; i$1++) if (k[i$1] !== "default") __createBinding(result, mod, k[i$1]);
- }
- __setModuleDefault(result, mod);
- return result;
- };
- })();
- var __importDefault = exports && exports.__importDefault || function(mod) {
- return mod && mod.__esModule ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ProxyServer = void 0;
- const http = __importStar(__require("node:http"));
- const http2 = __importStar(__require("node:http2"));
- const web_incoming_1 = require_web_incoming();
- const ws_incoming_1$1 = require_ws_incoming();
- const node_events_1 = __require("node:events");
- const debug_1 = __importDefault((init_node(), __toCommonJS(node_exports)));
- const common_1 = require_common();
- const log = (0, debug_1.default)("http-proxy-3");
- var ProxyServer = class ProxyServer extends node_events_1.EventEmitter {
- /**
- * Creates the proxy server with specified options.
- * @param options - Config object passed to the proxy
- */
- constructor(options$1 = {}) {
- super();
- this.createRightProxy = (type) => {
- log("createRightProxy", { type });
- return (options$2) => {
- return (...args) => {
- const req$4 = args[0];
- log("proxy: ", {
- type,
- path: req$4.url
- });
- const res = args[1];
- const passes = type === "ws" ? this.wsPasses : this.webPasses;
- if (type == "ws") res.on("error", (err$2) => {
- this.emit("error", err$2, req$4, res);
- });
- let counter = args.length - 1;
- let head;
- let cb;
- if (typeof args[counter] === "function") {
- cb = args[counter];
- counter--;
- }
- let requestOptions;
- if (!(args[counter] instanceof Buffer) && args[counter] !== res) {
- requestOptions = {
- ...options$2,
- ...args[counter]
- };
- counter--;
- } else requestOptions = { ...options$2 };
- if (args[counter] instanceof Buffer) head = args[counter];
- for (const e$1 of ["target", "forward"]) if (typeof requestOptions[e$1] === "string") requestOptions[e$1] = (0, common_1.toURL)(requestOptions[e$1]);
- if (!requestOptions.target && !requestOptions.forward) {
- this.emit("error", /* @__PURE__ */ new Error("Must set target or forward"), req$4, res);
- return;
- }
- for (const pass of passes)
- /**
- * Call of passes functions
- * pass(req, res, options, head)
- *
- * In WebSockets case, the `res` variable
- * refer to the connection socket
- * pass(req, socket, options, head)
- */
- if (pass(req$4, res, requestOptions, head, this, cb)) break;
- };
- };
- };
- this.onError = (err$2) => {
- if (this.listeners("error").length === 1) throw err$2;
- };
- /**
- * A function that wraps the object in a webserver, for your convenience
- * @param port - Port to listen on
- * @param hostname - The hostname to listen on
- */
- this.listen = (port, hostname) => {
- log("listen", {
- port,
- hostname
- });
- const requestListener = (req$4, res) => {
- this.web(req$4, res);
- };
- this._server = this.options.ssl ? http2.createSecureServer({
- ...this.options.ssl,
- allowHTTP1: true
- }, requestListener) : http.createServer(requestListener);
- if (this.options.ws) this._server.on("upgrade", (req$4, socket, head) => {
- this.ws(req$4, socket, head);
- });
- this._server.listen(port, hostname);
- return this;
- };
- this.address = () => {
- return this._server?.address();
- };
- /**
- * A function that closes the inner webserver and stops listening on given port
- */
- this.close = (cb) => {
- if (this._server == null) {
- cb?.();
- return;
- }
- this._server.close((err$2) => {
- this._server = null;
- cb?.(err$2);
- });
- };
- this.before = (type, passName, cb) => {
- if (type !== "ws" && type !== "web") throw new Error("type must be `web` or `ws`");
- const passes = type === "ws" ? this.wsPasses : this.webPasses;
- let i$1 = false;
- passes.forEach((v, idx) => {
- if (v.name === passName) i$1 = idx;
- });
- if (i$1 === false) throw new Error("No such pass");
- passes.splice(i$1, 0, cb);
- };
- this.after = (type, passName, cb) => {
- if (type !== "ws" && type !== "web") throw new Error("type must be `web` or `ws`");
- const passes = type === "ws" ? this.wsPasses : this.webPasses;
- let i$1 = false;
- passes.forEach((v, idx) => {
- if (v.name === passName) i$1 = idx;
- });
- if (i$1 === false) throw new Error("No such pass");
- passes.splice(i$1++, 0, cb);
- };
- log("creating a ProxyServer", options$1);
- options$1.prependPath = options$1.prependPath === false ? false : true;
- this.options = options$1;
- this.web = this.createRightProxy("web")(options$1);
- this.ws = this.createRightProxy("ws")(options$1);
- this.webPasses = Object.values(web_incoming_1.WEB_PASSES);
- this.wsPasses = Object.values(ws_incoming_1$1.WS_PASSES);
- this.on("error", this.onError);
- }
- /**
- * Creates the proxy server with specified options.
- * @param options Config object passed to the proxy
- * @returns Proxy object with handlers for `ws` and `web` requests
- */
- static createProxyServer(options$1) {
- return new ProxyServer(options$1);
- }
- /**
- * Creates the proxy server with specified options.
- * @param options Config object passed to the proxy
- * @returns Proxy object with handlers for `ws` and `web` requests
- */
- static createServer(options$1) {
- return new ProxyServer(options$1);
- }
- /**
- * Creates the proxy server with specified options.
- * @param options Config object passed to the proxy
- * @returns Proxy object with handlers for `ws` and `web` requests
- */
- static createProxy(options$1) {
- return new ProxyServer(options$1);
- }
- };
- exports.ProxyServer = ProxyServer;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/http-proxy-3@1.22.0_patch_hash=d89dff5a0afc2cb277080ad056a3baf7feeeeac19144878abc17f4c91ad89095_ms@2.1.3/node_modules/http-proxy-3/dist/lib/index.js
-var require_lib = /* @__PURE__ */ __commonJSMin(((exports) => {
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.numOpenSockets = exports.ProxyServer = void 0;
- exports.createProxyServer = createProxyServer;
- const index_1 = require_http_proxy();
- Object.defineProperty(exports, "ProxyServer", {
- enumerable: true,
- get: function() {
- return index_1.ProxyServer;
- }
- });
- var ws_incoming_1 = require_ws_incoming();
- Object.defineProperty(exports, "numOpenSockets", {
- enumerable: true,
- get: function() {
- return ws_incoming_1.numOpenSockets;
- }
- });
- /**
- * Creates the proxy server.
- *
- * Examples:
- *
- * httpProxy.createProxyServer({ .. }, 8000)
- * // => '{ web: [Function], ws: [Function] ... }'
- *
- * @param {Object} Options Config object passed to the proxy
- *
- * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests
- *
- * @api public
- */
- function createProxyServer(options$1 = {}) {
- return new index_1.ProxyServer(options$1);
- }
-}));
-
-//#endregion
-//#region src/node/server/middlewares/proxy.ts
-var import_lib$2 = /* @__PURE__ */ __toESM(require_lib(), 1);
-var import_picocolors$20 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const debug$9 = createDebugger("vite:proxy");
-const rewriteOriginHeader = (proxyReq, options$1, config$2) => {
- if (options$1.rewriteWsOrigin) {
- const { target } = options$1;
- if (proxyReq.headersSent) {
- config$2.logger.warn(import_picocolors$20.default.yellow(`Unable to rewrite Origin header as headers are already sent.`));
- return;
- }
- if (proxyReq.getHeader("origin") && target) {
- const changedOrigin = typeof target === "object" ? `${target.protocol ?? "http:"}//${target.host}` : target;
- proxyReq.setHeader("origin", changedOrigin);
- }
- }
-};
-function proxyMiddleware(httpServer, options$1, config$2) {
- const proxies = {};
- Object.keys(options$1).forEach((context) => {
- let opts = options$1[context];
- if (!opts) return;
- if (typeof opts === "string") opts = {
- target: opts,
- changeOrigin: true
- };
- const proxy = import_lib$2.createProxyServer(opts);
- if (opts.configure) opts.configure(proxy, opts);
- proxy.on("error", (err$2, _req, res) => {
- if ("req" in res) {
- config$2.logger.error(`${import_picocolors$20.default.red(`http proxy error: ${res.req.url}`)}\n${err$2.stack}`, {
- timestamp: true,
- error: err$2
- });
- if (!res.headersSent && !res.writableEnded) res.writeHead(500, { "Content-Type": "text/plain" }).end();
- } else {
- config$2.logger.error(`${import_picocolors$20.default.red(`ws proxy error:`)}\n${err$2.stack}`, {
- timestamp: true,
- error: err$2
- });
- res.end();
- }
- });
- proxy.on("proxyReqWs", (proxyReq, _req, socket, options$2) => {
- rewriteOriginHeader(proxyReq, options$2, config$2);
- socket.on("error", (err$2) => {
- config$2.logger.error(`${import_picocolors$20.default.red(`ws proxy socket error:`)}\n${err$2.stack}`, {
- timestamp: true,
- error: err$2
- });
- });
- });
- proxies[context] = [proxy, { ...opts }];
- });
- if (httpServer) httpServer.on("upgrade", async (req$4, socket, head) => {
- const url$3 = req$4.url;
- for (const context in proxies) if (doesProxyContextMatchUrl(context, url$3)) {
- const [proxy, opts] = proxies[context];
- if (opts.ws || opts.target?.toString().startsWith("ws:") || opts.target?.toString().startsWith("wss:")) {
- if (opts.bypass) try {
- const bypassResult = await opts.bypass(req$4, void 0, opts);
- if (typeof bypassResult === "string") {
- debug$9?.(`bypass: ${req$4.url} -> ${bypassResult}`);
- req$4.url = bypassResult;
- return;
- }
- if (bypassResult === false) {
- debug$9?.(`bypass: ${req$4.url} -> 404`);
- socket.end("HTTP/1.1 404 Not Found\r\n\r\n", "");
- return;
- }
- } catch (err$2) {
- config$2.logger.error(`${import_picocolors$20.default.red(`ws proxy bypass error:`)}\n${err$2.stack}`, {
- timestamp: true,
- error: err$2
- });
- return;
- }
- if (opts.rewrite) req$4.url = opts.rewrite(url$3);
- debug$9?.(`${req$4.url} -> ws ${opts.target}`);
- proxy.ws(req$4, socket, head);
- return;
- }
- }
- });
- return async function viteProxyMiddleware(req$4, res, next) {
- const url$3 = req$4.url;
- for (const context in proxies) if (doesProxyContextMatchUrl(context, url$3)) {
- const [proxy, opts] = proxies[context];
- const options$2 = {};
- if (opts.bypass) try {
- const bypassResult = await opts.bypass(req$4, res, opts);
- if (typeof bypassResult === "string") {
- debug$9?.(`bypass: ${req$4.url} -> ${bypassResult}`);
- req$4.url = bypassResult;
- if (res.writableEnded) return;
- return next();
- }
- if (bypassResult === false) {
- debug$9?.(`bypass: ${req$4.url} -> 404`);
- res.statusCode = 404;
- return res.end();
- }
- } catch (e$1) {
- debug$9?.(`bypass: ${req$4.url} -> ${e$1}`);
- return next(e$1);
- }
- debug$9?.(`${req$4.url} -> ${opts.target || opts.forward}`);
- if (opts.rewrite) req$4.url = opts.rewrite(req$4.url);
- proxy.web(req$4, res, options$2);
- return;
- }
- next();
- };
-}
-function doesProxyContextMatchUrl(context, url$3) {
- return context[0] === "^" && new RegExp(context).test(url$3) || url$3.startsWith(context);
-}
-
-//#endregion
-//#region src/node/server/middlewares/htmlFallback.ts
-const debug$8 = createDebugger("vite:html-fallback");
-function htmlFallbackMiddleware(root, spaFallback) {
- return function viteHtmlFallbackMiddleware(req$4, _res, next) {
- if (req$4.method !== "GET" && req$4.method !== "HEAD" || req$4.url === "/favicon.ico" || !(req$4.headers.accept === void 0 || req$4.headers.accept === "" || req$4.headers.accept.includes("text/html") || req$4.headers.accept.includes("*/*"))) return next();
- const url$3 = cleanUrl(req$4.url);
- let pathname;
- try {
- pathname = decodeURIComponent(url$3);
- } catch {
- return next();
- }
- if (pathname.endsWith(".html")) {
- const filePath = path.join(root, pathname);
- if (fs.existsSync(filePath)) {
- debug$8?.(`Rewriting ${req$4.method} ${req$4.url} to ${url$3}`);
- req$4.url = url$3;
- return next();
- }
- } else if (pathname.endsWith("/")) {
- const filePath = path.join(root, pathname, "index.html");
- if (fs.existsSync(filePath)) {
- const newUrl = url$3 + "index.html";
- debug$8?.(`Rewriting ${req$4.method} ${req$4.url} to ${newUrl}`);
- req$4.url = newUrl;
- return next();
- }
- } else {
- const filePath = path.join(root, pathname + ".html");
- if (fs.existsSync(filePath)) {
- const newUrl = url$3 + ".html";
- debug$8?.(`Rewriting ${req$4.method} ${req$4.url} to ${newUrl}`);
- req$4.url = newUrl;
- return next();
- }
- }
- if (spaFallback) {
- debug$8?.(`Rewriting ${req$4.method} ${req$4.url} to /index.html`);
- req$4.url = "/index.html";
- }
- next();
- };
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js
-/*!
-* etag
-* Copyright(c) 2014-2016 Douglas Christopher Wilson
-* MIT Licensed
-*/
-var require_etag = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- /**
- * Module exports.
- * @public
- */
- module.exports = etag;
- /**
- * Module dependencies.
- * @private
- */
- var crypto$1 = __require("crypto");
- var Stats = __require("fs").Stats;
- /**
- * Module variables.
- * @private
- */
- var toString = Object.prototype.toString;
- /**
- * Generate an entity tag.
- *
- * @param {Buffer|string} entity
- * @return {string}
- * @private
- */
- function entitytag(entity) {
- if (entity.length === 0) return "\"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk\"";
- var hash$1 = crypto$1.createHash("sha1").update(entity, "utf8").digest("base64").substring(0, 27);
- return "\"" + (typeof entity === "string" ? Buffer.byteLength(entity, "utf8") : entity.length).toString(16) + "-" + hash$1 + "\"";
- }
- /**
- * Create a simple ETag.
- *
- * @param {string|Buffer|Stats} entity
- * @param {object} [options]
- * @param {boolean} [options.weak]
- * @return {String}
- * @public
- */
- function etag(entity, options$1) {
- if (entity == null) throw new TypeError("argument entity is required");
- var isStats = isstats(entity);
- var weak = options$1 && typeof options$1.weak === "boolean" ? options$1.weak : isStats;
- if (!isStats && typeof entity !== "string" && !Buffer.isBuffer(entity)) throw new TypeError("argument entity must be string, Buffer, or fs.Stats");
- var tag = isStats ? stattag(entity) : entitytag(entity);
- return weak ? "W/" + tag : tag;
- }
- /**
- * Determine if object is a Stats object.
- *
- * @param {object} obj
- * @return {boolean}
- * @api private
- */
- function isstats(obj) {
- if (typeof Stats === "function" && obj instanceof Stats) return true;
- return obj && typeof obj === "object" && "ctime" in obj && toString.call(obj.ctime) === "[object Date]" && "mtime" in obj && toString.call(obj.mtime) === "[object Date]" && "ino" in obj && typeof obj.ino === "number" && "size" in obj && typeof obj.size === "number";
- }
- /**
- * Generate a tag for a stat.
- *
- * @param {object} stat
- * @return {string}
- * @private
- */
- function stattag(stat$4) {
- var mtime = stat$4.mtime.getTime().toString(16);
- return "\"" + stat$4.size.toString(16) + "-" + mtime + "\"";
- }
-}));
-
-//#endregion
-//#region src/node/server/send.ts
-var import_convert_source_map$1 = /* @__PURE__ */ __toESM(require_convert_source_map(), 1);
-var import_etag$1 = /* @__PURE__ */ __toESM(require_etag(), 1);
-const debug$7 = createDebugger("vite:send", { onlyWhenFocused: true });
-const alias$1 = {
- js: "text/javascript",
- css: "text/css",
- html: "text/html",
- json: "application/json"
-};
-function send(req$4, res, content, type, options$1) {
- const { etag: etag$1 = (0, import_etag$1.default)(content, { weak: true }), cacheControl = "no-cache", headers, map: map$1 } = options$1;
- if (res.writableEnded) return;
- if (req$4.headers["if-none-match"] === etag$1) {
- res.statusCode = 304;
- res.end();
- return;
- }
- res.setHeader("Content-Type", alias$1[type] || type);
- res.setHeader("Cache-Control", cacheControl);
- res.setHeader("Etag", etag$1);
- if (headers) for (const name in headers) res.setHeader(name, headers[name]);
- if (map$1 && "version" in map$1 && map$1.mappings) {
- if (type === "js" || type === "css") content = getCodeWithSourcemap(type, content.toString(), map$1);
- } else if (type === "js" && (!map$1 || map$1.mappings !== "")) {
- const code = content.toString();
- if (import_convert_source_map$1.default.mapFileCommentRegex.test(code)) debug$7?.(`Skipped injecting fallback sourcemap for ${req$4.url}`);
- else {
- const urlWithoutTimestamp = removeTimestampQuery(req$4.url);
- content = getCodeWithSourcemap(type, code, new MagicString(code).generateMap({
- source: path.basename(urlWithoutTimestamp),
- hires: "boundary",
- includeContent: true
- }));
- }
- }
- res.statusCode = 200;
- if (req$4.method === "HEAD") res.end();
- else res.end(content);
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/totalist@3.0.1/node_modules/totalist/sync/index.mjs
-function totalist(dir, callback, pre = "") {
- dir = resolve$1(".", dir);
- let arr = readdirSync(dir);
- let i$1 = 0, abs, stats;
- for (; i$1 < arr.length; i$1++) {
- abs = join$1(dir, arr[i$1]);
- stats = statSync(abs);
- stats.isDirectory() ? totalist(abs, callback, join$1(pre, arr[i$1])) : callback(join$1(pre, arr[i$1]), abs, stats);
- }
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/@polka+url@1.0.0-next.28/node_modules/@polka/url/build.mjs
-/**
-* @typedef ParsedURL
-* @type {import('.').ParsedURL}
-*/
-/**
-* @typedef Request
-* @property {string} url
-* @property {ParsedURL} _parsedUrl
-*/
-/**
-* @param {Request} req
-* @returns {ParsedURL|void}
-*/
-function parse$1(req$4) {
- let raw = req$4.url;
- if (raw == null) return;
- let prev = req$4._parsedUrl;
- if (prev && prev.raw === raw) return prev;
- let pathname = raw, search = "", query;
- if (raw.length > 1) {
- let idx = raw.indexOf("?", 1);
- if (idx !== -1) {
- search = raw.substring(idx);
- pathname = raw.substring(0, idx);
- if (search.length > 1) query = qs.parse(search.substring(1));
- }
- }
- return req$4._parsedUrl = {
- pathname,
- search,
- query,
- raw
- };
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/sirv@3.0.2_patch_hash=c07c56eb72faea34341d465cde2314e89db472106ed378181e3447893af6bf95/node_modules/sirv/build.mjs
-const noop = () => {};
-function isMatch(uri, arr) {
- for (let i$1 = 0; i$1 < arr.length; i$1++) if (arr[i$1].test(uri)) return true;
-}
-function toAssume(uri, extns) {
- let i$1 = 0, x, len = uri.length - 1;
- if (uri.charCodeAt(len) === 47) uri = uri.substring(0, len);
- let arr = [], tmp = `${uri}/index`;
- for (; i$1 < extns.length; i$1++) {
- x = extns[i$1] ? `.${extns[i$1]}` : "";
- if (uri) arr.push(uri + x);
- arr.push(tmp + x);
- }
- return arr;
-}
-function viaCache(cache$1, uri, extns) {
- let i$1 = 0, data, arr = toAssume(uri, extns);
- for (; i$1 < arr.length; i$1++) if (data = cache$1[arr[i$1]]) return data;
-}
-function viaLocal(dir, isEtag, uri, extns, shouldServe) {
- let i$1 = 0, arr = toAssume(uri, extns);
- let abs, stats, name, headers;
- for (; i$1 < arr.length; i$1++) {
- abs = normalize(join(dir, name = arr[i$1]));
- if (abs.startsWith(dir) && fs$1.existsSync(abs)) {
- stats = fs$1.statSync(abs);
- if (stats.isDirectory()) continue;
- if (shouldServe && !shouldServe(abs)) continue;
- headers = toHeaders(name, stats, isEtag);
- headers["Cache-Control"] = isEtag ? "no-cache" : "no-store";
- return {
- abs,
- stats,
- headers
- };
- }
- }
-}
-function is404(req$4, res) {
- return res.statusCode = 404, res.end();
-}
-function send$1(req$4, res, file, stats, headers) {
- let code = 200, tmp, opts = {};
- headers = { ...headers };
- for (let key in headers) {
- tmp = res.getHeader(key);
- if (tmp) headers[key] = tmp;
- }
- if (tmp = res.getHeader("content-type")) headers["Content-Type"] = tmp;
- if (req$4.headers.range) {
- code = 206;
- let [x, y] = req$4.headers.range.replace("bytes=", "").split("-");
- let end = opts.end = parseInt(y, 10) || stats.size - 1;
- let start = opts.start = parseInt(x, 10) || 0;
- if (end >= stats.size) end = stats.size - 1;
- if (start >= stats.size) {
- res.setHeader("Content-Range", `bytes */${stats.size}`);
- res.statusCode = 416;
- return res.end();
- }
- headers["Content-Range"] = `bytes ${start}-${end}/${stats.size}`;
- headers["Content-Length"] = end - start + 1;
- headers["Accept-Ranges"] = "bytes";
- }
- res.writeHead(code, headers);
- fs$1.createReadStream(file, opts).pipe(res);
-}
-const ENCODING = {
- ".br": "br",
- ".gz": "gzip"
-};
-function toHeaders(name, stats, isEtag) {
- let enc = ENCODING[name.slice(-3)];
- let ctype = lookup(name.slice(0, enc && -3)) || "";
- if (ctype === "text/html") ctype += ";charset=utf-8";
- let headers = {
- "Content-Length": stats.size,
- "Content-Type": ctype,
- "Last-Modified": stats.mtime.toUTCString()
- };
- if (enc) headers["Content-Encoding"] = enc;
- if (isEtag) headers["ETag"] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
- return headers;
-}
-function build_default(dir, opts = {}) {
- dir = resolve(dir || ".");
- let isNotFound = opts.onNoMatch || is404;
- let setHeaders$1 = opts.setHeaders || noop;
- let extensions$1 = opts.extensions || ["html", "htm"];
- let gzips = opts.gzip && extensions$1.map((x) => `${x}.gz`).concat("gz");
- let brots = opts.brotli && extensions$1.map((x) => `${x}.br`).concat("br");
- const FILES = {};
- let fallback = "/";
- let isEtag = !!opts.etag;
- let isSPA = !!opts.single;
- if (typeof opts.single === "string") {
- let idx = opts.single.lastIndexOf(".");
- fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
- }
- let ignores = [];
- if (opts.ignores !== false) {
- ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/);
- if (opts.dotfiles) ignores.push(/\/\.\w/);
- else ignores.push(/\/\.well-known/);
- [].concat(opts.ignores || []).forEach((x) => {
- ignores.push(new RegExp(x, "i"));
- });
- }
- let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
- if (cc && opts.immutable) cc += ",immutable";
- else if (cc && opts.maxAge === 0) cc += ",must-revalidate";
- if (!opts.dev) totalist(dir, (name, abs, stats) => {
- if (/\.well-known[\\+\/]/.test(name)) {} else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
- let headers = toHeaders(name, stats, isEtag);
- if (cc) headers["Cache-Control"] = cc;
- FILES["/" + name.normalize().replace(/\\+/g, "/")] = {
- abs,
- stats,
- headers
- };
- });
- let lookup$1 = opts.dev ? viaLocal.bind(0, dir.endsWith(sep) ? dir : dir + sep, isEtag) : viaCache.bind(0, FILES);
- return function(req$4, res, next) {
- let extns = [""];
- let pathname = parse$1(req$4).pathname;
- let val = req$4.headers["accept-encoding"] || "";
- if (gzips && val.includes("gzip")) extns.unshift(...gzips);
- if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
- extns.push(...extensions$1);
- if (pathname.indexOf("%") !== -1) try {
- pathname = decodeURI(pathname);
- } catch (err$2) {}
- let data = lookup$1(pathname, extns, opts.shouldServe) || isSPA && !isMatch(pathname, ignores) && lookup$1(fallback, extns, opts.shouldServe);
- if (!data) return next ? next() : isNotFound(req$4, res);
- if (isEtag && req$4.headers["if-none-match"] === data.headers["ETag"]) {
- res.writeHead(304);
- return res.end();
- }
- if (gzips || brots) res.setHeader("Vary", "Accept-Encoding");
- setHeaders$1(res, pathname, data.stats);
- send$1(req$4, res, data.abs, data.stats, data.headers);
- };
-}
-
-//#endregion
-//#region src/node/server/middlewares/static.ts
-var import_escape_html$1 = /* @__PURE__ */ __toESM(require_escape_html(), 1);
-const knownJavascriptExtensionRE = /\.(?:[tj]sx?|[cm][tj]s)$/;
-const ERR_DENIED_FILE = "ERR_DENIED_FILE";
-const sirvOptions = ({ config: config$2, getHeaders, disableFsServeCheck }) => {
- return {
- dev: true,
- etag: true,
- extensions: [],
- setHeaders(res, pathname) {
- if (knownJavascriptExtensionRE.test(pathname)) res.setHeader("Content-Type", "text/javascript");
- const headers = getHeaders();
- if (headers) for (const name in headers) res.setHeader(name, headers[name]);
- },
- shouldServe: disableFsServeCheck ? void 0 : (filePath) => {
- const servingAccessResult = checkLoadingAccess(config$2, filePath);
- if (servingAccessResult === "denied") {
- const error$1 = /* @__PURE__ */ new Error("denied access");
- error$1.code = ERR_DENIED_FILE;
- error$1.path = filePath;
- throw error$1;
- }
- if (servingAccessResult === "fallback") return false;
- return true;
- }
- };
-};
-function servePublicMiddleware(server, publicFiles) {
- const dir = server.config.publicDir;
- const serve = build_default(dir, sirvOptions({
- config: server.config,
- getHeaders: () => server.config.server.headers,
- disableFsServeCheck: true
- }));
- const toFilePath = (url$3) => {
- let filePath = cleanUrl(url$3);
- if (filePath.indexOf("%") !== -1) try {
- filePath = decodeURI(filePath);
- } catch {}
- return normalizePath(filePath);
- };
- return function viteServePublicMiddleware(req$4, res, next) {
- if (publicFiles && !publicFiles.has(toFilePath(req$4.url)) || isImportRequest(req$4.url) || isInternalRequest(req$4.url) || urlRE.test(req$4.url)) return next();
- serve(req$4, res, next);
- };
-}
-function serveStaticMiddleware(server) {
- const dir = server.config.root;
- const serve = build_default(dir, sirvOptions({
- config: server.config,
- getHeaders: () => server.config.server.headers
- }));
- return function viteServeStaticMiddleware(req$4, res, next) {
- const cleanedUrl = cleanUrl(req$4.url);
- if (cleanedUrl.endsWith("/") || path.extname(cleanedUrl) === ".html" || isInternalRequest(req$4.url) || req$4.url?.startsWith("//")) return next();
- const url$3 = new URL(req$4.url, "http://example.com");
- const pathname = decodeURIIfPossible(url$3.pathname);
- if (pathname === void 0) return next();
- let redirectedPathname;
- for (const { find: find$1, replacement } of server.config.resolve.alias) if (typeof find$1 === "string" ? pathname.startsWith(find$1) : find$1.test(pathname)) {
- redirectedPathname = pathname.replace(find$1, replacement);
- break;
- }
- if (redirectedPathname) {
- if (redirectedPathname.startsWith(withTrailingSlash(dir))) redirectedPathname = redirectedPathname.slice(dir.length);
- }
- const resolvedPathname = redirectedPathname || pathname;
- let fileUrl = path.resolve(dir, removeLeadingSlash(resolvedPathname));
- if (resolvedPathname.endsWith("/") && fileUrl[fileUrl.length - 1] !== "/") fileUrl = withTrailingSlash(fileUrl);
- if (redirectedPathname) {
- url$3.pathname = encodeURI(redirectedPathname);
- req$4.url = url$3.href.slice(url$3.origin.length);
- }
- try {
- serve(req$4, res, next);
- } catch (e$1) {
- if (e$1 && "code" in e$1 && e$1.code === ERR_DENIED_FILE) {
- respondWithAccessDenied(e$1.path, server, res);
- return;
- }
- throw e$1;
- }
- };
-}
-function serveRawFsMiddleware(server) {
- const serveFromRoot = build_default("/", sirvOptions({
- config: server.config,
- getHeaders: () => server.config.server.headers
- }));
- return function viteServeRawFsMiddleware(req$4, res, next) {
- if (req$4.url.startsWith(FS_PREFIX)) {
- const url$3 = new URL(req$4.url, "http://example.com");
- const pathname = decodeURIIfPossible(url$3.pathname);
- if (pathname === void 0) return next();
- let newPathname = pathname.slice(FS_PREFIX.length);
- if (isWindows) newPathname = newPathname.replace(/^[A-Z]:/i, "");
- url$3.pathname = encodeURI(newPathname);
- req$4.url = url$3.href.slice(url$3.origin.length);
- try {
- serveFromRoot(req$4, res, next);
- } catch (e$1) {
- if (e$1 && "code" in e$1 && e$1.code === ERR_DENIED_FILE) {
- respondWithAccessDenied(e$1.path, server, res);
- return;
- }
- throw e$1;
- }
- } else next();
- };
-}
-function isFileServingAllowed(configOrUrl, urlOrServer) {
- const config$2 = typeof urlOrServer === "string" ? configOrUrl : urlOrServer.config;
- const url$3 = typeof urlOrServer === "string" ? urlOrServer : configOrUrl;
- if (!config$2.server.fs.strict) return true;
- return isFileLoadingAllowed(config$2, fsPathFromUrl(url$3));
-}
-/**
-* Warning: parameters are not validated, only works with normalized absolute paths
-*
-* @param targetPath - normalized absolute path
-* @param filePath - normalized absolute path
-*/
-function isFileInTargetPath(targetPath, filePath) {
- return isSameFilePath(targetPath, filePath) || isParentDirectory(targetPath, filePath);
-}
-/**
-* Warning: parameters are not validated, only works with normalized absolute paths
-*/
-function isFileLoadingAllowed(config$2, filePath) {
- const { fs: fs$12 } = config$2.server;
- if (!fs$12.strict) return true;
- const filePathWithoutTrailingSlash = filePath.endsWith("/") ? filePath.slice(0, -1) : filePath;
- if (config$2.fsDenyGlob(filePathWithoutTrailingSlash)) return false;
- if (config$2.safeModulePaths.has(filePath)) return true;
- if (fs$12.allow.some((uri) => isFileInTargetPath(uri, filePath))) return true;
- return false;
-}
-function checkLoadingAccess(config$2, path$13) {
- if (isFileLoadingAllowed(config$2, slash(path$13))) return "allowed";
- if (isFileReadable(path$13)) return "denied";
- return "fallback";
-}
-function respondWithAccessDenied(id, server, res) {
- const urlMessage = `The request id "${id}" is outside of Vite serving allow list.`;
- const hintMessage = `
-${server.config.server.fs.allow.map((i$1) => `- ${i$1}`).join("\n")}
-
-Refer to docs https://vite.dev/config/server-options.html#server-fs-allow for configurations and more details.`;
- server.config.logger.error(urlMessage);
- server.config.logger.warnOnce(hintMessage + "\n");
- res.statusCode = 403;
- res.write(renderRestrictedErrorHTML(urlMessage + "\n" + hintMessage));
- res.end();
-}
-function renderRestrictedErrorHTML(msg) {
- return String.raw`
- <body>
- <h1>403 Restricted</h1>
- <p>${(0, import_escape_html$1.default)(msg).replace(/\n/g, "<br/>")}</p>
- <style>
- body {
- padding: 1em 2em;
- }
- </style>
- </body>
- `;
-}
-
-//#endregion
-//#region src/node/server/transformRequest.ts
-var import_etag = /* @__PURE__ */ __toESM(require_etag(), 1);
-var import_picocolors$19 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const ERR_LOAD_URL = "ERR_LOAD_URL";
-const ERR_LOAD_PUBLIC_URL = "ERR_LOAD_PUBLIC_URL";
-const ERR_DENIED_ID = "ERR_DENIED_ID";
-const debugLoad = createDebugger("vite:load");
-const debugTransform = createDebugger("vite:transform");
-const debugCache$1 = createDebugger("vite:cache");
-function transformRequest(environment, url$3, options$1 = {}) {
- if (environment._closing && environment.config.dev.recoverable) throwClosedServerError();
- const timestamp = monotonicDateNow();
- url$3 = removeTimestampQuery(url$3);
- const pending = environment._pendingRequests.get(url$3);
- if (pending) return environment.moduleGraph.getModuleByUrl(url$3).then((module$1) => {
- if (!module$1 || pending.timestamp > module$1.lastInvalidationTimestamp) return pending.request;
- else {
- pending.abort();
- return transformRequest(environment, url$3, options$1);
- }
- });
- const request = doTransform(environment, url$3, options$1, timestamp);
- let cleared = false;
- const clearCache = () => {
- if (!cleared) {
- environment._pendingRequests.delete(url$3);
- cleared = true;
- }
- };
- environment._pendingRequests.set(url$3, {
- request,
- timestamp,
- abort: clearCache
- });
- return request.finally(clearCache);
-}
-async function doTransform(environment, url$3, options$1, timestamp) {
- const { pluginContainer } = environment;
- let module$1 = await environment.moduleGraph.getModuleByUrl(url$3);
- if (module$1) {
- const cached = await getCachedTransformResult(environment, url$3, module$1, timestamp);
- if (cached) return cached;
- }
- const resolved = module$1 ? void 0 : await pluginContainer.resolveId(url$3, void 0) ?? void 0;
- const id = module$1?.id ?? resolved?.id ?? url$3;
- module$1 ??= environment.moduleGraph.getModuleById(id);
- if (module$1) {
- await environment.moduleGraph._ensureEntryFromUrl(url$3, void 0, resolved);
- const cached = await getCachedTransformResult(environment, url$3, module$1, timestamp);
- if (cached) return cached;
- }
- const result = loadAndTransform(environment, id, url$3, options$1, timestamp, module$1, resolved);
- const { depsOptimizer } = environment;
- if (!depsOptimizer?.isOptimizedDepFile(id)) environment._registerRequestProcessing(id, () => result);
- return result;
-}
-async function getCachedTransformResult(environment, url$3, module$1, timestamp) {
- const prettyUrl = debugCache$1 ? prettifyUrl(url$3, environment.config.root) : "";
- const softInvalidatedTransformResult = await handleModuleSoftInvalidation(environment, module$1, timestamp);
- if (softInvalidatedTransformResult) {
- debugCache$1?.(`[memory-hmr] ${prettyUrl}`);
- return softInvalidatedTransformResult;
- }
- const cached = module$1.transformResult;
- if (cached) {
- debugCache$1?.(`[memory] ${prettyUrl}`);
- return cached;
- }
-}
-async function loadAndTransform(environment, id, url$3, options$1, timestamp, mod, resolved) {
- const { config: config$2, pluginContainer, logger } = environment;
- const prettyUrl = debugLoad || debugTransform ? prettifyUrl(url$3, config$2.root) : "";
- const moduleGraph = environment.moduleGraph;
- if (options$1.allowId && !options$1.allowId(id)) {
- const err$2 = /* @__PURE__ */ new Error(`Denied ID ${id}`);
- err$2.code = ERR_DENIED_ID;
- err$2.id = id;
- throw err$2;
- }
- let code = null;
- let map$1 = null;
- const loadStart = debugLoad ? performance$1.now() : 0;
- const loadResult = await pluginContainer.load(id);
- if (loadResult == null) {
- const file = cleanUrl(id);
- if (environment.config.consumer === "server" || isFileLoadingAllowed(environment.getTopLevelConfig(), slash(file))) {
- try {
- code = await fsp.readFile(file, "utf-8");
- debugLoad?.(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
- } catch (e$1) {
- if (e$1.code !== "ENOENT" && e$1.code !== "EISDIR") throw e$1;
- }
- if (code != null && environment.pluginContainer.watcher) ensureWatchedFile(environment.pluginContainer.watcher, file, config$2.root);
- }
- if (code) try {
- const extracted = await extractSourcemapFromFile(code, file);
- if (extracted) {
- code = extracted.code;
- map$1 = extracted.map;
- }
- } catch (e$1) {
- logger.warn(`Failed to load source map for ${file}.\n${e$1}`, { timestamp: true });
- }
- } else {
- debugLoad?.(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`);
- if (isObject(loadResult)) {
- code = loadResult.code;
- map$1 = loadResult.map;
- } else code = loadResult;
- }
- if (code == null) {
- const isPublicFile = checkPublicFile(url$3, environment.getTopLevelConfig());
- let publicDirName = path.relative(config$2.root, config$2.publicDir);
- if (publicDirName[0] !== ".") publicDirName = "/" + publicDirName;
- const msg = isPublicFile ? `This file is in ${publicDirName} and will be copied as-is during build without going through the plugin transforms, and therefore should not be imported from source code. It can only be referenced via HTML tags.` : `Does the file exist?`;
- const importerMod = moduleGraph.idToModuleMap.get(id)?.importers.values().next().value;
- const importer = importerMod?.file || importerMod?.url;
- const err$2 = /* @__PURE__ */ new Error(`Failed to load url ${url$3} (resolved id: ${id})${importer ? ` in ${importer}` : ""}. ${msg}`);
- err$2.code = isPublicFile ? ERR_LOAD_PUBLIC_URL : ERR_LOAD_URL;
- throw err$2;
- }
- if (environment._closing && environment.config.dev.recoverable) throwClosedServerError();
- mod ??= await moduleGraph._ensureEntryFromUrl(url$3, void 0, resolved);
- const transformStart = debugTransform ? performance$1.now() : 0;
- const transformResult = await pluginContainer.transform(code, id, { inMap: map$1 });
- const originalCode = code;
- if (transformResult.code === originalCode) debugTransform?.(timeFrom(transformStart) + import_picocolors$19.default.dim(` [skipped] ${prettyUrl}`));
- else {
- debugTransform?.(`${timeFrom(transformStart)} ${prettyUrl}`);
- code = transformResult.code;
- map$1 = transformResult.map;
- }
- let normalizedMap;
- if (typeof map$1 === "string") normalizedMap = JSON.parse(map$1);
- else if (map$1) normalizedMap = map$1;
- else normalizedMap = null;
- if (normalizedMap && "version" in normalizedMap && mod.file) {
- if (normalizedMap.mappings) await injectSourcesContent(normalizedMap, mod.file, logger);
- const sourcemapPath = `${mod.file}.map`;
- applySourcemapIgnoreList(normalizedMap, sourcemapPath, config$2.server.sourcemapIgnoreList, logger);
- if (path.isAbsolute(mod.file)) {
- let modDirname;
- for (let sourcesIndex = 0; sourcesIndex < normalizedMap.sources.length; ++sourcesIndex) {
- const sourcePath = normalizedMap.sources[sourcesIndex];
- if (sourcePath) {
- if (path.isAbsolute(sourcePath)) {
- modDirname ??= path.dirname(mod.file);
- normalizedMap.sources[sourcesIndex] = path.relative(modDirname, sourcePath);
- }
- }
- }
- }
- }
- if (environment._closing && environment.config.dev.recoverable) throwClosedServerError();
- const topLevelConfig = environment.getTopLevelConfig();
- const result = environment.config.dev.moduleRunnerTransform ? await ssrTransform(code, normalizedMap, url$3, originalCode, { json: { stringify: topLevelConfig.json.stringify === true && topLevelConfig.json.namedExports !== true } }) : {
- code,
- map: normalizedMap,
- etag: (0, import_etag.default)(code, { weak: true })
- };
- if (timestamp > mod.lastInvalidationTimestamp) moduleGraph.updateModuleTransformResult(mod, result);
- return result;
-}
-/**
-* When a module is soft-invalidated, we can preserve its previous `transformResult` and
-* return similar code to before:
-*
-* - Client: We need to transform the import specifiers with new timestamps
-* - SSR: We don't need to change anything as `ssrLoadModule` controls it
-*/
-async function handleModuleSoftInvalidation(environment, mod, timestamp) {
- const transformResult = mod.invalidationState;
- mod.invalidationState = void 0;
- if (!transformResult || transformResult === "HARD_INVALIDATED") return;
- if (mod.transformResult) throw new Error(`Internal server error: Soft-invalidated module "${mod.url}" should not have existing transform result`);
- let result;
- if (transformResult.ssr) result = transformResult;
- else {
- await init;
- const source = transformResult.code;
- const s = new MagicString(source);
- const [imports] = parse(source, mod.id || void 0);
- for (const imp of imports) {
- let rawUrl = source.slice(imp.s, imp.e);
- if (rawUrl === "import.meta") continue;
- const hasQuotes = rawUrl[0] === "\"" || rawUrl[0] === "'";
- if (hasQuotes) rawUrl = rawUrl.slice(1, -1);
- const urlWithoutTimestamp = removeTimestampQuery(rawUrl);
- const hmrUrl = unwrapId(stripBase(removeImportQuery(urlWithoutTimestamp), environment.config.base));
- for (const importedMod of mod.importedModules) {
- if (importedMod.url !== hmrUrl) continue;
- if (importedMod.lastHMRTimestamp > 0) {
- const replacedUrl = injectQuery(urlWithoutTimestamp, `t=${importedMod.lastHMRTimestamp}`);
- const start = hasQuotes ? imp.s + 1 : imp.s;
- const end = hasQuotes ? imp.e - 1 : imp.e;
- s.overwrite(start, end, replacedUrl);
- }
- if (imp.d === -1 && environment.config.dev.preTransformRequests) environment.warmupRequest(hmrUrl);
- break;
- }
- }
- const code = s.toString();
- result = {
- ...transformResult,
- code,
- etag: (0, import_etag.default)(code, { weak: true })
- };
- }
- if (timestamp > mod.lastInvalidationTimestamp) environment.moduleGraph.updateModuleTransformResult(mod, result);
- return result;
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.js
-var require_js_tokens = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- var HashbangComment, Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]?|[^\/[\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/uy, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace;
- Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
- Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/uy;
- StringLiteral = /(['"])(?:[^'"\\\n\r]+|(?!\1)['"]|\\(?:\r\n|[^]))*(\1)?/y;
- NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y;
- Template = /[`}](?:[^`\\$]+|\\[^]|\$(?!\{))*(`|\$\{)?/y;
- WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/uy;
- LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
- MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y;
- SingleLineComment = /\/\/.*/y;
- HashbangComment = /^#!.*/;
- JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
- JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/uy;
- JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y;
- JSXText = /[^<>{}]+/y;
- TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/;
- TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/;
- KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/;
- KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/;
- Newline = RegExp(LineTerminatorSequence.source);
- module.exports = function* (input, { jsx = false } = {}) {
- var braces$2, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack;
- ({length} = input);
- lastIndex = 0;
- lastSignificantToken = "";
- stack = [{ tag: "JS" }];
- braces$2 = [];
- parenNesting = 0;
- postfixIncDec = false;
- if (match = HashbangComment.exec(input)) {
- yield {
- type: "HashbangComment",
- value: match[0]
- };
- lastIndex = match[0].length;
- }
- while (lastIndex < length) {
- mode = stack[stack.length - 1];
- switch (mode.tag) {
- case "JS":
- case "JSNonExpressionParen":
- case "InterpolationInTemplate":
- case "InterpolationInJSX":
- if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
- RegularExpressionLiteral.lastIndex = lastIndex;
- if (match = RegularExpressionLiteral.exec(input)) {
- lastIndex = RegularExpressionLiteral.lastIndex;
- lastSignificantToken = match[0];
- postfixIncDec = true;
- yield {
- type: "RegularExpressionLiteral",
- value: match[0],
- closed: match[1] !== void 0 && match[1] !== "\\"
- };
- continue;
- }
- }
- Punctuator.lastIndex = lastIndex;
- if (match = Punctuator.exec(input)) {
- punctuator = match[0];
- nextLastIndex = Punctuator.lastIndex;
- nextLastSignificantToken = punctuator;
- switch (punctuator) {
- case "(":
- if (lastSignificantToken === "?NonExpressionParenKeyword") stack.push({
- tag: "JSNonExpressionParen",
- nesting: parenNesting
- });
- parenNesting++;
- postfixIncDec = false;
- break;
- case ")":
- parenNesting--;
- postfixIncDec = true;
- if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) {
- stack.pop();
- nextLastSignificantToken = "?NonExpressionParenEnd";
- postfixIncDec = false;
- }
- break;
- case "{":
- Punctuator.lastIndex = 0;
- isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken));
- braces$2.push(isExpression);
- postfixIncDec = false;
- break;
- case "}":
- switch (mode.tag) {
- case "InterpolationInTemplate":
- if (braces$2.length === mode.nesting) {
- Template.lastIndex = lastIndex;
- match = Template.exec(input);
- lastIndex = Template.lastIndex;
- lastSignificantToken = match[0];
- if (match[1] === "${") {
- lastSignificantToken = "?InterpolationInTemplate";
- postfixIncDec = false;
- yield {
- type: "TemplateMiddle",
- value: match[0]
- };
- } else {
- stack.pop();
- postfixIncDec = true;
- yield {
- type: "TemplateTail",
- value: match[0],
- closed: match[1] === "`"
- };
- }
- continue;
- }
- break;
- case "InterpolationInJSX": if (braces$2.length === mode.nesting) {
- stack.pop();
- lastIndex += 1;
- lastSignificantToken = "}";
- yield {
- type: "JSXPunctuator",
- value: "}"
- };
- continue;
- }
- }
- postfixIncDec = braces$2.pop();
- nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}";
- break;
- case "]":
- postfixIncDec = true;
- break;
- case "++":
- case "--":
- nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec";
- break;
- case "<":
- if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
- stack.push({ tag: "JSXTag" });
- lastIndex += 1;
- lastSignificantToken = "<";
- yield {
- type: "JSXPunctuator",
- value: punctuator
- };
- continue;
- }
- postfixIncDec = false;
- break;
- default: postfixIncDec = false;
- }
- lastIndex = nextLastIndex;
- lastSignificantToken = nextLastSignificantToken;
- yield {
- type: "Punctuator",
- value: punctuator
- };
- continue;
- }
- Identifier.lastIndex = lastIndex;
- if (match = Identifier.exec(input)) {
- lastIndex = Identifier.lastIndex;
- nextLastSignificantToken = match[0];
- switch (match[0]) {
- case "for":
- case "if":
- case "while":
- case "with": if (lastSignificantToken !== "." && lastSignificantToken !== "?.") nextLastSignificantToken = "?NonExpressionParenKeyword";
- }
- lastSignificantToken = nextLastSignificantToken;
- postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]);
- yield {
- type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName",
- value: match[0]
- };
- continue;
- }
- StringLiteral.lastIndex = lastIndex;
- if (match = StringLiteral.exec(input)) {
- lastIndex = StringLiteral.lastIndex;
- lastSignificantToken = match[0];
- postfixIncDec = true;
- yield {
- type: "StringLiteral",
- value: match[0],
- closed: match[2] !== void 0
- };
- continue;
- }
- NumericLiteral.lastIndex = lastIndex;
- if (match = NumericLiteral.exec(input)) {
- lastIndex = NumericLiteral.lastIndex;
- lastSignificantToken = match[0];
- postfixIncDec = true;
- yield {
- type: "NumericLiteral",
- value: match[0]
- };
- continue;
- }
- Template.lastIndex = lastIndex;
- if (match = Template.exec(input)) {
- lastIndex = Template.lastIndex;
- lastSignificantToken = match[0];
- if (match[1] === "${") {
- lastSignificantToken = "?InterpolationInTemplate";
- stack.push({
- tag: "InterpolationInTemplate",
- nesting: braces$2.length
- });
- postfixIncDec = false;
- yield {
- type: "TemplateHead",
- value: match[0]
- };
- } else {
- postfixIncDec = true;
- yield {
- type: "NoSubstitutionTemplate",
- value: match[0],
- closed: match[1] === "`"
- };
- }
- continue;
- }
- break;
- case "JSXTag":
- case "JSXTagEnd":
- JSXPunctuator.lastIndex = lastIndex;
- if (match = JSXPunctuator.exec(input)) {
- lastIndex = JSXPunctuator.lastIndex;
- nextLastSignificantToken = match[0];
- switch (match[0]) {
- case "<":
- stack.push({ tag: "JSXTag" });
- break;
- case ">":
- stack.pop();
- if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") {
- nextLastSignificantToken = "?JSX";
- postfixIncDec = true;
- } else stack.push({ tag: "JSXChildren" });
- break;
- case "{":
- stack.push({
- tag: "InterpolationInJSX",
- nesting: braces$2.length
- });
- nextLastSignificantToken = "?InterpolationInJSX";
- postfixIncDec = false;
- break;
- case "/": if (lastSignificantToken === "<") {
- stack.pop();
- if (stack[stack.length - 1].tag === "JSXChildren") stack.pop();
- stack.push({ tag: "JSXTagEnd" });
- }
- }
- lastSignificantToken = nextLastSignificantToken;
- yield {
- type: "JSXPunctuator",
- value: match[0]
- };
- continue;
- }
- JSXIdentifier.lastIndex = lastIndex;
- if (match = JSXIdentifier.exec(input)) {
- lastIndex = JSXIdentifier.lastIndex;
- lastSignificantToken = match[0];
- yield {
- type: "JSXIdentifier",
- value: match[0]
- };
- continue;
- }
- JSXString.lastIndex = lastIndex;
- if (match = JSXString.exec(input)) {
- lastIndex = JSXString.lastIndex;
- lastSignificantToken = match[0];
- yield {
- type: "JSXString",
- value: match[0],
- closed: match[2] !== void 0
- };
- continue;
- }
- break;
- case "JSXChildren":
- JSXText.lastIndex = lastIndex;
- if (match = JSXText.exec(input)) {
- lastIndex = JSXText.lastIndex;
- lastSignificantToken = match[0];
- yield {
- type: "JSXText",
- value: match[0]
- };
- continue;
- }
- switch (input[lastIndex]) {
- case "<":
- stack.push({ tag: "JSXTag" });
- lastIndex++;
- lastSignificantToken = "<";
- yield {
- type: "JSXPunctuator",
- value: "<"
- };
- continue;
- case "{":
- stack.push({
- tag: "InterpolationInJSX",
- nesting: braces$2.length
- });
- lastIndex++;
- lastSignificantToken = "?InterpolationInJSX";
- postfixIncDec = false;
- yield {
- type: "JSXPunctuator",
- value: "{"
- };
- continue;
- }
- }
- WhiteSpace.lastIndex = lastIndex;
- if (match = WhiteSpace.exec(input)) {
- lastIndex = WhiteSpace.lastIndex;
- yield {
- type: "WhiteSpace",
- value: match[0]
- };
- continue;
- }
- LineTerminatorSequence.lastIndex = lastIndex;
- if (match = LineTerminatorSequence.exec(input)) {
- lastIndex = LineTerminatorSequence.lastIndex;
- postfixIncDec = false;
- if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) lastSignificantToken = "?NoLineTerminatorHere";
- yield {
- type: "LineTerminatorSequence",
- value: match[0]
- };
- continue;
- }
- MultiLineComment.lastIndex = lastIndex;
- if (match = MultiLineComment.exec(input)) {
- lastIndex = MultiLineComment.lastIndex;
- if (Newline.test(match[0])) {
- postfixIncDec = false;
- if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) lastSignificantToken = "?NoLineTerminatorHere";
- }
- yield {
- type: "MultiLineComment",
- value: match[0],
- closed: match[1] !== void 0
- };
- continue;
- }
- SingleLineComment.lastIndex = lastIndex;
- if (match = SingleLineComment.exec(input)) {
- lastIndex = SingleLineComment.lastIndex;
- postfixIncDec = false;
- yield {
- type: "SingleLineComment",
- value: match[0]
- };
- continue;
- }
- firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex));
- lastIndex += firstCodePoint.length;
- lastSignificantToken = firstCodePoint;
- postfixIncDec = false;
- yield {
- type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid",
- value: firstCodePoint
- };
- }
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.mjs
-var import_js_tokens = /* @__PURE__ */ __toESM(require_js_tokens(), 1);
-const FILL_COMMENT = " ";
-function stripLiteralFromToken(token, fillChar, filter$1) {
- if (token.type === "SingleLineComment") return FILL_COMMENT.repeat(token.value.length);
- if (token.type === "MultiLineComment") return token.value.replace(/[^\n]/g, FILL_COMMENT);
- if (token.type === "StringLiteral") {
- if (!token.closed) return token.value;
- const body = token.value.slice(1, -1);
- if (filter$1(body)) return token.value[0] + fillChar.repeat(body.length) + token.value[token.value.length - 1];
- }
- if (token.type === "NoSubstitutionTemplate") {
- const body = token.value.slice(1, -1);
- if (filter$1(body)) return `\`${body.replace(/[^\n]/g, fillChar)}\``;
- }
- if (token.type === "RegularExpressionLiteral") {
- const body = token.value;
- if (filter$1(body)) return body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${fillChar.repeat($1.length)}/${$2}`);
- }
- if (token.type === "TemplateHead") {
- const body = token.value.slice(1, -2);
- if (filter$1(body)) return `\`${body.replace(/[^\n]/g, fillChar)}\${`;
- }
- if (token.type === "TemplateTail") {
- const body = token.value.slice(0, -2);
- if (filter$1(body)) return `}${body.replace(/[^\n]/g, fillChar)}\``;
- }
- if (token.type === "TemplateMiddle") {
- const body = token.value.slice(1, -2);
- if (filter$1(body)) return `}${body.replace(/[^\n]/g, fillChar)}\${`;
- }
- return token.value;
-}
-function optionsWithDefaults(options$1) {
- return {
- fillChar: options$1?.fillChar ?? " ",
- filter: options$1?.filter ?? (() => true)
- };
-}
-function stripLiteral(code, options$1) {
- let result = "";
- const _options = optionsWithDefaults(options$1);
- for (const token of (0, import_js_tokens.default)(code, { jsx: false })) result += stripLiteralFromToken(token, _options.fillChar, _options.filter);
- return result;
-}
-
-//#endregion
-//#region src/node/assetSource.ts
-const ALLOWED_META_NAME = [
- "msapplication-tileimage",
- "msapplication-square70x70logo",
- "msapplication-square150x150logo",
- "msapplication-wide310x150logo",
- "msapplication-square310x310logo",
- "msapplication-config",
- "twitter:image"
-];
-const ALLOWED_META_PROPERTY = [
- "og:image",
- "og:image:url",
- "og:image:secure_url",
- "og:audio",
- "og:audio:secure_url",
- "og:video",
- "og:video:secure_url"
-];
-const DEFAULT_HTML_ASSET_SOURCES = {
- audio: { srcAttributes: ["src"] },
- embed: { srcAttributes: ["src"] },
- img: {
- srcAttributes: ["src"],
- srcsetAttributes: ["srcset"]
- },
- image: { srcAttributes: ["href", "xlink:href"] },
- input: { srcAttributes: ["src"] },
- link: {
- srcAttributes: ["href"],
- srcsetAttributes: ["imagesrcset"]
- },
- object: { srcAttributes: ["data"] },
- source: {
- srcAttributes: ["src"],
- srcsetAttributes: ["srcset"]
- },
- track: { srcAttributes: ["src"] },
- use: { srcAttributes: ["href", "xlink:href"] },
- video: { srcAttributes: ["src", "poster"] },
- meta: {
- srcAttributes: ["content"],
- filter({ attributes }) {
- if (attributes.name && ALLOWED_META_NAME.includes(attributes.name.trim().toLowerCase())) return true;
- if (attributes.property && ALLOWED_META_PROPERTY.includes(attributes.property.trim().toLowerCase())) return true;
- return false;
- }
- }
-};
-/**
-* Given a HTML node, find all attributes that references an asset to be processed
-*/
-function getNodeAssetAttributes(node) {
- const matched = DEFAULT_HTML_ASSET_SOURCES[node.nodeName];
- if (!matched) return [];
- const attributes = {};
- for (const attr of node.attrs) attributes[getAttrKey(attr)] = attr.value;
- if ("vite-ignore" in attributes) return [{
- type: "remove",
- key: "vite-ignore",
- value: "",
- attributes,
- location: node.sourceCodeLocation.attrs["vite-ignore"]
- }];
- const actions = [];
- function handleAttributeKey(key, type) {
- const value$1 = attributes[key];
- if (!value$1) return;
- if (matched.filter && !matched.filter({
- key,
- value: value$1,
- attributes
- })) return;
- const location$1 = node.sourceCodeLocation.attrs[key];
- actions.push({
- type,
- key,
- value: value$1,
- attributes,
- location: location$1
- });
- }
- matched.srcAttributes?.forEach((key) => handleAttributeKey(key, "src"));
- matched.srcsetAttributes?.forEach((key) => handleAttributeKey(key, "srcset"));
- return actions;
-}
-function getAttrKey(attr) {
- return attr.prefix === void 0 ? attr.name : `${attr.prefix}:${attr.name}`;
-}
-
-//#endregion
-//#region src/node/plugins/importAnalysisBuild.ts
-var import_convert_source_map = /* @__PURE__ */ __toESM(require_convert_source_map(), 1);
-/**
-* A flag for injected helpers. This flag will be set to `false` if the output
-* target is not native es - so that injected helper logic can be conditionally
-* dropped.
-*/
-const isModernFlag = `__VITE_IS_MODERN__`;
-const preloadMethod = `__vitePreload`;
-const preloadMarker = `__VITE_PRELOAD__`;
-const preloadHelperId = "\0vite/preload-helper.js";
-const preloadMarkerRE = new RegExp(preloadMarker, "g");
-const dynamicImportPrefixRE = /import\s*\(/;
-const dynamicImportTreeshakenRE = /((?:\bconst\s+|\blet\s+|\bvar\s+|,\s*)(\{[^{}.=]+\})\s*=\s*await\s+import\([^)]+\))(?=\s*(?:$|[^[.]))|(\(\s*await\s+import\([^)]+\)\s*\)(\??\.[\w$]+))|\bimport\([^)]+\)(\s*\.then\(\s*(?:function\s*)?\(\s*\{([^{}.=]+)\}\))/g;
-function toRelativePath(filename, importer) {
- const relPath = path.posix.relative(path.posix.dirname(importer), filename);
- return relPath[0] === "." ? relPath : `./${relPath}`;
-}
-function findPreloadMarker(str, pos = 0) {
- preloadMarkerRE.lastIndex = pos;
- return preloadMarkerRE.exec(str)?.index ?? -1;
-}
-/**
-* Helper for preloading CSS and direct imports of async chunks in parallel to
-* the async chunk itself.
-*/
-function detectScriptRel() {
- const relList = typeof document !== "undefined" && document.createElement("link").relList;
- return relList && relList.supports && relList.supports("modulepreload") ? "modulepreload" : "preload";
-}
-function preload(baseModule, deps, importerUrl) {
- let promise = Promise.resolve();
- if (__VITE_IS_MODERN__ && deps && deps.length > 0) {
- const links = document.getElementsByTagName("link");
- const cspNonceMeta = document.querySelector("meta[property=csp-nonce]");
- const cspNonce = cspNonceMeta?.nonce || cspNonceMeta?.getAttribute("nonce");
- function allSettled(promises$2) {
- return Promise.all(promises$2.map((p) => Promise.resolve(p).then((value$1) => ({
- status: "fulfilled",
- value: value$1
- }), (reason) => ({
- status: "rejected",
- reason
- }))));
- }
- promise = allSettled(deps.map((dep) => {
- dep = assetsURL(dep, importerUrl);
- if (dep in seen) return;
- seen[dep] = true;
- const isCss = dep.endsWith(".css");
- const cssSelector = isCss ? "[rel=\"stylesheet\"]" : "";
- if (!!importerUrl) for (let i$1 = links.length - 1; i$1 >= 0; i$1--) {
- const link$1 = links[i$1];
- if (link$1.href === dep && (!isCss || link$1.rel === "stylesheet")) return;
- }
- else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) return;
- const link = document.createElement("link");
- link.rel = isCss ? "stylesheet" : scriptRel;
- if (!isCss) link.as = "script";
- link.crossOrigin = "";
- link.href = dep;
- if (cspNonce) link.setAttribute("nonce", cspNonce);
- document.head.appendChild(link);
- if (isCss) return new Promise((res, rej) => {
- link.addEventListener("load", res);
- link.addEventListener("error", () => rej(/* @__PURE__ */ new Error(`Unable to preload CSS for ${dep}`)));
- });
- }));
- }
- function handlePreloadError(err$2) {
- const e$1 = new Event("vite:preloadError", { cancelable: true });
- e$1.payload = err$2;
- window.dispatchEvent(e$1);
- if (!e$1.defaultPrevented) throw err$2;
- }
- return promise.then((res) => {
- for (const item of res || []) {
- if (item.status !== "rejected") continue;
- handlePreloadError(item.reason);
- }
- return baseModule().catch(handlePreloadError);
- });
-}
-function getPreloadCode(environment, renderBuiltUrlBoolean, isRelativeBase) {
- const { modulePreload } = environment.config.build;
- return `const scriptRel = ${modulePreload && modulePreload.polyfill ? `'modulepreload'` : `/* @__PURE__ */ (${detectScriptRel.toString()})()`};const assetsURL = ${renderBuiltUrlBoolean || isRelativeBase ? `function(dep, importerUrl) { return new URL(dep, importerUrl).href }` : `function(dep) { return ${JSON.stringify(environment.config.base)}+dep }`};const seen = {};export const ${preloadMethod} = ${preload.toString()}`;
-}
-/**
-* Build only. During serve this is performed as part of ./importAnalysis.
-*/
-function buildImportAnalysisPlugin(config$2) {
- const getInsertPreload = (environment) => environment.config.consumer === "client" && !config$2.isWorker && !config$2.build.lib;
- const renderBuiltUrl = config$2.experimental.renderBuiltUrl;
- const isRelativeBase = config$2.base === "./" || config$2.base === "";
- return {
- name: "vite:build-import-analysis",
- resolveId: {
- filter: { id: exactRegex(preloadHelperId) },
- handler(id) {
- return id;
- }
- },
- load: {
- filter: { id: exactRegex(preloadHelperId) },
- handler(_id) {
- return {
- code: getPreloadCode(this.environment, !!renderBuiltUrl, isRelativeBase),
- moduleSideEffects: false
- };
- }
- },
- transform: {
- filter: { code: dynamicImportPrefixRE },
- async handler(source, importer) {
- await init;
- let imports = [];
- try {
- imports = parse(source)[0];
- } catch (_e) {
- const e$1 = _e;
- const { message, showCodeFrame } = createParseErrorInfo(importer, source);
- this.error(message, showCodeFrame ? e$1.idx : void 0);
- }
- if (!imports.length) return null;
- const insertPreload = getInsertPreload(this.environment);
- const dynamicImports = {};
- if (insertPreload) {
- let match;
- while (match = dynamicImportTreeshakenRE.exec(source)) {
- if (match[1]) {
- dynamicImports[dynamicImportTreeshakenRE.lastIndex] = {
- declaration: `const ${match[2]}`,
- names: match[2]?.trim()
- };
- continue;
- }
- if (match[3]) {
- let names$1 = /\.([^.?]+)/.exec(match[4])?.[1] || "";
- if (names$1 === "default") names$1 = "default: __vite_default__";
- dynamicImports[dynamicImportTreeshakenRE.lastIndex - match[4]?.length - 1] = {
- declaration: `const {${names$1}}`,
- names: `{ ${names$1} }`
- };
- continue;
- }
- const names = match[6]?.trim();
- dynamicImports[dynamicImportTreeshakenRE.lastIndex - match[5]?.length] = {
- declaration: `const {${names}}`,
- names: `{ ${names} }`
- };
- }
- }
- let s;
- const str = () => s || (s = new MagicString(source));
- let needPreloadHelper = false;
- for (let index = 0; index < imports.length; index++) {
- const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, a: attributeIndex } = imports[index];
- const isDynamicImport = dynamicIndex > -1;
- if (!isDynamicImport && attributeIndex > -1) str().remove(end + 1, expEnd);
- if (isDynamicImport && insertPreload && (source[start] === "\"" || source[start] === "'" || source[start] === "`")) {
- needPreloadHelper = true;
- const { declaration, names } = dynamicImports[expEnd] || {};
- if (names) {
- str().prependLeft(expStart, `${preloadMethod}(async () => { ${declaration} = await `);
- str().appendRight(expEnd, `;return ${names}}`);
- } else str().prependLeft(expStart, `${preloadMethod}(() => `);
- str().appendRight(expEnd, `,${isModernFlag}?${preloadMarker}:void 0${renderBuiltUrl || isRelativeBase ? ",import.meta.url" : ""})`);
- }
- }
- if (needPreloadHelper && insertPreload && !source.includes(`const ${preloadMethod} =`)) str().prepend(`import { ${preloadMethod} } from "${preloadHelperId}";`);
- if (s) return {
- code: s.toString(),
- map: this.environment.config.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
- };
- }
- },
- renderChunk(code, _, { format: format$3 }) {
- if (code.indexOf(isModernFlag) > -1) {
- const re = new RegExp(isModernFlag, "g");
- const isModern = String(format$3 === "es");
- const isModernWithPadding = isModern + " ".repeat(isModernFlag.length - isModern.length);
- return {
- code: code.replace(re, isModernWithPadding),
- map: null
- };
- }
- return null;
- },
- generateBundle({ format: format$3 }, bundle) {
- if (format$3 !== "es") return;
- if (!getInsertPreload(this.environment)) {
- const removedPureCssFiles = removedPureCssFilesCache.get(config$2);
- if (removedPureCssFiles && removedPureCssFiles.size > 0) for (const file in bundle) {
- const chunk = bundle[file];
- if (chunk.type === "chunk" && chunk.code.includes("import")) {
- const code = chunk.code;
- let imports;
- try {
- imports = parse(code)[0].filter((i$1) => i$1.d > -1);
- } catch (e$1) {
- const loc = numberToPos(code, e$1.idx);
- this.error({
- name: e$1.name,
- message: e$1.message,
- stack: e$1.stack,
- cause: e$1.cause,
- pos: e$1.idx,
- loc: {
- ...loc,
- file: chunk.fileName
- },
- frame: generateCodeFrame(code, loc)
- });
- }
- for (const imp of imports) {
- const { n: name, s: start, e: end, ss: expStart, se: expEnd } = imp;
- let url$3 = name;
- if (!url$3) {
- const rawUrl = code.slice(start, end);
- if (rawUrl[0] === `"` && rawUrl.endsWith(`"`)) url$3 = rawUrl.slice(1, -1);
- }
- if (!url$3) continue;
- const normalizedFile = path.posix.join(path.posix.dirname(chunk.fileName), url$3);
- if (removedPureCssFiles.has(normalizedFile)) chunk.code = chunk.code.slice(0, expStart) + `Promise.resolve({${"".padEnd(expEnd - expStart - 19, " ")}})` + chunk.code.slice(expEnd);
- }
- }
- }
- return;
- }
- const buildSourcemap = this.environment.config.build.sourcemap;
- const { modulePreload } = this.environment.config.build;
- for (const file in bundle) {
- const chunk = bundle[file];
- if (chunk.type === "chunk" && chunk.code.indexOf(preloadMarker) > -1) {
- const code = chunk.code;
- let imports;
- try {
- imports = parse(code)[0].filter((i$1) => i$1.d > -1);
- } catch (e$1) {
- const loc = numberToPos(code, e$1.idx);
- this.error({
- name: e$1.name,
- message: e$1.message,
- stack: e$1.stack,
- cause: e$1.cause,
- pos: e$1.idx,
- loc: {
- ...loc,
- file: chunk.fileName
- },
- frame: generateCodeFrame(code, loc)
- });
- }
- const s = new MagicString(code);
- const rewroteMarkerStartPos = /* @__PURE__ */ new Set();
- const fileDeps = [];
- const addFileDep = (url$3, runtime = false) => {
- const index = fileDeps.findIndex((dep) => dep.url === url$3);
- if (index === -1) return fileDeps.push({
- url: url$3,
- runtime
- }) - 1;
- else return index;
- };
- if (imports.length) for (let index = 0; index < imports.length; index++) {
- const { n: name, s: start, e: end, ss: expStart, se: expEnd } = imports[index];
- let url$3 = name;
- if (!url$3) {
- const rawUrl = code.slice(start, end);
- if (rawUrl[0] === `"` && rawUrl.endsWith(`"`)) url$3 = rawUrl.slice(1, -1);
- }
- const deps = /* @__PURE__ */ new Set();
- let hasRemovedPureCssChunk = false;
- let normalizedFile = void 0;
- if (url$3) {
- normalizedFile = path.posix.join(path.posix.dirname(chunk.fileName), url$3);
- const ownerFilename = chunk.fileName;
- const analyzed = /* @__PURE__ */ new Set();
- const addDeps = (filename) => {
- if (filename === ownerFilename) return;
- if (analyzed.has(filename)) return;
- analyzed.add(filename);
- const chunk$1 = bundle[filename];
- if (chunk$1) {
- deps.add(chunk$1.fileName);
- if (chunk$1.type === "chunk") {
- chunk$1.imports.forEach(addDeps);
- chunk$1.viteMetadata.importedCss.forEach((file$1) => {
- deps.add(file$1);
- });
- }
- } else {
- const chunk$2 = removedPureCssFilesCache.get(config$2).get(filename);
- if (chunk$2) {
- if (chunk$2.viteMetadata.importedCss.size) {
- chunk$2.viteMetadata.importedCss.forEach((file$1) => {
- deps.add(file$1);
- });
- hasRemovedPureCssChunk = true;
- }
- s.update(expStart, expEnd, "Promise.resolve({})");
- }
- }
- };
- addDeps(normalizedFile);
- }
- let markerStartPos$1 = findPreloadMarker(code, end);
- if (markerStartPos$1 === -1 && imports.length === 1) markerStartPos$1 = findPreloadMarker(code);
- if (markerStartPos$1 > 0) {
- let depsArray = deps.size > 1 || hasRemovedPureCssChunk && deps.size > 0 ? modulePreload === false ? [...deps].filter((d) => d.endsWith(".css")) : [...deps] : [];
- const resolveDependencies = modulePreload ? modulePreload.resolveDependencies : void 0;
- if (resolveDependencies && normalizedFile) {
- const cssDeps = [];
- const otherDeps = [];
- for (const dep of depsArray) (dep.endsWith(".css") ? cssDeps : otherDeps).push(dep);
- depsArray = [...resolveDependencies(normalizedFile, otherDeps, {
- hostId: file,
- hostType: "js"
- }), ...cssDeps];
- }
- let renderedDeps;
- if (renderBuiltUrl) renderedDeps = depsArray.map((dep) => {
- const replacement = toOutputFilePathInJS(this.environment, dep, "asset", chunk.fileName, "js", toRelativePath);
- if (typeof replacement === "string") return addFileDep(replacement);
- return addFileDep(replacement.runtime, true);
- });
- else renderedDeps = depsArray.map((d) => isRelativeBase ? addFileDep(toRelativePath(d, file)) : addFileDep(d));
- s.update(markerStartPos$1, markerStartPos$1 + preloadMarker.length, renderedDeps.length > 0 ? `__vite__mapDeps([${renderedDeps.join(",")}])` : `[]`);
- rewroteMarkerStartPos.add(markerStartPos$1);
- }
- }
- if (fileDeps.length > 0) {
- const mapDepsCode = `const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=${`[${fileDeps.map((fileDep) => fileDep.runtime ? fileDep.url : JSON.stringify(fileDep.url)).join(",")}]`})))=>i.map(i=>d[i]);\n`;
- if (code.startsWith("#!")) s.prependLeft(code.indexOf("\n") + 1, mapDepsCode);
- else s.prepend(mapDepsCode);
- }
- let markerStartPos = findPreloadMarker(code);
- while (markerStartPos >= 0) {
- if (!rewroteMarkerStartPos.has(markerStartPos)) s.update(markerStartPos, markerStartPos + preloadMarker.length, "void 0");
- markerStartPos = findPreloadMarker(code, markerStartPos + preloadMarker.length);
- }
- if (s.hasChanged()) {
- chunk.code = s.toString();
- if (buildSourcemap && chunk.map) {
- const nextMap = s.generateMap({
- source: chunk.fileName,
- hires: "boundary"
- });
- const originalFile = chunk.map.file;
- const map$1 = combineSourcemaps(chunk.fileName, [nextMap, chunk.map]);
- map$1.toUrl = () => genSourceMapUrl(map$1);
- if (originalFile) map$1.file = originalFile;
- const originalDebugId = chunk.map.debugId;
- chunk.map = map$1;
- if (buildSourcemap === "inline") {
- chunk.code = chunk.code.replace(import_convert_source_map.default.mapFileCommentRegex, "");
- chunk.code += `\n//# sourceMappingURL=${genSourceMapUrl(map$1)}`;
- } else {
- if (originalDebugId) map$1.debugId = originalDebugId;
- const mapAsset = bundle[chunk.fileName + ".map"];
- if (mapAsset && mapAsset.type === "asset") mapAsset.source = map$1.toString();
- }
- }
- }
- }
- }
- }
- };
-}
-
-//#endregion
-//#region src/node/plugins/modulePreloadPolyfill.ts
-const modulePreloadPolyfillId = "vite/modulepreload-polyfill";
-const resolvedModulePreloadPolyfillId = "\0" + modulePreloadPolyfillId + ".js";
-function modulePreloadPolyfillPlugin(config$2) {
- let polyfillString;
- return {
- name: "vite:modulepreload-polyfill",
- resolveId: {
- filter: { id: exactRegex(modulePreloadPolyfillId) },
- handler(_id) {
- return resolvedModulePreloadPolyfillId;
- }
- },
- load: {
- filter: { id: exactRegex(resolvedModulePreloadPolyfillId) },
- handler(_id) {
- if (config$2.command !== "build" || this.environment.config.consumer !== "client") return "";
- if (!polyfillString) polyfillString = `${isModernFlag}&&(${polyfill.toString()}());`;
- return {
- code: polyfillString,
- moduleSideEffects: true
- };
- }
- }
- };
-}
-function polyfill() {
- const relList = document.createElement("link").relList;
- if (relList && relList.supports && relList.supports("modulepreload")) return;
- for (const link of document.querySelectorAll("link[rel=\"modulepreload\"]")) processPreload(link);
- new MutationObserver((mutations) => {
- for (const mutation of mutations) {
- if (mutation.type !== "childList") continue;
- for (const node of mutation.addedNodes) if (node.tagName === "LINK" && node.rel === "modulepreload") processPreload(node);
- }
- }).observe(document, {
- childList: true,
- subtree: true
- });
- function getFetchOpts(link) {
- const fetchOpts = {};
- if (link.integrity) fetchOpts.integrity = link.integrity;
- if (link.referrerPolicy) fetchOpts.referrerPolicy = link.referrerPolicy;
- if (link.crossOrigin === "use-credentials") fetchOpts.credentials = "include";
- else if (link.crossOrigin === "anonymous") fetchOpts.credentials = "omit";
- else fetchOpts.credentials = "same-origin";
- return fetchOpts;
- }
- function processPreload(link) {
- if (link.ep) return;
- link.ep = true;
- const fetchOpts = getFetchOpts(link);
- fetch(link.href, fetchOpts);
- }
-}
-
-//#endregion
-//#region src/node/plugins/html.ts
-var import_picocolors$18 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-var import_escape_html = /* @__PURE__ */ __toESM(require_escape_html(), 1);
-const htmlProxyRE$1 = /[?&]html-proxy=?(?:&inline-css)?(?:&style-attr)?&index=(\d+)\.(?:js|css)$/;
-const isHtmlProxyRE = /[?&]html-proxy\b/;
-const inlineCSSRE$1 = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g;
-const inlineImportRE = /(?<!(?<!\.\.)\.)\bimport\s*\(("(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*')\)/dg;
-const htmlLangRE = /\.(?:html|htm)$/;
-const spaceRe = /[\t\n\f\r ]/;
-const importMapRE = /[ \t]*<script[^>]*type\s*=\s*(?:"importmap"|'importmap'|importmap)[^>]*>.*?<\/script>/is;
-const importMapAppendRE = new RegExp([/[ \t]*<script[^>]*type\s*=\s*(?:"module"|'module'|module)[^>]*>/i, /[ \t]*<link[^>]*rel\s*=\s*(?:"modulepreload"|'modulepreload'|modulepreload)[\s\S]*?\/>/i].map((r$1) => r$1.source).join("|"), "i");
-const isHTMLProxy = (id) => isHtmlProxyRE.test(id);
-const isHTMLRequest = (request) => htmlLangRE.test(request);
-const htmlProxyMap = /* @__PURE__ */ new WeakMap();
-const htmlProxyResult = /* @__PURE__ */ new Map();
-function htmlInlineProxyPlugin(config$2) {
- htmlProxyMap.set(config$2, /* @__PURE__ */ new Map());
- return {
- name: "vite:html-inline-proxy",
- resolveId: {
- filter: { id: isHtmlProxyRE },
- handler(id) {
- return id;
- }
- },
- load: {
- filter: { id: isHtmlProxyRE },
- handler(id) {
- const proxyMatch = htmlProxyRE$1.exec(id);
- if (proxyMatch) {
- const index = Number(proxyMatch[1]);
- const url$3 = cleanUrl(id).replace(normalizePath(config$2.root), "");
- const result = htmlProxyMap.get(config$2).get(url$3)?.[index];
- if (result) return {
- ...result,
- moduleSideEffects: true
- };
- else throw new Error(`No matching HTML proxy module found from ${id}`);
- }
- }
- }
- };
-}
-function addToHTMLProxyCache(config$2, filePath, index, result) {
- if (!htmlProxyMap.get(config$2)) htmlProxyMap.set(config$2, /* @__PURE__ */ new Map());
- if (!htmlProxyMap.get(config$2).get(filePath)) htmlProxyMap.get(config$2).set(filePath, []);
- htmlProxyMap.get(config$2).get(filePath)[index] = result;
-}
-function addToHTMLProxyTransformResult(hash$1, code) {
- htmlProxyResult.set(hash$1, code);
-}
-const noInlineLinkRels = new Set([
- "icon",
- "apple-touch-icon",
- "apple-touch-startup-image",
- "manifest"
-]);
-const isAsyncScriptMap = /* @__PURE__ */ new WeakMap();
-function nodeIsElement(node) {
- return node.nodeName[0] !== "#";
-}
-function traverseNodes(node, visitor) {
- if (node.nodeName === "template") node = node.content;
- visitor(node);
- if (nodeIsElement(node) || node.nodeName === "#document" || node.nodeName === "#document-fragment") node.childNodes.forEach((childNode) => traverseNodes(childNode, visitor));
-}
-async function traverseHtml(html, filePath, warn, visitor) {
- const { parse: parse$15 } = await import("./dist.js");
- const warnings = {};
- traverseNodes(parse$15(html, {
- scriptingEnabled: false,
- sourceCodeLocationInfo: true,
- onParseError: (e$1) => {
- handleParseError(e$1, html, filePath, warnings);
- }
- }), visitor);
- for (const message of Object.values(warnings)) warn(import_picocolors$18.default.yellow(`\n${message}`));
-}
-function getScriptInfo(node) {
- let src;
- let srcSourceCodeLocation;
- let isModule = false;
- let isAsync = false;
- let isIgnored = false;
- for (const p of node.attrs) {
- if (p.prefix !== void 0) continue;
- if (p.name === "src") {
- if (!src) {
- src = p;
- srcSourceCodeLocation = node.sourceCodeLocation?.attrs["src"];
- }
- } else if (p.name === "type" && p.value === "module") isModule = true;
- else if (p.name === "async") isAsync = true;
- else if (p.name === "vite-ignore") isIgnored = true;
- }
- return {
- src,
- srcSourceCodeLocation,
- isModule,
- isAsync,
- isIgnored
- };
-}
-const attrValueStartRE = /=\s*(.)/;
-function overwriteAttrValue(s, sourceCodeLocation, newValue) {
- const srcString = s.slice(sourceCodeLocation.startOffset, sourceCodeLocation.endOffset);
- const valueStart = attrValueStartRE.exec(srcString);
- if (!valueStart) throw new Error(`[vite:html] internal error, failed to overwrite attribute value`);
- const wrapOffset = valueStart[1] === "\"" || valueStart[1] === "'" ? 1 : 0;
- const valueOffset = valueStart.index + valueStart[0].length - 1;
- s.update(sourceCodeLocation.startOffset + valueOffset + wrapOffset, sourceCodeLocation.endOffset - wrapOffset, newValue);
- return s;
-}
-function removeViteIgnoreAttr(s, sourceCodeLocation) {
- const loc = sourceCodeLocation.attrs?.["vite-ignore"];
- if (loc) s.remove(loc.startOffset, loc.endOffset);
- return s;
-}
-/**
-* Format parse5 @type {ParserError} to @type {RollupError}
-*/
-function formatParseError(parserError, id, html) {
- return {
- code: parserError.code,
- message: `parse5 error code ${parserError.code}`,
- frame: generateCodeFrame(html, parserError.startOffset, parserError.endOffset),
- loc: {
- file: id,
- line: parserError.startLine,
- column: parserError.startCol
- }
- };
-}
-function handleParseError(parserError, html, filePath, warnings) {
- switch (parserError.code) {
- case "missing-doctype": return;
- case "abandoned-head-element-child": return;
- case "duplicate-attribute": return;
- case "non-void-html-element-start-tag-with-trailing-solidus": return;
- case "unexpected-question-mark-instead-of-tag-name": return;
- }
- const parseError = formatParseError(parserError, filePath, html);
- warnings[parseError.code] ??= `Unable to parse HTML; ${parseError.message}\n at ${parseError.loc.file}:${parseError.loc.line}:${parseError.loc.column}\n` + parseError.frame;
-}
-/**
-* Compiles index.html into an entry js module
-*/
-function buildHtmlPlugin(config$2) {
- const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(config$2.plugins);
- preHooks.unshift(injectCspNonceMetaTagHook(config$2));
- preHooks.unshift(preImportMapHook(config$2));
- preHooks.push(htmlEnvHook(config$2));
- postHooks.push(injectNonceAttributeTagHook(config$2));
- postHooks.push(postImportMapHook());
- const processedHtml = perEnvironmentState(() => /* @__PURE__ */ new Map());
- const isExcludedUrl = (url$3) => url$3[0] === "#" || isExternalUrl(url$3) || isDataUrl(url$3);
- isAsyncScriptMap.set(config$2, /* @__PURE__ */ new Map());
- return {
- name: "vite:build-html",
- transform: {
- filter: { id: /\.html$/ },
- async handler(html, id) {
- id = normalizePath(id);
- const relativeUrlPath = normalizePath(path.relative(config$2.root, id));
- const publicPath = `/${relativeUrlPath}`;
- const publicBase = getBaseInHTML(relativeUrlPath, config$2);
- const publicToRelative = (filename) => publicBase + filename;
- const toOutputPublicFilePath = (url$3) => toOutputFilePathInHtml(url$3.slice(1), "public", relativeUrlPath, "html", config$2, publicToRelative);
- const nodeStartWithLeadingWhitespace = (node) => {
- const startOffset = node.sourceCodeLocation.startOffset;
- if (startOffset === 0) return 0;
- const lineStartOffset = startOffset - node.sourceCodeLocation.startCol;
- let isLineEmpty = false;
- try {
- isLineEmpty = !s.slice(Math.max(0, lineStartOffset), startOffset).trim();
- } catch {}
- return isLineEmpty ? lineStartOffset : startOffset;
- };
- html = await applyHtmlTransforms(html, preHooks, this, {
- path: publicPath,
- filename: id
- });
- let js = "";
- const s = new MagicString(html);
- const scriptUrls = [];
- const styleUrls = [];
- let inlineModuleIndex = -1;
- let everyScriptIsAsync = true;
- let someScriptsAreAsync = false;
- let someScriptsAreDefer = false;
- const assetUrlsPromises = [];
- const namedOutput = Object.keys(config$2.build.rollupOptions.input || {});
- const processAssetUrl = async (url$3, shouldInline$1) => {
- if (url$3 !== "" && !namedOutput.includes(url$3) && !namedOutput.includes(removeLeadingSlash(url$3))) try {
- return await urlToBuiltUrl(this, url$3, id, shouldInline$1);
- } catch (e$1) {
- if (e$1.code !== "ENOENT") throw e$1;
- }
- return url$3;
- };
- const setModuleSideEffectPromises = [];
- await traverseHtml(html, id, config$2.logger.warn, (node) => {
- if (!nodeIsElement(node)) return;
- let shouldRemove = false;
- if (node.nodeName === "script") {
- const { src, srcSourceCodeLocation, isModule, isAsync, isIgnored } = getScriptInfo(node);
- if (isIgnored) removeViteIgnoreAttr(s, node.sourceCodeLocation);
- else {
- const url$3 = src && src.value;
- const isPublicFile = !!(url$3 && checkPublicFile(url$3, config$2));
- if (isPublicFile) overwriteAttrValue(s, srcSourceCodeLocation, partialEncodeURIPath(toOutputPublicFilePath(url$3)));
- if (isModule) {
- inlineModuleIndex++;
- if (url$3 && !isExcludedUrl(url$3) && !isPublicFile) {
- setModuleSideEffectPromises.push(this.resolve(url$3, id).then((resolved) => {
- if (!resolved) return Promise.reject(/* @__PURE__ */ new Error(`Failed to resolve ${url$3} from ${id}`));
- const moduleInfo = this.getModuleInfo(resolved.id);
- if (moduleInfo) moduleInfo.moduleSideEffects = true;
- else if (!resolved.external) return this.load(resolved).then((mod) => {
- mod.moduleSideEffects = true;
- });
- }));
- js += `\nimport ${JSON.stringify(url$3)}`;
- shouldRemove = true;
- } else if (node.childNodes.length) {
- const contents = node.childNodes.pop().value;
- addToHTMLProxyCache(config$2, id.replace(normalizePath(config$2.root), ""), inlineModuleIndex, { code: contents });
- js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`;
- shouldRemove = true;
- }
- everyScriptIsAsync &&= isAsync;
- someScriptsAreAsync ||= isAsync;
- someScriptsAreDefer ||= !isAsync;
- } else if (url$3 && !isPublicFile) {
- if (!isExcludedUrl(url$3)) config$2.logger.warn(`<script src="${url$3}"> in "${publicPath}" can't be bundled without type="module" attribute`);
- } else if (node.childNodes.length) {
- const scriptNode = node.childNodes.pop();
- scriptUrls.push(...extractImportExpressionFromClassicScript(scriptNode));
- }
- }
- }
- const assetAttributes = getNodeAssetAttributes(node);
- for (const attr of assetAttributes) if (attr.type === "remove") {
- s.remove(attr.location.startOffset, attr.location.endOffset);
- continue;
- } else if (attr.type === "srcset") assetUrlsPromises.push((async () => {
- const processedEncodedUrl = await processSrcSet(attr.value, async ({ url: url$3 }) => {
- const decodedUrl = decodeURIIfPossible(url$3);
- if (decodedUrl !== void 0 && !isExcludedUrl(decodedUrl)) {
- const result = await processAssetUrl(url$3);
- return result !== decodedUrl ? encodeURIPath(result) : url$3;
- }
- return url$3;
- });
- if (processedEncodedUrl !== attr.value) overwriteAttrValue(s, attr.location, processedEncodedUrl);
- })());
- else if (attr.type === "src") {
- const url$3 = decodeURIIfPossible(attr.value);
- if (url$3 === void 0) {} else if (checkPublicFile(url$3, config$2)) overwriteAttrValue(s, attr.location, partialEncodeURIPath(toOutputPublicFilePath(url$3)));
- else if (!isExcludedUrl(url$3)) if (node.nodeName === "link" && isCSSRequest(url$3) && !("media" in attr.attributes || "disabled" in attr.attributes)) {
- const importExpression = `\nimport ${JSON.stringify(url$3)}`;
- styleUrls.push({
- url: url$3,
- start: nodeStartWithLeadingWhitespace(node),
- end: node.sourceCodeLocation.endOffset
- });
- js += importExpression;
- } else {
- const shouldInline$1 = node.nodeName === "link" && attr.attributes.rel && parseRelAttr(attr.attributes.rel).some((v) => noInlineLinkRels.has(v)) ? false : void 0;
- assetUrlsPromises.push((async () => {
- const processedUrl = await processAssetUrl(url$3, shouldInline$1);
- if (processedUrl !== url$3) overwriteAttrValue(s, attr.location, partialEncodeURIPath(processedUrl));
- })());
- }
- }
- const inlineStyle = findNeedTransformStyleAttribute(node);
- if (inlineStyle) {
- inlineModuleIndex++;
- const code = inlineStyle.attr.value;
- addToHTMLProxyCache(config$2, id.replace(normalizePath(config$2.root), ""), inlineModuleIndex, { code });
- js += `\nimport "${id}?html-proxy&inline-css&style-attr&index=${inlineModuleIndex}.css"`;
- const hash$1 = getHash(cleanUrl(id));
- overwriteAttrValue(s, inlineStyle.location, `__VITE_INLINE_CSS__${hash$1}_${inlineModuleIndex}__`);
- }
- if (node.nodeName === "style" && node.childNodes.length) {
- const styleNode = node.childNodes.pop();
- const filePath = id.replace(normalizePath(config$2.root), "");
- inlineModuleIndex++;
- addToHTMLProxyCache(config$2, filePath, inlineModuleIndex, { code: styleNode.value });
- js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`;
- const hash$1 = getHash(cleanUrl(id));
- s.update(styleNode.sourceCodeLocation.startOffset, styleNode.sourceCodeLocation.endOffset, `__VITE_INLINE_CSS__${hash$1}_${inlineModuleIndex}__`);
- }
- if (shouldRemove) s.remove(nodeStartWithLeadingWhitespace(node), node.sourceCodeLocation.endOffset);
- });
- isAsyncScriptMap.get(config$2).set(id, everyScriptIsAsync);
- if (someScriptsAreAsync && someScriptsAreDefer) config$2.logger.warn(`\nMixed async and defer script modules in ${id}, output script will fallback to defer. Every script, including inline ones, need to be marked as async for your output script to be async.`);
- await Promise.all(assetUrlsPromises);
- for (const { start, end, url: url$3 } of scriptUrls) if (checkPublicFile(url$3, config$2)) s.update(start, end, partialEncodeURIPath(toOutputPublicFilePath(url$3)));
- else if (!isExcludedUrl(url$3)) s.update(start, end, partialEncodeURIPath(await urlToBuiltUrl(this, url$3, id)));
- const resolvedStyleUrls = await Promise.all(styleUrls.map(async (styleUrl) => ({
- ...styleUrl,
- resolved: await this.resolve(styleUrl.url, id)
- })));
- for (const { start, end, url: url$3, resolved } of resolvedStyleUrls) if (resolved == null) {
- config$2.logger.warnOnce(`\n${url$3} doesn't exist at build time, it will remain unchanged to be resolved at runtime`);
- const importExpression = `\nimport ${JSON.stringify(url$3)}`;
- js = js.replace(importExpression, "");
- } else s.remove(start, end);
- processedHtml(this).set(id, s.toString());
- const { modulePreload } = this.environment.config.build;
- if (modulePreload !== false && modulePreload.polyfill && (someScriptsAreAsync || someScriptsAreDefer)) js = `import "${modulePreloadPolyfillId}";\n${js}`;
- await Promise.all(setModuleSideEffectPromises);
- return {
- code: js,
- moduleSideEffects: "no-treeshake"
- };
- }
- },
- async generateBundle(options$1, bundle) {
- const analyzedImportedCssFiles = /* @__PURE__ */ new Map();
- const inlineEntryChunk = /* @__PURE__ */ new Set();
- const getImportedChunks = (chunk, seen$1 = /* @__PURE__ */ new Set()) => {
- const chunks = [];
- chunk.imports.forEach((file) => {
- const importee = bundle[file];
- if (importee) {
- if (importee.type === "chunk" && !seen$1.has(file)) {
- seen$1.add(file);
- chunks.push(...getImportedChunks(importee, seen$1));
- chunks.push(importee);
- }
- } else chunks.push(file);
- });
- return chunks;
- };
- const toScriptTag = (chunkOrUrl, toOutputPath, isAsync) => ({
- tag: "script",
- attrs: {
- ...isAsync ? { async: true } : {},
- type: "module",
- crossorigin: true,
- src: typeof chunkOrUrl === "string" ? chunkOrUrl : toOutputPath(chunkOrUrl.fileName)
- }
- });
- const toPreloadTag = (filename, toOutputPath) => ({
- tag: "link",
- attrs: {
- rel: "modulepreload",
- crossorigin: true,
- href: toOutputPath(filename)
- }
- });
- const toStyleSheetLinkTag = (file, toOutputPath) => ({
- tag: "link",
- attrs: {
- rel: "stylesheet",
- crossorigin: true,
- href: toOutputPath(file)
- }
- });
- const getCssFilesForChunk = (chunk, seenChunks = /* @__PURE__ */ new Set(), seenCss = /* @__PURE__ */ new Set()) => {
- if (seenChunks.has(chunk.fileName)) return [];
- seenChunks.add(chunk.fileName);
- if (analyzedImportedCssFiles.has(chunk)) {
- const additionals = analyzedImportedCssFiles.get(chunk).filter((file) => !seenCss.has(file));
- additionals.forEach((file) => seenCss.add(file));
- return additionals;
- }
- const files = [];
- chunk.imports.forEach((file) => {
- const importee = bundle[file];
- if (importee?.type === "chunk") files.push(...getCssFilesForChunk(importee, seenChunks, seenCss));
- });
- analyzedImportedCssFiles.set(chunk, files);
- chunk.viteMetadata.importedCss.forEach((file) => {
- if (!seenCss.has(file)) {
- seenCss.add(file);
- files.push(file);
- }
- });
- return files;
- };
- const getCssTagsForChunk = (chunk, toOutputPath) => getCssFilesForChunk(chunk).map((file) => toStyleSheetLinkTag(file, toOutputPath));
- for (const [normalizedId, html] of processedHtml(this)) {
- const relativeUrlPath = normalizePath(path.relative(config$2.root, normalizedId));
- const assetsBase = getBaseInHTML(relativeUrlPath, config$2);
- const toOutputFilePath = (filename, type) => {
- if (isExternalUrl(filename)) return filename;
- else return toOutputFilePathInHtml(filename, type, relativeUrlPath, "html", config$2, (filename$1) => assetsBase + filename$1);
- };
- const toOutputAssetFilePath = (filename) => toOutputFilePath(filename, "asset");
- const toOutputPublicAssetFilePath = (filename) => toOutputFilePath(filename, "public");
- const isAsync = isAsyncScriptMap.get(config$2).get(normalizedId);
- let result = html;
- const chunk = Object.values(bundle).find((chunk$1) => chunk$1.type === "chunk" && chunk$1.isEntry && chunk$1.facadeModuleId && normalizePath(chunk$1.facadeModuleId) === normalizedId);
- let canInlineEntry = false;
- if (chunk) {
- if (options$1.format === "es" && isEntirelyImport(chunk.code)) canInlineEntry = true;
- const imports = getImportedChunks(chunk);
- let assetTags;
- if (canInlineEntry) assetTags = imports.map((chunk$1) => toScriptTag(chunk$1, toOutputAssetFilePath, isAsync));
- else {
- const { modulePreload } = this.environment.config.build;
- assetTags = [toScriptTag(chunk, toOutputAssetFilePath, isAsync)];
- if (modulePreload !== false) {
- const resolveDependencies = typeof modulePreload === "object" && modulePreload.resolveDependencies;
- const importsFileNames = imports.filter((chunkOrUrl) => typeof chunkOrUrl !== "string").map((chunk$1) => chunk$1.fileName);
- const resolvedDeps = resolveDependencies ? resolveDependencies(chunk.fileName, importsFileNames, {
- hostId: relativeUrlPath,
- hostType: "html"
- }) : importsFileNames;
- assetTags.push(...resolvedDeps.map((i$1) => toPreloadTag(i$1, toOutputAssetFilePath)));
- }
- }
- assetTags.push(...getCssTagsForChunk(chunk, toOutputAssetFilePath));
- result = injectToHead(result, assetTags);
- }
- if (!this.environment.config.build.cssCodeSplit) {
- const cssBundleName = cssBundleNameCache.get(config$2);
- const cssChunk = cssBundleName && Object.values(bundle).find((chunk$1) => chunk$1.type === "asset" && chunk$1.names.includes(cssBundleName));
- if (cssChunk) result = injectToHead(result, [{
- tag: "link",
- attrs: {
- rel: "stylesheet",
- crossorigin: true,
- href: toOutputAssetFilePath(cssChunk.fileName)
- }
- }]);
- }
- let match;
- let s;
- inlineCSSRE$1.lastIndex = 0;
- while (match = inlineCSSRE$1.exec(result)) {
- s ||= new MagicString(result);
- const { 0: full, 1: scopedName } = match;
- const cssTransformedCode = htmlProxyResult.get(scopedName);
- s.update(match.index, match.index + full.length, cssTransformedCode);
- }
- if (s) result = s.toString();
- result = await applyHtmlTransforms(result, [...normalHooks, ...postHooks], this, {
- path: "/" + relativeUrlPath,
- filename: normalizedId,
- bundle,
- chunk
- });
- result = result.replace(assetUrlRE, (_, fileHash, postfix = "") => {
- const file = this.getFileName(fileHash);
- if (chunk) chunk.viteMetadata.importedAssets.add(cleanUrl(file));
- return encodeURIPath(toOutputAssetFilePath(file)) + postfix;
- });
- result = result.replace(publicAssetUrlRE, (_, fileHash) => {
- const publicAssetPath = toOutputPublicAssetFilePath(getPublicAssetFilename(fileHash, config$2));
- return encodeURIPath(URL$1.canParse(publicAssetPath) ? publicAssetPath : normalizePath(publicAssetPath));
- });
- if (chunk && canInlineEntry) inlineEntryChunk.add(chunk.fileName);
- const shortEmitName = normalizePath(path.relative(config$2.root, normalizedId));
- this.emitFile({
- type: "asset",
- originalFileName: normalizedId,
- fileName: shortEmitName,
- source: result
- });
- }
- for (const fileName of inlineEntryChunk) delete bundle[fileName];
- }
- };
-}
-function parseRelAttr(attr) {
- return attr.split(spaceRe).map((v) => v.toLowerCase());
-}
-function findNeedTransformStyleAttribute(node) {
- const attr = node.attrs.find((prop) => prop.prefix === void 0 && prop.name === "style" && (prop.value.includes("url(") || prop.value.includes("image-set(")));
- if (!attr) return void 0;
- return {
- attr,
- location: node.sourceCodeLocation?.attrs?.["style"]
- };
-}
-function extractImportExpressionFromClassicScript(scriptTextNode) {
- const startOffset = scriptTextNode.sourceCodeLocation.startOffset;
- const cleanCode = stripLiteral(scriptTextNode.value);
- const scriptUrls = [];
- let match;
- inlineImportRE.lastIndex = 0;
- while (match = inlineImportRE.exec(cleanCode)) {
- const [, [urlStart, urlEnd]] = match.indices;
- const start = urlStart + 1;
- const end = urlEnd - 1;
- scriptUrls.push({
- start: start + startOffset,
- end: end + startOffset,
- url: scriptTextNode.value.slice(start, end)
- });
- }
- return scriptUrls;
-}
-function preImportMapHook(config$2) {
- return (html, ctx) => {
- const importMapIndex = html.search(importMapRE);
- if (importMapIndex < 0) return;
- const importMapAppendIndex = html.search(importMapAppendRE);
- if (importMapAppendIndex < 0) return;
- if (importMapAppendIndex < importMapIndex) {
- const relativeHtml = normalizePath(path.relative(config$2.root, ctx.filename));
- config$2.logger.warnOnce(import_picocolors$18.default.yellow(import_picocolors$18.default.bold(`(!) <script type="importmap"> should come before <script type="module"> and <link rel="modulepreload"> in /${relativeHtml}`)));
- }
- };
-}
-/**
-* Move importmap before the first module script and modulepreload link
-*/
-function postImportMapHook() {
- return (html) => {
- if (!importMapAppendRE.test(html)) return;
- let importMap;
- html = html.replace(importMapRE, (match) => {
- importMap = match;
- return "";
- });
- if (importMap) html = html.replace(importMapAppendRE, (match) => `${importMap}\n${match}`);
- return html;
- };
-}
-function injectCspNonceMetaTagHook(config$2) {
- return () => {
- if (!config$2.html?.cspNonce) return;
- return [{
- tag: "meta",
- injectTo: "head",
- attrs: {
- property: "csp-nonce",
- nonce: config$2.html.cspNonce
- }
- }];
- };
-}
-/**
-* Support `%ENV_NAME%` syntax in html files
-*/
-function htmlEnvHook(config$2) {
- const pattern = /%(\S+?)%/g;
- const envPrefix = resolveEnvPrefix({ envPrefix: config$2.envPrefix });
- const env$1 = { ...config$2.env };
- for (const key in config$2.define) if (key.startsWith(`import.meta.env.`)) {
- const val = config$2.define[key];
- if (typeof val === "string") try {
- const parsed = JSON.parse(val);
- env$1[key.slice(16)] = typeof parsed === "string" ? parsed : val;
- } catch {
- env$1[key.slice(16)] = val;
- }
- else env$1[key.slice(16)] = JSON.stringify(val);
- }
- return (html, ctx) => {
- return html.replace(pattern, (text, key) => {
- if (key in env$1) return env$1[key];
- else {
- if (envPrefix.some((prefix) => key.startsWith(prefix))) {
- const relativeHtml = normalizePath(path.relative(config$2.root, ctx.filename));
- config$2.logger.warn(import_picocolors$18.default.yellow(import_picocolors$18.default.bold(`(!) ${text} is not defined in env variables found in /${relativeHtml}. Is the variable mistyped?`)));
- }
- return text;
- }
- });
- };
-}
-function injectNonceAttributeTagHook(config$2) {
- const processRelType = new Set([
- "stylesheet",
- "modulepreload",
- "preload"
- ]);
- return async (html, { filename }) => {
- const nonce = config$2.html?.cspNonce;
- if (!nonce) return;
- const s = new MagicString(html);
- await traverseHtml(html, filename, config$2.logger.warn, (node) => {
- if (!nodeIsElement(node)) return;
- const { nodeName, attrs, sourceCodeLocation } = node;
- if (nodeName === "script" || nodeName === "style" || nodeName === "link" && attrs.some((attr) => attr.name === "rel" && parseRelAttr(attr.value).some((a) => processRelType.has(a)))) {
- if (attrs.some(({ name }) => name === "nonce")) return;
- const startTagEndOffset = sourceCodeLocation.startTag.endOffset;
- const appendOffset = html[startTagEndOffset - 2] === "/" ? 2 : 1;
- s.appendRight(startTagEndOffset - appendOffset, ` nonce="${nonce}"`);
- }
- });
- return s.toString();
- };
-}
-function resolveHtmlTransforms(plugins$1) {
- const preHooks = [];
- const normalHooks = [];
- const postHooks = [];
- for (const plugin of plugins$1) {
- const hook = plugin.transformIndexHtml;
- if (!hook) continue;
- if (typeof hook === "function") normalHooks.push(hook);
- else {
- const handler = hook.handler;
- if (hook.order === "pre") preHooks.push(handler);
- else if (hook.order === "post") postHooks.push(handler);
- else normalHooks.push(handler);
- }
- }
- return [
- preHooks,
- normalHooks,
- postHooks
- ];
-}
-const elementsAllowedInHead = new Set([
- "title",
- "base",
- "link",
- "style",
- "meta",
- "script",
- "noscript",
- "template"
-]);
-function headTagInsertCheck(tags, ctx) {
- if (!tags.length) return;
- const { logger } = ctx.server?.config || {};
- const disallowedTags = tags.filter((tagDescriptor) => !elementsAllowedInHead.has(tagDescriptor.tag));
- if (disallowedTags.length) {
- const dedupedTags = unique(disallowedTags.map((tagDescriptor) => `<${tagDescriptor.tag}>`));
- logger?.warn(import_picocolors$18.default.yellow(import_picocolors$18.default.bold(`[${dedupedTags.join(",")}] can not be used inside the <head> Element, please check the 'injectTo' value`)));
- }
-}
-async function applyHtmlTransforms(html, hooks, pluginContext, ctx) {
- for (const hook of hooks) {
- const res = await hook.call(pluginContext, html, ctx);
- if (!res) continue;
- if (typeof res === "string") html = res;
- else {
- let tags;
- if (Array.isArray(res)) tags = res;
- else {
- html = res.html || html;
- tags = res.tags;
- }
- let headTags;
- let headPrependTags;
- let bodyTags;
- let bodyPrependTags;
- for (const tag of tags) switch (tag.injectTo) {
- case "body":
- (bodyTags ??= []).push(tag);
- break;
- case "body-prepend":
- (bodyPrependTags ??= []).push(tag);
- break;
- case "head":
- (headTags ??= []).push(tag);
- break;
- default: (headPrependTags ??= []).push(tag);
- }
- headTagInsertCheck([...headTags || [], ...headPrependTags || []], ctx);
- if (headPrependTags) html = injectToHead(html, headPrependTags, true);
- if (headTags) html = injectToHead(html, headTags);
- if (bodyPrependTags) html = injectToBody(html, bodyPrependTags, true);
- if (bodyTags) html = injectToBody(html, bodyTags);
- }
- }
- return html;
-}
-const importRE = /\bimport\s*(?:"[^"]*[^\\]"|'[^']*[^\\]');*/g;
-const commentRE$1 = /\/\*[\s\S]*?\*\/|\/\/.*$/gm;
-function isEntirelyImport(code) {
- return !code.replace(importRE, "").replace(commentRE$1, "").trim().length;
-}
-function getBaseInHTML(urlRelativePath, config$2) {
- return config$2.base === "./" || config$2.base === "" ? path.posix.join(path.posix.relative(urlRelativePath, "").slice(0, -2), "./") : config$2.base;
-}
-const headInjectRE = /([ \t]*)<\/head>/i;
-const headPrependInjectRE = /([ \t]*)<head[^>]*>/i;
-const htmlInjectRE = /<\/html>/i;
-const htmlPrependInjectRE = /([ \t]*)<html[^>]*>/i;
-const bodyInjectRE = /([ \t]*)<\/body>/i;
-const bodyPrependInjectRE = /([ \t]*)<body[^>]*>/i;
-const doctypePrependInjectRE = /<!doctype html>/i;
-function injectToHead(html, tags, prepend = false) {
- if (tags.length === 0) return html;
- if (prepend) {
- if (headPrependInjectRE.test(html)) return html.replace(headPrependInjectRE, (match, p1) => `${match}\n${serializeTags(tags, incrementIndent(p1))}`);
- } else {
- if (headInjectRE.test(html)) return html.replace(headInjectRE, (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`);
- if (bodyPrependInjectRE.test(html)) return html.replace(bodyPrependInjectRE, (match, p1) => `${serializeTags(tags, p1)}\n${match}`);
- }
- return prependInjectFallback(html, tags);
-}
-function injectToBody(html, tags, prepend = false) {
- if (tags.length === 0) return html;
- if (prepend) {
- if (bodyPrependInjectRE.test(html)) return html.replace(bodyPrependInjectRE, (match, p1) => `${match}\n${serializeTags(tags, incrementIndent(p1))}`);
- if (headInjectRE.test(html)) return html.replace(headInjectRE, (match, p1) => `${match}\n${serializeTags(tags, p1)}`);
- return prependInjectFallback(html, tags);
- } else {
- if (bodyInjectRE.test(html)) return html.replace(bodyInjectRE, (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`);
- if (htmlInjectRE.test(html)) return html.replace(htmlInjectRE, `${serializeTags(tags)}\n$&`);
- return html + `\n` + serializeTags(tags);
- }
-}
-function prependInjectFallback(html, tags) {
- if (htmlPrependInjectRE.test(html)) return html.replace(htmlPrependInjectRE, `$&\n${serializeTags(tags)}`);
- if (doctypePrependInjectRE.test(html)) return html.replace(doctypePrependInjectRE, `$&\n${serializeTags(tags)}`);
- return serializeTags(tags) + html;
-}
-const unaryTags = new Set([
- "link",
- "meta",
- "base"
-]);
-function serializeTag({ tag, attrs, children }, indent = "") {
- if (unaryTags.has(tag)) return `<${tag}${serializeAttrs(attrs)}>`;
- else return `<${tag}${serializeAttrs(attrs)}>${serializeTags(children, incrementIndent(indent))}</${tag}>`;
-}
-function serializeTags(tags, indent = "") {
- if (typeof tags === "string") return tags;
- else if (tags && tags.length) return tags.map((tag) => `${indent}${serializeTag(tag, indent)}\n`).join("");
- return "";
-}
-function serializeAttrs(attrs) {
- let res = "";
- for (const key in attrs) if (typeof attrs[key] === "boolean") res += attrs[key] ? ` ${key}` : ``;
- else res += ` ${key}="${(0, import_escape_html.default)(attrs[key])}"`;
- return res;
-}
-function incrementIndent(indent = "") {
- return `${indent}${indent[0] === " " ? " " : " "}`;
-}
-
-//#endregion
-//#region src/node/server/middlewares/transform.ts
-var import_picocolors$17 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const debugCache = createDebugger("vite:cache");
-const knownIgnoreList = new Set(["/", "/favicon.ico"]);
-const documentFetchDests = new Set([
- "document",
- "iframe",
- "frame",
- "fencedframe"
-]);
-function isDocumentFetchDest(req$4) {
- const fetchDest = req$4.headers["sec-fetch-dest"];
- return fetchDest !== void 0 && documentFetchDests.has(fetchDest);
-}
-const urlRE$1 = /[?&]url\b/;
-const rawRE$1 = /[?&]raw\b/;
-const inlineRE$2 = /[?&]inline\b/;
-const svgRE = /\.svg\b/;
-function isServerAccessDeniedForTransform(config$2, id) {
- if (rawRE$1.test(id) || urlRE$1.test(id) || inlineRE$2.test(id) || svgRE.test(id)) return checkLoadingAccess(config$2, id) !== "allowed";
- return false;
-}
-/**
-* A middleware that short-circuits the middleware chain to serve cached transformed modules
-*/
-function cachedTransformMiddleware(server) {
- return function viteCachedTransformMiddleware(req$4, res, next) {
- const environment = server.environments.client;
- if (isDocumentFetchDest(req$4)) {
- res.appendHeader("Vary", "Sec-Fetch-Dest");
- return next();
- }
- const ifNoneMatch = req$4.headers["if-none-match"];
- if (ifNoneMatch) {
- const moduleByEtag = environment.moduleGraph.getModuleByEtag(ifNoneMatch);
- if (moduleByEtag?.transformResult?.etag === ifNoneMatch && moduleByEtag.url === req$4.url) {
- if (!isCSSRequest(req$4.url)) {
- debugCache?.(`[304] ${prettifyUrl(req$4.url, server.config.root)}`);
- res.statusCode = 304;
- return res.end();
- }
- }
- }
- next();
- };
-}
-function transformMiddleware(server) {
- const { root, publicDir } = server.config;
- const publicDirInRoot = publicDir.startsWith(withTrailingSlash(root));
- const publicPath = `${publicDir.slice(root.length)}/`;
- return async function viteTransformMiddleware(req$4, res, next) {
- const environment = server.environments.client;
- if (req$4.method !== "GET" && req$4.method !== "HEAD" || knownIgnoreList.has(req$4.url) || isDocumentFetchDest(req$4)) return next();
- let url$3;
- try {
- url$3 = decodeURI(removeTimestampQuery(req$4.url)).replace(NULL_BYTE_PLACEHOLDER, "\0");
- } catch (e$1) {
- if (e$1 instanceof URIError) {
- server.config.logger.warn(import_picocolors$17.default.yellow(`Malformed URI sequence in request URL: ${removeTimestampQuery(req$4.url)}`));
- return next();
- }
- return next(e$1);
- }
- const withoutQuery = cleanUrl(url$3);
- try {
- if (withoutQuery.endsWith(".map")) if (environment.depsOptimizer?.isOptimizedDepUrl(url$3)) {
- const sourcemapPath = url$3.startsWith(FS_PREFIX) ? fsPathFromId(url$3) : normalizePath(path.resolve(server.config.root, url$3.slice(1)));
- try {
- const map$1 = JSON.parse(await fsp.readFile(sourcemapPath, "utf-8"));
- applySourcemapIgnoreList(map$1, sourcemapPath, server.config.server.sourcemapIgnoreList, server.config.logger);
- return send(req$4, res, JSON.stringify(map$1), "json", { headers: server.config.server.headers });
- } catch {
- const dummySourceMap = {
- version: 3,
- file: sourcemapPath.replace(/\.map$/, ""),
- sources: [],
- sourcesContent: [],
- names: [],
- mappings: ";;;;;;;;;"
- };
- return send(req$4, res, JSON.stringify(dummySourceMap), "json", {
- cacheControl: "no-cache",
- headers: server.config.server.headers
- });
- }
- } else {
- const originalUrl = url$3.replace(/\.map($|\?)/, "$1");
- const map$1 = (await environment.moduleGraph.getModuleByUrl(originalUrl))?.transformResult?.map;
- if (map$1) return send(req$4, res, JSON.stringify(map$1), "json", { headers: server.config.server.headers });
- else return next();
- }
- if (publicDirInRoot && url$3.startsWith(publicPath)) warnAboutExplicitPublicPathInUrl(url$3);
- if (req$4.headers["sec-fetch-dest"] === "script" || isJSRequest(url$3) || isImportRequest(url$3) || isCSSRequest(url$3) || isHTMLProxy(url$3)) {
- url$3 = removeImportQuery(url$3);
- url$3 = unwrapId(url$3);
- if (isCSSRequest(url$3)) {
- if (req$4.headers.accept?.includes("text/css") && !isDirectRequest(url$3)) url$3 = injectQuery(url$3, "direct");
- const ifNoneMatch = req$4.headers["if-none-match"];
- if (ifNoneMatch && (await environment.moduleGraph.getModuleByUrl(url$3))?.transformResult?.etag === ifNoneMatch) {
- debugCache?.(`[304] ${prettifyUrl(url$3, server.config.root)}`);
- res.statusCode = 304;
- return res.end();
- }
- }
- const result = await environment.transformRequest(url$3, { allowId(id) {
- return id[0] === "\0" || !isServerAccessDeniedForTransform(server.config, id);
- } });
- if (result) {
- const depsOptimizer = environment.depsOptimizer;
- const type = isDirectCSSRequest(url$3) ? "css" : "js";
- const isDep = DEP_VERSION_RE.test(url$3) || depsOptimizer?.isOptimizedDepUrl(url$3);
- return send(req$4, res, result.code, type, {
- etag: result.etag,
- cacheControl: isDep ? "max-age=31536000,immutable" : "no-cache",
- headers: server.config.server.headers,
- map: result.map
- });
- }
- }
- } catch (e$1) {
- if (e$1?.code === ERR_OPTIMIZE_DEPS_PROCESSING_ERROR) {
- if (!res.writableEnded) {
- res.statusCode = 504;
- res.statusMessage = "Optimize Deps Processing Error";
- res.end();
- }
- server.config.logger.error(e$1.message);
- return;
- }
- if (e$1?.code === ERR_OUTDATED_OPTIMIZED_DEP) {
- if (!res.writableEnded) {
- res.statusCode = 504;
- res.statusMessage = "Outdated Optimize Dep";
- res.end();
- }
- return;
- }
- if (e$1?.code === ERR_CLOSED_SERVER) {
- if (!res.writableEnded) {
- res.statusCode = 504;
- res.statusMessage = "Outdated Request";
- res.end();
- }
- return;
- }
- if (e$1?.code === ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR) {
- if (!res.writableEnded) {
- res.statusCode = 404;
- res.end();
- }
- server.config.logger.warn(import_picocolors$17.default.yellow(e$1.message));
- return;
- }
- if (e$1?.code === ERR_LOAD_URL) return next();
- if (e$1?.code === ERR_DENIED_ID) {
- const id = e$1.id;
- const servingAccessResult = checkLoadingAccess(server.config, id);
- if (servingAccessResult === "denied") {
- respondWithAccessDenied(id, server, res);
- return true;
- }
- if (servingAccessResult === "fallback") {
- next();
- return true;
- }
- throw new Error(`Unexpected access result for id ${id}`);
- }
- return next(e$1);
- }
- next();
- };
- function warnAboutExplicitPublicPathInUrl(url$3) {
- let warning;
- if (isImportRequest(url$3)) {
- const rawUrl = removeImportQuery(url$3);
- if (urlRE$1.test(url$3)) warning = `Assets in the public directory are served at the root path.\nInstead of ${import_picocolors$17.default.cyan(rawUrl)}, use ${import_picocolors$17.default.cyan(rawUrl.replace(publicPath, "/"))}.`;
- else warning = `Assets in public directory cannot be imported from JavaScript.
-If you intend to import that asset, put the file in the src directory, and use ${import_picocolors$17.default.cyan(rawUrl.replace(publicPath, "/src/"))} instead of ${import_picocolors$17.default.cyan(rawUrl)}.\nIf you intend to use the URL of that asset, use ${import_picocolors$17.default.cyan(injectQuery(rawUrl.replace(publicPath, "/"), "url"))}.`;
- } else warning = `Files in the public directory are served at the root path.\nInstead of ${import_picocolors$17.default.cyan(url$3)}, use ${import_picocolors$17.default.cyan(url$3.replace(publicPath, "/"))}.`;
- server.config.logger.warn(import_picocolors$17.default.yellow(warning));
- }
-}
-
-//#endregion
-//#region src/node/server/middlewares/indexHtml.ts
-function createDevHtmlTransformFn(config$2) {
- const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(config$2.plugins);
- const transformHooks = [
- preImportMapHook(config$2),
- injectCspNonceMetaTagHook(config$2),
- ...preHooks,
- htmlEnvHook(config$2),
- devHtmlHook,
- ...normalHooks,
- ...postHooks,
- injectNonceAttributeTagHook(config$2),
- postImportMapHook()
- ];
- const pluginContext = new BasicMinimalPluginContext({
- ...basePluginContextMeta,
- watchMode: true
- }, config$2.logger);
- return (server, url$3, html, originalUrl) => {
- return applyHtmlTransforms(html, transformHooks, pluginContext, {
- path: url$3,
- filename: getHtmlFilename(url$3, server),
- server,
- originalUrl
- });
- };
-}
-function getHtmlFilename(url$3, server) {
- if (url$3.startsWith(FS_PREFIX)) return decodeURIComponent(fsPathFromId(url$3));
- else return decodeURIComponent(normalizePath(path.join(server.config.root, url$3.slice(1))));
-}
-function shouldPreTransform(url$3, config$2) {
- return !checkPublicFile(url$3, config$2) && (isJSRequest(url$3) || isCSSRequest(url$3));
-}
-const wordCharRE = /\w/;
-function isBareRelative(url$3) {
- return wordCharRE.test(url$3[0]) && !url$3.includes(":");
-}
-const processNodeUrl = (url$3, useSrcSetReplacer, config$2, htmlPath, originalUrl, server, isClassicScriptLink) => {
- const replacer = (url$4) => {
- if (url$4[0] === "/" && url$4[1] !== "/" || (url$4[0] === "." || isBareRelative(url$4)) && originalUrl && originalUrl !== "/" && htmlPath === "/index.html") url$4 = path.posix.join(config$2.base, url$4);
- let preTransformUrl;
- if (!isClassicScriptLink && shouldPreTransform(url$4, config$2)) {
- if (url$4[0] === "/" && url$4[1] !== "/") preTransformUrl = url$4;
- else if (url$4[0] === "." || isBareRelative(url$4)) preTransformUrl = path.posix.join(config$2.base, path.posix.dirname(htmlPath), url$4);
- }
- if (server) {
- const mod = server.environments.client.moduleGraph.urlToModuleMap.get(preTransformUrl || url$4);
- if (mod && mod.lastHMRTimestamp > 0) url$4 = injectQuery(url$4, `t=${mod.lastHMRTimestamp}`);
- }
- if (server && preTransformUrl) {
- try {
- preTransformUrl = decodeURI(preTransformUrl);
- } catch {
- return url$4;
- }
- preTransformRequest(server, preTransformUrl, config$2.decodedBase);
- }
- return url$4;
- };
- return useSrcSetReplacer ? processSrcSetSync(url$3, ({ url: url$4 }) => replacer(url$4)) : replacer(url$3);
-};
-const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl }) => {
- const { config: config$2, watcher } = server;
- const base = config$2.base || "/";
- const decodedBase = config$2.decodedBase || "/";
- let proxyModulePath;
- let proxyModuleUrl;
- const trailingSlash = htmlPath.endsWith("/");
- if (!trailingSlash && fs.existsSync(filename)) {
- proxyModulePath = htmlPath;
- proxyModuleUrl = proxyModulePath;
- } else {
- proxyModulePath = `\0${`${htmlPath}${trailingSlash ? "index.html" : ""}`}`;
- proxyModuleUrl = wrapId(proxyModulePath);
- }
- proxyModuleUrl = joinUrlSegments(decodedBase, proxyModuleUrl);
- const s = new MagicString(html);
- let inlineModuleIndex = -1;
- const proxyCacheUrl = decodeURI(cleanUrl(proxyModulePath).replace(normalizePath(config$2.root), ""));
- const styleUrl = [];
- const inlineStyles = [];
- const inlineModulePaths = [];
- const addInlineModule = (node, ext) => {
- inlineModuleIndex++;
- const contentNode = node.childNodes[0];
- const code = contentNode.value;
- let map$1;
- if (proxyModulePath[0] !== "\0") {
- map$1 = new MagicString(html).snip(contentNode.sourceCodeLocation.startOffset, contentNode.sourceCodeLocation.endOffset).generateMap({ hires: "boundary" });
- map$1.sources = [filename];
- map$1.file = filename;
- }
- addToHTMLProxyCache(config$2, proxyCacheUrl, inlineModuleIndex, {
- code,
- map: map$1
- });
- const modulePath = `${proxyModuleUrl}?html-proxy&index=${inlineModuleIndex}.${ext}`;
- inlineModulePaths.push(modulePath);
- s.update(node.sourceCodeLocation.startOffset, node.sourceCodeLocation.endOffset, `<script type="module" src="${modulePath}"><\/script>`);
- preTransformRequest(server, modulePath, decodedBase);
- };
- await traverseHtml(html, filename, config$2.logger.warn, (node) => {
- if (!nodeIsElement(node)) return;
- if (node.nodeName === "script") {
- const { src, srcSourceCodeLocation, isModule, isIgnored } = getScriptInfo(node);
- if (isIgnored) removeViteIgnoreAttr(s, node.sourceCodeLocation);
- else if (src) {
- const processedUrl = processNodeUrl(src.value, false, config$2, htmlPath, originalUrl, server, !isModule);
- if (processedUrl !== src.value) overwriteAttrValue(s, srcSourceCodeLocation, processedUrl);
- } else if (isModule && node.childNodes.length) addInlineModule(node, "js");
- else if (node.childNodes.length) {
- const scriptNode = node.childNodes[node.childNodes.length - 1];
- for (const { url: url$3, start, end } of extractImportExpressionFromClassicScript(scriptNode)) {
- const processedUrl = processNodeUrl(url$3, false, config$2, htmlPath, originalUrl);
- if (processedUrl !== url$3) s.update(start, end, processedUrl);
- }
- }
- }
- const inlineStyle = findNeedTransformStyleAttribute(node);
- if (inlineStyle) {
- inlineModuleIndex++;
- inlineStyles.push({
- index: inlineModuleIndex,
- location: inlineStyle.location,
- code: inlineStyle.attr.value
- });
- }
- if (node.nodeName === "style" && node.childNodes.length) {
- const children = node.childNodes[0];
- styleUrl.push({
- start: children.sourceCodeLocation.startOffset,
- end: children.sourceCodeLocation.endOffset,
- code: children.value
- });
- }
- const assetAttributes = getNodeAssetAttributes(node);
- for (const attr of assetAttributes) if (attr.type === "remove") s.remove(attr.location.startOffset, attr.location.endOffset);
- else {
- const processedUrl = processNodeUrl(attr.value, attr.type === "srcset", config$2, htmlPath, originalUrl);
- if (processedUrl !== attr.value) overwriteAttrValue(s, attr.location, processedUrl);
- }
- });
- const clientModuelGraph = server?.environments.client.moduleGraph;
- if (clientModuelGraph) await Promise.all(inlineModulePaths.map(async (url$3) => {
- const module$1 = await clientModuelGraph.getModuleByUrl(url$3);
- if (module$1) clientModuelGraph.invalidateModule(module$1);
- }));
- await Promise.all([...styleUrl.map(async ({ start, end, code }, index) => {
- const url$3 = `${proxyModulePath}?html-proxy&direct&index=${index}.css`;
- const mod = await server.environments.client.moduleGraph.ensureEntryFromUrl(url$3, false);
- ensureWatchedFile(watcher, mod.file, config$2.root);
- const result = await server.environments.client.pluginContainer.transform(code, mod.id);
- let content = "";
- if (result.map && "version" in result.map) {
- if (result.map.mappings) await injectSourcesContent(result.map, proxyModulePath, config$2.logger);
- content = getCodeWithSourcemap("css", result.code, result.map);
- } else content = result.code;
- s.overwrite(start, end, content);
- }), ...inlineStyles.map(async ({ index, location: location$1, code }) => {
- const url$3 = `${proxyModulePath}?html-proxy&inline-css&style-attr&index=${index}.css`;
- const mod = await server.environments.client.moduleGraph.ensureEntryFromUrl(url$3, false);
- ensureWatchedFile(watcher, mod.file, config$2.root);
- await server?.environments.client.pluginContainer.transform(code, mod.id);
- const hash$1 = getHash(cleanUrl(mod.id));
- overwriteAttrValue(s, location$1, htmlProxyResult.get(`${hash$1}_${index}`) ?? "");
- })]);
- html = s.toString();
- return {
- html,
- tags: [{
- tag: "script",
- attrs: {
- type: "module",
- src: path.posix.join(base, CLIENT_PUBLIC_PATH)
- },
- injectTo: "head-prepend"
- }]
- };
-};
-function indexHtmlMiddleware(root, server) {
- const isDev = isDevServer(server);
- return async function viteIndexHtmlMiddleware(req$4, res, next) {
- if (res.writableEnded) return next();
- const url$3 = req$4.url && cleanUrl(req$4.url);
- if (url$3?.endsWith(".html") && req$4.headers["sec-fetch-dest"] !== "script") {
- let filePath;
- if (isDev && url$3.startsWith(FS_PREFIX)) filePath = decodeURIComponent(fsPathFromId(url$3));
- else filePath = normalizePath(path.resolve(path.join(root, decodeURIComponent(url$3))));
- if (isDev) {
- const servingAccessResult = checkLoadingAccess(server.config, filePath);
- if (servingAccessResult === "denied") return respondWithAccessDenied(filePath, server, res);
- if (servingAccessResult === "fallback") return next();
- } else if (!isParentDirectory(root, filePath)) return next();
- if (fs.existsSync(filePath)) {
- const headers = isDev ? server.config.server.headers : server.config.preview.headers;
- try {
- let html = await fsp.readFile(filePath, "utf-8");
- if (isDev) html = await server.transformIndexHtml(url$3, html, req$4.originalUrl);
- return send(req$4, res, html, "html", { headers });
- } catch (e$1) {
- return next(e$1);
- }
- }
- }
- next();
- };
-}
-function preTransformRequest(server, decodedUrl, decodedBase) {
- if (!server.config.server.preTransformRequests) return;
- decodedUrl = unwrapId(stripBase(decodedUrl, decodedBase));
- server.warmupRequest(decodedUrl);
-}
-
-//#endregion
-//#region src/node/server/middlewares/time.ts
-const logTime = createDebugger("vite:time");
-function timeMiddleware(root) {
- return function viteTimeMiddleware(req$4, res, next) {
- const start = performance$1.now();
- const end = res.end;
- res.end = (...args) => {
- logTime?.(`${timeFrom(start)} ${prettifyUrl(req$4.url, root)}`);
- return end.call(res, ...args);
- };
- next();
- };
-}
-
-//#endregion
-//#region src/node/server/mixedModuleGraph.ts
-/**
-* Backward compatible ModuleNode and ModuleGraph with mixed nodes from both the client and ssr environments
-* It would be good to take the types names for the new EnvironmentModuleNode and EnvironmentModuleGraph but we can't
-* do that at this point without breaking to much code in the ecosystem.
-* We are going to deprecate these types and we can try to use them back in the future.
-*/
-const EMPTY_OBJECT$1 = Object.freeze({});
-var ModuleNode = class {
- _moduleGraph;
- _clientModule;
- _ssrModule;
- constructor(moduleGraph, clientModule, ssrModule) {
- this._moduleGraph = moduleGraph;
- this._clientModule = clientModule;
- this._ssrModule = ssrModule;
- }
- _get(prop) {
- return this._clientModule?.[prop] ?? this._ssrModule?.[prop];
- }
- _set(prop, value$1) {
- if (this._clientModule) this._clientModule[prop] = value$1;
- if (this._ssrModule) this._ssrModule[prop] = value$1;
- }
- _wrapModuleSet(prop, module$1) {
- if (!module$1) return /* @__PURE__ */ new Set();
- return createBackwardCompatibleModuleSet(this._moduleGraph, prop, module$1);
- }
- _getModuleSetUnion(prop) {
- const importedModules = /* @__PURE__ */ new Set();
- const ids = /* @__PURE__ */ new Set();
- if (this._clientModule) for (const mod of this._clientModule[prop]) {
- if (mod.id) ids.add(mod.id);
- importedModules.add(this._moduleGraph.getBackwardCompatibleModuleNode(mod));
- }
- if (this._ssrModule) {
- for (const mod of this._ssrModule[prop]) if (mod.id && !ids.has(mod.id)) importedModules.add(this._moduleGraph.getBackwardCompatibleModuleNode(mod));
- }
- return importedModules;
- }
- _getModuleInfoUnion(prop) {
- const _clientValue = this._clientModule?.[prop];
- const _ssrValue = this._ssrModule?.[prop];
- if (_clientValue == null && _ssrValue == null) return void 0;
- return new Proxy({}, { get: (_, key) => {
- if (key === "meta") return this.meta || EMPTY_OBJECT$1;
- if (_clientValue) {
- if (key in _clientValue) return _clientValue[key];
- }
- if (_ssrValue) {
- if (key in _ssrValue) return _ssrValue[key];
- }
- } });
- }
- _getModuleObjectUnion(prop) {
- const _clientValue = this._clientModule?.[prop];
- const _ssrValue = this._ssrModule?.[prop];
- if (_clientValue == null && _ssrValue == null) return void 0;
- const info = {};
- if (_ssrValue) Object.assign(info, _ssrValue);
- if (_clientValue) Object.assign(info, _clientValue);
- return info;
- }
- get url() {
- return this._get("url");
- }
- set url(value$1) {
- this._set("url", value$1);
- }
- get id() {
- return this._get("id");
- }
- set id(value$1) {
- this._set("id", value$1);
- }
- get file() {
- return this._get("file");
- }
- set file(value$1) {
- this._set("file", value$1);
- }
- get type() {
- return this._get("type");
- }
- get info() {
- return this._getModuleInfoUnion("info");
- }
- get meta() {
- return this._getModuleObjectUnion("meta");
- }
- get importers() {
- return this._getModuleSetUnion("importers");
- }
- get clientImportedModules() {
- return this._wrapModuleSet("importedModules", this._clientModule);
- }
- get ssrImportedModules() {
- return this._wrapModuleSet("importedModules", this._ssrModule);
- }
- get importedModules() {
- return this._getModuleSetUnion("importedModules");
- }
- get acceptedHmrDeps() {
- return this._wrapModuleSet("acceptedHmrDeps", this._clientModule);
- }
- get acceptedHmrExports() {
- return this._clientModule?.acceptedHmrExports ?? null;
- }
- get importedBindings() {
- return this._clientModule?.importedBindings ?? null;
- }
- get isSelfAccepting() {
- return this._clientModule?.isSelfAccepting;
- }
- get transformResult() {
- return this._clientModule?.transformResult ?? null;
- }
- set transformResult(value$1) {
- if (this._clientModule) this._clientModule.transformResult = value$1;
- }
- get ssrTransformResult() {
- return this._ssrModule?.transformResult ?? null;
- }
- set ssrTransformResult(value$1) {
- if (this._ssrModule) this._ssrModule.transformResult = value$1;
- }
- get ssrModule() {
- return this._ssrModule?.ssrModule ?? null;
- }
- get ssrError() {
- return this._ssrModule?.ssrError ?? null;
- }
- get lastHMRTimestamp() {
- return Math.max(this._clientModule?.lastHMRTimestamp ?? 0, this._ssrModule?.lastHMRTimestamp ?? 0);
- }
- set lastHMRTimestamp(value$1) {
- if (this._clientModule) this._clientModule.lastHMRTimestamp = value$1;
- if (this._ssrModule) this._ssrModule.lastHMRTimestamp = value$1;
- }
- get lastInvalidationTimestamp() {
- return Math.max(this._clientModule?.lastInvalidationTimestamp ?? 0, this._ssrModule?.lastInvalidationTimestamp ?? 0);
- }
- get invalidationState() {
- return this._clientModule?.invalidationState;
- }
- get ssrInvalidationState() {
- return this._ssrModule?.invalidationState;
- }
-};
-function mapIterator(iterable, transform$2) {
- return {
- [Symbol.iterator]() {
- return this;
- },
- next() {
- const r$1 = iterable.next();
- return r$1.done ? r$1 : {
- value: transform$2(r$1.value),
- done: false
- };
- }
- };
-}
-var ModuleGraph = class {
- /** @internal */
- _moduleGraphs;
- /** @internal */
- get _client() {
- return this._moduleGraphs.client();
- }
- /** @internal */
- get _ssr() {
- return this._moduleGraphs.ssr();
- }
- urlToModuleMap;
- idToModuleMap;
- etagToModuleMap;
- fileToModulesMap;
- moduleNodeCache = new DualWeakMap();
- constructor(moduleGraphs) {
- this._moduleGraphs = moduleGraphs;
- const getModuleMapUnion = (prop) => () => {
- if (this._ssr[prop].size === 0) return this._client[prop];
- const map$1 = new Map(this._client[prop]);
- for (const [key, module$1] of this._ssr[prop]) if (!map$1.has(key)) map$1.set(key, module$1);
- return map$1;
- };
- this.urlToModuleMap = createBackwardCompatibleModuleMap(this, "urlToModuleMap", getModuleMapUnion("urlToModuleMap"));
- this.idToModuleMap = createBackwardCompatibleModuleMap(this, "idToModuleMap", getModuleMapUnion("idToModuleMap"));
- this.etagToModuleMap = createBackwardCompatibleModuleMap(this, "etagToModuleMap", () => this._client.etagToModuleMap);
- this.fileToModulesMap = createBackwardCompatibleFileToModulesMap(this);
- }
- getModuleById(id) {
- const clientModule = this._client.getModuleById(id);
- const ssrModule = this._ssr.getModuleById(id);
- if (!clientModule && !ssrModule) return;
- return this.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
- }
- async getModuleByUrl(url$3, _ssr) {
- const [clientModule, ssrModule] = await Promise.all([this._client.getModuleByUrl(url$3), this._ssr.getModuleByUrl(url$3)]);
- if (!clientModule && !ssrModule) return;
- return this.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
- }
- getModulesByFile(file) {
- const clientModules = this._client.getModulesByFile(file);
- const ssrModules = this._ssr.getModulesByFile(file);
- if (!clientModules && !ssrModules) return;
- const result = /* @__PURE__ */ new Set();
- if (clientModules) for (const mod of clientModules) result.add(this.getBackwardCompatibleBrowserModuleNode(mod));
- if (ssrModules) {
- for (const mod of ssrModules) if (mod.id == null || !this._client.getModuleById(mod.id)) result.add(this.getBackwardCompatibleServerModuleNode(mod));
- }
- return result;
- }
- onFileChange(file) {
- this._client.onFileChange(file);
- this._ssr.onFileChange(file);
- }
- onFileDelete(file) {
- this._client.onFileDelete(file);
- this._ssr.onFileDelete(file);
- }
- /** @internal */
- _getModuleGraph(environment) {
- switch (environment) {
- case "client": return this._client;
- case "ssr": return this._ssr;
- default: throw new Error(`Invalid module node environment ${environment}`);
- }
- }
- invalidateModule(mod, seen$1 = /* @__PURE__ */ new Set(), timestamp = monotonicDateNow(), isHmr = false, softInvalidate = false) {
- if (mod._clientModule) this._client.invalidateModule(mod._clientModule, new Set([...seen$1].map((mod$1) => mod$1._clientModule).filter(Boolean)), timestamp, isHmr, softInvalidate);
- if (mod._ssrModule) this._ssr.invalidateModule(mod._ssrModule, new Set([...seen$1].map((mod$1) => mod$1._ssrModule).filter(Boolean)), timestamp, isHmr, softInvalidate);
- }
- invalidateAll() {
- this._client.invalidateAll();
- this._ssr.invalidateAll();
- }
- async ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true) {
- const module$1 = await (ssr ? this._ssr : this._client).ensureEntryFromUrl(rawUrl, setIsSelfAccepting);
- return this.getBackwardCompatibleModuleNode(module$1);
- }
- createFileOnlyEntry(file) {
- const clientModule = this._client.createFileOnlyEntry(file);
- const ssrModule = this._ssr.createFileOnlyEntry(file);
- return this.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
- }
- async resolveUrl(url$3, ssr) {
- return ssr ? this._ssr.resolveUrl(url$3) : this._client.resolveUrl(url$3);
- }
- updateModuleTransformResult(mod, result, ssr) {
- const environment = ssr ? "ssr" : "client";
- this._getModuleGraph(environment).updateModuleTransformResult(environment === "client" ? mod._clientModule : mod._ssrModule, result);
- }
- getModuleByEtag(etag$1) {
- const mod = this._client.etagToModuleMap.get(etag$1);
- return mod && this.getBackwardCompatibleBrowserModuleNode(mod);
- }
- getBackwardCompatibleBrowserModuleNode(clientModule) {
- return this.getBackwardCompatibleModuleNodeDual(clientModule, clientModule.id ? this._ssr.getModuleById(clientModule.id) : void 0);
- }
- getBackwardCompatibleServerModuleNode(ssrModule) {
- return this.getBackwardCompatibleModuleNodeDual(ssrModule.id ? this._client.getModuleById(ssrModule.id) : void 0, ssrModule);
- }
- getBackwardCompatibleModuleNode(mod) {
- return mod.environment === "client" ? this.getBackwardCompatibleBrowserModuleNode(mod) : this.getBackwardCompatibleServerModuleNode(mod);
- }
- getBackwardCompatibleModuleNodeDual(clientModule, ssrModule) {
- const cached = this.moduleNodeCache.get(clientModule, ssrModule);
- if (cached) return cached;
- const moduleNode = new ModuleNode(this, clientModule, ssrModule);
- this.moduleNodeCache.set(clientModule, ssrModule, moduleNode);
- return moduleNode;
- }
-};
-var DualWeakMap = class {
- map = /* @__PURE__ */ new WeakMap();
- undefinedKey = {};
- get(key1, key2) {
- const k1 = key1 ?? this.undefinedKey;
- const k2 = key2 ?? this.undefinedKey;
- return this.map.get(k1)?.get(k2);
- }
- set(key1, key2, value$1) {
- const k1 = key1 ?? this.undefinedKey;
- const k2 = key2 ?? this.undefinedKey;
- if (!this.map.has(k1)) this.map.set(k1, /* @__PURE__ */ new Map());
- this.map.get(k1).set(k2, value$1);
- }
-};
-function createBackwardCompatibleModuleSet(moduleGraph, prop, module$1) {
- return {
- [Symbol.iterator]() {
- return this.keys();
- },
- has(key) {
- if (!key.id) return false;
- const keyModule = moduleGraph._getModuleGraph(module$1.environment).getModuleById(key.id);
- return keyModule !== void 0 && module$1[prop].has(keyModule);
- },
- values() {
- return this.keys();
- },
- keys() {
- return mapIterator(module$1[prop].keys(), (mod) => moduleGraph.getBackwardCompatibleModuleNode(mod));
- },
- get size() {
- return module$1[prop].size;
- },
- forEach(callback, thisArg) {
- return module$1[prop].forEach((mod) => {
- const backwardCompatibleMod = moduleGraph.getBackwardCompatibleModuleNode(mod);
- callback.call(thisArg, backwardCompatibleMod, backwardCompatibleMod, this);
- });
- }
- };
-}
-function createBackwardCompatibleModuleMap(moduleGraph, prop, getModuleMap) {
- return {
- [Symbol.iterator]() {
- return this.entries();
- },
- get(key) {
- const clientModule = moduleGraph._client[prop].get(key);
- const ssrModule = moduleGraph._ssr[prop].get(key);
- if (!clientModule && !ssrModule) return;
- return moduleGraph.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
- },
- set(key, mod) {
- const clientModule = mod._clientModule;
- if (clientModule) moduleGraph._client[prop].set(key, clientModule);
- const ssrModule = mod._ssrModule;
- if (ssrModule) moduleGraph._ssr[prop].set(key, ssrModule);
- },
- keys() {
- return getModuleMap().keys();
- },
- values() {
- return mapIterator(getModuleMap().values(), (mod) => moduleGraph.getBackwardCompatibleModuleNode(mod));
- },
- entries() {
- return mapIterator(getModuleMap().entries(), ([key, mod]) => [key, moduleGraph.getBackwardCompatibleModuleNode(mod)]);
- },
- get size() {
- return getModuleMap().size;
- },
- forEach(callback, thisArg) {
- return getModuleMap().forEach((mod, key) => {
- const backwardCompatibleMod = moduleGraph.getBackwardCompatibleModuleNode(mod);
- callback.call(thisArg, backwardCompatibleMod, key, this);
- });
- }
- };
-}
-function createBackwardCompatibleFileToModulesMap(moduleGraph) {
- const getFileToModulesMap = () => {
- if (!moduleGraph._ssr.fileToModulesMap.size) return moduleGraph._client.fileToModulesMap;
- const map$1 = new Map(moduleGraph._client.fileToModulesMap);
- for (const [key, modules] of moduleGraph._ssr.fileToModulesMap) {
- const modulesSet = map$1.get(key);
- if (!modulesSet) map$1.set(key, modules);
- else for (const ssrModule of modules) {
- let hasModule = false;
- for (const clientModule of modulesSet) {
- hasModule ||= clientModule.id === ssrModule.id;
- if (hasModule) break;
- }
- if (!hasModule) modulesSet.add(ssrModule);
- }
- }
- return map$1;
- };
- const getBackwardCompatibleModules = (modules) => new Set([...modules].map((mod) => moduleGraph.getBackwardCompatibleModuleNode(mod)));
- return {
- [Symbol.iterator]() {
- return this.entries();
- },
- get(key) {
- const clientModules = moduleGraph._client.fileToModulesMap.get(key);
- const ssrModules = moduleGraph._ssr.fileToModulesMap.get(key);
- if (!clientModules && !ssrModules) return;
- const modules = clientModules ?? /* @__PURE__ */ new Set();
- if (ssrModules) {
- for (const ssrModule of ssrModules) if (ssrModule.id) {
- let found$1 = false;
- for (const mod of modules) {
- found$1 ||= mod.id === ssrModule.id;
- if (found$1) break;
- }
- if (!found$1) modules.add(ssrModule);
- }
- }
- return getBackwardCompatibleModules(modules);
- },
- keys() {
- return getFileToModulesMap().keys();
- },
- values() {
- return mapIterator(getFileToModulesMap().values(), getBackwardCompatibleModules);
- },
- entries() {
- return mapIterator(getFileToModulesMap().entries(), ([key, modules]) => [key, getBackwardCompatibleModules(modules)]);
- },
- get size() {
- return getFileToModulesMap().size;
- },
- forEach(callback, thisArg) {
- return getFileToModulesMap().forEach((modules, key) => {
- callback.call(thisArg, getBackwardCompatibleModules(modules), key, this);
- });
- }
- };
-}
-
-//#endregion
-//#region src/node/server/middlewares/notFound.ts
-function notFoundMiddleware() {
- return function vite404Middleware(_, res) {
- res.statusCode = 404;
- res.end();
- };
-}
-
-//#endregion
-//#region src/node/server/searchRoot.ts
-const ROOT_FILES = ["pnpm-workspace.yaml", "lerna.json"];
-function hasWorkspacePackageJSON(root) {
- const path$13 = join(root, "package.json");
- if (!isFileReadable(path$13)) return false;
- try {
- return !!(JSON.parse(fs.readFileSync(path$13, "utf-8")) || {}).workspaces;
- } catch {
- return false;
- }
-}
-function hasRootFile(root) {
- return ROOT_FILES.some((file) => fs.existsSync(join(root, file)));
-}
-function hasPackageJSON(root) {
- const path$13 = join(root, "package.json");
- return fs.existsSync(path$13);
-}
-/**
-* Search up for the nearest `package.json`
-*/
-function searchForPackageRoot(current, root = current) {
- if (hasPackageJSON(current)) return current;
- const dir = dirname(current);
- if (!dir || dir === current) return root;
- return searchForPackageRoot(dir, root);
-}
-/**
-* Search up for the nearest workspace root
-*/
-function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
- if (hasRootFile(current)) return current;
- if (hasWorkspacePackageJSON(current)) return current;
- const dir = dirname(current);
- if (!dir || dir === current) return root;
- return searchForWorkspaceRoot(dir, root);
-}
-
-//#endregion
-//#region src/node/server/middlewares/hostCheck.ts
-function getAdditionalAllowedHosts(resolvedServerOptions, resolvedPreviewOptions) {
- const list = [];
- if (typeof resolvedServerOptions.host === "string" && resolvedServerOptions.host) list.push(resolvedServerOptions.host);
- if (typeof resolvedServerOptions.hmr === "object" && resolvedServerOptions.hmr.host) list.push(resolvedServerOptions.hmr.host);
- if (typeof resolvedPreviewOptions.host === "string" && resolvedPreviewOptions.host) list.push(resolvedPreviewOptions.host);
- if (resolvedServerOptions.origin) try {
- const serverOriginUrl = new URL(resolvedServerOptions.origin);
- list.push(serverOriginUrl.hostname);
- } catch {}
- return list;
-}
-function hostValidationMiddleware(allowedHosts, isPreview) {
- return hostValidationMiddleware$1({
- allowedHosts: Object.freeze([...allowedHosts]),
- generateErrorMessage(hostname) {
- const hostnameWithQuotes = JSON.stringify(hostname);
- return `Blocked request. This host (${hostnameWithQuotes}) is not allowed.\nTo allow this host, add ${hostnameWithQuotes} to \`${`${isPreview ? "preview" : "server"}.allowedHosts`}\` in vite.config.js.`;
- }
- });
-}
-
-//#endregion
-//#region src/node/server/middlewares/rejectInvalidRequest.ts
-function rejectInvalidRequestMiddleware() {
- return function viteRejectInvalidRequestMiddleware(req$4, res, next) {
- if (req$4.url?.includes("#")) {
- res.writeHead(400);
- res.end();
- return;
- }
- return next();
- };
-}
-
-//#endregion
-//#region src/node/server/index.ts
-var import_connect$1 = /* @__PURE__ */ __toESM(require_connect(), 1);
-var import_lib$1 = /* @__PURE__ */ __toESM(require_lib$1(), 1);
-var import_picocolors$16 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-var import_chokidar = /* @__PURE__ */ __toESM(require_chokidar(), 1);
-var import_launch_editor_middleware = /* @__PURE__ */ __toESM(require_launch_editor_middleware(), 1);
-const usedConfigs = /* @__PURE__ */ new WeakSet();
-function createServer$2(inlineConfig = {}) {
- return _createServer(inlineConfig, { listen: true });
-}
-async function _createServer(inlineConfig = {}, options$1) {
- const config$2 = isResolvedConfig(inlineConfig) ? inlineConfig : await resolveConfig(inlineConfig, "serve");
- if (usedConfigs.has(config$2)) throw new Error(`There is already a server associated with the config.`);
- if (config$2.command !== "serve") throw new Error(`Config was resolved for a "build", expected a "serve" command.`);
- usedConfigs.add(config$2);
- const initPublicFilesPromise = initPublicFiles(config$2);
- const { root, server: serverConfig } = config$2;
- const httpsOptions = await resolveHttpsConfig(config$2.server.https);
- const { middlewareMode } = serverConfig;
- const resolvedOutDirs = getResolvedOutDirs(config$2.root, config$2.build.outDir, config$2.build.rollupOptions.output);
- const emptyOutDir = resolveEmptyOutDir(config$2.build.emptyOutDir, config$2.root, resolvedOutDirs);
- const resolvedWatchOptions = resolveChokidarOptions({
- disableGlobbing: true,
- ...serverConfig.watch
- }, resolvedOutDirs, emptyOutDir, config$2.cacheDir);
- const middlewares = (0, import_connect$1.default)();
- const httpServer = middlewareMode ? null : await resolveHttpServer(middlewares, httpsOptions);
- const ws = createWebSocketServer(httpServer, config$2, httpsOptions);
- const publicFiles = await initPublicFilesPromise;
- const { publicDir } = config$2;
- if (httpServer) setClientErrorHandler(httpServer, config$2.logger);
- const watcher = serverConfig.watch !== null ? import_chokidar.watch([
- root,
- ...config$2.configFileDependencies,
- ...getEnvFilesForMode(config$2.mode, config$2.envDir),
- ...publicDir && publicFiles ? [publicDir] : []
- ], resolvedWatchOptions) : createNoopWatcher(resolvedWatchOptions);
- const environments = {};
- await Promise.all(Object.entries(config$2.environments).map(async ([name, environmentOptions]) => {
- const environment = await environmentOptions.dev.createEnvironment(name, config$2, { ws });
- environments[name] = environment;
- const previousInstance = options$1.previousEnvironments?.[environment.name];
- await environment.init({
- watcher,
- previousInstance
- });
- }));
- let moduleGraph = new ModuleGraph({
- client: () => environments.client.moduleGraph,
- ssr: () => environments.ssr.moduleGraph
- });
- let pluginContainer = createPluginContainer(environments);
- const closeHttpServer = createServerCloseFn(httpServer);
- const devHtmlTransformFn = createDevHtmlTransformFn(config$2);
- let closeServerPromise;
- const closeServer = async () => {
- if (!middlewareMode) teardownSIGTERMListener(closeServerAndExit);
- await Promise.allSettled([
- watcher.close(),
- ws.close(),
- Promise.allSettled(Object.values(server.environments).map((environment) => environment.close())),
- closeHttpServer(),
- server._ssrCompatModuleRunner?.close()
- ]);
- server.resolvedUrls = null;
- server._ssrCompatModuleRunner = void 0;
- };
- let hot = ws;
- let server = {
- config: config$2,
- middlewares,
- httpServer,
- watcher,
- ws,
- get hot() {
- warnFutureDeprecation(config$2, "removeServerHot");
- return hot;
- },
- set hot(h) {
- hot = h;
- },
- environments,
- get pluginContainer() {
- warnFutureDeprecation(config$2, "removeServerPluginContainer");
- return pluginContainer;
- },
- set pluginContainer(p) {
- pluginContainer = p;
- },
- get moduleGraph() {
- warnFutureDeprecation(config$2, "removeServerModuleGraph");
- return moduleGraph;
- },
- set moduleGraph(graph) {
- moduleGraph = graph;
- },
- resolvedUrls: null,
- ssrTransform(code, inMap, url$3, originalCode = code) {
- return ssrTransform(code, inMap, url$3, originalCode, { json: { stringify: config$2.json.stringify === true && config$2.json.namedExports !== true } });
- },
- transformRequest(url$3, options$2) {
- warnFutureDeprecation(config$2, "removeServerTransformRequest");
- return server.environments[options$2?.ssr ? "ssr" : "client"].transformRequest(url$3);
- },
- warmupRequest(url$3, options$2) {
- warnFutureDeprecation(config$2, "removeServerWarmupRequest");
- return server.environments[options$2?.ssr ? "ssr" : "client"].warmupRequest(url$3);
- },
- transformIndexHtml(url$3, html, originalUrl) {
- return devHtmlTransformFn(server, url$3, html, originalUrl);
- },
- async ssrLoadModule(url$3, opts) {
- warnFutureDeprecation(config$2, "removeSsrLoadModule");
- return ssrLoadModule(url$3, server, opts?.fixStacktrace);
- },
- ssrFixStacktrace(e$1) {
- warnFutureDeprecation(config$2, "removeSsrLoadModule", "ssrFixStacktrace doesn't need to be used for Environment Module Runners.");
- ssrFixStacktrace(e$1, server.environments.ssr.moduleGraph);
- },
- ssrRewriteStacktrace(stack) {
- warnFutureDeprecation(config$2, "removeSsrLoadModule", "ssrRewriteStacktrace doesn't need to be used for Environment Module Runners.");
- return ssrRewriteStacktrace(stack, server.environments.ssr.moduleGraph);
- },
- async reloadModule(module$1) {
- warnFutureDeprecation(config$2, "removeServerReloadModule");
- if (serverConfig.hmr !== false && module$1.file) {
- const environmentModule = module$1._clientModule ?? module$1._ssrModule;
- updateModules(environments[environmentModule.environment], module$1.file, [environmentModule], monotonicDateNow());
- }
- },
- async listen(port, isRestart) {
- const hostname = await resolveHostname(config$2.server.host);
- if (httpServer) httpServer.prependListener("listening", () => {
- server.resolvedUrls = resolveServerUrls(httpServer, config$2.server, hostname, httpsOptions, config$2);
- });
- await startServer(server, hostname, port);
- if (httpServer) {
- if (!isRestart && config$2.server.open) server.openBrowser();
- }
- return server;
- },
- openBrowser() {
- const options$2 = server.config.server;
- const url$3 = getServerUrlByHost(server.resolvedUrls, options$2.host);
- if (url$3) {
- const path$13 = typeof options$2.open === "string" ? new URL(options$2.open, url$3).href : url$3;
- if (server.config.server.preTransformRequests) setTimeout(() => {
- (path$13.startsWith("https:") ? get$1 : get)(path$13, { headers: { Accept: "text/html" } }, (res) => {
- res.on("end", () => {});
- }).on("error", () => {}).end();
- }, 0);
- openBrowser(path$13, true, server.config.logger);
- } else server.config.logger.warn("No URL available to open in browser");
- },
- async close() {
- if (!closeServerPromise) closeServerPromise = closeServer();
- return closeServerPromise;
- },
- printUrls() {
- if (server.resolvedUrls) printServerUrls(server.resolvedUrls, serverConfig.host, config$2.logger.info);
- else if (middlewareMode) throw new Error("cannot print server URLs in middleware mode.");
- else throw new Error("cannot print server URLs before server.listen is called.");
- },
- bindCLIShortcuts(options$2) {
- bindCLIShortcuts(server, options$2);
- },
- async restart(forceOptimize) {
- if (!server._restartPromise) {
- server._forceOptimizeOnRestart = !!forceOptimize;
- server._restartPromise = restartServer(server).finally(() => {
- server._restartPromise = null;
- server._forceOptimizeOnRestart = false;
- });
- }
- return server._restartPromise;
- },
- waitForRequestsIdle(ignoredId) {
- return environments.client.waitForRequestsIdle(ignoredId);
- },
- _setInternalServer(_server) {
- server = _server;
- },
- _restartPromise: null,
- _forceOptimizeOnRestart: false,
- _shortcutsState: options$1.previousShortcutsState
- };
- const reflexServer = new Proxy(server, {
- get: (_, property) => {
- return server[property];
- },
- set: (_, property, value$1) => {
- server[property] = value$1;
- return true;
- }
- });
- const closeServerAndExit = async (_, exitCode) => {
- try {
- await server.close();
- } finally {
- process.exitCode ??= exitCode ? 128 + exitCode : void 0;
- process.exit();
- }
- };
- if (!middlewareMode) setupSIGTERMListener(closeServerAndExit);
- const onHMRUpdate = async (type, file) => {
- if (serverConfig.hmr !== false) await handleHMRUpdate(type, file, server);
- };
- const onFileAddUnlink = async (file, isUnlink) => {
- file = normalizePath(file);
- reloadOnTsconfigChange(server, file);
- await Promise.all(Object.values(server.environments).map((environment) => environment.pluginContainer.watchChange(file, { event: isUnlink ? "delete" : "create" })));
- if (publicDir && publicFiles) {
- if (file.startsWith(publicDir)) {
- const path$13 = file.slice(publicDir.length);
- publicFiles[isUnlink ? "delete" : "add"](path$13);
- if (!isUnlink) {
- const clientModuleGraph = server.environments.client.moduleGraph;
- const etag$1 = (await clientModuleGraph.getModuleByUrl(path$13))?.transformResult?.etag;
- if (etag$1) clientModuleGraph.etagToModuleMap.delete(etag$1);
- }
- }
- }
- if (isUnlink) for (const environment of Object.values(server.environments)) environment.moduleGraph.onFileDelete(file);
- await onHMRUpdate(isUnlink ? "delete" : "create", file);
- };
- watcher.on("change", async (file) => {
- file = normalizePath(file);
- reloadOnTsconfigChange(server, file);
- await Promise.all(Object.values(server.environments).map((environment) => environment.pluginContainer.watchChange(file, { event: "update" })));
- for (const environment of Object.values(server.environments)) environment.moduleGraph.onFileChange(file);
- await onHMRUpdate("update", file);
- });
- watcher.on("add", (file) => {
- onFileAddUnlink(file, false);
- });
- watcher.on("unlink", (file) => {
- onFileAddUnlink(file, true);
- });
- if (!middlewareMode && httpServer) httpServer.once("listening", () => {
- serverConfig.port = httpServer.address().port;
- });
- if (process.env.DEBUG) middlewares.use(timeMiddleware(root));
- middlewares.use(rejectInvalidRequestMiddleware());
- const { cors } = serverConfig;
- if (cors !== false) middlewares.use((0, import_lib$1.default)(typeof cors === "boolean" ? {} : cors));
- const { allowedHosts } = serverConfig;
- if (allowedHosts !== true && !serverConfig.https) middlewares.use(hostValidationMiddleware(allowedHosts, false));
- const configureServerContext = new BasicMinimalPluginContext({
- ...basePluginContextMeta,
- watchMode: true
- }, config$2.logger);
- const postHooks = [];
- for (const hook of config$2.getSortedPluginHooks("configureServer")) postHooks.push(await hook.call(configureServerContext, reflexServer));
- middlewares.use(cachedTransformMiddleware(server));
- const { proxy } = serverConfig;
- if (proxy) {
- const middlewareServer = (isObject(middlewareMode) ? middlewareMode.server : null) || httpServer;
- middlewares.use(proxyMiddleware(middlewareServer, proxy, config$2));
- }
- if (config$2.base !== "/") middlewares.use(baseMiddleware(config$2.rawBase, !!middlewareMode));
- middlewares.use("/__open-in-editor", (0, import_launch_editor_middleware.default)());
- middlewares.use(function viteHMRPingMiddleware(req$4, res, next) {
- if (req$4.headers["accept"] === "text/x-vite-ping") res.writeHead(204).end();
- else next();
- });
- if (publicDir) middlewares.use(servePublicMiddleware(server, publicFiles));
- middlewares.use(transformMiddleware(server));
- middlewares.use(serveRawFsMiddleware(server));
- middlewares.use(serveStaticMiddleware(server));
- if (config$2.appType === "spa" || config$2.appType === "mpa") middlewares.use(htmlFallbackMiddleware(root, config$2.appType === "spa"));
- postHooks.forEach((fn) => fn && fn());
- if (config$2.appType === "spa" || config$2.appType === "mpa") {
- middlewares.use(indexHtmlMiddleware(root, server));
- middlewares.use(notFoundMiddleware());
- }
- middlewares.use(errorMiddleware(server, !!middlewareMode));
- let initingServer;
- let serverInited = false;
- const initServer = async (onListen) => {
- if (serverInited) return;
- if (initingServer) return initingServer;
- initingServer = (async function() {
- await environments.client.pluginContainer.buildStart();
- if (onListen || options$1.listen) await Promise.all(Object.values(environments).map((e$1) => e$1.listen(server)));
- initingServer = void 0;
- serverInited = true;
- })();
- return initingServer;
- };
- if (!middlewareMode && httpServer) {
- const listen = httpServer.listen.bind(httpServer);
- httpServer.listen = (async (port, ...args) => {
- try {
- await initServer(true);
- } catch (e$1) {
- httpServer.emit("error", e$1);
- return;
- }
- return listen(port, ...args);
- });
- } else await initServer(false);
- return server;
-}
-async function startServer(server, hostname, inlinePort) {
- const httpServer = server.httpServer;
- if (!httpServer) throw new Error("Cannot call server.listen in middleware mode.");
- const options$1 = server.config.server;
- const configPort = inlinePort ?? options$1.port;
- const port = (!configPort || configPort === server._configServerPort ? server._currentServerPort : configPort) ?? DEFAULT_DEV_PORT;
- server._configServerPort = configPort;
- server._currentServerPort = await httpServerStart(httpServer, {
- port,
- strictPort: options$1.strictPort,
- host: hostname.host,
- logger: server.config.logger
- });
-}
-function createServerCloseFn(server) {
- if (!server) return () => Promise.resolve();
- let hasListened = false;
- const openSockets = /* @__PURE__ */ new Set();
- server.on("connection", (socket) => {
- openSockets.add(socket);
- socket.on("close", () => {
- openSockets.delete(socket);
- });
- });
- server.once("listening", () => {
- hasListened = true;
- });
- return () => new Promise((resolve$4, reject) => {
- openSockets.forEach((s) => s.destroy());
- if (hasListened) server.close((err$2) => {
- if (err$2) reject(err$2);
- else resolve$4();
- });
- else resolve$4();
- });
-}
-function resolvedAllowDir(root, dir) {
- return normalizePath(path.resolve(root, dir));
-}
-const _serverConfigDefaults = Object.freeze({
- port: DEFAULT_DEV_PORT,
- strictPort: false,
- host: "localhost",
- allowedHosts: [],
- https: void 0,
- open: false,
- proxy: void 0,
- cors: { origin: defaultAllowedOrigins },
- headers: {},
- warmup: {
- clientFiles: [],
- ssrFiles: []
- },
- middlewareMode: false,
- fs: {
- strict: true,
- deny: [
- ".env",
- ".env.*",
- "*.{crt,pem}",
- "**/.git/**"
- ]
- },
- preTransformRequests: true,
- perEnvironmentStartEndDuringDev: false,
- perEnvironmentWatchChangeDuringDev: false
-});
-const serverConfigDefaults = _serverConfigDefaults;
-function resolveServerOptions(root, raw, logger) {
- const _server = mergeWithDefaults({
- ..._serverConfigDefaults,
- host: void 0,
- sourcemapIgnoreList: isInNodeModules
- }, raw ?? {});
- const server = {
- ..._server,
- fs: {
- ..._server.fs,
- allow: raw?.fs?.allow ?? [searchForWorkspaceRoot(root)]
- },
- sourcemapIgnoreList: _server.sourcemapIgnoreList === false ? () => false : _server.sourcemapIgnoreList
- };
- let allowDirs = server.fs.allow;
- if (process.versions.pnp) {
- const cwd = searchForPackageRoot(root);
- try {
- const yarnCacheDir = execSync(`yarn config get ${execSync("yarn config get enableGlobalCache", { cwd }).toString().trim() === "true" ? "globalFolder" : "cacheFolder"}`, { cwd }).toString().trim();
- allowDirs.push(yarnCacheDir);
- } catch (e$1) {
- logger.warn(`Get yarn cache dir error: ${e$1.message}`, { timestamp: true });
- }
- }
- allowDirs = allowDirs.map((i$1) => resolvedAllowDir(root, i$1));
- const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR);
- if (!allowDirs.some((dir) => isParentDirectory(dir, resolvedClientDir))) allowDirs.push(resolvedClientDir);
- server.fs.allow = allowDirs;
- if (server.origin?.endsWith("/")) {
- server.origin = server.origin.slice(0, -1);
- logger.warn(import_picocolors$16.default.yellow(`${import_picocolors$16.default.bold("(!)")} server.origin should not end with "/". Using "${server.origin}" instead.`));
- }
- if (process.env.__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS && Array.isArray(server.allowedHosts)) {
- const additionalHost = process.env.__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS;
- server.allowedHosts = [...server.allowedHosts, additionalHost];
- }
- return server;
-}
-async function restartServer(server) {
- global.__vite_start_time = performance$1.now();
- let inlineConfig = server.config.inlineConfig;
- if (server._forceOptimizeOnRestart) inlineConfig = mergeConfig(inlineConfig, { forceOptimizeDeps: true });
- {
- let newServer = null;
- try {
- newServer = await _createServer(inlineConfig, {
- listen: false,
- previousEnvironments: server.environments,
- previousShortcutsState: server._shortcutsState
- });
- } catch (err$2) {
- server.config.logger.error(err$2.message, { timestamp: true });
- server.config.logger.error("server restart failed", { timestamp: true });
- return;
- }
- server._shortcutsState = void 0;
- await server.close();
- const middlewares = server.middlewares;
- newServer._configServerPort = server._configServerPort;
- newServer._currentServerPort = server._currentServerPort;
- Object.assign(server, newServer);
- middlewares.stack = newServer.middlewares.stack;
- server.middlewares = middlewares;
- newServer._setInternalServer(server);
- }
- const { logger, server: { port, middlewareMode } } = server.config;
- if (!middlewareMode) await server.listen(port, true);
- else await Promise.all(Object.values(server.environments).map((e$1) => e$1.listen(server)));
- logger.info("server restarted.", { timestamp: true });
- if (server._shortcutsState?.options) bindCLIShortcuts(server, { print: false }, true);
-}
-/**
-* Internal function to restart the Vite server and print URLs if changed
-*/
-async function restartServerWithUrls(server) {
- if (server.config.server.middlewareMode) {
- await server.restart();
- return;
- }
- const { port: prevPort, host: prevHost } = server.config.server;
- const prevUrls = server.resolvedUrls;
- await server.restart();
- const { logger, server: { port, host } } = server.config;
- if ((port ?? DEFAULT_DEV_PORT) !== (prevPort ?? DEFAULT_DEV_PORT) || host !== prevHost || diffDnsOrderChange(prevUrls, server.resolvedUrls)) {
- logger.info("");
- server.printUrls();
- }
-}
-
-//#endregion
-//#region src/node/server/hmr.ts
-var import_picocolors$15 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const debugHmr = createDebugger("vite:hmr");
-const whitespaceRE = /\s/;
-const normalizedClientDir = normalizePath(CLIENT_DIR);
-function getShortName(file, root) {
- return file.startsWith(withTrailingSlash(root)) ? path.posix.relative(root, file) : file;
-}
-const normalizeHotChannel = (channel, enableHmr, normalizeClient = true) => {
- const normalizedListenerMap = /* @__PURE__ */ new WeakMap();
- const normalizedClients = /* @__PURE__ */ new WeakMap();
- let invokeHandlers;
- let listenerForInvokeHandler;
- const handleInvoke = async (payload) => {
- if (!invokeHandlers) return { error: {
- name: "TransportError",
- message: "invokeHandlers is not set",
- stack: (/* @__PURE__ */ new Error()).stack
- } };
- const { name, data: args } = payload.data;
- try {
- const invokeHandler = invokeHandlers[name];
- return { result: await invokeHandler(...args) };
- } catch (error$1) {
- return { error: {
- name: error$1.name,
- message: error$1.message,
- stack: error$1.stack,
- ...error$1
- } };
- }
- };
- return {
- ...channel,
- on: (event, fn) => {
- if (event === "connection" || !normalizeClient) {
- channel.on?.(event, fn);
- return;
- }
- const listenerWithNormalizedClient = (data, client) => {
- if (!normalizedClients.has(client)) normalizedClients.set(client, { send: (...args) => {
- let payload;
- if (typeof args[0] === "string") payload = {
- type: "custom",
- event: args[0],
- data: args[1]
- };
- else payload = args[0];
- client.send(payload);
- } });
- fn(data, normalizedClients.get(client));
- };
- normalizedListenerMap.set(fn, listenerWithNormalizedClient);
- channel.on?.(event, listenerWithNormalizedClient);
- },
- off: (event, fn) => {
- if (event === "connection" || !normalizeClient) {
- channel.off?.(event, fn);
- return;
- }
- const normalizedListener = normalizedListenerMap.get(fn);
- if (normalizedListener) channel.off?.(event, normalizedListener);
- },
- setInvokeHandler(_invokeHandlers) {
- invokeHandlers = _invokeHandlers;
- if (!_invokeHandlers) {
- if (listenerForInvokeHandler) channel.off?.("vite:invoke", listenerForInvokeHandler);
- return;
- }
- listenerForInvokeHandler = async (payload, client) => {
- const responseInvoke = payload.id.replace("send", "response");
- client.send({
- type: "custom",
- event: "vite:invoke",
- data: {
- name: payload.name,
- id: responseInvoke,
- data: await handleInvoke({
- type: "custom",
- event: "vite:invoke",
- data: payload
- })
- }
- });
- };
- channel.on?.("vite:invoke", listenerForInvokeHandler);
- },
- handleInvoke,
- send: (...args) => {
- let payload;
- if (typeof args[0] === "string") payload = {
- type: "custom",
- event: args[0],
- data: args[1]
- };
- else payload = args[0];
- if (enableHmr || payload.type === "connected" || payload.type === "ping" || payload.type === "custom" || payload.type === "error") channel.send?.(payload);
- },
- listen() {
- return channel.listen?.();
- },
- close() {
- return channel.close?.();
- }
- };
-};
-function getSortedPluginsByHotUpdateHook(plugins$1) {
- const sortedPlugins = [];
- let pre = 0, normal = 0, post = 0;
- for (const plugin of plugins$1) {
- const hook = plugin["hotUpdate"] ?? plugin["handleHotUpdate"];
- if (hook) {
- if (typeof hook === "object") {
- if (hook.order === "pre") {
- sortedPlugins.splice(pre++, 0, plugin);
- continue;
- }
- if (hook.order === "post") {
- sortedPlugins.splice(pre + normal + post++, 0, plugin);
- continue;
- }
- }
- sortedPlugins.splice(pre + normal++, 0, plugin);
- }
- }
- return sortedPlugins;
-}
-const sortedHotUpdatePluginsCache = /* @__PURE__ */ new WeakMap();
-function getSortedHotUpdatePlugins(environment) {
- let sortedPlugins = sortedHotUpdatePluginsCache.get(environment);
- if (!sortedPlugins) {
- sortedPlugins = getSortedPluginsByHotUpdateHook(environment.plugins);
- sortedHotUpdatePluginsCache.set(environment, sortedPlugins);
- }
- return sortedPlugins;
-}
-async function handleHMRUpdate(type, file, server) {
- const { config: config$2 } = server;
- const mixedModuleGraph = ignoreDeprecationWarnings(() => server.moduleGraph);
- const environments = Object.values(server.environments);
- const shortFile = getShortName(file, config$2.root);
- const isConfig = file === config$2.configFile;
- const isConfigDependency = config$2.configFileDependencies.some((name) => file === name);
- const isEnv = config$2.envDir !== false && getEnvFilesForMode(config$2.mode, config$2.envDir).includes(file);
- if (isConfig || isConfigDependency || isEnv) {
- debugHmr?.(`[config change] ${import_picocolors$15.default.dim(shortFile)}`);
- config$2.logger.info(import_picocolors$15.default.green(`${normalizePath(path.relative(process.cwd(), file))} changed, restarting server...`), {
- clear: true,
- timestamp: true
- });
- try {
- await restartServerWithUrls(server);
- } catch (e$1) {
- config$2.logger.error(import_picocolors$15.default.red(e$1));
- }
- return;
- }
- debugHmr?.(`[file change] ${import_picocolors$15.default.dim(shortFile)}`);
- if (file.startsWith(withTrailingSlash(normalizedClientDir))) {
- environments.forEach(({ hot }) => hot.send({
- type: "full-reload",
- path: "*",
- triggeredBy: path.resolve(config$2.root, file)
- }));
- return;
- }
- const timestamp = monotonicDateNow();
- const contextMeta = {
- type,
- file,
- timestamp,
- read: () => readModifiedFile(file),
- server
- };
- const hotMap = /* @__PURE__ */ new Map();
- for (const environment of Object.values(server.environments)) {
- const mods = new Set(environment.moduleGraph.getModulesByFile(file));
- if (type === "create") for (const mod of environment.moduleGraph._hasResolveFailedErrorModules) mods.add(mod);
- const options$1 = {
- ...contextMeta,
- modules: [...mods]
- };
- hotMap.set(environment, { options: options$1 });
- }
- const mixedMods = new Set(mixedModuleGraph.getModulesByFile(file));
- const mixedHmrContext = {
- ...contextMeta,
- modules: [...mixedMods]
- };
- const contextForHandleHotUpdate = new BasicMinimalPluginContext({
- ...basePluginContextMeta,
- watchMode: true
- }, config$2.logger);
- const clientEnvironment = server.environments.client;
- const ssrEnvironment = server.environments.ssr;
- const clientContext = clientEnvironment.pluginContainer.minimalContext;
- const clientHotUpdateOptions = hotMap.get(clientEnvironment).options;
- const ssrHotUpdateOptions = hotMap.get(ssrEnvironment)?.options;
- try {
- for (const plugin of getSortedHotUpdatePlugins(server.environments.client)) if (plugin.hotUpdate) {
- const filteredModules = await getHookHandler(plugin.hotUpdate).call(clientContext, clientHotUpdateOptions);
- if (filteredModules) {
- clientHotUpdateOptions.modules = filteredModules;
- mixedHmrContext.modules = mixedHmrContext.modules.filter((mixedMod) => filteredModules.some((mod) => mixedMod.id === mod.id) || ssrHotUpdateOptions?.modules.some((ssrMod) => ssrMod.id === mixedMod.id));
- mixedHmrContext.modules.push(...filteredModules.filter((mod) => !mixedHmrContext.modules.some((mixedMod) => mixedMod.id === mod.id)).map((mod) => mixedModuleGraph.getBackwardCompatibleModuleNode(mod)));
- }
- } else if (type === "update") {
- warnFutureDeprecation(config$2, "removePluginHookHandleHotUpdate", `Used in plugin "${plugin.name}".`, false);
- const filteredModules = await getHookHandler(plugin.handleHotUpdate).call(contextForHandleHotUpdate, mixedHmrContext);
- if (filteredModules) {
- mixedHmrContext.modules = filteredModules;
- clientHotUpdateOptions.modules = clientHotUpdateOptions.modules.filter((mod) => filteredModules.some((mixedMod) => mod.id === mixedMod.id));
- clientHotUpdateOptions.modules.push(...filteredModules.filter((mixedMod) => !clientHotUpdateOptions.modules.some((mod) => mod.id === mixedMod.id)).map((mixedMod) => mixedMod._clientModule).filter(Boolean));
- if (ssrHotUpdateOptions) {
- ssrHotUpdateOptions.modules = ssrHotUpdateOptions.modules.filter((mod) => filteredModules.some((mixedMod) => mod.id === mixedMod.id));
- ssrHotUpdateOptions.modules.push(...filteredModules.filter((mixedMod) => !ssrHotUpdateOptions.modules.some((mod) => mod.id === mixedMod.id)).map((mixedMod) => mixedMod._ssrModule).filter(Boolean));
- }
- }
- }
- } catch (error$1) {
- hotMap.get(server.environments.client).error = error$1;
- }
- for (const environment of Object.values(server.environments)) {
- if (environment.name === "client") continue;
- const hot = hotMap.get(environment);
- const context = environment.pluginContainer.minimalContext;
- try {
- for (const plugin of getSortedHotUpdatePlugins(environment)) if (plugin.hotUpdate) {
- const filteredModules = await getHookHandler(plugin.hotUpdate).call(context, hot.options);
- if (filteredModules) hot.options.modules = filteredModules;
- }
- } catch (error$1) {
- hot.error = error$1;
- }
- }
- async function hmr(environment) {
- try {
- const { options: options$1, error: error$1 } = hotMap.get(environment);
- if (error$1) throw error$1;
- if (!options$1.modules.length) {
- if (file.endsWith(".html") && environment.name === "client") {
- environment.logger.info(import_picocolors$15.default.green(`page reload `) + import_picocolors$15.default.dim(shortFile), {
- clear: true,
- timestamp: true
- });
- environment.hot.send({
- type: "full-reload",
- path: config$2.server.middlewareMode ? "*" : "/" + normalizePath(path.relative(config$2.root, file))
- });
- } else debugHmr?.(`(${environment.name}) [no modules matched] ${import_picocolors$15.default.dim(shortFile)}`);
- return;
- }
- updateModules(environment, shortFile, options$1.modules, timestamp);
- } catch (err$2) {
- environment.hot.send({
- type: "error",
- err: prepareError(err$2)
- });
- }
- }
- await (server.config.server.hotUpdateEnvironments ?? ((server$1, hmr$1) => {
- return Promise.all(Object.values(server$1.environments).map((environment) => hmr$1(environment)));
- }))(server, hmr);
-}
-function updateModules(environment, file, modules, timestamp, firstInvalidatedBy) {
- const { hot } = environment;
- const updates = [];
- const invalidatedModules = /* @__PURE__ */ new Set();
- const traversedModules = /* @__PURE__ */ new Set();
- let needFullReload = modules.length === 0;
- for (const mod of modules) {
- const boundaries = [];
- const hasDeadEnd = propagateUpdate(mod, traversedModules, boundaries);
- environment.moduleGraph.invalidateModule(mod, invalidatedModules, timestamp, true);
- if (needFullReload) continue;
- if (hasDeadEnd) {
- needFullReload = hasDeadEnd;
- continue;
- }
- if (firstInvalidatedBy && boundaries.some(({ acceptedVia }) => normalizeHmrUrl(acceptedVia.url) === firstInvalidatedBy)) {
- needFullReload = "circular import invalidate";
- continue;
- }
- updates.push(...boundaries.map(({ boundary, acceptedVia, isWithinCircularImport }) => ({
- type: `${boundary.type}-update`,
- timestamp,
- path: normalizeHmrUrl(boundary.url),
- acceptedPath: normalizeHmrUrl(acceptedVia.url),
- explicitImportRequired: boundary.type === "js" ? isExplicitImportRequired(acceptedVia.url) : false,
- isWithinCircularImport,
- firstInvalidatedBy
- })));
- }
- const isClientHtmlChange = file.endsWith(".html") && environment.name === "client" && modules.every((mod) => mod.type !== "js");
- if (needFullReload || isClientHtmlChange) {
- const reason = typeof needFullReload === "string" ? import_picocolors$15.default.dim(` (${needFullReload})`) : "";
- environment.logger.info(import_picocolors$15.default.green(`page reload `) + import_picocolors$15.default.dim(file) + reason, {
- clear: !firstInvalidatedBy,
- timestamp: true
- });
- hot.send({
- type: "full-reload",
- triggeredBy: path.resolve(environment.config.root, file),
- path: !isClientHtmlChange || environment.config.server.middlewareMode || updates.length > 0 ? "*" : "/" + file
- });
- return;
- }
- if (updates.length === 0) {
- debugHmr?.(import_picocolors$15.default.yellow(`no update happened `) + import_picocolors$15.default.dim(file));
- return;
- }
- environment.logger.info(import_picocolors$15.default.green(`hmr update `) + import_picocolors$15.default.dim([...new Set(updates.map((u) => u.path))].join(", ")), {
- clear: !firstInvalidatedBy,
- timestamp: true
- });
- hot.send({
- type: "update",
- updates
- });
-}
-function areAllImportsAccepted(importedBindings, acceptedExports) {
- for (const binding of importedBindings) if (!acceptedExports.has(binding)) return false;
- return true;
-}
-function propagateUpdate(node, traversedModules, boundaries, currentChain = [node]) {
- if (traversedModules.has(node)) return false;
- traversedModules.add(node);
- if (node.id && node.isSelfAccepting === void 0) {
- debugHmr?.(`[propagate update] stop propagation because not analyzed: ${import_picocolors$15.default.dim(node.id)}`);
- return false;
- }
- if (node.isSelfAccepting) {
- const boundary = node;
- boundaries.push({
- boundary,
- acceptedVia: boundary,
- isWithinCircularImport: isNodeWithinCircularImports(node, currentChain)
- });
- return false;
- }
- if (node.acceptedHmrExports) {
- const boundary = node;
- boundaries.push({
- boundary,
- acceptedVia: boundary,
- isWithinCircularImport: isNodeWithinCircularImports(node, currentChain)
- });
- } else if (!node.importers.size) return true;
- for (const importer of node.importers) {
- const subChain = currentChain.concat(importer);
- if (importer.acceptedHmrDeps.has(node)) {
- boundaries.push({
- boundary: importer,
- acceptedVia: node,
- isWithinCircularImport: isNodeWithinCircularImports(importer, subChain)
- });
- continue;
- }
- if (node.id && node.acceptedHmrExports && importer.importedBindings) {
- const importedBindingsFromNode = importer.importedBindings.get(node.id);
- if (importedBindingsFromNode && areAllImportsAccepted(importedBindingsFromNode, node.acceptedHmrExports)) continue;
- }
- if (!currentChain.includes(importer) && propagateUpdate(importer, traversedModules, boundaries, subChain)) return true;
- }
- return false;
-}
-/**
-* Check importers recursively if it's an import loop. An accepted module within
-* an import loop cannot recover its execution order and should be reloaded.
-*
-* @param node The node that accepts HMR and is a boundary
-* @param nodeChain The chain of nodes/imports that lead to the node.
-* (The last node in the chain imports the `node` parameter)
-* @param currentChain The current chain tracked from the `node` parameter
-* @param traversedModules The set of modules that have traversed
-*/
-function isNodeWithinCircularImports(node, nodeChain, currentChain = [node], traversedModules = /* @__PURE__ */ new Set()) {
- if (traversedModules.has(node)) return false;
- traversedModules.add(node);
- for (const importer of node.importers) {
- if (importer === node) continue;
- const importerIndex = nodeChain.indexOf(importer);
- if (importerIndex > -1) {
- if (debugHmr) {
- const importChain = [
- importer,
- ...[...currentChain].reverse(),
- ...nodeChain.slice(importerIndex, -1).reverse()
- ];
- debugHmr(import_picocolors$15.default.yellow(`circular imports detected: `) + importChain.map((m) => import_picocolors$15.default.dim(m.url)).join(" -> "));
- }
- return true;
- }
- if (!currentChain.includes(importer)) {
- const result = isNodeWithinCircularImports(importer, nodeChain, currentChain.concat(importer), traversedModules);
- if (result) return result;
- }
- }
- return false;
-}
-function handlePrunedModules(mods, { hot }) {
- const t$1 = monotonicDateNow();
- mods.forEach((mod) => {
- mod.lastHMRTimestamp = t$1;
- mod.lastHMRInvalidationReceived = false;
- debugHmr?.(`[dispose] ${import_picocolors$15.default.dim(mod.file)}`);
- });
- hot.send({
- type: "prune",
- paths: [...mods].map((m) => m.url)
- });
-}
-var LexerState = /* @__PURE__ */ function(LexerState$1) {
- LexerState$1[LexerState$1["inCall"] = 0] = "inCall";
- LexerState$1[LexerState$1["inSingleQuoteString"] = 1] = "inSingleQuoteString";
- LexerState$1[LexerState$1["inDoubleQuoteString"] = 2] = "inDoubleQuoteString";
- LexerState$1[LexerState$1["inTemplateString"] = 3] = "inTemplateString";
- LexerState$1[LexerState$1["inArray"] = 4] = "inArray";
- return LexerState$1;
-}(LexerState || {});
-/**
-* Lex import.meta.hot.accept() for accepted deps.
-* Since hot.accept() can only accept string literals or array of string
-* literals, we don't really need a heavy @babel/parse call on the entire source.
-*
-* @returns selfAccepts
-*/
-function lexAcceptedHmrDeps(code, start, urls) {
- let state = LexerState.inCall;
- let prevState = LexerState.inCall;
- let currentDep = "";
- function addDep(index) {
- urls.add({
- url: currentDep,
- start: index - currentDep.length - 1,
- end: index + 1
- });
- currentDep = "";
- }
- for (let i$1 = start; i$1 < code.length; i$1++) {
- const char = code.charAt(i$1);
- switch (state) {
- case LexerState.inCall:
- case LexerState.inArray:
- if (char === `'`) {
- prevState = state;
- state = LexerState.inSingleQuoteString;
- } else if (char === `"`) {
- prevState = state;
- state = LexerState.inDoubleQuoteString;
- } else if (char === "`") {
- prevState = state;
- state = LexerState.inTemplateString;
- } else if (whitespaceRE.test(char)) continue;
- else if (state === LexerState.inCall) if (char === `[`) state = LexerState.inArray;
- else return true;
- else if (char === `]`) return false;
- else if (char === ",") continue;
- else error(i$1);
- break;
- case LexerState.inSingleQuoteString:
- if (char === `'`) {
- addDep(i$1);
- if (prevState === LexerState.inCall) return false;
- else state = prevState;
- } else currentDep += char;
- break;
- case LexerState.inDoubleQuoteString:
- if (char === `"`) {
- addDep(i$1);
- if (prevState === LexerState.inCall) return false;
- else state = prevState;
- } else currentDep += char;
- break;
- case LexerState.inTemplateString:
- if (char === "`") {
- addDep(i$1);
- if (prevState === LexerState.inCall) return false;
- else state = prevState;
- } else if (char === "$" && code.charAt(i$1 + 1) === "{") error(i$1);
- else currentDep += char;
- break;
- default: throw new Error("unknown import.meta.hot lexer state");
- }
- }
- return false;
-}
-function lexAcceptedHmrExports(code, start, exportNames) {
- const urls = /* @__PURE__ */ new Set();
- lexAcceptedHmrDeps(code, start, urls);
- for (const { url: url$3 } of urls) exportNames.add(url$3);
- return urls.size > 0;
-}
-function normalizeHmrUrl(url$3) {
- if (url$3[0] !== "." && url$3[0] !== "/") url$3 = wrapId(url$3);
- return url$3;
-}
-function error(pos) {
- const err$2 = /* @__PURE__ */ new Error("import.meta.hot.accept() can only accept string literals or an Array of string literals.");
- err$2.pos = pos;
- throw err$2;
-}
-async function readModifiedFile(file) {
- const content = await fsp.readFile(file, "utf-8");
- if (!content) {
- const mtime = (await fsp.stat(file)).mtimeMs;
- for (let n$2 = 0; n$2 < 10; n$2++) {
- await new Promise((r$1) => setTimeout(r$1, 10));
- if ((await fsp.stat(file)).mtimeMs !== mtime) break;
- }
- return await fsp.readFile(file, "utf-8");
- } else return content;
-}
-function createServerHotChannel() {
- const innerEmitter = new EventEmitter();
- const outsideEmitter = new EventEmitter();
- return {
- send(payload) {
- outsideEmitter.emit("send", payload);
- },
- off(event, listener$1) {
- innerEmitter.off(event, listener$1);
- },
- on: ((event, listener$1) => {
- innerEmitter.on(event, listener$1);
- }),
- close() {
- innerEmitter.removeAllListeners();
- outsideEmitter.removeAllListeners();
- },
- listen() {
- innerEmitter.emit("connection");
- },
- api: {
- innerEmitter,
- outsideEmitter
- }
- };
-}
-
-//#endregion
-//#region src/node/external.ts
-const debug$6 = createDebugger("vite:external");
-const isExternalCache = /* @__PURE__ */ new WeakMap();
-function shouldExternalize(environment, id, importer) {
- let isExternal$1 = isExternalCache.get(environment);
- if (!isExternal$1) {
- isExternal$1 = createIsExternal(environment);
- isExternalCache.set(environment, isExternal$1);
- }
- return isExternal$1(id, importer);
-}
-function createIsConfiguredAsExternal(environment) {
- const { config: config$2 } = environment;
- const { root, resolve: resolve$4 } = config$2;
- const { external, noExternal } = resolve$4;
- const noExternalFilter = typeof noExternal !== "boolean" && !(Array.isArray(noExternal) && noExternal.length === 0) && createFilter(void 0, noExternal, { resolve: false });
- const targetConditions = resolve$4.externalConditions;
- const resolveOptions = {
- ...resolve$4,
- root,
- isProduction: false,
- isBuild: true,
- conditions: targetConditions
- };
- const isExternalizable = (id, importer, configuredAsExternal) => {
- if (!bareImportRE.test(id) || id.includes("\0")) return false;
- try {
- const resolved = tryNodeResolve(id, config$2.command === "build" ? void 0 : importer, resolveOptions, void 0, false);
- if (!resolved) return false;
- if (!configuredAsExternal && !isInNodeModules(resolved.id)) return false;
- return canExternalizeFile(resolved.id);
- } catch {
- debug$6?.(`Failed to node resolve "${id}". Skipping externalizing it by default.`);
- return false;
- }
- };
- return (id, importer) => {
- if (external !== true && external.includes(id)) return true;
- const pkgName = getNpmPackageName(id);
- if (!pkgName) return isExternalizable(id, importer, false);
- if (external !== true && external.includes(pkgName)) return isExternalizable(id, importer, true);
- if (typeof noExternal === "boolean") return !noExternal;
- if (noExternalFilter && !noExternalFilter(pkgName)) return false;
- return isExternalizable(id, importer, external === true);
- };
-}
-function createIsExternal(environment) {
- const processedIds = /* @__PURE__ */ new Map();
- const isConfiguredAsExternal = createIsConfiguredAsExternal(environment);
- return (id, importer) => {
- if (processedIds.has(id)) return processedIds.get(id);
- let isExternal$1 = false;
- if (id[0] !== "." && !path.isAbsolute(id)) isExternal$1 = isBuiltin(environment.config.resolve.builtins, id) || isConfiguredAsExternal(id, importer);
- processedIds.set(id, isExternal$1);
- return isExternal$1;
- };
-}
-function canExternalizeFile(filePath) {
- const ext = path.extname(filePath);
- return !ext || ext === ".js" || ext === ".mjs" || ext === ".cjs";
-}
-
-//#endregion
-//#region src/node/plugins/define.ts
-const nonJsRe = /\.json(?:$|\?)/;
-const isNonJsRequest = (request) => nonJsRe.test(request);
-const importMetaEnvMarker = "__vite_import_meta_env__";
-const importMetaEnvKeyReCache = /* @__PURE__ */ new Map();
-const escapedDotRE = /(?<!\\)\\./g;
-function definePlugin(config$2) {
- const isBuild = config$2.command === "build";
- const isBuildLib = isBuild && config$2.build.lib;
- const processEnv = {};
- if (!isBuildLib) {
- const nodeEnv = process.env.NODE_ENV || config$2.mode;
- Object.assign(processEnv, {
- "process.env": `{}`,
- "global.process.env": `{}`,
- "globalThis.process.env": `{}`,
- "process.env.NODE_ENV": JSON.stringify(nodeEnv),
- "global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
- "globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv)
- });
- }
- const importMetaKeys = {};
- const importMetaEnvKeys = {};
- const importMetaFallbackKeys = {};
- if (isBuild) {
- importMetaKeys["import.meta.hot"] = `undefined`;
- for (const key in config$2.env) {
- const val = JSON.stringify(config$2.env[key]);
- importMetaKeys[`import.meta.env.${key}`] = val;
- importMetaEnvKeys[key] = val;
- }
- importMetaKeys["import.meta.env.SSR"] = `undefined`;
- importMetaFallbackKeys["import.meta.env"] = `undefined`;
- }
- function generatePattern(environment) {
- const keepProcessEnv = environment.config.keepProcessEnv;
- const userDefine = {};
- const userDefineEnv = {};
- for (const key in environment.config.define) {
- userDefine[key] = handleDefineValue(environment.config.define[key]);
- if (isBuild && key.startsWith("import.meta.env.")) userDefineEnv[key.slice(16)] = environment.config.define[key];
- }
- const define$1 = {
- ...keepProcessEnv ? {} : processEnv,
- ...importMetaKeys,
- ...userDefine,
- ...importMetaFallbackKeys
- };
- const ssr = environment.config.consumer === "server";
- if ("import.meta.env.SSR" in define$1) define$1["import.meta.env.SSR"] = ssr + "";
- if ("import.meta.env" in define$1) define$1["import.meta.env"] = importMetaEnvMarker;
- const importMetaEnvVal = serializeDefine({
- ...importMetaEnvKeys,
- SSR: ssr + "",
- ...userDefineEnv
- });
- const patternKeys = Object.keys(userDefine);
- if (!keepProcessEnv && Object.keys(processEnv).length) patternKeys.push("process.env");
- if (Object.keys(importMetaKeys).length) patternKeys.push("import.meta.env", "import.meta.hot");
- return [
- define$1,
- patternKeys.length ? new RegExp(patternKeys.map((key) => escapeRegex(key).replaceAll(escapedDotRE, "\\??\\.")).join("|")) : null,
- importMetaEnvVal
- ];
- }
- const patternsCache = /* @__PURE__ */ new WeakMap();
- function getPattern(environment) {
- let pattern = patternsCache.get(environment);
- if (!pattern) {
- pattern = generatePattern(environment);
- patternsCache.set(environment, pattern);
- }
- return pattern;
- }
- return {
- name: "vite:define",
- transform: { async handler(code, id) {
- if (this.environment.config.consumer === "client" && !isBuild) return;
- if (isHTMLRequest(id) || isCSSRequest(id) || isNonJsRequest(id) || config$2.assetsInclude(id)) return;
- let [define$1, pattern, importMetaEnvVal] = getPattern(this.environment);
- if (!pattern) return;
- pattern.lastIndex = 0;
- if (!pattern.test(code)) return;
- const hasDefineImportMetaEnv = "import.meta.env" in define$1;
- let marker = importMetaEnvMarker;
- if (hasDefineImportMetaEnv && code.includes(marker)) {
- let i$1 = 1;
- do
- marker = importMetaEnvMarker + i$1++;
- while (code.includes(marker));
- if (marker !== importMetaEnvMarker) define$1 = {
- ...define$1,
- "import.meta.env": marker
- };
- }
- const result = await replaceDefine(this.environment, code, id, define$1);
- if (hasDefineImportMetaEnv) {
- result.code = result.code.replaceAll(getImportMetaEnvKeyRe(marker), (m) => "undefined".padEnd(m.length));
- if (result.code.includes(marker)) {
- result.code = `const ${marker} = ${importMetaEnvVal};\n` + result.code;
- if (result.map) {
- const map$1 = JSON.parse(result.map);
- map$1.mappings = ";" + map$1.mappings;
- result.map = map$1;
- }
- }
- }
- return result;
- } }
- };
-}
-async function replaceDefine(environment, code, id, define$1) {
- const result = await transform(code, {
- loader: "js",
- charset: (environment.config.esbuild || {}).charset,
- platform: "neutral",
- define: define$1,
- sourcefile: id,
- sourcemap: environment.config.command === "build" ? !!environment.config.build.sourcemap : true
- });
- if (result.map.includes("<define:")) {
- const originalMap = new TraceMap(result.map);
- if (originalMap.sources.length >= 2) {
- const sourceIndex = originalMap.sources.indexOf(id);
- const decoded = decodedMap(originalMap);
- decoded.sources = [id];
- decoded.mappings = decoded.mappings.map((segments) => segments.filter((segment) => {
- const index = segment[1];
- segment[1] = 0;
- return index === sourceIndex;
- }));
- result.map = JSON.stringify(encodedMap(new TraceMap(decoded)));
- }
- }
- return {
- code: result.code,
- map: result.map || null
- };
-}
-/**
-* Like `JSON.stringify` but keeps raw string values as a literal
-* in the generated code. For example: `"window"` would refer to
-* the global `window` object directly.
-*/
-function serializeDefine(define$1) {
- let res = `{`;
- const keys = Object.keys(define$1).sort();
- for (let i$1 = 0; i$1 < keys.length; i$1++) {
- const key = keys[i$1];
- const val = define$1[key];
- res += `${JSON.stringify(key)}: ${handleDefineValue(val)}`;
- if (i$1 !== keys.length - 1) res += `, `;
- }
- return res + `}`;
-}
-function handleDefineValue(value$1) {
- if (typeof value$1 === "undefined") return "undefined";
- if (typeof value$1 === "string") return value$1;
- return JSON.stringify(value$1);
-}
-function getImportMetaEnvKeyRe(marker) {
- let re = importMetaEnvKeyReCache.get(marker);
- if (!re) {
- re = new RegExp(`${marker}\\..+?\\b`, "g");
- importMetaEnvKeyReCache.set(marker, re);
- }
- return re;
-}
-
-//#endregion
-//#region src/node/plugins/worker.ts
-var import_picocolors$14 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-var WorkerOutputCache = class {
- /**
- * worker bundle information for each input id
- * used to bundle the same worker file only once
- */
- bundles = /* @__PURE__ */ new Map();
- /** list of assets emitted for the worker bundles */
- assets = /* @__PURE__ */ new Map();
- fileNameHash = /* @__PURE__ */ new Map();
- invalidatedBundles = /* @__PURE__ */ new Set();
- saveWorkerBundle(file, watchedFiles, outputEntryFilename, outputEntryCode, outputAssets, logger) {
- for (const asset of outputAssets) this.saveAsset(asset, logger);
- const bundle = {
- entryFilename: outputEntryFilename,
- entryCode: outputEntryCode,
- entryUrlPlaceholder: this.generateEntryUrlPlaceholder(outputEntryFilename),
- referencedAssets: new Set(outputAssets.map((asset) => asset.fileName)),
- watchedFiles
- };
- this.bundles.set(file, bundle);
- return bundle;
- }
- saveAsset(asset, logger) {
- const duplicateAsset = this.assets.get(asset.fileName);
- if (duplicateAsset) {
- if (!isSameContent(duplicateAsset.source, asset.source)) logger.warn(`\n` + import_picocolors$14.default.yellow(`The emitted file ${JSON.stringify(asset.fileName)} overwrites a previously emitted file of the same name.`));
- }
- this.assets.set(asset.fileName, asset);
- }
- invalidateAffectedBundles(file) {
- for (const [bundleInputFile, bundle] of this.bundles.entries()) if (bundle.watchedFiles.includes(file)) this.invalidatedBundles.add(bundleInputFile);
- }
- removeBundleIfInvalidated(file) {
- if (this.invalidatedBundles.has(file)) {
- this.invalidatedBundles.delete(file);
- this.removeBundle(file);
- }
- }
- removeBundle(file) {
- const bundle = this.bundles.get(file);
- if (!bundle) return;
- this.bundles.delete(file);
- this.fileNameHash.delete(getHash(bundle.entryFilename));
- this.assets.delete(bundle.entryFilename);
- const keptBundles = [...this.bundles.values()];
- for (const asset of bundle.referencedAssets) if (keptBundles.every((b) => !b.referencedAssets.has(asset))) this.assets.delete(asset);
- }
- getWorkerBundle(file) {
- return this.bundles.get(file);
- }
- getAssets() {
- return this.assets.values();
- }
- getEntryFilenameFromHash(hash$1) {
- return this.fileNameHash.get(hash$1);
- }
- generateEntryUrlPlaceholder(entryFilename) {
- const hash$1 = getHash(entryFilename);
- if (!this.fileNameHash.has(hash$1)) this.fileNameHash.set(hash$1, entryFilename);
- return `__VITE_WORKER_ASSET__${hash$1}__`;
- }
-};
-const workerOrSharedWorkerRE = /(?:\?|&)(worker|sharedworker)(?:&|$)/;
-const workerFileRE = /(?:\?|&)worker_file&type=(\w+)(?:&|$)/;
-const inlineRE$1 = /[?&]inline\b/;
-const WORKER_FILE_ID = "worker_file";
-const workerOutputCaches = /* @__PURE__ */ new WeakMap();
-async function bundleWorkerEntry(config$2, id) {
- const input = cleanUrl(id);
- const workerOutput = workerOutputCaches.get(config$2.mainConfig || config$2);
- workerOutput.removeBundleIfInvalidated(input);
- const bundleInfo = workerOutput.getWorkerBundle(input);
- if (bundleInfo) return bundleInfo;
- const newBundleChain = [...config$2.bundleChain, input];
- if (config$2.bundleChain.includes(input)) throw new Error(`Circular worker imports detected. Vite does not support it. Import chain: ${newBundleChain.map((id$1) => prettifyUrl(id$1, config$2.root)).join(" -> ")}`);
- const { rollup } = await import("rollup");
- const { plugins: plugins$1, rollupOptions, format: format$3 } = config$2.worker;
- const workerEnvironment = new BuildEnvironment("client", await plugins$1(newBundleChain));
- await workerEnvironment.init();
- const bundle = await rollup({
- ...rollupOptions,
- input,
- plugins: workerEnvironment.plugins.map((p) => injectEnvironmentToHooks(workerEnvironment, p)),
- onLog(level, log$3) {
- onRollupLog(level, log$3, workerEnvironment);
- },
- preserveEntrySignatures: false
- });
- let result;
- let watchedFiles;
- try {
- const workerOutputConfig = config$2.worker.rollupOptions.output;
- const workerConfig = workerOutputConfig ? Array.isArray(workerOutputConfig) ? workerOutputConfig[0] || {} : workerOutputConfig : {};
- result = await bundle.generate({
- entryFileNames: path.posix.join(config$2.build.assetsDir, "[name]-[hash].js"),
- chunkFileNames: path.posix.join(config$2.build.assetsDir, "[name]-[hash].js"),
- assetFileNames: path.posix.join(config$2.build.assetsDir, "[name]-[hash].[ext]"),
- ...workerConfig,
- format: format$3,
- sourcemap: config$2.build.sourcemap
- });
- watchedFiles = bundle.watchFiles.map((f$1) => normalizePath(f$1));
- } catch (e$1) {
- if (e$1 instanceof Error && e$1.name === "RollupError" && e$1.code === "INVALID_OPTION" && e$1.message.includes("\"output.format\"")) e$1.message = e$1.message.replace("output.format", "worker.format");
- throw e$1;
- } finally {
- await bundle.close();
- }
- const { output: [outputChunk, ...outputChunks] } = result;
- const assets = outputChunks.map((outputChunk$1) => outputChunk$1.type === "asset" ? outputChunk$1 : {
- fileName: outputChunk$1.fileName,
- originalFileName: null,
- originalFileNames: [],
- source: outputChunk$1.code
- });
- if ((config$2.build.sourcemap === "hidden" || config$2.build.sourcemap === true) && outputChunk.map) assets.push({
- fileName: outputChunk.fileName + ".map",
- originalFileName: null,
- originalFileNames: [],
- source: outputChunk.map.toString()
- });
- return workerOutputCaches.get(config$2.mainConfig || config$2).saveWorkerBundle(input, watchedFiles, outputChunk.fileName, outputChunk.code, assets, config$2.logger);
-}
-const workerAssetUrlRE = /__VITE_WORKER_ASSET__([a-z\d]{8})__/g;
-async function workerFileToUrl(config$2, id) {
- const workerOutput = workerOutputCaches.get(config$2.mainConfig || config$2);
- const bundle = await bundleWorkerEntry(config$2, id);
- workerOutput.saveAsset({
- fileName: bundle.entryFilename,
- originalFileName: null,
- originalFileNames: [],
- source: bundle.entryCode
- }, config$2.logger);
- return bundle;
-}
-function webWorkerPostPlugin() {
- return {
- name: "vite:worker-post",
- resolveImportMeta(property, { format: format$3 }) {
- if (format$3 === "iife") {
- if (!property) return `{
- url: self.location.href
- }`;
- if (property === "url") return "self.location.href";
- }
- return null;
- }
- };
-}
-function webWorkerPlugin(config$2) {
- const isBuild = config$2.command === "build";
- const isWorker = config$2.isWorker;
- workerOutputCaches.set(config$2, new WorkerOutputCache());
- const emittedAssets = /* @__PURE__ */ new Set();
- return {
- name: "vite:worker",
- buildStart() {
- if (isWorker) return;
- emittedAssets.clear();
- },
- load: {
- filter: { id: workerOrSharedWorkerRE },
- async handler(id) {
- const workerMatch = workerOrSharedWorkerRE.exec(id);
- if (!workerMatch) return;
- const { format: format$3 } = config$2.worker;
- const workerConstructor = workerMatch[1] === "sharedworker" ? "SharedWorker" : "Worker";
- const workerType = isBuild ? format$3 === "es" ? "module" : "classic" : "module";
- const workerTypeOption = `{
- ${workerType === "module" ? `type: "module",` : ""}
- name: options?.name
- }`;
- let urlCode;
- if (isBuild) if (isWorker && config$2.bundleChain.at(-1) === cleanUrl(id)) urlCode = "self.location.href";
- else if (inlineRE$1.test(id)) {
- const result = await bundleWorkerEntry(config$2, id);
- for (const file of result.watchedFiles) this.addWatchFile(file);
- const jsContent = `const jsContent = ${JSON.stringify(result.entryCode)};`;
- return {
- code: workerConstructor === "Worker" ? `${jsContent}
- const blob = typeof self !== "undefined" && self.Blob && new Blob([${workerType === "classic" ? `'(self.URL || self.webkitURL).revokeObjectURL(self.location.href);',` : `'URL.revokeObjectURL(import.meta.url);',`}jsContent], { type: "text/javascript;charset=utf-8" });
- export default function WorkerWrapper(options) {
- let objURL;
- try {
- objURL = blob && (self.URL || self.webkitURL).createObjectURL(blob);
- if (!objURL) throw ''
- const worker = new ${workerConstructor}(objURL, ${workerTypeOption});
- worker.addEventListener("error", () => {
- (self.URL || self.webkitURL).revokeObjectURL(objURL);
- });
- return worker;
- } catch(e) {
- return new ${workerConstructor}(
- 'data:text/javascript;charset=utf-8,' + encodeURIComponent(jsContent),
- ${workerTypeOption}
- );
- }
- }` : `${jsContent}
- export default function WorkerWrapper(options) {
- return new ${workerConstructor}(
- 'data:text/javascript;charset=utf-8,' + encodeURIComponent(jsContent),
- ${workerTypeOption}
- );
- }
- `,
- map: { mappings: "" }
- };
- } else {
- const result = await workerFileToUrl(config$2, id);
- urlCode = JSON.stringify(result.entryUrlPlaceholder);
- for (const file of result.watchedFiles) this.addWatchFile(file);
- }
- else {
- let url$3 = await fileToUrl$1(this, cleanUrl(id));
- url$3 = injectQuery(url$3, `${WORKER_FILE_ID}&type=${workerType}`);
- urlCode = JSON.stringify(url$3);
- }
- if (urlRE.test(id)) return {
- code: `export default ${urlCode}`,
- map: { mappings: "" }
- };
- return {
- code: `export default function WorkerWrapper(options) {
- return new ${workerConstructor}(
- ${urlCode},
- ${workerTypeOption}
- );
- }`,
- map: { mappings: "" }
- };
- }
- },
- transform: {
- filter: { id: workerFileRE },
- async handler(raw, id) {
- const workerFileMatch = workerFileRE.exec(id);
- if (workerFileMatch) {
- const workerType = workerFileMatch[1];
- let injectEnv = "";
- const scriptPath = JSON.stringify(path.posix.join(config$2.base, ENV_PUBLIC_PATH));
- if (workerType === "classic") injectEnv = `importScripts(${scriptPath})\n`;
- else if (workerType === "module") injectEnv = `import ${scriptPath}\n`;
- else if (workerType === "ignore") if (isBuild) injectEnv = "";
- else {
- const environment = this.environment;
- injectEnv = ((environment.mode === "dev" ? environment.moduleGraph : void 0)?.getModuleById(ENV_ENTRY))?.transformResult?.code || "";
- }
- if (injectEnv) {
- const s = new MagicString(raw);
- s.prepend(injectEnv + ";\n");
- return {
- code: s.toString(),
- map: s.generateMap({ hires: "boundary" })
- };
- }
- }
- }
- },
- renderChunk(code, chunk, outputOptions) {
- let s;
- const result = () => {
- return s && {
- code: s.toString(),
- map: this.environment.config.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
- };
- };
- workerAssetUrlRE.lastIndex = 0;
- if (workerAssetUrlRE.test(code)) {
- const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(outputOptions.format, this.environment.config.isWorker);
- let match;
- s = new MagicString(code);
- workerAssetUrlRE.lastIndex = 0;
- const workerOutputCache = workerOutputCaches.get(config$2.mainConfig || config$2);
- while (match = workerAssetUrlRE.exec(code)) {
- const [full, hash$1] = match;
- const filename = workerOutputCache.getEntryFilenameFromHash(hash$1);
- if (!filename) {
- this.warn(`Could not find worker asset for hash: ${hash$1}`);
- continue;
- }
- const replacement = toOutputFilePathInJS(this.environment, filename, "asset", chunk.fileName, "js", toRelativeRuntime);
- const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
- s.update(match.index, match.index + full.length, replacementString);
- }
- }
- return result();
- },
- generateBundle(opts, bundle) {
- if (opts.__vite_skip_asset_emit__ || isWorker) return;
- for (const asset of workerOutputCaches.get(config$2).getAssets()) {
- if (emittedAssets.has(asset.fileName)) continue;
- emittedAssets.add(asset.fileName);
- const duplicateAsset = bundle[asset.fileName];
- if (duplicateAsset) {
- if (isSameContent(duplicateAsset.type === "asset" ? duplicateAsset.source : duplicateAsset.code, asset.source)) continue;
- }
- this.emitFile({
- type: "asset",
- fileName: asset.fileName,
- source: asset.source
- });
- }
- },
- watchChange(file) {
- if (isWorker) return;
- workerOutputCaches.get(config$2).invalidateAffectedBundles(normalizePath(file));
- }
- };
-}
-function isSameContent(a, b) {
- if (typeof a === "string") {
- if (typeof b === "string") return a === b;
- return Buffer.from(a).equals(b);
- }
- return Buffer.from(b).equals(a);
-}
-
-//#endregion
-//#region src/node/plugins/preAlias.ts
-/**
-* A plugin to avoid an aliased AND optimized dep from being aliased in src
-*/
-function preAliasPlugin(config$2) {
- const findPatterns = getAliasPatterns(config$2.resolve.alias);
- return {
- name: "vite:pre-alias",
- applyToEnvironment(environment) {
- return !isDepOptimizationDisabled(environment.config.optimizeDeps);
- },
- async resolveId(id, importer, options$1) {
- const environment = this.environment;
- const ssr = environment.config.consumer === "server";
- const depsOptimizer = environment.depsOptimizer;
- if (importer && depsOptimizer && bareImportRE.test(id) && !options$1.scan && id !== "@vite/client" && id !== "@vite/env") {
- if (findPatterns.find((pattern) => matches(pattern, id))) {
- const optimizedId = await tryOptimizedResolve(depsOptimizer, id, importer, config$2.resolve.preserveSymlinks, config$2.packageCache);
- if (optimizedId) return optimizedId;
- if (depsOptimizer.options.noDiscovery) return;
- const resolved = await this.resolve(id, importer, options$1);
- if (resolved && !depsOptimizer.isOptimizedDepFile(resolved.id)) {
- const optimizeDeps$1 = depsOptimizer.options;
- const resolvedId = cleanUrl(resolved.id);
- if (!(resolvedId === id || resolvedId.includes("\0")) && fs.existsSync(resolvedId) && !moduleListContains(optimizeDeps$1.exclude, id) && path.isAbsolute(resolvedId) && (isInNodeModules(resolvedId) || optimizeDeps$1.include?.includes(id)) && isOptimizable(resolvedId, optimizeDeps$1) && (!ssr || optimizeAliasReplacementForSSR(resolvedId, optimizeDeps$1))) {
- const optimizedInfo = depsOptimizer.registerMissingImport(id, resolvedId);
- return { id: depsOptimizer.getOptimizedDepId(optimizedInfo) };
- }
- }
- return resolved;
- }
- }
- }
- };
-}
-function optimizeAliasReplacementForSSR(id, optimizeDeps$1) {
- if (optimizeDeps$1.include?.includes(id)) return true;
- return false;
-}
-function matches(pattern, importee) {
- if (pattern instanceof RegExp) return pattern.test(importee);
- if (importee.length < pattern.length) return false;
- if (importee === pattern) return true;
- return importee.startsWith(withTrailingSlash(pattern));
-}
-function getAliasPatterns(entries) {
- if (Array.isArray(entries)) return entries.map((entry) => entry.find);
- return Object.entries(entries).map(([find$1]) => find$1);
-}
-function getAliasPatternMatcher(entries) {
- const patterns = getAliasPatterns(entries);
- return (importee) => patterns.some((pattern) => matches(pattern, importee));
-}
-
-//#endregion
-//#region src/node/plugins/importAnalysis.ts
-var import_picocolors$13 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const debug$5 = createDebugger("vite:import-analysis");
-const clientDir = normalizePath(CLIENT_DIR);
-const skipRE = /\.(?:map|json)(?:$|\?)/;
-const canSkipImportAnalysis = (id) => skipRE.test(id) || isDirectCSSRequest(id);
-const optimizedDepChunkRE = /\/chunk-[A-Z\d]{8}\.js/;
-const optimizedDepDynamicRE = /-[A-Z\d]{8}\.js/;
-const hasViteIgnoreRE = /\/\*\s*@vite-ignore\s*\*\//;
-const urlIsStringRE = /^(?:'.*'|".*"|`.*`)$/;
-const templateLiteralRE = /^\s*`(.*)`\s*$/;
-function isExplicitImportRequired(url$3) {
- return !isJSRequest(url$3) && !isCSSRequest(url$3);
-}
-function normalizeResolvedIdToUrl(environment, url$3, resolved) {
- const root = environment.config.root;
- const depsOptimizer = environment.depsOptimizer;
- if (resolved.id.startsWith(withTrailingSlash(root))) url$3 = resolved.id.slice(root.length);
- else if (depsOptimizer?.isOptimizedDepFile(resolved.id) || resolved.id !== "/@react-refresh" && path.isAbsolute(resolved.id) && fs.existsSync(cleanUrl(resolved.id))) url$3 = path.posix.join(FS_PREFIX, resolved.id);
- else url$3 = resolved.id;
- if (url$3[0] !== "." && url$3[0] !== "/") url$3 = wrapId(resolved.id);
- return url$3;
-}
-function extractImportedBindings(id, source, importSpec, importedBindings) {
- let bindings = importedBindings.get(id);
- if (!bindings) {
- bindings = /* @__PURE__ */ new Set();
- importedBindings.set(id, bindings);
- }
- if (importSpec.d > -1 || importSpec.d === -2) {
- bindings.add("*");
- return;
- }
- const exp = source.slice(importSpec.ss, importSpec.se);
- ESM_STATIC_IMPORT_RE.lastIndex = 0;
- const match = ESM_STATIC_IMPORT_RE.exec(exp);
- if (!match) return;
- const parsed = parseStaticImport({
- type: "static",
- code: match[0],
- start: match.index,
- end: match.index + match[0].length,
- imports: match.groups.imports,
- specifier: match.groups.specifier
- });
- if (parsed.namespacedImport) bindings.add("*");
- if (parsed.defaultImport) bindings.add("default");
- if (parsed.namedImports) for (const name of Object.keys(parsed.namedImports)) bindings.add(name);
-}
-/**
-* Dev-only plugin that lexes, resolves, rewrites and analyzes url imports.
-*
-* - Imports are resolved to ensure they exist on disk
-*
-* - Lexes HMR accept calls and updates import relationships in the module graph
-*
-* - Bare module imports are resolved (by @rollup-plugin/node-resolve) to
-* absolute file paths, e.g.
-*
-* ```js
-* import 'foo'
-* ```
-* is rewritten to
-* ```js
-* import '/@fs//project/node_modules/foo/dist/foo.js'
-* ```
-*
-* - CSS imports are appended with `.js` since both the js module and the actual
-* css (referenced via `<link>`) may go through the transform pipeline:
-*
-* ```js
-* import './style.css'
-* ```
-* is rewritten to
-* ```js
-* import './style.css.js'
-* ```
-*/
-function importAnalysisPlugin(config$2) {
- const { root, base } = config$2;
- const clientPublicPath = path.posix.join(base, CLIENT_PUBLIC_PATH);
- const enablePartialAccept = config$2.experimental.hmrPartialAccept;
- const matchAlias = getAliasPatternMatcher(config$2.resolve.alias);
- let _env;
- let _ssrEnv;
- function getEnv(ssr) {
- if (!_ssrEnv || !_env) {
- const importMetaEnvKeys = {};
- const userDefineEnv = {};
- for (const key in config$2.env) importMetaEnvKeys[key] = JSON.stringify(config$2.env[key]);
- for (const key in config$2.define) if (key.startsWith("import.meta.env.")) userDefineEnv[key.slice(16)] = config$2.define[key];
- const env$1 = `import.meta.env = ${serializeDefine({
- ...importMetaEnvKeys,
- SSR: "__vite_ssr__",
- ...userDefineEnv
- })};`;
- _ssrEnv = env$1.replace("__vite_ssr__", "true");
- _env = env$1.replace("__vite_ssr__", "false");
- }
- return ssr ? _ssrEnv : _env;
- }
- return {
- name: "vite:import-analysis",
- async transform(source, importer) {
- const environment = this.environment;
- const ssr = environment.config.consumer === "server";
- const moduleGraph = environment.moduleGraph;
- if (canSkipImportAnalysis(importer)) {
- debug$5?.(import_picocolors$13.default.dim(`[skipped] ${prettifyUrl(importer, root)}`));
- return null;
- }
- const msAtStart = debug$5 ? performance$1.now() : 0;
- await init;
- let imports;
- let exports$1;
- source = stripBomTag(source);
- try {
- [imports, exports$1] = parse(source);
- } catch (_e) {
- const e$1 = _e;
- const { message, showCodeFrame } = createParseErrorInfo(importer, source);
- this.error(message, showCodeFrame ? e$1.idx : void 0);
- }
- const depsOptimizer = environment.depsOptimizer;
- const importerModule = moduleGraph.getModuleById(importer);
- if (!importerModule) throwOutdatedRequest(importer);
- if (!imports.length && !this._addedImports) {
- importerModule.isSelfAccepting = false;
- debug$5?.(`${timeFrom(msAtStart)} ${import_picocolors$13.default.dim(`[no imports] ${prettifyUrl(importer, root)}`)}`);
- return source;
- }
- let hasHMR = false;
- let isSelfAccepting = false;
- let hasEnv = false;
- let needQueryInjectHelper = false;
- let s;
- const str = () => s || (s = new MagicString(source));
- let isPartiallySelfAccepting = false;
- const importedBindings = enablePartialAccept ? /* @__PURE__ */ new Map() : null;
- const toAbsoluteUrl = (url$3) => path.posix.resolve(path.posix.dirname(importerModule.url), url$3);
- const normalizeUrl = async (url$3, pos, forceSkipImportAnalysis = false) => {
- url$3 = stripBase(url$3, base);
- let importerFile = importer;
- if (depsOptimizer && moduleListContains(depsOptimizer.options.exclude, url$3)) {
- await depsOptimizer.scanProcessing;
- for (const optimizedModule of depsOptimizer.metadata.depInfoList) {
- if (!optimizedModule.src) continue;
- if (optimizedModule.file === importerModule.file) importerFile = optimizedModule.src;
- }
- }
- const resolved = await this.resolve(url$3, importerFile).catch((e$1) => {
- if (e$1 instanceof Error) e$1.pos ??= pos;
- throw e$1;
- });
- if (!resolved || resolved.meta?.["vite:alias"]?.noResolved) {
- if (ssr) return [url$3, null];
- importerModule.isSelfAccepting = false;
- moduleGraph._hasResolveFailedErrorModules.add(importerModule);
- return this.error(`Failed to resolve import "${url$3}" from "${normalizePath(path.relative(process.cwd(), importerFile))}". Does the file exist?`, pos);
- }
- if (isExternalUrl(resolved.id)) return [resolved.id, resolved.id];
- url$3 = normalizeResolvedIdToUrl(environment, url$3, resolved);
- try {
- const depModule = await moduleGraph._ensureEntryFromUrl(unwrapId(url$3), canSkipImportAnalysis(url$3) || forceSkipImportAnalysis, resolved);
- if (environment.config.consumer === "client" && depModule.lastHMRTimestamp > 0) url$3 = injectQuery(url$3, `t=${depModule.lastHMRTimestamp}`);
- } catch (e$1) {
- e$1.pos = pos;
- throw e$1;
- }
- if (environment.config.consumer === "client") {
- const isRelative$1 = url$3[0] === ".";
- const isSelfImport = !isRelative$1 && cleanUrl(url$3) === cleanUrl(importer);
- if (isExplicitImportRequired(url$3)) url$3 = injectQuery(url$3, "import");
- else if ((isRelative$1 || isSelfImport) && !DEP_VERSION_RE.test(url$3)) {
- const versionMatch = DEP_VERSION_RE.exec(importer);
- if (versionMatch) url$3 = injectQuery(url$3, versionMatch[1]);
- }
- }
- if (!ssr) url$3 = joinUrlSegments(base, url$3);
- return [url$3, resolved.id];
- };
- const orderedImportedUrls = new Array(imports.length);
- const orderedAcceptedUrls = new Array(imports.length);
- const orderedAcceptedExports = new Array(imports.length);
- await Promise.all(imports.map(async (importSpecifier, index) => {
- const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, a: attributeIndex } = importSpecifier;
- let specifier = importSpecifier.n;
- const rawUrl = source.slice(start, end);
- if (rawUrl === "import.meta") {
- const prop = source.slice(end, end + 4);
- if (prop === ".hot") {
- hasHMR = true;
- const endHot = end + 4 + (source[end + 4] === "?" ? 1 : 0);
- if (source.slice(endHot, endHot + 7) === ".accept") if (source.slice(endHot, endHot + 14) === ".acceptExports") {
- const importAcceptedExports = orderedAcceptedExports[index] = /* @__PURE__ */ new Set();
- lexAcceptedHmrExports(source, source.indexOf("(", endHot + 14) + 1, importAcceptedExports);
- isPartiallySelfAccepting = true;
- } else {
- const importAcceptedUrls = orderedAcceptedUrls[index] = /* @__PURE__ */ new Set();
- if (lexAcceptedHmrDeps(source, source.indexOf("(", endHot + 7) + 1, importAcceptedUrls)) isSelfAccepting = true;
- }
- } else if (prop === ".env") hasEnv = true;
- return;
- } else if (templateLiteralRE.test(rawUrl)) {
- if (!(rawUrl.includes("${") && rawUrl.includes("}"))) specifier = rawUrl.replace(templateLiteralRE, "$1");
- }
- const isDynamicImport = dynamicIndex > -1;
- if (!isDynamicImport && attributeIndex > -1) str().remove(end + 1, expEnd);
- if (specifier !== void 0) {
- if ((isExternalUrl(specifier) && !specifier.startsWith("file://") || isDataUrl(specifier)) && !matchAlias(specifier)) return;
- if (ssr && !matchAlias(specifier)) {
- if (shouldExternalize(environment, specifier, importer)) return;
- if (isBuiltin(environment.config.resolve.builtins, specifier)) return;
- }
- if (specifier === clientPublicPath) return;
- if (specifier[0] === "/" && !(config$2.assetsInclude(cleanUrl(specifier)) || urlRE.test(specifier)) && checkPublicFile(specifier, config$2)) throw new Error(`Cannot import non-asset file ${specifier} which is inside /public. JS/CSS files inside /public are copied as-is on build and can only be referenced via <script src> or <link href> in html. If you want to get the URL of that file, use ${injectQuery(specifier, "url")} instead.`);
- let [url$3, resolvedId] = await normalizeUrl(specifier, start);
- resolvedId = resolvedId || url$3;
- config$2.safeModulePaths.add(fsPathFromUrl(stripBase(url$3, base)));
- if (url$3 !== specifier) {
- let rewriteDone = false;
- if (depsOptimizer?.isOptimizedDepFile(resolvedId) && !optimizedDepChunkRE.test(resolvedId)) {
- const file = cleanUrl(resolvedId);
- const needsInterop$1 = await optimizedDepNeedsInterop(environment, depsOptimizer.metadata, file);
- if (needsInterop$1 === void 0) {
- if (!optimizedDepDynamicRE.test(file)) config$2.logger.error(import_picocolors$13.default.red(`Vite Error, ${url$3} optimized info should be defined`));
- } else if (needsInterop$1) {
- debug$5?.(`${url$3} needs interop`);
- interopNamedImports(str(), importSpecifier, url$3, index, importer, config$2);
- rewriteDone = true;
- }
- } else if (url$3.includes(browserExternalId) && source.slice(expStart, start).includes("{")) {
- interopNamedImports(str(), importSpecifier, url$3, index, importer, config$2);
- rewriteDone = true;
- }
- if (!rewriteDone) {
- const rewrittenUrl = JSON.stringify(url$3);
- const s$1 = isDynamicImport ? start : start - 1;
- const e$1 = isDynamicImport ? end : end + 1;
- str().overwrite(s$1, e$1, rewrittenUrl, { contentOnly: true });
- }
- }
- const hmrUrl = unwrapId(stripBase(url$3, base));
- const isLocalImport = !isExternalUrl(hmrUrl) && !isDataUrl(hmrUrl);
- if (isLocalImport) orderedImportedUrls[index] = hmrUrl;
- if (enablePartialAccept && importedBindings) extractImportedBindings(resolvedId, source, importSpecifier, importedBindings);
- if (!isDynamicImport && isLocalImport && environment.config.dev.preTransformRequests) {
- const url$4 = removeImportQuery(hmrUrl);
- environment.warmupRequest(url$4);
- }
- } else if (!importer.startsWith(withTrailingSlash(clientDir))) {
- if (!isInNodeModules(importer)) {
- if (!hasViteIgnoreRE.test(source.slice(dynamicIndex + 1, end))) this.warn(`\n` + import_picocolors$13.default.cyan(importerModule.file) + `\n` + import_picocolors$13.default.reset(generateCodeFrame(source, start, end)) + import_picocolors$13.default.yellow(`\nThe above dynamic import cannot be analyzed by Vite.\nSee ${import_picocolors$13.default.blue(`https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations`)} for supported dynamic import formats. If this is intended to be left as-is, you can use the /* @vite-ignore */ comment inside the import() call to suppress this warning.\n`));
- }
- if (!ssr) {
- if (!urlIsStringRE.test(rawUrl) || isExplicitImportRequired(rawUrl.slice(1, -1))) {
- needQueryInjectHelper = true;
- str().overwrite(start, end, `__vite__injectQuery(${rawUrl}, 'import')`, { contentOnly: true });
- }
- }
- }
- }));
- const _orderedImportedUrls = orderedImportedUrls.filter(isDefined);
- const importedUrls = new Set(_orderedImportedUrls);
- const staticImportedUrls = new Set(_orderedImportedUrls.map((url$3) => removeTimestampQuery(url$3)));
- const acceptedUrls = mergeAcceptedUrls(orderedAcceptedUrls);
- const acceptedExports = mergeAcceptedUrls(orderedAcceptedExports);
- const isClassicWorker = importer.includes(WORKER_FILE_ID) && importer.includes("type=classic");
- if (hasEnv && !isClassicWorker) str().prepend(getEnv(ssr));
- if (hasHMR && !ssr && !isClassicWorker) {
- debugHmr?.(`${isSelfAccepting ? `[self-accepts]` : isPartiallySelfAccepting ? `[accepts-exports]` : acceptedUrls.size ? `[accepts-deps]` : `[detected api usage]`} ${prettifyUrl(importer, root)}`);
- str().prepend(`import { createHotContext as __vite__createHotContext } from "${clientPublicPath}";import.meta.hot = __vite__createHotContext(${JSON.stringify(normalizeHmrUrl(importerModule.url))});`);
- }
- if (needQueryInjectHelper) if (isClassicWorker) str().append("\n" + __vite__injectQuery.toString());
- else str().prepend(`import { injectQuery as __vite__injectQuery } from "${clientPublicPath}";`);
- const normalizedAcceptedUrls = /* @__PURE__ */ new Set();
- for (const { url: url$3, start, end } of acceptedUrls) {
- let [normalized, resolvedId] = await normalizeUrl(url$3, start).catch(() => []);
- if (resolvedId) {
- const mod = moduleGraph.getModuleById(resolvedId);
- if (!mod) {
- this.error(`module was not found for ${JSON.stringify(resolvedId)}`, start);
- return;
- }
- normalized = mod.url;
- } else try {
- const [resolved] = await moduleGraph.resolveUrl(toAbsoluteUrl(url$3));
- normalized = resolved;
- if (resolved) this.warn({
- message: `Failed to resolve ${JSON.stringify(url$3)} from ${importer}. An id should be written. Did you pass a URL?`,
- pos: start
- });
- } catch {
- this.error(`Failed to resolve ${JSON.stringify(url$3)}`, start);
- return;
- }
- normalizedAcceptedUrls.add(normalized);
- const hmrAccept = normalizeHmrUrl(normalized);
- str().overwrite(start, end, JSON.stringify(hmrAccept), { contentOnly: true });
- }
- if (!isCSSRequest(importer) || SPECIAL_QUERY_RE.test(importer)) {
- const pluginImports = this._addedImports;
- if (pluginImports) (await Promise.all([...pluginImports].map((id) => normalizeUrl(id, 0, true)))).forEach(([url$3]) => importedUrls.add(stripBase(url$3, base)));
- if (ssr && importerModule.isSelfAccepting) isSelfAccepting = true;
- if (!isSelfAccepting && isPartiallySelfAccepting && acceptedExports.size >= exports$1.length && exports$1.every((e$1) => acceptedExports.has(e$1.n))) isSelfAccepting = true;
- const prunedImports = await moduleGraph.updateModuleInfo(importerModule, importedUrls, importedBindings, normalizedAcceptedUrls, isPartiallySelfAccepting ? acceptedExports : null, isSelfAccepting, staticImportedUrls);
- if (prunedImports) handlePrunedModules(prunedImports, environment);
- }
- debug$5?.(`${timeFrom(msAtStart)} ${import_picocolors$13.default.dim(`[${importedUrls.size} imports rewritten] ${prettifyUrl(importer, root)}`)}`);
- if (s) return transformStableResult(s, importer, config$2);
- else return source;
- }
- };
-}
-function mergeAcceptedUrls(orderedUrls) {
- const acceptedUrls = /* @__PURE__ */ new Set();
- for (const urls of orderedUrls) {
- if (!urls) continue;
- for (const url$3 of urls) acceptedUrls.add(url$3);
- }
- return acceptedUrls;
-}
-function createParseErrorInfo(importer, source) {
- const isVue = importer.endsWith(".vue");
- const isJsx = importer.endsWith(".jsx") || importer.endsWith(".tsx");
- const maybeJSX = !isVue && isJSRequest(importer);
- const probablyBinary = source.includes("�");
- return {
- message: "Failed to parse source for import analysis because the content contains invalid JS syntax. " + (isVue ? `Install @vitejs/plugin-vue to handle .vue files.` : maybeJSX ? isJsx ? `If you use tsconfig.json, make sure to not set jsx to preserve.` : `If you are using JSX, make sure to name the file with the .jsx or .tsx extension.` : `You may need to install appropriate plugins to handle the ${path.extname(importer)} file format, or if it's an asset, add "**/*${path.extname(importer)}" to \`assetsInclude\` in your configuration.`),
- showCodeFrame: !probablyBinary
- };
-}
-const interopHelper = (m) => m?.__esModule ? m : {
- ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {},
- default: m
-};
-const interopHelperStr = interopHelper.toString().replaceAll("\n", "");
-function interopNamedImports(str, importSpecifier, rewrittenUrl, importIndex, importer, config$2) {
- const source = str.original;
- const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex } = importSpecifier;
- const exp = source.slice(expStart, expEnd);
- if (dynamicIndex > -1) str.overwrite(expStart, expEnd, `import('${rewrittenUrl}').then(m => (${interopHelperStr})(m.default))` + getLineBreaks(exp), { contentOnly: true });
- else {
- const rewritten = transformCjsImport(exp, rewrittenUrl, source.slice(start, end), importIndex, importer, config$2);
- if (rewritten) str.overwrite(expStart, expEnd, rewritten + getLineBreaks(exp), { contentOnly: true });
- else str.overwrite(start, end, rewrittenUrl + getLineBreaks(source.slice(start, end)), { contentOnly: true });
- }
-}
-function getLineBreaks(str) {
- return str.includes("\n") ? "\n".repeat(str.split("\n").length - 1) : "";
-}
-/**
-* Detect import statements to a known optimized CJS dependency and provide
-* ES named imports interop. We do this by rewriting named imports to a variable
-* assignment to the corresponding property on the `module.exports` of the cjs
-* module. Note this doesn't support dynamic re-assignments from within the cjs
-* module.
-*
-* Note that es-module-lexer treats `export * from '...'` as an import as well,
-* so, we may encounter ExportAllDeclaration here, in which case `undefined`
-* will be returned.
-*
-* Credits \@csr632 via #837
-*/
-function transformCjsImport(importExp, url$3, rawUrl, importIndex, importer, config$2) {
- const node = parseAst(importExp).body[0];
- if (config$2.command === "serve" && node.type === "ExportAllDeclaration" && !node.exported) config$2.logger.warn(import_picocolors$13.default.yellow(`\nUnable to interop \`${importExp}\` in ${importer}, this may lose module exports. Please export "${rawUrl}" as ESM or use named exports instead, e.g. \`export { A, B } from "${rawUrl}"\``));
- else if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration") {
- if (!node.specifiers.length) return `import "${url$3}"`;
- const importNames = [];
- const exportNames = [];
- let defaultExports = "";
- for (const spec of node.specifiers) if (spec.type === "ImportSpecifier") {
- const importedName = getIdentifierNameOrLiteralValue(spec.imported);
- importNames.push({
- importedName,
- localName: spec.local.name
- });
- } else if (spec.type === "ImportDefaultSpecifier") importNames.push({
- importedName: "default",
- localName: spec.local.name
- });
- else if (spec.type === "ImportNamespaceSpecifier") importNames.push({
- importedName: "*",
- localName: spec.local.name
- });
- else if (spec.type === "ExportSpecifier") {
- const importedName = getIdentifierNameOrLiteralValue(spec.local);
- const exportedName = getIdentifierNameOrLiteralValue(spec.exported);
- if (exportedName === "default") {
- defaultExports = makeLegalIdentifier(`__vite__cjsExportDefault_${importIndex}`);
- importNames.push({
- importedName,
- localName: defaultExports
- });
- } else {
- const localName = `__vite__cjsExport${spec.exported.type === "Literal" ? `L_${getHash(spec.exported.value)}` : "I_" + spec.exported.name}`;
- importNames.push({
- importedName,
- localName
- });
- exportNames.push(`${localName} as ${spec.exported.type === "Literal" ? JSON.stringify(exportedName) : exportedName}`);
- }
- }
- const cjsModuleName = makeLegalIdentifier(`__vite__cjsImport${importIndex}_${rawUrl}`);
- const lines = [`import ${cjsModuleName} from "${url$3}"`];
- importNames.forEach(({ importedName, localName }) => {
- if (importedName === "*") lines.push(`const ${localName} = (${interopHelperStr})(${cjsModuleName})`);
- else if (importedName === "default") lines.push(`const ${localName} = ${cjsModuleName}.__esModule ? ${cjsModuleName}.default : ${cjsModuleName}`);
- else lines.push(`const ${localName} = ${cjsModuleName}["${importedName}"]`);
- });
- if (defaultExports) lines.push(`export default ${defaultExports}`);
- if (exportNames.length) lines.push(`export { ${exportNames.join(", ")} }`);
- return lines.join("; ");
- }
-}
-function getIdentifierNameOrLiteralValue(node) {
- return node.type === "Identifier" ? node.name : node.value;
-}
-function __vite__injectQuery(url$3, queryToInject) {
- if (url$3[0] !== "." && url$3[0] !== "/") return url$3;
- const pathname = url$3.replace(/[?#].*$/, "");
- const { search, hash: hash$1 } = new URL(url$3, "http://vite.dev");
- return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ""}${hash$1 || ""}`;
-}
-
-//#endregion
-//#region src/node/plugins/clientInjections.ts
-const normalizedClientEntry$1 = normalizePath(CLIENT_ENTRY);
-const normalizedEnvEntry$1 = normalizePath(ENV_ENTRY);
-/**
-* some values used by the client needs to be dynamically injected by the server
-* @server-only
-*/
-function clientInjectionsPlugin(config$2) {
- let injectConfigValues;
- const getDefineReplacer = perEnvironmentState((environment) => {
- const userDefine = {};
- for (const key in environment.config.define) if (!key.startsWith("import.meta.env.")) userDefine[key] = environment.config.define[key];
- const serializedDefines = serializeDefine(userDefine);
- const definesReplacement = () => serializedDefines;
- return (code) => code.replace(`__DEFINES__`, definesReplacement);
- });
- return {
- name: "vite:client-inject",
- async buildStart() {
- const resolvedServerHostname = (await resolveHostname(config$2.server.host)).name;
- const resolvedServerPort = config$2.server.port;
- const devBase = config$2.base;
- const serverHost = `${resolvedServerHostname}:${resolvedServerPort}${devBase}`;
- let hmrConfig = config$2.server.hmr;
- hmrConfig = isObject(hmrConfig) ? hmrConfig : void 0;
- const host = hmrConfig?.host || null;
- const protocol = hmrConfig?.protocol || null;
- const timeout$1 = hmrConfig?.timeout || 3e4;
- const overlay = hmrConfig?.overlay !== false;
- const isHmrServerSpecified = !!hmrConfig?.server;
- const hmrConfigName = path.basename(config$2.configFile || "vite.config.js");
- let port = hmrConfig?.clientPort || hmrConfig?.port || null;
- if (config$2.server.middlewareMode && !isHmrServerSpecified) port ||= 24678;
- let directTarget = hmrConfig?.host || resolvedServerHostname;
- directTarget += `:${hmrConfig?.port || resolvedServerPort}`;
- directTarget += devBase;
- let hmrBase = devBase;
- if (hmrConfig?.path) hmrBase = path.posix.join(hmrBase, hmrConfig.path);
- const modeReplacement = escapeReplacement(config$2.mode);
- const baseReplacement = escapeReplacement(devBase);
- const serverHostReplacement = escapeReplacement(serverHost);
- const hmrProtocolReplacement = escapeReplacement(protocol);
- const hmrHostnameReplacement = escapeReplacement(host);
- const hmrPortReplacement = escapeReplacement(port);
- const hmrDirectTargetReplacement = escapeReplacement(directTarget);
- const hmrBaseReplacement = escapeReplacement(hmrBase);
- const hmrTimeoutReplacement = escapeReplacement(timeout$1);
- const hmrEnableOverlayReplacement = escapeReplacement(overlay);
- const hmrConfigNameReplacement = escapeReplacement(hmrConfigName);
- const wsTokenReplacement = escapeReplacement(config$2.webSocketToken);
- injectConfigValues = (code) => {
- return code.replace(`__MODE__`, modeReplacement).replace(/__BASE__/g, baseReplacement).replace(`__SERVER_HOST__`, serverHostReplacement).replace(`__HMR_PROTOCOL__`, hmrProtocolReplacement).replace(`__HMR_HOSTNAME__`, hmrHostnameReplacement).replace(`__HMR_PORT__`, hmrPortReplacement).replace(`__HMR_DIRECT_TARGET__`, hmrDirectTargetReplacement).replace(`__HMR_BASE__`, hmrBaseReplacement).replace(`__HMR_TIMEOUT__`, hmrTimeoutReplacement).replace(`__HMR_ENABLE_OVERLAY__`, hmrEnableOverlayReplacement).replace(`__HMR_CONFIG_NAME__`, hmrConfigNameReplacement).replace(`__WS_TOKEN__`, wsTokenReplacement);
- };
- },
- async transform(code, id) {
- const ssr = this.environment.config.consumer === "server";
- const cleanId = cleanUrl(id);
- if (cleanId === normalizedClientEntry$1 || cleanId === normalizedEnvEntry$1) return getDefineReplacer(this)(injectConfigValues(code));
- else if (!ssr && code.includes("process.env.NODE_ENV")) {
- const nodeEnv = this.environment.config.define?.["process.env.NODE_ENV"] || JSON.stringify(process.env.NODE_ENV || config$2.mode);
- return await replaceDefine(this.environment, code, id, {
- "process.env.NODE_ENV": nodeEnv,
- "global.process.env.NODE_ENV": nodeEnv,
- "globalThis.process.env.NODE_ENV": nodeEnv
- });
- }
- }
- };
-}
-function escapeReplacement(value$1) {
- const jsonValue = JSON.stringify(value$1);
- return () => jsonValue;
-}
-
-//#endregion
-//#region src/node/plugins/wasm.ts
-const wasmHelperId = "\0vite/wasm-helper.js";
-const wasmInitRE = /(?<![?#].*)\.wasm\?init/;
-const wasmHelper = async (opts = {}, url$3) => {
- let result;
- if (url$3.startsWith("data:")) {
- const urlContent = url$3.replace(/^data:.*?base64,/, "");
- let bytes;
- if (typeof Buffer === "function" && typeof Buffer.from === "function") bytes = Buffer.from(urlContent, "base64");
- else if (typeof atob === "function") {
- const binaryString = atob(urlContent);
- bytes = new Uint8Array(binaryString.length);
- for (let i$1 = 0; i$1 < binaryString.length; i$1++) bytes[i$1] = binaryString.charCodeAt(i$1);
- } else throw new Error("Failed to decode base64-encoded data URL, Buffer and atob are not supported");
- result = await WebAssembly.instantiate(bytes, opts);
- } else {
- const response = await fetch(url$3);
- const contentType = response.headers.get("Content-Type") || "";
- if ("instantiateStreaming" in WebAssembly && contentType.startsWith("application/wasm")) result = await WebAssembly.instantiateStreaming(response, opts);
- else {
- const buffer = await response.arrayBuffer();
- result = await WebAssembly.instantiate(buffer, opts);
- }
- }
- return result.instance;
-};
-const wasmHelperCode = wasmHelper.toString();
-const wasmHelperPlugin = () => {
- return {
- name: "vite:wasm-helper",
- resolveId: {
- filter: { id: exactRegex(wasmHelperId) },
- handler(id) {
- return id;
- }
- },
- load: {
- filter: { id: [exactRegex(wasmHelperId), wasmInitRE] },
- async handler(id) {
- if (id === wasmHelperId) return `export default ${wasmHelperCode}`;
- const url$3 = await fileToUrl$1(this, id);
- return `
- import initWasm from "${wasmHelperId}"
- export default opts => initWasm(opts, ${JSON.stringify(url$3)})
- `;
- }
- }
- };
-};
-const wasmFallbackPlugin = () => {
- return {
- name: "vite:wasm-fallback",
- load: {
- filter: { id: /\.wasm$/ },
- handler(_id) {
- throw new Error("\"ESM integration proposal for Wasm\" is not supported currently. Use vite-plugin-wasm or other community plugins to handle this. Alternatively, you can use `.wasm?init` or `.wasm?url`. See https://vite.dev/guide/features.html#webassembly for more details.");
- }
- }
- };
-};
-
-//#endregion
-//#region src/node/plugins/workerImportMetaUrl.ts
-function err$1(e$1, pos) {
- const error$1 = new Error(e$1);
- error$1.pos = pos;
- return error$1;
-}
-function findClosingParen(input, fromIndex) {
- let count = 1;
- for (let i$1 = fromIndex; i$1 < input.length; i$1++) {
- if (input[i$1] === "(") count++;
- if (input[i$1] === ")") count--;
- if (count === 0) return i$1;
- }
- return -1;
-}
-function extractWorkerTypeFromAst(expression, optsStartIndex) {
- if (expression.type !== "ObjectExpression") return;
- let lastSpreadElementIndex = -1;
- let typeProperty = null;
- let typePropertyIndex = -1;
- for (let i$1 = 0; i$1 < expression.properties.length; i$1++) {
- const property = expression.properties[i$1];
- if (property.type === "SpreadElement") {
- lastSpreadElementIndex = i$1;
- continue;
- }
- if (property.type === "Property" && (property.key.type === "Identifier" && property.key.name === "type" || property.key.type === "Literal" && property.key.value === "type")) {
- typeProperty = property;
- typePropertyIndex = i$1;
- }
- }
- if (typePropertyIndex === -1 && lastSpreadElementIndex === -1) return "classic";
- if (typePropertyIndex < lastSpreadElementIndex) throw err$1("Expected object spread to be used before the definition of the type property. Vite needs a static value for the type property to correctly infer it.", optsStartIndex);
- if (typeProperty?.value.type !== "Literal") throw err$1("Expected worker options type property to be a literal value.", optsStartIndex);
- return typeProperty?.value.value === "module" ? "module" : "classic";
-}
-async function parseWorkerOptions(rawOpts, optsStartIndex) {
- let opts = {};
- try {
- opts = evalValue(rawOpts);
- } catch {
- const optsNode = (await parseAstAsync(`(${rawOpts})`)).body[0].expression;
- const type = extractWorkerTypeFromAst(optsNode, optsStartIndex);
- if (type) return { type };
- throw err$1("Vite is unable to parse the worker options as the value is not static. To ignore this error, please use /* @vite-ignore */ in the worker options.", optsStartIndex);
- }
- if (opts == null) return {};
- if (typeof opts !== "object") throw err$1(`Expected worker options to be an object, got ${typeof opts}`, optsStartIndex);
- return opts;
-}
-async function getWorkerType(raw, clean, i$1) {
- const commaIndex = clean.indexOf(",", i$1);
- if (commaIndex === -1) return "classic";
- const endIndex = findClosingParen(clean, i$1);
- if (commaIndex > endIndex) return "classic";
- let workerOptString = raw.substring(commaIndex + 1, endIndex);
- if (hasViteIgnoreRE.test(workerOptString)) return "ignore";
- const cleanWorkerOptString = clean.substring(commaIndex + 1, endIndex);
- const trimmedCleanWorkerOptString = cleanWorkerOptString.trim();
- if (!trimmedCleanWorkerOptString.length) return "classic";
- if (trimmedCleanWorkerOptString.endsWith(",")) workerOptString = workerOptString.slice(0, cleanWorkerOptString.lastIndexOf(","));
- const workerOpts = await parseWorkerOptions(workerOptString, commaIndex + 1);
- if (workerOpts.type && (workerOpts.type === "module" || workerOpts.type === "classic")) return workerOpts.type;
- return "classic";
-}
-const workerImportMetaUrlRE = /new\s+(?:Worker|SharedWorker)\s*\(\s*new\s+URL.+?import\.meta\.url/s;
-function workerImportMetaUrlPlugin(config$2) {
- const isBuild = config$2.command === "build";
- let workerResolver;
- const fsResolveOptions = {
- ...config$2.resolve,
- root: config$2.root,
- isProduction: config$2.isProduction,
- isBuild: config$2.command === "build",
- packageCache: config$2.packageCache,
- asSrc: true
- };
- return {
- name: "vite:worker-import-meta-url",
- applyToEnvironment(environment) {
- return environment.config.consumer === "client";
- },
- transform: {
- filter: { code: workerImportMetaUrlRE },
- async handler(code, id) {
- let s;
- const cleanString = stripLiteral(code);
- const workerImportMetaUrlRE$1 = /\bnew\s+(?:Worker|SharedWorker)\s*\(\s*(new\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*\))/dg;
- let match;
- while (match = workerImportMetaUrlRE$1.exec(cleanString)) {
- const [[, endIndex], [expStart, expEnd], [urlStart, urlEnd]] = match.indices;
- const rawUrl = code.slice(urlStart, urlEnd);
- if (rawUrl[0] === "`" && rawUrl.includes("${")) this.error(`\`new URL(url, import.meta.url)\` is not supported in dynamic template string.`, expStart);
- s ||= new MagicString(code);
- const workerType = await getWorkerType(code, cleanString, endIndex);
- const url$3 = rawUrl.slice(1, -1);
- let file;
- if (url$3[0] === ".") {
- file = path.resolve(path.dirname(id), url$3);
- file = slash(tryFsResolve(file, fsResolveOptions) ?? file);
- } else {
- workerResolver ??= createBackCompatIdResolver(config$2, {
- extensions: [],
- tryIndex: false,
- preferRelative: true
- });
- file = await workerResolver(this.environment, url$3, id);
- file ??= url$3[0] === "/" ? slash(path.join(config$2.publicDir, url$3)) : slash(path.resolve(path.dirname(id), url$3));
- }
- if (isBuild && config$2.isWorker && config$2.bundleChain.at(-1) === cleanUrl(file)) s.update(expStart, expEnd, "self.location.href");
- else {
- let builtUrl;
- if (isBuild) {
- const result = await workerFileToUrl(config$2, file);
- builtUrl = result.entryUrlPlaceholder;
- for (const file$1 of result.watchedFiles) this.addWatchFile(file$1);
- } else {
- builtUrl = await fileToUrl$1(this, cleanUrl(file));
- builtUrl = injectQuery(builtUrl, `${WORKER_FILE_ID}&type=${workerType}`);
- }
- s.update(expStart, expEnd, `new URL(/* @vite-ignore */ ${JSON.stringify(builtUrl)}, import.meta.url)`);
- }
- }
- if (s) return transformStableResult(s, id, config$2);
- return null;
- }
- }
- };
-}
-
-//#endregion
-//#region src/node/plugins/assetImportMetaUrl.ts
-/**
-* Convert `new URL('./foo.png', import.meta.url)` to its resolved built URL
-*
-* Supports template string with dynamic segments:
-* ```
-* new URL(`./dir/${name}.png`, import.meta.url)
-* // transformed to
-* import.meta.glob('./dir/**.png', { eager: true, import: 'default' })[`./dir/${name}.png`]
-* ```
-*/
-function assetImportMetaUrlPlugin(config$2) {
- const { publicDir } = config$2;
- let assetResolver;
- const fsResolveOptions = {
- ...config$2.resolve,
- root: config$2.root,
- isProduction: config$2.isProduction,
- isBuild: config$2.command === "build",
- packageCache: config$2.packageCache,
- asSrc: true
- };
- return {
- name: "vite:asset-import-meta-url",
- applyToEnvironment(environment) {
- return environment.config.consumer === "client";
- },
- transform: {
- filter: {
- id: { exclude: [exactRegex(preloadHelperId), exactRegex(CLIENT_ENTRY)] },
- code: /new\s+URL.+import\.meta\.url/s
- },
- async handler(code, id) {
- let s;
- const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/dg;
- const cleanString = stripLiteral(code);
- let match;
- while (match = assetImportMetaUrlRE.exec(cleanString)) {
- const [[startIndex, endIndex], [urlStart, urlEnd]] = match.indices;
- if (hasViteIgnoreRE.test(code.slice(startIndex, urlStart))) continue;
- const rawUrl = code.slice(urlStart, urlEnd);
- if (!s) s = new MagicString(code);
- if (rawUrl[0] === "`" && rawUrl.includes("${")) {
- const queryDelimiterIndex = getQueryDelimiterIndex(rawUrl);
- const hasQueryDelimiter = queryDelimiterIndex !== -1;
- const pureUrl = hasQueryDelimiter ? rawUrl.slice(0, queryDelimiterIndex) + "`" : rawUrl;
- const queryString = hasQueryDelimiter ? rawUrl.slice(queryDelimiterIndex, -1) : "";
- const templateLiteral = this.parse(pureUrl).body[0].expression;
- if (templateLiteral.expressions.length) {
- const pattern = buildGlobPattern(templateLiteral);
- if (pattern[0] === "*") continue;
- const globOptions = {
- eager: true,
- import: "default",
- query: injectQuery(queryString, "url")
- };
- s.update(startIndex, endIndex, `new URL((import.meta.glob(${JSON.stringify(pattern)}, ${JSON.stringify(globOptions)}))[${pureUrl}], import.meta.url)`);
- continue;
- }
- }
- const url$3 = rawUrl.slice(1, -1);
- if (isDataUrl(url$3)) continue;
- let file;
- if (url$3[0] === ".") {
- file = slash(path.resolve(path.dirname(id), url$3));
- file = tryFsResolve(file, fsResolveOptions) ?? file;
- } else {
- assetResolver ??= createBackCompatIdResolver(config$2, {
- extensions: [],
- mainFields: [],
- tryIndex: false,
- preferRelative: true
- });
- file = await assetResolver(this.environment, url$3, id);
- file ??= url$3[0] === "/" ? slash(path.join(publicDir, url$3)) : slash(path.resolve(path.dirname(id), url$3));
- }
- let builtUrl;
- if (file) try {
- if (publicDir && isParentDirectory(publicDir, file)) {
- const publicPath = "/" + path.posix.relative(publicDir, file);
- builtUrl = await fileToUrl$1(this, publicPath);
- } else {
- builtUrl = await fileToUrl$1(this, file);
- if (tryStatSync(file)?.isFile()) this.addWatchFile(file);
- }
- } catch {}
- if (!builtUrl) {
- const rawExp = code.slice(startIndex, endIndex);
- config$2.logger.warnOnce(`\n${rawExp} doesn't exist at build time, it will remain unchanged to be resolved at runtime. If this is intended, you can use the /* @vite-ignore */ comment to suppress this warning.`);
- builtUrl = url$3;
- }
- s.update(startIndex, endIndex, `new URL(${JSON.stringify(builtUrl)}, import.meta.url)`);
- }
- if (s) return transformStableResult(s, id, config$2);
- }
- }
- };
-}
-function buildGlobPattern(ast) {
- let pattern = "";
- let lastIsGlob = false;
- for (let i$1 = 0; i$1 < ast.quasis.length; i$1++) {
- const str = ast.quasis[i$1].value.raw;
- if (str) {
- pattern += str;
- lastIsGlob = false;
- }
- if (ast.expressions[i$1] && !lastIsGlob) {
- pattern += "*";
- lastIsGlob = true;
- }
- }
- return pattern;
-}
-function getQueryDelimiterIndex(rawUrl) {
- let bracketsStack = 0;
- for (let i$1 = 0; i$1 < rawUrl.length; i$1++) if (rawUrl[i$1] === "{") bracketsStack++;
- else if (rawUrl[i$1] === "}") bracketsStack--;
- else if (rawUrl[i$1] === "?" && bracketsStack === 0) return i$1;
- return -1;
-}
-
-//#endregion
-//#region src/node/plugins/metadata.ts
-/**
-* Prepares the rendered chunks to contain additional metadata during build.
-*/
-function metadataPlugin() {
- return {
- name: "vite:build-metadata",
- async renderChunk(_code, chunk) {
- chunk.viteMetadata = {
- importedAssets: /* @__PURE__ */ new Set(),
- importedCss: /* @__PURE__ */ new Set()
- };
- return null;
- }
- };
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/@rollup+plugin-dynamic-import-vars@2.1.4_rollup@4.43.0/node_modules/@rollup/plugin-dynamic-import-vars/dist/es/index.js
-var VariableDynamicImportError = class extends Error {};
-const example = "For example: import(`./foo/${bar}.js`).";
-function sanitizeString(str) {
- if (str === "") return str;
- if (str.includes("*")) throw new VariableDynamicImportError("A dynamic import cannot contain * characters.");
- return escapePath(str);
-}
-function templateLiteralToGlob(node) {
- let glob$1 = "";
- for (let i$1 = 0; i$1 < node.quasis.length; i$1 += 1) {
- glob$1 += sanitizeString(node.quasis[i$1].value.raw);
- if (node.expressions[i$1]) glob$1 += expressionToGlob(node.expressions[i$1]);
- }
- return glob$1;
-}
-function callExpressionToGlob(node) {
- const { callee } = node;
- if (callee.type === "MemberExpression" && callee.property.type === "Identifier" && callee.property.name === "concat") return `${expressionToGlob(callee.object)}${node.arguments.map(expressionToGlob).join("")}`;
- return "*";
-}
-function binaryExpressionToGlob(node) {
- if (node.operator !== "+") throw new VariableDynamicImportError(`${node.operator} operator is not supported.`);
- return `${expressionToGlob(node.left)}${expressionToGlob(node.right)}`;
-}
-function expressionToGlob(node) {
- switch (node.type) {
- case "TemplateLiteral": return templateLiteralToGlob(node);
- case "CallExpression": return callExpressionToGlob(node);
- case "BinaryExpression": return binaryExpressionToGlob(node);
- case "Literal": return sanitizeString(node.value);
- default: return "*";
- }
-}
-const defaultProtocol = "file:";
-const ignoredProtocols = [
- "data:",
- "http:",
- "https:"
-];
-function shouldIgnore(glob$1) {
- const containsAsterisk = glob$1.includes("*");
- const globURL = new URL(glob$1, defaultProtocol);
- const containsIgnoredProtocol = ignoredProtocols.some((ignoredProtocol) => ignoredProtocol === globURL.protocol);
- return !containsAsterisk || containsIgnoredProtocol;
-}
-function dynamicImportToGlob(node, sourceString) {
- let glob$1 = expressionToGlob(node);
- if (shouldIgnore(glob$1)) return null;
- glob$1 = glob$1.replace(/\*\*/g, "*");
- if (glob$1.startsWith("*")) throw new VariableDynamicImportError(`invalid import "${sourceString}". It cannot be statically analyzed. Variable dynamic imports must start with ./ and be limited to a specific directory. ${example}`);
- if (glob$1.startsWith("/")) throw new VariableDynamicImportError(`invalid import "${sourceString}". Variable absolute imports are not supported, imports must start with ./ in the static part of the import. ${example}`);
- if (!glob$1.startsWith("./") && !glob$1.startsWith("../")) throw new VariableDynamicImportError(`invalid import "${sourceString}". Variable bare imports are not supported, imports must start with ./ in the static part of the import. ${example}`);
- if (/^\.\/\*\.\w+$/.test(glob$1)) throw new VariableDynamicImportError(`${`invalid import "${sourceString}". Variable imports cannot import their own directory, place imports in a separate directory or make the import filename more specific. `}${example}`);
- if (path$1.extname(glob$1) === "") throw new VariableDynamicImportError(`invalid import "${sourceString}". A file extension must be included in the static part of the import. ${example}`);
- return glob$1;
-}
-
-//#endregion
-//#region src/node/plugins/dynamicImportVars.ts
-const dynamicImportHelperId = "\0vite/dynamic-import-helper.js";
-const relativePathRE = /^\.{1,2}\//;
-const hasDynamicImportRE = /\bimport\s*[(/]/;
-const dynamicImportHelper = (glob$1, path$13, segs) => {
- const v = glob$1[path$13];
- if (v) return typeof v === "function" ? v() : Promise.resolve(v);
- return new Promise((_, reject) => {
- (typeof queueMicrotask === "function" ? queueMicrotask : setTimeout)(reject.bind(null, /* @__PURE__ */ new Error("Unknown variable dynamic import: " + path$13 + (path$13.split("/").length !== segs ? ". Note that variables only represent file names one level deep." : ""))));
- });
-};
-function parseDynamicImportPattern(strings) {
- const filename = strings.slice(1, -1);
- const ast = parseAst(strings).body[0].expression;
- const userPatternQuery = dynamicImportToGlob(ast, filename);
- if (!userPatternQuery) return null;
- const [userPattern] = userPatternQuery.split(requestQueryMaybeEscapedSplitRE, 2);
- let [rawPattern, search] = filename.split(requestQuerySplitRE, 2);
- let globParams = null;
- if (search) {
- search = "?" + search;
- if (workerOrSharedWorkerRE.test(search) || urlRE.test(search) || rawRE.test(search)) globParams = {
- query: search,
- import: "*"
- };
- else globParams = { query: search };
- }
- return {
- globParams,
- userPattern,
- rawPattern
- };
-}
-async function transformDynamicImport(importSource, importer, resolve$4, root) {
- if (importSource[1] !== "." && importSource[1] !== "/") {
- const resolvedFileName = await resolve$4(importSource.slice(1, -1), importer);
- if (!resolvedFileName) return null;
- const relativeFileName = normalizePath(posix.relative(posix.dirname(normalizePath(importer)), normalizePath(resolvedFileName)));
- importSource = "`" + (relativeFileName[0] === "." ? "" : "./") + relativeFileName + "`";
- }
- const dynamicImportPattern = parseDynamicImportPattern(importSource);
- if (!dynamicImportPattern) return null;
- const { globParams, rawPattern, userPattern } = dynamicImportPattern;
- const params = globParams ? `, ${JSON.stringify(globParams)}` : "";
- const dir = importer ? posix.dirname(importer) : root;
- const normalized = rawPattern[0] === "/" ? posix.join(root, rawPattern.slice(1)) : posix.join(dir, rawPattern);
- let newRawPattern = posix.relative(posix.dirname(importer), normalized);
- if (!relativePathRE.test(newRawPattern)) newRawPattern = `./${newRawPattern}`;
- const exp = `(import.meta.glob(${JSON.stringify(userPattern)}${params}))`;
- return {
- rawPattern: newRawPattern,
- pattern: userPattern,
- glob: exp
- };
-}
-function dynamicImportVarsPlugin(config$2) {
- const resolve$4 = createBackCompatIdResolver(config$2, {
- preferRelative: true,
- tryIndex: false,
- extensions: []
- });
- const getFilter = perEnvironmentState((environment) => {
- const { include, exclude } = environment.config.build.dynamicImportVarsOptions;
- return createFilter(include, exclude);
- });
- return {
- name: "vite:dynamic-import-vars",
- resolveId: {
- filter: { id: exactRegex(dynamicImportHelperId) },
- handler(id) {
- return id;
- }
- },
- load: {
- filter: { id: exactRegex(dynamicImportHelperId) },
- handler(_id) {
- return `export default ${dynamicImportHelper.toString()}`;
- }
- },
- transform: {
- filter: {
- id: { exclude: exactRegex(CLIENT_ENTRY) },
- code: hasDynamicImportRE
- },
- async handler(source, importer) {
- const { environment } = this;
- if (!getFilter(this)(importer)) return;
- await init;
- let imports = [];
- try {
- imports = parse(source)[0];
- } catch {
- return null;
- }
- if (!imports.length) return null;
- let s;
- let needDynamicImportHelper = false;
- for (let index = 0; index < imports.length; index++) {
- const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex } = imports[index];
- if (dynamicIndex === -1 || source[start] !== "`") continue;
- if (hasViteIgnoreRE.test(source.slice(expStart, expEnd))) continue;
- s ||= new MagicString(source);
- let result;
- try {
- result = await transformDynamicImport(source.slice(start, end), importer, (id, importer$1) => resolve$4(environment, id, importer$1), config$2.root);
- } catch (error$1) {
- if (environment.config.build.dynamicImportVarsOptions.warnOnError) this.warn(error$1);
- else this.error(error$1);
- }
- if (!result) continue;
- const { rawPattern, glob: glob$1 } = result;
- needDynamicImportHelper = true;
- s.overwrite(expStart, expEnd, `__variableDynamicImportRuntimeHelper(${glob$1}, \`${rawPattern}\`, ${rawPattern.split("/").length})`);
- }
- if (s) {
- if (needDynamicImportHelper) s.prepend(`import __variableDynamicImportRuntimeHelper from "${dynamicImportHelperId}";`);
- return transformStableResult(s, importer, config$2);
- }
- }
- }
- };
-}
-
-//#endregion
-//#region src/node/plugins/importMetaGlob.ts
-var import_picocolors$12 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-function importGlobPlugin(config$2) {
- const importGlobMaps = /* @__PURE__ */ new Map();
- return {
- name: "vite:import-glob",
- buildStart() {
- importGlobMaps.clear();
- },
- transform: {
- filter: { code: "import.meta.glob" },
- async handler(code, id) {
- const result = await transformGlobImport(code, id, config$2.root, (im, _, options$1) => this.resolve(im, id, options$1).then((i$1) => i$1?.id || im), config$2.experimental.importGlobRestoreExtension, config$2.logger);
- if (result) {
- const allGlobs = result.matches.map((i$1) => i$1.globsResolved);
- if (!importGlobMaps.has(this.environment)) importGlobMaps.set(this.environment, /* @__PURE__ */ new Map());
- const globMatchers = allGlobs.map((globs) => {
- const affirmed = [];
- const negated = [];
- for (const glob$1 of globs) if (glob$1[0] === "!") negated.push(glob$1.slice(1));
- else affirmed.push(glob$1);
- const affirmedMatcher = picomatch(affirmed);
- const negatedMatcher = picomatch(negated);
- return (file) => {
- return (affirmed.length === 0 || affirmedMatcher(file)) && !(negated.length > 0 && negatedMatcher(file));
- };
- });
- importGlobMaps.get(this.environment).set(id, globMatchers);
- return transformStableResult(result.s, id, config$2);
- }
- }
- },
- hotUpdate({ type, file, modules: oldModules }) {
- if (type === "update") return;
- const importGlobMap = importGlobMaps.get(this.environment);
- if (!importGlobMap) return;
- const modules = [];
- for (const [id, globMatchers] of importGlobMap) if (globMatchers.some((matcher) => matcher(file))) {
- const mod = this.environment.moduleGraph.getModuleById(id);
- if (mod) modules.push(mod);
- }
- return modules.length > 0 ? [...oldModules, ...modules] : void 0;
- }
- };
-}
-const importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g;
-const objectKeysRE = /\bObject\.keys\(\s*$/;
-const objectValuesRE = /\bObject\.values\(\s*$/;
-const knownOptions = {
- as: ["string"],
- eager: ["boolean"],
- import: ["string"],
- exhaustive: ["boolean"],
- query: ["object", "string"],
- base: ["string"]
-};
-const forceDefaultAs = ["raw", "url"];
-function err(e$1, pos) {
- const error$1 = new Error(e$1);
- error$1.pos = pos;
- return error$1;
-}
-function parseGlobOptions(rawOpts, optsStartIndex, logger) {
- let opts = {};
- try {
- opts = evalValue(rawOpts);
- } catch {
- throw err("Vite is unable to parse the glob options as the value is not static", optsStartIndex);
- }
- if (opts == null) return {};
- for (const key in opts) {
- if (!(key in knownOptions)) throw err(`Unknown glob option "${key}"`, optsStartIndex);
- const allowedTypes = knownOptions[key];
- const valueType = typeof opts[key];
- if (!allowedTypes.includes(valueType)) throw err(`Expected glob option "${key}" to be of type ${allowedTypes.join(" or ")}, but got ${valueType}`, optsStartIndex);
- }
- if (opts.base) {
- if (opts.base[0] === "!") throw err("Option \"base\" cannot start with \"!\"", optsStartIndex);
- else if (opts.base[0] !== "/" && !opts.base.startsWith("./") && !opts.base.startsWith("../")) throw err(`Option "base" must start with '/', './' or '../', but got "${opts.base}"`, optsStartIndex);
- }
- if (typeof opts.query === "object") {
- for (const key in opts.query) {
- const value$1 = opts.query[key];
- if (![
- "string",
- "number",
- "boolean"
- ].includes(typeof value$1)) throw err(`Expected glob option "query.${key}" to be of type string, number, or boolean, but got ${typeof value$1}`, optsStartIndex);
- }
- opts.query = stringifyQuery(opts.query);
- }
- if (opts.as && logger) {
- const importSuggestion = forceDefaultAs.includes(opts.as) ? `, import: 'default'` : "";
- logger.warn(import_picocolors$12.default.yellow(`The glob option "as" has been deprecated in favour of "query". Please update \`as: '${opts.as}'\` to \`query: '?${opts.as}'${importSuggestion}\`.`));
- }
- if (opts.as && forceDefaultAs.includes(opts.as)) {
- if (opts.import && opts.import !== "default" && opts.import !== "*") throw err(`Option "import" can only be "default" or "*" when "as" is "${opts.as}", but got "${opts.import}"`, optsStartIndex);
- opts.import = opts.import || "default";
- }
- if (opts.as && opts.query) throw err("Options \"as\" and \"query\" cannot be used together", optsStartIndex);
- if (opts.as) opts.query = opts.as;
- if (opts.query && opts.query[0] !== "?") opts.query = `?${opts.query}`;
- return opts;
-}
-async function parseImportGlob(code, importer, root, resolveId, logger) {
- let cleanCode;
- try {
- cleanCode = stripLiteral(code);
- } catch {
- return [];
- }
- const tasks = Array.from(cleanCode.matchAll(importGlobRE)).map(async (match, index) => {
- const start = match.index;
- const err$2 = (msg) => {
- const e$1 = /* @__PURE__ */ new Error(`Invalid glob import syntax: ${msg}`);
- e$1.pos = start;
- return e$1;
- };
- const end = findCorrespondingCloseParenthesisPosition(cleanCode, start + match[0].length) + 1;
- if (end <= 0) throw err$2("Close parenthesis not found");
- const rootAst = (await parseAstAsync(code.slice(start, end))).body[0];
- if (rootAst.type !== "ExpressionStatement") throw err$2(`Expect CallExpression, got ${rootAst.type}`);
- const ast = rootAst.expression;
- if (ast.type !== "CallExpression") throw err$2(`Expect CallExpression, got ${ast.type}`);
- if (ast.arguments.length < 1 || ast.arguments.length > 2) throw err$2(`Expected 1-2 arguments, but got ${ast.arguments.length}`);
- const arg1 = ast.arguments[0];
- const arg2 = ast.arguments[1];
- const globs = [];
- const validateLiteral = (element) => {
- if (!element) return;
- if (element.type === "Literal") {
- if (typeof element.value !== "string") throw err$2(`Expected glob to be a string, but got "${typeof element.value}"`);
- globs.push(element.value);
- } else if (element.type === "TemplateLiteral") {
- if (element.expressions.length !== 0) throw err$2(`Expected glob to be a string, but got dynamic template literal`);
- globs.push(element.quasis[0].value.raw);
- } else throw err$2("Could only use literals");
- };
- if (arg1.type === "ArrayExpression") for (const element of arg1.elements) validateLiteral(element);
- else validateLiteral(arg1);
- let options$1 = {};
- if (arg2) {
- if (arg2.type !== "ObjectExpression") throw err$2(`Expected the second argument to be an object literal, but got "${arg2.type}"`);
- options$1 = parseGlobOptions(code.slice(start + arg2.start, start + arg2.end), start + arg2.start, logger);
- }
- const globsResolved = await Promise.all(globs.map((glob$1) => toAbsoluteGlob(glob$1, root, importer, resolveId, options$1.base)));
- const isRelative$1 = globs.every((i$1) => ".!".includes(i$1[0]));
- const sliceCode = cleanCode.slice(0, start);
- const onlyKeys = objectKeysRE.test(sliceCode);
- let onlyValues = false;
- if (!onlyKeys) onlyValues = objectValuesRE.test(sliceCode);
- return {
- index,
- globs,
- globsResolved,
- isRelative: isRelative$1,
- options: options$1,
- start,
- end,
- onlyKeys,
- onlyValues
- };
- });
- return (await Promise.all(tasks)).filter(Boolean);
-}
-function findCorrespondingCloseParenthesisPosition(cleanCode, openPos) {
- const closePos = cleanCode.indexOf(")", openPos);
- if (closePos < 0) return -1;
- if (!cleanCode.slice(openPos, closePos).includes("(")) return closePos;
- let remainingParenthesisCount = 0;
- const cleanCodeLen = cleanCode.length;
- for (let pos = openPos; pos < cleanCodeLen; pos++) switch (cleanCode[pos]) {
- case "(":
- remainingParenthesisCount++;
- break;
- case ")":
- remainingParenthesisCount--;
- if (remainingParenthesisCount <= 0) return pos;
- }
- return -1;
-}
-const importPrefix = "__vite_glob_";
-const { basename: basename$2, dirname: dirname$2, relative: relative$2 } = posix;
-/**
-* @param optimizeExport for dynamicImportVar plugin don't need to optimize export.
-*/
-async function transformGlobImport(code, id, root, resolveId, restoreQueryExtension = false, logger) {
- id = slash(id);
- root = slash(root);
- const isVirtual = isVirtualModule(id);
- const dir = isVirtual ? void 0 : dirname$2(id);
- const matches$2 = await parseImportGlob(code, isVirtual ? void 0 : id, root, resolveId, logger);
- const matchedFiles = /* @__PURE__ */ new Set();
- if (!matches$2.length) return null;
- const s = new MagicString(code);
- const staticImports = (await Promise.all(matches$2.map(async ({ globsResolved, isRelative: isRelative$1, options: options$1, index, start, end, onlyKeys, onlyValues }) => {
- const files = (await glob(globsResolved, {
- absolute: true,
- cwd: getCommonBase(globsResolved) ?? root,
- dot: !!options$1.exhaustive,
- expandDirectories: false,
- ignore: options$1.exhaustive ? [] : ["**/node_modules/**"]
- })).filter((file) => file !== id).sort();
- const objectProps = [];
- const staticImports$1 = [];
- const resolvePaths = (file) => {
- if (!dir) {
- if (!options$1.base && isRelative$1) throw new Error("In virtual modules, all globs must start with '/'");
- const importPath$1 = `/${relative$2(root, file)}`;
- let filePath$1 = options$1.base ? `${relative$2(posix.join(root, options$1.base), file)}` : importPath$1;
- if (options$1.base && !filePath$1.startsWith("./") && !filePath$1.startsWith("../")) filePath$1 = `./${filePath$1}`;
- return {
- filePath: filePath$1,
- importPath: importPath$1
- };
- }
- let importPath = relative$2(dir, file);
- if (!importPath.startsWith("./") && !importPath.startsWith("../")) importPath = `./${importPath}`;
- let filePath;
- if (options$1.base) {
- filePath = relative$2(posix.join(options$1.base[0] === "/" ? root : dir, options$1.base), file);
- if (!filePath.startsWith("./") && !filePath.startsWith("../")) filePath = `./${filePath}`;
- if (options$1.base[0] === "/") importPath = `/${relative$2(root, file)}`;
- } else if (isRelative$1) filePath = importPath;
- else {
- filePath = relative$2(root, file);
- if (!filePath.startsWith("./") && !filePath.startsWith("../")) filePath = `/${filePath}`;
- }
- return {
- filePath,
- importPath
- };
- };
- files.forEach((file, i$1) => {
- const paths = resolvePaths(file);
- const filePath = paths.filePath;
- let importPath = paths.importPath;
- let importQuery = options$1.query ?? "";
- if (onlyKeys) {
- objectProps.push(`${JSON.stringify(filePath)}: 0`);
- return;
- }
- if (importQuery && importQuery !== "?raw") {
- const fileExtension = basename$2(file).split(".").slice(-1)[0];
- if (fileExtension && restoreQueryExtension) importQuery = `${importQuery}&lang.${fileExtension}`;
- }
- importPath = `${importPath}${importQuery}`;
- const importKey = options$1.import && options$1.import !== "*" ? options$1.import : void 0;
- if (options$1.eager) {
- const variableName = `${importPrefix}${index}_${i$1}`;
- const expression = importKey ? `{ ${importKey} as ${variableName} }` : `* as ${variableName}`;
- staticImports$1.push(`import ${expression} from ${JSON.stringify(importPath)}`);
- objectProps.push(onlyValues ? `${variableName}` : `${JSON.stringify(filePath)}: ${variableName}`);
- } else {
- let importStatement = `import(${JSON.stringify(importPath)})`;
- if (importKey) importStatement += `.then(m => m[${JSON.stringify(importKey)}])`;
- objectProps.push(onlyValues ? `() => ${importStatement}` : `${JSON.stringify(filePath)}: () => ${importStatement}`);
- }
- });
- files.forEach((i$1) => matchedFiles.add(i$1));
- const originalLineBreakCount = code.slice(start, end).match(/\n/g)?.length ?? 0;
- const lineBreaks = originalLineBreakCount > 0 ? "\n".repeat(originalLineBreakCount) : "";
- let replacement = "";
- if (onlyKeys) replacement = `{${objectProps.join(",")}${lineBreaks}}`;
- else if (onlyValues) replacement = `[${objectProps.join(",")}${lineBreaks}]`;
- else replacement = `/* #__PURE__ */ Object.assign({${objectProps.join(",")}${lineBreaks}})`;
- s.overwrite(start, end, replacement);
- return staticImports$1;
- }))).flat();
- if (staticImports.length) s.prepend(`${staticImports.join(";")};`);
- return {
- s,
- matches: matches$2,
- files: matchedFiles
- };
-}
-function globSafePath(path$13) {
- return escapePath(normalizePath(path$13));
-}
-function lastNthChar(str, n$2) {
- return str.charAt(str.length - 1 - n$2);
-}
-function globSafeResolvedPath(resolved, glob$1) {
- let numEqual = 0;
- const maxEqual = Math.min(resolved.length, glob$1.length);
- while (numEqual < maxEqual && lastNthChar(resolved, numEqual) === lastNthChar(glob$1, numEqual)) numEqual += 1;
- const staticPartEnd = resolved.length - numEqual;
- const staticPart = resolved.slice(0, staticPartEnd);
- const dynamicPart = resolved.slice(staticPartEnd);
- return globSafePath(staticPart) + dynamicPart;
-}
-async function toAbsoluteGlob(glob$1, root, importer, resolveId, base) {
- let pre = "";
- if (glob$1[0] === "!") {
- pre = "!";
- glob$1 = glob$1.slice(1);
- }
- root = globSafePath(root);
- let dir;
- if (base) if (base[0] === "/") dir = posix.join(root, base);
- else dir = posix.resolve(importer ? globSafePath(dirname$2(importer)) : root, base);
- else dir = importer ? globSafePath(dirname$2(importer)) : root;
- if (glob$1[0] === "/") return pre + posix.join(root, glob$1.slice(1));
- if (glob$1.startsWith("./")) return pre + posix.join(dir, glob$1.slice(2));
- if (glob$1.startsWith("../")) return pre + posix.join(dir, glob$1);
- if (glob$1.startsWith("**")) return pre + glob$1;
- const isSubImportsPattern = glob$1[0] === "#" && glob$1.includes("*");
- const resolved = normalizePath(await resolveId(glob$1, importer, { custom: { "vite:import-glob": { isSubImportsPattern } } }) || glob$1);
- if (isAbsolute(resolved)) return pre + globSafeResolvedPath(resolved, glob$1);
- throw new Error(`Invalid glob: "${glob$1}" (resolved: "${resolved}"). It must start with '/' or './'`);
-}
-function getCommonBase(globsResolved) {
- const bases = globsResolved.filter((g) => g[0] !== "!").map((glob$1) => {
- let { base } = picomatch.scan(glob$1);
- if (posix.basename(base).includes(".")) base = posix.dirname(base);
- return base;
- });
- if (!bases.length) return null;
- let commonAncestor = "";
- const dirS = bases[0].split("/");
- for (let i$1 = 0; i$1 < dirS.length; i$1++) {
- const candidate = dirS.slice(0, i$1 + 1).join("/");
- if (bases.every((base) => base.startsWith(candidate))) commonAncestor = candidate;
- else break;
- }
- if (!commonAncestor) commonAncestor = "/";
- return commonAncestor;
-}
-function isVirtualModule(id) {
- return id.startsWith("virtual:") || id[0] === "\0" || !id.includes("/");
-}
-
-//#endregion
-//#region src/node/plugins/pluginFilter.ts
-function getMatcherString(glob$1, cwd) {
- if (glob$1.startsWith("**") || path.isAbsolute(glob$1)) return slash(glob$1);
- return slash(path.join(cwd, glob$1));
-}
-function patternToIdFilter(pattern, cwd) {
- if (pattern instanceof RegExp) return (id) => {
- const normalizedId = slash(id);
- const result = pattern.test(normalizedId);
- pattern.lastIndex = 0;
- return result;
- };
- const matcher = picomatch(getMatcherString(pattern, cwd), { dot: true });
- return (id) => {
- return matcher(slash(id));
- };
-}
-function patternToCodeFilter(pattern) {
- if (pattern instanceof RegExp) return (code) => {
- const result = pattern.test(code);
- pattern.lastIndex = 0;
- return result;
- };
- return (code) => code.includes(pattern);
-}
-function createFilter$1(exclude, include) {
- if (!exclude && !include) return;
- return (input) => {
- if (exclude?.some((filter$1) => filter$1(input))) return false;
- if (include?.some((filter$1) => filter$1(input))) return true;
- return !(include && include.length > 0);
- };
-}
-function normalizeFilter(filter$1) {
- if (typeof filter$1 === "string" || filter$1 instanceof RegExp) return { include: [filter$1] };
- if (Array.isArray(filter$1)) return { include: filter$1 };
- return {
- include: filter$1.include ? arraify(filter$1.include) : void 0,
- exclude: filter$1.exclude ? arraify(filter$1.exclude) : void 0
- };
-}
-function createIdFilter(filter$1, cwd = process.cwd()) {
- if (!filter$1) return;
- const { exclude, include } = normalizeFilter(filter$1);
- const excludeFilter = exclude?.map((p) => patternToIdFilter(p, cwd));
- const includeFilter = include?.map((p) => patternToIdFilter(p, cwd));
- return createFilter$1(excludeFilter, includeFilter);
-}
-function createCodeFilter(filter$1) {
- if (!filter$1) return;
- const { exclude, include } = normalizeFilter(filter$1);
- const excludeFilter = exclude?.map(patternToCodeFilter);
- const includeFilter = include?.map(patternToCodeFilter);
- return createFilter$1(excludeFilter, includeFilter);
-}
-function createFilterForTransform(idFilter, codeFilter, cwd) {
- if (!idFilter && !codeFilter) return;
- const idFilterFn = createIdFilter(idFilter, cwd);
- const codeFilterFn = createCodeFilter(codeFilter);
- return (id, code) => {
- let fallback = true;
- if (idFilterFn) fallback &&= idFilterFn(id);
- if (!fallback) return false;
- if (codeFilterFn) fallback &&= codeFilterFn(code);
- return fallback;
- };
-}
-
-//#endregion
-//#region src/node/plugins/index.ts
-async function resolvePlugins(config$2, prePlugins, normalPlugins, postPlugins) {
- const isBuild = config$2.command === "build";
- const isWorker = config$2.isWorker;
- const buildPlugins = isBuild ? await (await import("./build.js")).resolveBuildPlugins(config$2) : {
- pre: [],
- post: []
- };
- const { modulePreload } = config$2.build;
- return [
- !isBuild ? optimizedDepsPlugin() : null,
- isBuild ? metadataPlugin() : null,
- !isWorker ? watchPackageDataPlugin(config$2.packageCache) : null,
- !isBuild ? preAliasPlugin(config$2) : null,
- alias({
- entries: config$2.resolve.alias,
- customResolver: viteAliasCustomResolver
- }),
- ...prePlugins,
- modulePreload !== false && modulePreload.polyfill ? modulePreloadPolyfillPlugin(config$2) : null,
- resolvePlugin({
- root: config$2.root,
- isProduction: config$2.isProduction,
- isBuild,
- packageCache: config$2.packageCache,
- asSrc: true,
- optimizeDeps: true,
- externalize: true
- }),
- htmlInlineProxyPlugin(config$2),
- cssPlugin(config$2),
- config$2.esbuild !== false ? esbuildPlugin(config$2) : null,
- jsonPlugin(config$2.json, isBuild),
- wasmHelperPlugin(),
- webWorkerPlugin(config$2),
- assetPlugin(config$2),
- ...normalPlugins,
- wasmFallbackPlugin(),
- definePlugin(config$2),
- cssPostPlugin(config$2),
- isBuild && buildHtmlPlugin(config$2),
- workerImportMetaUrlPlugin(config$2),
- assetImportMetaUrlPlugin(config$2),
- ...buildPlugins.pre,
- dynamicImportVarsPlugin(config$2),
- importGlobPlugin(config$2),
- ...postPlugins,
- ...buildPlugins.post,
- ...isBuild ? [] : [
- clientInjectionsPlugin(config$2),
- cssAnalysisPlugin(config$2),
- importAnalysisPlugin(config$2)
- ]
- ].filter(Boolean);
-}
-function createPluginHookUtils(plugins$1) {
- const sortedPluginsCache = /* @__PURE__ */ new Map();
- function getSortedPlugins(hookName) {
- if (sortedPluginsCache.has(hookName)) return sortedPluginsCache.get(hookName);
- const sorted = getSortedPluginsByHook(hookName, plugins$1);
- sortedPluginsCache.set(hookName, sorted);
- return sorted;
- }
- function getSortedPluginHooks(hookName) {
- return getSortedPlugins(hookName).map((p) => getHookHandler(p[hookName])).filter(Boolean);
- }
- return {
- getSortedPlugins,
- getSortedPluginHooks
- };
-}
-function getSortedPluginsByHook(hookName, plugins$1) {
- const sortedPlugins = [];
- let pre = 0, normal = 0, post = 0;
- for (const plugin of plugins$1) {
- const hook = plugin[hookName];
- if (hook) {
- if (typeof hook === "object") {
- if (hook.order === "pre") {
- sortedPlugins.splice(pre++, 0, plugin);
- continue;
- }
- if (hook.order === "post") {
- sortedPlugins.splice(pre + normal + post++, 0, plugin);
- continue;
- }
- }
- sortedPlugins.splice(pre + normal++, 0, plugin);
- }
- }
- return sortedPlugins;
-}
-function getHookHandler(hook) {
- return typeof hook === "object" ? hook.handler : hook;
-}
-const filterForPlugin = /* @__PURE__ */ new WeakMap();
-function getCachedFilterForPlugin(plugin, hookName) {
- let filters = filterForPlugin.get(plugin);
- if (filters && hookName in filters) return filters[hookName];
- if (!filters) {
- filters = {};
- filterForPlugin.set(plugin, filters);
- }
- let filter$1;
- switch (hookName) {
- case "resolveId": {
- const rawFilter = extractFilter(plugin.resolveId)?.id;
- filters.resolveId = createIdFilter(rawFilter);
- filter$1 = filters.resolveId;
- break;
- }
- case "load": {
- const rawFilter = extractFilter(plugin.load)?.id;
- filters.load = createIdFilter(rawFilter);
- filter$1 = filters.load;
- break;
- }
- case "transform": {
- const rawFilters = extractFilter(plugin.transform);
- filters.transform = createFilterForTransform(rawFilters?.id, rawFilters?.code);
- filter$1 = filters.transform;
- break;
- }
- }
- return filter$1;
-}
-function extractFilter(hook) {
- return hook && "filter" in hook && hook.filter ? hook.filter : void 0;
-}
-const viteAliasCustomResolver = async function(id, importer, options$1) {
- return await this.resolve(id, importer, options$1) || {
- id,
- meta: { "vite:alias": { noResolved: true } }
- };
-};
-
-//#endregion
-//#region src/node/server/pluginContainer.ts
-/**
-* This file is refactored into TypeScript based on
-* https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/rollup-plugin-container.js
-*/
-/**
-https://github.com/preactjs/wmr/blob/master/LICENSE
-
-MIT License
-
-Copyright (c) 2020 The Preact Authors
-
-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 import_picocolors$11 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const EMPTY_OBJECT = Object.freeze({});
-const debugSourcemapCombineFilter = process.env.DEBUG_VITE_SOURCEMAP_COMBINE_FILTER;
-const debugSourcemapCombine = createDebugger("vite:sourcemap-combine", { onlyWhenFocused: true });
-const debugResolve = createDebugger("vite:resolve");
-const debugPluginResolve = createDebugger("vite:plugin-resolve", { onlyWhenFocused: "vite:plugin" });
-const debugPluginTransform = createDebugger("vite:plugin-transform", { onlyWhenFocused: "vite:plugin" });
-const debugPluginContainerContext = createDebugger("vite:plugin-container-context");
-const ERR_CLOSED_SERVER = "ERR_CLOSED_SERVER";
-function throwClosedServerError() {
- const err$2 = /* @__PURE__ */ new Error("The server is being restarted or closed. Request is outdated");
- err$2.code = ERR_CLOSED_SERVER;
- throw err$2;
-}
-/**
-* Create a plugin container with a set of plugins. We pass them as a parameter
-* instead of using environment.plugins to allow the creation of different
-* pipelines working with the same environment (used for createIdResolver).
-*/
-async function createEnvironmentPluginContainer(environment, plugins$1, watcher, autoStart = true) {
- const container = new EnvironmentPluginContainer(environment, plugins$1, watcher, autoStart);
- await container.resolveRollupOptions();
- return container;
-}
-var EnvironmentPluginContainer = class {
- _pluginContextMap = /* @__PURE__ */ new Map();
- _resolvedRollupOptions;
- _processesing = /* @__PURE__ */ new Set();
- _seenResolves = {};
- _moduleNodeToLoadAddedImports = /* @__PURE__ */ new WeakMap();
- getSortedPluginHooks;
- getSortedPlugins;
- moduleGraph;
- watchFiles = /* @__PURE__ */ new Set();
- minimalContext;
- _started = false;
- _buildStartPromise;
- _closed = false;
- /**
- * @internal use `createEnvironmentPluginContainer` instead
- */
- constructor(environment, plugins$1, watcher, autoStart = true) {
- this.environment = environment;
- this.plugins = plugins$1;
- this.watcher = watcher;
- this._started = !autoStart;
- this.minimalContext = new MinimalPluginContext({
- ...basePluginContextMeta,
- watchMode: true
- }, environment);
- const utils$3 = createPluginHookUtils(plugins$1);
- this.getSortedPlugins = utils$3.getSortedPlugins;
- this.getSortedPluginHooks = utils$3.getSortedPluginHooks;
- this.moduleGraph = environment.mode === "dev" ? environment.moduleGraph : void 0;
- }
- _updateModuleLoadAddedImports(id, addedImports) {
- const module$1 = this.moduleGraph?.getModuleById(id);
- if (module$1) this._moduleNodeToLoadAddedImports.set(module$1, addedImports);
- }
- _getAddedImports(id) {
- const module$1 = this.moduleGraph?.getModuleById(id);
- return module$1 ? this._moduleNodeToLoadAddedImports.get(module$1) || null : null;
- }
- getModuleInfo(id) {
- const module$1 = this.moduleGraph?.getModuleById(id);
- if (!module$1) return null;
- if (!module$1.info) module$1.info = new Proxy({
- id,
- meta: module$1.meta || EMPTY_OBJECT
- }, { get(info, key) {
- if (key in info) return info[key];
- if (key === "then") return;
- throw Error(`[vite] The "${key}" property of ModuleInfo is not supported.`);
- } });
- return module$1.info ?? null;
- }
- handleHookPromise(maybePromise) {
- if (!maybePromise?.then) return maybePromise;
- const promise = maybePromise;
- this._processesing.add(promise);
- return promise.finally(() => this._processesing.delete(promise));
- }
- get options() {
- return this._resolvedRollupOptions;
- }
- async resolveRollupOptions() {
- if (!this._resolvedRollupOptions) {
- let options$1 = this.environment.config.build.rollupOptions;
- for (const optionsHook of this.getSortedPluginHooks("options")) {
- if (this._closed) throwClosedServerError();
- options$1 = await this.handleHookPromise(optionsHook.call(this.minimalContext, options$1)) || options$1;
- }
- this._resolvedRollupOptions = options$1;
- }
- return this._resolvedRollupOptions;
- }
- _getPluginContext(plugin) {
- if (!this._pluginContextMap.has(plugin)) this._pluginContextMap.set(plugin, new PluginContext(plugin, this));
- return this._pluginContextMap.get(plugin);
- }
- async hookParallel(hookName, context, args, condition) {
- const parallelPromises = [];
- for (const plugin of this.getSortedPlugins(hookName)) {
- if (condition && !condition(plugin)) continue;
- const hook = plugin[hookName];
- const handler = getHookHandler(hook);
- if (hook.sequential) {
- await Promise.all(parallelPromises);
- parallelPromises.length = 0;
- await handler.apply(context(plugin), args(plugin));
- } else parallelPromises.push(handler.apply(context(plugin), args(plugin)));
- }
- await Promise.all(parallelPromises);
- }
- async buildStart(_options) {
- if (this._started) {
- if (this._buildStartPromise) await this._buildStartPromise;
- return;
- }
- this._started = true;
- const config$2 = this.environment.getTopLevelConfig();
- this._buildStartPromise = this.handleHookPromise(this.hookParallel("buildStart", (plugin) => this._getPluginContext(plugin), () => [this.options], (plugin) => this.environment.name === "client" || config$2.server.perEnvironmentStartEndDuringDev || plugin.perEnvironmentStartEndDuringDev));
- await this._buildStartPromise;
- this._buildStartPromise = void 0;
- }
- async resolveId(rawId, importer = join(this.environment.config.root, "index.html"), options$1) {
- if (!this._started) {
- this.buildStart();
- await this._buildStartPromise;
- }
- const skip = options$1?.skip;
- const skipCalls = options$1?.skipCalls;
- const scan = !!options$1?.scan;
- const ssr = this.environment.config.consumer === "server";
- const ctx = new ResolveIdContext(this, skip, skipCalls, scan);
- const topLevelConfig = this.environment.getTopLevelConfig();
- const mergedSkip = new Set(skip);
- for (const call$1 of skipCalls ?? []) if (call$1.called || call$1.id === rawId && call$1.importer === importer) mergedSkip.add(call$1.plugin);
- const resolveStart = debugResolve ? performance$1.now() : 0;
- let id = null;
- const partial = {};
- for (const plugin of this.getSortedPlugins("resolveId")) {
- if (this._closed && this.environment.config.dev.recoverable) throwClosedServerError();
- if (mergedSkip?.has(plugin)) continue;
- const filter$1 = getCachedFilterForPlugin(plugin, "resolveId");
- if (filter$1 && !filter$1(rawId)) continue;
- ctx._plugin = plugin;
- const normalizedOptions = {
- attributes: options$1?.attributes ?? {},
- custom: options$1?.custom,
- isEntry: !!options$1?.isEntry,
- ssr,
- scan
- };
- if (isFutureDeprecationEnabled(topLevelConfig, "removePluginHookSsrArgument")) {
- let ssrTemp = ssr;
- Object.defineProperty(normalizedOptions, "ssr", {
- get() {
- warnFutureDeprecation(topLevelConfig, "removePluginHookSsrArgument", `Used in plugin "${plugin.name}".`);
- return ssrTemp;
- },
- set(v) {
- ssrTemp = v;
- }
- });
- }
- const pluginResolveStart = debugPluginResolve ? performance$1.now() : 0;
- const handler = getHookHandler(plugin.resolveId);
- const result = await this.handleHookPromise(handler.call(ctx, rawId, importer, normalizedOptions));
- if (!result) continue;
- if (typeof result === "string") id = result;
- else {
- id = result.id;
- Object.assign(partial, result);
- }
- debugPluginResolve?.(timeFrom(pluginResolveStart), plugin.name, prettifyUrl(id, this.environment.config.root));
- break;
- }
- if (debugResolve && rawId !== id && !rawId.startsWith(FS_PREFIX)) {
- const key = rawId + id;
- if (!this._seenResolves[key]) {
- this._seenResolves[key] = true;
- debugResolve(`${timeFrom(resolveStart)} ${import_picocolors$11.default.cyan(rawId)} -> ${import_picocolors$11.default.dim(id)}`);
- }
- }
- if (id) {
- partial.id = isExternalUrl(id) || id[0] === "\0" ? id : normalizePath(id);
- return partial;
- } else return null;
- }
- async load(id) {
- let ssr = this.environment.config.consumer === "server";
- const topLevelConfig = this.environment.getTopLevelConfig();
- const options$1 = { ssr };
- const ctx = new LoadPluginContext(this);
- for (const plugin of this.getSortedPlugins("load")) {
- if (this._closed && this.environment.config.dev.recoverable) throwClosedServerError();
- const filter$1 = getCachedFilterForPlugin(plugin, "load");
- if (filter$1 && !filter$1(id)) continue;
- ctx._plugin = plugin;
- if (isFutureDeprecationEnabled(topLevelConfig, "removePluginHookSsrArgument")) Object.defineProperty(options$1, "ssr", {
- get() {
- warnFutureDeprecation(topLevelConfig, "removePluginHookSsrArgument", `Used in plugin "${plugin.name}".`);
- return ssr;
- },
- set(v) {
- ssr = v;
- }
- });
- const handler = getHookHandler(plugin.load);
- const result = await this.handleHookPromise(handler.call(ctx, id, options$1));
- if (result != null) {
- if (isObject(result)) ctx._updateModuleInfo(id, result);
- this._updateModuleLoadAddedImports(id, ctx._addedImports);
- return result;
- }
- }
- this._updateModuleLoadAddedImports(id, ctx._addedImports);
- return null;
- }
- async transform(code, id, options$1) {
- let ssr = this.environment.config.consumer === "server";
- const topLevelConfig = this.environment.getTopLevelConfig();
- const optionsWithSSR = options$1 ? {
- ...options$1,
- ssr
- } : { ssr };
- const inMap = options$1?.inMap;
- const ctx = new TransformPluginContext(this, id, code, inMap);
- ctx._addedImports = this._getAddedImports(id);
- for (const plugin of this.getSortedPlugins("transform")) {
- if (this._closed && this.environment.config.dev.recoverable) throwClosedServerError();
- const filter$1 = getCachedFilterForPlugin(plugin, "transform");
- if (filter$1 && !filter$1(id, code)) continue;
- if (isFutureDeprecationEnabled(topLevelConfig, "removePluginHookSsrArgument")) Object.defineProperty(optionsWithSSR, "ssr", {
- get() {
- warnFutureDeprecation(topLevelConfig, "removePluginHookSsrArgument", `Used in plugin "${plugin.name}".`);
- return ssr;
- },
- set(v) {
- ssr = v;
- }
- });
- ctx._updateActiveInfo(plugin, id, code);
- const start = debugPluginTransform ? performance$1.now() : 0;
- let result;
- const handler = getHookHandler(plugin.transform);
- try {
- result = await this.handleHookPromise(handler.call(ctx, code, id, optionsWithSSR));
- } catch (e$1) {
- ctx.error(e$1);
- }
- if (!result) continue;
- debugPluginTransform?.(timeFrom(start), plugin.name, prettifyUrl(id, this.environment.config.root));
- if (isObject(result)) {
- if (result.code !== void 0) {
- code = result.code;
- if (result.map) {
- if (debugSourcemapCombine) result.map.name = plugin.name;
- ctx.sourcemapChain.push(result.map);
- }
- }
- ctx._updateModuleInfo(id, result);
- } else code = result;
- }
- return {
- code,
- map: ctx._getCombinedSourcemap()
- };
- }
- async watchChange(id, change) {
- const config$2 = this.environment.getTopLevelConfig();
- await this.hookParallel("watchChange", (plugin) => this._getPluginContext(plugin), () => [id, change], (plugin) => this.environment.name === "client" || config$2.server.perEnvironmentWatchChangeDuringDev || plugin.perEnvironmentWatchChangeDuringDev);
- }
- async close() {
- if (this._closed) return;
- this._closed = true;
- await Promise.allSettled(Array.from(this._processesing));
- const config$2 = this.environment.getTopLevelConfig();
- await this.hookParallel("buildEnd", (plugin) => this._getPluginContext(plugin), () => [], (plugin) => this.environment.name === "client" || config$2.server.perEnvironmentStartEndDuringDev || plugin.perEnvironmentStartEndDuringDev);
- await this.hookParallel("closeBundle", (plugin) => this._getPluginContext(plugin), () => []);
- }
-};
-const basePluginContextMeta = {
- viteVersion: VERSION,
- rollupVersion
-};
-var BasicMinimalPluginContext = class {
- constructor(meta, _logger) {
- this.meta = meta;
- this._logger = _logger;
- }
- debug(rawLog) {
- const log$3 = this._normalizeRawLog(rawLog);
- const msg = buildErrorMessage(log$3, [`debug: ${log$3.message}`], false);
- debugPluginContainerContext?.(msg);
- }
- info(rawLog) {
- const log$3 = this._normalizeRawLog(rawLog);
- const msg = buildErrorMessage(log$3, [`info: ${log$3.message}`], false);
- this._logger.info(msg, {
- clear: true,
- timestamp: true
- });
- }
- warn(rawLog) {
- const log$3 = this._normalizeRawLog(rawLog);
- const msg = buildErrorMessage(log$3, [import_picocolors$11.default.yellow(`warning: ${log$3.message}`)], false);
- this._logger.warn(msg, {
- clear: true,
- timestamp: true
- });
- }
- error(e$1) {
- throw typeof e$1 === "string" ? new Error(e$1) : e$1;
- }
- _normalizeRawLog(rawLog) {
- const logValue = typeof rawLog === "function" ? rawLog() : rawLog;
- return typeof logValue === "string" ? new Error(logValue) : logValue;
- }
-};
-var MinimalPluginContext = class extends BasicMinimalPluginContext {
- environment;
- constructor(meta, environment) {
- super(meta, environment.logger);
- this.environment = environment;
- }
-};
-const fsModule = {
- appendFile: fsp.appendFile,
- copyFile: fsp.copyFile,
- mkdir: fsp.mkdir,
- mkdtemp: fsp.mkdtemp,
- readdir: fsp.readdir,
- readFile: fsp.readFile,
- realpath: fsp.realpath,
- rename: fsp.rename,
- rmdir: fsp.rmdir,
- stat: fsp.stat,
- lstat: fsp.lstat,
- unlink: fsp.unlink,
- writeFile: fsp.writeFile
-};
-var PluginContext = class extends MinimalPluginContext {
- ssr = false;
- _scan = false;
- _activeId = null;
- _activeCode = null;
- _resolveSkips;
- _resolveSkipCalls;
- constructor(_plugin, _container) {
- super(_container.minimalContext.meta, _container.environment);
- this._plugin = _plugin;
- this._container = _container;
- }
- fs = fsModule;
- parse(code, opts) {
- return parseAst(code, opts);
- }
- async resolve(id, importer, options$1) {
- let skipCalls;
- if (options$1?.skipSelf === false) skipCalls = this._resolveSkipCalls;
- else if (this._resolveSkipCalls) {
- const skipCallsTemp = [...this._resolveSkipCalls];
- const sameCallIndex = this._resolveSkipCalls.findIndex((c) => c.id === id && c.importer === importer && c.plugin === this._plugin);
- if (sameCallIndex !== -1) skipCallsTemp[sameCallIndex] = {
- ...skipCallsTemp[sameCallIndex],
- called: true
- };
- else skipCallsTemp.push({
- id,
- importer,
- plugin: this._plugin
- });
- skipCalls = skipCallsTemp;
- } else skipCalls = [{
- id,
- importer,
- plugin: this._plugin
- }];
- let out = await this._container.resolveId(id, importer, {
- attributes: options$1?.attributes,
- custom: options$1?.custom,
- isEntry: !!options$1?.isEntry,
- skip: this._resolveSkips,
- skipCalls,
- scan: this._scan
- });
- if (typeof out === "string") out = { id: out };
- return out;
- }
- async load(options$1) {
- await this._container.moduleGraph?.ensureEntryFromUrl(unwrapId(options$1.id));
- this._updateModuleInfo(options$1.id, options$1);
- const loadResult = await this._container.load(options$1.id);
- const code = typeof loadResult === "object" ? loadResult?.code : loadResult;
- if (code != null) await this._container.transform(code, options$1.id);
- const moduleInfo = this.getModuleInfo(options$1.id);
- if (!moduleInfo) throw Error(`Failed to load module with id ${options$1.id}`);
- return moduleInfo;
- }
- getModuleInfo(id) {
- return this._container.getModuleInfo(id);
- }
- _updateModuleInfo(id, { meta }) {
- if (meta) {
- const moduleInfo = this.getModuleInfo(id);
- if (moduleInfo) moduleInfo.meta = {
- ...moduleInfo.meta,
- ...meta
- };
- }
- }
- getModuleIds() {
- return this._container.moduleGraph ? this._container.moduleGraph.idToModuleMap.keys() : Array.prototype[Symbol.iterator]();
- }
- addWatchFile(id) {
- this._container.watchFiles.add(id);
- if (this._container.watcher) ensureWatchedFile(this._container.watcher, id, this.environment.config.root);
- }
- getWatchFiles() {
- return [...this._container.watchFiles];
- }
- emitFile(_assetOrFile) {
- this._warnIncompatibleMethod(`emitFile`);
- return "";
- }
- setAssetSource() {
- this._warnIncompatibleMethod(`setAssetSource`);
- }
- getFileName() {
- this._warnIncompatibleMethod(`getFileName`);
- return "";
- }
- debug(log$3) {
- const err$2 = this._formatLog(typeof log$3 === "function" ? log$3() : log$3);
- super.debug(err$2);
- }
- info(log$3) {
- const err$2 = this._formatLog(typeof log$3 === "function" ? log$3() : log$3);
- super.info(err$2);
- }
- warn(log$3, position) {
- const err$2 = this._formatLog(typeof log$3 === "function" ? log$3() : log$3, position);
- super.warn(err$2);
- }
- error(e$1, position) {
- throw this._formatLog(e$1, position);
- }
- _formatLog(e$1, position) {
- const err$2 = typeof e$1 === "string" ? new Error(e$1) : e$1;
- if (err$2.pluginCode) return err$2;
- err$2.plugin = this._plugin.name;
- if (this._activeId && !err$2.id) err$2.id = this._activeId;
- if (this._activeCode) {
- err$2.pluginCode = this._activeCode;
- const pos = position ?? err$2.pos ?? err$2.position;
- if (pos != null) {
- let errLocation;
- try {
- errLocation = numberToPos(this._activeCode, pos);
- } catch (err2) {
- this.environment.logger.error(import_picocolors$11.default.red(`Error in error handler:\n${err2.stack || err2.message}\n`), { error: err2 });
- throw err$2;
- }
- err$2.loc = err$2.loc || {
- file: err$2.id,
- ...errLocation
- };
- err$2.frame = err$2.frame || generateCodeFrame(this._activeCode, pos);
- } else if (err$2.loc) {
- if (!err$2.frame) {
- let code = this._activeCode;
- if (err$2.loc.file) {
- err$2.id = normalizePath(err$2.loc.file);
- try {
- code = fs.readFileSync(err$2.loc.file, "utf-8");
- } catch {}
- }
- err$2.frame = generateCodeFrame(code, err$2.loc);
- }
- } else if (err$2.line && err$2.column) {
- err$2.loc = {
- file: err$2.id,
- line: err$2.line,
- column: err$2.column
- };
- err$2.frame = err$2.frame || generateCodeFrame(this._activeCode, err$2.loc);
- }
- if (this instanceof TransformPluginContext && typeof err$2.loc?.line === "number" && typeof err$2.loc.column === "number") {
- const rawSourceMap = this._getCombinedSourcemap();
- if (rawSourceMap && "version" in rawSourceMap) {
- const { source, line, column } = originalPositionFor(new TraceMap(rawSourceMap), {
- line: Number(err$2.loc.line),
- column: Number(err$2.loc.column)
- });
- if (source) err$2.loc = {
- file: source,
- line,
- column
- };
- }
- }
- } else if (err$2.loc) {
- if (!err$2.frame) {
- let code = err$2.pluginCode;
- if (err$2.loc.file) {
- err$2.id = normalizePath(err$2.loc.file);
- if (!code) try {
- code = fs.readFileSync(err$2.loc.file, "utf-8");
- } catch {}
- }
- if (code) err$2.frame = generateCodeFrame(`${code}`, err$2.loc);
- }
- }
- if (typeof err$2.loc?.column !== "number" && typeof err$2.loc?.line !== "number" && !err$2.loc?.file) delete err$2.loc;
- return err$2;
- }
- _warnIncompatibleMethod(method) {
- this.environment.logger.warn(import_picocolors$11.default.cyan(`[plugin:${this._plugin.name}] `) + import_picocolors$11.default.yellow(`context method ${import_picocolors$11.default.bold(`${method}()`)} is not supported in serve mode. This plugin is likely not vite-compatible.`));
- }
-};
-var ResolveIdContext = class extends PluginContext {
- constructor(container, skip, skipCalls, scan) {
- super(null, container);
- this._resolveSkips = skip;
- this._resolveSkipCalls = skipCalls;
- this._scan = scan;
- }
-};
-var LoadPluginContext = class extends PluginContext {
- _addedImports = null;
- constructor(container) {
- super(null, container);
- }
- addWatchFile(id) {
- if (!this._addedImports) this._addedImports = /* @__PURE__ */ new Set();
- this._addedImports.add(id);
- super.addWatchFile(id);
- }
-};
-var TransformPluginContext = class extends LoadPluginContext {
- filename;
- originalCode;
- originalSourcemap = null;
- sourcemapChain = [];
- combinedMap = null;
- constructor(container, id, code, inMap) {
- super(container);
- this.filename = id;
- this.originalCode = code;
- if (inMap) {
- if (debugSourcemapCombine) inMap.name = "$inMap";
- this.sourcemapChain.push(inMap);
- }
- }
- _getCombinedSourcemap() {
- if (debugSourcemapCombine && debugSourcemapCombineFilter && this.filename.includes(debugSourcemapCombineFilter)) {
- debugSourcemapCombine("----------", this.filename);
- debugSourcemapCombine(this.combinedMap);
- debugSourcemapCombine(this.sourcemapChain);
- debugSourcemapCombine("----------");
- }
- let combinedMap = this.combinedMap;
- if (combinedMap && !("version" in combinedMap) && combinedMap.mappings === "") {
- this.sourcemapChain.length = 0;
- return combinedMap;
- }
- for (let m of this.sourcemapChain) {
- if (typeof m === "string") m = JSON.parse(m);
- if (!("version" in m)) {
- if (m.mappings === "") {
- combinedMap = { mappings: "" };
- break;
- }
- combinedMap = null;
- break;
- }
- if (!combinedMap) {
- const sm = m;
- if (sm.sources.length === 1 && !sm.sources[0]) combinedMap = {
- ...sm,
- sources: [this.filename],
- sourcesContent: [this.originalCode]
- };
- else combinedMap = sm;
- } else combinedMap = combineSourcemaps(cleanUrl(this.filename), [m, combinedMap]);
- }
- if (combinedMap !== this.combinedMap) {
- this.combinedMap = combinedMap;
- this.sourcemapChain.length = 0;
- }
- return this.combinedMap;
- }
- getCombinedSourcemap() {
- const map$1 = this._getCombinedSourcemap();
- if (!map$1 || !("version" in map$1) && map$1.mappings === "") return new MagicString(this.originalCode).generateMap({
- includeContent: true,
- hires: "boundary",
- source: cleanUrl(this.filename)
- });
- return map$1;
- }
- _updateActiveInfo(plugin, id, code) {
- this._plugin = plugin;
- this._activeId = id;
- this._activeCode = code;
- }
-};
-var PluginContainer = class {
- constructor(environments) {
- this.environments = environments;
- }
- _getEnvironment(options$1) {
- return options$1?.environment ? options$1.environment : this.environments[options$1?.ssr ? "ssr" : "client"];
- }
- _getPluginContainer(options$1) {
- return this._getEnvironment(options$1).pluginContainer;
- }
- getModuleInfo(id) {
- const clientModuleInfo = this.environments.client.pluginContainer.getModuleInfo(id);
- const ssrModuleInfo = this.environments.ssr.pluginContainer.getModuleInfo(id);
- if (clientModuleInfo == null && ssrModuleInfo == null) return null;
- return new Proxy({}, { get: (_, key) => {
- if (key === "meta") {
- const meta = {};
- if (ssrModuleInfo) Object.assign(meta, ssrModuleInfo.meta);
- if (clientModuleInfo) Object.assign(meta, clientModuleInfo.meta);
- return meta;
- }
- if (clientModuleInfo) {
- if (key in clientModuleInfo) return clientModuleInfo[key];
- }
- if (ssrModuleInfo) {
- if (key in ssrModuleInfo) return ssrModuleInfo[key];
- }
- } });
- }
- get options() {
- return this.environments.client.pluginContainer.options;
- }
- async buildStart(_options) {
- return this.environments.client.pluginContainer.buildStart(_options);
- }
- async watchChange(id, change) {
- return this.environments.client.pluginContainer.watchChange(id, change);
- }
- async resolveId(rawId, importer, options$1) {
- return this._getPluginContainer(options$1).resolveId(rawId, importer, options$1);
- }
- async load(id, options$1) {
- return this._getPluginContainer(options$1).load(id);
- }
- async transform(code, id, options$1) {
- return this._getPluginContainer(options$1).transform(code, id, options$1);
- }
- async close() {}
-};
-/**
-* server.pluginContainer compatibility
-*
-* The default environment is in buildStart, buildEnd, watchChange, and closeBundle hooks,
-* which are called once for all environments, or when no environment is passed in other hooks.
-* The ssrEnvironment is needed for backward compatibility when the ssr flag is passed without
-* an environment. The defaultEnvironment in the main pluginContainer in the server should be
-* the client environment for backward compatibility.
-**/
-function createPluginContainer(environments) {
- return new PluginContainer(environments);
-}
-
-//#endregion
-//#region src/node/idResolver.ts
-/**
-* Some projects like Astro were overriding config.createResolver to add a custom
-* alias plugin. For the client and ssr environments, we root through it to avoid
-* breaking changes for now.
-*/
-function createBackCompatIdResolver(config$2, options$1) {
- const compatResolve = config$2.createResolver(options$1);
- let resolve$4;
- return async (environment, id, importer, aliasOnly) => {
- if (environment.name === "client" || environment.name === "ssr") return compatResolve(id, importer, aliasOnly, environment.name === "ssr");
- resolve$4 ??= createIdResolver(config$2, options$1);
- return resolve$4(environment, id, importer, aliasOnly);
- };
-}
-/**
-* Create an internal resolver to be used in special scenarios, e.g.
-* optimizer and handling css @imports
-*/
-function createIdResolver(config$2, options$1) {
- const scan = options$1?.scan;
- const pluginContainerMap = /* @__PURE__ */ new Map();
- async function resolve$4(environment, id, importer) {
- let pluginContainer = pluginContainerMap.get(environment);
- if (!pluginContainer) {
- pluginContainer = await createEnvironmentPluginContainer(environment, [alias({ entries: environment.config.resolve.alias }), resolvePlugin({
- root: config$2.root,
- isProduction: config$2.isProduction,
- isBuild: config$2.command === "build",
- asSrc: true,
- preferRelative: false,
- tryIndex: true,
- ...options$1,
- idOnly: true
- })], void 0, false);
- pluginContainerMap.set(environment, pluginContainer);
- }
- return await pluginContainer.resolveId(id, importer, { scan });
- }
- const aliasOnlyPluginContainerMap = /* @__PURE__ */ new Map();
- async function resolveAlias(environment, id, importer) {
- let pluginContainer = aliasOnlyPluginContainerMap.get(environment);
- if (!pluginContainer) {
- pluginContainer = await createEnvironmentPluginContainer(environment, [alias({ entries: environment.config.resolve.alias })], void 0, false);
- aliasOnlyPluginContainerMap.set(environment, pluginContainer);
- }
- return await pluginContainer.resolveId(id, importer, { scan });
- }
- return async (environment, id, importer, aliasOnly) => {
- return (await (aliasOnly ? resolveAlias : resolve$4)(environment, id, importer))?.id;
- };
-}
-
-//#endregion
-//#region src/node/baseEnvironment.ts
-var import_picocolors$10 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const environmentColors = [
- import_picocolors$10.default.blue,
- import_picocolors$10.default.magenta,
- import_picocolors$10.default.green,
- import_picocolors$10.default.gray
-];
-var PartialEnvironment = class {
- name;
- getTopLevelConfig() {
- return this._topLevelConfig;
- }
- config;
- logger;
- /**
- * @internal
- */
- _options;
- /**
- * @internal
- */
- _topLevelConfig;
- constructor(name, topLevelConfig, options$1 = topLevelConfig.environments[name]) {
- if (!/^[\w$]+$/.test(name)) throw new Error(`Invalid environment name "${name}". Environment names must only contain alphanumeric characters and "$", "_".`);
- this.name = name;
- this._topLevelConfig = topLevelConfig;
- this._options = options$1;
- this.config = new Proxy(options$1, { get: (target, prop) => {
- if (prop === "logger") return this.logger;
- if (prop in target) return this._options[prop];
- return this._topLevelConfig[prop];
- } });
- const environment = import_picocolors$10.default.dim(`(${this.name})`);
- const infoColor = environmentColors[[...this.name].reduce((acc, c) => acc + c.charCodeAt(0), 0) % environmentColors.length || 0];
- this.logger = {
- get hasWarned() {
- return topLevelConfig.logger.hasWarned;
- },
- info(msg, opts) {
- return topLevelConfig.logger.info(msg, {
- ...opts,
- environment: infoColor(environment)
- });
- },
- warn(msg, opts) {
- return topLevelConfig.logger.warn(msg, {
- ...opts,
- environment: import_picocolors$10.default.yellow(environment)
- });
- },
- warnOnce(msg, opts) {
- return topLevelConfig.logger.warnOnce(msg, {
- ...opts,
- environment: import_picocolors$10.default.yellow(environment)
- });
- },
- error(msg, opts) {
- return topLevelConfig.logger.error(msg, {
- ...opts,
- environment: import_picocolors$10.default.red(environment)
- });
- },
- clearScreen(type) {
- return topLevelConfig.logger.clearScreen(type);
- },
- hasErrorLogged(error$1) {
- return topLevelConfig.logger.hasErrorLogged(error$1);
- }
- };
- }
-};
-var BaseEnvironment = class extends PartialEnvironment {
- get plugins() {
- return this.config.plugins;
- }
- /**
- * @internal
- */
- _initiated = false;
- constructor(name, config$2, options$1 = config$2.environments[name]) {
- super(name, config$2, options$1);
- }
-};
-
-//#endregion
-//#region src/node/plugins/manifest.ts
-const endsWithJSRE = /\.[cm]?js$/;
-function manifestPlugin() {
- const getState = perEnvironmentState(() => {
- return {
- manifest: {},
- outputCount: 0,
- reset() {
- this.manifest = {};
- this.outputCount = 0;
- }
- };
- });
- return {
- name: "vite:manifest",
- perEnvironmentStartEndDuringDev: true,
- applyToEnvironment(environment) {
- return !!environment.config.build.manifest;
- },
- buildStart() {
- getState(this).reset();
- },
- generateBundle({ format: format$3 }, bundle) {
- const state = getState(this);
- const { manifest } = state;
- const { root } = this.environment.config;
- const buildOptions = this.environment.config.build;
- function getChunkName(chunk) {
- return getChunkOriginalFileName(chunk, root, format$3) ?? `_${path.basename(chunk.fileName)}`;
- }
- function getInternalImports(imports) {
- const filteredImports = [];
- for (const file of imports) {
- if (bundle[file] === void 0) continue;
- filteredImports.push(getChunkName(bundle[file]));
- }
- return filteredImports;
- }
- function createChunk(chunk) {
- const manifestChunk = {
- file: chunk.fileName,
- name: chunk.name
- };
- if (chunk.facadeModuleId) manifestChunk.src = getChunkName(chunk);
- if (chunk.isEntry) manifestChunk.isEntry = true;
- if (chunk.isDynamicEntry) manifestChunk.isDynamicEntry = true;
- if (chunk.imports.length) {
- const internalImports = getInternalImports(chunk.imports);
- if (internalImports.length > 0) manifestChunk.imports = internalImports;
- }
- if (chunk.dynamicImports.length) {
- const internalImports = getInternalImports(chunk.dynamicImports);
- if (internalImports.length > 0) manifestChunk.dynamicImports = internalImports;
- }
- if (chunk.viteMetadata?.importedCss.size) manifestChunk.css = [...chunk.viteMetadata.importedCss];
- if (chunk.viteMetadata?.importedAssets.size) manifestChunk.assets = [...chunk.viteMetadata.importedAssets];
- return manifestChunk;
- }
- function createAsset(asset, src, name) {
- const manifestChunk = {
- file: asset.fileName,
- src
- };
- if (name) {
- manifestChunk.isEntry = true;
- manifestChunk.name = name;
- manifestChunk.names = asset.names;
- }
- return manifestChunk;
- }
- const entryCssReferenceIds = cssEntriesMap.get(this.environment);
- const entryCssAssetFileNames = /* @__PURE__ */ new Map();
- for (const [name, id] of entryCssReferenceIds) try {
- const fileName = this.getFileName(id);
- entryCssAssetFileNames.set(fileName, name);
- } catch {}
- for (const file in bundle) {
- const chunk = bundle[file];
- if (chunk.type === "chunk") manifest[getChunkName(chunk)] = createChunk(chunk);
- else if (chunk.type === "asset" && chunk.names.length > 0) {
- const src = chunk.originalFileNames.length > 0 ? chunk.originalFileNames[0] : `_${path.basename(chunk.fileName)}`;
- const asset = createAsset(chunk, src, entryCssAssetFileNames.get(chunk.fileName));
- const file$1 = manifest[src]?.file;
- if (!(file$1 && endsWithJSRE.test(file$1))) manifest[src] = asset;
- for (const originalFileName of chunk.originalFileNames.slice(1)) {
- const file$2 = manifest[originalFileName]?.file;
- if (!(file$2 && endsWithJSRE.test(file$2))) manifest[originalFileName] = asset;
- }
- }
- }
- state.outputCount++;
- const output = buildOptions.rollupOptions.output;
- if (state.outputCount >= (Array.isArray(output) ? output.length : 1)) this.emitFile({
- fileName: typeof buildOptions.manifest === "string" ? buildOptions.manifest : ".vite/manifest.json",
- type: "asset",
- source: JSON.stringify(sortObjectKeys(manifest), void 0, 2)
- });
- }
- };
-}
-function getChunkOriginalFileName(chunk, root, format$3) {
- if (chunk.facadeModuleId) {
- let name = normalizePath(path.relative(root, chunk.facadeModuleId));
- if (format$3 === "system" && !chunk.name.includes("-legacy")) {
- const ext = path.extname(name);
- const endPos = ext.length !== 0 ? -ext.length : void 0;
- name = `${name.slice(0, endPos)}-legacy${ext}`;
- }
- return name.replace(/\0/g, "");
- }
-}
-
-//#endregion
-//#region src/node/plugins/css.ts
-var import_src = /* @__PURE__ */ __toESM(require_src(), 1);
-var import_picocolors$9 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const decoder = new TextDecoder();
-const _cssConfigDefaults = Object.freeze({
- transformer: "postcss",
- preprocessorMaxWorkers: true,
- devSourcemap: false
-});
-const cssConfigDefaults = _cssConfigDefaults;
-function resolveCSSOptions(options$1) {
- const resolved = mergeWithDefaults(_cssConfigDefaults, options$1 ?? {});
- if (resolved.transformer === "lightningcss") {
- resolved.lightningcss ??= {};
- resolved.lightningcss.targets ??= convertTargets(ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET);
- }
- return resolved;
-}
-const cssModuleRE = /* @__PURE__ */ new RegExp(`\\.module${CSS_LANGS_RE.source}`);
-const directRequestRE = /[?&]direct\b/;
-const htmlProxyRE = /[?&]html-proxy\b/;
-const htmlProxyIndexRE = /&index=(\d+)/;
-const commonjsProxyRE = /[?&]commonjs-proxy/;
-const inlineRE = /[?&]inline\b/;
-const inlineCSSRE = /[?&]inline-css\b/;
-const styleAttrRE = /[?&]style-attr\b/;
-const functionCallRE = /^[A-Z_][.\w-]*\(/i;
-const transformOnlyRE = /[?&]transform-only\b/;
-const nonEscapedDoubleQuoteRe = /(?<!\\)"/g;
-const defaultCssBundleName = "style.css";
-var PreprocessLang = /* @__PURE__ */ function(PreprocessLang$1) {
- PreprocessLang$1["less"] = "less";
- PreprocessLang$1["sass"] = "sass";
- PreprocessLang$1["scss"] = "scss";
- PreprocessLang$1["styl"] = "styl";
- PreprocessLang$1["stylus"] = "stylus";
- return PreprocessLang$1;
-}(PreprocessLang || {});
-var PostCssDialectLang = /* @__PURE__ */ function(PostCssDialectLang$1) {
- PostCssDialectLang$1["sss"] = "sugarss";
- return PostCssDialectLang$1;
-}(PostCssDialectLang || {});
-const isModuleCSSRequest = (request) => cssModuleRE.test(request);
-const isDirectCSSRequest = (request) => CSS_LANGS_RE.test(request) && directRequestRE.test(request);
-const isDirectRequest = (request) => directRequestRE.test(request);
-const cssModulesCache = /* @__PURE__ */ new WeakMap();
-const removedPureCssFilesCache = /* @__PURE__ */ new WeakMap();
-const cssBundleNameCache = /* @__PURE__ */ new WeakMap();
-const postcssConfigCache = /* @__PURE__ */ new WeakMap();
-function encodePublicUrlsInCSS(config$2) {
- return config$2.command === "build";
-}
-const cssUrlAssetRE = /__VITE_CSS_URL__([\da-f]+)__/g;
-/**
-* Plugin applied before user plugins
-*/
-function cssPlugin(config$2) {
- const isBuild = config$2.command === "build";
- let moduleCache;
- const idResolver = createBackCompatIdResolver(config$2, {
- preferRelative: true,
- tryIndex: false,
- extensions: []
- });
- let preprocessorWorkerController;
- if (config$2.css.transformer !== "lightningcss") resolvePostcssConfig(config$2).catch(() => {});
- return {
- name: "vite:css",
- buildStart() {
- moduleCache = /* @__PURE__ */ new Map();
- cssModulesCache.set(config$2, moduleCache);
- removedPureCssFilesCache.set(config$2, /* @__PURE__ */ new Map());
- preprocessorWorkerController = createPreprocessorWorkerController(normalizeMaxWorkers(config$2.css.preprocessorMaxWorkers));
- preprocessorWorkerControllerCache.set(config$2, preprocessorWorkerController);
- },
- buildEnd() {
- preprocessorWorkerController?.close();
- },
- load: {
- filter: { id: CSS_LANGS_RE },
- async handler(id) {
- if (urlRE.test(id)) {
- if (isModuleCSSRequest(id)) throw new Error(`?url is not supported with CSS modules. (tried to import ${JSON.stringify(id)})`);
- if (isBuild) {
- id = injectQuery(removeUrlQuery(id), "transform-only");
- return `import ${JSON.stringify(id)};export default "__VITE_CSS_URL__${Buffer.from(id).toString("hex")}__"`;
- }
- }
- }
- },
- transform: {
- filter: { id: {
- include: CSS_LANGS_RE,
- exclude: [commonjsProxyRE, SPECIAL_QUERY_RE]
- } },
- async handler(raw, id) {
- const { environment } = this;
- const resolveUrl$1 = (url$3, importer) => idResolver(environment, url$3, importer);
- const urlResolver = async (url$3, importer) => {
- const decodedUrl = decodeURI(url$3);
- if (checkPublicFile(decodedUrl, config$2)) if (encodePublicUrlsInCSS(config$2)) return [publicFileToBuiltUrl(decodedUrl, config$2), void 0];
- else return [joinUrlSegments(config$2.base, decodedUrl), void 0];
- const [id$1, fragment] = decodedUrl.split("#");
- let resolved = await resolveUrl$1(id$1, importer);
- if (resolved) {
- if (fragment) resolved += "#" + fragment;
- let url$4 = await fileToUrl$1(this, resolved);
- if (!url$4.startsWith("data:") && this.environment.mode === "dev") {
- const mod = [...this.environment.moduleGraph.getModulesByFile(resolved) ?? []].find((mod$1) => mod$1.type === "asset");
- if (mod?.lastHMRTimestamp) url$4 = injectQuery(url$4, `t=${mod.lastHMRTimestamp}`);
- }
- return [url$4, resolved];
- }
- if (config$2.command === "build") {
- if (!(config$2.build.rollupOptions.external ? resolveUserExternal(config$2.build.rollupOptions.external, decodedUrl, id$1, false) : false)) config$2.logger.warnOnce(`\n${decodedUrl} referenced in ${id$1} didn't resolve at build time, it will remain unchanged to be resolved at runtime`);
- }
- return [url$3, void 0];
- };
- const { code: css, modules, deps, map: map$1 } = await compileCSS(environment, id, raw, preprocessorWorkerController, urlResolver);
- if (modules) moduleCache.set(id, modules);
- if (deps) for (const file of deps) this.addWatchFile(file);
- return {
- code: css,
- map: map$1
- };
- }
- }
- };
-}
-/**
-* Plugin applied after user plugins
-*/
-function cssPostPlugin(config$2) {
- const styles = /* @__PURE__ */ new Map();
- let codeSplitEmitQueue = createSerialPromiseQueue();
- const urlEmitQueue = createSerialPromiseQueue();
- let pureCssChunks;
- let hasEmitted = false;
- let chunkCSSMap;
- const rollupOptionsOutput = config$2.build.rollupOptions.output;
- const assetFileNames = (Array.isArray(rollupOptionsOutput) ? rollupOptionsOutput[0] : rollupOptionsOutput)?.assetFileNames;
- const getCssAssetDirname = (cssAssetName) => {
- const cssAssetNameDir = path.dirname(cssAssetName);
- if (!assetFileNames) return path.join(config$2.build.assetsDir, cssAssetNameDir);
- else if (typeof assetFileNames === "string") return path.join(path.dirname(assetFileNames), cssAssetNameDir);
- else return path.dirname(assetFileNames({
- type: "asset",
- name: cssAssetName,
- names: [cssAssetName],
- originalFileName: null,
- originalFileNames: [],
- source: "/* vite internal call, ignore */"
- }));
- };
- function getCssBundleName() {
- const cached = cssBundleNameCache.get(config$2);
- if (cached) return cached;
- const cssBundleName = config$2.build.lib ? resolveLibCssFilename(config$2.build.lib, config$2.root, config$2.packageCache) : defaultCssBundleName;
- cssBundleNameCache.set(config$2, cssBundleName);
- return cssBundleName;
- }
- return {
- name: "vite:css-post",
- renderStart() {
- pureCssChunks = /* @__PURE__ */ new Set();
- hasEmitted = false;
- chunkCSSMap = /* @__PURE__ */ new Map();
- codeSplitEmitQueue = createSerialPromiseQueue();
- },
- transform: {
- filter: { id: {
- include: CSS_LANGS_RE,
- exclude: [commonjsProxyRE, SPECIAL_QUERY_RE]
- } },
- async handler(css, id) {
- css = stripBomTag(css);
- const inlineCSS = inlineCSSRE.test(id);
- const isHTMLProxy$1 = htmlProxyRE.test(id);
- if (inlineCSS && isHTMLProxy$1) {
- if (styleAttrRE.test(id)) css = css.replace(/"/g, "&quot;");
- const index = htmlProxyIndexRE.exec(id)?.[1];
- if (index == null) throw new Error(`HTML proxy index in "${id}" not found`);
- addToHTMLProxyTransformResult(`${getHash(cleanUrl(id))}_${Number.parseInt(index)}`, css);
- return `export default ''`;
- }
- const inlined = inlineRE.test(id);
- const modules = cssModulesCache.get(config$2).get(id);
- const modulesCode = modules && !inlined && dataToEsm(modules, {
- namedExports: true,
- preferConst: true
- });
- if (config$2.command === "serve") {
- const getContentWithSourcemap = async (content) => {
- if (config$2.css.devSourcemap) {
- const sourcemap = this.getCombinedSourcemap();
- if (sourcemap.mappings) await injectSourcesContent(sourcemap, cleanUrl(id), config$2.logger);
- return getCodeWithSourcemap("css", content, sourcemap);
- }
- return content;
- };
- if (isDirectCSSRequest(id)) return null;
- if (inlined) return `export default ${JSON.stringify(css)}`;
- if (this.environment.config.consumer === "server") return modulesCode || "export {}";
- const cssContent = await getContentWithSourcemap(css);
- return {
- code: [
- `import { updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle } from ${JSON.stringify(path.posix.join(config$2.base, CLIENT_PUBLIC_PATH))}`,
- `const __vite__id = ${JSON.stringify(id)}`,
- `const __vite__css = ${JSON.stringify(cssContent)}`,
- `__vite__updateStyle(__vite__id, __vite__css)`,
- `${modulesCode || "import.meta.hot.accept()"}`,
- `import.meta.hot.prune(() => __vite__removeStyle(__vite__id))`
- ].join("\n"),
- map: { mappings: "" }
- };
- }
- if (!inlined) styles.set(id, css);
- let code;
- if (modulesCode) code = modulesCode;
- else if (inlined) {
- let content = css;
- if (config$2.build.cssMinify) content = await minifyCSS(content, config$2, true);
- code = `export default ${JSON.stringify(content)}`;
- } else code = "";
- return {
- code,
- map: { mappings: "" },
- moduleSideEffects: modulesCode || inlined ? false : "no-treeshake"
- };
- }
- },
- async renderChunk(code, chunk, opts, meta) {
- let chunkCSS;
- const renderedModules = new Proxy({}, { get(_target, p) {
- for (const name in meta.chunks) {
- const module$1 = meta.chunks[name].modules[p];
- if (module$1) return module$1;
- }
- } });
- const isJsChunkEmpty = code === "" && !chunk.isEntry;
- let isPureCssChunk = chunk.exports.length === 0;
- const ids = Object.keys(chunk.modules);
- for (const id of ids) if (styles.has(id)) {
- if (transformOnlyRE.test(id)) continue;
- const cssScopeTo = this.getModuleInfo(id)?.meta?.vite?.cssScopeTo;
- if (cssScopeTo && !isCssScopeToRendered(cssScopeTo, renderedModules)) continue;
- if (cssModuleRE.test(id)) isPureCssChunk = false;
- chunkCSS = (chunkCSS || "") + styles.get(id);
- } else if (!isJsChunkEmpty) isPureCssChunk = false;
- const publicAssetUrlMap = publicAssetUrlCache.get(config$2);
- const resolveAssetUrlsInCss = (chunkCSS$1, cssAssetName) => {
- const encodedPublicUrls = encodePublicUrlsInCSS(config$2);
- const cssAssetDirname = encodedPublicUrls || config$2.base === "./" || config$2.base === "" ? slash(getCssAssetDirname(cssAssetName)) : void 0;
- const toRelative = (filename) => {
- const relativePath = normalizePath(path.relative(cssAssetDirname, filename));
- return relativePath[0] === "." ? relativePath : "./" + relativePath;
- };
- chunkCSS$1 = chunkCSS$1.replace(assetUrlRE, (_, fileHash, postfix = "") => {
- const filename = this.getFileName(fileHash) + postfix;
- chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
- return encodeURIPath(toOutputFilePathInCss(filename, "asset", cssAssetName, "css", config$2, toRelative));
- });
- if (encodedPublicUrls) {
- const relativePathToPublicFromCSS = normalizePath(path.relative(cssAssetDirname, ""));
- chunkCSS$1 = chunkCSS$1.replace(publicAssetUrlRE, (_, hash$1) => {
- const publicUrl = publicAssetUrlMap.get(hash$1).slice(1);
- return encodeURIPath(toOutputFilePathInCss(publicUrl, "public", cssAssetName, "css", config$2, () => `${relativePathToPublicFromCSS}/${publicUrl}`));
- });
- }
- return chunkCSS$1;
- };
- function ensureFileExt(name, ext) {
- return normalizePath(path.format({
- ...path.parse(name),
- base: void 0,
- ext
- }));
- }
- let s;
- const urlEmitTasks = [];
- if (code.includes("__VITE_CSS_URL__")) {
- let match;
- cssUrlAssetRE.lastIndex = 0;
- while (match = cssUrlAssetRE.exec(code)) {
- const [full, idHex] = match;
- const id = Buffer.from(idHex, "hex").toString();
- const originalFileName = cleanUrl(id);
- const cssAssetName = ensureFileExt(path.basename(originalFileName), ".css");
- if (!styles.has(id)) throw new Error(`css content for ${JSON.stringify(id)} was not found`);
- let cssContent = styles.get(id);
- cssContent = resolveAssetUrlsInCss(cssContent, cssAssetName);
- urlEmitTasks.push({
- cssAssetName,
- originalFileName,
- content: cssContent,
- start: match.index,
- end: match.index + full.length
- });
- }
- }
- await urlEmitQueue.run(async () => Promise.all(urlEmitTasks.map(async (info) => {
- info.content = await finalizeCss(info.content, config$2);
- })));
- if (urlEmitTasks.length > 0) {
- const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, config$2.isWorker);
- s ||= new MagicString(code);
- for (const { cssAssetName, originalFileName, content, start, end } of urlEmitTasks) {
- const referenceId = this.emitFile({
- type: "asset",
- name: cssAssetName,
- originalFileName,
- source: content
- });
- const filename = this.getFileName(referenceId);
- chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
- const replacement = toOutputFilePathInJS(this.environment, filename, "asset", chunk.fileName, "js", toRelativeRuntime);
- const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
- s.update(start, end, replacementString);
- }
- }
- if (chunkCSS !== void 0) {
- if (isPureCssChunk && (opts.format === "es" || opts.format === "cjs")) pureCssChunks.add(chunk);
- if (this.environment.config.build.cssCodeSplit) {
- if (opts.format === "es" || opts.format === "cjs") {
- const isEntry = chunk.isEntry && isPureCssChunk;
- const cssFullAssetName = ensureFileExt(chunk.name, ".css");
- const cssAssetName = chunk.isEntry && (!chunk.facadeModuleId || !isCSSRequest(chunk.facadeModuleId)) ? path.basename(cssFullAssetName) : cssFullAssetName;
- const originalFileName = getChunkOriginalFileName(chunk, config$2.root, opts.format);
- chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssAssetName);
- chunkCSS = await codeSplitEmitQueue.run(async () => {
- return finalizeCss(chunkCSS, config$2);
- });
- const referenceId = this.emitFile({
- type: "asset",
- name: cssAssetName,
- originalFileName,
- source: chunkCSS
- });
- if (isEntry) cssEntriesMap.get(this.environment).set(chunk.name, referenceId);
- chunk.viteMetadata.importedCss.add(this.getFileName(referenceId));
- } else if (this.environment.config.consumer === "client") {
- chunkCSS = await finalizeCss(chunkCSS, config$2);
- let cssString = JSON.stringify(chunkCSS);
- cssString = renderAssetUrlInJS(this, chunk, opts, cssString)?.toString() || cssString;
- const style = `__vite_style__`;
- const injectCode = `var ${style} = document.createElement('style');${style}.textContent = ${cssString};document.head.appendChild(${style});`;
- let injectionPoint;
- const wrapIdx = code.indexOf("System.register");
- const singleQuoteUseStrict = `'use strict';`;
- const doubleQuoteUseStrict = `"use strict";`;
- if (wrapIdx >= 0) {
- const executeFnStart = code.indexOf("execute:", wrapIdx);
- injectionPoint = code.indexOf("{", executeFnStart) + 1;
- } else if (code.includes(singleQuoteUseStrict)) injectionPoint = code.indexOf(singleQuoteUseStrict) + singleQuoteUseStrict.length;
- else if (code.includes(doubleQuoteUseStrict)) injectionPoint = code.indexOf(doubleQuoteUseStrict) + doubleQuoteUseStrict.length;
- else throw new Error("Injection point for inlined CSS not found");
- s ||= new MagicString(code);
- s.appendRight(injectionPoint, injectCode);
- }
- } else {
- chunkCSS = resolveAssetUrlsInCss(chunkCSS, getCssBundleName());
- chunkCSSMap.set(chunk.fileName, chunkCSS);
- }
- }
- if (s) if (config$2.build.sourcemap) return {
- code: s.toString(),
- map: s.generateMap({ hires: "boundary" })
- };
- else return { code: s.toString() };
- return null;
- },
- augmentChunkHash(chunk) {
- if (chunk.viteMetadata?.importedCss.size) {
- let hash$1 = "";
- for (const id of chunk.viteMetadata.importedCss) hash$1 += id;
- return hash$1;
- }
- },
- async generateBundle(opts, bundle) {
- if (opts.__vite_skip_asset_emit__) return;
- if ((config$2.command !== "build" || this.environment.config.build.emitAssets) && !this.environment.config.build.cssCodeSplit && !hasEmitted) {
- let extractedCss = "";
- const collected = /* @__PURE__ */ new Set();
- const dynamicImports = /* @__PURE__ */ new Set();
- function collect(chunk) {
- if (!chunk || chunk.type !== "chunk" || collected.has(chunk)) return;
- collected.add(chunk);
- chunk.imports.forEach((importName) => collect(bundle[importName]));
- chunk.dynamicImports.forEach((importName) => dynamicImports.add(importName));
- extractedCss += chunkCSSMap.get(chunk.preliminaryFileName) ?? "";
- }
- for (const chunk of Object.values(bundle)) if (chunk.type === "chunk" && chunk.isEntry) collect(chunk);
- for (const chunkName of dynamicImports) collect(bundle[chunkName]);
- if (extractedCss) {
- hasEmitted = true;
- extractedCss = await finalizeCss(extractedCss, config$2);
- this.emitFile({
- name: getCssBundleName(),
- type: "asset",
- source: extractedCss,
- originalFileName: "style.css"
- });
- }
- }
- if (pureCssChunks.size) {
- const prelimaryNameToChunkMap = Object.fromEntries(Object.values(bundle).filter((chunk) => chunk.type === "chunk").map((chunk) => [chunk.preliminaryFileName, chunk.fileName]));
- const pureCssChunkNames = [...pureCssChunks].map((pureCssChunk) => prelimaryNameToChunkMap[pureCssChunk.fileName]).filter(Boolean);
- const replaceEmptyChunk = getEmptyChunkReplacer(pureCssChunkNames, opts.format);
- for (const file in bundle) {
- const chunk = bundle[file];
- if (chunk.type === "chunk") {
- let chunkImportsPureCssChunk = false;
- chunk.imports = chunk.imports.filter((file$1) => {
- if (pureCssChunkNames.includes(file$1)) {
- const { importedCss, importedAssets } = bundle[file$1].viteMetadata;
- importedCss.forEach((file$2) => chunk.viteMetadata.importedCss.add(file$2));
- importedAssets.forEach((file$2) => chunk.viteMetadata.importedAssets.add(file$2));
- chunkImportsPureCssChunk = true;
- return false;
- }
- return true;
- });
- if (chunkImportsPureCssChunk) chunk.code = replaceEmptyChunk(chunk.code);
- }
- }
- const removedPureCssFiles = removedPureCssFilesCache.get(config$2);
- pureCssChunkNames.forEach((fileName) => {
- removedPureCssFiles.set(fileName, bundle[fileName]);
- delete bundle[fileName];
- delete bundle[`${fileName}.map`];
- });
- }
- const cssAssets = Object.values(bundle).filter((asset) => asset.type === "asset" && asset.fileName.endsWith(".css"));
- for (const cssAsset of cssAssets) if (typeof cssAsset.source === "string") cssAsset.source = cssAsset.source.replace(viteHashUpdateMarkerRE, "");
- }
- };
-}
-function cssAnalysisPlugin(config$2) {
- return {
- name: "vite:css-analysis",
- transform: {
- filter: { id: {
- include: CSS_LANGS_RE,
- exclude: [commonjsProxyRE, SPECIAL_QUERY_RE]
- } },
- async handler(_, id) {
- const { moduleGraph } = this.environment;
- const thisModule = moduleGraph.getModuleById(id);
- if (thisModule) {
- const isSelfAccepting = !cssModulesCache.get(config$2)?.get(id) && !inlineRE.test(id) && !htmlProxyRE.test(id);
- const pluginImports = this._addedImports;
- if (pluginImports) {
- const depModules = /* @__PURE__ */ new Set();
- for (const file of pluginImports) depModules.add(moduleGraph.createFileOnlyEntry(file));
- moduleGraph.updateModuleInfo(thisModule, depModules, null, /* @__PURE__ */ new Set(), null, isSelfAccepting);
- } else thisModule.isSelfAccepting = isSelfAccepting;
- }
- }
- }
- };
-}
-function isCssScopeToRendered(cssScopeTo, renderedModules) {
- const [importerId, exp] = cssScopeTo;
- const importer = renderedModules[importerId];
- return importer && (exp === void 0 || importer.renderedExports.includes(exp));
-}
-/**
-* Create a replacer function that takes code and replaces given pure CSS chunk imports
-* @param pureCssChunkNames The chunks that only contain pure CSS and should be replaced
-* @param outputFormat The module output format to decide whether to replace `import` or `require`
-*/
-function getEmptyChunkReplacer(pureCssChunkNames, outputFormat) {
- const emptyChunkFiles = pureCssChunkNames.map((file) => escapeRegex(path.basename(file))).join("|");
- const emptyChunkRE = new RegExp(outputFormat === "es" ? `\\bimport\\s*["'][^"']*(?:${emptyChunkFiles})["'];` : `(\\b|,\\s*)require\\(\\s*["'][^"']*(?:${emptyChunkFiles})["']\\)(;|,)`, "g");
- return (code) => code.replace(emptyChunkRE, (m, p1, p2) => {
- if (outputFormat === "es") return `/* empty css ${"".padEnd(m.length - 15)}*/`;
- if (p2 === ";") return `${p2}/* empty css ${"".padEnd(m.length - 16)}*/`;
- return `${p1}/* empty css ${"".padEnd(m.length - 15 - p1.length)}*/`;
- });
-}
-const fileURLWithWindowsDriveRE = /^file:\/\/\/[a-zA-Z]:\//;
-function createCSSResolvers(config$2) {
- let cssResolve;
- let sassResolve;
- let lessResolve;
- return {
- get css() {
- return cssResolve ??= createBackCompatIdResolver(config$2, {
- extensions: [".css"],
- mainFields: ["style"],
- conditions: ["style", DEV_PROD_CONDITION],
- tryIndex: false,
- preferRelative: true
- });
- },
- get sass() {
- if (!sassResolve) {
- const resolver$1 = createBackCompatIdResolver(config$2, {
- extensions: [
- ".scss",
- ".sass",
- ".css"
- ],
- mainFields: ["sass", "style"],
- conditions: [
- "sass",
- "style",
- DEV_PROD_CONDITION
- ],
- tryIndex: true,
- tryPrefix: "_",
- preferRelative: true
- });
- sassResolve = async (...args) => {
- if (args[1].startsWith("file://")) args[1] = fileURLToPath(args[1], { windows: isWindows && !fileURLWithWindowsDriveRE.test(args[1]) ? false : void 0 });
- return resolver$1(...args);
- };
- }
- return sassResolve;
- },
- get less() {
- return lessResolve ??= createBackCompatIdResolver(config$2, {
- extensions: [".less", ".css"],
- mainFields: ["less", "style"],
- conditions: [
- "less",
- "style",
- DEV_PROD_CONDITION
- ],
- tryIndex: false,
- preferRelative: true
- });
- }
- };
-}
-function getCssResolversKeys(resolvers) {
- return Object.keys(resolvers);
-}
-async function compileCSSPreprocessors(environment, id, lang, code, workerController) {
- const { config: config$2 } = environment;
- const { preprocessorOptions, devSourcemap } = config$2.css;
- const atImportResolvers = getAtImportResolvers(environment.getTopLevelConfig());
- const opts = {
- ...preprocessorOptions && preprocessorOptions[lang] || {},
- filename: cleanUrl(id),
- enableSourcemap: devSourcemap ?? false
- };
- const preProcessor = workerController[lang];
- const preprocessResult = await preProcessor(environment, code, config$2.root, opts, atImportResolvers);
- if (preprocessResult.error) throw preprocessResult.error;
- let deps;
- if (preprocessResult.deps.length > 0) {
- const normalizedFilename = normalizePath(opts.filename);
- deps = new Set([...preprocessResult.deps].filter((dep) => normalizePath(dep) !== normalizedFilename));
- }
- return {
- code: preprocessResult.code,
- map: combineSourcemapsIfExists(opts.filename, preprocessResult.map, preprocessResult.additionalMap),
- deps
- };
-}
-const configToAtImportResolvers = /* @__PURE__ */ new WeakMap();
-function getAtImportResolvers(config$2) {
- let atImportResolvers = configToAtImportResolvers.get(config$2);
- if (!atImportResolvers) {
- atImportResolvers = createCSSResolvers(config$2);
- configToAtImportResolvers.set(config$2, atImportResolvers);
- }
- return atImportResolvers;
-}
-async function compileCSS(environment, id, code, workerController, urlResolver) {
- const { config: config$2 } = environment;
- const lang = CSS_LANGS_RE.exec(id)?.[1];
- const deps = /* @__PURE__ */ new Set();
- let preprocessorMap;
- if (isPreProcessor(lang)) {
- const preprocessorResult = await compileCSSPreprocessors(environment, id, lang, code, workerController);
- code = preprocessorResult.code;
- preprocessorMap = preprocessorResult.map;
- preprocessorResult.deps?.forEach((dep) => deps.add(dep));
- } else if (lang === "sss" && config$2.css.transformer === "lightningcss") {
- const sssResult = await transformSugarSS(environment, id, code);
- code = sssResult.code;
- preprocessorMap = sssResult.map;
- }
- const transformResult = await (config$2.css.transformer === "lightningcss" ? compileLightningCSS(environment, id, code, deps, workerController, urlResolver) : compilePostCSS(environment, id, code, deps, lang, workerController, urlResolver));
- if (!transformResult) return {
- code,
- map: config$2.css.devSourcemap ? preprocessorMap : { mappings: "" },
- deps
- };
- return {
- ...transformResult,
- map: config$2.css.devSourcemap ? combineSourcemapsIfExists(cleanUrl(id), typeof transformResult.map === "string" ? JSON.parse(transformResult.map) : transformResult.map, preprocessorMap) : { mappings: "" },
- deps
- };
-}
-async function compilePostCSS(environment, id, code, deps, lang, workerController, urlResolver) {
- const { config: config$2 } = environment;
- const { modules: modulesOptions, devSourcemap } = config$2.css;
- const isModule = modulesOptions !== false && cssModuleRE.test(id);
- const needInlineImport = code.includes("@import");
- const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
- const postcssConfig = await resolvePostcssConfig(environment.getTopLevelConfig());
- if (lang !== "sss" && !postcssConfig && !isModule && !needInlineImport && !hasUrl) return;
- const atImportResolvers = getAtImportResolvers(environment.getTopLevelConfig());
- const postcssPlugins = postcssConfig?.plugins.slice() ?? [];
- if (needInlineImport) postcssPlugins.unshift((await importPostcssImport()).default({
- async resolve(id$1, basedir) {
- const publicFile = checkPublicFile(id$1, environment.getTopLevelConfig());
- if (publicFile) return publicFile;
- const resolved = await atImportResolvers.css(environment, id$1, path.join(basedir, "*"));
- if (resolved) return path.resolve(resolved);
- if (!path.isAbsolute(id$1)) environment.logger.error(import_picocolors$9.default.red(`Unable to resolve \`@import "${id$1}"\` from ${basedir}`));
- return id$1;
- },
- async load(id$1) {
- const code$1 = await fs.promises.readFile(id$1, "utf-8");
- const lang$1 = CSS_LANGS_RE.exec(id$1)?.[1];
- if (isPreProcessor(lang$1)) {
- const result = await compileCSSPreprocessors(environment, id$1, lang$1, code$1, workerController);
- result.deps?.forEach((dep) => deps.add(dep));
- return result.code;
- }
- return code$1;
- },
- nameLayer(index) {
- return `vite--anon-layer-${getHash(id)}-${index}`;
- }
- }));
- if (urlResolver && (postcssPlugins.length > 0 || isModule || hasUrl)) postcssPlugins.push(UrlRewritePostcssPlugin({
- resolver: urlResolver,
- deps,
- logger: environment.logger
- }));
- let modules;
- if (isModule) postcssPlugins.unshift((await importPostcssModules()).default({
- ...modulesOptions,
- localsConvention: modulesOptions?.localsConvention,
- getJSON(cssFileName, _modules, outputFileName) {
- modules = _modules;
- if (modulesOptions && typeof modulesOptions.getJSON === "function") modulesOptions.getJSON(cssFileName, _modules, outputFileName);
- },
- async resolve(id$1, importer) {
- for (const key of getCssResolversKeys(atImportResolvers)) {
- const resolved = await atImportResolvers[key](environment, id$1, importer);
- if (resolved) return path.resolve(resolved);
- }
- return id$1;
- }
- }));
- const postcssOptions = postcssConfig?.options ?? {};
- const postcssParser = lang === "sss" ? await loadSss(config$2.root) : postcssOptions.parser;
- if (!postcssPlugins.length && !postcssParser) return;
- return {
- ...await runPostCSS(id, code, postcssPlugins, {
- ...postcssOptions,
- parser: postcssParser
- }, deps, environment.logger, devSourcemap),
- modules
- };
-}
-async function transformSugarSS(environment, id, code) {
- const { config: config$2 } = environment;
- const { devSourcemap } = config$2.css;
- return await runPostCSS(id, code, [], { parser: await loadSss(config$2.root) }, void 0, environment.logger, devSourcemap);
-}
-async function runPostCSS(id, code, plugins$1, options$1, deps, logger, enableSourcemap) {
- let postcssResult;
- try {
- const source = removeDirectQuery(id);
- postcssResult = await (await importPostcss()).default(plugins$1).process(code, {
- ...options$1,
- to: source,
- from: source,
- ...enableSourcemap ? { map: {
- inline: false,
- annotation: false,
- sourcesContent: true
- } } : {}
- });
- for (const message of postcssResult.messages) if (message.type === "dependency") deps?.add(normalizePath(message.file));
- else if (message.type === "dir-dependency") {
- const { dir, glob: globPattern = "**" } = message;
- const files = globSync(globPattern, {
- absolute: true,
- cwd: path.resolve(path.dirname(id), dir),
- expandDirectories: false,
- ignore: ["**/node_modules/**"]
- });
- for (let i$1 = 0; i$1 < files.length; i$1++) deps?.add(files[i$1]);
- } else if (message.type === "warning") {
- const warning = message;
- let msg = `[vite:css][postcss] ${warning.text}`;
- msg += `\n${generateCodeFrame(code, {
- line: warning.line,
- column: warning.column - 1
- }, warning.endLine !== void 0 && warning.endColumn !== void 0 ? {
- line: warning.endLine,
- column: warning.endColumn - 1
- } : void 0)}`;
- logger.warn(import_picocolors$9.default.yellow(msg));
- }
- } catch (e$1) {
- e$1.message = `[postcss] ${e$1.message}`;
- e$1.code = code;
- e$1.loc = {
- file: e$1.file,
- line: e$1.line,
- column: e$1.column - 1
- };
- throw e$1;
- }
- if (!enableSourcemap) return {
- code: postcssResult.css,
- map: { mappings: "" }
- };
- const postcssMap = await formatPostcssSourceMap(postcssResult.map.toJSON(), cleanUrl(id));
- return {
- code: postcssResult.css,
- map: postcssMap
- };
-}
-function createCachedImport(imp) {
- let cached;
- return () => {
- if (!cached) cached = imp().then((module$1) => {
- cached = module$1;
- return module$1;
- });
- return cached;
- };
-}
-const importPostcssImport = createCachedImport(() => import("./postcss-import.js").then(__toDynamicImportESM(1)));
-const importPostcssModules = createCachedImport(() => import("./build2.js").then(__toDynamicImportESM(1)));
-const importPostcss = createCachedImport(() => import("postcss"));
-const preprocessorWorkerControllerCache = /* @__PURE__ */ new WeakMap();
-let alwaysFakeWorkerWorkerControllerCache;
-/**
-* @experimental
-*/
-async function preprocessCSS(code, filename, config$2) {
- let workerController = preprocessorWorkerControllerCache.get(config$2);
- if (!workerController) {
- alwaysFakeWorkerWorkerControllerCache ||= createPreprocessorWorkerController(0);
- workerController = alwaysFakeWorkerWorkerControllerCache;
- }
- return await compileCSS(new PartialEnvironment("client", config$2), filename, code, workerController);
-}
-async function formatPostcssSourceMap(rawMap, file) {
- const inputFileDir = path.dirname(file);
- const sources = rawMap.sources.map((source) => {
- const cleanSource = cleanUrl(decodeURIComponent(source));
- if (cleanSource[0] === "<" && cleanSource.endsWith(">")) return `\0${cleanSource}`;
- return normalizePath(path.resolve(inputFileDir, cleanSource));
- });
- return {
- file,
- mappings: rawMap.mappings,
- names: rawMap.names,
- sources,
- sourcesContent: rawMap.sourcesContent,
- version: rawMap.version
- };
-}
-function combineSourcemapsIfExists(filename, map1, map2) {
- if (!map1 || !map2) return map1;
- if (map1.mappings === "" || map2.mappings === "") return { mappings: "" };
- return combineSourcemaps(filename, [map1, map2]);
-}
-const viteHashUpdateMarker = "/*$vite$:1*/";
-const viteHashUpdateMarkerRE = /\/\*\$vite\$:\d+\*\//;
-async function finalizeCss(css, config$2) {
- if (css.includes("@import") || css.includes("@charset")) css = await hoistAtRules(css);
- if (config$2.build.cssMinify) css = await minifyCSS(css, config$2, false);
- css += viteHashUpdateMarker;
- return css;
-}
-async function resolvePostcssConfig(config$2) {
- let result = postcssConfigCache.get(config$2);
- if (result !== void 0) return await result;
- const inlineOptions = config$2.css.postcss;
- if (isObject(inlineOptions)) {
- const options$1 = { ...inlineOptions };
- delete options$1.plugins;
- result = {
- options: options$1,
- plugins: inlineOptions.plugins || []
- };
- } else {
- const searchPath = typeof inlineOptions === "string" ? inlineOptions : config$2.root;
- result = (0, import_src.default)({}, searchPath, { stopDir: searchForWorkspaceRoot(config$2.root) }).catch((e$1) => {
- if (!e$1.message.includes("No PostCSS Config found")) if (e$1 instanceof Error) {
- const { name, message, stack } = e$1;
- e$1.name = "Failed to load PostCSS config";
- e$1.message = `Failed to load PostCSS config (searchPath: ${searchPath}): [${name}] ${message}\n${stack}`;
- e$1.stack = "";
- throw e$1;
- } else throw new Error(`Failed to load PostCSS config: ${e$1}`);
- return null;
- });
- result.then((resolved) => {
- postcssConfigCache.set(config$2, resolved);
- }, () => {});
- }
- postcssConfigCache.set(config$2, result);
- return result;
-}
-const cssUrlRE = /(?<!@import\s+)(?<=^|[^\w\-\u0080-\uffff])url\((\s*('[^']+'|"[^"]+")\s*|(?:\\.|[^'")\\])+)\)/;
-const cssDataUriRE = /(?<=^|[^\w\-\u0080-\uffff])data-uri\((\s*('[^']+'|"[^"]+")\s*|[^'")]+)\)/;
-const importCssRE = /@import\s+(?:url\()?('[^']+\.css'|"[^"]+\.css"|[^'"\s)]+\.css)/;
-const cssImageSetRE = /(?<=image-set\()((?:[\w-]{1,256}\([^)]*\)|[^)])*)(?=\))/;
-const UrlRewritePostcssPlugin = (opts) => {
- if (!opts) throw new Error("base or replace is required");
- return {
- postcssPlugin: "vite-url-rewrite",
- Once(root) {
- const promises$2 = [];
- root.walkDecls((declaration) => {
- const importer = declaration.source?.input.file;
- if (!importer) opts.logger.warnOnce("\nA PostCSS plugin did not pass the `from` option to `postcss.parse`. This may cause imported assets to be incorrectly transformed. If you've recently added a PostCSS plugin that raised this warning, please contact the package author to fix the issue.");
- const isCssUrl = cssUrlRE.test(declaration.value);
- const isCssImageSet = cssImageSetRE.test(declaration.value);
- if (isCssUrl || isCssImageSet) {
- const replacerForDeclaration = async (rawUrl) => {
- const [newUrl, resolvedId] = await opts.resolver(rawUrl, importer);
- if (resolvedId) opts.deps.add(resolvedId);
- return newUrl;
- };
- if (isCssUrl && isCssImageSet) promises$2.push(rewriteCssUrls(declaration.value, replacerForDeclaration).then((url$3) => rewriteCssImageSet(url$3, replacerForDeclaration)).then((url$3) => {
- declaration.value = url$3;
- }));
- else promises$2.push((isCssImageSet ? rewriteCssImageSet : rewriteCssUrls)(declaration.value, replacerForDeclaration).then((url$3) => {
- declaration.value = url$3;
- }));
- }
- });
- if (promises$2.length) return Promise.all(promises$2);
- }
- };
-};
-UrlRewritePostcssPlugin.postcss = true;
-function rewriteCssUrls(css, replacer) {
- return asyncReplace(css, cssUrlRE, async (match) => {
- const [matched, rawUrl] = match;
- return await doUrlReplace(rawUrl.trim(), matched, replacer);
- });
-}
-function rewriteCssDataUris(css, replacer) {
- return asyncReplace(css, cssDataUriRE, async (match) => {
- const [matched, rawUrl] = match;
- return await doUrlReplace(rawUrl.trim(), matched, replacer, "data-uri");
- });
-}
-function rewriteImportCss(css, replacer) {
- return asyncReplace(css, importCssRE, async (match) => {
- const [matched, rawUrl] = match;
- return await doImportCSSReplace(rawUrl, matched, replacer);
- });
-}
-const cssNotProcessedRE = /(?:gradient|element|cross-fade|image)\(/;
-async function rewriteCssImageSet(css, replacer) {
- return await asyncReplace(css, cssImageSetRE, async (match) => {
- const [, rawUrl] = match;
- return await processSrcSet(rawUrl, async ({ url: url$3 }) => {
- if (cssUrlRE.test(url$3)) return await rewriteCssUrls(url$3, replacer);
- if (!cssNotProcessedRE.test(url$3)) return await doUrlReplace(url$3, url$3, replacer);
- return url$3;
- });
- });
-}
-function skipUrlReplacer(unquotedUrl) {
- return isExternalUrl(unquotedUrl) || isDataUrl(unquotedUrl) || unquotedUrl[0] === "#" || functionCallRE.test(unquotedUrl) || unquotedUrl.startsWith("__VITE_ASSET__") || unquotedUrl.startsWith("__VITE_PUBLIC_ASSET__");
-}
-async function doUrlReplace(rawUrl, matched, replacer, funcName = "url") {
- let wrap$1 = "";
- const first$2 = rawUrl[0];
- let unquotedUrl = rawUrl;
- if (first$2 === `"` || first$2 === `'`) {
- wrap$1 = first$2;
- unquotedUrl = rawUrl.slice(1, -1);
- }
- if (skipUrlReplacer(unquotedUrl)) return matched;
- unquotedUrl = unquotedUrl.replace(/\\(\W)/g, "$1");
- let newUrl = await replacer(unquotedUrl, rawUrl);
- if (newUrl === false) return matched;
- if (wrap$1 === "" && (newUrl !== encodeURI(newUrl) || newUrl.includes(")"))) wrap$1 = "\"";
- if (wrap$1 === "'" && newUrl.includes("'")) wrap$1 = "\"";
- if (wrap$1 === "\"" && newUrl.includes("\"")) newUrl = newUrl.replace(nonEscapedDoubleQuoteRe, "\\\"");
- return `${funcName}(${wrap$1}${newUrl}${wrap$1})`;
-}
-async function doImportCSSReplace(rawUrl, matched, replacer) {
- let wrap$1 = "";
- const first$2 = rawUrl[0];
- let unquotedUrl = rawUrl;
- if (first$2 === `"` || first$2 === `'`) {
- wrap$1 = first$2;
- unquotedUrl = rawUrl.slice(1, -1);
- }
- if (skipUrlReplacer(unquotedUrl)) return matched;
- const newUrl = await replacer(unquotedUrl, rawUrl);
- if (newUrl === false) return matched;
- return `@import ${matched.includes("url(") ? "url(" : ""}${wrap$1}${newUrl}${wrap$1}`;
-}
-async function minifyCSS(css, config$2, inlined) {
- if (config$2.build.cssMinify === "lightningcss") try {
- const { code, warnings } = (await importLightningCSS()).transform({
- ...config$2.css.lightningcss,
- targets: convertTargets(config$2.build.cssTarget),
- cssModules: void 0,
- filename: defaultCssBundleName,
- code: Buffer.from(css),
- minify: true
- });
- for (const warning of warnings) {
- let msg = `[lightningcss minify] ${warning.message}`;
- msg += `\n${generateCodeFrame(css, {
- line: warning.loc.line,
- column: warning.loc.column - 1
- })}`;
- config$2.logger.warn(import_picocolors$9.default.yellow(msg));
- }
- return decoder.decode(code) + (inlined ? "" : "\n");
- } catch (e$1) {
- e$1.message = `[lightningcss minify] ${e$1.message}`;
- const friendlyMessage = getLightningCssErrorMessageForIeSyntaxes(css);
- if (friendlyMessage) e$1.message += friendlyMessage;
- if (e$1.loc) {
- e$1.loc = {
- line: e$1.loc.line,
- column: e$1.loc.column - 1
- };
- e$1.frame = generateCodeFrame(css, e$1.loc);
- }
- throw e$1;
- }
- try {
- const { code, warnings } = await transform(css, {
- loader: "css",
- target: config$2.build.cssTarget || void 0,
- ...resolveMinifyCssEsbuildOptions(config$2.esbuild || {})
- });
- if (warnings.length) {
- const msgs = await formatMessages(warnings, { kind: "warning" });
- config$2.logger.warn(import_picocolors$9.default.yellow(`[esbuild css minify]\n${msgs.join("\n")}`));
- }
- return inlined ? code.trimEnd() : code;
- } catch (e$1) {
- if (e$1.errors) {
- e$1.message = "[esbuild css minify] " + e$1.message;
- e$1.frame = "\n" + (await formatMessages(e$1.errors, { kind: "error" })).join("\n");
- e$1.loc = e$1.errors[0].location;
- }
- throw e$1;
- }
-}
-function resolveMinifyCssEsbuildOptions(options$1) {
- const base = {
- charset: options$1.charset,
- logLevel: options$1.logLevel,
- logLimit: options$1.logLimit,
- logOverride: options$1.logOverride,
- legalComments: options$1.legalComments
- };
- if (options$1.minifyIdentifiers != null || options$1.minifySyntax != null || options$1.minifyWhitespace != null) return {
- ...base,
- minifyIdentifiers: options$1.minifyIdentifiers ?? true,
- minifySyntax: options$1.minifySyntax ?? true,
- minifyWhitespace: options$1.minifyWhitespace ?? true
- };
- else return {
- ...base,
- minify: true
- };
-}
-const atImportRE = /@import(?:\s*(?:url\([^)]*\)|"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
-const atCharsetRE = /@charset(?:\s*(?:"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
-async function hoistAtRules(css) {
- const s = new MagicString(css);
- const cleanCss = emptyCssComments(css);
- let match;
- atImportRE.lastIndex = 0;
- while (match = atImportRE.exec(cleanCss)) {
- s.remove(match.index, match.index + match[0].length);
- s.appendLeft(0, match[0]);
- }
- atCharsetRE.lastIndex = 0;
- let foundCharset = false;
- while (match = atCharsetRE.exec(cleanCss)) {
- s.remove(match.index, match.index + match[0].length);
- if (!foundCharset) {
- s.prepend(match[0]);
- foundCharset = true;
- }
- }
- return s.toString();
-}
-const loadedPreprocessorPath = {};
-function loadPreprocessorPath(lang, root) {
- const cached = loadedPreprocessorPath[lang];
- if (cached) return cached;
- const resolved = nodeResolveWithVite(lang, void 0, { root }) ?? nodeResolveWithVite(lang, _dirname, { root });
- if (resolved) return loadedPreprocessorPath[lang] = resolved;
- const installCommand = getPackageManagerCommand("install");
- throw new Error(`Preprocessor dependency "${lang}" not found. Did you install it? Try \`${installCommand} -D ${lang}\`.`);
-}
-function loadSassPackage(root, skipEmbedded = false) {
- if (!skipEmbedded) try {
- return {
- name: "sass-embedded",
- path: loadPreprocessorPath("sass-embedded", root)
- };
- } catch (e1) {
- try {
- return {
- name: "sass",
- path: loadPreprocessorPath(PreprocessLang.sass, root)
- };
- } catch {
- throw e1;
- }
- }
- return {
- name: "sass",
- path: loadPreprocessorPath(PreprocessLang.sass, root)
- };
-}
-let cachedSss;
-async function loadSss(root) {
- if (!cachedSss) cachedSss = (async () => {
- return cachedSss = (await import(pathToFileURL(loadPreprocessorPath(PostCssDialectLang.sss, root)).href)).default;
- })();
- return cachedSss;
-}
-function cleanScssBugUrl(url$3) {
- if (typeof window !== "undefined" && typeof location !== "undefined" && typeof location.href === "string") {
- const prefix = location.href.replace(/\/$/, "");
- return url$3.replace(prefix, "");
- } else return url$3;
-}
-const makeScssWorker = (environment, resolvers, _maxWorkers) => {
- let compilerPromise;
- return {
- async run(sassPath, data, options$1) {
- const sass = await import(sassPath);
- compilerPromise ??= sass.initAsyncCompiler();
- const compiler = await compilerPromise;
- const sassOptions = { ...options$1 };
- sassOptions.url = pathToFileURL(options$1.filename);
- sassOptions.sourceMap = options$1.enableSourcemap;
- const skipRebaseUrls = (unquotedUrl, rawUrl) => {
- if (!(rawUrl[0] === "\"" || rawUrl[0] === "'") && unquotedUrl[0] === "$") return true;
- return unquotedUrl.startsWith("#{");
- };
- const internalImporter = {
- async canonicalize(url$3, context) {
- const importer = context.containingUrl ? fileURLToPath(context.containingUrl) : options$1.filename;
- const resolved = await resolvers.sass(environment, url$3, cleanScssBugUrl(importer));
- if (resolved && (resolved.endsWith(".css") || resolved.endsWith(".scss") || resolved.endsWith(".sass"))) return pathToFileURL(resolved);
- return null;
- },
- async load(canonicalUrl) {
- const ext = path.extname(canonicalUrl.pathname);
- let syntax = "scss";
- if (ext === ".sass") syntax = "indented";
- else if (ext === ".css") syntax = "css";
- const result$1 = await rebaseUrls(environment, fileURLToPath(canonicalUrl), options$1.filename, resolvers.sass, skipRebaseUrls);
- return {
- contents: result$1.contents ?? await fsp.readFile(result$1.file, "utf-8"),
- syntax,
- sourceMapUrl: canonicalUrl
- };
- }
- };
- sassOptions.importers = [...sassOptions.importers ?? [], internalImporter];
- sassOptions.importer ??= internalImporter;
- const result = await compiler.compileStringAsync(data, sassOptions);
- return {
- css: result.css,
- map: result.sourceMap ? JSON.stringify(result.sourceMap) : void 0,
- stats: { includedFiles: result.loadedUrls.filter((url$3) => url$3.protocol === "file:").map((url$3) => fileURLToPath(url$3)) }
- };
- },
- async stop() {
- await (await compilerPromise)?.dispose();
- compilerPromise = void 0;
- }
- };
-};
-const scssProcessor = (maxWorkers) => {
- let worker;
- let failedSassEmbedded;
- return {
- close() {
- worker?.stop();
- },
- async process(environment, source, root, options$1, resolvers) {
- let sassPackage = loadSassPackage(root, failedSassEmbedded ?? false);
- if (failedSassEmbedded === void 0) {
- failedSassEmbedded = false;
- try {
- await import(sassPackage.path);
- } catch (e$1) {
- if (/sass-embedded-[a-z0-9]+-[a-z0-9]+/i.test(e$1.message)) {
- failedSassEmbedded = true;
- sassPackage = loadSassPackage(root, failedSassEmbedded);
- }
- }
- }
- worker ??= makeScssWorker(environment, resolvers, maxWorkers);
- const { content: data, map: additionalMap } = await getSource(source, options$1.filename, options$1.additionalData, options$1.enableSourcemap);
- const optionsWithoutAdditionalData = {
- ...options$1,
- additionalData: void 0
- };
- try {
- const result = await worker.run(pathToFileURL(sassPackage.path).href, data, optionsWithoutAdditionalData);
- const deps = result.stats.includedFiles.map((f$1) => cleanScssBugUrl(f$1));
- const map$1 = result.map ? JSON.parse(result.map.toString()) : void 0;
- if (map$1) map$1.sources = map$1.sources.map((url$3) => url$3.startsWith("file://") ? normalizePath(fileURLToPath(url$3)) : url$3);
- return {
- code: result.css.toString(),
- map: map$1,
- additionalMap,
- deps
- };
- } catch (e$1) {
- e$1.message = `[sass] ${e$1.message}`;
- e$1.id = e$1.file;
- e$1.frame = e$1.formatted;
- if (e$1.span?.start) {
- e$1.line = e$1.span.start.line + 1;
- e$1.column = e$1.span.start.column + 1;
- e$1.frame = e$1.message;
- }
- return {
- code: "",
- error: e$1,
- deps: []
- };
- }
- }
- };
-};
-/**
-* relative url() inside \@imported sass and less files must be rebased to use
-* root file as base.
-*/
-async function rebaseUrls(environment, file, rootFile, resolver$1, ignoreUrl) {
- file = path.resolve(file);
- const fileDir = path.dirname(file);
- const rootDir = path.dirname(rootFile);
- if (fileDir === rootDir) return { file };
- const content = await fsp.readFile(file, "utf-8");
- const hasUrls = cssUrlRE.test(content);
- const hasDataUris = cssDataUriRE.test(content);
- const hasImportCss = importCssRE.test(content);
- if (!hasUrls && !hasDataUris && !hasImportCss) return { file };
- let rebased;
- const rebaseFn = async (unquotedUrl, rawUrl) => {
- if (ignoreUrl?.(unquotedUrl, rawUrl)) return false;
- if (unquotedUrl[0] === "/") return unquotedUrl;
- const absolute = await resolver$1(environment, unquotedUrl, file) || path.resolve(fileDir, unquotedUrl);
- return normalizePath(path.relative(rootDir, absolute));
- };
- if (hasImportCss) rebased = await rewriteImportCss(content, rebaseFn);
- if (hasUrls) rebased = await rewriteCssUrls(rebased || content, rebaseFn);
- if (hasDataUris) rebased = await rewriteCssDataUris(rebased || content, rebaseFn);
- return {
- file,
- contents: rebased
- };
-}
-const makeLessWorker = (environment, resolvers, maxWorkers) => {
- const skipRebaseUrls = (unquotedUrl, _rawUrl) => {
- return unquotedUrl[0] === "@";
- };
- const viteLessResolve = async (filename, dir, rootFile, mime) => {
- const resolved = await resolvers.less(environment, filename, path.join(dir, "*"));
- if (!resolved) return void 0;
- if (mime === "application/javascript") return { resolved: path.resolve(resolved) };
- const result = await rebaseUrls(environment, resolved, rootFile, resolvers.less, skipRebaseUrls);
- return {
- resolved,
- contents: "contents" in result ? result.contents : void 0
- };
- };
- return new WorkerWithFallback(async () => {
- const [fsp$1, path$13] = await Promise.all([import("node:fs/promises"), import("node:path")]);
- let ViteLessManager;
- const createViteLessPlugin = (less, rootFile) => {
- const { FileManager } = less;
- ViteLessManager ??= class ViteManager extends FileManager {
- rootFile;
- constructor(rootFile$1) {
- super();
- this.rootFile = rootFile$1;
- }
- supports(filename) {
- return !/^(?:https?:)?\/\//.test(filename);
- }
- supportsSync() {
- return false;
- }
- async loadFile(filename, dir, opts, env$1) {
- const result = await viteLessResolve(filename, dir, this.rootFile, opts.mime);
- if (result) return {
- filename: path$13.resolve(result.resolved),
- contents: result.contents ?? await fsp$1.readFile(result.resolved, "utf-8")
- };
- else return super.loadFile(filename, dir, opts, env$1);
- }
- };
- return {
- install(_, pluginManager) {
- pluginManager.addFileManager(new ViteLessManager(rootFile));
- },
- minVersion: [
- 3,
- 0,
- 0
- ]
- };
- };
- return async (lessPath, content, options$1) => {
- const nodeLess = (await import(lessPath)).default;
- const viteResolverPlugin = createViteLessPlugin(nodeLess, options$1.filename);
- return await nodeLess.render(content, {
- paths: ["node_modules"],
- ...options$1,
- plugins: [viteResolverPlugin, ...options$1.plugins || []],
- ...options$1.enableSourcemap ? { sourceMap: {
- outputSourceFiles: true,
- sourceMapFileInline: false
- } } : {}
- });
- };
- }, {
- parentFunctions: { viteLessResolve },
- shouldUseFake(_lessPath, _content, options$1) {
- return !!options$1.plugins && options$1.plugins.length > 0;
- },
- max: maxWorkers
- });
-};
-const lessProcessor = (maxWorkers) => {
- let worker;
- return {
- close() {
- worker?.stop();
- },
- async process(environment, source, root, options$1, resolvers) {
- const lessPath = loadPreprocessorPath(PreprocessLang.less, root);
- worker ??= makeLessWorker(environment, resolvers, maxWorkers);
- const { content, map: additionalMap } = await getSource(source, options$1.filename, options$1.additionalData, options$1.enableSourcemap);
- let result;
- const optionsWithoutAdditionalData = {
- ...options$1,
- additionalData: void 0
- };
- try {
- result = await worker.run(pathToFileURL(lessPath).href, content, optionsWithoutAdditionalData);
- } catch (e$1) {
- const error$1 = e$1;
- const normalizedError = /* @__PURE__ */ new Error(`[less] ${error$1.message || error$1.type}`);
- normalizedError.loc = {
- file: error$1.filename || options$1.filename,
- line: error$1.line,
- column: error$1.column
- };
- return {
- code: "",
- error: normalizedError,
- deps: []
- };
- }
- const map$1 = result.map && JSON.parse(result.map);
- if (map$1) delete map$1.sourcesContent;
- return {
- code: result.css.toString(),
- map: map$1,
- additionalMap,
- deps: result.imports
- };
- }
- };
-};
-const makeStylWorker = (maxWorkers) => {
- return new WorkerWithFallback(() => {
- return async (stylusPath, content, root, options$1) => {
- const stylus = (await import(stylusPath)).default;
- const ref = stylus(content, {
- paths: ["node_modules"],
- ...options$1
- });
- if (options$1.define) for (const key in options$1.define) ref.define(key, options$1.define[key]);
- if (options$1.enableSourcemap) ref.set("sourcemap", {
- comment: false,
- inline: false,
- basePath: root
- });
- return {
- code: ref.render(),
- map: ref.sourcemap,
- deps: ref.deps()
- };
- };
- }, {
- shouldUseFake(_stylusPath, _content, _root, options$1) {
- return !!(options$1.define && Object.values(options$1.define).some((d) => typeof d === "function"));
- },
- max: maxWorkers
- });
-};
-const stylProcessor = (maxWorkers) => {
- let worker;
- return {
- close() {
- worker?.stop();
- },
- async process(_environment, source, root, options$1, _resolvers) {
- const stylusPath = loadPreprocessorPath(PreprocessLang.stylus, root);
- worker ??= makeStylWorker(maxWorkers);
- const { content, map: additionalMap } = await getSource(source, options$1.filename, options$1.additionalData, options$1.enableSourcemap, "\n");
- const importsDeps = (options$1.imports ?? []).map((dep) => path.resolve(dep));
- const optionsWithoutAdditionalData = {
- ...options$1,
- additionalData: void 0
- };
- try {
- const { code, map: map$1, deps } = await worker.run(pathToFileURL(stylusPath).href, content, root, optionsWithoutAdditionalData);
- return {
- code,
- map: formatStylusSourceMap(map$1, root),
- additionalMap,
- deps: [...deps, ...importsDeps]
- };
- } catch (e$1) {
- const wrapped = /* @__PURE__ */ new Error(`[stylus] ${e$1.message}`);
- wrapped.name = e$1.name;
- wrapped.stack = e$1.stack;
- return {
- code: "",
- error: wrapped,
- deps: []
- };
- }
- }
- };
-};
-function formatStylusSourceMap(mapBefore, root) {
- if (!mapBefore) return void 0;
- const map$1 = { ...mapBefore };
- const resolveFromRoot = (p) => normalizePath(path.resolve(root, p));
- if (map$1.file) map$1.file = resolveFromRoot(map$1.file);
- map$1.sources = map$1.sources.map(resolveFromRoot);
- return map$1;
-}
-async function getSource(source, filename, additionalData, enableSourcemap, sep$3 = "") {
- if (!additionalData) return { content: source };
- if (typeof additionalData === "function") {
- const newContent = await additionalData(source, filename);
- if (typeof newContent === "string") return { content: newContent };
- return newContent;
- }
- if (!enableSourcemap) return { content: additionalData + sep$3 + source };
- const ms = new MagicString(source);
- ms.appendLeft(0, sep$3);
- ms.appendLeft(0, additionalData);
- const map$1 = ms.generateMap({ hires: "boundary" });
- map$1.file = filename;
- map$1.sources = [filename];
- return {
- content: ms.toString(),
- map: map$1
- };
-}
-const createPreprocessorWorkerController = (maxWorkers) => {
- const scss = scssProcessor(maxWorkers);
- const less = lessProcessor(maxWorkers);
- const styl = stylProcessor(maxWorkers);
- const sassProcess = (environment, source, root, options$1, resolvers) => {
- const opts = { ...options$1 };
- opts.syntax = "indented";
- return scss.process(environment, source, root, opts, resolvers);
- };
- const close$1 = () => {
- less.close();
- scss.close();
- styl.close();
- };
- return {
- [PreprocessLang.less]: less.process,
- [PreprocessLang.scss]: scss.process,
- [PreprocessLang.sass]: sassProcess,
- [PreprocessLang.styl]: styl.process,
- [PreprocessLang.stylus]: styl.process,
- close: close$1
- };
-};
-const normalizeMaxWorkers = (maxWorker) => {
- if (maxWorker === void 0) return 0;
- if (maxWorker === true) return void 0;
- return maxWorker;
-};
-const preprocessorSet = new Set([
- PreprocessLang.less,
- PreprocessLang.sass,
- PreprocessLang.scss,
- PreprocessLang.styl,
- PreprocessLang.stylus
-]);
-function isPreProcessor(lang) {
- return lang && preprocessorSet.has(lang);
-}
-const importLightningCSS = createCachedImport(() => import("lightningcss"));
-async function compileLightningCSS(environment, id, src, deps, workerController, urlResolver) {
- const { config: config$2 } = environment;
- const filename = removeDirectQuery(id).replace("\0", NULL_BYTE_PLACEHOLDER);
- let res;
- try {
- res = styleAttrRE.test(id) ? (await importLightningCSS()).transformStyleAttribute({
- filename,
- code: Buffer.from(src),
- targets: config$2.css.lightningcss?.targets,
- minify: config$2.isProduction && !!config$2.build.cssMinify,
- analyzeDependencies: true
- }) : await (await importLightningCSS()).bundleAsync({
- ...config$2.css.lightningcss,
- filename,
- projectRoot: config$2.root,
- resolver: {
- async read(filePath) {
- if (filePath === filename) return src;
- const code = fs.readFileSync(filePath, "utf-8");
- const lang = CSS_LANGS_RE.exec(filePath)?.[1];
- if (isPreProcessor(lang)) {
- const result = await compileCSSPreprocessors(environment, id, lang, code, workerController);
- result.deps?.forEach((dep) => deps.add(dep));
- return result.code;
- } else if (lang === "sss") return (await transformSugarSS(environment, id, code)).code;
- return code;
- },
- async resolve(id$1, from) {
- const publicFile = checkPublicFile(id$1, environment.getTopLevelConfig());
- if (publicFile) return publicFile;
- const atImportResolvers = getAtImportResolvers(environment.getTopLevelConfig());
- const lang = CSS_LANGS_RE.exec(from)?.[1];
- let resolver$1;
- switch (lang) {
- case "css":
- case "sss":
- case "styl":
- case "stylus":
- case void 0:
- resolver$1 = atImportResolvers.css;
- break;
- case "sass":
- case "scss":
- resolver$1 = atImportResolvers.sass;
- break;
- case "less":
- resolver$1 = atImportResolvers.less;
- break;
- default: throw new Error(`Unknown lang: ${lang}`);
- }
- const resolved = await resolver$1(environment, id$1, from);
- if (resolved) {
- deps.add(resolved);
- return resolved;
- }
- return id$1;
- }
- },
- minify: config$2.isProduction && !!config$2.build.cssMinify,
- sourceMap: config$2.command === "build" ? !!config$2.build.sourcemap : config$2.css.devSourcemap,
- analyzeDependencies: true,
- cssModules: cssModuleRE.test(id) ? config$2.css.lightningcss?.cssModules ?? true : void 0
- });
- } catch (e$1) {
- e$1.message = `[lightningcss] ${e$1.message}`;
- if (e$1.loc) {
- e$1.loc = {
- file: e$1.fileName.replace(NULL_BYTE_PLACEHOLDER, "\0"),
- line: e$1.loc.line,
- column: e$1.loc.column - 1
- };
- try {
- const friendlyMessage = getLightningCssErrorMessageForIeSyntaxes(fs.readFileSync(e$1.fileName, "utf-8"));
- if (friendlyMessage) e$1.message += friendlyMessage;
- } catch {}
- }
- throw e$1;
- }
- for (const warning of res.warnings) {
- let msg = `[vite:css][lightningcss] ${warning.message}`;
- msg += `\n${generateCodeFrame(src, {
- line: warning.loc.line,
- column: warning.loc.column - 1
- })}`;
- environment.logger.warn(import_picocolors$9.default.yellow(msg));
- }
- let css = decoder.decode(res.code);
- for (const dep of res.dependencies) switch (dep.type) {
- case "url": {
- let replaceUrl;
- if (skipUrlReplacer(dep.url)) replaceUrl = dep.url;
- else if (urlResolver) {
- const [newUrl, resolvedId] = await urlResolver(dep.url, dep.loc.filePath.replace(NULL_BYTE_PLACEHOLDER, "\0"));
- if (resolvedId) deps.add(resolvedId);
- replaceUrl = newUrl;
- } else replaceUrl = dep.url;
- css = css.replace(dep.placeholder, () => replaceUrl.replaceAll("\"", "\\\""));
- break;
- }
- default: throw new Error(`Unsupported dependency type: ${dep.type}`);
- }
- let modules;
- if ("exports" in res && res.exports) {
- modules = {};
- const sortedEntries = Object.entries(res.exports).sort((a, b) => a[0].localeCompare(b[0]));
- for (const [key, value$1] of sortedEntries) {
- modules[key] = value$1.name;
- for (const c of value$1.composes) modules[key] += " " + c.name;
- }
- }
- return {
- code: css,
- map: "map" in res ? res.map?.toString() : void 0,
- modules
- };
-}
-function getLightningCssErrorMessageForIeSyntaxes(code) {
- const commonIeMessage = ", which was used in the past to support old Internet Explorer versions. This is not a valid CSS syntax and will be ignored by modern browsers. \nWhile this is not supported by LightningCSS, you can set `css.lightningcss.errorRecovery: true` to strip these codes.";
- if (/[\s;{]\*[a-zA-Z-][\w-]+\s*:/.test(code)) return ".\nThis file contains star property hack (e.g. `*zoom`)" + commonIeMessage;
- if (/min-width:\s*0\\0/.test(code)) return ".\nThis file contains @media zero hack (e.g. `@media (min-width: 0\\0)`)" + commonIeMessage;
-}
-const map = {
- chrome: "chrome",
- edge: "edge",
- firefox: "firefox",
- hermes: false,
- ie: "ie",
- ios: "ios_saf",
- node: false,
- opera: "opera",
- rhino: false,
- safari: "safari"
-};
-const esMap = {
- 2015: [
- "chrome49",
- "edge13",
- "safari10",
- "firefox44",
- "opera36"
- ],
- 2016: [
- "chrome50",
- "edge13",
- "safari10",
- "firefox43",
- "opera37"
- ],
- 2017: [
- "chrome58",
- "edge15",
- "safari11",
- "firefox52",
- "opera45"
- ],
- 2018: [
- "chrome63",
- "edge79",
- "safari12",
- "firefox58",
- "opera50"
- ],
- 2019: [
- "chrome73",
- "edge79",
- "safari12.1",
- "firefox64",
- "opera60"
- ],
- 2020: [
- "chrome80",
- "edge80",
- "safari14.1",
- "firefox80",
- "opera67"
- ],
- 2021: [
- "chrome85",
- "edge85",
- "safari14.1",
- "firefox80",
- "opera71"
- ],
- 2022: [
- "chrome94",
- "edge94",
- "safari16.4",
- "firefox93",
- "opera80"
- ],
- 2023: [
- "chrome110",
- "edge110",
- "safari16.4",
- "opera96"
- ]
-};
-const esRE = /es(\d{4})/;
-const versionRE = /\d/;
-const convertTargetsCache = /* @__PURE__ */ new Map();
-const convertTargets = (esbuildTarget) => {
- if (!esbuildTarget) return {};
- const cached = convertTargetsCache.get(esbuildTarget);
- if (cached) return cached;
- const targets = {};
- const entriesWithoutES = arraify(esbuildTarget).flatMap((e$1) => {
- const match = esRE.exec(e$1);
- if (!match) return e$1;
- const year = Number(match[1]);
- if (!esMap[year]) throw new Error(`Unsupported target "${e$1}"`);
- return esMap[year];
- });
- for (const entry of entriesWithoutES) {
- if (entry === "esnext") continue;
- const index = entry.search(versionRE);
- if (index >= 0) {
- const browser = map[entry.slice(0, index)];
- if (browser === false) continue;
- if (browser) {
- const [major, minor = 0] = entry.slice(index).split(".").map((v) => parseInt(v, 10));
- if (!isNaN(major) && !isNaN(minor)) {
- const version$2 = major << 16 | minor << 8;
- if (!targets[browser] || version$2 < targets[browser]) targets[browser] = version$2;
- continue;
- }
- }
- }
- throw new Error(`Unsupported target "${entry}"`);
- }
- convertTargetsCache.set(esbuildTarget, targets);
- return targets;
-};
-function resolveLibCssFilename(libOptions, root, packageCache) {
- if (typeof libOptions.cssFileName === "string") return `${libOptions.cssFileName}.css`;
- else if (typeof libOptions.fileName === "string") return `${libOptions.fileName}.css`;
- const packageJson = findNearestMainPackageData(root, packageCache)?.data;
- const name = packageJson ? getPkgName(packageJson.name) : void 0;
- if (!name) throw new Error("Name in package.json is required if option \"build.lib.cssFileName\" is not provided.");
- return `${name}.css`;
-}
-
-//#endregion
-//#region src/node/optimizer/esbuildDepPlugin.ts
-const externalWithConversionNamespace = "vite:dep-pre-bundle:external-conversion";
-const convertedExternalPrefix = "vite-dep-pre-bundle-external:";
-const cjsExternalFacadeNamespace = "vite:cjs-external-facade";
-const nonFacadePrefix = "vite-cjs-external-facade:";
-const externalTypes = [
- "css",
- "less",
- "sass",
- "scss",
- "styl",
- "stylus",
- "pcss",
- "postcss",
- "wasm",
- "vue",
- "svelte",
- "marko",
- "astro",
- "imba",
- "jsx",
- "tsx",
- ...KNOWN_ASSET_TYPES
-];
-function esbuildDepPlugin(environment, qualified, external) {
- const { isProduction } = environment.config;
- const { extensions: extensions$1 } = environment.config.optimizeDeps;
- const allExternalTypes = extensions$1 ? externalTypes.filter((type) => !extensions$1.includes("." + type)) : externalTypes;
- const esmPackageCache = /* @__PURE__ */ new Map();
- const cjsPackageCache = /* @__PURE__ */ new Map();
- const _resolve = createBackCompatIdResolver(environment.getTopLevelConfig(), {
- asSrc: false,
- scan: true,
- packageCache: esmPackageCache
- });
- const _resolveRequire = createBackCompatIdResolver(environment.getTopLevelConfig(), {
- asSrc: false,
- isRequire: true,
- scan: true,
- packageCache: cjsPackageCache
- });
- const resolve$4 = (id, importer, kind, resolveDir) => {
- let _importer;
- if (resolveDir) _importer = normalizePath(path.join(resolveDir, "*"));
- else _importer = importer in qualified ? qualified[importer] : importer;
- return (kind.startsWith("require") ? _resolveRequire : _resolve)(environment, id, _importer);
- };
- const resolveResult = (id, resolved) => {
- if (resolved.startsWith(browserExternalId)) return {
- path: id,
- namespace: "browser-external"
- };
- if (resolved.startsWith(optionalPeerDepId)) return {
- path: resolved,
- namespace: "optional-peer-dep"
- };
- if (isBuiltin(environment.config.resolve.builtins, resolved)) return;
- if (isExternalUrl(resolved)) return {
- path: resolved,
- external: true
- };
- return { path: path.resolve(resolved) };
- };
- return {
- name: "vite:dep-pre-bundle",
- setup(build$3) {
- build$3.onEnd(() => {
- esmPackageCache.clear();
- cjsPackageCache.clear();
- });
- build$3.onResolve({ filter: /* @__PURE__ */ new RegExp(`\\.(` + allExternalTypes.join("|") + `)(\\?.*)?$`) }, async ({ path: id, importer, kind }) => {
- if (id.startsWith(convertedExternalPrefix)) return {
- path: id.slice(29),
- external: true
- };
- const resolved = await resolve$4(id, importer, kind);
- if (resolved) {
- if (JS_TYPES_RE.test(resolved)) return {
- path: resolved,
- external: false
- };
- if (kind === "require-call") return {
- path: resolved,
- namespace: externalWithConversionNamespace
- };
- return {
- path: resolved,
- external: true
- };
- }
- });
- build$3.onLoad({
- filter: /./,
- namespace: externalWithConversionNamespace
- }, (args) => {
- const modulePath = `"${convertedExternalPrefix}${args.path}"`;
- return {
- contents: isCSSRequest(args.path) && !isModuleCSSRequest(args.path) ? `import ${modulePath};` : `export { default } from ${modulePath};export * from ${modulePath};`,
- loader: "js"
- };
- });
- function resolveEntry(id) {
- const flatId = flattenId(id);
- if (flatId in qualified) return { path: qualified[flatId] };
- }
- build$3.onResolve({ filter: /^[\w@][^:]/ }, async ({ path: id, importer, kind }) => {
- if (moduleListContains(external, id)) return {
- path: id,
- external: true
- };
- let entry;
- if (!importer) {
- if (entry = resolveEntry(id)) return entry;
- const aliased = await _resolve(environment, id, void 0, true);
- if (aliased && (entry = resolveEntry(aliased))) return entry;
- }
- const resolved = await resolve$4(id, importer, kind);
- if (resolved) return resolveResult(id, resolved);
- });
- build$3.onLoad({
- filter: /.*/,
- namespace: "browser-external"
- }, ({ path: path$13 }) => {
- if (isProduction) return { contents: "module.exports = {}" };
- else return { contents: `\
-module.exports = Object.create(new Proxy({}, {
- get(_, key) {
- if (
- key !== '__esModule' &&
- key !== '__proto__' &&
- key !== 'constructor' &&
- key !== 'splice'
- ) {
- console.warn(\`Module "${path$13}" has been externalized for browser compatibility. Cannot access "${path$13}.\${key}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
- }
- }
-}))` };
- });
- build$3.onLoad({
- filter: /.*/,
- namespace: "optional-peer-dep"
- }, ({ path: path$13 }) => {
- const [, peerDep, parentDep] = path$13.split(":");
- return { contents: `module.exports = {};throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}".${isProduction ? "" : " Is it installed?"}\`)` };
- });
- }
- };
-}
-const matchesEntireLine = (text) => `^${escapeRegex(text)}$`;
-function esbuildCjsExternalPlugin(externals, platform$2) {
- return {
- name: "cjs-external",
- setup(build$3) {
- const filter$1 = new RegExp(externals.map(matchesEntireLine).join("|"));
- build$3.onResolve({ filter: /* @__PURE__ */ new RegExp(`^${nonFacadePrefix}`) }, (args) => {
- return {
- path: args.path.slice(25),
- external: true
- };
- });
- build$3.onResolve({ filter: filter$1 }, (args) => {
- if (args.kind === "require-call" && platform$2 !== "node") return {
- path: args.path,
- namespace: cjsExternalFacadeNamespace
- };
- return {
- path: args.path,
- external: true
- };
- });
- build$3.onLoad({
- filter: /.*/,
- namespace: cjsExternalFacadeNamespace
- }, (args) => ({ contents: `\
-import * as m from ${JSON.stringify(nonFacadePrefix + args.path)};
-module.exports = ${isNodeBuiltin(args.path) ? "m.default" : "{ ...m }"};
-` }));
- }
- };
-}
-
-//#endregion
-//#region src/node/optimizer/scan.ts
-var import_picocolors$8 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-var ScanEnvironment = class extends BaseEnvironment {
- mode = "scan";
- get pluginContainer() {
- if (!this._pluginContainer) throw new Error(`${this.name} environment.pluginContainer called before initialized`);
- return this._pluginContainer;
- }
- /**
- * @internal
- */
- _pluginContainer;
- async init() {
- if (this._initiated) return;
- this._initiated = true;
- this._pluginContainer = await createEnvironmentPluginContainer(this, this.plugins, void 0, false);
- }
-};
-function devToScanEnvironment(environment) {
- return {
- mode: "scan",
- get name() {
- return environment.name;
- },
- getTopLevelConfig() {
- return environment.getTopLevelConfig();
- },
- get config() {
- return environment.config;
- },
- get logger() {
- return environment.logger;
- },
- get pluginContainer() {
- return environment.pluginContainer;
- },
- get plugins() {
- return environment.plugins;
- }
- };
-}
-const debug$4 = createDebugger("vite:deps");
-const htmlTypesRE = /\.(html|vue|svelte|astro|imba)$/;
-const importsRE = /(?<!\/\/.*)(?<=^|;|\*\/)\s*import(?!\s+type)(?:[\w*{}\n\r\t, ]+from)?\s*("[^"]+"|'[^']+')\s*(?=$|;|\/\/|\/\*)/gm;
-function scanImports(environment) {
- const start = performance$1.now();
- const { config: config$2 } = environment;
- const scanContext = { cancelled: false };
- let esbuildContext;
- async function cancel() {
- scanContext.cancelled = true;
- return esbuildContext?.then((context) => context?.cancel());
- }
- async function scan() {
- const entries = await computeEntries(environment);
- if (!entries.length) {
- if (!config$2.optimizeDeps.entries && !config$2.optimizeDeps.include) environment.logger.warn(import_picocolors$8.default.yellow("(!) Could not auto-determine entry point from rollupOptions or html files and there are no explicit optimizeDeps.include patterns. Skipping dependency pre-bundling."));
- return;
- }
- if (scanContext.cancelled) return;
- debug$4?.(`Crawling dependencies using entries: ${entries.map((entry) => `\n ${import_picocolors$8.default.dim(entry)}`).join("")}`);
- const deps = {};
- const missing = {};
- let context;
- try {
- esbuildContext = prepareEsbuildScanner(environment, entries, deps, missing);
- context = await esbuildContext;
- if (scanContext.cancelled) return;
- try {
- await context.rebuild();
- return {
- deps: orderedDependencies(deps),
- missing
- };
- } catch (e$1) {
- if (e$1.errors && e$1.message.includes("The build was canceled")) return;
- const prependMessage = import_picocolors$8.default.red(`\
- Failed to scan for dependencies from entries:
- ${entries.join("\n")}
-
- `);
- if (e$1.errors) e$1.message = prependMessage + (await formatMessages(e$1.errors, {
- kind: "error",
- color: true
- })).join("\n");
- else e$1.message = prependMessage + e$1.message;
- throw e$1;
- } finally {
- if (debug$4) debug$4(`Scan completed in ${(performance$1.now() - start).toFixed(2)}ms: ${Object.keys(orderedDependencies(deps)).sort().map((id) => `\n ${import_picocolors$8.default.cyan(id)} -> ${import_picocolors$8.default.dim(deps[id])}`).join("") || import_picocolors$8.default.dim("no dependencies found")}`);
- }
- } finally {
- context?.dispose().catch((e$1) => {
- environment.logger.error("Failed to dispose esbuild context", { error: e$1 });
- });
- }
- }
- return {
- cancel,
- result: scan().then((res) => res ?? {
- deps: {},
- missing: {}
- })
- };
-}
-async function computeEntries(environment) {
- let entries = [];
- const explicitEntryPatterns = environment.config.optimizeDeps.entries;
- const buildInput = environment.config.build.rollupOptions.input;
- if (explicitEntryPatterns) entries = await globEntries(explicitEntryPatterns, environment);
- else if (buildInput) {
- const resolvePath = async (p) => {
- const id = (await environment.pluginContainer.resolveId(p, path.join(process.cwd(), "*"), {
- isEntry: true,
- scan: true
- }))?.id;
- if (id === void 0) throw new Error(`failed to resolve rollupOptions.input value: ${JSON.stringify(p)}.`);
- return id;
- };
- if (typeof buildInput === "string") entries = [await resolvePath(buildInput)];
- else if (Array.isArray(buildInput)) entries = await Promise.all(buildInput.map(resolvePath));
- else if (isObject(buildInput)) entries = await Promise.all(Object.values(buildInput).map(resolvePath));
- else throw new Error("invalid rollupOptions.input value.");
- } else entries = await globEntries("**/*.html", environment);
- entries = entries.filter((entry) => isScannable(entry, environment.config.optimizeDeps.extensions) && fs.existsSync(entry));
- return entries;
-}
-async function prepareEsbuildScanner(environment, entries, deps, missing) {
- const plugin = esbuildScanPlugin(environment, deps, missing, entries);
- const { plugins: plugins$1 = [], ...esbuildOptions } = environment.config.optimizeDeps.esbuildOptions ?? {};
- let tsconfigRaw = esbuildOptions.tsconfigRaw;
- if (!tsconfigRaw && !esbuildOptions.tsconfig) {
- const { tsconfig } = await loadTsconfigJsonForFile(path.join(environment.config.root, "_dummy.js"));
- if (tsconfig.compilerOptions?.experimentalDecorators || tsconfig.compilerOptions?.jsx || tsconfig.compilerOptions?.jsxFactory || tsconfig.compilerOptions?.jsxFragmentFactory || tsconfig.compilerOptions?.jsxImportSource) tsconfigRaw = { compilerOptions: {
- experimentalDecorators: tsconfig.compilerOptions?.experimentalDecorators,
- jsx: esbuildOptions.jsx ? void 0 : tsconfig.compilerOptions?.jsx,
- jsxFactory: esbuildOptions.jsxFactory ? void 0 : tsconfig.compilerOptions?.jsxFactory,
- jsxFragmentFactory: esbuildOptions.jsxFragment ? void 0 : tsconfig.compilerOptions?.jsxFragmentFactory,
- jsxImportSource: esbuildOptions.jsxImportSource ? void 0 : tsconfig.compilerOptions?.jsxImportSource
- } };
- }
- return await esbuild.context({
- absWorkingDir: process.cwd(),
- write: false,
- stdin: {
- contents: entries.map((e$1) => `import ${JSON.stringify(e$1)}`).join("\n"),
- loader: "js"
- },
- bundle: true,
- format: "esm",
- logLevel: "silent",
- plugins: [...plugins$1, plugin],
- jsxDev: !environment.config.isProduction,
- ...esbuildOptions,
- tsconfigRaw
- });
-}
-function orderedDependencies(deps) {
- const depsList = Object.entries(deps);
- depsList.sort((a, b) => a[0].localeCompare(b[0]));
- return Object.fromEntries(depsList);
-}
-async function globEntries(patterns, environment) {
- const nodeModulesPatterns = [];
- const regularPatterns = [];
- for (const pattern of arraify(patterns)) if (pattern.includes("node_modules")) nodeModulesPatterns.push(pattern);
- else regularPatterns.push(pattern);
- const sharedOptions = {
- absolute: true,
- cwd: environment.config.root,
- ignore: [`**/${environment.config.build.outDir}/**`, ...environment.config.optimizeDeps.entries ? [] : [`**/__tests__/**`, `**/coverage/**`]]
- };
- return (await Promise.all([glob(nodeModulesPatterns, sharedOptions), glob(regularPatterns, {
- ...sharedOptions,
- ignore: [...sharedOptions.ignore, "**/node_modules/**"]
- })])).flat();
-}
-const scriptRE = /(<script(?:\s+[a-z_:][-\w:]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^"'<>=\s]+))?)*\s*>)(.*?)<\/script>/gis;
-const commentRE = /<!--.*?-->/gs;
-const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
-const typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
-const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
-const svelteScriptModuleRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
-const svelteModuleRE = /\smodule\b/i;
-function esbuildScanPlugin(environment, depImports, missing, entries) {
- const seen$1 = /* @__PURE__ */ new Map();
- async function resolveId(id, importer) {
- return environment.pluginContainer.resolveId(id, importer && normalizePath(importer), { scan: true });
- }
- const resolve$4 = async (id, importer) => {
- const key = id + (importer && path.dirname(importer));
- if (seen$1.has(key)) return seen$1.get(key);
- const res = (await resolveId(id, importer))?.id;
- seen$1.set(key, res);
- return res;
- };
- const optimizeDepsOptions = environment.config.optimizeDeps;
- const include = optimizeDepsOptions.include;
- const exclude = [
- ...optimizeDepsOptions.exclude ?? [],
- "@vite/client",
- "@vite/env"
- ];
- const isUnlessEntry = (path$13) => !entries.includes(path$13);
- const externalUnlessEntry = ({ path: path$13 }) => ({
- path: path$13,
- external: isUnlessEntry(path$13)
- });
- const doTransformGlobImport = async (contents, id, loader$1) => {
- let transpiledContents;
- if (loader$1 !== "js") transpiledContents = (await transform(contents, { loader: loader$1 })).code;
- else transpiledContents = contents;
- return (await transformGlobImport(transpiledContents, id, environment.config.root, resolve$4))?.s.toString() || transpiledContents;
- };
- return {
- name: "vite:dep-scan",
- setup(build$3) {
- const scripts = {};
- build$3.onResolve({ filter: externalRE }, ({ path: path$13 }) => ({
- path: path$13,
- external: true
- }));
- build$3.onResolve({ filter: dataUrlRE }, ({ path: path$13 }) => ({
- path: path$13,
- external: true
- }));
- build$3.onResolve({ filter: virtualModuleRE }, ({ path: path$13 }) => {
- return {
- path: path$13.replace(virtualModulePrefix, ""),
- namespace: "script"
- };
- });
- build$3.onLoad({
- filter: /.*/,
- namespace: "script"
- }, ({ path: path$13 }) => {
- return scripts[path$13];
- });
- build$3.onResolve({ filter: htmlTypesRE }, async ({ path: path$13, importer }) => {
- const resolved = await resolve$4(path$13, importer);
- if (!resolved) return;
- if (isInNodeModules(resolved) && isOptimizable(resolved, optimizeDepsOptions)) return;
- if (shouldExternalizeDep(resolved, path$13)) return externalUnlessEntry({ path: path$13 });
- return {
- path: resolved,
- namespace: "html"
- };
- });
- const htmlTypeOnLoadCallback = async ({ path: p }) => {
- let raw = await fsp.readFile(p, "utf-8");
- raw = raw.replace(commentRE, "<!---->");
- const isHtml = p.endsWith(".html");
- let js = "";
- let scriptId = 0;
- const matches$2 = raw.matchAll(scriptRE);
- for (const [, openTag, content] of matches$2) {
- const typeMatch = typeRE.exec(openTag);
- const type = typeMatch && (typeMatch[1] || typeMatch[2] || typeMatch[3]);
- const langMatch = langRE.exec(openTag);
- const lang = langMatch && (langMatch[1] || langMatch[2] || langMatch[3]);
- if (isHtml && type !== "module") continue;
- if (type && !(type.includes("javascript") || type.includes("ecmascript") || type === "module")) continue;
- let loader$1 = "js";
- if (lang === "ts" || lang === "tsx" || lang === "jsx") loader$1 = lang;
- else if (p.endsWith(".astro")) loader$1 = "ts";
- const srcMatch = srcRE.exec(openTag);
- if (srcMatch) {
- const src = srcMatch[1] || srcMatch[2] || srcMatch[3];
- js += `import ${JSON.stringify(src)}\n`;
- } else if (content.trim()) {
- const contents = content + (loader$1.startsWith("ts") ? extractImportPaths(content) : "");
- const key = `${p}?id=${scriptId++}`;
- if (contents.includes("import.meta.glob")) scripts[key] = {
- loader: "js",
- contents: await doTransformGlobImport(contents, p, loader$1),
- resolveDir: normalizePath(path.dirname(p)),
- pluginData: { htmlType: { loader: loader$1 } }
- };
- else scripts[key] = {
- loader: loader$1,
- contents,
- resolveDir: normalizePath(path.dirname(p)),
- pluginData: { htmlType: { loader: loader$1 } }
- };
- const virtualModulePath = JSON.stringify(virtualModulePrefix + key);
- let addedImport = false;
- if (p.endsWith(".svelte")) {
- let isModule = svelteModuleRE.test(openTag);
- if (!isModule) {
- const contextMatch = svelteScriptModuleRE.exec(openTag);
- isModule = (contextMatch && (contextMatch[1] || contextMatch[2] || contextMatch[3])) === "module";
- }
- if (!isModule) {
- addedImport = true;
- js += `import ${virtualModulePath}\n`;
- }
- }
- if (!addedImport) js += `export * from ${virtualModulePath}\n`;
- }
- }
- if (!p.endsWith(".vue") || !js.includes("export default")) js += "\nexport default {}";
- return {
- loader: "js",
- contents: js
- };
- };
- build$3.onLoad({
- filter: htmlTypesRE,
- namespace: "html"
- }, htmlTypeOnLoadCallback);
- build$3.onLoad({
- filter: htmlTypesRE,
- namespace: "file"
- }, htmlTypeOnLoadCallback);
- build$3.onResolve({ filter: /^[\w@][^:]/ }, async ({ path: id, importer }) => {
- if (moduleListContains(exclude, id)) return externalUnlessEntry({ path: id });
- if (depImports[id]) return externalUnlessEntry({ path: id });
- const resolved = await resolve$4(id, importer);
- if (resolved) {
- if (shouldExternalizeDep(resolved, id)) return externalUnlessEntry({ path: id });
- if (isInNodeModules(resolved) || include?.includes(id)) {
- if (isOptimizable(resolved, optimizeDepsOptions)) depImports[id] = resolved;
- return externalUnlessEntry({ path: id });
- } else if (isScannable(resolved, optimizeDepsOptions.extensions)) {
- const namespace = htmlTypesRE.test(resolved) ? "html" : void 0;
- return {
- path: path.resolve(resolved),
- namespace
- };
- } else return externalUnlessEntry({ path: id });
- } else missing[id] = normalizePath(importer);
- });
- const setupExternalize = (filter$1, doExternalize) => {
- build$3.onResolve({ filter: filter$1 }, ({ path: path$13 }) => {
- return {
- path: path$13,
- external: doExternalize(path$13)
- };
- });
- };
- setupExternalize(CSS_LANGS_RE, isUnlessEntry);
- setupExternalize(/\.(json|json5|wasm)$/, isUnlessEntry);
- setupExternalize(/* @__PURE__ */ new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`), isUnlessEntry);
- setupExternalize(SPECIAL_QUERY_RE, () => true);
- build$3.onResolve({ filter: /.*/ }, async ({ path: id, importer }) => {
- const resolved = await resolve$4(id, importer);
- if (resolved) {
- if (shouldExternalizeDep(resolved, id) || !isScannable(resolved, optimizeDepsOptions.extensions)) return externalUnlessEntry({ path: id });
- const namespace = htmlTypesRE.test(resolved) ? "html" : void 0;
- return {
- path: path.resolve(cleanUrl(resolved)),
- namespace
- };
- } else return externalUnlessEntry({ path: id });
- });
- build$3.onLoad({ filter: JS_TYPES_RE }, async ({ path: id }) => {
- let ext = path.extname(id).slice(1);
- if (ext === "mjs") ext = "js";
- const esbuildConfig = environment.config.esbuild;
- let contents = await fsp.readFile(id, "utf-8");
- if (ext.endsWith("x") && esbuildConfig && esbuildConfig.jsxInject) contents = esbuildConfig.jsxInject + `\n` + contents;
- const loader$1 = optimizeDepsOptions.esbuildOptions?.loader?.[`.${ext}`] ?? ext;
- if (contents.includes("import.meta.glob")) return {
- loader: "js",
- contents: await doTransformGlobImport(contents, id, loader$1)
- };
- return {
- loader: loader$1,
- contents
- };
- });
- build$3.onLoad({
- filter: /.*/,
- namespace: "file"
- }, () => {
- return {
- loader: "js",
- contents: "export default {}"
- };
- });
- }
- };
-}
-/**
-* when using TS + (Vue + `<script setup>`) or Svelte, imports may seem
-* unused to esbuild and dropped in the build output, which prevents
-* esbuild from crawling further.
-* the solution is to add `import 'x'` for every source to force
-* esbuild to keep crawling due to potential side effects.
-*/
-function extractImportPaths(code) {
- code = code.replace(multilineCommentsRE, "/* */").replace(singlelineCommentsRE, "");
- let js = "";
- let m;
- importsRE.lastIndex = 0;
- while ((m = importsRE.exec(code)) != null) js += `\nimport ${m[1]}`;
- return js;
-}
-function shouldExternalizeDep(resolvedId, rawId) {
- if (!path.isAbsolute(resolvedId)) return true;
- if (resolvedId === rawId || resolvedId.includes("\0")) return true;
- return false;
-}
-function isScannable(id, extensions$1) {
- return JS_TYPES_RE.test(id) || htmlTypesRE.test(id) || extensions$1?.includes(path.extname(id)) || false;
-}
-
-//#endregion
-//#region src/node/optimizer/resolve.ts
-function createOptimizeDepsIncludeResolver(environment) {
- const topLevelConfig = environment.getTopLevelConfig();
- const resolve$4 = createBackCompatIdResolver(topLevelConfig, {
- asSrc: false,
- scan: true,
- packageCache: /* @__PURE__ */ new Map()
- });
- return async (id) => {
- const lastArrowIndex = id.lastIndexOf(">");
- if (lastArrowIndex === -1) return await resolve$4(environment, id, void 0);
- const nestedRoot = id.substring(0, lastArrowIndex).trim();
- const nestedPath = id.substring(lastArrowIndex + 1).trim();
- const basedir = nestedResolveBasedir(nestedRoot, topLevelConfig.root, topLevelConfig.resolve.preserveSymlinks);
- return await resolve$4(environment, nestedPath, path.resolve(basedir, "package.json"));
- };
-}
-/**
-* Expand the glob syntax in `optimizeDeps.include` to proper import paths
-*/
-function expandGlobIds(id, config$2) {
- const pkgName = getNpmPackageName(id);
- if (!pkgName) return [];
- const pkgData = resolvePackageData(pkgName, config$2.root, config$2.resolve.preserveSymlinks, config$2.packageCache);
- if (!pkgData) return [];
- const pattern = "." + id.slice(pkgName.length);
- const exports$1 = pkgData.data.exports;
- if (exports$1) {
- if (typeof exports$1 === "string" || Array.isArray(exports$1)) return [pkgName];
- const possibleExportPaths = [];
- for (const key in exports$1) if (key[0] === ".") if (key.includes("*")) {
- const exportsValue = getFirstExportStringValue(exports$1[key]);
- if (!exportsValue) continue;
- const exportValuePattern = exportsValue.replace(/\*/g, "**/*");
- const exportsValueGlobRe = new RegExp(exportsValue.split("*").map(escapeRegex).join("(.*)"));
- possibleExportPaths.push(...globSync(exportValuePattern, {
- cwd: pkgData.dir,
- expandDirectories: false,
- ignore: ["node_modules"]
- }).map((filePath) => {
- if (exportsValue.startsWith("./")) filePath = "./" + filePath;
- const matched$1 = exportsValueGlobRe.exec(slash(filePath));
- if (matched$1) {
- let allGlobSame = matched$1.length === 2;
- if (!allGlobSame) {
- allGlobSame = true;
- for (let i$1 = 2; i$1 < matched$1.length; i$1++) if (matched$1[i$1] !== matched$1[i$1 - 1]) {
- allGlobSame = false;
- break;
- }
- }
- if (allGlobSame) return key.replace("*", matched$1[1]).slice(2);
- }
- return "";
- }).filter(Boolean));
- } else possibleExportPaths.push(key.slice(2));
- const isMatch$1 = picomatch(pattern);
- const matched = possibleExportPaths.filter((p) => isMatch$1(p)).map((match) => path.posix.join(pkgName, match));
- matched.unshift(pkgName);
- return matched;
- } else {
- const matched = globSync(pattern, {
- cwd: pkgData.dir,
- expandDirectories: false,
- ignore: ["node_modules"]
- }).map((match) => path.posix.join(pkgName, slash(match)));
- matched.unshift(pkgName);
- return matched;
- }
-}
-function getFirstExportStringValue(obj) {
- if (typeof obj === "string") return obj;
- else if (Array.isArray(obj)) return obj[0];
- else for (const key in obj) return getFirstExportStringValue(obj[key]);
-}
-/**
-* Continuously resolve the basedir of packages separated by '>'
-*/
-function nestedResolveBasedir(id, basedir, preserveSymlinks = false) {
- const pkgs = id.split(">").map((pkg) => pkg.trim());
- for (const pkg of pkgs) basedir = resolvePackageData(pkg, basedir, preserveSymlinks)?.dir || basedir;
- return basedir;
-}
-
-//#endregion
-//#region src/node/optimizer/index.ts
-var import_picocolors$7 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const debug$3 = createDebugger("vite:deps");
-const jsExtensionRE = /\.js$/i;
-const jsMapExtensionRE = /\.js\.map$/i;
-function isDepOptimizationDisabled(optimizeDeps$1) {
- return optimizeDeps$1.disabled === true || optimizeDeps$1.disabled === "dev" || !!optimizeDeps$1.noDiscovery && !optimizeDeps$1.include?.length;
-}
-/**
-* Scan and optimize dependencies within a project.
-* Used by Vite CLI when running `vite optimize`.
-*
-* @deprecated the optimization process runs automatically and does not need to be called
-*/
-async function optimizeDeps(config$2, force = config$2.optimizeDeps.force, asCommand = false) {
- const log$3 = asCommand ? config$2.logger.info : debug$3;
- config$2.logger.warn(import_picocolors$7.default.yellow("manually calling optimizeDeps is deprecated. This is done automatically and does not need to be called manually."));
- const environment = new ScanEnvironment("client", config$2);
- await environment.init();
- const cachedMetadata = await loadCachedDepOptimizationMetadata(environment, force, asCommand);
- if (cachedMetadata) return cachedMetadata;
- const deps = await discoverProjectDependencies(environment).result;
- await addManuallyIncludedOptimizeDeps(environment, deps);
- const depsString = depsLogString(Object.keys(deps));
- log$3?.(import_picocolors$7.default.green(`Optimizing dependencies:\n ${depsString}`));
- const result = await runOptimizeDeps(environment, toDiscoveredDependencies(environment, deps)).result;
- await result.commit();
- return result.metadata;
-}
-async function optimizeExplicitEnvironmentDeps(environment) {
- const cachedMetadata = await loadCachedDepOptimizationMetadata(environment, environment.config.optimizeDeps.force ?? false, false);
- if (cachedMetadata) return cachedMetadata;
- const deps = {};
- await addManuallyIncludedOptimizeDeps(environment, deps);
- const result = await runOptimizeDeps(environment, toDiscoveredDependencies(environment, deps)).result;
- await result.commit();
- return result.metadata;
-}
-function initDepsOptimizerMetadata(environment, timestamp) {
- const { lockfileHash, configHash, hash: hash$1 } = getDepHash(environment);
- return {
- hash: hash$1,
- lockfileHash,
- configHash,
- browserHash: getOptimizedBrowserHash(hash$1, {}, timestamp),
- optimized: {},
- chunks: {},
- discovered: {},
- depInfoList: []
- };
-}
-function addOptimizedDepInfo(metadata, type, depInfo) {
- metadata[type][depInfo.id] = depInfo;
- metadata.depInfoList.push(depInfo);
- return depInfo;
-}
-let firstLoadCachedDepOptimizationMetadata = true;
-/**
-* Creates the initial dep optimization metadata, loading it from the deps cache
-* if it exists and pre-bundling isn't forced
-*/
-async function loadCachedDepOptimizationMetadata(environment, force = environment.config.optimizeDeps.force ?? false, asCommand = false) {
- const log$3 = asCommand ? environment.logger.info : debug$3;
- if (firstLoadCachedDepOptimizationMetadata) {
- firstLoadCachedDepOptimizationMetadata = false;
- setTimeout(() => cleanupDepsCacheStaleDirs(environment.getTopLevelConfig()), 0);
- }
- const depsCacheDir = getDepsCacheDir(environment);
- if (!force) {
- let cachedMetadata;
- try {
- const cachedMetadataPath = path.join(depsCacheDir, METADATA_FILENAME);
- cachedMetadata = parseDepsOptimizerMetadata(await fsp.readFile(cachedMetadataPath, "utf-8"), depsCacheDir);
- } catch {}
- if (cachedMetadata) if (cachedMetadata.lockfileHash !== getLockfileHash(environment)) environment.logger.info("Re-optimizing dependencies because lockfile has changed", { timestamp: true });
- else if (cachedMetadata.configHash !== getConfigHash(environment)) environment.logger.info("Re-optimizing dependencies because vite config has changed", { timestamp: true });
- else {
- log$3?.(`(${environment.name}) Hash is consistent. Skipping. Use --force to override.`);
- return cachedMetadata;
- }
- } else environment.logger.info("Forced re-optimization of dependencies", { timestamp: true });
- debug$3?.(`(${environment.name}) ${import_picocolors$7.default.green(`removing old cache dir ${depsCacheDir}`)}`);
- await fsp.rm(depsCacheDir, {
- recursive: true,
- force: true
- });
-}
-/**
-* Initial optimizeDeps at server start. Perform a fast scan using esbuild to
-* find deps to pre-bundle and include user hard-coded dependencies
-*/
-function discoverProjectDependencies(environment) {
- const { cancel, result } = scanImports(environment);
- return {
- cancel,
- result: result.then(({ deps, missing }) => {
- const missingIds = Object.keys(missing);
- if (missingIds.length) throw new Error(`The following dependencies are imported but could not be resolved:\n\n ${missingIds.map((id) => `${import_picocolors$7.default.cyan(id)} ${import_picocolors$7.default.white(import_picocolors$7.default.dim(`(imported by ${missing[id]})`))}`).join(`\n `)}\n\nAre they installed?`);
- return deps;
- })
- };
-}
-function toDiscoveredDependencies(environment, deps, timestamp) {
- const browserHash = getOptimizedBrowserHash(getDepHash(environment).hash, deps, timestamp);
- const discovered = {};
- for (const id in deps) {
- const src = deps[id];
- discovered[id] = {
- id,
- file: getOptimizedDepPath(environment, id),
- src,
- browserHash,
- exportsData: extractExportsData(environment, src)
- };
- }
- return discovered;
-}
-function depsLogString(qualifiedIds) {
- return import_picocolors$7.default.yellow(qualifiedIds.join(`, `));
-}
-/**
-* Internally, Vite uses this function to prepare a optimizeDeps run. When Vite starts, we can get
-* the metadata and start the server without waiting for the optimizeDeps processing to be completed
-*/
-function runOptimizeDeps(environment, depsInfo) {
- const optimizerContext = { cancelled: false };
- const depsCacheDir = getDepsCacheDir(environment);
- const processingCacheDir = getProcessingDepsCacheDir(environment);
- fs.mkdirSync(processingCacheDir, { recursive: true });
- debug$3?.(import_picocolors$7.default.green(`creating package.json in ${processingCacheDir}`));
- fs.writeFileSync(path.resolve(processingCacheDir, "package.json"), `{\n "type": "module"\n}\n`);
- const metadata = initDepsOptimizerMetadata(environment);
- metadata.browserHash = getOptimizedBrowserHash(metadata.hash, depsFromOptimizedDepInfo(depsInfo));
- const qualifiedIds = Object.keys(depsInfo);
- let cleaned = false;
- let committed = false;
- const cleanUp = () => {
- if (!cleaned && !committed) {
- cleaned = true;
- debug$3?.(import_picocolors$7.default.green(`removing cache dir ${processingCacheDir}`));
- try {
- fs.rmSync(processingCacheDir, {
- recursive: true,
- force: true
- });
- } catch {}
- }
- };
- const successfulResult = {
- metadata,
- cancel: cleanUp,
- commit: async () => {
- if (cleaned) throw new Error("Can not commit a Deps Optimization run as it was cancelled");
- committed = true;
- const dataPath = path.join(processingCacheDir, METADATA_FILENAME);
- debug$3?.(import_picocolors$7.default.green(`creating ${METADATA_FILENAME} in ${processingCacheDir}`));
- fs.writeFileSync(dataPath, stringifyDepsOptimizerMetadata(metadata, depsCacheDir));
- const temporaryPath = depsCacheDir + getTempSuffix();
- const depsCacheDirPresent = fs.existsSync(depsCacheDir);
- if (isWindows) {
- if (depsCacheDirPresent) {
- debug$3?.(import_picocolors$7.default.green(`renaming ${depsCacheDir} to ${temporaryPath}`));
- await safeRename(depsCacheDir, temporaryPath);
- }
- debug$3?.(import_picocolors$7.default.green(`renaming ${processingCacheDir} to ${depsCacheDir}`));
- await safeRename(processingCacheDir, depsCacheDir);
- } else {
- if (depsCacheDirPresent) {
- debug$3?.(import_picocolors$7.default.green(`renaming ${depsCacheDir} to ${temporaryPath}`));
- fs.renameSync(depsCacheDir, temporaryPath);
- }
- debug$3?.(import_picocolors$7.default.green(`renaming ${processingCacheDir} to ${depsCacheDir}`));
- fs.renameSync(processingCacheDir, depsCacheDir);
- }
- if (depsCacheDirPresent) {
- debug$3?.(import_picocolors$7.default.green(`removing cache temp dir ${temporaryPath}`));
- fsp.rm(temporaryPath, {
- recursive: true,
- force: true
- });
- }
- }
- };
- if (!qualifiedIds.length) return {
- cancel: async () => cleanUp(),
- result: Promise.resolve(successfulResult)
- };
- const cancelledResult = {
- metadata,
- commit: async () => cleanUp(),
- cancel: cleanUp
- };
- const start = performance$1.now();
- const preparedRun = prepareEsbuildOptimizerRun(environment, depsInfo, processingCacheDir, optimizerContext);
- const runResult = preparedRun.then(({ context, idToExports }) => {
- function disposeContext() {
- return context?.dispose().catch((e$1) => {
- environment.logger.error("Failed to dispose esbuild context", { error: e$1 });
- });
- }
- if (!context || optimizerContext.cancelled) {
- disposeContext();
- return cancelledResult;
- }
- return context.rebuild().then((result) => {
- const meta = result.metafile;
- const processingCacheDirOutputPath = path.relative(process.cwd(), processingCacheDir);
- for (const id in depsInfo) {
- const output = esbuildOutputFromId(meta.outputs, id, processingCacheDir);
- const { exportsData, ...info } = depsInfo[id];
- addOptimizedDepInfo(metadata, "optimized", {
- ...info,
- fileHash: getHash(metadata.hash + depsInfo[id].file + JSON.stringify(output.imports)),
- browserHash: metadata.browserHash,
- needsInterop: needsInterop(environment, id, idToExports[id], output)
- });
- }
- for (const o$1 of Object.keys(meta.outputs)) if (!jsMapExtensionRE.test(o$1)) {
- const id = path.relative(processingCacheDirOutputPath, o$1).replace(jsExtensionRE, "");
- const file = getOptimizedDepPath(environment, id);
- if (!findOptimizedDepInfoInRecord(metadata.optimized, (depInfo) => depInfo.file === file)) addOptimizedDepInfo(metadata, "chunks", {
- id,
- file,
- needsInterop: false,
- browserHash: metadata.browserHash
- });
- } else if (meta.outputs[o$1].bytes === 93) {
- const jsMapPath = path.resolve(o$1);
- const jsPath = jsMapPath.slice(0, -4);
- if (fs.existsSync(jsPath) && fs.existsSync(jsMapPath)) {
- if (JSON.parse(fs.readFileSync(jsMapPath, "utf-8")).sources.length === 0) {
- const js = fs.readFileSync(jsPath, "utf-8");
- fs.writeFileSync(jsPath, js.slice(0, js.lastIndexOf("//# sourceMappingURL=")));
- }
- }
- }
- debug$3?.(`Dependencies bundled in ${(performance$1.now() - start).toFixed(2)}ms`);
- return successfulResult;
- }).catch(async (e$1) => {
- if (e$1.errors && e$1.message.includes("The build was canceled")) return cancelledResult;
- const prependMessage = import_picocolors$7.default.red("Error during dependency optimization:\n\n");
- if (e$1.errors) e$1.message = prependMessage + (await formatMessages(e$1.errors, {
- kind: "error",
- color: true
- })).join("\n");
- else e$1.message = prependMessage + e$1.message;
- throw e$1;
- }).finally(() => {
- return disposeContext();
- });
- });
- runResult.catch(() => {
- cleanUp();
- });
- return {
- async cancel() {
- optimizerContext.cancelled = true;
- const { context } = await preparedRun;
- await context?.cancel();
- cleanUp();
- },
- result: runResult
- };
-}
-async function prepareEsbuildOptimizerRun(environment, depsInfo, processingCacheDir, optimizerContext) {
- const flatIdDeps = {};
- const idToExports = {};
- const { optimizeDeps: optimizeDeps$1 } = environment.config;
- const { plugins: pluginsFromConfig = [], ...esbuildOptions } = optimizeDeps$1.esbuildOptions ?? {};
- await Promise.all(Object.keys(depsInfo).map(async (id) => {
- const src = depsInfo[id].src;
- const exportsData = await (depsInfo[id].exportsData ?? extractExportsData(environment, src));
- if (exportsData.jsxLoader && !esbuildOptions.loader?.[".js"]) esbuildOptions.loader = {
- ".js": "jsx",
- ...esbuildOptions.loader
- };
- const flatId = flattenId(id);
- flatIdDeps[flatId] = src;
- idToExports[id] = exportsData;
- }));
- if (optimizerContext.cancelled) return {
- context: void 0,
- idToExports
- };
- const define$1 = { "process.env.NODE_ENV": environment.config.keepProcessEnv ? "process.env.NODE_ENV" : JSON.stringify(process.env.NODE_ENV || environment.config.mode) };
- const platform$2 = optimizeDeps$1.esbuildOptions?.platform ?? (environment.config.consumer === "client" || environment.config.ssr.target === "webworker" ? "browser" : "node");
- const external = [...optimizeDeps$1.exclude ?? []];
- const plugins$1 = [...pluginsFromConfig];
- if (external.length) plugins$1.push(esbuildCjsExternalPlugin(external, platform$2));
- plugins$1.push(esbuildDepPlugin(environment, flatIdDeps, external));
- return {
- context: await esbuild.context({
- absWorkingDir: process.cwd(),
- entryPoints: Object.keys(flatIdDeps),
- bundle: true,
- platform: platform$2,
- define: define$1,
- format: "esm",
- banner: platform$2 === "node" ? { js: `import { createRequire } from 'module';const require = createRequire(import.meta.url);` } : void 0,
- target: ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET,
- external,
- logLevel: "error",
- splitting: true,
- sourcemap: true,
- outdir: processingCacheDir,
- ignoreAnnotations: true,
- metafile: true,
- plugins: plugins$1,
- charset: "utf8",
- legalComments: "none",
- ...esbuildOptions,
- supported: {
- ...defaultEsbuildSupported,
- ...esbuildOptions.supported
- }
- }),
- idToExports
- };
-}
-async function addManuallyIncludedOptimizeDeps(environment, deps) {
- const { logger } = environment;
- const { optimizeDeps: optimizeDeps$1 } = environment.config;
- const optimizeDepsInclude = optimizeDeps$1.include ?? [];
- if (optimizeDepsInclude.length) {
- const unableToOptimize = (id, msg) => {
- if (optimizeDepsInclude.includes(id)) logger.warn(`${msg}: ${import_picocolors$7.default.cyan(id)}, present in ${environment.name} 'optimizeDeps.include'`);
- };
- const includes = [...optimizeDepsInclude];
- for (let i$1 = 0; i$1 < includes.length; i$1++) {
- const id = includes[i$1];
- if (isDynamicPattern(id)) {
- const globIds = expandGlobIds(id, environment.getTopLevelConfig());
- includes.splice(i$1, 1, ...globIds);
- i$1 += globIds.length - 1;
- }
- }
- const resolve$4 = createOptimizeDepsIncludeResolver(environment);
- for (const id of includes) {
- const normalizedId = normalizeId(id);
- if (!deps[normalizedId]) {
- const entry = await resolve$4(id);
- if (entry) if (isOptimizable(entry, optimizeDeps$1)) deps[normalizedId] = entry;
- else unableToOptimize(id, "Cannot optimize dependency");
- else unableToOptimize(id, "Failed to resolve dependency");
- }
- }
- }
-}
-function depsFromOptimizedDepInfo(depsInfo) {
- const obj = {};
- for (const key in depsInfo) obj[key] = depsInfo[key].src;
- return obj;
-}
-function getOptimizedDepPath(environment, id) {
- return normalizePath(path.resolve(getDepsCacheDir(environment), flattenId(id) + ".js"));
-}
-function getDepsCacheSuffix(environment) {
- return environment.name === "client" ? "" : `_${environment.name}`;
-}
-function getDepsCacheDir(environment) {
- return getDepsCacheDirPrefix(environment) + getDepsCacheSuffix(environment);
-}
-function getProcessingDepsCacheDir(environment) {
- return getDepsCacheDirPrefix(environment) + getDepsCacheSuffix(environment) + getTempSuffix();
-}
-function getTempSuffix() {
- return "_temp_" + getHash(`${process.pid}:${Date.now().toString()}:${Math.random().toString(16).slice(2)}`);
-}
-function getDepsCacheDirPrefix(environment) {
- return normalizePath(path.resolve(environment.config.cacheDir, "deps"));
-}
-function createIsOptimizedDepFile(environment) {
- const depsCacheDirPrefix = getDepsCacheDirPrefix(environment);
- return (id) => id.startsWith(depsCacheDirPrefix);
-}
-function createIsOptimizedDepUrl(environment) {
- const { root } = environment.config;
- const depsCacheDir = getDepsCacheDirPrefix(environment);
- const depsCacheDirRelative = normalizePath(path.relative(root, depsCacheDir));
- const depsCacheDirPrefix = depsCacheDirRelative.startsWith("../") ? `/@fs/${removeLeadingSlash(normalizePath(depsCacheDir))}` : `/${depsCacheDirRelative}`;
- return function isOptimizedDepUrl(url$3) {
- return url$3.startsWith(depsCacheDirPrefix);
- };
-}
-function parseDepsOptimizerMetadata(jsonMetadata, depsCacheDir) {
- const { hash: hash$1, lockfileHash, configHash, browserHash, optimized, chunks } = JSON.parse(jsonMetadata, (key, value$1) => {
- if (key === "file" || key === "src") return normalizePath(path.resolve(depsCacheDir, value$1));
- return value$1;
- });
- if (!chunks || Object.values(optimized).some((depInfo) => !depInfo.fileHash)) return;
- const metadata = {
- hash: hash$1,
- lockfileHash,
- configHash,
- browserHash,
- optimized: {},
- discovered: {},
- chunks: {},
- depInfoList: []
- };
- for (const id of Object.keys(optimized)) addOptimizedDepInfo(metadata, "optimized", {
- ...optimized[id],
- id,
- browserHash
- });
- for (const id of Object.keys(chunks)) addOptimizedDepInfo(metadata, "chunks", {
- ...chunks[id],
- id,
- browserHash,
- needsInterop: false
- });
- return metadata;
-}
-/**
-* Stringify metadata for deps cache. Remove processing promises
-* and individual dep info browserHash. Once the cache is reload
-* the next time the server start we need to use the global
-* browserHash to allow long term caching
-*/
-function stringifyDepsOptimizerMetadata(metadata, depsCacheDir) {
- const { hash: hash$1, configHash, lockfileHash, browserHash, optimized, chunks } = metadata;
- return JSON.stringify({
- hash: hash$1,
- configHash,
- lockfileHash,
- browserHash,
- optimized: Object.fromEntries(Object.values(optimized).map(({ id, src, file, fileHash, needsInterop: needsInterop$1 }) => [id, {
- src,
- file,
- fileHash,
- needsInterop: needsInterop$1
- }])),
- chunks: Object.fromEntries(Object.values(chunks).map(({ id, file }) => [id, { file }]))
- }, (key, value$1) => {
- if (key === "file" || key === "src") return normalizePath(path.relative(depsCacheDir, value$1));
- return value$1;
- }, 2);
-}
-function esbuildOutputFromId(outputs, id, cacheDirOutputPath) {
- const cwd = process.cwd();
- const flatId = flattenId(id) + ".js";
- const normalizedOutputPath = normalizePath(path.relative(cwd, path.join(cacheDirOutputPath, flatId)));
- const output = outputs[normalizedOutputPath];
- if (output) return output;
- for (const [key, value$1] of Object.entries(outputs)) if (normalizePath(path.relative(cwd, key)) === normalizedOutputPath) return value$1;
-}
-async function extractExportsData(environment, filePath) {
- await init;
- const { optimizeDeps: optimizeDeps$1 } = environment.config;
- const esbuildOptions = optimizeDeps$1.esbuildOptions ?? {};
- if (optimizeDeps$1.extensions?.some((ext) => filePath.endsWith(ext))) {
- const [, exports$2, , hasModuleSyntax$1] = parse((await build({
- ...esbuildOptions,
- entryPoints: [filePath],
- write: false,
- format: "esm"
- })).outputFiles[0].text);
- return {
- hasModuleSyntax: hasModuleSyntax$1,
- exports: exports$2.map((e$1) => e$1.n)
- };
- }
- let parseResult;
- let usedJsxLoader = false;
- const entryContent = await fsp.readFile(filePath, "utf-8");
- try {
- parseResult = parse(entryContent);
- } catch {
- const loader$1 = esbuildOptions.loader?.[path.extname(filePath)] || "jsx";
- debug$3?.(`Unable to parse: ${filePath}.\n Trying again with a ${loader$1} transform.`);
- parseResult = parse((await transformWithEsbuild(entryContent, filePath, { loader: loader$1 }, void 0, environment.config)).code);
- usedJsxLoader = true;
- }
- const [, exports$1, , hasModuleSyntax] = parseResult;
- return {
- hasModuleSyntax,
- exports: exports$1.map((e$1) => e$1.n),
- jsxLoader: usedJsxLoader
- };
-}
-function needsInterop(environment, id, exportsData, output) {
- if (environment.config.optimizeDeps.needsInterop?.includes(id)) return true;
- const { hasModuleSyntax, exports: exports$1 } = exportsData;
- if (!hasModuleSyntax) return true;
- if (output) {
- const generatedExports = output.exports;
- if (isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports$1)) return true;
- }
- return false;
-}
-function isSingleDefaultExport(exports$1) {
- return exports$1.length === 1 && exports$1[0] === "default";
-}
-const lockfileFormats = [
- {
- path: "node_modules/.package-lock.json",
- checkPatchesDir: "patches",
- manager: "npm"
- },
- {
- path: "node_modules/.yarn-state.yml",
- checkPatchesDir: false,
- manager: "yarn"
- },
- {
- path: ".pnp.cjs",
- checkPatchesDir: ".yarn/patches",
- manager: "yarn"
- },
- {
- path: ".pnp.js",
- checkPatchesDir: ".yarn/patches",
- manager: "yarn"
- },
- {
- path: "node_modules/.yarn-integrity",
- checkPatchesDir: "patches",
- manager: "yarn"
- },
- {
- path: "node_modules/.pnpm/lock.yaml",
- checkPatchesDir: false,
- manager: "pnpm"
- },
- {
- path: ".rush/temp/shrinkwrap-deps.json",
- checkPatchesDir: false,
- manager: "pnpm"
- },
- {
- path: "bun.lock",
- checkPatchesDir: "patches",
- manager: "bun"
- },
- {
- path: "bun.lockb",
- checkPatchesDir: "patches",
- manager: "bun"
- }
-].sort((_, { manager }) => {
- return process.env.npm_config_user_agent?.startsWith(manager) ? 1 : -1;
-});
-const lockfilePaths = lockfileFormats.map((l) => l.path);
-function getConfigHash(environment) {
- const { config: config$2 } = environment;
- const { optimizeDeps: optimizeDeps$1 } = config$2;
- return getHash(JSON.stringify({
- define: !config$2.keepProcessEnv ? process.env.NODE_ENV || config$2.mode : null,
- root: config$2.root,
- resolve: config$2.resolve,
- assetsInclude: config$2.assetsInclude,
- plugins: config$2.plugins.map((p) => p.name),
- optimizeDeps: {
- include: optimizeDeps$1.include ? unique(optimizeDeps$1.include).sort() : void 0,
- exclude: optimizeDeps$1.exclude ? unique(optimizeDeps$1.exclude).sort() : void 0,
- esbuildOptions: {
- ...optimizeDeps$1.esbuildOptions,
- plugins: optimizeDeps$1.esbuildOptions?.plugins?.map((p) => p.name)
- }
- }
- }, (_, value$1) => {
- if (typeof value$1 === "function" || value$1 instanceof RegExp) return value$1.toString();
- return value$1;
- }));
-}
-function getLockfileHash(environment) {
- const lockfilePath = lookupFile(environment.config.root, lockfilePaths);
- let content = lockfilePath ? fs.readFileSync(lockfilePath, "utf-8") : "";
- if (lockfilePath) {
- const normalizedLockfilePath = lockfilePath.replaceAll("\\", "/");
- const lockfileFormat = lockfileFormats.find((f$1) => normalizedLockfilePath.endsWith(f$1.path));
- if (lockfileFormat.checkPatchesDir) {
- const baseDir = lockfilePath.slice(0, -lockfileFormat.path.length);
- const stat$4 = tryStatSync(path.join(baseDir, lockfileFormat.checkPatchesDir));
- if (stat$4?.isDirectory()) content += stat$4.mtimeMs.toString();
- }
- }
- return getHash(content);
-}
-function getDepHash(environment) {
- const lockfileHash = getLockfileHash(environment);
- const configHash = getConfigHash(environment);
- return {
- hash: getHash(lockfileHash + configHash),
- lockfileHash,
- configHash
- };
-}
-function getOptimizedBrowserHash(hash$1, deps, timestamp = "") {
- return getHash(hash$1 + JSON.stringify(deps) + timestamp);
-}
-function optimizedDepInfoFromId(metadata, id) {
- return metadata.optimized[id] || metadata.discovered[id] || metadata.chunks[id];
-}
-function optimizedDepInfoFromFile(metadata, file) {
- return metadata.depInfoList.find((depInfo) => depInfo.file === file);
-}
-function findOptimizedDepInfoInRecord(dependenciesInfo, callbackFn) {
- for (const o$1 of Object.keys(dependenciesInfo)) {
- const info = dependenciesInfo[o$1];
- if (callbackFn(info, o$1)) return info;
- }
-}
-async function optimizedDepNeedsInterop(environment, metadata, file) {
- const depInfo = optimizedDepInfoFromFile(metadata, file);
- if (depInfo?.src && depInfo.needsInterop === void 0) {
- depInfo.exportsData ??= extractExportsData(environment, depInfo.src);
- depInfo.needsInterop = needsInterop(environment, depInfo.id, await depInfo.exportsData);
- }
- return depInfo?.needsInterop;
-}
-const MAX_TEMP_DIR_AGE_MS = 1440 * 60 * 1e3;
-async function cleanupDepsCacheStaleDirs(config$2) {
- try {
- const cacheDir = path.resolve(config$2.cacheDir);
- if (fs.existsSync(cacheDir)) {
- const dirents = await fsp.readdir(cacheDir, { withFileTypes: true });
- for (const dirent of dirents) if (dirent.isDirectory() && dirent.name.includes("_temp_")) {
- const tempDirPath = path.resolve(config$2.cacheDir, dirent.name);
- const stats = await fsp.stat(tempDirPath).catch(() => null);
- if (stats?.mtime && Date.now() - stats.mtime.getTime() > MAX_TEMP_DIR_AGE_MS) {
- debug$3?.(`removing stale cache temp dir ${tempDirPath}`);
- await fsp.rm(tempDirPath, {
- recursive: true,
- force: true
- });
- }
- }
- }
- } catch (err$2) {
- config$2.logger.error(err$2);
- }
-}
-const GRACEFUL_RENAME_TIMEOUT = 5e3;
-const safeRename = promisify(function gracefulRename(from, to, cb) {
- const start = Date.now();
- let backoff = 0;
- fs.rename(from, to, function CB(er) {
- if (er && (er.code === "EACCES" || er.code === "EPERM") && Date.now() - start < GRACEFUL_RENAME_TIMEOUT) {
- setTimeout(function() {
- fs.stat(to, function(stater, _st) {
- if (stater && stater.code === "ENOENT") fs.rename(from, to, CB);
- else CB(er);
- });
- }, backoff);
- if (backoff < 100) backoff += 10;
- return;
- }
- cb(er);
- });
-});
-
-//#endregion
-//#region src/node/plugins/resolve.ts
-var import_picocolors$6 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const normalizedClientEntry = normalizePath(CLIENT_ENTRY);
-const normalizedEnvEntry = normalizePath(ENV_ENTRY);
-const ERR_RESOLVE_PACKAGE_ENTRY_FAIL = "ERR_RESOLVE_PACKAGE_ENTRY_FAIL";
-const browserExternalId = "__vite-browser-external";
-const optionalPeerDepId = "__vite-optional-peer-dep";
-const subpathImportsPrefix = "#";
-const relativePrefixRE = /^\.\.?(?:[/\\]|$)/;
-const startsWithWordCharRE = /^\w/;
-const debug$2 = createDebugger("vite:resolve-details", { onlyWhenFocused: true });
-function resolvePlugin(resolveOptions) {
- const { root, isProduction, asSrc, preferRelative = false } = resolveOptions;
- const rootInRoot = tryStatSync(path.join(root, root))?.isDirectory() ?? false;
- return {
- name: "vite:resolve",
- resolveId: {
- filter: { id: { exclude: /^(?:\0|\/?virtual:)/ } },
- async handler(id, importer, resolveOpts) {
- const depsOptimizer = resolveOptions.optimizeDeps && this.environment.mode === "dev" ? this.environment.depsOptimizer : void 0;
- if (id.startsWith(browserExternalId)) return id;
- const isRequire$1 = resolveOpts.custom?.["node-resolve"]?.isRequire ?? false;
- const currentEnvironmentOptions = this.environment.config;
- const options$1 = {
- isRequire: isRequire$1,
- ...currentEnvironmentOptions.resolve,
- ...resolveOptions,
- scan: resolveOpts.scan ?? resolveOptions.scan
- };
- const resolvedImports = resolveSubpathImports(id, importer, options$1);
- if (resolvedImports) {
- id = resolvedImports;
- if (resolveOpts.custom?.["vite:import-glob"]?.isSubImportsPattern) return normalizePath(path.join(root, id));
- }
- let res;
- if (asSrc && depsOptimizer?.isOptimizedDepUrl(id)) return id.startsWith(FS_PREFIX) ? fsPathFromId(id) : normalizePath(path.resolve(root, id.slice(1)));
- if (asSrc && id.startsWith(FS_PREFIX)) {
- res = fsPathFromId(id);
- debug$2?.(`[@fs] ${import_picocolors$6.default.cyan(id)} -> ${import_picocolors$6.default.dim(res)}`);
- return ensureVersionQuery(res, id, options$1, depsOptimizer);
- }
- if (asSrc && id[0] === "/" && (rootInRoot || !id.startsWith(withTrailingSlash(root)))) {
- if (res = tryFsResolve(path.resolve(root, id.slice(1)), options$1)) {
- debug$2?.(`[url] ${import_picocolors$6.default.cyan(id)} -> ${import_picocolors$6.default.dim(res)}`);
- return ensureVersionQuery(res, id, options$1, depsOptimizer);
- }
- }
- if (relativePrefixRE.test(id) || (preferRelative || resolveOpts.isEntry || importer?.endsWith(".html")) && startsWithWordCharRE.test(id)) {
- const basedir = importer ? path.dirname(importer) : process.cwd();
- const fsPath = path.resolve(basedir, id);
- const normalizedFsPath = normalizePath(fsPath);
- if (depsOptimizer?.isOptimizedDepFile(normalizedFsPath)) {
- if (!options$1.isBuild && !DEP_VERSION_RE.test(normalizedFsPath)) {
- const browserHash = optimizedDepInfoFromFile(depsOptimizer.metadata, normalizedFsPath)?.browserHash;
- if (browserHash) return injectQuery(normalizedFsPath, `v=${browserHash}`);
- }
- return normalizedFsPath;
- }
- if (options$1.mainFields.includes("browser") && (res = tryResolveBrowserMapping(fsPath, importer, options$1, true))) return res;
- if (res = tryFsResolve(fsPath, options$1)) {
- res = ensureVersionQuery(res, id, options$1, depsOptimizer);
- debug$2?.(`[relative] ${import_picocolors$6.default.cyan(id)} -> ${import_picocolors$6.default.dim(res)}`);
- if (!options$1.idOnly && !options$1.scan && options$1.isBuild) {
- const resPkg = findNearestPackageData(path.dirname(res), options$1.packageCache);
- if (resPkg) return {
- id: res,
- moduleSideEffects: resPkg.hasSideEffects(res)
- };
- }
- return res;
- }
- }
- if (id.startsWith("file://")) {
- const { file, postfix } = splitFileAndPostfix(id);
- id = fileURLToPath(file) + postfix;
- }
- if (isWindows && id[0] === "/") {
- const basedir = importer ? path.dirname(importer) : process.cwd();
- if (res = tryFsResolve(path.resolve(basedir, id), options$1)) {
- debug$2?.(`[drive-relative] ${import_picocolors$6.default.cyan(id)} -> ${import_picocolors$6.default.dim(res)}`);
- return ensureVersionQuery(res, id, options$1, depsOptimizer);
- }
- }
- if (isNonDriveRelativeAbsolutePath(id) && (res = tryFsResolve(id, options$1))) {
- debug$2?.(`[fs] ${import_picocolors$6.default.cyan(id)} -> ${import_picocolors$6.default.dim(res)}`);
- return ensureVersionQuery(res, id, options$1, depsOptimizer);
- }
- if (isExternalUrl(id)) return options$1.idOnly ? id : {
- id,
- external: true
- };
- if (isDataUrl(id)) return null;
- if (bareImportRE.test(id)) {
- const external = options$1.externalize && options$1.isBuild && currentEnvironmentOptions.consumer === "server" && shouldExternalize(this.environment, id, importer);
- if (!external && asSrc && depsOptimizer && !options$1.scan && (res = await tryOptimizedResolve(depsOptimizer, id, importer, options$1.preserveSymlinks, options$1.packageCache))) return res;
- if (options$1.mainFields.includes("browser") && (res = tryResolveBrowserMapping(id, importer, options$1, false, external))) return res;
- if (res = tryNodeResolve(id, importer, options$1, depsOptimizer, external)) return res;
- if (currentEnvironmentOptions.consumer === "server" && isBuiltin(options$1.builtins, id)) return options$1.idOnly ? id : {
- id,
- external: true,
- moduleSideEffects: false
- };
- else if (currentEnvironmentOptions.consumer === "server" && isNodeLikeBuiltin(id)) {
- if (!(options$1.external === true || options$1.external.includes(id))) {
- let message = `Automatically externalized node built-in module "${id}"`;
- if (importer) message += ` imported from "${path.relative(process.cwd(), importer)}"`;
- message += `. Consider adding it to environments.${this.environment.name}.external if it is intended.`;
- this.warn(message);
- }
- return options$1.idOnly ? id : {
- id,
- external: true,
- moduleSideEffects: false
- };
- } else if (currentEnvironmentOptions.consumer === "client" && isNodeLikeBuiltin(id)) {
- if (options$1.noExternal === true && (options$1.external === true || !options$1.external.includes(id))) {
- let message = `Cannot bundle built-in module "${id}"`;
- if (importer) message += ` imported from "${path.relative(process.cwd(), importer)}"`;
- message += `. Consider disabling environments.${this.environment.name}.noExternal or remove the built-in dependency.`;
- this.error(message);
- }
- if (!asSrc) debug$2?.(`externalized node built-in "${id}" to empty module. (imported by: ${import_picocolors$6.default.white(import_picocolors$6.default.dim(importer))})`);
- else if (isProduction) this.warn(`Module "${id}" has been externalized for browser compatibility, imported by "${importer}". See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
- return isProduction ? browserExternalId : `${browserExternalId}:${id}`;
- }
- }
- debug$2?.(`[fallthrough] ${import_picocolors$6.default.dim(id)}`);
- }
- },
- load: {
- filter: { id: [prefixRegex(browserExternalId), prefixRegex(optionalPeerDepId)] },
- handler(id) {
- if (id.startsWith(browserExternalId)) if (isProduction) return `export default {}`;
- else {
- id = id.slice(24);
- return `\
- export default new Proxy({}, {
- get(_, key) {
- throw new Error(\`Module "${id}" has been externalized for browser compatibility. Cannot access "${id}.\${key}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
- }
- })`;
- }
- if (id.startsWith(optionalPeerDepId)) {
- const [, peerDep, parentDep, isRequire$1] = id.split(":");
- if (isRequire$1 === "true" && isProduction) return "export default {}";
- return `export default {};throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}".${isProduction ? "" : " Is it installed?"}\`)`;
- }
- }
- }
- };
-}
-function resolveSubpathImports(id, importer, options$1) {
- if (!importer || !id.startsWith(subpathImportsPrefix)) return;
- const basedir = path.dirname(importer);
- const pkgData = findNearestPackageData(basedir, options$1.packageCache);
- if (!pkgData) return;
- let { file: idWithoutPostfix, postfix } = splitFileAndPostfix(id.slice(1));
- idWithoutPostfix = "#" + idWithoutPostfix;
- let importsPath = resolveExportsOrImports(pkgData.data, idWithoutPostfix, options$1, "imports");
- if (importsPath?.[0] === ".") {
- importsPath = path.relative(basedir, path.join(pkgData.dir, importsPath));
- if (!relativePrefixRE.test(importsPath)) importsPath = `./${importsPath}`;
- }
- return importsPath + postfix;
-}
-function ensureVersionQuery(resolved, id, options$1, depsOptimizer) {
- if (!options$1.isBuild && !options$1.scan && depsOptimizer && !(resolved === normalizedClientEntry || resolved === normalizedEnvEntry)) {
- if ((isInNodeModules(id) || isInNodeModules(resolved)) && !DEP_VERSION_RE.test(resolved)) {
- const versionHash = depsOptimizer.metadata.browserHash;
- if (versionHash && isOptimizable(resolved, depsOptimizer.options)) resolved = injectQuery(resolved, `v=${versionHash}`);
- }
- }
- return resolved;
-}
-function tryFsResolve(fsPath, options$1, tryIndex = true, skipPackageJson = false) {
- const hashIndex = fsPath.indexOf("#");
- if (hashIndex >= 0 && isInNodeModules(fsPath)) {
- const queryIndex = fsPath.indexOf("?");
- if (queryIndex < 0 || queryIndex > hashIndex) {
- const file$1 = queryIndex > hashIndex ? fsPath.slice(0, queryIndex) : fsPath;
- const res$1 = tryCleanFsResolve(file$1, options$1, tryIndex, skipPackageJson);
- if (res$1) return res$1 + fsPath.slice(file$1.length);
- }
- }
- const { file, postfix } = splitFileAndPostfix(fsPath);
- const res = tryCleanFsResolve(file, options$1, tryIndex, skipPackageJson);
- if (res) return res + postfix;
-}
-const knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/;
-const isPossibleTsOutput = (url$3) => knownTsOutputRE.test(url$3);
-function tryCleanFsResolve(file, options$1, tryIndex = true, skipPackageJson = false) {
- const { tryPrefix, extensions: extensions$1, preserveSymlinks } = options$1;
- const fileResult = tryResolveRealFileOrType(file, options$1.preserveSymlinks);
- if (fileResult?.path) return fileResult.path;
- let res;
- const possibleJsToTs = isPossibleTsOutput(file);
- if (possibleJsToTs || options$1.extensions.length || tryPrefix) {
- const dirPath = path.dirname(file);
- if (isDirectory(dirPath)) {
- if (possibleJsToTs) {
- const fileExt = path.extname(file);
- const fileName = file.slice(0, -fileExt.length);
- if (res = tryResolveRealFile(fileName + fileExt.replace("js", "ts"), preserveSymlinks)) return res;
- if (fileExt === ".js" && (res = tryResolveRealFile(fileName + ".tsx", preserveSymlinks))) return res;
- }
- if (res = tryResolveRealFileWithExtensions(file, extensions$1, preserveSymlinks)) return res;
- if (tryPrefix) {
- const prefixed = `${dirPath}/${options$1.tryPrefix}${path.basename(file)}`;
- if (res = tryResolveRealFile(prefixed, preserveSymlinks)) return res;
- if (res = tryResolveRealFileWithExtensions(prefixed, extensions$1, preserveSymlinks)) return res;
- }
- }
- }
- if (tryIndex && fileResult?.type === "directory") {
- const dirPath = file;
- if (!skipPackageJson) {
- let pkgPath = `${dirPath}/package.json`;
- try {
- if (fs.existsSync(pkgPath)) {
- if (!options$1.preserveSymlinks) pkgPath = safeRealpathSync(pkgPath);
- return resolvePackageEntry(dirPath, loadPackageData(pkgPath), options$1);
- }
- } catch (e$1) {
- if (e$1.code !== ERR_RESOLVE_PACKAGE_ENTRY_FAIL && e$1.code !== "ENOENT") throw e$1;
- }
- }
- if (res = tryResolveRealFileWithExtensions(`${dirPath}/index`, extensions$1, preserveSymlinks)) return res;
- if (tryPrefix) {
- if (res = tryResolveRealFileWithExtensions(`${dirPath}/${options$1.tryPrefix}index`, extensions$1, preserveSymlinks)) return res;
- }
- }
-}
-function tryNodeResolve(id, importer, options$1, depsOptimizer, externalize) {
- const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options$1;
- const deepMatch = deepImportRE.exec(id);
- const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : cleanUrl(id);
- let basedir;
- if (dedupe.includes(pkgId)) basedir = root;
- else if (importer && path.isAbsolute(importer) && (importer.endsWith("*") || fs.existsSync(cleanUrl(importer)))) basedir = path.dirname(importer);
- else basedir = root;
- const isModuleBuiltin = (id$1) => isBuiltin(options$1.builtins, id$1);
- let selfPkg = null;
- if (!isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
- const selfPackageData = findNearestPackageData(basedir, packageCache);
- selfPkg = selfPackageData?.data.exports && selfPackageData.data.name === pkgId ? selfPackageData : null;
- }
- const pkg = selfPkg || resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache);
- if (!pkg) {
- if (!options$1.disableOptionalPeerDepHandling && basedir !== root && !isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
- const mainPkg = findNearestMainPackageData(basedir, packageCache)?.data;
- if (mainPkg) {
- const pkgName = getNpmPackageName(id);
- if (pkgName != null && mainPkg.peerDependencies?.[pkgName] && mainPkg.peerDependenciesMeta?.[pkgName]?.optional) return { id: `${optionalPeerDepId}:${id}:${mainPkg.name}:${!!options$1.isRequire}` };
- }
- }
- return;
- }
- let resolved = (deepMatch ? resolveDeepImport : resolvePackageEntry)(deepMatch ? "." + id.slice(pkgId.length) : id, pkg, options$1, externalize);
- if (!resolved) return;
- const processResult$1 = (resolved$1) => {
- if (!externalize) return resolved$1;
- if (!canExternalizeFile(resolved$1.id)) return resolved$1;
- let resolvedId = id;
- if (deepMatch && !pkg.data.exports && path.extname(id) !== path.extname(resolved$1.id)) {
- const index = resolved$1.id.indexOf(id);
- if (index > -1) {
- resolvedId = resolved$1.id.slice(index);
- debug$2?.(`[processResult] ${import_picocolors$6.default.cyan(id)} -> ${import_picocolors$6.default.dim(resolvedId)}`);
- }
- }
- return {
- ...resolved$1,
- id: resolvedId,
- external: true
- };
- };
- if (!options$1.idOnly && (!options$1.scan && isBuild || externalize)) return processResult$1({
- id: resolved,
- moduleSideEffects: pkg.hasSideEffects(resolved)
- });
- if (!isInNodeModules(resolved) || !depsOptimizer || options$1.scan) return { id: resolved };
- const isJsType = isOptimizable(resolved, depsOptimizer.options);
- const exclude = depsOptimizer.options.exclude;
- if (depsOptimizer.options.noDiscovery || !isJsType || importer && isInNodeModules(importer) || exclude?.includes(pkgId) || exclude?.includes(id) || SPECIAL_QUERY_RE.test(resolved)) {
- const versionHash = depsOptimizer.metadata.browserHash;
- if (versionHash && isJsType) resolved = injectQuery(resolved, `v=${versionHash}`);
- } else {
- const optimizedInfo = depsOptimizer.registerMissingImport(id, resolved);
- resolved = depsOptimizer.getOptimizedDepId(optimizedInfo);
- }
- return { id: resolved };
-}
-async function tryOptimizedResolve(depsOptimizer, id, importer, preserveSymlinks, packageCache) {
- await depsOptimizer.scanProcessing;
- const metadata = depsOptimizer.metadata;
- const depInfo = optimizedDepInfoFromId(metadata, id);
- if (depInfo) return depsOptimizer.getOptimizedDepId(depInfo);
- if (!importer) return;
- let idPkgDir;
- const nestedIdMatch = `> ${id}`;
- for (const optimizedData of metadata.depInfoList) {
- if (!optimizedData.src) continue;
- if (!optimizedData.id.endsWith(nestedIdMatch)) continue;
- if (idPkgDir == null) {
- const pkgName = getNpmPackageName(id);
- if (!pkgName) break;
- idPkgDir = resolvePackageData(pkgName, importer, preserveSymlinks, packageCache)?.dir;
- if (idPkgDir == null) break;
- idPkgDir = normalizePath(idPkgDir);
- }
- if (optimizedData.src.startsWith(withTrailingSlash(idPkgDir))) return depsOptimizer.getOptimizedDepId(optimizedData);
- }
-}
-function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache }, options$1, externalize) {
- const { file: idWithoutPostfix, postfix } = splitFileAndPostfix(id);
- const cached = getResolvedCache(".", options$1);
- if (cached) return cached + postfix;
- try {
- let entryPoint;
- if (data.exports) entryPoint = resolveExportsOrImports(data, ".", options$1, "exports", externalize);
- if (!entryPoint) {
- for (const field of options$1.mainFields) if (field === "browser") {
- entryPoint = tryResolveBrowserEntry(dir, data, options$1);
- if (entryPoint) break;
- } else if (typeof data[field] === "string") {
- entryPoint = data[field];
- break;
- }
- }
- entryPoint ||= data.main;
- const entryPoints = entryPoint ? [entryPoint] : [
- "index.js",
- "index.json",
- "index.node"
- ];
- for (let entry of entryPoints) {
- let skipPackageJson = false;
- if (options$1.mainFields[0] === "sass" && !options$1.extensions.includes(path.extname(entry))) {
- entry = "";
- skipPackageJson = true;
- } else {
- const { browser: browserField } = data;
- if (options$1.mainFields.includes("browser") && isObject(browserField)) entry = mapWithBrowserField(entry, browserField) || entry;
- }
- const resolvedEntryPoint = tryFsResolve(path.join(dir, entry), options$1, true, skipPackageJson);
- if (resolvedEntryPoint) {
- debug$2?.(`[package entry] ${import_picocolors$6.default.cyan(idWithoutPostfix)} -> ${import_picocolors$6.default.dim(resolvedEntryPoint)}${postfix !== "" ? ` (postfix: ${postfix})` : ""}`);
- setResolvedCache(".", resolvedEntryPoint, options$1);
- return resolvedEntryPoint + postfix;
- }
- }
- } catch (e$1) {
- packageEntryFailure(id, e$1.message);
- }
- packageEntryFailure(id);
-}
-function packageEntryFailure(id, details) {
- const err$2 = /* @__PURE__ */ new Error(`Failed to resolve entry for package "${id}". The package may have incorrect main/module/exports specified in its package.json` + (details ? ": " + details : "."));
- err$2.code = ERR_RESOLVE_PACKAGE_ENTRY_FAIL;
- throw err$2;
-}
-function resolveExportsOrImports(pkg, key, options$1, type, externalize) {
- const conditions = (externalize ? options$1.externalConditions : options$1.conditions).map((condition) => {
- if (condition === DEV_PROD_CONDITION) return options$1.isProduction ? "production" : "development";
- return condition;
- });
- if (options$1.isRequire) conditions.push("require");
- else conditions.push("import");
- const result = (type === "imports" ? f : o)(pkg, key, {
- conditions,
- unsafe: true
- });
- return result ? result[0] : void 0;
-}
-function resolveDeepImport(id, { setResolvedCache, getResolvedCache, dir, data }, options$1, externalize) {
- const cache$1 = getResolvedCache(id, options$1);
- if (cache$1) return cache$1;
- let relativeId = id;
- const { exports: exportsField, browser: browserField } = data;
- if (exportsField) {
- if (isObject(exportsField) && !Array.isArray(exportsField)) {
- const { file, postfix } = splitFileAndPostfix(relativeId);
- const exportsId = resolveExportsOrImports(data, file, options$1, "exports", externalize);
- if (exportsId !== void 0) relativeId = exportsId + postfix;
- else relativeId = void 0;
- } else relativeId = void 0;
- if (!relativeId) throw new Error(`Package subpath '${relativeId}' is not defined by "exports" in ${path.join(dir, "package.json")}.`);
- } else if (options$1.mainFields.includes("browser") && isObject(browserField)) {
- const { file, postfix } = splitFileAndPostfix(relativeId);
- const mapped = mapWithBrowserField(file, browserField);
- if (mapped) relativeId = mapped + postfix;
- else if (mapped === false) {
- setResolvedCache(id, browserExternalId, options$1);
- return browserExternalId;
- }
- }
- if (relativeId) {
- const resolved = tryFsResolve(path.join(dir, relativeId), options$1, !exportsField);
- if (resolved) {
- debug$2?.(`[node/deep-import] ${import_picocolors$6.default.cyan(id)} -> ${import_picocolors$6.default.dim(resolved)}`);
- setResolvedCache(id, resolved, options$1);
- return resolved;
- }
- }
-}
-function tryResolveBrowserMapping(id, importer, options$1, isFilePath, externalize) {
- let res;
- const pkg = importer && findNearestPackageData(path.dirname(importer), options$1.packageCache);
- if (pkg && isObject(pkg.data.browser)) {
- const browserMappedPath = mapWithBrowserField(isFilePath ? "./" + slash(path.relative(pkg.dir, id)) : id, pkg.data.browser);
- if (browserMappedPath) {
- if (res = bareImportRE.test(browserMappedPath) ? tryNodeResolve(browserMappedPath, importer, options$1, void 0, void 0)?.id : tryFsResolve(path.join(pkg.dir, browserMappedPath), options$1)) {
- debug$2?.(`[browser mapped] ${import_picocolors$6.default.cyan(id)} -> ${import_picocolors$6.default.dim(res)}`);
- let result = { id: res };
- if (options$1.idOnly) return result;
- if (!options$1.scan && options$1.isBuild) {
- const resPkg = findNearestPackageData(path.dirname(res), options$1.packageCache);
- if (resPkg) result = {
- id: res,
- moduleSideEffects: resPkg.hasSideEffects(res)
- };
- }
- return externalize ? {
- ...result,
- external: true
- } : result;
- }
- } else if (browserMappedPath === false) return browserExternalId;
- }
-}
-function tryResolveBrowserEntry(dir, data, options$1) {
- const browserEntry = typeof data.browser === "string" ? data.browser : isObject(data.browser) && data.browser["."];
- if (browserEntry) if (!options$1.isRequire && options$1.mainFields.includes("module") && typeof data.module === "string" && data.module !== browserEntry) {
- const resolvedBrowserEntry = tryFsResolve(path.join(dir, browserEntry), options$1);
- if (resolvedBrowserEntry) if (hasESMSyntax(fs.readFileSync(resolvedBrowserEntry, "utf-8"))) return browserEntry;
- else return data.module;
- } else return browserEntry;
-}
-/**
-* given a relative path in pkg dir,
-* return a relative path in pkg dir,
-* mapped with the "map" object
-*
-* - Returning `undefined` means there is no browser mapping for this id
-* - Returning `false` means this id is explicitly externalized for browser
-*/
-function mapWithBrowserField(relativePathInPkgDir, map$1) {
- const normalizedPath = path.posix.normalize(relativePathInPkgDir);
- for (const key in map$1) {
- const normalizedKey = path.posix.normalize(key);
- if (normalizedPath === normalizedKey || equalWithoutSuffix(normalizedPath, normalizedKey, ".js") || equalWithoutSuffix(normalizedPath, normalizedKey, "/index.js")) return map$1[key];
- }
-}
-function equalWithoutSuffix(path$13, key, suffix) {
- return key.endsWith(suffix) && key.slice(0, -suffix.length) === path$13;
-}
-function tryResolveRealFile(file, preserveSymlinks) {
- if (tryStatSync(file)?.isFile()) return getRealPath(file, preserveSymlinks);
-}
-function tryResolveRealFileWithExtensions(filePath, extensions$1, preserveSymlinks) {
- for (const ext of extensions$1) {
- const res = tryResolveRealFile(filePath + ext, preserveSymlinks);
- if (res) return res;
- }
-}
-function tryResolveRealFileOrType(file, preserveSymlinks) {
- const fileStat = tryStatSync(file);
- if (fileStat?.isFile()) return {
- path: getRealPath(file, preserveSymlinks),
- type: "file"
- };
- if (fileStat?.isDirectory()) return { type: "directory" };
-}
-function getRealPath(resolved, preserveSymlinks) {
- if (!preserveSymlinks) resolved = safeRealpathSync(resolved);
- return normalizePath(resolved);
-}
-function isDirectory(path$13) {
- return tryStatSync(path$13)?.isDirectory() ?? false;
-}
-
-//#endregion
-//#region src/node/nodeResolve.ts
-/**
-* Resolve like Node.js using Vite's resolution algorithm with preconfigured options.
-*/
-function nodeResolveWithVite(id, importer, options$1) {
- return tryNodeResolve(id, importer, {
- root: options$1.root,
- isBuild: true,
- isProduction: true,
- preferRelative: false,
- tryIndex: true,
- mainFields: [],
- conditions: ["node", ...isModuleSyncConditionEnabled ? ["module-sync"] : []],
- externalConditions: [],
- external: [],
- noExternal: [],
- dedupe: [],
- extensions: DEFAULT_EXTENSIONS,
- preserveSymlinks: false,
- packageCache: void 0,
- isRequire: options$1.isRequire,
- builtins: nodeLikeBuiltins,
- disableOptionalPeerDepHandling: true
- })?.id;
-}
-
-//#endregion
-//#region src/node/plugins/terser.ts
-let terserPath;
-function loadTerserPath(root) {
- if (terserPath) return terserPath;
- const resolved = nodeResolveWithVite("terser", void 0, { root }) ?? nodeResolveWithVite("terser", _dirname, { root });
- if (resolved) return terserPath = resolved;
- throw new Error("terser not found. Since Vite v3, terser has become an optional dependency. You need to install it.");
-}
-function terserPlugin(config$2) {
- const { maxWorkers, ...terserOptions } = config$2.build.terserOptions;
- const makeWorker = () => new WorkerWithFallback(() => async (terserPath$1, code, options$1) => {
- const terser = await import(terserPath$1);
- try {
- return await terser.minify(code, options$1);
- } catch (e$1) {
- throw {
- stack: e$1.stack,
- ...e$1
- };
- }
- }, {
- shouldUseFake(_terserPath, _code, options$1) {
- return !!(typeof options$1.mangle === "object" && (options$1.mangle.nth_identifier?.get || typeof options$1.mangle.properties === "object" && options$1.mangle.properties.nth_identifier?.get) || typeof options$1.format?.comments === "function" || typeof options$1.output?.comments === "function" || options$1.nameCache);
- },
- max: maxWorkers
- });
- let worker;
- return {
- name: "vite:terser",
- applyToEnvironment(environment) {
- return !!environment.config.build.minify;
- },
- async renderChunk(code, chunk, outputOptions) {
- if (config$2.build.minify !== "terser" && !outputOptions.__vite_force_terser__) return null;
- worker ||= makeWorker();
- const terserPath$1 = pathToFileURL(loadTerserPath(config$2.root)).href;
- try {
- const res = await worker.run(terserPath$1, code, {
- safari10: true,
- ...terserOptions,
- format: {
- ...terserOptions.format,
- preserve_annotations: config$2.build.lib && outputOptions.format === "es" ? true : terserOptions.format?.preserve_annotations
- },
- sourceMap: !!outputOptions.sourcemap,
- module: outputOptions.format.startsWith("es"),
- toplevel: outputOptions.format === "cjs"
- });
- return {
- code: res.code,
- map: res.map
- };
- } catch (e$1) {
- if (e$1.line !== void 0 && e$1.col !== void 0) e$1.loc = {
- file: chunk.fileName,
- line: e$1.line,
- column: e$1.col
- };
- if (e$1.pos !== void 0) e$1.frame = generateCodeFrame(code, e$1.pos);
- throw e$1;
- }
- },
- closeBundle() {
- worker?.stop();
- }
- };
-}
-
-//#endregion
-//#region src/node/plugins/dataUri.ts
-const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/;
-const base64RE = /base64/i;
-const dataUriPrefix = `\0/@data-uri/`;
-/**
-* Build only, since importing from a data URI works natively.
-*/
-function dataURIPlugin() {
- let resolved;
- return {
- name: "vite:data-uri",
- buildStart() {
- resolved = /* @__PURE__ */ new Map();
- },
- resolveId(id) {
- if (!id.trimStart().startsWith("data:")) return;
- const uri = new URL$1(id);
- if (uri.protocol !== "data:") return;
- const match = dataUriRE.exec(uri.pathname);
- if (!match) return;
- const [, mime, format$3, data] = match;
- if (mime !== "text/javascript") throw new Error(`data URI with non-JavaScript mime type is not supported. If you're using legacy JavaScript MIME types (such as 'application/javascript'), please use 'text/javascript' instead.`);
- const content = format$3 && base64RE.test(format$3.substring(1)) ? Buffer.from(data, "base64").toString("utf-8") : data;
- resolved.set(id, content);
- return dataUriPrefix + id;
- },
- load(id) {
- if (id.startsWith(dataUriPrefix)) return resolved.get(id.slice(dataUriPrefix.length));
- }
- };
-}
-
-//#endregion
-//#region src/node/ssr/ssrManifestPlugin.ts
-function ssrManifestPlugin() {
- const getSsrManifest = perEnvironmentState(() => {
- return {};
- });
- return {
- name: "vite:ssr-manifest",
- applyToEnvironment(environment) {
- return !!environment.config.build.ssrManifest;
- },
- generateBundle(_options, bundle) {
- const config$2 = this.environment.config;
- const ssrManifest = getSsrManifest(this);
- const { base } = config$2;
- for (const file in bundle) {
- const chunk = bundle[file];
- if (chunk.type === "chunk") {
- for (const id in chunk.modules) {
- const normalizedId = normalizePath(relative(config$2.root, id));
- const mappedChunks = ssrManifest[normalizedId] ?? (ssrManifest[normalizedId] = []);
- if (!chunk.isEntry) {
- mappedChunks.push(joinUrlSegments(base, chunk.fileName));
- chunk.viteMetadata.importedCss.forEach((file$1) => {
- mappedChunks.push(joinUrlSegments(base, file$1));
- });
- }
- chunk.viteMetadata.importedAssets.forEach((file$1) => {
- mappedChunks.push(joinUrlSegments(base, file$1));
- });
- }
- if (chunk.code.includes(preloadMethod)) {
- const code = chunk.code;
- let imports = [];
- try {
- imports = parse(code)[0].filter((i$1) => i$1.n && i$1.d > -1);
- } catch (_e) {
- const e$1 = _e;
- const loc = numberToPos(code, e$1.idx);
- this.error({
- name: e$1.name,
- message: e$1.message,
- stack: e$1.stack,
- cause: e$1.cause,
- pos: e$1.idx,
- loc: {
- ...loc,
- file: chunk.fileName
- },
- frame: generateCodeFrame(code, loc)
- });
- }
- if (imports.length) for (let index = 0; index < imports.length; index++) {
- const { s: start, e: end, n: name } = imports[index];
- const url$3 = code.slice(start, end);
- const deps = [];
- const ownerFilename = chunk.fileName;
- const analyzed = /* @__PURE__ */ new Set();
- const addDeps = (filename) => {
- if (filename === ownerFilename) return;
- if (analyzed.has(filename)) return;
- analyzed.add(filename);
- const chunk$1 = bundle[filename];
- if (chunk$1) {
- chunk$1.viteMetadata.importedCss.forEach((file$1) => {
- deps.push(joinUrlSegments(base, file$1));
- });
- chunk$1.imports.forEach(addDeps);
- }
- };
- addDeps(normalizePath(join(dirname(chunk.fileName), url$3.slice(1, -1))));
- ssrManifest[basename(name)] = deps;
- }
- }
- }
- }
- this.emitFile({
- fileName: typeof config$2.build.ssrManifest === "string" ? config$2.build.ssrManifest : ".vite/ssr-manifest.json",
- type: "asset",
- source: JSON.stringify(sortObjectKeys(ssrManifest), void 0, 2)
- });
- }
- };
-}
-
-//#endregion
-//#region src/node/plugins/loadFallback.ts
-/**
-* A plugin to provide build load fallback for arbitrary request with queries.
-*/
-function buildLoadFallbackPlugin() {
- return {
- name: "vite:load-fallback",
- load: { async handler(id) {
- try {
- const cleanedId = cleanUrl(id);
- const content = await fsp.readFile(cleanedId, "utf-8");
- this.addWatchFile(cleanedId);
- return content;
- } catch {
- const content = await fsp.readFile(id, "utf-8");
- this.addWatchFile(id);
- return content;
- }
- } }
- };
-}
-
-//#endregion
-//#region src/node/plugins/completeAmdWrap.ts
-/**
-* ensure amd bundles request `require` to be injected
-*/
-function completeAmdWrapPlugin() {
- const AmdWrapRE = /\bdefine\((?:\s*\[([^\]]*)\],)?\s*(?:\(\s*)?function\s*\(([^)]*)\)\s*\{/g;
- return {
- name: "vite:force-amd-wrap-require",
- renderChunk(code, _chunk, opts) {
- if (opts.format !== "amd") return;
- return {
- code: code.replace(AmdWrapRE, (_, deps, params) => {
- if (deps?.includes(`"require"`) || deps?.includes(`'require'`)) return `define([${deps}], (function(${params}) {`;
- return `define([${deps ? `"require", ${deps}` : "\"require\""}], (function(${params.trim() ? `require, ${params}` : "require"}) {`;
- }),
- map: null
- };
- }
- };
-}
-
-//#endregion
-//#region src/node/plugins/completeSystemWrap.ts
-/**
-* make sure systemjs register wrap to had complete parameters in system format
-*/
-function completeSystemWrapPlugin() {
- const SystemJSWrapRE = /System.register\(.*?(\(exports\)|\(\))/g;
- return {
- name: "vite:force-systemjs-wrap-complete",
- renderChunk(code, _chunk, opts) {
- if (opts.format === "system") return {
- code: code.replace(SystemJSWrapRE, (s, s1) => s.replace(s1, "(exports, module)")),
- map: null
- };
- }
- };
-}
-
-//#endregion
-//#region src/node/plugins/license.ts
-const licenseConfigDefaults = Object.freeze({ fileName: ".vite/license.md" });
-const licenseFiles = [
- /^license/i,
- /^licence/i,
- /^copying/i
-];
-function licensePlugin() {
- return {
- name: "vite:license",
- async generateBundle(_, bundle) {
- const licenseOption = this.environment.config.build.license;
- if (licenseOption === false) return;
- const packageCache = /* @__PURE__ */ new Map();
- const licenses = {};
- for (const file in bundle) {
- const chunk = bundle[file];
- if (chunk.type === "asset") continue;
- for (const moduleId of chunk.moduleIds) {
- if (moduleId.startsWith("\0") || !isInNodeModules(moduleId)) continue;
- const pkgData = findNearestMainPackageData(path.dirname(moduleId), packageCache);
- if (!pkgData) continue;
- const { name, version: version$2 = "0.0.0", license } = pkgData.data;
- const key = `${name}@${version$2}`;
- if (licenses[key]) continue;
- const entry = {
- name,
- version: version$2
- };
- if (license) entry.identifier = license.trim();
- const licenseFile = findLicenseFile(pkgData.dir);
- if (licenseFile) entry.text = fs.readFileSync(licenseFile, "utf-8").trim();
- licenses[key] = entry;
- }
- }
- const licenseEntries = Object.values(sortObjectKeys(licenses));
- const licenseOutputFileName = typeof licenseOption === "object" ? licenseOption.fileName : licenseConfigDefaults.fileName;
- if (licenseOutputFileName.endsWith(".json")) {
- this.emitFile({
- fileName: licenseOutputFileName,
- type: "asset",
- source: JSON.stringify(licenseEntries, null, 2)
- });
- return;
- }
- const markdown = licenseEntryToMarkdown(licenseEntries);
- this.emitFile({
- fileName: licenseOutputFileName,
- type: "asset",
- source: markdown
- });
- }
- };
-}
-function licenseEntryToMarkdown(licenses) {
- if (licenses.length === 0) return `\
-# Licenses
-
-The app does not bundle any dependencies with licenses.
-`;
- let text = `\
-# Licenses
-
-The app bundles dependencies which contain the following licenses:
-`;
- for (const license of licenses) {
- const nameAndVersionText = `${license.name} - ${license.version}`;
- const identifierText = license.identifier ? ` (${license.identifier})` : "";
- text += `\n## ${nameAndVersionText}${identifierText}\n`;
- if (license.text) text += `\n${license.text}\n`;
- }
- return text;
-}
-function findLicenseFile(pkgDir) {
- const matchedFile = fs.readdirSync(pkgDir).find((file) => licenseFiles.some((re) => re.test(file)));
- if (matchedFile) return path.join(pkgDir, matchedFile);
-}
-
-//#endregion
-//#region src/node/plugins/prepareOutDir.ts
-var import_picocolors$5 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-function prepareOutDirPlugin() {
- const rendered = /* @__PURE__ */ new Set();
- return {
- name: "vite:prepare-out-dir",
- options() {
- rendered.delete(this.environment);
- },
- renderStart: {
- order: "pre",
- handler() {
- if (rendered.has(this.environment)) return;
- rendered.add(this.environment);
- const { config: config$2 } = this.environment;
- if (config$2.build.write) {
- const { root, build: options$1 } = config$2;
- const resolvedOutDirs = getResolvedOutDirs(root, options$1.outDir, options$1.rollupOptions.output);
- prepareOutDir(resolvedOutDirs, resolveEmptyOutDir(options$1.emptyOutDir, root, resolvedOutDirs, this.environment.logger), this.environment);
- }
- }
- }
- };
-}
-function prepareOutDir(outDirs, emptyOutDir, environment) {
- const { publicDir } = environment.config;
- const outDirsArray = [...outDirs];
- for (const outDir of outDirs) {
- if (emptyOutDir !== false && fs.existsSync(outDir)) emptyDir(outDir, [...outDirsArray.map((dir) => {
- const relative$3 = path.relative(outDir, dir);
- if (relative$3 && !relative$3.startsWith("..") && !path.isAbsolute(relative$3)) return relative$3;
- return "";
- }).filter(Boolean), ".git"]);
- if (environment.config.build.copyPublicDir && publicDir && fs.existsSync(publicDir)) {
- if (!areSeparateFolders(outDir, publicDir)) environment.logger.warn(import_picocolors$5.default.yellow(`\n${import_picocolors$5.default.bold(`(!)`)} The public directory feature may not work correctly. outDir ${import_picocolors$5.default.white(import_picocolors$5.default.dim(outDir))} and publicDir ${import_picocolors$5.default.white(import_picocolors$5.default.dim(publicDir))} are not separate folders.\n`));
- copyDir(publicDir, outDir);
- }
- }
-}
-function areSeparateFolders(a, b) {
- const na = normalizePath(a);
- const nb = normalizePath(b);
- return na !== nb && !na.startsWith(withTrailingSlash(nb)) && !nb.startsWith(withTrailingSlash(na));
-}
-
-//#endregion
-//#region src/node/build.ts
-var import_picocolors$4 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const _buildEnvironmentOptionsDefaults = Object.freeze({
- target: "baseline-widely-available",
- polyfillModulePreload: true,
- modulePreload: true,
- outDir: "dist",
- assetsDir: "assets",
- assetsInlineLimit: DEFAULT_ASSETS_INLINE_LIMIT,
- sourcemap: false,
- terserOptions: {},
- rollupOptions: {},
- commonjsOptions: {
- include: [/node_modules/],
- extensions: [".js", ".cjs"]
- },
- dynamicImportVarsOptions: {
- warnOnError: true,
- exclude: [/node_modules/]
- },
- write: true,
- emptyOutDir: null,
- copyPublicDir: true,
- license: false,
- manifest: false,
- lib: false,
- ssrManifest: false,
- ssrEmitAssets: false,
- reportCompressedSize: true,
- chunkSizeWarningLimit: 500,
- watch: null
-});
-const buildEnvironmentOptionsDefaults = _buildEnvironmentOptionsDefaults;
-function resolveBuildEnvironmentOptions(raw, logger, consumer) {
- const deprecatedPolyfillModulePreload = raw.polyfillModulePreload;
- const { polyfillModulePreload, ...rest } = raw;
- raw = rest;
- if (deprecatedPolyfillModulePreload !== void 0) logger.warn("polyfillModulePreload is deprecated. Use modulePreload.polyfill instead.");
- if (deprecatedPolyfillModulePreload === false && raw.modulePreload === void 0) raw.modulePreload = { polyfill: false };
- const merged = mergeWithDefaults({
- ..._buildEnvironmentOptionsDefaults,
- cssCodeSplit: !raw.lib,
- minify: consumer === "server" ? false : "esbuild",
- ssr: consumer === "server",
- emitAssets: consumer === "client",
- createEnvironment: (name, config$2) => new BuildEnvironment(name, config$2)
- }, raw);
- if (merged.target === "baseline-widely-available") merged.target = ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET;
- if (merged.minify === "false") merged.minify = false;
- else if (merged.minify === true) merged.minify = "esbuild";
- const defaultModulePreload = { polyfill: true };
- return {
- ...merged,
- cssTarget: merged.cssTarget ?? merged.target,
- cssMinify: merged.cssMinify ?? (consumer === "server" ? "esbuild" : !!merged.minify),
- modulePreload: merged.modulePreload === false ? false : merged.modulePreload === true ? defaultModulePreload : {
- ...defaultModulePreload,
- ...merged.modulePreload
- }
- };
-}
-async function resolveBuildPlugins(config$2) {
- return {
- pre: [
- completeAmdWrapPlugin(),
- completeSystemWrapPlugin(),
- ...!config$2.isWorker ? [prepareOutDirPlugin()] : [],
- perEnvironmentPlugin("commonjs", (environment) => {
- const { commonjsOptions } = environment.config.build;
- return !Array.isArray(commonjsOptions.include) || commonjsOptions.include.length !== 0 ? commonjs(commonjsOptions) : false;
- }),
- dataURIPlugin(),
- perEnvironmentPlugin("vite:rollup-options-plugins", async (environment) => (await asyncFlatten(arraify(environment.config.build.rollupOptions.plugins))).filter(Boolean)),
- ...config$2.isWorker ? [webWorkerPostPlugin()] : []
- ],
- post: [
- buildImportAnalysisPlugin(config$2),
- buildEsbuildPlugin(),
- terserPlugin(config$2),
- ...!config$2.isWorker ? [
- licensePlugin(),
- manifestPlugin(),
- ssrManifestPlugin(),
- buildReporterPlugin(config$2)
- ] : [],
- buildLoadFallbackPlugin()
- ]
- };
-}
-/**
-* Bundles a single environment for production.
-* Returns a Promise containing the build result.
-*/
-async function build$1(inlineConfig = {}) {
- const builder = await createBuilder(inlineConfig, true);
- const environment = Object.values(builder.environments)[0];
- if (!environment) throw new Error("No environment found");
- return builder.build(environment);
-}
-function resolveConfigToBuild(inlineConfig = {}, patchConfig, patchPlugins) {
- return resolveConfig(inlineConfig, "build", "production", "production", false, patchConfig, patchPlugins);
-}
-function resolveRollupOptions(environment) {
- const { root, packageCache, build: options$1 } = environment.config;
- const libOptions = options$1.lib;
- const { logger } = environment;
- const ssr = environment.config.consumer === "server";
- const resolve$4 = (p) => path.resolve(root, p);
- const input = libOptions ? options$1.rollupOptions.input || (typeof libOptions.entry === "string" ? resolve$4(libOptions.entry) : Array.isArray(libOptions.entry) ? libOptions.entry.map(resolve$4) : Object.fromEntries(Object.entries(libOptions.entry).map(([alias$2, file]) => [alias$2, resolve$4(file)]))) : typeof options$1.ssr === "string" ? resolve$4(options$1.ssr) : options$1.rollupOptions.input || resolve$4("index.html");
- if (ssr && typeof input === "string" && input.endsWith(".html")) throw new Error("rollupOptions.input should not be an html file when building for SSR. Please specify a dedicated SSR entry.");
- if (options$1.cssCodeSplit === false) {
- if ((typeof input === "string" ? [input] : Array.isArray(input) ? input : Object.values(input)).some((input$1) => input$1.endsWith(".css"))) throw new Error(`When "build.cssCodeSplit: false" is set, "rollupOptions.input" should not include CSS files.`);
- }
- const outDir = resolve$4(options$1.outDir);
- const plugins$1 = environment.plugins.map((p) => injectEnvironmentToHooks(environment, p));
- const rollupOptions = {
- preserveEntrySignatures: ssr ? "allow-extension" : libOptions ? "strict" : false,
- cache: options$1.watch ? void 0 : false,
- ...options$1.rollupOptions,
- output: options$1.rollupOptions.output,
- input,
- plugins: plugins$1,
- external: options$1.rollupOptions.external,
- onLog(level, log$3) {
- onRollupLog(level, log$3, environment);
- }
- };
- const isSsrTargetWebworkerEnvironment = environment.name === "ssr" && environment.getTopLevelConfig().ssr?.target === "webworker";
- const buildOutputOptions = (output = {}) => {
- if (output.output) logger.warn("You've set \"rollupOptions.output.output\" in your config. This is deprecated and will override all Vite.js default output options. Please use \"rollupOptions.output\" instead.");
- if (output.file) throw new Error("Vite does not support \"rollupOptions.output.file\". Please use \"rollupOptions.output.dir\" and \"rollupOptions.output.entryFileNames\" instead.");
- if (output.sourcemap) logger.warnOnce(import_picocolors$4.default.yellow("Vite does not support \"rollupOptions.output.sourcemap\". Please use \"build.sourcemap\" instead."));
- const format$3 = output.format || "es";
- const jsExt = ssr && !isSsrTargetWebworkerEnvironment || libOptions ? resolveOutputJsExtension(format$3, findNearestPackageData(root, packageCache)?.data.type) : "js";
- return {
- dir: outDir,
- format: format$3,
- exports: "auto",
- sourcemap: options$1.sourcemap,
- name: libOptions ? libOptions.name : void 0,
- hoistTransitiveImports: libOptions ? false : void 0,
- generatedCode: "es2015",
- entryFileNames: ssr ? `[name].${jsExt}` : libOptions ? ({ name }) => resolveLibFilename(libOptions, format$3, name, root, jsExt, packageCache) : path.posix.join(options$1.assetsDir, `[name]-[hash].${jsExt}`),
- chunkFileNames: libOptions ? `[name]-[hash].${jsExt}` : path.posix.join(options$1.assetsDir, `[name]-[hash].${jsExt}`),
- assetFileNames: libOptions ? `[name].[ext]` : path.posix.join(options$1.assetsDir, `[name]-[hash].[ext]`),
- inlineDynamicImports: output.format === "umd" || output.format === "iife" || isSsrTargetWebworkerEnvironment && (typeof input === "string" || Object.keys(input).length === 1),
- ...output
- };
- };
- const outputs = resolveBuildOutputs(options$1.rollupOptions.output, libOptions, logger);
- if (Array.isArray(outputs)) rollupOptions.output = outputs.map(buildOutputOptions);
- else rollupOptions.output = buildOutputOptions(outputs);
- return rollupOptions;
-}
-/**
-* Build an App environment, or a App library (if libraryOptions is provided)
-**/
-async function buildEnvironment(environment) {
- const { logger, config: config$2 } = environment;
- const { root, build: options$1 } = config$2;
- logger.info(import_picocolors$4.default.cyan(`vite v${VERSION} ${import_picocolors$4.default.green(`building ${environment.name} environment for ${environment.config.mode}...`)}`));
- let bundle;
- let startTime;
- try {
- const rollupOptions = resolveRollupOptions(environment);
- if (options$1.watch) {
- logger.info(import_picocolors$4.default.cyan(`\nwatching for file changes...`));
- const resolvedOutDirs = getResolvedOutDirs(root, options$1.outDir, options$1.rollupOptions.output);
- const emptyOutDir = resolveEmptyOutDir(options$1.emptyOutDir, root, resolvedOutDirs, logger);
- const resolvedChokidarOptions = resolveChokidarOptions({
- ...(rollupOptions.watch || {}).chokidar,
- ...options$1.watch.chokidar
- }, resolvedOutDirs, emptyOutDir, environment.config.cacheDir);
- const { watch: watch$1 } = await import("rollup");
- const watcher = watch$1({
- ...rollupOptions,
- watch: {
- ...rollupOptions.watch,
- ...options$1.watch,
- chokidar: resolvedChokidarOptions
- }
- });
- watcher.on("event", (event) => {
- if (event.code === "BUNDLE_START") logger.info(import_picocolors$4.default.cyan(`\nbuild started...`));
- else if (event.code === "BUNDLE_END") {
- event.result.close();
- logger.info(import_picocolors$4.default.cyan(`built in ${event.duration}ms.`));
- } else if (event.code === "ERROR") {
- const e$1 = event.error;
- enhanceRollupError(e$1);
- clearLine();
- logger.error(e$1.message, { error: e$1 });
- }
- });
- return watcher;
- }
- const { rollup } = await import("rollup");
- startTime = Date.now();
- bundle = await rollup(rollupOptions);
- const res = [];
- for (const output of arraify(rollupOptions.output)) res.push(await bundle[options$1.write ? "write" : "generate"](output));
- logger.info(`${import_picocolors$4.default.green(`✓ built in ${displayTime(Date.now() - startTime)}`)}`);
- return Array.isArray(rollupOptions.output) ? res : res[0];
- } catch (e$1) {
- enhanceRollupError(e$1);
- clearLine();
- if (startTime) {
- logger.error(`${import_picocolors$4.default.red("✗")} Build failed in ${displayTime(Date.now() - startTime)}`);
- startTime = void 0;
- }
- throw e$1;
- } finally {
- if (bundle) await bundle.close();
- }
-}
-function enhanceRollupError(e$1) {
- const stackOnly = extractStack(e$1);
- let msg = import_picocolors$4.default.red((e$1.plugin ? `[${e$1.plugin}] ` : "") + e$1.message);
- if (e$1.loc && e$1.loc.file && e$1.loc.file !== e$1.id) msg += `\nfile: ${import_picocolors$4.default.cyan(`${e$1.loc.file}:${e$1.loc.line}:${e$1.loc.column}` + (e$1.id ? ` (${e$1.id})` : ""))}`;
- else if (e$1.id) msg += `\nfile: ${import_picocolors$4.default.cyan(e$1.id + (e$1.loc ? `:${e$1.loc.line}:${e$1.loc.column}` : ""))}`;
- if (e$1.frame) msg += `\n` + import_picocolors$4.default.yellow(normalizeCodeFrame(e$1.frame));
- e$1.message = msg;
- if (stackOnly !== void 0) e$1.stack = `${e$1.message}\n${stackOnly}`;
-}
-/**
-* The stack string usually contains a copy of the message at the start of the stack.
-* If the stack starts with the message, we remove it and just return the stack trace
-* portion. Otherwise the original stack trace is used.
-*/
-function extractStack(e$1) {
- const { stack, name = "Error", message } = e$1;
- if (!stack) return stack;
- const expectedPrefix = `${name}: ${message}\n`;
- if (stack.startsWith(expectedPrefix)) return stack.slice(expectedPrefix.length);
- return stack;
-}
-/**
-* Esbuild code frames have newlines at the start and end of the frame, rollup doesn't
-* This function normalizes the frame to match the esbuild format which has more pleasing padding
-*/
-function normalizeCodeFrame(frame) {
- return `\n${frame.replace(/^\n|\n$/g, "")}\n`;
-}
-function resolveOutputJsExtension(format$3, type = "commonjs") {
- if (type === "module") return format$3 === "cjs" || format$3 === "umd" ? "cjs" : "js";
- else return format$3 === "es" ? "mjs" : "js";
-}
-function resolveLibFilename(libOptions, format$3, entryName, root, extension$1, packageCache) {
- if (typeof libOptions.fileName === "function") return libOptions.fileName(format$3, entryName);
- const packageJson = findNearestMainPackageData(root, packageCache)?.data;
- const name = libOptions.fileName || (packageJson && typeof libOptions.entry === "string" ? getPkgName(packageJson.name) : entryName);
- if (!name) throw new Error("Name in package.json is required if option \"build.lib.fileName\" is not provided.");
- extension$1 ??= resolveOutputJsExtension(format$3, packageJson?.type);
- if (format$3 === "cjs" || format$3 === "es") return `${name}.${extension$1}`;
- return `${name}.${format$3}.${extension$1}`;
-}
-function resolveBuildOutputs(outputs, libOptions, logger) {
- if (libOptions) {
- const libHasMultipleEntries = typeof libOptions.entry !== "string" && Object.values(libOptions.entry).length > 1;
- const libFormats = libOptions.formats || (libHasMultipleEntries ? ["es", "cjs"] : ["es", "umd"]);
- if (!Array.isArray(outputs)) {
- if (libFormats.includes("umd") || libFormats.includes("iife")) {
- if (libHasMultipleEntries) throw new Error("Multiple entry points are not supported when output formats include \"umd\" or \"iife\".");
- if (!libOptions.name) throw new Error("Option \"build.lib.name\" is required when output formats include \"umd\" or \"iife\".");
- }
- return libFormats.map((format$3) => ({
- ...outputs,
- format: format$3
- }));
- }
- if (libOptions.formats) logger.warn(import_picocolors$4.default.yellow("\"build.lib.formats\" will be ignored because \"build.rollupOptions.output\" is already an array format."));
- outputs.forEach((output) => {
- if ((output.format === "umd" || output.format === "iife") && !output.name) throw new Error("Entries in \"build.rollupOptions.output\" must specify \"name\" when the format is \"umd\" or \"iife\".");
- });
- }
- return outputs;
-}
-const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`];
-const dynamicImportWarningIgnoreList = [`Unsupported expression`, `statically analyzed`];
-function clearLine() {
- if (process.stdout.isTTY && !process.env.CI) {
- process.stdout.clearLine(0);
- process.stdout.cursorTo(0);
- }
-}
-function onRollupLog(level, log$3, environment) {
- const debugLogger = createDebugger("vite:build");
- const viteLog = (logLeveling, rawLogging) => {
- const logging = typeof rawLogging === "object" ? rawLogging : { message: rawLogging };
- if (logging.code === "UNRESOLVED_IMPORT") {
- const id = logging.id;
- const exporter = logging.exporter;
- if (!id || !id.endsWith("?commonjs-external")) throw new Error(`[vite]: Rollup failed to resolve import "${exporter}" from "${id}".\nThis is most likely unintended because it can break your application at runtime.\nIf you do want to externalize this module explicitly add it to\n\`build.rollupOptions.external\``);
- }
- if (logLeveling === "warn") {
- if (logging.plugin === "rollup-plugin-dynamic-import-variables" && dynamicImportWarningIgnoreList.some((msg) => logging.message.includes(msg))) return;
- if (warningIgnoreList.includes(logging.code)) return;
- }
- switch (logLeveling) {
- case "info":
- environment.logger.info(logging.message);
- return;
- case "warn":
- environment.logger.warn(import_picocolors$4.default.yellow(logging.message));
- return;
- case "error":
- environment.logger.error(import_picocolors$4.default.red(logging.message));
- return;
- case "debug":
- debugLogger?.(logging.message);
- return;
- default:
- environment.logger.info(logging.message);
- return;
- }
- };
- clearLine();
- const userOnLog = environment.config.build.rollupOptions?.onLog;
- const userOnWarn = environment.config.build.rollupOptions?.onwarn;
- if (userOnLog) if (userOnWarn) userOnLog(level, log$3, normalizeUserOnWarn(userOnWarn, viteLog));
- else userOnLog(level, log$3, viteLog);
- else if (userOnWarn) normalizeUserOnWarn(userOnWarn, viteLog)(level, log$3);
- else viteLog(level, log$3);
-}
-function normalizeUserOnWarn(userOnWarn, defaultHandler) {
- return (logLevel, logging) => {
- if (logLevel === "warn") userOnWarn(normalizeLog(logging), (log$3) => defaultHandler("warn", typeof log$3 === "function" ? log$3() : log$3));
- else defaultHandler(logLevel, logging);
- };
-}
-const normalizeLog = (log$3) => typeof log$3 === "string" ? { message: log$3 } : log$3;
-function resolveUserExternal(user, id, parentId, isResolved) {
- if (typeof user === "function") return user(id, parentId, isResolved);
- else if (Array.isArray(user)) return user.some((test) => isExternal(id, test));
- else return isExternal(id, user);
-}
-function isExternal(id, test) {
- if (typeof test === "string") return id === test;
- else return test.test(id);
-}
-function injectEnvironmentToHooks(environment, plugin) {
- const { resolveId, load: load$2, transform: transform$2 } = plugin;
- const clone$1 = { ...plugin };
- for (const hook of Object.keys(clone$1)) switch (hook) {
- case "resolveId":
- clone$1[hook] = wrapEnvironmentResolveId(environment, resolveId, plugin.name);
- break;
- case "load":
- clone$1[hook] = wrapEnvironmentLoad(environment, load$2, plugin.name);
- break;
- case "transform":
- clone$1[hook] = wrapEnvironmentTransform(environment, transform$2, plugin.name);
- break;
- default:
- if (ROLLUP_HOOKS.includes(hook)) clone$1[hook] = wrapEnvironmentHook(environment, clone$1[hook]);
- break;
- }
- return clone$1;
-}
-function wrapEnvironmentResolveId(environment, hook, pluginName) {
- if (!hook) return;
- const fn = getHookHandler(hook);
- const handler = function(id, importer, options$1) {
- return fn.call(injectEnvironmentInContext(this, environment), id, importer, injectSsrFlag(options$1, environment, pluginName));
- };
- if ("handler" in hook) return {
- ...hook,
- handler
- };
- else return handler;
-}
-function wrapEnvironmentLoad(environment, hook, pluginName) {
- if (!hook) return;
- const fn = getHookHandler(hook);
- const handler = function(id, ...args) {
- return fn.call(injectEnvironmentInContext(this, environment), id, injectSsrFlag(args[0], environment, pluginName));
- };
- if ("handler" in hook) return {
- ...hook,
- handler
- };
- else return handler;
-}
-function wrapEnvironmentTransform(environment, hook, pluginName) {
- if (!hook) return;
- const fn = getHookHandler(hook);
- const handler = function(code, importer, ...args) {
- return fn.call(injectEnvironmentInContext(this, environment), code, importer, injectSsrFlag(args[0], environment, pluginName));
- };
- if ("handler" in hook) return {
- ...hook,
- handler
- };
- else return handler;
-}
-function wrapEnvironmentHook(environment, hook) {
- if (!hook) return;
- const fn = getHookHandler(hook);
- if (typeof fn !== "function") return hook;
- const handler = function(...args) {
- return fn.call(injectEnvironmentInContext(this, environment), ...args);
- };
- if ("handler" in hook) return {
- ...hook,
- handler
- };
- else return handler;
-}
-function injectEnvironmentInContext(context, environment) {
- context.meta.viteVersion ??= VERSION;
- context.environment ??= environment;
- return context;
-}
-function injectSsrFlag(options$1, environment, pluginName) {
- let ssr = environment.config.consumer === "server";
- const newOptions = {
- ...options$1 ?? {},
- ssr
- };
- if (isFutureDeprecationEnabled(environment?.getTopLevelConfig(), "removePluginHookSsrArgument")) Object.defineProperty(newOptions, "ssr", {
- get() {
- warnFutureDeprecation(environment?.getTopLevelConfig(), "removePluginHookSsrArgument", `Used in plugin "${pluginName}".`);
- return ssr;
- },
- set(v) {
- ssr = v;
- }
- });
- return newOptions;
-}
-const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
-const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
-const backSlashRegEx = /\\/g;
-function escapeId(id) {
- if (!needsEscapeRegEx.test(id)) return id;
- return id.replace(backSlashRegEx, "\\\\").replace(quoteNewlineRegEx, "\\$1");
-}
-const getResolveUrl = (path$13, URL$4 = "URL") => `new ${URL$4}(${path$13}).href`;
-const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ""}document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || document.baseURI`);
-const getFileUrlFromFullPath = (path$13) => `require('u' + 'rl').pathToFileURL(${path$13}).href`;
-const getFileUrlFromRelativePath = (path$13) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path$13)}'`);
-const customRelativeUrlMechanisms = {
- amd: (relativePath) => {
- if (relativePath[0] !== ".") relativePath = "./" + relativePath;
- return getResolveUrl(`require.toUrl('${escapeId(relativePath)}'), document.baseURI`);
- },
- cjs: (relativePath) => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
- es: (relativePath) => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', import.meta.url`),
- iife: (relativePath) => getRelativeUrlFromDocument(relativePath),
- system: (relativePath) => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', module.meta.url`),
- umd: (relativePath) => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`,
- "worker-iife": (relativePath) => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', self.location.href`)
-};
-function toOutputFilePathInJS(environment, filename, type, hostId, hostType, toRelative) {
- const { experimental, base, decodedBase } = environment.config;
- const ssr = environment.config.consumer === "server";
- const { renderBuiltUrl } = experimental;
- let relative$3 = base === "" || base === "./";
- if (renderBuiltUrl) {
- const result = renderBuiltUrl(filename, {
- hostId,
- hostType,
- type,
- ssr
- });
- if (typeof result === "object") {
- if (result.runtime) return { runtime: result.runtime };
- if (typeof result.relative === "boolean") relative$3 = result.relative;
- } else if (result) return result;
- }
- if (relative$3 && !ssr) return toRelative(filename, hostId);
- return joinUrlSegments(decodedBase, filename);
-}
-function createToImportMetaURLBasedRelativeRuntime(format$3, isWorker) {
- const toRelativePath$1 = customRelativeUrlMechanisms[isWorker && format$3 === "iife" ? "worker-iife" : format$3];
- return (filename, importer) => ({ runtime: toRelativePath$1(path.posix.relative(path.dirname(importer), filename)) });
-}
-function toOutputFilePathWithoutRuntime(filename, type, hostId, hostType, config$2, toRelative) {
- const { renderBuiltUrl } = config$2.experimental;
- let relative$3 = config$2.base === "" || config$2.base === "./";
- if (renderBuiltUrl) {
- const result = renderBuiltUrl(filename, {
- hostId,
- hostType,
- type,
- ssr: !!config$2.build.ssr
- });
- if (typeof result === "object") {
- if (result.runtime) throw new Error(`{ runtime: "${result.runtime}" } is not supported for assets in ${hostType} files: ${filename}`);
- if (typeof result.relative === "boolean") relative$3 = result.relative;
- } else if (result) return result;
- }
- if (relative$3 && !config$2.build.ssr) return toRelative(filename, hostId);
- else return joinUrlSegments(config$2.decodedBase, filename);
-}
-const toOutputFilePathInCss = toOutputFilePathWithoutRuntime;
-const toOutputFilePathInHtml = toOutputFilePathWithoutRuntime;
-var BuildEnvironment = class extends BaseEnvironment {
- mode = "build";
- isBuilt = false;
- constructor(name, config$2, setup$1) {
- let options$1 = config$2.environments[name];
- if (!options$1) throw new Error(`Environment "${name}" is not defined in the config.`);
- if (setup$1?.options) options$1 = mergeConfig(options$1, setup$1.options);
- super(name, config$2, options$1);
- }
- async init() {
- if (this._initiated) return;
- this._initiated = true;
- }
-};
-const _builderOptionsDefaults = Object.freeze({
- sharedConfigBuild: false,
- sharedPlugins: false
-});
-const builderOptionsDefaults = _builderOptionsDefaults;
-function resolveBuilderOptions(options$1) {
- if (!options$1) return;
- return mergeWithDefaults({
- ..._builderOptionsDefaults,
- buildApp: async () => {}
- }, options$1);
-}
-/**
-* Creates a ViteBuilder to orchestrate building multiple environments.
-* @experimental
-*/
-async function createBuilder(inlineConfig = {}, useLegacyBuilder = false) {
- const patchConfig = (resolved) => {
- if (!(useLegacyBuilder ?? !resolved.builder)) return;
- resolved.build = { ...resolved.environments[resolved.build.ssr ? "ssr" : "client"].build };
- };
- const config$2 = await resolveConfigToBuild(inlineConfig, patchConfig);
- useLegacyBuilder ??= !config$2.builder;
- const configBuilder = config$2.builder ?? resolveBuilderOptions({});
- const environments = {};
- const builder = {
- environments,
- config: config$2,
- async buildApp() {
- const pluginContext = new BasicMinimalPluginContext({
- ...basePluginContextMeta,
- watchMode: false
- }, config$2.logger);
- let configBuilderBuildAppCalled = false;
- for (const p of config$2.getSortedPlugins("buildApp")) {
- const hook = p.buildApp;
- if (!configBuilderBuildAppCalled && typeof hook === "object" && hook.order === "post") {
- configBuilderBuildAppCalled = true;
- await configBuilder.buildApp(builder);
- }
- await getHookHandler(hook).call(pluginContext, builder);
- }
- if (!configBuilderBuildAppCalled) await configBuilder.buildApp(builder);
- if (Object.values(builder.environments).every((environment) => !environment.isBuilt)) for (const environment of Object.values(builder.environments)) await builder.build(environment);
- },
- async build(environment) {
- const output = await buildEnvironment(environment);
- environment.isBuilt = true;
- return output;
- }
- };
- async function setupEnvironment(name, config$3) {
- const environment = await config$3.build.createEnvironment(name, config$3);
- await environment.init();
- environments[name] = environment;
- }
- if (useLegacyBuilder) await setupEnvironment(config$2.build.ssr ? "ssr" : "client", config$2);
- else {
- const environmentConfigs = [];
- for (const environmentName of Object.keys(config$2.environments)) {
- let environmentConfig = config$2;
- if (!configBuilder.sharedConfigBuild) {
- const patchConfig$1 = (resolved) => {
- resolved.build = { ...resolved.environments[environmentName].build };
- };
- const patchPlugins = (resolvedPlugins) => {
- let j = 0;
- for (let i$1 = 0; i$1 < resolvedPlugins.length; i$1++) {
- const environmentPlugin = resolvedPlugins[i$1];
- if (configBuilder.sharedPlugins || environmentPlugin.sharedDuringBuild) {
- for (let k = j; k < config$2.plugins.length; k++) if (environmentPlugin.name === config$2.plugins[k].name) {
- resolvedPlugins[i$1] = config$2.plugins[k];
- j = k + 1;
- break;
- }
- }
- }
- };
- environmentConfig = await resolveConfigToBuild(inlineConfig, patchConfig$1, patchPlugins);
- }
- environmentConfigs.push([environmentName, environmentConfig]);
- }
- await Promise.all(environmentConfigs.map(async ([environmentName, environmentConfig]) => await setupEnvironment(environmentName, environmentConfig)));
- }
- return builder;
-}
-
-//#endregion
-//#region src/node/ssr/fetchModule.ts
-/**
-* Fetch module information for Vite runner.
-* @experimental
-*/
-async function fetchModule(environment, url$3, importer, options$1 = {}) {
- if (url$3.startsWith("data:") || isBuiltin(environment.config.resolve.builtins, url$3)) return {
- externalize: url$3,
- type: "builtin"
- };
- const isFileUrl$1 = url$3.startsWith("file://");
- if (isExternalUrl(url$3) && !isFileUrl$1) return {
- externalize: url$3,
- type: "network"
- };
- if (!isFileUrl$1 && importer && url$3[0] !== "." && url$3[0] !== "/") {
- const { isProduction, root } = environment.config;
- const { externalConditions, dedupe, preserveSymlinks } = environment.config.resolve;
- const resolved = tryNodeResolve(url$3, importer, {
- mainFields: ["main"],
- conditions: externalConditions,
- externalConditions,
- external: [],
- noExternal: [],
- extensions: [
- ".js",
- ".cjs",
- ".json"
- ],
- dedupe,
- preserveSymlinks,
- isBuild: false,
- isProduction,
- root,
- packageCache: environment.config.packageCache,
- builtins: environment.config.resolve.builtins
- });
- if (!resolved) {
- const err$2 = /* @__PURE__ */ new Error(`Cannot find module '${url$3}' imported from '${importer}'`);
- err$2.code = "ERR_MODULE_NOT_FOUND";
- throw err$2;
- }
- return {
- externalize: pathToFileURL(resolved.id).toString(),
- type: isFilePathESM(resolved.id, environment.config.packageCache) ? "module" : "commonjs"
- };
- }
- url$3 = unwrapId(url$3);
- const mod = await environment.moduleGraph.ensureEntryFromUrl(url$3);
- const cached = !!mod.transformResult;
- if (options$1.cached && cached) return { cache: true };
- let result = await environment.transformRequest(url$3);
- if (!result) throw new Error(`[vite] transform failed for module '${url$3}'${importer ? ` imported from '${importer}'` : ""}.`);
- if (options$1.inlineSourceMap !== false) result = inlineSourceMap(mod, result, options$1.startOffset);
- if (result.code[0] === "#") result.code = result.code.replace(/^#!.*/, (s) => " ".repeat(s.length));
- return {
- code: result.code,
- file: mod.file,
- id: mod.id,
- url: mod.url,
- invalidate: !cached
- };
-}
-const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`, "gm");
-function inlineSourceMap(mod, result, startOffset) {
- const map$1 = result.map;
- let code = result.code;
- if (!map$1 || !("version" in map$1) || code.includes(MODULE_RUNNER_SOURCEMAPPING_SOURCE)) return result;
- OTHER_SOURCE_MAP_REGEXP.lastIndex = 0;
- if (OTHER_SOURCE_MAP_REGEXP.test(code)) code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
- const sourceMap = startOffset ? Object.assign({}, map$1, { mappings: ";".repeat(startOffset) + map$1.mappings }) : map$1;
- result.code = `${code.trimEnd()}\n//# sourceURL=${mod.id}\n${MODULE_RUNNER_SOURCEMAPPING_SOURCE}\n//# ${SOURCEMAPPING_URL}=${genSourceMapUrl(sourceMap)}\n`;
- return result;
-}
-
-//#endregion
-//#region src/node/optimizer/optimizer.ts
-var import_picocolors$3 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const debug$1 = createDebugger("vite:deps");
-/**
-* The amount to wait for requests to register newly found dependencies before triggering
-* a re-bundle + page reload
-*/
-const debounceMs = 100;
-function createDepsOptimizer(environment) {
- const { logger } = environment;
- const sessionTimestamp = Date.now().toString();
- let debounceProcessingHandle;
- let closed = false;
- const options$1 = environment.config.optimizeDeps;
- const { noDiscovery, holdUntilCrawlEnd } = options$1;
- let metadata = initDepsOptimizerMetadata(environment, sessionTimestamp);
- const depsOptimizer = {
- init: init$2,
- metadata,
- registerMissingImport,
- run: () => debouncedProcessing(0),
- isOptimizedDepFile: createIsOptimizedDepFile(environment),
- isOptimizedDepUrl: createIsOptimizedDepUrl(environment),
- getOptimizedDepId: (depInfo) => `${depInfo.file}?v=${depInfo.browserHash}`,
- close: close$1,
- options: options$1
- };
- let newDepsDiscovered = false;
- let newDepsToLog = [];
- let newDepsToLogHandle;
- const logNewlyDiscoveredDeps = () => {
- if (newDepsToLog.length) {
- logger.info(import_picocolors$3.default.green(`✨ new dependencies optimized: ${depsLogString(newDepsToLog)}`), { timestamp: true });
- newDepsToLog = [];
- }
- };
- let discoveredDepsWhileScanning = [];
- const logDiscoveredDepsWhileScanning = () => {
- if (discoveredDepsWhileScanning.length) {
- logger.info(import_picocolors$3.default.green(`✨ discovered while scanning: ${depsLogString(discoveredDepsWhileScanning)}`), { timestamp: true });
- discoveredDepsWhileScanning = [];
- }
- };
- let depOptimizationProcessing = promiseWithResolvers();
- let depOptimizationProcessingQueue = [];
- const resolveEnqueuedProcessingPromises = () => {
- for (const processing of depOptimizationProcessingQueue) processing.resolve();
- depOptimizationProcessingQueue = [];
- };
- let enqueuedRerun;
- let currentlyProcessing = false;
- let firstRunCalled = false;
- let warnAboutMissedDependencies = false;
- let waitingForCrawlEnd = false;
- let optimizationResult;
- let discover;
- async function close$1() {
- closed = true;
- await Promise.allSettled([
- discover?.cancel(),
- depsOptimizer.scanProcessing,
- optimizationResult?.cancel()
- ]);
- }
- let inited = false;
- async function init$2() {
- if (inited) return;
- inited = true;
- const cachedMetadata = await loadCachedDepOptimizationMetadata(environment);
- firstRunCalled = !!cachedMetadata;
- metadata = depsOptimizer.metadata = cachedMetadata || initDepsOptimizerMetadata(environment, sessionTimestamp);
- if (!cachedMetadata) {
- waitingForCrawlEnd = true;
- currentlyProcessing = true;
- const manuallyIncludedDeps = {};
- await addManuallyIncludedOptimizeDeps(environment, manuallyIncludedDeps);
- const manuallyIncludedDepsInfo = toDiscoveredDependencies(environment, manuallyIncludedDeps, sessionTimestamp);
- for (const depInfo of Object.values(manuallyIncludedDepsInfo)) {
- addOptimizedDepInfo(metadata, "discovered", {
- ...depInfo,
- processing: depOptimizationProcessing.promise
- });
- newDepsDiscovered = true;
- }
- environment.waitForRequestsIdle().then(onCrawlEnd);
- if (noDiscovery) runOptimizer();
- else depsOptimizer.scanProcessing = new Promise((resolve$4) => {
- (async () => {
- try {
- debug$1?.(import_picocolors$3.default.green(`scanning for dependencies...`));
- let deps;
- try {
- discover = discoverProjectDependencies(devToScanEnvironment(environment));
- deps = await discover.result;
- discover = void 0;
- } catch (e$1) {
- environment.logger.error(import_picocolors$3.default.red("(!) Failed to run dependency scan. Skipping dependency pre-bundling. " + e$1.stack));
- return;
- }
- const manuallyIncluded = Object.keys(manuallyIncludedDepsInfo);
- discoveredDepsWhileScanning.push(...Object.keys(metadata.discovered).filter((dep) => !deps[dep] && !manuallyIncluded.includes(dep)));
- for (const id of Object.keys(deps)) if (!metadata.discovered[id]) addMissingDep(id, deps[id]);
- const knownDeps = prepareKnownDeps();
- startNextDiscoveredBatch();
- optimizationResult = runOptimizeDeps(environment, knownDeps);
- if (!holdUntilCrawlEnd) optimizationResult.result.then((result) => {
- if (!waitingForCrawlEnd) return;
- optimizationResult = void 0;
- runOptimizer(result);
- });
- } catch (e$1) {
- logger.error(e$1.stack || e$1.message);
- } finally {
- resolve$4();
- depsOptimizer.scanProcessing = void 0;
- }
- })();
- });
- }
- }
- function startNextDiscoveredBatch() {
- newDepsDiscovered = false;
- depOptimizationProcessingQueue.push(depOptimizationProcessing);
- depOptimizationProcessing = promiseWithResolvers();
- }
- function prepareKnownDeps() {
- const knownDeps = {};
- const metadata$1 = depsOptimizer.metadata;
- for (const dep of Object.keys(metadata$1.optimized)) knownDeps[dep] = { ...metadata$1.optimized[dep] };
- for (const dep of Object.keys(metadata$1.discovered)) {
- const { processing, ...info } = metadata$1.discovered[dep];
- knownDeps[dep] = info;
- }
- return knownDeps;
- }
- async function runOptimizer(preRunResult) {
- const isRerun = firstRunCalled;
- firstRunCalled = true;
- enqueuedRerun = void 0;
- if (debounceProcessingHandle) clearTimeout(debounceProcessingHandle);
- if (closed) {
- currentlyProcessing = false;
- depOptimizationProcessing.resolve();
- resolveEnqueuedProcessingPromises();
- return;
- }
- currentlyProcessing = true;
- try {
- let processingResult;
- if (preRunResult) processingResult = preRunResult;
- else {
- const knownDeps = prepareKnownDeps();
- startNextDiscoveredBatch();
- optimizationResult = runOptimizeDeps(environment, knownDeps);
- processingResult = await optimizationResult.result;
- optimizationResult = void 0;
- }
- if (closed) {
- currentlyProcessing = false;
- processingResult.cancel();
- resolveEnqueuedProcessingPromises();
- return;
- }
- const newData = processingResult.metadata;
- const needsInteropMismatch = findInteropMismatches(metadata.discovered, newData.optimized);
- const needsReload = needsInteropMismatch.length > 0 || metadata.hash !== newData.hash || Object.keys(metadata.optimized).some((dep) => {
- return metadata.optimized[dep].fileHash !== newData.optimized[dep].fileHash;
- });
- const commitProcessing = async () => {
- await processingResult.commit();
- for (const id in metadata.discovered) if (!newData.optimized[id]) addOptimizedDepInfo(newData, "discovered", metadata.discovered[id]);
- if (!needsReload) {
- newData.browserHash = metadata.browserHash;
- for (const dep in newData.chunks) newData.chunks[dep].browserHash = metadata.browserHash;
- for (const dep in newData.optimized) newData.optimized[dep].browserHash = (metadata.optimized[dep] || metadata.discovered[dep]).browserHash;
- }
- for (const o$1 in newData.optimized) {
- const discovered = metadata.discovered[o$1];
- if (discovered) {
- const optimized = newData.optimized[o$1];
- discovered.browserHash = optimized.browserHash;
- discovered.fileHash = optimized.fileHash;
- discovered.needsInterop = optimized.needsInterop;
- discovered.processing = void 0;
- }
- }
- if (isRerun) newDepsToLog.push(...Object.keys(newData.optimized).filter((dep) => !metadata.optimized[dep]));
- metadata = depsOptimizer.metadata = newData;
- resolveEnqueuedProcessingPromises();
- };
- if (!needsReload) {
- await commitProcessing();
- if (!debug$1) {
- if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
- newDepsToLogHandle = setTimeout(() => {
- newDepsToLogHandle = void 0;
- logNewlyDiscoveredDeps();
- if (warnAboutMissedDependencies) {
- logDiscoveredDepsWhileScanning();
- logger.info(import_picocolors$3.default.magenta(`❗ add these dependencies to optimizeDeps.include to speed up cold start`), { timestamp: true });
- warnAboutMissedDependencies = false;
- }
- }, 2 * debounceMs);
- } else debug$1(import_picocolors$3.default.green(`✨ ${!isRerun ? `dependencies optimized` : `optimized dependencies unchanged`}`));
- } else if (newDepsDiscovered) {
- processingResult.cancel();
- debug$1?.(import_picocolors$3.default.green(`✨ delaying reload as new dependencies have been found...`));
- } else {
- await commitProcessing();
- if (!debug$1) {
- if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
- newDepsToLogHandle = void 0;
- logNewlyDiscoveredDeps();
- if (warnAboutMissedDependencies) {
- logDiscoveredDepsWhileScanning();
- logger.info(import_picocolors$3.default.magenta(`❗ add these dependencies to optimizeDeps.include to avoid a full page reload during cold start`), { timestamp: true });
- warnAboutMissedDependencies = false;
- }
- }
- logger.info(import_picocolors$3.default.green(`✨ optimized dependencies changed. reloading`), { timestamp: true });
- if (needsInteropMismatch.length > 0) logger.warn(`Mixed ESM and CJS detected in ${import_picocolors$3.default.yellow(needsInteropMismatch.join(", "))}, add ${needsInteropMismatch.length === 1 ? "it" : "them"} to optimizeDeps.needsInterop to speed up cold start`, { timestamp: true });
- fullReload();
- }
- } catch (e$1) {
- logger.error(import_picocolors$3.default.red(`error while updating dependencies:\n${e$1.stack}`), {
- timestamp: true,
- error: e$1
- });
- resolveEnqueuedProcessingPromises();
- metadata.discovered = {};
- }
- currentlyProcessing = false;
- enqueuedRerun?.();
- }
- function fullReload() {
- environment.moduleGraph.invalidateAll();
- environment.hot.send({
- type: "full-reload",
- path: "*"
- });
- }
- async function rerun() {
- const depsString = depsLogString(Object.keys(metadata.discovered));
- debug$1?.(import_picocolors$3.default.green(`new dependencies found: ${depsString}`));
- runOptimizer();
- }
- function getDiscoveredBrowserHash(hash$1, deps, missing) {
- return getHash(hash$1 + JSON.stringify(deps) + JSON.stringify(missing) + sessionTimestamp);
- }
- function registerMissingImport(id, resolved) {
- const optimized = metadata.optimized[id];
- if (optimized) return optimized;
- const chunk = metadata.chunks[id];
- if (chunk) return chunk;
- let missing = metadata.discovered[id];
- if (missing) return missing;
- missing = addMissingDep(id, resolved);
- if (!waitingForCrawlEnd) debouncedProcessing();
- return missing;
- }
- function addMissingDep(id, resolved) {
- newDepsDiscovered = true;
- return addOptimizedDepInfo(metadata, "discovered", {
- id,
- file: getOptimizedDepPath(environment, id),
- src: resolved,
- browserHash: getDiscoveredBrowserHash(metadata.hash, depsFromOptimizedDepInfo(metadata.optimized), depsFromOptimizedDepInfo(metadata.discovered)),
- processing: depOptimizationProcessing.promise,
- exportsData: extractExportsData(environment, resolved)
- });
- }
- function debouncedProcessing(timeout$1 = debounceMs) {
- enqueuedRerun = void 0;
- if (debounceProcessingHandle) clearTimeout(debounceProcessingHandle);
- if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
- newDepsToLogHandle = void 0;
- debounceProcessingHandle = setTimeout(() => {
- debounceProcessingHandle = void 0;
- enqueuedRerun = rerun;
- if (!currentlyProcessing) enqueuedRerun();
- }, timeout$1);
- }
- async function onCrawlEnd() {
- waitingForCrawlEnd = false;
- debug$1?.(import_picocolors$3.default.green(`✨ static imports crawl ended`));
- if (closed) return;
- await depsOptimizer.scanProcessing;
- if (optimizationResult && !options$1.noDiscovery) {
- const afterScanResult = optimizationResult.result;
- optimizationResult = void 0;
- const result = await afterScanResult;
- currentlyProcessing = false;
- const crawlDeps = Object.keys(metadata.discovered);
- const scanDeps = Object.keys(result.metadata.optimized);
- if (scanDeps.length === 0 && crawlDeps.length === 0) {
- debug$1?.(import_picocolors$3.default.green(`✨ no dependencies found by the scanner or crawling static imports`));
- startNextDiscoveredBatch();
- runOptimizer(result);
- return;
- }
- const needsInteropMismatch = findInteropMismatches(metadata.discovered, result.metadata.optimized);
- const scannerMissedDeps = crawlDeps.some((dep) => !scanDeps.includes(dep));
- if (needsInteropMismatch.length > 0 || scannerMissedDeps) {
- result.cancel();
- for (const dep of scanDeps) if (!crawlDeps.includes(dep)) addMissingDep(dep, result.metadata.optimized[dep].src);
- if (scannerMissedDeps) debug$1?.(import_picocolors$3.default.yellow(`✨ new dependencies were found while crawling that weren't detected by the scanner`));
- debug$1?.(import_picocolors$3.default.green(`✨ re-running optimizer`));
- debouncedProcessing(0);
- } else {
- debug$1?.(import_picocolors$3.default.green(`✨ using post-scan optimizer result, the scanner found every used dependency`));
- startNextDiscoveredBatch();
- runOptimizer(result);
- }
- } else if (!holdUntilCrawlEnd) {
- if (newDepsDiscovered) {
- debug$1?.(import_picocolors$3.default.green(`✨ new dependencies were found while crawling static imports, re-running optimizer`));
- warnAboutMissedDependencies = true;
- debouncedProcessing(0);
- }
- } else {
- const crawlDeps = Object.keys(metadata.discovered);
- currentlyProcessing = false;
- if (crawlDeps.length === 0) {
- debug$1?.(import_picocolors$3.default.green(`✨ no dependencies found while crawling the static imports`));
- firstRunCalled = true;
- }
- debouncedProcessing(0);
- }
- }
- return depsOptimizer;
-}
-function createExplicitDepsOptimizer(environment) {
- const depsOptimizer = {
- metadata: initDepsOptimizerMetadata(environment),
- isOptimizedDepFile: createIsOptimizedDepFile(environment),
- isOptimizedDepUrl: createIsOptimizedDepUrl(environment),
- getOptimizedDepId: (depInfo) => `${depInfo.file}?v=${depInfo.browserHash}`,
- registerMissingImport: () => {
- throw new Error(`Vite Internal Error: registerMissingImport is not supported in dev ${environment.name}`);
- },
- init: init$2,
- run: () => {},
- close: async () => {},
- options: environment.config.optimizeDeps
- };
- let inited = false;
- async function init$2() {
- if (inited) return;
- inited = true;
- depsOptimizer.metadata = await optimizeExplicitEnvironmentDeps(environment);
- }
- return depsOptimizer;
-}
-function findInteropMismatches(discovered, optimized) {
- const needsInteropMismatch = [];
- for (const dep in discovered) {
- const discoveredDepInfo = discovered[dep];
- if (discoveredDepInfo.needsInterop === void 0) continue;
- const depInfo = optimized[dep];
- if (!depInfo) continue;
- if (depInfo.needsInterop !== discoveredDepInfo.needsInterop) {
- needsInteropMismatch.push(dep);
- debug$1?.(import_picocolors$3.default.cyan(`✨ needsInterop mismatch detected for ${dep}`));
- }
- }
- return needsInteropMismatch;
-}
-
-//#endregion
-//#region src/node/server/moduleGraph.ts
-var EnvironmentModuleNode = class {
- environment;
- /**
- * Public served url path, starts with /
- */
- url;
- /**
- * Resolved file system path + query
- */
- id = null;
- file = null;
- type;
- info;
- meta;
- importers = /* @__PURE__ */ new Set();
- importedModules = /* @__PURE__ */ new Set();
- acceptedHmrDeps = /* @__PURE__ */ new Set();
- acceptedHmrExports = null;
- importedBindings = null;
- isSelfAccepting;
- transformResult = null;
- ssrModule = null;
- ssrError = null;
- lastHMRTimestamp = 0;
- /**
- * `import.meta.hot.invalidate` is called by the client.
- * If there's multiple clients, multiple `invalidate` request is received.
- * This property is used to dedupe those request to avoid multiple updates happening.
- * @internal
- */
- lastHMRInvalidationReceived = false;
- lastInvalidationTimestamp = 0;
- /**
- * If the module only needs to update its imports timestamp (e.g. within an HMR chain),
- * it is considered soft-invalidated. In this state, its `transformResult` should exist,
- * and the next `transformRequest` for this module will replace the timestamps.
- *
- * By default the value is `undefined` if it's not soft/hard-invalidated. If it gets
- * soft-invalidated, this will contain the previous `transformResult` value. If it gets
- * hard-invalidated, this will be set to `'HARD_INVALIDATED'`.
- * @internal
- */
- invalidationState;
- /**
- * The module urls that are statically imported in the code. This information is separated
- * out from `importedModules` as only importers that statically import the module can be
- * soft invalidated. Other imports (e.g. watched files) needs the importer to be hard invalidated.
- * @internal
- */
- staticImportedUrls;
- /**
- * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870
- */
- constructor(url$3, environment, setIsSelfAccepting = true) {
- this.environment = environment;
- this.url = url$3;
- this.type = isDirectCSSRequest(url$3) ? "css" : "js";
- if (setIsSelfAccepting) this.isSelfAccepting = false;
- }
-};
-var EnvironmentModuleGraph = class {
- environment;
- urlToModuleMap = /* @__PURE__ */ new Map();
- idToModuleMap = /* @__PURE__ */ new Map();
- etagToModuleMap = /* @__PURE__ */ new Map();
- fileToModulesMap = /* @__PURE__ */ new Map();
- /**
- * @internal
- */
- _unresolvedUrlToModuleMap = /* @__PURE__ */ new Map();
- /**
- * @internal
- */
- _resolveId;
- /** @internal */
- _hasResolveFailedErrorModules = /* @__PURE__ */ new Set();
- constructor(environment, resolveId) {
- this.environment = environment;
- this._resolveId = resolveId;
- }
- async getModuleByUrl(rawUrl) {
- rawUrl = removeImportQuery(removeTimestampQuery(rawUrl));
- const mod = this._getUnresolvedUrlToModule(rawUrl);
- if (mod) return mod;
- const [url$3] = await this._resolveUrl(rawUrl);
- return this.urlToModuleMap.get(url$3);
- }
- getModuleById(id) {
- return this.idToModuleMap.get(removeTimestampQuery(id));
- }
- getModulesByFile(file) {
- return this.fileToModulesMap.get(file);
- }
- onFileChange(file) {
- const mods = this.getModulesByFile(file);
- if (mods) {
- const seen$1 = /* @__PURE__ */ new Set();
- mods.forEach((mod) => {
- this.invalidateModule(mod, seen$1);
- });
- }
- }
- onFileDelete(file) {
- const mods = this.getModulesByFile(file);
- if (mods) mods.forEach((mod) => {
- mod.importedModules.forEach((importedMod) => {
- importedMod.importers.delete(mod);
- });
- });
- }
- invalidateModule(mod, seen$1 = /* @__PURE__ */ new Set(), timestamp = monotonicDateNow(), isHmr = false, softInvalidate = false) {
- const prevInvalidationState = mod.invalidationState;
- if (softInvalidate) mod.invalidationState ??= mod.transformResult ?? "HARD_INVALIDATED";
- else mod.invalidationState = "HARD_INVALIDATED";
- if (seen$1.has(mod) && prevInvalidationState === mod.invalidationState) return;
- seen$1.add(mod);
- if (isHmr) {
- mod.lastHMRTimestamp = timestamp;
- mod.lastHMRInvalidationReceived = false;
- } else mod.lastInvalidationTimestamp = timestamp;
- const etag$1 = mod.transformResult?.etag;
- if (etag$1) this.etagToModuleMap.delete(etag$1);
- mod.transformResult = null;
- mod.ssrModule = null;
- mod.ssrError = null;
- mod.importers.forEach((importer) => {
- if (!importer.acceptedHmrDeps.has(mod)) {
- const shouldSoftInvalidateImporter = (importer.staticImportedUrls?.has(mod.url) || softInvalidate) && importer.type === "js";
- this.invalidateModule(importer, seen$1, timestamp, isHmr, shouldSoftInvalidateImporter);
- }
- });
- this._hasResolveFailedErrorModules.delete(mod);
- }
- invalidateAll() {
- const timestamp = monotonicDateNow();
- const seen$1 = /* @__PURE__ */ new Set();
- this.idToModuleMap.forEach((mod) => {
- this.invalidateModule(mod, seen$1, timestamp);
- });
- }
- /**
- * Update the module graph based on a module's updated imports information
- * If there are dependencies that no longer have any importers, they are
- * returned as a Set.
- *
- * @param staticImportedUrls Subset of `importedModules` where they're statically imported in code.
- * This is only used for soft invalidations so `undefined` is fine but may cause more runtime processing.
- */
- async updateModuleInfo(mod, importedModules, importedBindings, acceptedModules, acceptedExports, isSelfAccepting, staticImportedUrls) {
- mod.isSelfAccepting = isSelfAccepting;
- const prevImports = mod.importedModules;
- let noLongerImported;
- let resolvePromises = [];
- let resolveResults = new Array(importedModules.size);
- let index = 0;
- for (const imported of importedModules) {
- const nextIndex = index++;
- if (typeof imported === "string") resolvePromises.push(this.ensureEntryFromUrl(imported).then((dep) => {
- dep.importers.add(mod);
- resolveResults[nextIndex] = dep;
- }));
- else {
- imported.importers.add(mod);
- resolveResults[nextIndex] = imported;
- }
- }
- if (resolvePromises.length) await Promise.all(resolvePromises);
- mod.importedModules = new Set(resolveResults);
- prevImports.forEach((dep) => {
- if (!mod.importedModules.has(dep)) {
- dep.importers.delete(mod);
- if (!dep.importers.size) (noLongerImported || (noLongerImported = /* @__PURE__ */ new Set())).add(dep);
- }
- });
- resolvePromises = [];
- resolveResults = new Array(acceptedModules.size);
- index = 0;
- for (const accepted of acceptedModules) {
- const nextIndex = index++;
- if (typeof accepted === "string") resolvePromises.push(this.ensureEntryFromUrl(accepted).then((dep) => {
- resolveResults[nextIndex] = dep;
- }));
- else resolveResults[nextIndex] = accepted;
- }
- if (resolvePromises.length) await Promise.all(resolvePromises);
- mod.acceptedHmrDeps = new Set(resolveResults);
- mod.staticImportedUrls = staticImportedUrls;
- mod.acceptedHmrExports = acceptedExports;
- mod.importedBindings = importedBindings;
- return noLongerImported;
- }
- async ensureEntryFromUrl(rawUrl, setIsSelfAccepting = true) {
- return this._ensureEntryFromUrl(rawUrl, setIsSelfAccepting);
- }
- /**
- * @internal
- */
- async _ensureEntryFromUrl(rawUrl, setIsSelfAccepting = true, resolved) {
- rawUrl = removeImportQuery(removeTimestampQuery(rawUrl));
- let mod = this._getUnresolvedUrlToModule(rawUrl);
- if (mod) return mod;
- const modPromise = (async () => {
- const [url$3, resolvedId, meta] = await this._resolveUrl(rawUrl, resolved);
- mod = this.idToModuleMap.get(resolvedId);
- if (!mod) {
- mod = new EnvironmentModuleNode(url$3, this.environment, setIsSelfAccepting);
- if (meta) mod.meta = meta;
- this.urlToModuleMap.set(url$3, mod);
- mod.id = resolvedId;
- this.idToModuleMap.set(resolvedId, mod);
- const file = mod.file = cleanUrl(resolvedId);
- let fileMappedModules = this.fileToModulesMap.get(file);
- if (!fileMappedModules) {
- fileMappedModules = /* @__PURE__ */ new Set();
- this.fileToModulesMap.set(file, fileMappedModules);
- }
- fileMappedModules.add(mod);
- } else if (!this.urlToModuleMap.has(url$3)) this.urlToModuleMap.set(url$3, mod);
- this._setUnresolvedUrlToModule(rawUrl, mod);
- return mod;
- })();
- this._setUnresolvedUrlToModule(rawUrl, modPromise);
- return modPromise;
- }
- createFileOnlyEntry(file) {
- file = normalizePath(file);
- let fileMappedModules = this.fileToModulesMap.get(file);
- if (!fileMappedModules) {
- fileMappedModules = /* @__PURE__ */ new Set();
- this.fileToModulesMap.set(file, fileMappedModules);
- }
- const url$3 = `${FS_PREFIX}${file}`;
- for (const m of fileMappedModules) if ((m.url === url$3 || m.id === file) && m.type === "asset") return m;
- const mod = new EnvironmentModuleNode(url$3, this.environment);
- mod.type = "asset";
- mod.file = file;
- fileMappedModules.add(mod);
- return mod;
- }
- async resolveUrl(url$3) {
- url$3 = removeImportQuery(removeTimestampQuery(url$3));
- const mod = await this._getUnresolvedUrlToModule(url$3);
- if (mod?.id) return [
- mod.url,
- mod.id,
- mod.meta
- ];
- return this._resolveUrl(url$3);
- }
- updateModuleTransformResult(mod, result) {
- if (this.environment === "client") {
- const prevEtag = mod.transformResult?.etag;
- if (prevEtag) this.etagToModuleMap.delete(prevEtag);
- if (result?.etag) this.etagToModuleMap.set(result.etag, mod);
- }
- mod.transformResult = result;
- }
- getModuleByEtag(etag$1) {
- return this.etagToModuleMap.get(etag$1);
- }
- /**
- * @internal
- */
- _getUnresolvedUrlToModule(url$3) {
- return this._unresolvedUrlToModuleMap.get(url$3);
- }
- /**
- * @internal
- */
- _setUnresolvedUrlToModule(url$3, mod) {
- this._unresolvedUrlToModuleMap.set(url$3, mod);
- }
- /**
- * @internal
- */
- async _resolveUrl(url$3, alreadyResolved) {
- const resolved = alreadyResolved ?? await this._resolveId(url$3);
- const resolvedId = resolved?.id || url$3;
- if (url$3 !== resolvedId && !url$3.includes("\0") && !url$3.startsWith(`virtual:`)) {
- const ext = extname(cleanUrl(resolvedId));
- if (ext) {
- const pathname = cleanUrl(url$3);
- if (!pathname.endsWith(ext)) url$3 = pathname + ext + url$3.slice(pathname.length);
- }
- }
- return [
- url$3,
- resolvedId,
- resolved?.meta
- ];
- }
-};
-
-//#endregion
-//#region src/node/server/warmup.ts
-var import_picocolors$2 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-function warmupFiles(server, environment) {
- const { root } = server.config;
- mapFiles(environment.config.dev.warmup, root).then((files) => {
- for (const file of files) warmupFile(server, environment, file);
- });
-}
-async function warmupFile(server, environment, file) {
- if (file.endsWith(".html")) {
- const url$3 = htmlFileToUrl(file, server.config.root);
- if (url$3) try {
- const html = await fsp.readFile(file, "utf-8");
- await server.transformIndexHtml(url$3, html);
- } catch (e$1) {
- environment.logger.error(`Pre-transform error (${import_picocolors$2.default.cyan(file)}): ${e$1.message}`, {
- error: e$1,
- timestamp: true
- });
- }
- } else {
- const url$3 = fileToUrl(file, server.config.root);
- await environment.warmupRequest(url$3);
- }
-}
-function htmlFileToUrl(file, root) {
- const url$3 = path.relative(root, file);
- if (url$3[0] === ".") return;
- return "/" + normalizePath(url$3);
-}
-function fileToUrl(file, root) {
- const url$3 = path.relative(root, file);
- if (url$3[0] === ".") return path.posix.join(FS_PREFIX, normalizePath(file));
- return "/" + normalizePath(url$3);
-}
-async function mapFiles(files, root) {
- if (!files.length) return [];
- const result = [];
- const globs = [];
- for (const file of files) if (isDynamicPattern(file)) globs.push(file);
- else if (path.isAbsolute(file)) result.push(file);
- else result.push(path.resolve(root, file));
- if (globs.length) result.push(...await glob(globs, {
- absolute: true,
- cwd: root,
- expandDirectories: false,
- ignore: ["**/.git/**", "**/node_modules/**"]
- }));
- return result;
-}
-
-//#endregion
-//#region src/node/server/environment.ts
-var import_picocolors$1 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-var DevEnvironment = class extends BaseEnvironment {
- mode = "dev";
- moduleGraph;
- depsOptimizer;
- /**
- * @internal
- */
- _remoteRunnerOptions;
- get pluginContainer() {
- if (!this._pluginContainer) throw new Error(`${this.name} environment.pluginContainer called before initialized`);
- return this._pluginContainer;
- }
- /**
- * @internal
- */
- _pluginContainer;
- /**
- * @internal
- */
- _closing = false;
- /**
- * @internal
- */
- _pendingRequests;
- /**
- * @internal
- */
- _crawlEndFinder;
- /**
- * Hot channel for this environment. If not provided or disabled,
- * it will be a noop channel that does nothing.
- *
- * @example
- * environment.hot.send({ type: 'full-reload' })
- */
- hot;
- constructor(name, config$2, context) {
- let options$1 = config$2.environments[name];
- if (!options$1) throw new Error(`Environment "${name}" is not defined in the config.`);
- if (context.options) options$1 = mergeConfig(options$1, context.options);
- super(name, config$2, options$1);
- this._pendingRequests = /* @__PURE__ */ new Map();
- this.moduleGraph = new EnvironmentModuleGraph(name, (url$3) => this.pluginContainer.resolveId(url$3, void 0));
- this._crawlEndFinder = setupOnCrawlEnd();
- this._remoteRunnerOptions = context.remoteRunner ?? {};
- this.hot = context.transport ? isWebSocketServer in context.transport ? context.transport : normalizeHotChannel(context.transport, context.hot) : normalizeHotChannel({}, context.hot);
- this.hot.setInvokeHandler({
- fetchModule: (id, importer, options$2) => {
- return this.fetchModule(id, importer, options$2);
- },
- getBuiltins: async () => {
- return this.config.resolve.builtins.map((builtin) => typeof builtin === "string" ? {
- type: "string",
- value: builtin
- } : {
- type: "RegExp",
- source: builtin.source,
- flags: builtin.flags
- });
- }
- });
- this.hot.on("vite:invalidate", async ({ path: path$13, message, firstInvalidatedBy }) => {
- invalidateModule(this, {
- path: path$13,
- message,
- firstInvalidatedBy
- });
- });
- const { optimizeDeps: optimizeDeps$1 } = this.config;
- if (context.depsOptimizer) this.depsOptimizer = context.depsOptimizer;
- else if (isDepOptimizationDisabled(optimizeDeps$1)) this.depsOptimizer = void 0;
- else this.depsOptimizer = (optimizeDeps$1.noDiscovery ? createExplicitDepsOptimizer : createDepsOptimizer)(this);
- }
- async init(options$1) {
- if (this._initiated) return;
- this._initiated = true;
- this._pluginContainer = await createEnvironmentPluginContainer(this, this.config.plugins, options$1?.watcher);
- }
- /**
- * When the dev server is restarted, the methods are called in the following order:
- * - new instance `init`
- * - previous instance `close`
- * - new instance `listen`
- */
- async listen(server) {
- this.hot.listen();
- await this.depsOptimizer?.init();
- warmupFiles(server, this);
- }
- fetchModule(id, importer, options$1) {
- return fetchModule(this, id, importer, {
- ...this._remoteRunnerOptions,
- ...options$1
- });
- }
- async reloadModule(module$1) {
- if (this.config.server.hmr !== false && module$1.file) updateModules(this, module$1.file, [module$1], monotonicDateNow());
- }
- transformRequest(url$3, options$1) {
- return transformRequest(this, url$3, options$1);
- }
- async warmupRequest(url$3) {
- try {
- await this.transformRequest(url$3);
- } catch (e$1) {
- if (e$1?.code === ERR_OUTDATED_OPTIMIZED_DEP || e$1?.code === ERR_CLOSED_SERVER) return;
- this.logger.error(buildErrorMessage(e$1, [`Pre-transform error: ${e$1.message}`], false), {
- error: e$1,
- timestamp: true
- });
- }
- }
- async close() {
- this._closing = true;
- this._crawlEndFinder.cancel();
- await Promise.allSettled([
- this.pluginContainer.close(),
- this.depsOptimizer?.close(),
- isWebSocketServer in this.hot ? Promise.resolve() : this.hot.close(),
- (async () => {
- while (this._pendingRequests.size > 0) await Promise.allSettled([...this._pendingRequests.values()].map((pending) => pending.request));
- })()
- ]);
- }
- /**
- * Calling `await environment.waitForRequestsIdle(id)` will wait until all static imports
- * are processed after the first transformRequest call. If called from a load or transform
- * plugin hook, the id needs to be passed as a parameter to avoid deadlocks.
- * Calling this function after the first static imports section of the module graph has been
- * processed will resolve immediately.
- * @experimental
- */
- waitForRequestsIdle(ignoredId) {
- return this._crawlEndFinder.waitForRequestsIdle(ignoredId);
- }
- /**
- * @internal
- */
- _registerRequestProcessing(id, done) {
- this._crawlEndFinder.registerRequestProcessing(id, done);
- }
-};
-function invalidateModule(environment, m) {
- const mod = environment.moduleGraph.urlToModuleMap.get(m.path);
- if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0 && !mod.lastHMRInvalidationReceived) {
- mod.lastHMRInvalidationReceived = true;
- environment.logger.info(import_picocolors$1.default.yellow(`hmr invalidate `) + import_picocolors$1.default.dim(m.path) + (m.message ? ` ${m.message}` : ""), { timestamp: true });
- updateModules(environment, getShortName(mod.file, environment.config.root), [...mod.importers], mod.lastHMRTimestamp, m.firstInvalidatedBy);
- }
-}
-const callCrawlEndIfIdleAfterMs = 50;
-function setupOnCrawlEnd() {
- const registeredIds = /* @__PURE__ */ new Set();
- const seenIds = /* @__PURE__ */ new Set();
- const onCrawlEndPromiseWithResolvers = promiseWithResolvers();
- let timeoutHandle;
- let cancelled = false;
- function cancel() {
- cancelled = true;
- }
- function registerRequestProcessing(id, done) {
- if (!seenIds.has(id)) {
- seenIds.add(id);
- registeredIds.add(id);
- done().catch(() => {}).finally(() => markIdAsDone(id));
- }
- }
- function waitForRequestsIdle(ignoredId) {
- if (ignoredId) {
- seenIds.add(ignoredId);
- markIdAsDone(ignoredId);
- } else checkIfCrawlEndAfterTimeout();
- return onCrawlEndPromiseWithResolvers.promise;
- }
- function markIdAsDone(id) {
- registeredIds.delete(id);
- checkIfCrawlEndAfterTimeout();
- }
- function checkIfCrawlEndAfterTimeout() {
- if (cancelled || registeredIds.size > 0) return;
- if (timeoutHandle) clearTimeout(timeoutHandle);
- timeoutHandle = setTimeout(callOnCrawlEndWhenIdle, callCrawlEndIfIdleAfterMs);
- }
- async function callOnCrawlEndWhenIdle() {
- if (cancelled || registeredIds.size > 0) return;
- onCrawlEndPromiseWithResolvers.resolve();
- }
- return {
- registerRequestProcessing,
- waitForRequestsIdle,
- cancel
- };
-}
-
-//#endregion
-//#region src/node/server/environments/runnableEnvironment.ts
-function createRunnableDevEnvironment(name, config$2, context = {}) {
- if (context.transport == null) context.transport = createServerHotChannel();
- if (context.hot == null) context.hot = true;
- return new RunnableDevEnvironment(name, config$2, context);
-}
-function isRunnableDevEnvironment(environment) {
- return environment instanceof RunnableDevEnvironment;
-}
-var RunnableDevEnvironment = class extends DevEnvironment {
- _runner;
- _runnerFactory;
- _runnerOptions;
- constructor(name, config$2, context) {
- super(name, config$2, context);
- this._runnerFactory = context.runner;
- this._runnerOptions = context.runnerOptions;
- }
- get runner() {
- if (this._runner) return this._runner;
- this._runner = (this._runnerFactory || createServerModuleRunner)(this, this._runnerOptions);
- return this._runner;
- }
- async close() {
- await super.close();
- if (this._runner) await this._runner.close();
- }
-};
-
-//#endregion
-//#region ../../node_modules/.pnpm/@polka+compression@1.0.0-next.25/node_modules/@polka/compression/build.mjs
-const NOOP = () => {};
-const MIMES = /text|javascript|\/json|xml/i;
-/**
-* @param {any} chunk
-* @param {BufferEncoding} enc
-* @returns {number}
-*/
-function getChunkSize(chunk, enc) {
- return chunk ? Buffer.byteLength(chunk, enc) : 0;
-}
-/**
-* @param {import('./index.d.mts').Options} [options]
-* @returns {import('./index.d.mts').Middleware}
-*/
-function build_default$1({ threshold = 1024, level = -1, brotli = false, gzip: gzip$1 = true, mimes: mimes$1 = MIMES } = {}) {
- const brotliOpts = typeof brotli === "object" && brotli || {};
- const gzipOpts = typeof gzip$1 === "object" && gzip$1 || {};
- if (!zlib.createBrotliCompress) brotli = false;
- return (req$4, res, next = NOOP) => {
- const accept = req$4.headers["accept-encoding"] + "";
- const encoding = (brotli && accept.match(/\bbr\b/) || gzip$1 && accept.match(/\bgzip\b/) || [])[0];
- if (req$4.method === "HEAD" || !encoding) return next();
- /** @type {zlib.Gzip | zlib.BrotliCompress} */
- let compress;
- /** @type {Array<[string, function]>?} */
- let pendingListeners = [];
- let pendingStatus = 0;
- let started = false;
- let size = 0;
- function start() {
- started = true;
- size = res.getHeader("Content-Length") | 0 || size;
- const compressible = mimes$1.test(String(res.getHeader("Content-Type") || "text/plain"));
- const cleartext = !res.getHeader("Content-Encoding");
- const listeners = pendingListeners || [];
- if (compressible && cleartext && size >= threshold) {
- res.setHeader("Content-Encoding", encoding);
- res.removeHeader("Content-Length");
- if (encoding === "br") compress = zlib.createBrotliCompress({ params: Object.assign({
- [zlib.constants.BROTLI_PARAM_QUALITY]: level,
- [zlib.constants.BROTLI_PARAM_SIZE_HINT]: size
- }, brotliOpts) });
- else compress = zlib.createGzip(Object.assign({ level }, gzipOpts));
- compress.on("data", (chunk) => write.call(res, chunk) || compress.pause());
- on.call(res, "drain", () => compress.resume());
- compress.on("end", () => end.call(res));
- listeners.forEach((p) => compress.on.apply(compress, p));
- } else {
- pendingListeners = null;
- listeners.forEach((p) => on.apply(res, p));
- }
- writeHead.call(res, pendingStatus || res.statusCode);
- }
- const { end, write, on, writeHead } = res;
- res.writeHead = function(status$1, reason, headers) {
- if (typeof reason !== "string") [headers, reason] = [reason, headers];
- if (headers) for (let k in headers) res.setHeader(k, headers[k]);
- pendingStatus = status$1;
- return this;
- };
- res.write = function(chunk, enc) {
- size += getChunkSize(chunk, enc);
- if (!started) start();
- if (!compress) return write.apply(this, arguments);
- return compress.write.apply(compress, arguments);
- };
- res.end = function(chunk, enc) {
- if (arguments.length > 0 && typeof chunk !== "function") size += getChunkSize(chunk, enc);
- if (!started) start();
- if (!compress) return end.apply(this, arguments);
- return compress.end.apply(compress, arguments);
- };
- res.on = function(type, listener$1) {
- if (!pendingListeners) on.call(this, type, listener$1);
- else if (compress) compress.on(type, listener$1);
- else pendingListeners.push([type, listener$1]);
- return this;
- };
- next();
- };
-}
-
-//#endregion
-//#region src/node/preview.ts
-var import_connect = /* @__PURE__ */ __toESM(require_connect(), 1);
-var import_lib = /* @__PURE__ */ __toESM(require_lib$1(), 1);
-function resolvePreviewOptions(preview$1, server) {
- return {
- port: preview$1?.port ?? DEFAULT_PREVIEW_PORT,
- strictPort: preview$1?.strictPort ?? server.strictPort,
- host: preview$1?.host ?? server.host,
- allowedHosts: preview$1?.allowedHosts ?? server.allowedHosts,
- https: preview$1?.https ?? server.https,
- open: preview$1?.open ?? server.open,
- proxy: preview$1?.proxy ?? server.proxy,
- cors: preview$1?.cors ?? server.cors,
- headers: preview$1?.headers ?? server.headers
- };
-}
-/**
-* Starts the Vite server in preview mode, to simulate a production deployment
-*/
-async function preview(inlineConfig = {}) {
- const config$2 = await resolveConfig(inlineConfig, "serve", "production", "production", true);
- const clientOutDir = config$2.environments.client.build.outDir;
- const distDir = path.resolve(config$2.root, clientOutDir);
- if (!fs.existsSync(distDir) && config$2.plugins.every((plugin) => !plugin.configurePreviewServer) && process.argv[1]?.endsWith(path.normalize("bin/vite.js")) && process.argv[2] === "preview") throw new Error(`The directory "${clientOutDir}" does not exist. Did you build your project?`);
- const httpsOptions = await resolveHttpsConfig(config$2.preview.https);
- const app = (0, import_connect.default)();
- const httpServer = await resolveHttpServer(app, httpsOptions);
- setClientErrorHandler(httpServer, config$2.logger);
- const options$1 = config$2.preview;
- const logger = config$2.logger;
- const closeHttpServer = createServerCloseFn(httpServer);
- let closeServerPromise;
- const closeServer = async () => {
- teardownSIGTERMListener(closeServerAndExit);
- await closeHttpServer();
- server.resolvedUrls = null;
- };
- const server = {
- config: config$2,
- middlewares: app,
- httpServer,
- async close() {
- if (!closeServerPromise) closeServerPromise = closeServer();
- return closeServerPromise;
- },
- resolvedUrls: null,
- printUrls() {
- if (server.resolvedUrls) printServerUrls(server.resolvedUrls, options$1.host, logger.info);
- else throw new Error("cannot print server URLs before server is listening.");
- },
- bindCLIShortcuts(options$2) {
- bindCLIShortcuts(server, options$2);
- }
- };
- const closeServerAndExit = async (_, exitCode) => {
- try {
- await server.close();
- } finally {
- process.exitCode ??= exitCode ? 128 + exitCode : void 0;
- process.exit();
- }
- };
- setupSIGTERMListener(closeServerAndExit);
- const { cors } = config$2.preview;
- if (cors !== false) app.use((0, import_lib.default)(typeof cors === "boolean" ? {} : cors));
- const { allowedHosts } = config$2.preview;
- if (allowedHosts !== true && !config$2.preview.https) app.use(hostValidationMiddleware(allowedHosts, true));
- const configurePreviewServerContext = new BasicMinimalPluginContext({
- ...basePluginContextMeta,
- watchMode: false
- }, config$2.logger);
- const postHooks = [];
- for (const hook of config$2.getSortedPluginHooks("configurePreviewServer")) postHooks.push(await hook.call(configurePreviewServerContext, server));
- const { proxy } = config$2.preview;
- if (proxy) app.use(proxyMiddleware(httpServer, proxy, config$2));
- app.use(build_default$1());
- if (config$2.base !== "/") app.use(baseMiddleware(config$2.rawBase, false));
- const headers = config$2.preview.headers;
- const viteAssetMiddleware = (...args) => build_default(distDir, {
- etag: true,
- dev: true,
- extensions: [],
- ignores: false,
- setHeaders(res) {
- if (headers) for (const name in headers) res.setHeader(name, headers[name]);
- },
- shouldServe(filePath) {
- return shouldServeFile(filePath, distDir);
- }
- })(...args);
- app.use(viteAssetMiddleware);
- if (config$2.appType === "spa" || config$2.appType === "mpa") app.use(htmlFallbackMiddleware(distDir, config$2.appType === "spa"));
- postHooks.forEach((fn) => fn && fn());
- if (config$2.appType === "spa" || config$2.appType === "mpa") {
- const normalizedDistDir = normalizePath(distDir);
- app.use(indexHtmlMiddleware(normalizedDistDir, server));
- app.use(notFoundMiddleware());
- }
- const hostname = await resolveHostname(options$1.host);
- await httpServerStart(httpServer, {
- port: options$1.port,
- strictPort: options$1.strictPort,
- host: hostname.host,
- logger
- });
- server.resolvedUrls = resolveServerUrls(httpServer, config$2.preview, hostname, httpsOptions, config$2);
- if (options$1.open) {
- const url$3 = getServerUrlByHost(server.resolvedUrls, options$1.host);
- if (url$3) openBrowser(typeof options$1.open === "string" ? new URL(options$1.open, url$3).href : url$3, true, logger);
- }
- return server;
-}
-
-//#endregion
-//#region src/node/ssr/index.ts
-const _ssrConfigDefaults = Object.freeze({
- target: "node",
- optimizeDeps: {}
-});
-const ssrConfigDefaults = _ssrConfigDefaults;
-function resolveSSROptions(ssr, preserveSymlinks) {
- return mergeWithDefaults(mergeWithDefaults(_ssrConfigDefaults, { optimizeDeps: { esbuildOptions: { preserveSymlinks } } }), ssr ?? {});
-}
-
-//#endregion
-//#region src/node/ssr/runnerImport.ts
-/**
-* Import any file using the default Vite environment.
-* @experimental
-*/
-async function runnerImport(moduleId, inlineConfig) {
- const isModuleSyncConditionEnabled$1 = (await import("#module-sync-enabled")).default;
- const environment = createRunnableDevEnvironment("inline", await resolveConfig(mergeConfig(inlineConfig || {}, {
- configFile: false,
- envDir: false,
- cacheDir: process.cwd(),
- environments: { inline: {
- consumer: "server",
- dev: { moduleRunnerTransform: true },
- resolve: {
- external: true,
- mainFields: [],
- conditions: ["node", ...isModuleSyncConditionEnabled$1 ? ["module-sync"] : []]
- }
- } }
- }), "serve"), {
- runnerOptions: { hmr: { logger: false } },
- hot: false
- });
- await environment.init();
- try {
- const module$1 = await environment.runner.import(moduleId);
- return {
- module: module$1,
- dependencies: [...environment.runner.evaluatedModules.urlToIdModuleMap.values()].filter((m) => {
- if (!m.meta || "externalize" in m.meta) return false;
- return m.exports !== module$1;
- }).map((m) => m.file)
- };
- } finally {
- await environment.close();
- }
-}
-
-//#endregion
-//#region src/node/config.ts
-var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const debug = createDebugger("vite:config", { depth: 10 });
-const promisifiedRealpath = promisify(fs.realpath);
-const SYMBOL_RESOLVED_CONFIG = Symbol("vite:resolved-config");
-function defineConfig(config$2) {
- return config$2;
-}
-function defaultCreateClientDevEnvironment(name, config$2, context) {
- return new DevEnvironment(name, config$2, {
- hot: true,
- transport: context.ws
- });
-}
-function defaultCreateDevEnvironment(name, config$2) {
- return createRunnableDevEnvironment(name, config$2);
-}
-const configDefaults = Object.freeze({
- define: {},
- dev: {
- warmup: [],
- sourcemap: { js: true },
- sourcemapIgnoreList: void 0
- },
- build: buildEnvironmentOptionsDefaults,
- resolve: {
- externalConditions: [...DEFAULT_EXTERNAL_CONDITIONS],
- extensions: DEFAULT_EXTENSIONS,
- dedupe: [],
- noExternal: [],
- external: [],
- preserveSymlinks: false,
- alias: []
- },
- base: "/",
- publicDir: "public",
- plugins: [],
- html: { cspNonce: void 0 },
- css: cssConfigDefaults,
- json: {
- namedExports: true,
- stringify: "auto"
- },
- assetsInclude: void 0,
- builder: builderOptionsDefaults,
- server: serverConfigDefaults,
- preview: { port: DEFAULT_PREVIEW_PORT },
- experimental: {
- importGlobRestoreExtension: false,
- renderBuiltUrl: void 0,
- hmrPartialAccept: false
- },
- future: {
- removePluginHookHandleHotUpdate: void 0,
- removePluginHookSsrArgument: void 0,
- removeServerModuleGraph: void 0,
- removeServerHot: void 0,
- removeServerTransformRequest: void 0,
- removeServerWarmupRequest: void 0,
- removeSsrLoadModule: void 0
- },
- legacy: { skipWebSocketTokenCheck: false },
- logLevel: "info",
- customLogger: void 0,
- clearScreen: true,
- envDir: void 0,
- envPrefix: "VITE_",
- worker: {
- format: "iife",
- plugins: () => []
- },
- optimizeDeps: {
- include: [],
- exclude: [],
- needsInterop: [],
- extensions: [],
- disabled: "build",
- holdUntilCrawlEnd: true,
- force: false,
- ignoreOutdatedRequests: false
- },
- ssr: ssrConfigDefaults,
- environments: {},
- appType: "spa"
-});
-function resolveDevEnvironmentOptions(dev, environmentName, consumer, preTransformRequest$1) {
- const resolved = mergeWithDefaults({
- ...configDefaults.dev,
- sourcemapIgnoreList: isInNodeModules,
- preTransformRequests: preTransformRequest$1 ?? consumer === "client",
- createEnvironment: environmentName === "client" ? defaultCreateClientDevEnvironment : defaultCreateDevEnvironment,
- recoverable: consumer === "client",
- moduleRunnerTransform: consumer === "server"
- }, dev ?? {});
- return {
- ...resolved,
- sourcemapIgnoreList: resolved.sourcemapIgnoreList === false ? () => false : resolved.sourcemapIgnoreList
- };
-}
-function resolveEnvironmentOptions(options$1, alias$2, preserveSymlinks, forceOptimizeDeps, logger, environmentName, isSsrTargetWebworkerSet, preTransformRequests) {
- const consumer = options$1.consumer ?? (environmentName === "client" ? "client" : "server");
- const isSsrTargetWebworkerEnvironment = isSsrTargetWebworkerSet && environmentName === "ssr";
- if (options$1.define?.["process.env"]) {
- const processEnvDefine = options$1.define["process.env"];
- if (typeof processEnvDefine === "object") {
- const pathKey$1 = Object.entries(processEnvDefine).find(([key, value$1]) => key.toLowerCase() === "path" && !!value$1)?.[0];
- if (pathKey$1) logger.warnOnce(import_picocolors.default.yellow(`The \`define\` option contains an object with ${JSON.stringify(pathKey$1)} for "process.env" key. It looks like you may have passed the entire \`process.env\` object to \`define\`, which can unintentionally expose all environment variables. This poses a security risk and is discouraged.`));
- }
- }
- const resolve$4 = resolveEnvironmentResolveOptions(options$1.resolve, alias$2, preserveSymlinks, logger, consumer, isSsrTargetWebworkerEnvironment);
- return {
- define: options$1.define,
- resolve: resolve$4,
- keepProcessEnv: options$1.keepProcessEnv ?? (isSsrTargetWebworkerEnvironment ? false : consumer === "server"),
- consumer,
- optimizeDeps: resolveDepOptimizationOptions(options$1.optimizeDeps, resolve$4.preserveSymlinks, forceOptimizeDeps, consumer),
- dev: resolveDevEnvironmentOptions(options$1.dev, environmentName, consumer, preTransformRequests),
- build: resolveBuildEnvironmentOptions(options$1.build ?? {}, logger, consumer),
- plugins: void 0
- };
-}
-function getDefaultEnvironmentOptions(config$2) {
- return {
- define: config$2.define,
- resolve: {
- ...config$2.resolve,
- mainFields: void 0,
- conditions: void 0
- },
- dev: config$2.dev,
- build: config$2.build
- };
-}
-/**
-* Check and warn if `path` includes characters that don't work well in Vite,
-* such as `#` and `?` and `*`.
-*/
-function checkBadCharactersInPath(name, path$13, logger) {
- const badChars = [];
- if (path$13.includes("#")) badChars.push("#");
- if (path$13.includes("?")) badChars.push("?");
- if (path$13.includes("*")) badChars.push("*");
- if (badChars.length > 0) {
- const charString = badChars.map((c) => `"${c}"`).join(" and ");
- logger.warn(import_picocolors.default.yellow(`${name} contains the ${charString} ${badChars.length > 1 ? "characters" : "character"} (${import_picocolors.default.cyan(path$13)}), which may not work when running Vite. Consider renaming the directory / file to remove the characters.`));
- }
-}
-const clientAlias = [{
- find: /^\/?@vite\/env/,
- replacement: path.posix.join(FS_PREFIX, normalizePath(ENV_ENTRY))
-}, {
- find: /^\/?@vite\/client/,
- replacement: path.posix.join(FS_PREFIX, normalizePath(CLIENT_ENTRY))
-}];
-/**
-* alias and preserveSymlinks are not per-environment options, but they are
-* included in the resolved environment options for convenience.
-*/
-function resolveEnvironmentResolveOptions(resolve$4, alias$2, preserveSymlinks, logger, consumer, isSsrTargetWebworkerEnvironment) {
- const resolvedResolve = mergeWithDefaults({
- ...configDefaults.resolve,
- mainFields: consumer === void 0 || consumer === "client" || isSsrTargetWebworkerEnvironment ? DEFAULT_CLIENT_MAIN_FIELDS : DEFAULT_SERVER_MAIN_FIELDS,
- conditions: consumer === void 0 || consumer === "client" || isSsrTargetWebworkerEnvironment ? DEFAULT_CLIENT_CONDITIONS : DEFAULT_SERVER_CONDITIONS.filter((c) => c !== "browser"),
- builtins: resolve$4?.builtins ?? (consumer === "server" ? isSsrTargetWebworkerEnvironment && resolve$4?.noExternal === true ? [] : nodeLikeBuiltins : [])
- }, resolve$4 ?? {});
- resolvedResolve.preserveSymlinks = preserveSymlinks;
- resolvedResolve.alias = alias$2;
- if (resolve$4?.browserField === false && resolvedResolve.mainFields.includes("browser")) logger.warn(import_picocolors.default.yellow("`resolve.browserField` is set to false, but the option is removed in favour of the 'browser' string in `resolve.mainFields`. You may want to update `resolve.mainFields` to remove the 'browser' string and preserve the previous browser behaviour."));
- return resolvedResolve;
-}
-function resolveResolveOptions(resolve$4, logger) {
- const alias$2 = normalizeAlias(mergeAlias(clientAlias, resolve$4?.alias || configDefaults.resolve.alias));
- const preserveSymlinks = resolve$4?.preserveSymlinks ?? configDefaults.resolve.preserveSymlinks;
- if (alias$2.some((a) => a.find === "/")) logger.warn(import_picocolors.default.yellow("`resolve.alias` contains an alias that maps `/`. This is not recommended as it can cause unexpected behavior when resolving paths."));
- return resolveEnvironmentResolveOptions(resolve$4, alias$2, preserveSymlinks, logger, void 0);
-}
-function resolveDepOptimizationOptions(optimizeDeps$1, preserveSymlinks, forceOptimizeDeps, consumer) {
- return mergeWithDefaults({
- ...configDefaults.optimizeDeps,
- disabled: void 0,
- noDiscovery: consumer !== "client",
- esbuildOptions: { preserveSymlinks },
- force: forceOptimizeDeps ?? configDefaults.optimizeDeps.force
- }, optimizeDeps$1 ?? {});
-}
-function isResolvedConfig(inlineConfig) {
- return SYMBOL_RESOLVED_CONFIG in inlineConfig && inlineConfig[SYMBOL_RESOLVED_CONFIG];
-}
-async function resolveConfig(inlineConfig, command, defaultMode = "development", defaultNodeEnv = "development", isPreview = false, patchConfig = void 0, patchPlugins = void 0) {
- let config$2 = inlineConfig;
- let configFileDependencies = [];
- let mode = inlineConfig.mode || defaultMode;
- const isNodeEnvSet = !!process.env.NODE_ENV;
- const packageCache = /* @__PURE__ */ new Map();
- if (!isNodeEnvSet) process.env.NODE_ENV = defaultNodeEnv;
- const configEnv = {
- mode,
- command,
- isSsrBuild: command === "build" && !!config$2.build?.ssr,
- isPreview
- };
- let { configFile } = config$2;
- if (configFile !== false) {
- const loadResult = await loadConfigFromFile(configEnv, configFile, config$2.root, config$2.logLevel, config$2.customLogger, config$2.configLoader);
- if (loadResult) {
- config$2 = mergeConfig(loadResult.config, config$2);
- configFile = loadResult.path;
- configFileDependencies = loadResult.dependencies;
- }
- }
- mode = inlineConfig.mode || config$2.mode || mode;
- configEnv.mode = mode;
- const filterPlugin = (p) => {
- if (!p) return false;
- else if (!p.apply) return true;
- else if (typeof p.apply === "function") return p.apply({
- ...config$2,
- mode
- }, configEnv);
- else return p.apply === command;
- };
- const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins((await asyncFlatten(config$2.plugins || [])).filter(filterPlugin));
- const isBuild = command === "build";
- const userPlugins = [
- ...prePlugins,
- ...normalPlugins,
- ...postPlugins
- ];
- config$2 = await runConfigHook(config$2, userPlugins, configEnv);
- config$2.environments ??= {};
- if (!config$2.environments.ssr && (!isBuild || config$2.ssr || config$2.build?.ssr)) config$2.environments = {
- ssr: {},
- ...config$2.environments
- };
- if (!config$2.environments.client) config$2.environments = {
- client: {},
- ...config$2.environments
- };
- const logger = createLogger(config$2.logLevel, {
- allowClearScreen: config$2.clearScreen,
- customLogger: config$2.customLogger
- });
- const resolvedRoot = normalizePath(config$2.root ? path.resolve(config$2.root) : process.cwd());
- checkBadCharactersInPath("The project root", resolvedRoot, logger);
- const configEnvironmentsClient = config$2.environments.client;
- configEnvironmentsClient.dev ??= {};
- const deprecatedSsrOptimizeDepsConfig = config$2.ssr?.optimizeDeps ?? {};
- let configEnvironmentsSsr = config$2.environments.ssr;
- const warmupOptions = config$2.server?.warmup;
- if (warmupOptions?.clientFiles) configEnvironmentsClient.dev.warmup = warmupOptions.clientFiles;
- if (warmupOptions?.ssrFiles) {
- configEnvironmentsSsr ??= {};
- configEnvironmentsSsr.dev ??= {};
- configEnvironmentsSsr.dev.warmup = warmupOptions.ssrFiles;
- }
- if (configEnvironmentsSsr) {
- configEnvironmentsSsr.optimizeDeps = mergeConfig(deprecatedSsrOptimizeDepsConfig, configEnvironmentsSsr.optimizeDeps ?? {});
- configEnvironmentsSsr.resolve = mergeConfig({ resolve: {
- conditions: config$2.ssr?.resolve?.conditions,
- externalConditions: config$2.ssr?.resolve?.externalConditions,
- mainFields: config$2.ssr?.resolve?.mainFields,
- external: config$2.ssr?.external,
- noExternal: config$2.ssr?.noExternal
- } }, { resolve: configEnvironmentsSsr.resolve ?? {} }).resolve;
- }
- if (config$2.build?.ssrEmitAssets !== void 0) {
- configEnvironmentsSsr ??= {};
- configEnvironmentsSsr.build ??= {};
- configEnvironmentsSsr.build.emitAssets = config$2.build.ssrEmitAssets;
- }
- if (!config$2.environments.client || !config$2.environments.ssr && !isBuild) throw new Error("Required environments configuration were stripped out in the config hook");
- const defaultEnvironmentOptions = getDefaultEnvironmentOptions(config$2);
- const defaultClientEnvironmentOptions = {
- ...defaultEnvironmentOptions,
- resolve: config$2.resolve,
- optimizeDeps: config$2.optimizeDeps
- };
- const defaultNonClientEnvironmentOptions = {
- ...defaultEnvironmentOptions,
- dev: {
- ...defaultEnvironmentOptions.dev,
- createEnvironment: void 0,
- warmup: void 0
- },
- build: {
- ...defaultEnvironmentOptions.build,
- createEnvironment: void 0
- }
- };
- for (const name of Object.keys(config$2.environments)) config$2.environments[name] = mergeConfig(name === "client" ? defaultClientEnvironmentOptions : defaultNonClientEnvironmentOptions, config$2.environments[name]);
- await runConfigEnvironmentHook(config$2.environments, userPlugins, logger, configEnv, config$2.ssr?.target === "webworker");
- config$2.resolve ??= {};
- config$2.resolve.conditions = config$2.environments.client.resolve?.conditions;
- config$2.resolve.mainFields = config$2.environments.client.resolve?.mainFields;
- const resolvedDefaultResolve = resolveResolveOptions(config$2.resolve, logger);
- const resolvedEnvironments = {};
- for (const environmentName of Object.keys(config$2.environments)) resolvedEnvironments[environmentName] = resolveEnvironmentOptions(config$2.environments[environmentName], resolvedDefaultResolve.alias, resolvedDefaultResolve.preserveSymlinks, inlineConfig.forceOptimizeDeps, logger, environmentName, config$2.ssr?.target === "webworker", config$2.server?.preTransformRequests);
- const backwardCompatibleOptimizeDeps = resolvedEnvironments.client.optimizeDeps;
- const resolvedDevEnvironmentOptions = resolveDevEnvironmentOptions(config$2.dev, void 0, void 0);
- const resolvedBuildOptions = resolveBuildEnvironmentOptions(config$2.build ?? {}, logger, void 0);
- const ssr = resolveSSROptions({
- ...config$2.ssr,
- external: resolvedEnvironments.ssr?.resolve.external,
- noExternal: resolvedEnvironments.ssr?.resolve.noExternal,
- optimizeDeps: resolvedEnvironments.ssr?.optimizeDeps,
- resolve: {
- ...config$2.ssr?.resolve,
- conditions: resolvedEnvironments.ssr?.resolve.conditions,
- externalConditions: resolvedEnvironments.ssr?.resolve.externalConditions
- }
- }, resolvedDefaultResolve.preserveSymlinks);
- let envDir = config$2.envFile === false ? false : config$2.envDir;
- if (envDir !== false) envDir = config$2.envDir ? normalizePath(path.resolve(resolvedRoot, config$2.envDir)) : resolvedRoot;
- const userEnv = loadEnv(mode, envDir, resolveEnvPrefix(config$2));
- const userNodeEnv = process.env.VITE_USER_NODE_ENV;
- if (!isNodeEnvSet && userNodeEnv) if (userNodeEnv === "development") process.env.NODE_ENV = "development";
- else logger.warn(`NODE_ENV=${userNodeEnv} is not supported in the .env file. Only NODE_ENV=development is supported to create a development build of your project. If you need to set process.env.NODE_ENV, you can set it in the Vite config instead.`);
- const isProduction = process.env.NODE_ENV === "production";
- const resolvedBase = config$2.base === "" || config$2.base === "./" ? !isBuild || config$2.build?.ssr ? "/" : "./" : resolveBaseUrl(config$2.base, isBuild, logger);
- const pkgDir = findNearestPackageData(resolvedRoot, packageCache)?.dir;
- const cacheDir = normalizePath(config$2.cacheDir ? path.resolve(resolvedRoot, config$2.cacheDir) : pkgDir ? path.join(pkgDir, `node_modules/.vite`) : path.join(resolvedRoot, `.vite`));
- const assetsFilter = config$2.assetsInclude && (!Array.isArray(config$2.assetsInclude) || config$2.assetsInclude.length) ? createFilter(config$2.assetsInclude) : () => false;
- const { publicDir } = config$2;
- const resolvedPublicDir = publicDir !== false && publicDir !== "" ? normalizePath(path.resolve(resolvedRoot, typeof publicDir === "string" ? publicDir : configDefaults.publicDir)) : "";
- const server = resolveServerOptions(resolvedRoot, config$2.server, logger);
- const builder = resolveBuilderOptions(config$2.builder);
- const BASE_URL = resolvedBase;
- const resolvedConfigContext = new BasicMinimalPluginContext({
- ...basePluginContextMeta,
- watchMode: command === "serve" && !isPreview || command === "build" && !!resolvedBuildOptions.watch
- }, logger);
- let resolved;
- let createUserWorkerPlugins = config$2.worker?.plugins;
- if (Array.isArray(createUserWorkerPlugins)) {
- createUserWorkerPlugins = () => config$2.worker?.plugins;
- logger.warn(import_picocolors.default.yellow("worker.plugins is now a function that returns an array of plugins. Please update your Vite config accordingly.\n"));
- }
- const createWorkerPlugins = async function(bundleChain) {
- const rawWorkerUserPlugins = (await asyncFlatten(createUserWorkerPlugins?.() || [])).filter(filterPlugin);
- let workerConfig = mergeConfig({}, config$2);
- const [workerPrePlugins, workerNormalPlugins, workerPostPlugins] = sortUserPlugins(rawWorkerUserPlugins);
- const workerUserPlugins = [
- ...workerPrePlugins,
- ...workerNormalPlugins,
- ...workerPostPlugins
- ];
- workerConfig = await runConfigHook(workerConfig, workerUserPlugins, configEnv);
- const workerResolved = {
- ...workerConfig,
- ...resolved,
- isWorker: true,
- mainConfig: resolved,
- bundleChain
- };
- workerResolved.plugins = await resolvePlugins(workerResolved, workerPrePlugins, workerNormalPlugins, workerPostPlugins);
- await Promise.all(createPluginHookUtils(workerResolved.plugins).getSortedPluginHooks("configResolved").map((hook) => hook.call(resolvedConfigContext, workerResolved)));
- workerResolved.environments = {
- ...workerResolved.environments,
- client: {
- ...workerResolved.environments.client,
- plugins: await resolveEnvironmentPlugins(new PartialEnvironment("client", workerResolved))
- }
- };
- return workerResolved;
- };
- const resolvedWorkerOptions = {
- format: config$2.worker?.format || "iife",
- plugins: createWorkerPlugins,
- rollupOptions: config$2.worker?.rollupOptions || {}
- };
- const base = withTrailingSlash(resolvedBase);
- const preview$1 = resolvePreviewOptions(config$2.preview, server);
- const additionalAllowedHosts = getAdditionalAllowedHosts(server, preview$1);
- if (Array.isArray(server.allowedHosts)) server.allowedHosts.push(...additionalAllowedHosts);
- if (Array.isArray(preview$1.allowedHosts)) preview$1.allowedHosts.push(...additionalAllowedHosts);
- resolved = {
- configFile: configFile ? normalizePath(configFile) : void 0,
- configFileDependencies: configFileDependencies.map((name) => normalizePath(path.resolve(name))),
- inlineConfig,
- root: resolvedRoot,
- base,
- decodedBase: decodeBase(base),
- rawBase: resolvedBase,
- publicDir: resolvedPublicDir,
- cacheDir,
- command,
- mode,
- isWorker: false,
- mainConfig: null,
- bundleChain: [],
- isProduction,
- plugins: userPlugins,
- css: resolveCSSOptions(config$2.css),
- json: mergeWithDefaults(configDefaults.json, config$2.json ?? {}),
- esbuild: config$2.esbuild === false ? false : {
- jsxDev: !isProduction,
- charset: "utf8",
- legalComments: "none",
- ...config$2.esbuild
- },
- server,
- builder,
- preview: preview$1,
- envDir,
- env: {
- ...userEnv,
- BASE_URL,
- MODE: mode,
- DEV: !isProduction,
- PROD: isProduction
- },
- assetsInclude(file) {
- return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file);
- },
- logger,
- packageCache,
- worker: resolvedWorkerOptions,
- appType: config$2.appType ?? "spa",
- experimental: mergeWithDefaults(configDefaults.experimental, config$2.experimental ?? {}),
- future: config$2.future === "warn" ? {
- removePluginHookHandleHotUpdate: "warn",
- removePluginHookSsrArgument: "warn",
- removeServerModuleGraph: "warn",
- removeServerReloadModule: "warn",
- removeServerPluginContainer: "warn",
- removeServerHot: "warn",
- removeServerTransformRequest: "warn",
- removeServerWarmupRequest: "warn",
- removeSsrLoadModule: "warn"
- } : config$2.future,
- ssr,
- optimizeDeps: backwardCompatibleOptimizeDeps,
- resolve: resolvedDefaultResolve,
- dev: resolvedDevEnvironmentOptions,
- build: resolvedBuildOptions,
- environments: resolvedEnvironments,
- webSocketToken: Buffer.from(crypto.getRandomValues(new Uint8Array(9))).toString("base64url"),
- getSortedPlugins: void 0,
- getSortedPluginHooks: void 0,
- createResolver(options$1) {
- const resolve$4 = createIdResolver(this, options$1);
- const clientEnvironment = new PartialEnvironment("client", this);
- let ssrEnvironment;
- return async (id, importer, aliasOnly, ssr$1) => {
- if (ssr$1) ssrEnvironment ??= new PartialEnvironment("ssr", this);
- return await resolve$4(ssr$1 ? ssrEnvironment : clientEnvironment, id, importer, aliasOnly);
- };
- },
- fsDenyGlob: picomatch(server.fs.deny.map((pattern) => pattern.includes("/") ? pattern : `**/${pattern}`), {
- matchBase: false,
- nocase: true,
- dot: true
- }),
- safeModulePaths: /* @__PURE__ */ new Set(),
- [SYMBOL_RESOLVED_CONFIG]: true
- };
- resolved = {
- ...config$2,
- ...resolved
- };
- patchConfig?.(resolved);
- const resolvedPlugins = await resolvePlugins(resolved, prePlugins, normalPlugins, postPlugins);
- patchPlugins?.(resolvedPlugins);
- resolved.plugins = resolvedPlugins;
- Object.assign(resolved, createPluginHookUtils(resolved.plugins));
- await Promise.all(resolved.getSortedPluginHooks("configResolved").map((hook) => hook.call(resolvedConfigContext, resolved)));
- for (const name of Object.keys(resolved.environments)) resolved.environments[name].plugins = await resolveEnvironmentPlugins(new PartialEnvironment(name, resolved));
- optimizeDepsDisabledBackwardCompatibility(resolved, resolved.optimizeDeps);
- optimizeDepsDisabledBackwardCompatibility(resolved, resolved.ssr.optimizeDeps, "ssr.");
- if (!resolved.builder?.sharedConfigBuild && resolved.environments.ssr) resolved.environments.ssr.build.emitAssets = resolved.build.ssrEmitAssets || resolved.build.emitAssets;
- debug?.(`using resolved config: %O`, {
- ...resolved,
- plugins: resolved.plugins.map((p) => p.name),
- worker: {
- ...resolved.worker,
- plugins: `() => plugins`
- }
- });
- const outputOption = config$2.build?.rollupOptions?.output ?? [];
- if (Array.isArray(outputOption)) {
- const assetFileNamesList = outputOption.map((output) => output.assetFileNames);
- if (assetFileNamesList.length > 1) {
- const firstAssetFileNames = assetFileNamesList[0];
- if (assetFileNamesList.some((assetFileNames) => assetFileNames !== firstAssetFileNames)) resolved.logger.warn(import_picocolors.default.yellow(`
-assetFileNames isn't equal for every build.rollupOptions.output. A single pattern across all outputs is supported by Vite.
-`));
- }
- }
- if (config$2.legacy?.buildSsrCjsExternalHeuristics || config$2.ssr?.format === "cjs") resolved.logger.warn(import_picocolors.default.yellow(`
-(!) Experimental legacy.buildSsrCjsExternalHeuristics and ssr.format were be removed in Vite 5.
- The only SSR Output format is ESM. Find more information at https://github.com/vitejs/vite/discussions/13816.
-`));
- const resolvedBuildOutDir = normalizePath(path.resolve(resolved.root, resolved.build.outDir));
- if (isParentDirectory(resolvedBuildOutDir, resolved.root) || resolvedBuildOutDir === resolved.root) resolved.logger.warn(import_picocolors.default.yellow(`
-(!) build.outDir must not be the same directory of root or a parent directory of root as this could cause Vite to overwriting source files with build outputs.
-`));
- return resolved;
-}
-/**
-* Resolve base url. Note that some users use Vite to build for non-web targets like
-* electron or expects to deploy
-*/
-function resolveBaseUrl(base = configDefaults.base, isBuild, logger) {
- if (base[0] === ".") {
- logger.warn(import_picocolors.default.yellow(import_picocolors.default.bold(`(!) invalid "base" option: "${base}". The value can only be an absolute URL, "./", or an empty string.`)));
- return "/";
- }
- const isExternal$1 = isExternalUrl(base);
- if (!isExternal$1 && base[0] !== "/") logger.warn(import_picocolors.default.yellow(import_picocolors.default.bold(`(!) "base" option should start with a slash.`)));
- if (!isBuild || !isExternal$1) {
- base = new URL(base, "http://vite.dev").pathname;
- if (base[0] !== "/") base = "/" + base;
- }
- return base;
-}
-function decodeBase(base) {
- try {
- return decodeURI(base);
- } catch {
- throw new Error("The value passed to \"base\" option was malformed. It should be a valid URL.");
- }
-}
-function sortUserPlugins(plugins$1) {
- const prePlugins = [];
- const postPlugins = [];
- const normalPlugins = [];
- if (plugins$1) plugins$1.flat().forEach((p) => {
- if (p.enforce === "pre") prePlugins.push(p);
- else if (p.enforce === "post") postPlugins.push(p);
- else normalPlugins.push(p);
- });
- return [
- prePlugins,
- normalPlugins,
- postPlugins
- ];
-}
-async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel, customLogger, configLoader = "bundle") {
- if (configLoader !== "bundle" && configLoader !== "runner" && configLoader !== "native") throw new Error(`Unsupported configLoader: ${configLoader}. Accepted values are 'bundle', 'runner', and 'native'.`);
- const start = performance$1.now();
- const getTime = () => `${(performance$1.now() - start).toFixed(2)}ms`;
- let resolvedPath;
- if (configFile) resolvedPath = path.resolve(configFile);
- else for (const filename of DEFAULT_CONFIG_FILES) {
- const filePath = path.resolve(configRoot, filename);
- if (!fs.existsSync(filePath)) continue;
- resolvedPath = filePath;
- break;
- }
- if (!resolvedPath) {
- debug?.("no config file found.");
- return null;
- }
- try {
- const { configExport, dependencies } = await (configLoader === "bundle" ? bundleAndLoadConfigFile : configLoader === "runner" ? runnerImportConfigFile : nativeImportConfigFile)(resolvedPath);
- debug?.(`config file loaded in ${getTime()}`);
- const config$2 = await (typeof configExport === "function" ? configExport(configEnv) : configExport);
- if (!isObject(config$2)) throw new Error(`config must export or return an object.`);
- return {
- path: normalizePath(resolvedPath),
- config: config$2,
- dependencies
- };
- } catch (e$1) {
- const logger = createLogger(logLevel, { customLogger });
- checkBadCharactersInPath("The config path", resolvedPath, logger);
- logger.error(import_picocolors.default.red(`failed to load config from ${resolvedPath}`), { error: e$1 });
- throw e$1;
- }
-}
-async function nativeImportConfigFile(resolvedPath) {
- return {
- configExport: (await import(pathToFileURL(resolvedPath).href + "?t=" + Date.now())).default,
- dependencies: []
- };
-}
-async function runnerImportConfigFile(resolvedPath) {
- const { module: module$1, dependencies } = await runnerImport(resolvedPath);
- return {
- configExport: module$1.default,
- dependencies
- };
-}
-async function bundleAndLoadConfigFile(resolvedPath) {
- const isESM = typeof process.versions.deno === "string" || isFilePathESM(resolvedPath);
- const bundled = await bundleConfigFile(resolvedPath, isESM);
- return {
- configExport: await loadConfigFromBundledFile(resolvedPath, bundled.code, isESM),
- dependencies: bundled.dependencies
- };
-}
-async function bundleConfigFile(fileName, isESM) {
- let importMetaResolverRegistered = false;
- const root = path.dirname(fileName);
- const dirnameVarName = "__vite_injected_original_dirname";
- const filenameVarName = "__vite_injected_original_filename";
- const importMetaUrlVarName = "__vite_injected_original_import_meta_url";
- const importMetaResolveVarName = "__vite_injected_original_import_meta_resolve";
- const result = await build({
- absWorkingDir: process.cwd(),
- entryPoints: [fileName],
- write: false,
- target: [`node${process.versions.node}`],
- platform: "node",
- bundle: true,
- format: isESM ? "esm" : "cjs",
- mainFields: ["main"],
- sourcemap: "inline",
- sourceRoot: pathToFileURL(path.dirname(fileName)).href + "/",
- metafile: true,
- define: {
- __dirname: dirnameVarName,
- __filename: filenameVarName,
- "import.meta.url": importMetaUrlVarName,
- "import.meta.dirname": dirnameVarName,
- "import.meta.filename": filenameVarName,
- "import.meta.resolve": importMetaResolveVarName,
- "import.meta.main": "false"
- },
- plugins: [{
- name: "externalize-deps",
- setup(build$3) {
- build$3.onResolve({ filter: /^[^.#].*/ }, async ({ path: id, importer, kind }) => {
- if (kind === "entry-point" || path.isAbsolute(id) || isNodeBuiltin(id)) return;
- if (isNodeLikeBuiltin(id) || id.startsWith("npm:")) return { external: true };
- const isImport = isESM || kind === "dynamic-import";
- let idFsPath;
- try {
- idFsPath = nodeResolveWithVite(id, importer, {
- root,
- isRequire: !isImport
- });
- } catch (e$1) {
- if (!isImport) {
- let canResolveWithImport = false;
- try {
- canResolveWithImport = !!nodeResolveWithVite(id, importer, { root });
- } catch {}
- if (canResolveWithImport) throw new Error(`Failed to resolve ${JSON.stringify(id)}. This package is ESM only but it was tried to load by \`require\`. See https://vite.dev/guide/troubleshooting.html#this-package-is-esm-only for more details.`);
- }
- throw e$1;
- }
- if (idFsPath && isImport) idFsPath = pathToFileURL(idFsPath).href;
- return {
- path: idFsPath,
- external: true
- };
- });
- }
- }, {
- name: "inject-file-scope-variables",
- setup(build$3) {
- build$3.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => {
- const contents = await fsp.readFile(args.path, "utf-8");
- let injectValues = `const ${dirnameVarName} = ${JSON.stringify(path.dirname(args.path))};const ${filenameVarName} = ${JSON.stringify(args.path)};const ${importMetaUrlVarName} = ${JSON.stringify(pathToFileURL(args.path).href)};`;
- if (contents.includes("import.meta.resolve")) if (isESM) {
- if (!importMetaResolverRegistered) {
- importMetaResolverRegistered = true;
- await createImportMetaResolver();
- }
- injectValues += `const ${importMetaResolveVarName} = (specifier, importer = ${importMetaUrlVarName}) => (${importMetaResolveWithCustomHookString})(specifier, importer);`;
- } else injectValues += `const ${importMetaResolveVarName} = (specifier, importer = ${importMetaUrlVarName}) => { throw new Error('import.meta.resolve is not supported in CJS config files') };`;
- let injectedContents;
- if (contents.startsWith("#!")) {
- let firstLineEndIndex = contents.indexOf("\n");
- if (firstLineEndIndex < 0) firstLineEndIndex = contents.length;
- injectedContents = contents.slice(0, firstLineEndIndex + 1) + injectValues + contents.slice(firstLineEndIndex + 1);
- } else injectedContents = injectValues + contents;
- return {
- loader: args.path.endsWith("ts") ? "ts" : "js",
- contents: injectedContents
- };
- });
- }
- }]
- });
- const { text } = result.outputFiles[0];
- return {
- code: text,
- dependencies: Object.keys(result.metafile.inputs)
- };
-}
-const _require = createRequire(
- /** #__KEEP__ */
- import.meta.url
-);
-async function loadConfigFromBundledFile(fileName, bundledCode, isESM) {
- if (isESM) {
- let nodeModulesDir = typeof process.versions.deno === "string" ? void 0 : findNearestNodeModules(path.dirname(fileName));
- if (nodeModulesDir) try {
- await fsp.mkdir(path.resolve(nodeModulesDir, ".vite-temp/"), { recursive: true });
- } catch (e$1) {
- if (e$1.code === "EACCES") nodeModulesDir = void 0;
- else throw e$1;
- }
- const hash$1 = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
- const tempFileName = nodeModulesDir ? path.resolve(nodeModulesDir, `.vite-temp/${path.basename(fileName)}.${hash$1}.mjs`) : `${fileName}.${hash$1}.mjs`;
- await fsp.writeFile(tempFileName, bundledCode);
- try {
- return (await import(pathToFileURL(tempFileName).href)).default;
- } finally {
- fs.unlink(tempFileName, () => {});
- }
- } else {
- const extension$1 = path.extname(fileName);
- const realFileName = await promisifiedRealpath(fileName);
- const loaderExt = extension$1 in _require.extensions ? extension$1 : ".js";
- const defaultLoader = _require.extensions[loaderExt];
- _require.extensions[loaderExt] = (module$1, filename) => {
- if (filename === realFileName) module$1._compile(bundledCode, filename);
- else defaultLoader(module$1, filename);
- };
- delete _require.cache[_require.resolve(fileName)];
- const raw = _require(fileName);
- _require.extensions[loaderExt] = defaultLoader;
- return raw.__esModule ? raw.default : raw;
- }
-}
-async function runConfigHook(config$2, plugins$1, configEnv) {
- let conf = config$2;
- const context = new BasicMinimalPluginContext(basePluginContextMeta, createLogger(config$2.logLevel, {
- allowClearScreen: config$2.clearScreen,
- customLogger: config$2.customLogger
- }));
- for (const p of getSortedPluginsByHook("config", plugins$1)) {
- const hook = p.config;
- const res = await getHookHandler(hook).call(context, conf, configEnv);
- if (res && res !== conf) conf = mergeConfig(conf, res);
- }
- return conf;
-}
-async function runConfigEnvironmentHook(environments, plugins$1, logger, configEnv, isSsrTargetWebworkerSet) {
- const context = new BasicMinimalPluginContext(basePluginContextMeta, logger);
- const environmentNames = Object.keys(environments);
- for (const p of getSortedPluginsByHook("configEnvironment", plugins$1)) {
- const hook = p.configEnvironment;
- const handler = getHookHandler(hook);
- for (const name of environmentNames) {
- const res = await handler.call(context, name, environments[name], {
- ...configEnv,
- isSsrTargetWebworker: isSsrTargetWebworkerSet && name === "ssr"
- });
- if (res) environments[name] = mergeConfig(environments[name], res);
- }
- }
-}
-function optimizeDepsDisabledBackwardCompatibility(resolved, optimizeDeps$1, optimizeDepsPath = "") {
- const optimizeDepsDisabled = optimizeDeps$1.disabled;
- if (optimizeDepsDisabled !== void 0) {
- if (optimizeDepsDisabled === true || optimizeDepsDisabled === "dev") {
- const commonjsOptionsInclude = resolved.build.commonjsOptions.include;
- const commonjsPluginDisabled = Array.isArray(commonjsOptionsInclude) && commonjsOptionsInclude.length === 0;
- optimizeDeps$1.noDiscovery = true;
- optimizeDeps$1.include = void 0;
- if (commonjsPluginDisabled) resolved.build.commonjsOptions.include = void 0;
- resolved.logger.warn(import_picocolors.default.yellow(`(!) Experimental ${optimizeDepsPath}optimizeDeps.disabled and deps pre-bundling during build were removed in Vite 5.1.
- To disable the deps optimizer, set ${optimizeDepsPath}optimizeDeps.noDiscovery to true and ${optimizeDepsPath}optimizeDeps.include as undefined or empty.
- Please remove ${optimizeDepsPath}optimizeDeps.disabled from your config.
- ${commonjsPluginDisabled ? "Empty config.build.commonjsOptions.include will be ignored to support CJS during build. This config should also be removed." : ""}
- `));
- } else if (optimizeDepsDisabled === false || optimizeDepsDisabled === "build") resolved.logger.warn(import_picocolors.default.yellow(`(!) Experimental ${optimizeDepsPath}optimizeDeps.disabled and deps pre-bundling during build were removed in Vite 5.1.
- Setting it to ${optimizeDepsDisabled} now has no effect.
- Please remove ${optimizeDepsPath}optimizeDeps.disabled from your config.
- `));
- }
-}
-
-//#endregion
-export { runOptimizeDeps as $, toOutputFilePathInCss as A, depsLogString as B, onRollupLog as C, perEnvironmentPlugin as Ct, resolveBuilderOptions as D, mergeConfig as Dt, resolveBuildPlugins as E, mergeAlias as Et, addOptimizedDepInfo as F, initDepsOptimizerMetadata as G, extractExportsData as H, cleanupDepsCacheStaleDirs as I, optimizeDeps as J, isDepOptimizationDisabled as K, createIsOptimizedDepFile as L, toOutputFilePathInJS as M, toOutputFilePathWithoutRuntime as N, resolveLibFilename as O, normalizePath as Ot, addManuallyIncludedOptimizeDeps as P, optimizedDepNeedsInterop as Q, createIsOptimizedDepUrl as R, injectEnvironmentToHooks as S, perEnvironmentState as St, resolveBuildOutputs as T, isCSSRequest as Tt, getDepsCacheDir as U, discoverProjectDependencies as V, getOptimizedDepPath as W, optimizedDepInfoFromFile as X, optimizeExplicitEnvironmentDeps as Y, optimizedDepInfoFromId as Z, build$1 as _, createServerModuleRunnerTransport as _t, resolveBaseUrl as a, _createServer as at, createBuilder as b, resolveEnvPrefix as bt, sortUserPlugins as c, resolveServerOptions as ct, resolvePreviewOptions as d, searchForWorkspaceRoot as dt, toDiscoveredDependencies as et, createRunnableDevEnvironment as f, isFileLoadingAllowed as ft, BuildEnvironment as g, createServerModuleRunner as gt, fetchModule as h, ssrTransform as ht, loadConfigFromFile as i, createServerHotChannel as it, toOutputFilePathInHtml as j, resolveUserExternal as k, rollupVersion as kt, runnerImport as l, restartServerWithUrls as lt, DevEnvironment as m, send as mt, getDefaultEnvironmentOptions as n, preprocessCSS as nt, resolveConfig as o, createServer$2 as ot, isRunnableDevEnvironment as p, isFileServingAllowed as pt, loadCachedDepOptimizationMetadata as q, isResolvedConfig as r, createIdResolver as rt, resolveDevEnvironmentOptions as s, createServerCloseFn as st, defineConfig as t, formatPostcssSourceMap as tt, preview as u, serverConfigDefaults as ut, buildEnvironmentOptionsDefaults as v, buildErrorMessage as vt, resolveBuildEnvironmentOptions as w, createFilter as wt, createToImportMetaURLBasedRelativeRuntime as x, transformWithEsbuild as xt, builderOptionsDefaults as y, loadEnv as yt, depsFromOptimizedDepInfo as z }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/chunks/config2.js b/vanilla/node_modules/vite/dist/node/chunks/config2.js
deleted file mode 100644
index 38de917..0000000
--- a/vanilla/node_modules/vite/dist/node/chunks/config2.js
+++ /dev/null
@@ -1,4 +0,0 @@
-import "./logger.js";
-import { a as resolveBaseUrl, c as sortUserPlugins, i as loadConfigFromFile, n as getDefaultEnvironmentOptions, o as resolveConfig, r as isResolvedConfig, s as resolveDevEnvironmentOptions, t as defineConfig } from "./config.js";
-
-export { resolveConfig }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/chunks/dist.js b/vanilla/node_modules/vite/dist/node/chunks/dist.js
deleted file mode 100644
index a826f2a..0000000
--- a/vanilla/node_modules/vite/dist/node/chunks/dist.js
+++ /dev/null
@@ -1,6758 +0,0 @@
-//#region ../../node_modules/.pnpm/parse5@8.0.0/node_modules/parse5/dist/common/unicode.js
-const UNDEFINED_CODE_POINTS = new Set([
- 65534,
- 65535,
- 131070,
- 131071,
- 196606,
- 196607,
- 262142,
- 262143,
- 327678,
- 327679,
- 393214,
- 393215,
- 458750,
- 458751,
- 524286,
- 524287,
- 589822,
- 589823,
- 655358,
- 655359,
- 720894,
- 720895,
- 786430,
- 786431,
- 851966,
- 851967,
- 917502,
- 917503,
- 983038,
- 983039,
- 1048574,
- 1048575,
- 1114110,
- 1114111
-]);
-const REPLACEMENT_CHARACTER = "�";
-var CODE_POINTS;
-(function(CODE_POINTS$1) {
- CODE_POINTS$1[CODE_POINTS$1["EOF"] = -1] = "EOF";
- CODE_POINTS$1[CODE_POINTS$1["NULL"] = 0] = "NULL";
- CODE_POINTS$1[CODE_POINTS$1["TABULATION"] = 9] = "TABULATION";
- CODE_POINTS$1[CODE_POINTS$1["CARRIAGE_RETURN"] = 13] = "CARRIAGE_RETURN";
- CODE_POINTS$1[CODE_POINTS$1["LINE_FEED"] = 10] = "LINE_FEED";
- CODE_POINTS$1[CODE_POINTS$1["FORM_FEED"] = 12] = "FORM_FEED";
- CODE_POINTS$1[CODE_POINTS$1["SPACE"] = 32] = "SPACE";
- CODE_POINTS$1[CODE_POINTS$1["EXCLAMATION_MARK"] = 33] = "EXCLAMATION_MARK";
- CODE_POINTS$1[CODE_POINTS$1["QUOTATION_MARK"] = 34] = "QUOTATION_MARK";
- CODE_POINTS$1[CODE_POINTS$1["AMPERSAND"] = 38] = "AMPERSAND";
- CODE_POINTS$1[CODE_POINTS$1["APOSTROPHE"] = 39] = "APOSTROPHE";
- CODE_POINTS$1[CODE_POINTS$1["HYPHEN_MINUS"] = 45] = "HYPHEN_MINUS";
- CODE_POINTS$1[CODE_POINTS$1["SOLIDUS"] = 47] = "SOLIDUS";
- CODE_POINTS$1[CODE_POINTS$1["DIGIT_0"] = 48] = "DIGIT_0";
- CODE_POINTS$1[CODE_POINTS$1["DIGIT_9"] = 57] = "DIGIT_9";
- CODE_POINTS$1[CODE_POINTS$1["SEMICOLON"] = 59] = "SEMICOLON";
- CODE_POINTS$1[CODE_POINTS$1["LESS_THAN_SIGN"] = 60] = "LESS_THAN_SIGN";
- CODE_POINTS$1[CODE_POINTS$1["EQUALS_SIGN"] = 61] = "EQUALS_SIGN";
- CODE_POINTS$1[CODE_POINTS$1["GREATER_THAN_SIGN"] = 62] = "GREATER_THAN_SIGN";
- CODE_POINTS$1[CODE_POINTS$1["QUESTION_MARK"] = 63] = "QUESTION_MARK";
- CODE_POINTS$1[CODE_POINTS$1["LATIN_CAPITAL_A"] = 65] = "LATIN_CAPITAL_A";
- CODE_POINTS$1[CODE_POINTS$1["LATIN_CAPITAL_Z"] = 90] = "LATIN_CAPITAL_Z";
- CODE_POINTS$1[CODE_POINTS$1["RIGHT_SQUARE_BRACKET"] = 93] = "RIGHT_SQUARE_BRACKET";
- CODE_POINTS$1[CODE_POINTS$1["GRAVE_ACCENT"] = 96] = "GRAVE_ACCENT";
- CODE_POINTS$1[CODE_POINTS$1["LATIN_SMALL_A"] = 97] = "LATIN_SMALL_A";
- CODE_POINTS$1[CODE_POINTS$1["LATIN_SMALL_Z"] = 122] = "LATIN_SMALL_Z";
-})(CODE_POINTS || (CODE_POINTS = {}));
-const SEQUENCES = {
- DASH_DASH: "--",
- CDATA_START: "[CDATA[",
- DOCTYPE: "doctype",
- SCRIPT: "script",
- PUBLIC: "public",
- SYSTEM: "system"
-};
-function isSurrogate(cp) {
- return cp >= 55296 && cp <= 57343;
-}
-function isSurrogatePair(cp) {
- return cp >= 56320 && cp <= 57343;
-}
-function getSurrogatePairCodePoint(cp1, cp2) {
- return (cp1 - 55296) * 1024 + 9216 + cp2;
-}
-function isControlCodePoint(cp) {
- return cp !== 32 && cp !== 10 && cp !== 13 && cp !== 9 && cp !== 12 && cp >= 1 && cp <= 31 || cp >= 127 && cp <= 159;
-}
-function isUndefinedCodePoint(cp) {
- return cp >= 64976 && cp <= 65007 || UNDEFINED_CODE_POINTS.has(cp);
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/parse5@8.0.0/node_modules/parse5/dist/common/error-codes.js
-var ERR;
-(function(ERR$1) {
- ERR$1["controlCharacterInInputStream"] = "control-character-in-input-stream";
- ERR$1["noncharacterInInputStream"] = "noncharacter-in-input-stream";
- ERR$1["surrogateInInputStream"] = "surrogate-in-input-stream";
- ERR$1["nonVoidHtmlElementStartTagWithTrailingSolidus"] = "non-void-html-element-start-tag-with-trailing-solidus";
- ERR$1["endTagWithAttributes"] = "end-tag-with-attributes";
- ERR$1["endTagWithTrailingSolidus"] = "end-tag-with-trailing-solidus";
- ERR$1["unexpectedSolidusInTag"] = "unexpected-solidus-in-tag";
- ERR$1["unexpectedNullCharacter"] = "unexpected-null-character";
- ERR$1["unexpectedQuestionMarkInsteadOfTagName"] = "unexpected-question-mark-instead-of-tag-name";
- ERR$1["invalidFirstCharacterOfTagName"] = "invalid-first-character-of-tag-name";
- ERR$1["unexpectedEqualsSignBeforeAttributeName"] = "unexpected-equals-sign-before-attribute-name";
- ERR$1["missingEndTagName"] = "missing-end-tag-name";
- ERR$1["unexpectedCharacterInAttributeName"] = "unexpected-character-in-attribute-name";
- ERR$1["unknownNamedCharacterReference"] = "unknown-named-character-reference";
- ERR$1["missingSemicolonAfterCharacterReference"] = "missing-semicolon-after-character-reference";
- ERR$1["unexpectedCharacterAfterDoctypeSystemIdentifier"] = "unexpected-character-after-doctype-system-identifier";
- ERR$1["unexpectedCharacterInUnquotedAttributeValue"] = "unexpected-character-in-unquoted-attribute-value";
- ERR$1["eofBeforeTagName"] = "eof-before-tag-name";
- ERR$1["eofInTag"] = "eof-in-tag";
- ERR$1["missingAttributeValue"] = "missing-attribute-value";
- ERR$1["missingWhitespaceBetweenAttributes"] = "missing-whitespace-between-attributes";
- ERR$1["missingWhitespaceAfterDoctypePublicKeyword"] = "missing-whitespace-after-doctype-public-keyword";
- ERR$1["missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers"] = "missing-whitespace-between-doctype-public-and-system-identifiers";
- ERR$1["missingWhitespaceAfterDoctypeSystemKeyword"] = "missing-whitespace-after-doctype-system-keyword";
- ERR$1["missingQuoteBeforeDoctypePublicIdentifier"] = "missing-quote-before-doctype-public-identifier";
- ERR$1["missingQuoteBeforeDoctypeSystemIdentifier"] = "missing-quote-before-doctype-system-identifier";
- ERR$1["missingDoctypePublicIdentifier"] = "missing-doctype-public-identifier";
- ERR$1["missingDoctypeSystemIdentifier"] = "missing-doctype-system-identifier";
- ERR$1["abruptDoctypePublicIdentifier"] = "abrupt-doctype-public-identifier";
- ERR$1["abruptDoctypeSystemIdentifier"] = "abrupt-doctype-system-identifier";
- ERR$1["cdataInHtmlContent"] = "cdata-in-html-content";
- ERR$1["incorrectlyOpenedComment"] = "incorrectly-opened-comment";
- ERR$1["eofInScriptHtmlCommentLikeText"] = "eof-in-script-html-comment-like-text";
- ERR$1["eofInDoctype"] = "eof-in-doctype";
- ERR$1["nestedComment"] = "nested-comment";
- ERR$1["abruptClosingOfEmptyComment"] = "abrupt-closing-of-empty-comment";
- ERR$1["eofInComment"] = "eof-in-comment";
- ERR$1["incorrectlyClosedComment"] = "incorrectly-closed-comment";
- ERR$1["eofInCdata"] = "eof-in-cdata";
- ERR$1["absenceOfDigitsInNumericCharacterReference"] = "absence-of-digits-in-numeric-character-reference";
- ERR$1["nullCharacterReference"] = "null-character-reference";
- ERR$1["surrogateCharacterReference"] = "surrogate-character-reference";
- ERR$1["characterReferenceOutsideUnicodeRange"] = "character-reference-outside-unicode-range";
- ERR$1["controlCharacterReference"] = "control-character-reference";
- ERR$1["noncharacterCharacterReference"] = "noncharacter-character-reference";
- ERR$1["missingWhitespaceBeforeDoctypeName"] = "missing-whitespace-before-doctype-name";
- ERR$1["missingDoctypeName"] = "missing-doctype-name";
- ERR$1["invalidCharacterSequenceAfterDoctypeName"] = "invalid-character-sequence-after-doctype-name";
- ERR$1["duplicateAttribute"] = "duplicate-attribute";
- ERR$1["nonConformingDoctype"] = "non-conforming-doctype";
- ERR$1["missingDoctype"] = "missing-doctype";
- ERR$1["misplacedDoctype"] = "misplaced-doctype";
- ERR$1["endTagWithoutMatchingOpenElement"] = "end-tag-without-matching-open-element";
- ERR$1["closingOfElementWithOpenChildElements"] = "closing-of-element-with-open-child-elements";
- ERR$1["disallowedContentInNoscriptInHead"] = "disallowed-content-in-noscript-in-head";
- ERR$1["openElementsLeftAfterEof"] = "open-elements-left-after-eof";
- ERR$1["abandonedHeadElementChild"] = "abandoned-head-element-child";
- ERR$1["misplacedStartTagForHeadElement"] = "misplaced-start-tag-for-head-element";
- ERR$1["nestedNoscriptInHead"] = "nested-noscript-in-head";
- ERR$1["eofInElementThatCanContainOnlyText"] = "eof-in-element-that-can-contain-only-text";
-})(ERR || (ERR = {}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/parse5@8.0.0/node_modules/parse5/dist/tokenizer/preprocessor.js
-const DEFAULT_BUFFER_WATERLINE = 65536;
-var Preprocessor = class {
- constructor(handler) {
- this.handler = handler;
- this.html = "";
- this.pos = -1;
- this.lastGapPos = -2;
- this.gapStack = [];
- this.skipNextNewLine = false;
- this.lastChunkWritten = false;
- this.endOfChunkHit = false;
- this.bufferWaterline = DEFAULT_BUFFER_WATERLINE;
- this.isEol = false;
- this.lineStartPos = 0;
- this.droppedBufferSize = 0;
- this.line = 1;
- this.lastErrOffset = -1;
- }
- /** The column on the current line. If we just saw a gap (eg. a surrogate pair), return the index before. */
- get col() {
- return this.pos - this.lineStartPos + Number(this.lastGapPos !== this.pos);
- }
- get offset() {
- return this.droppedBufferSize + this.pos;
- }
- getError(code, cpOffset) {
- const { line, col, offset } = this;
- const startCol = col + cpOffset;
- const startOffset = offset + cpOffset;
- return {
- code,
- startLine: line,
- endLine: line,
- startCol,
- endCol: startCol,
- startOffset,
- endOffset: startOffset
- };
- }
- _err(code) {
- if (this.handler.onParseError && this.lastErrOffset !== this.offset) {
- this.lastErrOffset = this.offset;
- this.handler.onParseError(this.getError(code, 0));
- }
- }
- _addGap() {
- this.gapStack.push(this.lastGapPos);
- this.lastGapPos = this.pos;
- }
- _processSurrogate(cp) {
- if (this.pos !== this.html.length - 1) {
- const nextCp = this.html.charCodeAt(this.pos + 1);
- if (isSurrogatePair(nextCp)) {
- this.pos++;
- this._addGap();
- return getSurrogatePairCodePoint(cp, nextCp);
- }
- } else if (!this.lastChunkWritten) {
- this.endOfChunkHit = true;
- return CODE_POINTS.EOF;
- }
- this._err(ERR.surrogateInInputStream);
- return cp;
- }
- willDropParsedChunk() {
- return this.pos > this.bufferWaterline;
- }
- dropParsedChunk() {
- if (this.willDropParsedChunk()) {
- this.html = this.html.substring(this.pos);
- this.lineStartPos -= this.pos;
- this.droppedBufferSize += this.pos;
- this.pos = 0;
- this.lastGapPos = -2;
- this.gapStack.length = 0;
- }
- }
- write(chunk, isLastChunk) {
- if (this.html.length > 0) this.html += chunk;
- else this.html = chunk;
- this.endOfChunkHit = false;
- this.lastChunkWritten = isLastChunk;
- }
- insertHtmlAtCurrentPos(chunk) {
- this.html = this.html.substring(0, this.pos + 1) + chunk + this.html.substring(this.pos + 1);
- this.endOfChunkHit = false;
- }
- startsWith(pattern, caseSensitive) {
- if (this.pos + pattern.length > this.html.length) {
- this.endOfChunkHit = !this.lastChunkWritten;
- return false;
- }
- if (caseSensitive) return this.html.startsWith(pattern, this.pos);
- for (let i = 0; i < pattern.length; i++) if ((this.html.charCodeAt(this.pos + i) | 32) !== pattern.charCodeAt(i)) return false;
- return true;
- }
- peek(offset) {
- const pos = this.pos + offset;
- if (pos >= this.html.length) {
- this.endOfChunkHit = !this.lastChunkWritten;
- return CODE_POINTS.EOF;
- }
- const code = this.html.charCodeAt(pos);
- return code === CODE_POINTS.CARRIAGE_RETURN ? CODE_POINTS.LINE_FEED : code;
- }
- advance() {
- this.pos++;
- if (this.isEol) {
- this.isEol = false;
- this.line++;
- this.lineStartPos = this.pos;
- }
- if (this.pos >= this.html.length) {
- this.endOfChunkHit = !this.lastChunkWritten;
- return CODE_POINTS.EOF;
- }
- let cp = this.html.charCodeAt(this.pos);
- if (cp === CODE_POINTS.CARRIAGE_RETURN) {
- this.isEol = true;
- this.skipNextNewLine = true;
- return CODE_POINTS.LINE_FEED;
- }
- if (cp === CODE_POINTS.LINE_FEED) {
- this.isEol = true;
- if (this.skipNextNewLine) {
- this.line--;
- this.skipNextNewLine = false;
- this._addGap();
- return this.advance();
- }
- }
- this.skipNextNewLine = false;
- if (isSurrogate(cp)) cp = this._processSurrogate(cp);
- if (!(this.handler.onParseError === null || cp > 31 && cp < 127 || cp === CODE_POINTS.LINE_FEED || cp === CODE_POINTS.CARRIAGE_RETURN || cp > 159 && cp < 64976)) this._checkForProblematicCharacters(cp);
- return cp;
- }
- _checkForProblematicCharacters(cp) {
- if (isControlCodePoint(cp)) this._err(ERR.controlCharacterInInputStream);
- else if (isUndefinedCodePoint(cp)) this._err(ERR.noncharacterInInputStream);
- }
- retreat(count) {
- this.pos -= count;
- while (this.pos < this.lastGapPos) {
- this.lastGapPos = this.gapStack.pop();
- this.pos--;
- }
- this.isEol = false;
- }
-};
-
-//#endregion
-//#region ../../node_modules/.pnpm/parse5@8.0.0/node_modules/parse5/dist/common/token.js
-var TokenType;
-(function(TokenType$1) {
- TokenType$1[TokenType$1["CHARACTER"] = 0] = "CHARACTER";
- TokenType$1[TokenType$1["NULL_CHARACTER"] = 1] = "NULL_CHARACTER";
- TokenType$1[TokenType$1["WHITESPACE_CHARACTER"] = 2] = "WHITESPACE_CHARACTER";
- TokenType$1[TokenType$1["START_TAG"] = 3] = "START_TAG";
- TokenType$1[TokenType$1["END_TAG"] = 4] = "END_TAG";
- TokenType$1[TokenType$1["COMMENT"] = 5] = "COMMENT";
- TokenType$1[TokenType$1["DOCTYPE"] = 6] = "DOCTYPE";
- TokenType$1[TokenType$1["EOF"] = 7] = "EOF";
- TokenType$1[TokenType$1["HIBERNATION"] = 8] = "HIBERNATION";
-})(TokenType || (TokenType = {}));
-function getTokenAttr(token, attrName) {
- for (let i = token.attrs.length - 1; i >= 0; i--) if (token.attrs[i].name === attrName) return token.attrs[i].value;
- return null;
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/entities@6.0.0/node_modules/entities/dist/esm/generated/decode-data-html.js
-const htmlDecodeTree = /* @__PURE__ */ new Uint16Array(/* @__PURE__ */ "ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms„‹•˜¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻\"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉Dzኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙ῜ῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻\xA0ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌".split("").map((c) => c.charCodeAt(0)));
-
-//#endregion
-//#region ../../node_modules/.pnpm/entities@6.0.0/node_modules/entities/dist/esm/decode-codepoint.js
-var _a;
-const decodeMap = new Map([
- [0, 65533],
- [128, 8364],
- [130, 8218],
- [131, 402],
- [132, 8222],
- [133, 8230],
- [134, 8224],
- [135, 8225],
- [136, 710],
- [137, 8240],
- [138, 352],
- [139, 8249],
- [140, 338],
- [142, 381],
- [145, 8216],
- [146, 8217],
- [147, 8220],
- [148, 8221],
- [149, 8226],
- [150, 8211],
- [151, 8212],
- [152, 732],
- [153, 8482],
- [154, 353],
- [155, 8250],
- [156, 339],
- [158, 382],
- [159, 376]
-]);
-/**
-* Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point.
-*/
-const fromCodePoint = (_a = String.fromCodePoint) !== null && _a !== void 0 ? _a : function(codePoint) {
- let output = "";
- if (codePoint > 65535) {
- codePoint -= 65536;
- output += String.fromCharCode(codePoint >>> 10 & 1023 | 55296);
- codePoint = 56320 | codePoint & 1023;
- }
- output += String.fromCharCode(codePoint);
- return output;
-};
-/**
-* Replace the given code point with a replacement character if it is a
-* surrogate or is outside the valid range. Otherwise return the code
-* point unchanged.
-*/
-function replaceCodePoint(codePoint) {
- var _a$1;
- if (codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111) return 65533;
- return (_a$1 = decodeMap.get(codePoint)) !== null && _a$1 !== void 0 ? _a$1 : codePoint;
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/entities@6.0.0/node_modules/entities/dist/esm/decode.js
-var CharCodes;
-(function(CharCodes$1) {
- CharCodes$1[CharCodes$1["NUM"] = 35] = "NUM";
- CharCodes$1[CharCodes$1["SEMI"] = 59] = "SEMI";
- CharCodes$1[CharCodes$1["EQUALS"] = 61] = "EQUALS";
- CharCodes$1[CharCodes$1["ZERO"] = 48] = "ZERO";
- CharCodes$1[CharCodes$1["NINE"] = 57] = "NINE";
- CharCodes$1[CharCodes$1["LOWER_A"] = 97] = "LOWER_A";
- CharCodes$1[CharCodes$1["LOWER_F"] = 102] = "LOWER_F";
- CharCodes$1[CharCodes$1["LOWER_X"] = 120] = "LOWER_X";
- CharCodes$1[CharCodes$1["LOWER_Z"] = 122] = "LOWER_Z";
- CharCodes$1[CharCodes$1["UPPER_A"] = 65] = "UPPER_A";
- CharCodes$1[CharCodes$1["UPPER_F"] = 70] = "UPPER_F";
- CharCodes$1[CharCodes$1["UPPER_Z"] = 90] = "UPPER_Z";
-})(CharCodes || (CharCodes = {}));
-/** Bit that needs to be set to convert an upper case ASCII character to lower case */
-const TO_LOWER_BIT = 32;
-var BinTrieFlags;
-(function(BinTrieFlags$1) {
- BinTrieFlags$1[BinTrieFlags$1["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
- BinTrieFlags$1[BinTrieFlags$1["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH";
- BinTrieFlags$1[BinTrieFlags$1["JUMP_TABLE"] = 127] = "JUMP_TABLE";
-})(BinTrieFlags || (BinTrieFlags = {}));
-function isNumber(code) {
- return code >= CharCodes.ZERO && code <= CharCodes.NINE;
-}
-function isHexadecimalCharacter(code) {
- return code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F || code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F;
-}
-function isAsciiAlphaNumeric$1(code) {
- return code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z || code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z || isNumber(code);
-}
-/**
-* Checks if the given character is a valid end character for an entity in an attribute.
-*
-* Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error.
-* See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state
-*/
-function isEntityInAttributeInvalidEnd(code) {
- return code === CharCodes.EQUALS || isAsciiAlphaNumeric$1(code);
-}
-var EntityDecoderState;
-(function(EntityDecoderState$1) {
- EntityDecoderState$1[EntityDecoderState$1["EntityStart"] = 0] = "EntityStart";
- EntityDecoderState$1[EntityDecoderState$1["NumericStart"] = 1] = "NumericStart";
- EntityDecoderState$1[EntityDecoderState$1["NumericDecimal"] = 2] = "NumericDecimal";
- EntityDecoderState$1[EntityDecoderState$1["NumericHex"] = 3] = "NumericHex";
- EntityDecoderState$1[EntityDecoderState$1["NamedEntity"] = 4] = "NamedEntity";
-})(EntityDecoderState || (EntityDecoderState = {}));
-var DecodingMode;
-(function(DecodingMode$1) {
- /** Entities in text nodes that can end with any character. */
- DecodingMode$1[DecodingMode$1["Legacy"] = 0] = "Legacy";
- /** Only allow entities terminated with a semicolon. */
- DecodingMode$1[DecodingMode$1["Strict"] = 1] = "Strict";
- /** Entities in attributes have limitations on ending characters. */
- DecodingMode$1[DecodingMode$1["Attribute"] = 2] = "Attribute";
-})(DecodingMode || (DecodingMode = {}));
-/**
-* Token decoder with support of writing partial entities.
-*/
-var EntityDecoder = class {
- constructor(decodeTree, emitCodePoint, errors) {
- this.decodeTree = decodeTree;
- this.emitCodePoint = emitCodePoint;
- this.errors = errors;
- /** The current state of the decoder. */
- this.state = EntityDecoderState.EntityStart;
- /** Characters that were consumed while parsing an entity. */
- this.consumed = 1;
- /**
- * The result of the entity.
- *
- * Either the result index of a numeric entity, or the codepoint of a
- * numeric entity.
- */
- this.result = 0;
- /** The current index in the decode tree. */
- this.treeIndex = 0;
- /** The number of characters that were consumed in excess. */
- this.excess = 1;
- /** The mode in which the decoder is operating. */
- this.decodeMode = DecodingMode.Strict;
- }
- /** Resets the instance to make it reusable. */
- startEntity(decodeMode) {
- this.decodeMode = decodeMode;
- this.state = EntityDecoderState.EntityStart;
- this.result = 0;
- this.treeIndex = 0;
- this.excess = 1;
- this.consumed = 1;
- }
- /**
- * Write an entity to the decoder. This can be called multiple times with partial entities.
- * If the entity is incomplete, the decoder will return -1.
- *
- * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the
- * entity is incomplete, and resume when the next string is written.
- *
- * @param input The string containing the entity (or a continuation of the entity).
- * @param offset The offset at which the entity begins. Should be 0 if this is not the first call.
- * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
- */
- write(input, offset) {
- switch (this.state) {
- case EntityDecoderState.EntityStart:
- if (input.charCodeAt(offset) === CharCodes.NUM) {
- this.state = EntityDecoderState.NumericStart;
- this.consumed += 1;
- return this.stateNumericStart(input, offset + 1);
- }
- this.state = EntityDecoderState.NamedEntity;
- return this.stateNamedEntity(input, offset);
- case EntityDecoderState.NumericStart: return this.stateNumericStart(input, offset);
- case EntityDecoderState.NumericDecimal: return this.stateNumericDecimal(input, offset);
- case EntityDecoderState.NumericHex: return this.stateNumericHex(input, offset);
- case EntityDecoderState.NamedEntity: return this.stateNamedEntity(input, offset);
- }
- }
- /**
- * Switches between the numeric decimal and hexadecimal states.
- *
- * Equivalent to the `Numeric character reference state` in the HTML spec.
- *
- * @param input The string containing the entity (or a continuation of the entity).
- * @param offset The current offset.
- * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
- */
- stateNumericStart(input, offset) {
- if (offset >= input.length) return -1;
- if ((input.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
- this.state = EntityDecoderState.NumericHex;
- this.consumed += 1;
- return this.stateNumericHex(input, offset + 1);
- }
- this.state = EntityDecoderState.NumericDecimal;
- return this.stateNumericDecimal(input, offset);
- }
- addToNumericResult(input, start, end, base) {
- if (start !== end) {
- const digitCount = end - start;
- this.result = this.result * Math.pow(base, digitCount) + Number.parseInt(input.substr(start, digitCount), base);
- this.consumed += digitCount;
- }
- }
- /**
- * Parses a hexadecimal numeric entity.
- *
- * Equivalent to the `Hexademical character reference state` in the HTML spec.
- *
- * @param input The string containing the entity (or a continuation of the entity).
- * @param offset The current offset.
- * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
- */
- stateNumericHex(input, offset) {
- const startIndex = offset;
- while (offset < input.length) {
- const char = input.charCodeAt(offset);
- if (isNumber(char) || isHexadecimalCharacter(char)) offset += 1;
- else {
- this.addToNumericResult(input, startIndex, offset, 16);
- return this.emitNumericEntity(char, 3);
- }
- }
- this.addToNumericResult(input, startIndex, offset, 16);
- return -1;
- }
- /**
- * Parses a decimal numeric entity.
- *
- * Equivalent to the `Decimal character reference state` in the HTML spec.
- *
- * @param input The string containing the entity (or a continuation of the entity).
- * @param offset The current offset.
- * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
- */
- stateNumericDecimal(input, offset) {
- const startIndex = offset;
- while (offset < input.length) {
- const char = input.charCodeAt(offset);
- if (isNumber(char)) offset += 1;
- else {
- this.addToNumericResult(input, startIndex, offset, 10);
- return this.emitNumericEntity(char, 2);
- }
- }
- this.addToNumericResult(input, startIndex, offset, 10);
- return -1;
- }
- /**
- * Validate and emit a numeric entity.
- *
- * Implements the logic from the `Hexademical character reference start
- * state` and `Numeric character reference end state` in the HTML spec.
- *
- * @param lastCp The last code point of the entity. Used to see if the
- * entity was terminated with a semicolon.
- * @param expectedLength The minimum number of characters that should be
- * consumed. Used to validate that at least one digit
- * was consumed.
- * @returns The number of characters that were consumed.
- */
- emitNumericEntity(lastCp, expectedLength) {
- var _a$1;
- if (this.consumed <= expectedLength) {
- (_a$1 = this.errors) === null || _a$1 === void 0 || _a$1.absenceOfDigitsInNumericCharacterReference(this.consumed);
- return 0;
- }
- if (lastCp === CharCodes.SEMI) this.consumed += 1;
- else if (this.decodeMode === DecodingMode.Strict) return 0;
- this.emitCodePoint(replaceCodePoint(this.result), this.consumed);
- if (this.errors) {
- if (lastCp !== CharCodes.SEMI) this.errors.missingSemicolonAfterCharacterReference();
- this.errors.validateNumericCharacterReference(this.result);
- }
- return this.consumed;
- }
- /**
- * Parses a named entity.
- *
- * Equivalent to the `Named character reference state` in the HTML spec.
- *
- * @param input The string containing the entity (or a continuation of the entity).
- * @param offset The current offset.
- * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
- */
- stateNamedEntity(input, offset) {
- const { decodeTree } = this;
- let current = decodeTree[this.treeIndex];
- let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
- for (; offset < input.length; offset++, this.excess++) {
- const char = input.charCodeAt(offset);
- this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char);
- if (this.treeIndex < 0) return this.result === 0 || this.decodeMode === DecodingMode.Attribute && (valueLength === 0 || isEntityInAttributeInvalidEnd(char)) ? 0 : this.emitNotTerminatedNamedEntity();
- current = decodeTree[this.treeIndex];
- valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
- if (valueLength !== 0) {
- if (char === CharCodes.SEMI) return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
- if (this.decodeMode !== DecodingMode.Strict) {
- this.result = this.treeIndex;
- this.consumed += this.excess;
- this.excess = 0;
- }
- }
- }
- return -1;
- }
- /**
- * Emit a named entity that was not terminated with a semicolon.
- *
- * @returns The number of characters consumed.
- */
- emitNotTerminatedNamedEntity() {
- var _a$1;
- const { result, decodeTree } = this;
- const valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14;
- this.emitNamedEntityData(result, valueLength, this.consumed);
- (_a$1 = this.errors) === null || _a$1 === void 0 || _a$1.missingSemicolonAfterCharacterReference();
- return this.consumed;
- }
- /**
- * Emit a named entity.
- *
- * @param result The index of the entity in the decode tree.
- * @param valueLength The number of bytes in the entity.
- * @param consumed The number of characters consumed.
- *
- * @returns The number of characters consumed.
- */
- emitNamedEntityData(result, valueLength, consumed) {
- const { decodeTree } = this;
- this.emitCodePoint(valueLength === 1 ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH : decodeTree[result + 1], consumed);
- if (valueLength === 3) this.emitCodePoint(decodeTree[result + 2], consumed);
- return consumed;
- }
- /**
- * Signal to the parser that the end of the input was reached.
- *
- * Remaining data will be emitted and relevant errors will be produced.
- *
- * @returns The number of characters consumed.
- */
- end() {
- var _a$1;
- switch (this.state) {
- case EntityDecoderState.NamedEntity: return this.result !== 0 && (this.decodeMode !== DecodingMode.Attribute || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0;
- case EntityDecoderState.NumericDecimal: return this.emitNumericEntity(0, 2);
- case EntityDecoderState.NumericHex: return this.emitNumericEntity(0, 3);
- case EntityDecoderState.NumericStart:
- (_a$1 = this.errors) === null || _a$1 === void 0 || _a$1.absenceOfDigitsInNumericCharacterReference(this.consumed);
- return 0;
- case EntityDecoderState.EntityStart: return 0;
- }
- }
-};
-/**
-* Determines the branch of the current node that is taken given the current
-* character. This function is used to traverse the trie.
-*
-* @param decodeTree The trie.
-* @param current The current node.
-* @param nodeIdx The index right after the current node and its value.
-* @param char The current character.
-* @returns The index of the next node, or -1 if no branch is taken.
-*/
-function determineBranch(decodeTree, current, nodeIndex, char) {
- const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
- const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
- if (branchCount === 0) return jumpOffset !== 0 && char === jumpOffset ? nodeIndex : -1;
- if (jumpOffset) {
- const value = char - jumpOffset;
- return value < 0 || value >= branchCount ? -1 : decodeTree[nodeIndex + value] - 1;
- }
- let lo = nodeIndex;
- let hi = lo + branchCount - 1;
- while (lo <= hi) {
- const mid = lo + hi >>> 1;
- const midValue = decodeTree[mid];
- if (midValue < char) lo = mid + 1;
- else if (midValue > char) hi = mid - 1;
- else return decodeTree[mid + branchCount];
- }
- return -1;
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/parse5@8.0.0/node_modules/parse5/dist/common/html.js
-/** All valid namespaces in HTML. */
-var NS;
-(function(NS$1) {
- NS$1["HTML"] = "http://www.w3.org/1999/xhtml";
- NS$1["MATHML"] = "http://www.w3.org/1998/Math/MathML";
- NS$1["SVG"] = "http://www.w3.org/2000/svg";
- NS$1["XLINK"] = "http://www.w3.org/1999/xlink";
- NS$1["XML"] = "http://www.w3.org/XML/1998/namespace";
- NS$1["XMLNS"] = "http://www.w3.org/2000/xmlns/";
-})(NS || (NS = {}));
-var ATTRS;
-(function(ATTRS$1) {
- ATTRS$1["TYPE"] = "type";
- ATTRS$1["ACTION"] = "action";
- ATTRS$1["ENCODING"] = "encoding";
- ATTRS$1["PROMPT"] = "prompt";
- ATTRS$1["NAME"] = "name";
- ATTRS$1["COLOR"] = "color";
- ATTRS$1["FACE"] = "face";
- ATTRS$1["SIZE"] = "size";
-})(ATTRS || (ATTRS = {}));
-/**
-* The mode of the document.
-*
-* @see {@link https://dom.spec.whatwg.org/#concept-document-limited-quirks}
-*/
-var DOCUMENT_MODE;
-(function(DOCUMENT_MODE$1) {
- DOCUMENT_MODE$1["NO_QUIRKS"] = "no-quirks";
- DOCUMENT_MODE$1["QUIRKS"] = "quirks";
- DOCUMENT_MODE$1["LIMITED_QUIRKS"] = "limited-quirks";
-})(DOCUMENT_MODE || (DOCUMENT_MODE = {}));
-var TAG_NAMES;
-(function(TAG_NAMES$1) {
- TAG_NAMES$1["A"] = "a";
- TAG_NAMES$1["ADDRESS"] = "address";
- TAG_NAMES$1["ANNOTATION_XML"] = "annotation-xml";
- TAG_NAMES$1["APPLET"] = "applet";
- TAG_NAMES$1["AREA"] = "area";
- TAG_NAMES$1["ARTICLE"] = "article";
- TAG_NAMES$1["ASIDE"] = "aside";
- TAG_NAMES$1["B"] = "b";
- TAG_NAMES$1["BASE"] = "base";
- TAG_NAMES$1["BASEFONT"] = "basefont";
- TAG_NAMES$1["BGSOUND"] = "bgsound";
- TAG_NAMES$1["BIG"] = "big";
- TAG_NAMES$1["BLOCKQUOTE"] = "blockquote";
- TAG_NAMES$1["BODY"] = "body";
- TAG_NAMES$1["BR"] = "br";
- TAG_NAMES$1["BUTTON"] = "button";
- TAG_NAMES$1["CAPTION"] = "caption";
- TAG_NAMES$1["CENTER"] = "center";
- TAG_NAMES$1["CODE"] = "code";
- TAG_NAMES$1["COL"] = "col";
- TAG_NAMES$1["COLGROUP"] = "colgroup";
- TAG_NAMES$1["DD"] = "dd";
- TAG_NAMES$1["DESC"] = "desc";
- TAG_NAMES$1["DETAILS"] = "details";
- TAG_NAMES$1["DIALOG"] = "dialog";
- TAG_NAMES$1["DIR"] = "dir";
- TAG_NAMES$1["DIV"] = "div";
- TAG_NAMES$1["DL"] = "dl";
- TAG_NAMES$1["DT"] = "dt";
- TAG_NAMES$1["EM"] = "em";
- TAG_NAMES$1["EMBED"] = "embed";
- TAG_NAMES$1["FIELDSET"] = "fieldset";
- TAG_NAMES$1["FIGCAPTION"] = "figcaption";
- TAG_NAMES$1["FIGURE"] = "figure";
- TAG_NAMES$1["FONT"] = "font";
- TAG_NAMES$1["FOOTER"] = "footer";
- TAG_NAMES$1["FOREIGN_OBJECT"] = "foreignObject";
- TAG_NAMES$1["FORM"] = "form";
- TAG_NAMES$1["FRAME"] = "frame";
- TAG_NAMES$1["FRAMESET"] = "frameset";
- TAG_NAMES$1["H1"] = "h1";
- TAG_NAMES$1["H2"] = "h2";
- TAG_NAMES$1["H3"] = "h3";
- TAG_NAMES$1["H4"] = "h4";
- TAG_NAMES$1["H5"] = "h5";
- TAG_NAMES$1["H6"] = "h6";
- TAG_NAMES$1["HEAD"] = "head";
- TAG_NAMES$1["HEADER"] = "header";
- TAG_NAMES$1["HGROUP"] = "hgroup";
- TAG_NAMES$1["HR"] = "hr";
- TAG_NAMES$1["HTML"] = "html";
- TAG_NAMES$1["I"] = "i";
- TAG_NAMES$1["IMG"] = "img";
- TAG_NAMES$1["IMAGE"] = "image";
- TAG_NAMES$1["INPUT"] = "input";
- TAG_NAMES$1["IFRAME"] = "iframe";
- TAG_NAMES$1["KEYGEN"] = "keygen";
- TAG_NAMES$1["LABEL"] = "label";
- TAG_NAMES$1["LI"] = "li";
- TAG_NAMES$1["LINK"] = "link";
- TAG_NAMES$1["LISTING"] = "listing";
- TAG_NAMES$1["MAIN"] = "main";
- TAG_NAMES$1["MALIGNMARK"] = "malignmark";
- TAG_NAMES$1["MARQUEE"] = "marquee";
- TAG_NAMES$1["MATH"] = "math";
- TAG_NAMES$1["MENU"] = "menu";
- TAG_NAMES$1["META"] = "meta";
- TAG_NAMES$1["MGLYPH"] = "mglyph";
- TAG_NAMES$1["MI"] = "mi";
- TAG_NAMES$1["MO"] = "mo";
- TAG_NAMES$1["MN"] = "mn";
- TAG_NAMES$1["MS"] = "ms";
- TAG_NAMES$1["MTEXT"] = "mtext";
- TAG_NAMES$1["NAV"] = "nav";
- TAG_NAMES$1["NOBR"] = "nobr";
- TAG_NAMES$1["NOFRAMES"] = "noframes";
- TAG_NAMES$1["NOEMBED"] = "noembed";
- TAG_NAMES$1["NOSCRIPT"] = "noscript";
- TAG_NAMES$1["OBJECT"] = "object";
- TAG_NAMES$1["OL"] = "ol";
- TAG_NAMES$1["OPTGROUP"] = "optgroup";
- TAG_NAMES$1["OPTION"] = "option";
- TAG_NAMES$1["P"] = "p";
- TAG_NAMES$1["PARAM"] = "param";
- TAG_NAMES$1["PLAINTEXT"] = "plaintext";
- TAG_NAMES$1["PRE"] = "pre";
- TAG_NAMES$1["RB"] = "rb";
- TAG_NAMES$1["RP"] = "rp";
- TAG_NAMES$1["RT"] = "rt";
- TAG_NAMES$1["RTC"] = "rtc";
- TAG_NAMES$1["RUBY"] = "ruby";
- TAG_NAMES$1["S"] = "s";
- TAG_NAMES$1["SCRIPT"] = "script";
- TAG_NAMES$1["SEARCH"] = "search";
- TAG_NAMES$1["SECTION"] = "section";
- TAG_NAMES$1["SELECT"] = "select";
- TAG_NAMES$1["SOURCE"] = "source";
- TAG_NAMES$1["SMALL"] = "small";
- TAG_NAMES$1["SPAN"] = "span";
- TAG_NAMES$1["STRIKE"] = "strike";
- TAG_NAMES$1["STRONG"] = "strong";
- TAG_NAMES$1["STYLE"] = "style";
- TAG_NAMES$1["SUB"] = "sub";
- TAG_NAMES$1["SUMMARY"] = "summary";
- TAG_NAMES$1["SUP"] = "sup";
- TAG_NAMES$1["TABLE"] = "table";
- TAG_NAMES$1["TBODY"] = "tbody";
- TAG_NAMES$1["TEMPLATE"] = "template";
- TAG_NAMES$1["TEXTAREA"] = "textarea";
- TAG_NAMES$1["TFOOT"] = "tfoot";
- TAG_NAMES$1["TD"] = "td";
- TAG_NAMES$1["TH"] = "th";
- TAG_NAMES$1["THEAD"] = "thead";
- TAG_NAMES$1["TITLE"] = "title";
- TAG_NAMES$1["TR"] = "tr";
- TAG_NAMES$1["TRACK"] = "track";
- TAG_NAMES$1["TT"] = "tt";
- TAG_NAMES$1["U"] = "u";
- TAG_NAMES$1["UL"] = "ul";
- TAG_NAMES$1["SVG"] = "svg";
- TAG_NAMES$1["VAR"] = "var";
- TAG_NAMES$1["WBR"] = "wbr";
- TAG_NAMES$1["XMP"] = "xmp";
-})(TAG_NAMES || (TAG_NAMES = {}));
-/**
-* Tag IDs are numeric IDs for known tag names.
-*
-* We use tag IDs to improve the performance of tag name comparisons.
-*/
-var TAG_ID;
-(function(TAG_ID$1) {
- TAG_ID$1[TAG_ID$1["UNKNOWN"] = 0] = "UNKNOWN";
- TAG_ID$1[TAG_ID$1["A"] = 1] = "A";
- TAG_ID$1[TAG_ID$1["ADDRESS"] = 2] = "ADDRESS";
- TAG_ID$1[TAG_ID$1["ANNOTATION_XML"] = 3] = "ANNOTATION_XML";
- TAG_ID$1[TAG_ID$1["APPLET"] = 4] = "APPLET";
- TAG_ID$1[TAG_ID$1["AREA"] = 5] = "AREA";
- TAG_ID$1[TAG_ID$1["ARTICLE"] = 6] = "ARTICLE";
- TAG_ID$1[TAG_ID$1["ASIDE"] = 7] = "ASIDE";
- TAG_ID$1[TAG_ID$1["B"] = 8] = "B";
- TAG_ID$1[TAG_ID$1["BASE"] = 9] = "BASE";
- TAG_ID$1[TAG_ID$1["BASEFONT"] = 10] = "BASEFONT";
- TAG_ID$1[TAG_ID$1["BGSOUND"] = 11] = "BGSOUND";
- TAG_ID$1[TAG_ID$1["BIG"] = 12] = "BIG";
- TAG_ID$1[TAG_ID$1["BLOCKQUOTE"] = 13] = "BLOCKQUOTE";
- TAG_ID$1[TAG_ID$1["BODY"] = 14] = "BODY";
- TAG_ID$1[TAG_ID$1["BR"] = 15] = "BR";
- TAG_ID$1[TAG_ID$1["BUTTON"] = 16] = "BUTTON";
- TAG_ID$1[TAG_ID$1["CAPTION"] = 17] = "CAPTION";
- TAG_ID$1[TAG_ID$1["CENTER"] = 18] = "CENTER";
- TAG_ID$1[TAG_ID$1["CODE"] = 19] = "CODE";
- TAG_ID$1[TAG_ID$1["COL"] = 20] = "COL";
- TAG_ID$1[TAG_ID$1["COLGROUP"] = 21] = "COLGROUP";
- TAG_ID$1[TAG_ID$1["DD"] = 22] = "DD";
- TAG_ID$1[TAG_ID$1["DESC"] = 23] = "DESC";
- TAG_ID$1[TAG_ID$1["DETAILS"] = 24] = "DETAILS";
- TAG_ID$1[TAG_ID$1["DIALOG"] = 25] = "DIALOG";
- TAG_ID$1[TAG_ID$1["DIR"] = 26] = "DIR";
- TAG_ID$1[TAG_ID$1["DIV"] = 27] = "DIV";
- TAG_ID$1[TAG_ID$1["DL"] = 28] = "DL";
- TAG_ID$1[TAG_ID$1["DT"] = 29] = "DT";
- TAG_ID$1[TAG_ID$1["EM"] = 30] = "EM";
- TAG_ID$1[TAG_ID$1["EMBED"] = 31] = "EMBED";
- TAG_ID$1[TAG_ID$1["FIELDSET"] = 32] = "FIELDSET";
- TAG_ID$1[TAG_ID$1["FIGCAPTION"] = 33] = "FIGCAPTION";
- TAG_ID$1[TAG_ID$1["FIGURE"] = 34] = "FIGURE";
- TAG_ID$1[TAG_ID$1["FONT"] = 35] = "FONT";
- TAG_ID$1[TAG_ID$1["FOOTER"] = 36] = "FOOTER";
- TAG_ID$1[TAG_ID$1["FOREIGN_OBJECT"] = 37] = "FOREIGN_OBJECT";
- TAG_ID$1[TAG_ID$1["FORM"] = 38] = "FORM";
- TAG_ID$1[TAG_ID$1["FRAME"] = 39] = "FRAME";
- TAG_ID$1[TAG_ID$1["FRAMESET"] = 40] = "FRAMESET";
- TAG_ID$1[TAG_ID$1["H1"] = 41] = "H1";
- TAG_ID$1[TAG_ID$1["H2"] = 42] = "H2";
- TAG_ID$1[TAG_ID$1["H3"] = 43] = "H3";
- TAG_ID$1[TAG_ID$1["H4"] = 44] = "H4";
- TAG_ID$1[TAG_ID$1["H5"] = 45] = "H5";
- TAG_ID$1[TAG_ID$1["H6"] = 46] = "H6";
- TAG_ID$1[TAG_ID$1["HEAD"] = 47] = "HEAD";
- TAG_ID$1[TAG_ID$1["HEADER"] = 48] = "HEADER";
- TAG_ID$1[TAG_ID$1["HGROUP"] = 49] = "HGROUP";
- TAG_ID$1[TAG_ID$1["HR"] = 50] = "HR";
- TAG_ID$1[TAG_ID$1["HTML"] = 51] = "HTML";
- TAG_ID$1[TAG_ID$1["I"] = 52] = "I";
- TAG_ID$1[TAG_ID$1["IMG"] = 53] = "IMG";
- TAG_ID$1[TAG_ID$1["IMAGE"] = 54] = "IMAGE";
- TAG_ID$1[TAG_ID$1["INPUT"] = 55] = "INPUT";
- TAG_ID$1[TAG_ID$1["IFRAME"] = 56] = "IFRAME";
- TAG_ID$1[TAG_ID$1["KEYGEN"] = 57] = "KEYGEN";
- TAG_ID$1[TAG_ID$1["LABEL"] = 58] = "LABEL";
- TAG_ID$1[TAG_ID$1["LI"] = 59] = "LI";
- TAG_ID$1[TAG_ID$1["LINK"] = 60] = "LINK";
- TAG_ID$1[TAG_ID$1["LISTING"] = 61] = "LISTING";
- TAG_ID$1[TAG_ID$1["MAIN"] = 62] = "MAIN";
- TAG_ID$1[TAG_ID$1["MALIGNMARK"] = 63] = "MALIGNMARK";
- TAG_ID$1[TAG_ID$1["MARQUEE"] = 64] = "MARQUEE";
- TAG_ID$1[TAG_ID$1["MATH"] = 65] = "MATH";
- TAG_ID$1[TAG_ID$1["MENU"] = 66] = "MENU";
- TAG_ID$1[TAG_ID$1["META"] = 67] = "META";
- TAG_ID$1[TAG_ID$1["MGLYPH"] = 68] = "MGLYPH";
- TAG_ID$1[TAG_ID$1["MI"] = 69] = "MI";
- TAG_ID$1[TAG_ID$1["MO"] = 70] = "MO";
- TAG_ID$1[TAG_ID$1["MN"] = 71] = "MN";
- TAG_ID$1[TAG_ID$1["MS"] = 72] = "MS";
- TAG_ID$1[TAG_ID$1["MTEXT"] = 73] = "MTEXT";
- TAG_ID$1[TAG_ID$1["NAV"] = 74] = "NAV";
- TAG_ID$1[TAG_ID$1["NOBR"] = 75] = "NOBR";
- TAG_ID$1[TAG_ID$1["NOFRAMES"] = 76] = "NOFRAMES";
- TAG_ID$1[TAG_ID$1["NOEMBED"] = 77] = "NOEMBED";
- TAG_ID$1[TAG_ID$1["NOSCRIPT"] = 78] = "NOSCRIPT";
- TAG_ID$1[TAG_ID$1["OBJECT"] = 79] = "OBJECT";
- TAG_ID$1[TAG_ID$1["OL"] = 80] = "OL";
- TAG_ID$1[TAG_ID$1["OPTGROUP"] = 81] = "OPTGROUP";
- TAG_ID$1[TAG_ID$1["OPTION"] = 82] = "OPTION";
- TAG_ID$1[TAG_ID$1["P"] = 83] = "P";
- TAG_ID$1[TAG_ID$1["PARAM"] = 84] = "PARAM";
- TAG_ID$1[TAG_ID$1["PLAINTEXT"] = 85] = "PLAINTEXT";
- TAG_ID$1[TAG_ID$1["PRE"] = 86] = "PRE";
- TAG_ID$1[TAG_ID$1["RB"] = 87] = "RB";
- TAG_ID$1[TAG_ID$1["RP"] = 88] = "RP";
- TAG_ID$1[TAG_ID$1["RT"] = 89] = "RT";
- TAG_ID$1[TAG_ID$1["RTC"] = 90] = "RTC";
- TAG_ID$1[TAG_ID$1["RUBY"] = 91] = "RUBY";
- TAG_ID$1[TAG_ID$1["S"] = 92] = "S";
- TAG_ID$1[TAG_ID$1["SCRIPT"] = 93] = "SCRIPT";
- TAG_ID$1[TAG_ID$1["SEARCH"] = 94] = "SEARCH";
- TAG_ID$1[TAG_ID$1["SECTION"] = 95] = "SECTION";
- TAG_ID$1[TAG_ID$1["SELECT"] = 96] = "SELECT";
- TAG_ID$1[TAG_ID$1["SOURCE"] = 97] = "SOURCE";
- TAG_ID$1[TAG_ID$1["SMALL"] = 98] = "SMALL";
- TAG_ID$1[TAG_ID$1["SPAN"] = 99] = "SPAN";
- TAG_ID$1[TAG_ID$1["STRIKE"] = 100] = "STRIKE";
- TAG_ID$1[TAG_ID$1["STRONG"] = 101] = "STRONG";
- TAG_ID$1[TAG_ID$1["STYLE"] = 102] = "STYLE";
- TAG_ID$1[TAG_ID$1["SUB"] = 103] = "SUB";
- TAG_ID$1[TAG_ID$1["SUMMARY"] = 104] = "SUMMARY";
- TAG_ID$1[TAG_ID$1["SUP"] = 105] = "SUP";
- TAG_ID$1[TAG_ID$1["TABLE"] = 106] = "TABLE";
- TAG_ID$1[TAG_ID$1["TBODY"] = 107] = "TBODY";
- TAG_ID$1[TAG_ID$1["TEMPLATE"] = 108] = "TEMPLATE";
- TAG_ID$1[TAG_ID$1["TEXTAREA"] = 109] = "TEXTAREA";
- TAG_ID$1[TAG_ID$1["TFOOT"] = 110] = "TFOOT";
- TAG_ID$1[TAG_ID$1["TD"] = 111] = "TD";
- TAG_ID$1[TAG_ID$1["TH"] = 112] = "TH";
- TAG_ID$1[TAG_ID$1["THEAD"] = 113] = "THEAD";
- TAG_ID$1[TAG_ID$1["TITLE"] = 114] = "TITLE";
- TAG_ID$1[TAG_ID$1["TR"] = 115] = "TR";
- TAG_ID$1[TAG_ID$1["TRACK"] = 116] = "TRACK";
- TAG_ID$1[TAG_ID$1["TT"] = 117] = "TT";
- TAG_ID$1[TAG_ID$1["U"] = 118] = "U";
- TAG_ID$1[TAG_ID$1["UL"] = 119] = "UL";
- TAG_ID$1[TAG_ID$1["SVG"] = 120] = "SVG";
- TAG_ID$1[TAG_ID$1["VAR"] = 121] = "VAR";
- TAG_ID$1[TAG_ID$1["WBR"] = 122] = "WBR";
- TAG_ID$1[TAG_ID$1["XMP"] = 123] = "XMP";
-})(TAG_ID || (TAG_ID = {}));
-const TAG_NAME_TO_ID = new Map([
- [TAG_NAMES.A, TAG_ID.A],
- [TAG_NAMES.ADDRESS, TAG_ID.ADDRESS],
- [TAG_NAMES.ANNOTATION_XML, TAG_ID.ANNOTATION_XML],
- [TAG_NAMES.APPLET, TAG_ID.APPLET],
- [TAG_NAMES.AREA, TAG_ID.AREA],
- [TAG_NAMES.ARTICLE, TAG_ID.ARTICLE],
- [TAG_NAMES.ASIDE, TAG_ID.ASIDE],
- [TAG_NAMES.B, TAG_ID.B],
- [TAG_NAMES.BASE, TAG_ID.BASE],
- [TAG_NAMES.BASEFONT, TAG_ID.BASEFONT],
- [TAG_NAMES.BGSOUND, TAG_ID.BGSOUND],
- [TAG_NAMES.BIG, TAG_ID.BIG],
- [TAG_NAMES.BLOCKQUOTE, TAG_ID.BLOCKQUOTE],
- [TAG_NAMES.BODY, TAG_ID.BODY],
- [TAG_NAMES.BR, TAG_ID.BR],
- [TAG_NAMES.BUTTON, TAG_ID.BUTTON],
- [TAG_NAMES.CAPTION, TAG_ID.CAPTION],
- [TAG_NAMES.CENTER, TAG_ID.CENTER],
- [TAG_NAMES.CODE, TAG_ID.CODE],
- [TAG_NAMES.COL, TAG_ID.COL],
- [TAG_NAMES.COLGROUP, TAG_ID.COLGROUP],
- [TAG_NAMES.DD, TAG_ID.DD],
- [TAG_NAMES.DESC, TAG_ID.DESC],
- [TAG_NAMES.DETAILS, TAG_ID.DETAILS],
- [TAG_NAMES.DIALOG, TAG_ID.DIALOG],
- [TAG_NAMES.DIR, TAG_ID.DIR],
- [TAG_NAMES.DIV, TAG_ID.DIV],
- [TAG_NAMES.DL, TAG_ID.DL],
- [TAG_NAMES.DT, TAG_ID.DT],
- [TAG_NAMES.EM, TAG_ID.EM],
- [TAG_NAMES.EMBED, TAG_ID.EMBED],
- [TAG_NAMES.FIELDSET, TAG_ID.FIELDSET],
- [TAG_NAMES.FIGCAPTION, TAG_ID.FIGCAPTION],
- [TAG_NAMES.FIGURE, TAG_ID.FIGURE],
- [TAG_NAMES.FONT, TAG_ID.FONT],
- [TAG_NAMES.FOOTER, TAG_ID.FOOTER],
- [TAG_NAMES.FOREIGN_OBJECT, TAG_ID.FOREIGN_OBJECT],
- [TAG_NAMES.FORM, TAG_ID.FORM],
- [TAG_NAMES.FRAME, TAG_ID.FRAME],
- [TAG_NAMES.FRAMESET, TAG_ID.FRAMESET],
- [TAG_NAMES.H1, TAG_ID.H1],
- [TAG_NAMES.H2, TAG_ID.H2],
- [TAG_NAMES.H3, TAG_ID.H3],
- [TAG_NAMES.H4, TAG_ID.H4],
- [TAG_NAMES.H5, TAG_ID.H5],
- [TAG_NAMES.H6, TAG_ID.H6],
- [TAG_NAMES.HEAD, TAG_ID.HEAD],
- [TAG_NAMES.HEADER, TAG_ID.HEADER],
- [TAG_NAMES.HGROUP, TAG_ID.HGROUP],
- [TAG_NAMES.HR, TAG_ID.HR],
- [TAG_NAMES.HTML, TAG_ID.HTML],
- [TAG_NAMES.I, TAG_ID.I],
- [TAG_NAMES.IMG, TAG_ID.IMG],
- [TAG_NAMES.IMAGE, TAG_ID.IMAGE],
- [TAG_NAMES.INPUT, TAG_ID.INPUT],
- [TAG_NAMES.IFRAME, TAG_ID.IFRAME],
- [TAG_NAMES.KEYGEN, TAG_ID.KEYGEN],
- [TAG_NAMES.LABEL, TAG_ID.LABEL],
- [TAG_NAMES.LI, TAG_ID.LI],
- [TAG_NAMES.LINK, TAG_ID.LINK],
- [TAG_NAMES.LISTING, TAG_ID.LISTING],
- [TAG_NAMES.MAIN, TAG_ID.MAIN],
- [TAG_NAMES.MALIGNMARK, TAG_ID.MALIGNMARK],
- [TAG_NAMES.MARQUEE, TAG_ID.MARQUEE],
- [TAG_NAMES.MATH, TAG_ID.MATH],
- [TAG_NAMES.MENU, TAG_ID.MENU],
- [TAG_NAMES.META, TAG_ID.META],
- [TAG_NAMES.MGLYPH, TAG_ID.MGLYPH],
- [TAG_NAMES.MI, TAG_ID.MI],
- [TAG_NAMES.MO, TAG_ID.MO],
- [TAG_NAMES.MN, TAG_ID.MN],
- [TAG_NAMES.MS, TAG_ID.MS],
- [TAG_NAMES.MTEXT, TAG_ID.MTEXT],
- [TAG_NAMES.NAV, TAG_ID.NAV],
- [TAG_NAMES.NOBR, TAG_ID.NOBR],
- [TAG_NAMES.NOFRAMES, TAG_ID.NOFRAMES],
- [TAG_NAMES.NOEMBED, TAG_ID.NOEMBED],
- [TAG_NAMES.NOSCRIPT, TAG_ID.NOSCRIPT],
- [TAG_NAMES.OBJECT, TAG_ID.OBJECT],
- [TAG_NAMES.OL, TAG_ID.OL],
- [TAG_NAMES.OPTGROUP, TAG_ID.OPTGROUP],
- [TAG_NAMES.OPTION, TAG_ID.OPTION],
- [TAG_NAMES.P, TAG_ID.P],
- [TAG_NAMES.PARAM, TAG_ID.PARAM],
- [TAG_NAMES.PLAINTEXT, TAG_ID.PLAINTEXT],
- [TAG_NAMES.PRE, TAG_ID.PRE],
- [TAG_NAMES.RB, TAG_ID.RB],
- [TAG_NAMES.RP, TAG_ID.RP],
- [TAG_NAMES.RT, TAG_ID.RT],
- [TAG_NAMES.RTC, TAG_ID.RTC],
- [TAG_NAMES.RUBY, TAG_ID.RUBY],
- [TAG_NAMES.S, TAG_ID.S],
- [TAG_NAMES.SCRIPT, TAG_ID.SCRIPT],
- [TAG_NAMES.SEARCH, TAG_ID.SEARCH],
- [TAG_NAMES.SECTION, TAG_ID.SECTION],
- [TAG_NAMES.SELECT, TAG_ID.SELECT],
- [TAG_NAMES.SOURCE, TAG_ID.SOURCE],
- [TAG_NAMES.SMALL, TAG_ID.SMALL],
- [TAG_NAMES.SPAN, TAG_ID.SPAN],
- [TAG_NAMES.STRIKE, TAG_ID.STRIKE],
- [TAG_NAMES.STRONG, TAG_ID.STRONG],
- [TAG_NAMES.STYLE, TAG_ID.STYLE],
- [TAG_NAMES.SUB, TAG_ID.SUB],
- [TAG_NAMES.SUMMARY, TAG_ID.SUMMARY],
- [TAG_NAMES.SUP, TAG_ID.SUP],
- [TAG_NAMES.TABLE, TAG_ID.TABLE],
- [TAG_NAMES.TBODY, TAG_ID.TBODY],
- [TAG_NAMES.TEMPLATE, TAG_ID.TEMPLATE],
- [TAG_NAMES.TEXTAREA, TAG_ID.TEXTAREA],
- [TAG_NAMES.TFOOT, TAG_ID.TFOOT],
- [TAG_NAMES.TD, TAG_ID.TD],
- [TAG_NAMES.TH, TAG_ID.TH],
- [TAG_NAMES.THEAD, TAG_ID.THEAD],
- [TAG_NAMES.TITLE, TAG_ID.TITLE],
- [TAG_NAMES.TR, TAG_ID.TR],
- [TAG_NAMES.TRACK, TAG_ID.TRACK],
- [TAG_NAMES.TT, TAG_ID.TT],
- [TAG_NAMES.U, TAG_ID.U],
- [TAG_NAMES.UL, TAG_ID.UL],
- [TAG_NAMES.SVG, TAG_ID.SVG],
- [TAG_NAMES.VAR, TAG_ID.VAR],
- [TAG_NAMES.WBR, TAG_ID.WBR],
- [TAG_NAMES.XMP, TAG_ID.XMP]
-]);
-function getTagID(tagName) {
- var _a$1;
- return (_a$1 = TAG_NAME_TO_ID.get(tagName)) !== null && _a$1 !== void 0 ? _a$1 : TAG_ID.UNKNOWN;
-}
-const $ = TAG_ID;
-const SPECIAL_ELEMENTS = {
- [NS.HTML]: new Set([
- $.ADDRESS,
- $.APPLET,
- $.AREA,
- $.ARTICLE,
- $.ASIDE,
- $.BASE,
- $.BASEFONT,
- $.BGSOUND,
- $.BLOCKQUOTE,
- $.BODY,
- $.BR,
- $.BUTTON,
- $.CAPTION,
- $.CENTER,
- $.COL,
- $.COLGROUP,
- $.DD,
- $.DETAILS,
- $.DIR,
- $.DIV,
- $.DL,
- $.DT,
- $.EMBED,
- $.FIELDSET,
- $.FIGCAPTION,
- $.FIGURE,
- $.FOOTER,
- $.FORM,
- $.FRAME,
- $.FRAMESET,
- $.H1,
- $.H2,
- $.H3,
- $.H4,
- $.H5,
- $.H6,
- $.HEAD,
- $.HEADER,
- $.HGROUP,
- $.HR,
- $.HTML,
- $.IFRAME,
- $.IMG,
- $.INPUT,
- $.LI,
- $.LINK,
- $.LISTING,
- $.MAIN,
- $.MARQUEE,
- $.MENU,
- $.META,
- $.NAV,
- $.NOEMBED,
- $.NOFRAMES,
- $.NOSCRIPT,
- $.OBJECT,
- $.OL,
- $.P,
- $.PARAM,
- $.PLAINTEXT,
- $.PRE,
- $.SCRIPT,
- $.SECTION,
- $.SELECT,
- $.SOURCE,
- $.STYLE,
- $.SUMMARY,
- $.TABLE,
- $.TBODY,
- $.TD,
- $.TEMPLATE,
- $.TEXTAREA,
- $.TFOOT,
- $.TH,
- $.THEAD,
- $.TITLE,
- $.TR,
- $.TRACK,
- $.UL,
- $.WBR,
- $.XMP
- ]),
- [NS.MATHML]: new Set([
- $.MI,
- $.MO,
- $.MN,
- $.MS,
- $.MTEXT,
- $.ANNOTATION_XML
- ]),
- [NS.SVG]: new Set([
- $.TITLE,
- $.FOREIGN_OBJECT,
- $.DESC
- ]),
- [NS.XLINK]: /* @__PURE__ */ new Set(),
- [NS.XML]: /* @__PURE__ */ new Set(),
- [NS.XMLNS]: /* @__PURE__ */ new Set()
-};
-const NUMBERED_HEADERS = new Set([
- $.H1,
- $.H2,
- $.H3,
- $.H4,
- $.H5,
- $.H6
-]);
-
-//#endregion
-//#region ../../node_modules/.pnpm/parse5@8.0.0/node_modules/parse5/dist/tokenizer/index.js
-var State;
-(function(State$1) {
- State$1[State$1["DATA"] = 0] = "DATA";
- State$1[State$1["RCDATA"] = 1] = "RCDATA";
- State$1[State$1["RAWTEXT"] = 2] = "RAWTEXT";
- State$1[State$1["SCRIPT_DATA"] = 3] = "SCRIPT_DATA";
- State$1[State$1["PLAINTEXT"] = 4] = "PLAINTEXT";
- State$1[State$1["TAG_OPEN"] = 5] = "TAG_OPEN";
- State$1[State$1["END_TAG_OPEN"] = 6] = "END_TAG_OPEN";
- State$1[State$1["TAG_NAME"] = 7] = "TAG_NAME";
- State$1[State$1["RCDATA_LESS_THAN_SIGN"] = 8] = "RCDATA_LESS_THAN_SIGN";
- State$1[State$1["RCDATA_END_TAG_OPEN"] = 9] = "RCDATA_END_TAG_OPEN";
- State$1[State$1["RCDATA_END_TAG_NAME"] = 10] = "RCDATA_END_TAG_NAME";
- State$1[State$1["RAWTEXT_LESS_THAN_SIGN"] = 11] = "RAWTEXT_LESS_THAN_SIGN";
- State$1[State$1["RAWTEXT_END_TAG_OPEN"] = 12] = "RAWTEXT_END_TAG_OPEN";
- State$1[State$1["RAWTEXT_END_TAG_NAME"] = 13] = "RAWTEXT_END_TAG_NAME";
- State$1[State$1["SCRIPT_DATA_LESS_THAN_SIGN"] = 14] = "SCRIPT_DATA_LESS_THAN_SIGN";
- State$1[State$1["SCRIPT_DATA_END_TAG_OPEN"] = 15] = "SCRIPT_DATA_END_TAG_OPEN";
- State$1[State$1["SCRIPT_DATA_END_TAG_NAME"] = 16] = "SCRIPT_DATA_END_TAG_NAME";
- State$1[State$1["SCRIPT_DATA_ESCAPE_START"] = 17] = "SCRIPT_DATA_ESCAPE_START";
- State$1[State$1["SCRIPT_DATA_ESCAPE_START_DASH"] = 18] = "SCRIPT_DATA_ESCAPE_START_DASH";
- State$1[State$1["SCRIPT_DATA_ESCAPED"] = 19] = "SCRIPT_DATA_ESCAPED";
- State$1[State$1["SCRIPT_DATA_ESCAPED_DASH"] = 20] = "SCRIPT_DATA_ESCAPED_DASH";
- State$1[State$1["SCRIPT_DATA_ESCAPED_DASH_DASH"] = 21] = "SCRIPT_DATA_ESCAPED_DASH_DASH";
- State$1[State$1["SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN"] = 22] = "SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN";
- State$1[State$1["SCRIPT_DATA_ESCAPED_END_TAG_OPEN"] = 23] = "SCRIPT_DATA_ESCAPED_END_TAG_OPEN";
- State$1[State$1["SCRIPT_DATA_ESCAPED_END_TAG_NAME"] = 24] = "SCRIPT_DATA_ESCAPED_END_TAG_NAME";
- State$1[State$1["SCRIPT_DATA_DOUBLE_ESCAPE_START"] = 25] = "SCRIPT_DATA_DOUBLE_ESCAPE_START";
- State$1[State$1["SCRIPT_DATA_DOUBLE_ESCAPED"] = 26] = "SCRIPT_DATA_DOUBLE_ESCAPED";
- State$1[State$1["SCRIPT_DATA_DOUBLE_ESCAPED_DASH"] = 27] = "SCRIPT_DATA_DOUBLE_ESCAPED_DASH";
- State$1[State$1["SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH"] = 28] = "SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH";
- State$1[State$1["SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN"] = 29] = "SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN";
- State$1[State$1["SCRIPT_DATA_DOUBLE_ESCAPE_END"] = 30] = "SCRIPT_DATA_DOUBLE_ESCAPE_END";
- State$1[State$1["BEFORE_ATTRIBUTE_NAME"] = 31] = "BEFORE_ATTRIBUTE_NAME";
- State$1[State$1["ATTRIBUTE_NAME"] = 32] = "ATTRIBUTE_NAME";
- State$1[State$1["AFTER_ATTRIBUTE_NAME"] = 33] = "AFTER_ATTRIBUTE_NAME";
- State$1[State$1["BEFORE_ATTRIBUTE_VALUE"] = 34] = "BEFORE_ATTRIBUTE_VALUE";
- State$1[State$1["ATTRIBUTE_VALUE_DOUBLE_QUOTED"] = 35] = "ATTRIBUTE_VALUE_DOUBLE_QUOTED";
- State$1[State$1["ATTRIBUTE_VALUE_SINGLE_QUOTED"] = 36] = "ATTRIBUTE_VALUE_SINGLE_QUOTED";
- State$1[State$1["ATTRIBUTE_VALUE_UNQUOTED"] = 37] = "ATTRIBUTE_VALUE_UNQUOTED";
- State$1[State$1["AFTER_ATTRIBUTE_VALUE_QUOTED"] = 38] = "AFTER_ATTRIBUTE_VALUE_QUOTED";
- State$1[State$1["SELF_CLOSING_START_TAG"] = 39] = "SELF_CLOSING_START_TAG";
- State$1[State$1["BOGUS_COMMENT"] = 40] = "BOGUS_COMMENT";
- State$1[State$1["MARKUP_DECLARATION_OPEN"] = 41] = "MARKUP_DECLARATION_OPEN";
- State$1[State$1["COMMENT_START"] = 42] = "COMMENT_START";
- State$1[State$1["COMMENT_START_DASH"] = 43] = "COMMENT_START_DASH";
- State$1[State$1["COMMENT"] = 44] = "COMMENT";
- State$1[State$1["COMMENT_LESS_THAN_SIGN"] = 45] = "COMMENT_LESS_THAN_SIGN";
- State$1[State$1["COMMENT_LESS_THAN_SIGN_BANG"] = 46] = "COMMENT_LESS_THAN_SIGN_BANG";
- State$1[State$1["COMMENT_LESS_THAN_SIGN_BANG_DASH"] = 47] = "COMMENT_LESS_THAN_SIGN_BANG_DASH";
- State$1[State$1["COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH"] = 48] = "COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH";
- State$1[State$1["COMMENT_END_DASH"] = 49] = "COMMENT_END_DASH";
- State$1[State$1["COMMENT_END"] = 50] = "COMMENT_END";
- State$1[State$1["COMMENT_END_BANG"] = 51] = "COMMENT_END_BANG";
- State$1[State$1["DOCTYPE"] = 52] = "DOCTYPE";
- State$1[State$1["BEFORE_DOCTYPE_NAME"] = 53] = "BEFORE_DOCTYPE_NAME";
- State$1[State$1["DOCTYPE_NAME"] = 54] = "DOCTYPE_NAME";
- State$1[State$1["AFTER_DOCTYPE_NAME"] = 55] = "AFTER_DOCTYPE_NAME";
- State$1[State$1["AFTER_DOCTYPE_PUBLIC_KEYWORD"] = 56] = "AFTER_DOCTYPE_PUBLIC_KEYWORD";
- State$1[State$1["BEFORE_DOCTYPE_PUBLIC_IDENTIFIER"] = 57] = "BEFORE_DOCTYPE_PUBLIC_IDENTIFIER";
- State$1[State$1["DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED"] = 58] = "DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED";
- State$1[State$1["DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED"] = 59] = "DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED";
- State$1[State$1["AFTER_DOCTYPE_PUBLIC_IDENTIFIER"] = 60] = "AFTER_DOCTYPE_PUBLIC_IDENTIFIER";
- State$1[State$1["BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS"] = 61] = "BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS";
- State$1[State$1["AFTER_DOCTYPE_SYSTEM_KEYWORD"] = 62] = "AFTER_DOCTYPE_SYSTEM_KEYWORD";
- State$1[State$1["BEFORE_DOCTYPE_SYSTEM_IDENTIFIER"] = 63] = "BEFORE_DOCTYPE_SYSTEM_IDENTIFIER";
- State$1[State$1["DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED"] = 64] = "DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED";
- State$1[State$1["DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED"] = 65] = "DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED";
- State$1[State$1["AFTER_DOCTYPE_SYSTEM_IDENTIFIER"] = 66] = "AFTER_DOCTYPE_SYSTEM_IDENTIFIER";
- State$1[State$1["BOGUS_DOCTYPE"] = 67] = "BOGUS_DOCTYPE";
- State$1[State$1["CDATA_SECTION"] = 68] = "CDATA_SECTION";
- State$1[State$1["CDATA_SECTION_BRACKET"] = 69] = "CDATA_SECTION_BRACKET";
- State$1[State$1["CDATA_SECTION_END"] = 70] = "CDATA_SECTION_END";
- State$1[State$1["CHARACTER_REFERENCE"] = 71] = "CHARACTER_REFERENCE";
- State$1[State$1["AMBIGUOUS_AMPERSAND"] = 72] = "AMBIGUOUS_AMPERSAND";
-})(State || (State = {}));
-const TokenizerMode = {
- DATA: State.DATA,
- RCDATA: State.RCDATA,
- RAWTEXT: State.RAWTEXT,
- SCRIPT_DATA: State.SCRIPT_DATA,
- PLAINTEXT: State.PLAINTEXT,
- CDATA_SECTION: State.CDATA_SECTION
-};
-function isAsciiDigit(cp) {
- return cp >= CODE_POINTS.DIGIT_0 && cp <= CODE_POINTS.DIGIT_9;
-}
-function isAsciiUpper(cp) {
- return cp >= CODE_POINTS.LATIN_CAPITAL_A && cp <= CODE_POINTS.LATIN_CAPITAL_Z;
-}
-function isAsciiLower(cp) {
- return cp >= CODE_POINTS.LATIN_SMALL_A && cp <= CODE_POINTS.LATIN_SMALL_Z;
-}
-function isAsciiLetter(cp) {
- return isAsciiLower(cp) || isAsciiUpper(cp);
-}
-function isAsciiAlphaNumeric(cp) {
- return isAsciiLetter(cp) || isAsciiDigit(cp);
-}
-function toAsciiLower(cp) {
- return cp + 32;
-}
-function isWhitespace(cp) {
- return cp === CODE_POINTS.SPACE || cp === CODE_POINTS.LINE_FEED || cp === CODE_POINTS.TABULATION || cp === CODE_POINTS.FORM_FEED;
-}
-function isScriptDataDoubleEscapeSequenceEnd(cp) {
- return isWhitespace(cp) || cp === CODE_POINTS.SOLIDUS || cp === CODE_POINTS.GREATER_THAN_SIGN;
-}
-function getErrorForNumericCharacterReference(code) {
- if (code === CODE_POINTS.NULL) return ERR.nullCharacterReference;
- else if (code > 1114111) return ERR.characterReferenceOutsideUnicodeRange;
- else if (isSurrogate(code)) return ERR.surrogateCharacterReference;
- else if (isUndefinedCodePoint(code)) return ERR.noncharacterCharacterReference;
- else if (isControlCodePoint(code) || code === CODE_POINTS.CARRIAGE_RETURN) return ERR.controlCharacterReference;
- return null;
-}
-var Tokenizer = class {
- constructor(options, handler) {
- this.options = options;
- this.handler = handler;
- this.paused = false;
- /** Ensures that the parsing loop isn't run multiple times at once. */
- this.inLoop = false;
- /**
- * Indicates that the current adjusted node exists, is not an element in the HTML namespace,
- * and that it is not an integration point for either MathML or HTML.
- *
- * @see {@link https://html.spec.whatwg.org/multipage/parsing.html#tree-construction}
- */
- this.inForeignNode = false;
- this.lastStartTagName = "";
- this.active = false;
- this.state = State.DATA;
- this.returnState = State.DATA;
- this.entityStartPos = 0;
- this.consumedAfterSnapshot = -1;
- this.currentCharacterToken = null;
- this.currentToken = null;
- this.currentAttr = {
- name: "",
- value: ""
- };
- this.preprocessor = new Preprocessor(handler);
- this.currentLocation = this.getCurrentLocation(-1);
- this.entityDecoder = new EntityDecoder(htmlDecodeTree, (cp, consumed) => {
- this.preprocessor.pos = this.entityStartPos + consumed - 1;
- this._flushCodePointConsumedAsCharacterReference(cp);
- }, handler.onParseError ? {
- missingSemicolonAfterCharacterReference: () => {
- this._err(ERR.missingSemicolonAfterCharacterReference, 1);
- },
- absenceOfDigitsInNumericCharacterReference: (consumed) => {
- this._err(ERR.absenceOfDigitsInNumericCharacterReference, this.entityStartPos - this.preprocessor.pos + consumed);
- },
- validateNumericCharacterReference: (code) => {
- const error = getErrorForNumericCharacterReference(code);
- if (error) this._err(error, 1);
- }
- } : void 0);
- }
- _err(code, cpOffset = 0) {
- var _a$1, _b;
- (_b = (_a$1 = this.handler).onParseError) === null || _b === void 0 || _b.call(_a$1, this.preprocessor.getError(code, cpOffset));
- }
- getCurrentLocation(offset) {
- if (!this.options.sourceCodeLocationInfo) return null;
- return {
- startLine: this.preprocessor.line,
- startCol: this.preprocessor.col - offset,
- startOffset: this.preprocessor.offset - offset,
- endLine: -1,
- endCol: -1,
- endOffset: -1
- };
- }
- _runParsingLoop() {
- if (this.inLoop) return;
- this.inLoop = true;
- while (this.active && !this.paused) {
- this.consumedAfterSnapshot = 0;
- const cp = this._consume();
- if (!this._ensureHibernation()) this._callState(cp);
- }
- this.inLoop = false;
- }
- pause() {
- this.paused = true;
- }
- resume(writeCallback) {
- if (!this.paused) throw new Error("Parser was already resumed");
- this.paused = false;
- if (this.inLoop) return;
- this._runParsingLoop();
- if (!this.paused) writeCallback === null || writeCallback === void 0 || writeCallback();
- }
- write(chunk, isLastChunk, writeCallback) {
- this.active = true;
- this.preprocessor.write(chunk, isLastChunk);
- this._runParsingLoop();
- if (!this.paused) writeCallback === null || writeCallback === void 0 || writeCallback();
- }
- insertHtmlAtCurrentPos(chunk) {
- this.active = true;
- this.preprocessor.insertHtmlAtCurrentPos(chunk);
- this._runParsingLoop();
- }
- _ensureHibernation() {
- if (this.preprocessor.endOfChunkHit) {
- this.preprocessor.retreat(this.consumedAfterSnapshot);
- this.consumedAfterSnapshot = 0;
- this.active = false;
- return true;
- }
- return false;
- }
- _consume() {
- this.consumedAfterSnapshot++;
- return this.preprocessor.advance();
- }
- _advanceBy(count) {
- this.consumedAfterSnapshot += count;
- for (let i = 0; i < count; i++) this.preprocessor.advance();
- }
- _consumeSequenceIfMatch(pattern, caseSensitive) {
- if (this.preprocessor.startsWith(pattern, caseSensitive)) {
- this._advanceBy(pattern.length - 1);
- return true;
- }
- return false;
- }
- _createStartTagToken() {
- this.currentToken = {
- type: TokenType.START_TAG,
- tagName: "",
- tagID: TAG_ID.UNKNOWN,
- selfClosing: false,
- ackSelfClosing: false,
- attrs: [],
- location: this.getCurrentLocation(1)
- };
- }
- _createEndTagToken() {
- this.currentToken = {
- type: TokenType.END_TAG,
- tagName: "",
- tagID: TAG_ID.UNKNOWN,
- selfClosing: false,
- ackSelfClosing: false,
- attrs: [],
- location: this.getCurrentLocation(2)
- };
- }
- _createCommentToken(offset) {
- this.currentToken = {
- type: TokenType.COMMENT,
- data: "",
- location: this.getCurrentLocation(offset)
- };
- }
- _createDoctypeToken(initialName) {
- this.currentToken = {
- type: TokenType.DOCTYPE,
- name: initialName,
- forceQuirks: false,
- publicId: null,
- systemId: null,
- location: this.currentLocation
- };
- }
- _createCharacterToken(type, chars) {
- this.currentCharacterToken = {
- type,
- chars,
- location: this.currentLocation
- };
- }
- _createAttr(attrNameFirstCh) {
- this.currentAttr = {
- name: attrNameFirstCh,
- value: ""
- };
- this.currentLocation = this.getCurrentLocation(0);
- }
- _leaveAttrName() {
- var _a$1;
- var _b;
- const token = this.currentToken;
- if (getTokenAttr(token, this.currentAttr.name) === null) {
- token.attrs.push(this.currentAttr);
- if (token.location && this.currentLocation) {
- const attrLocations = (_a$1 = (_b = token.location).attrs) !== null && _a$1 !== void 0 ? _a$1 : _b.attrs = Object.create(null);
- attrLocations[this.currentAttr.name] = this.currentLocation;
- this._leaveAttrValue();
- }
- } else this._err(ERR.duplicateAttribute);
- }
- _leaveAttrValue() {
- if (this.currentLocation) {
- this.currentLocation.endLine = this.preprocessor.line;
- this.currentLocation.endCol = this.preprocessor.col;
- this.currentLocation.endOffset = this.preprocessor.offset;
- }
- }
- prepareToken(ct) {
- this._emitCurrentCharacterToken(ct.location);
- this.currentToken = null;
- if (ct.location) {
- ct.location.endLine = this.preprocessor.line;
- ct.location.endCol = this.preprocessor.col + 1;
- ct.location.endOffset = this.preprocessor.offset + 1;
- }
- this.currentLocation = this.getCurrentLocation(-1);
- }
- emitCurrentTagToken() {
- const ct = this.currentToken;
- this.prepareToken(ct);
- ct.tagID = getTagID(ct.tagName);
- if (ct.type === TokenType.START_TAG) {
- this.lastStartTagName = ct.tagName;
- this.handler.onStartTag(ct);
- } else {
- if (ct.attrs.length > 0) this._err(ERR.endTagWithAttributes);
- if (ct.selfClosing) this._err(ERR.endTagWithTrailingSolidus);
- this.handler.onEndTag(ct);
- }
- this.preprocessor.dropParsedChunk();
- }
- emitCurrentComment(ct) {
- this.prepareToken(ct);
- this.handler.onComment(ct);
- this.preprocessor.dropParsedChunk();
- }
- emitCurrentDoctype(ct) {
- this.prepareToken(ct);
- this.handler.onDoctype(ct);
- this.preprocessor.dropParsedChunk();
- }
- _emitCurrentCharacterToken(nextLocation) {
- if (this.currentCharacterToken) {
- if (nextLocation && this.currentCharacterToken.location) {
- this.currentCharacterToken.location.endLine = nextLocation.startLine;
- this.currentCharacterToken.location.endCol = nextLocation.startCol;
- this.currentCharacterToken.location.endOffset = nextLocation.startOffset;
- }
- switch (this.currentCharacterToken.type) {
- case TokenType.CHARACTER:
- this.handler.onCharacter(this.currentCharacterToken);
- break;
- case TokenType.NULL_CHARACTER:
- this.handler.onNullCharacter(this.currentCharacterToken);
- break;
- case TokenType.WHITESPACE_CHARACTER:
- this.handler.onWhitespaceCharacter(this.currentCharacterToken);
- break;
- }
- this.currentCharacterToken = null;
- }
- }
- _emitEOFToken() {
- const location = this.getCurrentLocation(0);
- if (location) {
- location.endLine = location.startLine;
- location.endCol = location.startCol;
- location.endOffset = location.startOffset;
- }
- this._emitCurrentCharacterToken(location);
- this.handler.onEof({
- type: TokenType.EOF,
- location
- });
- this.active = false;
- }
- _appendCharToCurrentCharacterToken(type, ch) {
- if (this.currentCharacterToken) if (this.currentCharacterToken.type === type) {
- this.currentCharacterToken.chars += ch;
- return;
- } else {
- this.currentLocation = this.getCurrentLocation(0);
- this._emitCurrentCharacterToken(this.currentLocation);
- this.preprocessor.dropParsedChunk();
- }
- this._createCharacterToken(type, ch);
- }
- _emitCodePoint(cp) {
- const type = isWhitespace(cp) ? TokenType.WHITESPACE_CHARACTER : cp === CODE_POINTS.NULL ? TokenType.NULL_CHARACTER : TokenType.CHARACTER;
- this._appendCharToCurrentCharacterToken(type, String.fromCodePoint(cp));
- }
- _emitChars(ch) {
- this._appendCharToCurrentCharacterToken(TokenType.CHARACTER, ch);
- }
- _startCharacterReference() {
- this.returnState = this.state;
- this.state = State.CHARACTER_REFERENCE;
- this.entityStartPos = this.preprocessor.pos;
- this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute() ? DecodingMode.Attribute : DecodingMode.Legacy);
- }
- _isCharacterReferenceInAttribute() {
- return this.returnState === State.ATTRIBUTE_VALUE_DOUBLE_QUOTED || this.returnState === State.ATTRIBUTE_VALUE_SINGLE_QUOTED || this.returnState === State.ATTRIBUTE_VALUE_UNQUOTED;
- }
- _flushCodePointConsumedAsCharacterReference(cp) {
- if (this._isCharacterReferenceInAttribute()) this.currentAttr.value += String.fromCodePoint(cp);
- else this._emitCodePoint(cp);
- }
- _callState(cp) {
- switch (this.state) {
- case State.DATA:
- this._stateData(cp);
- break;
- case State.RCDATA:
- this._stateRcdata(cp);
- break;
- case State.RAWTEXT:
- this._stateRawtext(cp);
- break;
- case State.SCRIPT_DATA:
- this._stateScriptData(cp);
- break;
- case State.PLAINTEXT:
- this._statePlaintext(cp);
- break;
- case State.TAG_OPEN:
- this._stateTagOpen(cp);
- break;
- case State.END_TAG_OPEN:
- this._stateEndTagOpen(cp);
- break;
- case State.TAG_NAME:
- this._stateTagName(cp);
- break;
- case State.RCDATA_LESS_THAN_SIGN:
- this._stateRcdataLessThanSign(cp);
- break;
- case State.RCDATA_END_TAG_OPEN:
- this._stateRcdataEndTagOpen(cp);
- break;
- case State.RCDATA_END_TAG_NAME:
- this._stateRcdataEndTagName(cp);
- break;
- case State.RAWTEXT_LESS_THAN_SIGN:
- this._stateRawtextLessThanSign(cp);
- break;
- case State.RAWTEXT_END_TAG_OPEN:
- this._stateRawtextEndTagOpen(cp);
- break;
- case State.RAWTEXT_END_TAG_NAME:
- this._stateRawtextEndTagName(cp);
- break;
- case State.SCRIPT_DATA_LESS_THAN_SIGN:
- this._stateScriptDataLessThanSign(cp);
- break;
- case State.SCRIPT_DATA_END_TAG_OPEN:
- this._stateScriptDataEndTagOpen(cp);
- break;
- case State.SCRIPT_DATA_END_TAG_NAME:
- this._stateScriptDataEndTagName(cp);
- break;
- case State.SCRIPT_DATA_ESCAPE_START:
- this._stateScriptDataEscapeStart(cp);
- break;
- case State.SCRIPT_DATA_ESCAPE_START_DASH:
- this._stateScriptDataEscapeStartDash(cp);
- break;
- case State.SCRIPT_DATA_ESCAPED:
- this._stateScriptDataEscaped(cp);
- break;
- case State.SCRIPT_DATA_ESCAPED_DASH:
- this._stateScriptDataEscapedDash(cp);
- break;
- case State.SCRIPT_DATA_ESCAPED_DASH_DASH:
- this._stateScriptDataEscapedDashDash(cp);
- break;
- case State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:
- this._stateScriptDataEscapedLessThanSign(cp);
- break;
- case State.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:
- this._stateScriptDataEscapedEndTagOpen(cp);
- break;
- case State.SCRIPT_DATA_ESCAPED_END_TAG_NAME:
- this._stateScriptDataEscapedEndTagName(cp);
- break;
- case State.SCRIPT_DATA_DOUBLE_ESCAPE_START:
- this._stateScriptDataDoubleEscapeStart(cp);
- break;
- case State.SCRIPT_DATA_DOUBLE_ESCAPED:
- this._stateScriptDataDoubleEscaped(cp);
- break;
- case State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:
- this._stateScriptDataDoubleEscapedDash(cp);
- break;
- case State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:
- this._stateScriptDataDoubleEscapedDashDash(cp);
- break;
- case State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:
- this._stateScriptDataDoubleEscapedLessThanSign(cp);
- break;
- case State.SCRIPT_DATA_DOUBLE_ESCAPE_END:
- this._stateScriptDataDoubleEscapeEnd(cp);
- break;
- case State.BEFORE_ATTRIBUTE_NAME:
- this._stateBeforeAttributeName(cp);
- break;
- case State.ATTRIBUTE_NAME:
- this._stateAttributeName(cp);
- break;
- case State.AFTER_ATTRIBUTE_NAME:
- this._stateAfterAttributeName(cp);
- break;
- case State.BEFORE_ATTRIBUTE_VALUE:
- this._stateBeforeAttributeValue(cp);
- break;
- case State.ATTRIBUTE_VALUE_DOUBLE_QUOTED:
- this._stateAttributeValueDoubleQuoted(cp);
- break;
- case State.ATTRIBUTE_VALUE_SINGLE_QUOTED:
- this._stateAttributeValueSingleQuoted(cp);
- break;
- case State.ATTRIBUTE_VALUE_UNQUOTED:
- this._stateAttributeValueUnquoted(cp);
- break;
- case State.AFTER_ATTRIBUTE_VALUE_QUOTED:
- this._stateAfterAttributeValueQuoted(cp);
- break;
- case State.SELF_CLOSING_START_TAG:
- this._stateSelfClosingStartTag(cp);
- break;
- case State.BOGUS_COMMENT:
- this._stateBogusComment(cp);
- break;
- case State.MARKUP_DECLARATION_OPEN:
- this._stateMarkupDeclarationOpen(cp);
- break;
- case State.COMMENT_START:
- this._stateCommentStart(cp);
- break;
- case State.COMMENT_START_DASH:
- this._stateCommentStartDash(cp);
- break;
- case State.COMMENT:
- this._stateComment(cp);
- break;
- case State.COMMENT_LESS_THAN_SIGN:
- this._stateCommentLessThanSign(cp);
- break;
- case State.COMMENT_LESS_THAN_SIGN_BANG:
- this._stateCommentLessThanSignBang(cp);
- break;
- case State.COMMENT_LESS_THAN_SIGN_BANG_DASH:
- this._stateCommentLessThanSignBangDash(cp);
- break;
- case State.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:
- this._stateCommentLessThanSignBangDashDash(cp);
- break;
- case State.COMMENT_END_DASH:
- this._stateCommentEndDash(cp);
- break;
- case State.COMMENT_END:
- this._stateCommentEnd(cp);
- break;
- case State.COMMENT_END_BANG:
- this._stateCommentEndBang(cp);
- break;
- case State.DOCTYPE:
- this._stateDoctype(cp);
- break;
- case State.BEFORE_DOCTYPE_NAME:
- this._stateBeforeDoctypeName(cp);
- break;
- case State.DOCTYPE_NAME:
- this._stateDoctypeName(cp);
- break;
- case State.AFTER_DOCTYPE_NAME:
- this._stateAfterDoctypeName(cp);
- break;
- case State.AFTER_DOCTYPE_PUBLIC_KEYWORD:
- this._stateAfterDoctypePublicKeyword(cp);
- break;
- case State.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:
- this._stateBeforeDoctypePublicIdentifier(cp);
- break;
- case State.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:
- this._stateDoctypePublicIdentifierDoubleQuoted(cp);
- break;
- case State.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:
- this._stateDoctypePublicIdentifierSingleQuoted(cp);
- break;
- case State.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:
- this._stateAfterDoctypePublicIdentifier(cp);
- break;
- case State.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:
- this._stateBetweenDoctypePublicAndSystemIdentifiers(cp);
- break;
- case State.AFTER_DOCTYPE_SYSTEM_KEYWORD:
- this._stateAfterDoctypeSystemKeyword(cp);
- break;
- case State.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:
- this._stateBeforeDoctypeSystemIdentifier(cp);
- break;
- case State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:
- this._stateDoctypeSystemIdentifierDoubleQuoted(cp);
- break;
- case State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:
- this._stateDoctypeSystemIdentifierSingleQuoted(cp);
- break;
- case State.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:
- this._stateAfterDoctypeSystemIdentifier(cp);
- break;
- case State.BOGUS_DOCTYPE:
- this._stateBogusDoctype(cp);
- break;
- case State.CDATA_SECTION:
- this._stateCdataSection(cp);
- break;
- case State.CDATA_SECTION_BRACKET:
- this._stateCdataSectionBracket(cp);
- break;
- case State.CDATA_SECTION_END:
- this._stateCdataSectionEnd(cp);
- break;
- case State.CHARACTER_REFERENCE:
- this._stateCharacterReference();
- break;
- case State.AMBIGUOUS_AMPERSAND:
- this._stateAmbiguousAmpersand(cp);
- break;
- default: throw new Error("Unknown state");
- }
- }
- _stateData(cp) {
- switch (cp) {
- case CODE_POINTS.LESS_THAN_SIGN:
- this.state = State.TAG_OPEN;
- break;
- case CODE_POINTS.AMPERSAND:
- this._startCharacterReference();
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- this._emitCodePoint(cp);
- break;
- case CODE_POINTS.EOF:
- this._emitEOFToken();
- break;
- default: this._emitCodePoint(cp);
- }
- }
- _stateRcdata(cp) {
- switch (cp) {
- case CODE_POINTS.AMPERSAND:
- this._startCharacterReference();
- break;
- case CODE_POINTS.LESS_THAN_SIGN:
- this.state = State.RCDATA_LESS_THAN_SIGN;
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- this._emitChars(REPLACEMENT_CHARACTER);
- break;
- case CODE_POINTS.EOF:
- this._emitEOFToken();
- break;
- default: this._emitCodePoint(cp);
- }
- }
- _stateRawtext(cp) {
- switch (cp) {
- case CODE_POINTS.LESS_THAN_SIGN:
- this.state = State.RAWTEXT_LESS_THAN_SIGN;
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- this._emitChars(REPLACEMENT_CHARACTER);
- break;
- case CODE_POINTS.EOF:
- this._emitEOFToken();
- break;
- default: this._emitCodePoint(cp);
- }
- }
- _stateScriptData(cp) {
- switch (cp) {
- case CODE_POINTS.LESS_THAN_SIGN:
- this.state = State.SCRIPT_DATA_LESS_THAN_SIGN;
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- this._emitChars(REPLACEMENT_CHARACTER);
- break;
- case CODE_POINTS.EOF:
- this._emitEOFToken();
- break;
- default: this._emitCodePoint(cp);
- }
- }
- _statePlaintext(cp) {
- switch (cp) {
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- this._emitChars(REPLACEMENT_CHARACTER);
- break;
- case CODE_POINTS.EOF:
- this._emitEOFToken();
- break;
- default: this._emitCodePoint(cp);
- }
- }
- _stateTagOpen(cp) {
- if (isAsciiLetter(cp)) {
- this._createStartTagToken();
- this.state = State.TAG_NAME;
- this._stateTagName(cp);
- } else switch (cp) {
- case CODE_POINTS.EXCLAMATION_MARK:
- this.state = State.MARKUP_DECLARATION_OPEN;
- break;
- case CODE_POINTS.SOLIDUS:
- this.state = State.END_TAG_OPEN;
- break;
- case CODE_POINTS.QUESTION_MARK:
- this._err(ERR.unexpectedQuestionMarkInsteadOfTagName);
- this._createCommentToken(1);
- this.state = State.BOGUS_COMMENT;
- this._stateBogusComment(cp);
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofBeforeTagName);
- this._emitChars("<");
- this._emitEOFToken();
- break;
- default:
- this._err(ERR.invalidFirstCharacterOfTagName);
- this._emitChars("<");
- this.state = State.DATA;
- this._stateData(cp);
- }
- }
- _stateEndTagOpen(cp) {
- if (isAsciiLetter(cp)) {
- this._createEndTagToken();
- this.state = State.TAG_NAME;
- this._stateTagName(cp);
- } else switch (cp) {
- case CODE_POINTS.GREATER_THAN_SIGN:
- this._err(ERR.missingEndTagName);
- this.state = State.DATA;
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofBeforeTagName);
- this._emitChars("</");
- this._emitEOFToken();
- break;
- default:
- this._err(ERR.invalidFirstCharacterOfTagName);
- this._createCommentToken(2);
- this.state = State.BOGUS_COMMENT;
- this._stateBogusComment(cp);
- }
- }
- _stateTagName(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED:
- this.state = State.BEFORE_ATTRIBUTE_NAME;
- break;
- case CODE_POINTS.SOLIDUS:
- this.state = State.SELF_CLOSING_START_TAG;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this.state = State.DATA;
- this.emitCurrentTagToken();
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- token.tagName += REPLACEMENT_CHARACTER;
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInTag);
- this._emitEOFToken();
- break;
- default: token.tagName += String.fromCodePoint(isAsciiUpper(cp) ? toAsciiLower(cp) : cp);
- }
- }
- _stateRcdataLessThanSign(cp) {
- if (cp === CODE_POINTS.SOLIDUS) this.state = State.RCDATA_END_TAG_OPEN;
- else {
- this._emitChars("<");
- this.state = State.RCDATA;
- this._stateRcdata(cp);
- }
- }
- _stateRcdataEndTagOpen(cp) {
- if (isAsciiLetter(cp)) {
- this.state = State.RCDATA_END_TAG_NAME;
- this._stateRcdataEndTagName(cp);
- } else {
- this._emitChars("</");
- this.state = State.RCDATA;
- this._stateRcdata(cp);
- }
- }
- handleSpecialEndTag(_cp) {
- if (!this.preprocessor.startsWith(this.lastStartTagName, false)) return !this._ensureHibernation();
- this._createEndTagToken();
- const token = this.currentToken;
- token.tagName = this.lastStartTagName;
- switch (this.preprocessor.peek(this.lastStartTagName.length)) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED:
- this._advanceBy(this.lastStartTagName.length);
- this.state = State.BEFORE_ATTRIBUTE_NAME;
- return false;
- case CODE_POINTS.SOLIDUS:
- this._advanceBy(this.lastStartTagName.length);
- this.state = State.SELF_CLOSING_START_TAG;
- return false;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this._advanceBy(this.lastStartTagName.length);
- this.emitCurrentTagToken();
- this.state = State.DATA;
- return false;
- default: return !this._ensureHibernation();
- }
- }
- _stateRcdataEndTagName(cp) {
- if (this.handleSpecialEndTag(cp)) {
- this._emitChars("</");
- this.state = State.RCDATA;
- this._stateRcdata(cp);
- }
- }
- _stateRawtextLessThanSign(cp) {
- if (cp === CODE_POINTS.SOLIDUS) this.state = State.RAWTEXT_END_TAG_OPEN;
- else {
- this._emitChars("<");
- this.state = State.RAWTEXT;
- this._stateRawtext(cp);
- }
- }
- _stateRawtextEndTagOpen(cp) {
- if (isAsciiLetter(cp)) {
- this.state = State.RAWTEXT_END_TAG_NAME;
- this._stateRawtextEndTagName(cp);
- } else {
- this._emitChars("</");
- this.state = State.RAWTEXT;
- this._stateRawtext(cp);
- }
- }
- _stateRawtextEndTagName(cp) {
- if (this.handleSpecialEndTag(cp)) {
- this._emitChars("</");
- this.state = State.RAWTEXT;
- this._stateRawtext(cp);
- }
- }
- _stateScriptDataLessThanSign(cp) {
- switch (cp) {
- case CODE_POINTS.SOLIDUS:
- this.state = State.SCRIPT_DATA_END_TAG_OPEN;
- break;
- case CODE_POINTS.EXCLAMATION_MARK:
- this.state = State.SCRIPT_DATA_ESCAPE_START;
- this._emitChars("<!");
- break;
- default:
- this._emitChars("<");
- this.state = State.SCRIPT_DATA;
- this._stateScriptData(cp);
- }
- }
- _stateScriptDataEndTagOpen(cp) {
- if (isAsciiLetter(cp)) {
- this.state = State.SCRIPT_DATA_END_TAG_NAME;
- this._stateScriptDataEndTagName(cp);
- } else {
- this._emitChars("</");
- this.state = State.SCRIPT_DATA;
- this._stateScriptData(cp);
- }
- }
- _stateScriptDataEndTagName(cp) {
- if (this.handleSpecialEndTag(cp)) {
- this._emitChars("</");
- this.state = State.SCRIPT_DATA;
- this._stateScriptData(cp);
- }
- }
- _stateScriptDataEscapeStart(cp) {
- if (cp === CODE_POINTS.HYPHEN_MINUS) {
- this.state = State.SCRIPT_DATA_ESCAPE_START_DASH;
- this._emitChars("-");
- } else {
- this.state = State.SCRIPT_DATA;
- this._stateScriptData(cp);
- }
- }
- _stateScriptDataEscapeStartDash(cp) {
- if (cp === CODE_POINTS.HYPHEN_MINUS) {
- this.state = State.SCRIPT_DATA_ESCAPED_DASH_DASH;
- this._emitChars("-");
- } else {
- this.state = State.SCRIPT_DATA;
- this._stateScriptData(cp);
- }
- }
- _stateScriptDataEscaped(cp) {
- switch (cp) {
- case CODE_POINTS.HYPHEN_MINUS:
- this.state = State.SCRIPT_DATA_ESCAPED_DASH;
- this._emitChars("-");
- break;
- case CODE_POINTS.LESS_THAN_SIGN:
- this.state = State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- this._emitChars(REPLACEMENT_CHARACTER);
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInScriptHtmlCommentLikeText);
- this._emitEOFToken();
- break;
- default: this._emitCodePoint(cp);
- }
- }
- _stateScriptDataEscapedDash(cp) {
- switch (cp) {
- case CODE_POINTS.HYPHEN_MINUS:
- this.state = State.SCRIPT_DATA_ESCAPED_DASH_DASH;
- this._emitChars("-");
- break;
- case CODE_POINTS.LESS_THAN_SIGN:
- this.state = State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- this.state = State.SCRIPT_DATA_ESCAPED;
- this._emitChars(REPLACEMENT_CHARACTER);
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInScriptHtmlCommentLikeText);
- this._emitEOFToken();
- break;
- default:
- this.state = State.SCRIPT_DATA_ESCAPED;
- this._emitCodePoint(cp);
- }
- }
- _stateScriptDataEscapedDashDash(cp) {
- switch (cp) {
- case CODE_POINTS.HYPHEN_MINUS:
- this._emitChars("-");
- break;
- case CODE_POINTS.LESS_THAN_SIGN:
- this.state = State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this.state = State.SCRIPT_DATA;
- this._emitChars(">");
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- this.state = State.SCRIPT_DATA_ESCAPED;
- this._emitChars(REPLACEMENT_CHARACTER);
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInScriptHtmlCommentLikeText);
- this._emitEOFToken();
- break;
- default:
- this.state = State.SCRIPT_DATA_ESCAPED;
- this._emitCodePoint(cp);
- }
- }
- _stateScriptDataEscapedLessThanSign(cp) {
- if (cp === CODE_POINTS.SOLIDUS) this.state = State.SCRIPT_DATA_ESCAPED_END_TAG_OPEN;
- else if (isAsciiLetter(cp)) {
- this._emitChars("<");
- this.state = State.SCRIPT_DATA_DOUBLE_ESCAPE_START;
- this._stateScriptDataDoubleEscapeStart(cp);
- } else {
- this._emitChars("<");
- this.state = State.SCRIPT_DATA_ESCAPED;
- this._stateScriptDataEscaped(cp);
- }
- }
- _stateScriptDataEscapedEndTagOpen(cp) {
- if (isAsciiLetter(cp)) {
- this.state = State.SCRIPT_DATA_ESCAPED_END_TAG_NAME;
- this._stateScriptDataEscapedEndTagName(cp);
- } else {
- this._emitChars("</");
- this.state = State.SCRIPT_DATA_ESCAPED;
- this._stateScriptDataEscaped(cp);
- }
- }
- _stateScriptDataEscapedEndTagName(cp) {
- if (this.handleSpecialEndTag(cp)) {
- this._emitChars("</");
- this.state = State.SCRIPT_DATA_ESCAPED;
- this._stateScriptDataEscaped(cp);
- }
- }
- _stateScriptDataDoubleEscapeStart(cp) {
- if (this.preprocessor.startsWith(SEQUENCES.SCRIPT, false) && isScriptDataDoubleEscapeSequenceEnd(this.preprocessor.peek(SEQUENCES.SCRIPT.length))) {
- this._emitCodePoint(cp);
- for (let i = 0; i < SEQUENCES.SCRIPT.length; i++) this._emitCodePoint(this._consume());
- this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
- } else if (!this._ensureHibernation()) {
- this.state = State.SCRIPT_DATA_ESCAPED;
- this._stateScriptDataEscaped(cp);
- }
- }
- _stateScriptDataDoubleEscaped(cp) {
- switch (cp) {
- case CODE_POINTS.HYPHEN_MINUS:
- this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH;
- this._emitChars("-");
- break;
- case CODE_POINTS.LESS_THAN_SIGN:
- this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN;
- this._emitChars("<");
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- this._emitChars(REPLACEMENT_CHARACTER);
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInScriptHtmlCommentLikeText);
- this._emitEOFToken();
- break;
- default: this._emitCodePoint(cp);
- }
- }
- _stateScriptDataDoubleEscapedDash(cp) {
- switch (cp) {
- case CODE_POINTS.HYPHEN_MINUS:
- this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH;
- this._emitChars("-");
- break;
- case CODE_POINTS.LESS_THAN_SIGN:
- this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN;
- this._emitChars("<");
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
- this._emitChars(REPLACEMENT_CHARACTER);
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInScriptHtmlCommentLikeText);
- this._emitEOFToken();
- break;
- default:
- this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
- this._emitCodePoint(cp);
- }
- }
- _stateScriptDataDoubleEscapedDashDash(cp) {
- switch (cp) {
- case CODE_POINTS.HYPHEN_MINUS:
- this._emitChars("-");
- break;
- case CODE_POINTS.LESS_THAN_SIGN:
- this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN;
- this._emitChars("<");
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this.state = State.SCRIPT_DATA;
- this._emitChars(">");
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
- this._emitChars(REPLACEMENT_CHARACTER);
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInScriptHtmlCommentLikeText);
- this._emitEOFToken();
- break;
- default:
- this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
- this._emitCodePoint(cp);
- }
- }
- _stateScriptDataDoubleEscapedLessThanSign(cp) {
- if (cp === CODE_POINTS.SOLIDUS) {
- this.state = State.SCRIPT_DATA_DOUBLE_ESCAPE_END;
- this._emitChars("/");
- } else {
- this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
- this._stateScriptDataDoubleEscaped(cp);
- }
- }
- _stateScriptDataDoubleEscapeEnd(cp) {
- if (this.preprocessor.startsWith(SEQUENCES.SCRIPT, false) && isScriptDataDoubleEscapeSequenceEnd(this.preprocessor.peek(SEQUENCES.SCRIPT.length))) {
- this._emitCodePoint(cp);
- for (let i = 0; i < SEQUENCES.SCRIPT.length; i++) this._emitCodePoint(this._consume());
- this.state = State.SCRIPT_DATA_ESCAPED;
- } else if (!this._ensureHibernation()) {
- this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
- this._stateScriptDataDoubleEscaped(cp);
- }
- }
- _stateBeforeAttributeName(cp) {
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED: break;
- case CODE_POINTS.SOLIDUS:
- case CODE_POINTS.GREATER_THAN_SIGN:
- case CODE_POINTS.EOF:
- this.state = State.AFTER_ATTRIBUTE_NAME;
- this._stateAfterAttributeName(cp);
- break;
- case CODE_POINTS.EQUALS_SIGN:
- this._err(ERR.unexpectedEqualsSignBeforeAttributeName);
- this._createAttr("=");
- this.state = State.ATTRIBUTE_NAME;
- break;
- default:
- this._createAttr("");
- this.state = State.ATTRIBUTE_NAME;
- this._stateAttributeName(cp);
- }
- }
- _stateAttributeName(cp) {
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED:
- case CODE_POINTS.SOLIDUS:
- case CODE_POINTS.GREATER_THAN_SIGN:
- case CODE_POINTS.EOF:
- this._leaveAttrName();
- this.state = State.AFTER_ATTRIBUTE_NAME;
- this._stateAfterAttributeName(cp);
- break;
- case CODE_POINTS.EQUALS_SIGN:
- this._leaveAttrName();
- this.state = State.BEFORE_ATTRIBUTE_VALUE;
- break;
- case CODE_POINTS.QUOTATION_MARK:
- case CODE_POINTS.APOSTROPHE:
- case CODE_POINTS.LESS_THAN_SIGN:
- this._err(ERR.unexpectedCharacterInAttributeName);
- this.currentAttr.name += String.fromCodePoint(cp);
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- this.currentAttr.name += REPLACEMENT_CHARACTER;
- break;
- default: this.currentAttr.name += String.fromCodePoint(isAsciiUpper(cp) ? toAsciiLower(cp) : cp);
- }
- }
- _stateAfterAttributeName(cp) {
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED: break;
- case CODE_POINTS.SOLIDUS:
- this.state = State.SELF_CLOSING_START_TAG;
- break;
- case CODE_POINTS.EQUALS_SIGN:
- this.state = State.BEFORE_ATTRIBUTE_VALUE;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this.state = State.DATA;
- this.emitCurrentTagToken();
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInTag);
- this._emitEOFToken();
- break;
- default:
- this._createAttr("");
- this.state = State.ATTRIBUTE_NAME;
- this._stateAttributeName(cp);
- }
- }
- _stateBeforeAttributeValue(cp) {
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED: break;
- case CODE_POINTS.QUOTATION_MARK:
- this.state = State.ATTRIBUTE_VALUE_DOUBLE_QUOTED;
- break;
- case CODE_POINTS.APOSTROPHE:
- this.state = State.ATTRIBUTE_VALUE_SINGLE_QUOTED;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this._err(ERR.missingAttributeValue);
- this.state = State.DATA;
- this.emitCurrentTagToken();
- break;
- default:
- this.state = State.ATTRIBUTE_VALUE_UNQUOTED;
- this._stateAttributeValueUnquoted(cp);
- }
- }
- _stateAttributeValueDoubleQuoted(cp) {
- switch (cp) {
- case CODE_POINTS.QUOTATION_MARK:
- this.state = State.AFTER_ATTRIBUTE_VALUE_QUOTED;
- break;
- case CODE_POINTS.AMPERSAND:
- this._startCharacterReference();
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- this.currentAttr.value += REPLACEMENT_CHARACTER;
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInTag);
- this._emitEOFToken();
- break;
- default: this.currentAttr.value += String.fromCodePoint(cp);
- }
- }
- _stateAttributeValueSingleQuoted(cp) {
- switch (cp) {
- case CODE_POINTS.APOSTROPHE:
- this.state = State.AFTER_ATTRIBUTE_VALUE_QUOTED;
- break;
- case CODE_POINTS.AMPERSAND:
- this._startCharacterReference();
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- this.currentAttr.value += REPLACEMENT_CHARACTER;
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInTag);
- this._emitEOFToken();
- break;
- default: this.currentAttr.value += String.fromCodePoint(cp);
- }
- }
- _stateAttributeValueUnquoted(cp) {
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED:
- this._leaveAttrValue();
- this.state = State.BEFORE_ATTRIBUTE_NAME;
- break;
- case CODE_POINTS.AMPERSAND:
- this._startCharacterReference();
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this._leaveAttrValue();
- this.state = State.DATA;
- this.emitCurrentTagToken();
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- this.currentAttr.value += REPLACEMENT_CHARACTER;
- break;
- case CODE_POINTS.QUOTATION_MARK:
- case CODE_POINTS.APOSTROPHE:
- case CODE_POINTS.LESS_THAN_SIGN:
- case CODE_POINTS.EQUALS_SIGN:
- case CODE_POINTS.GRAVE_ACCENT:
- this._err(ERR.unexpectedCharacterInUnquotedAttributeValue);
- this.currentAttr.value += String.fromCodePoint(cp);
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInTag);
- this._emitEOFToken();
- break;
- default: this.currentAttr.value += String.fromCodePoint(cp);
- }
- }
- _stateAfterAttributeValueQuoted(cp) {
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED:
- this._leaveAttrValue();
- this.state = State.BEFORE_ATTRIBUTE_NAME;
- break;
- case CODE_POINTS.SOLIDUS:
- this._leaveAttrValue();
- this.state = State.SELF_CLOSING_START_TAG;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this._leaveAttrValue();
- this.state = State.DATA;
- this.emitCurrentTagToken();
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInTag);
- this._emitEOFToken();
- break;
- default:
- this._err(ERR.missingWhitespaceBetweenAttributes);
- this.state = State.BEFORE_ATTRIBUTE_NAME;
- this._stateBeforeAttributeName(cp);
- }
- }
- _stateSelfClosingStartTag(cp) {
- switch (cp) {
- case CODE_POINTS.GREATER_THAN_SIGN: {
- const token = this.currentToken;
- token.selfClosing = true;
- this.state = State.DATA;
- this.emitCurrentTagToken();
- break;
- }
- case CODE_POINTS.EOF:
- this._err(ERR.eofInTag);
- this._emitEOFToken();
- break;
- default:
- this._err(ERR.unexpectedSolidusInTag);
- this.state = State.BEFORE_ATTRIBUTE_NAME;
- this._stateBeforeAttributeName(cp);
- }
- }
- _stateBogusComment(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.GREATER_THAN_SIGN:
- this.state = State.DATA;
- this.emitCurrentComment(token);
- break;
- case CODE_POINTS.EOF:
- this.emitCurrentComment(token);
- this._emitEOFToken();
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- token.data += REPLACEMENT_CHARACTER;
- break;
- default: token.data += String.fromCodePoint(cp);
- }
- }
- _stateMarkupDeclarationOpen(cp) {
- if (this._consumeSequenceIfMatch(SEQUENCES.DASH_DASH, true)) {
- this._createCommentToken(SEQUENCES.DASH_DASH.length + 1);
- this.state = State.COMMENT_START;
- } else if (this._consumeSequenceIfMatch(SEQUENCES.DOCTYPE, false)) {
- this.currentLocation = this.getCurrentLocation(SEQUENCES.DOCTYPE.length + 1);
- this.state = State.DOCTYPE;
- } else if (this._consumeSequenceIfMatch(SEQUENCES.CDATA_START, true)) if (this.inForeignNode) this.state = State.CDATA_SECTION;
- else {
- this._err(ERR.cdataInHtmlContent);
- this._createCommentToken(SEQUENCES.CDATA_START.length + 1);
- this.currentToken.data = "[CDATA[";
- this.state = State.BOGUS_COMMENT;
- }
- else if (!this._ensureHibernation()) {
- this._err(ERR.incorrectlyOpenedComment);
- this._createCommentToken(2);
- this.state = State.BOGUS_COMMENT;
- this._stateBogusComment(cp);
- }
- }
- _stateCommentStart(cp) {
- switch (cp) {
- case CODE_POINTS.HYPHEN_MINUS:
- this.state = State.COMMENT_START_DASH;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this._err(ERR.abruptClosingOfEmptyComment);
- this.state = State.DATA;
- this.emitCurrentComment(this.currentToken);
- break;
- default:
- this.state = State.COMMENT;
- this._stateComment(cp);
- }
- }
- _stateCommentStartDash(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.HYPHEN_MINUS:
- this.state = State.COMMENT_END;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this._err(ERR.abruptClosingOfEmptyComment);
- this.state = State.DATA;
- this.emitCurrentComment(token);
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInComment);
- this.emitCurrentComment(token);
- this._emitEOFToken();
- break;
- default:
- token.data += "-";
- this.state = State.COMMENT;
- this._stateComment(cp);
- }
- }
- _stateComment(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.HYPHEN_MINUS:
- this.state = State.COMMENT_END_DASH;
- break;
- case CODE_POINTS.LESS_THAN_SIGN:
- token.data += "<";
- this.state = State.COMMENT_LESS_THAN_SIGN;
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- token.data += REPLACEMENT_CHARACTER;
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInComment);
- this.emitCurrentComment(token);
- this._emitEOFToken();
- break;
- default: token.data += String.fromCodePoint(cp);
- }
- }
- _stateCommentLessThanSign(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.EXCLAMATION_MARK:
- token.data += "!";
- this.state = State.COMMENT_LESS_THAN_SIGN_BANG;
- break;
- case CODE_POINTS.LESS_THAN_SIGN:
- token.data += "<";
- break;
- default:
- this.state = State.COMMENT;
- this._stateComment(cp);
- }
- }
- _stateCommentLessThanSignBang(cp) {
- if (cp === CODE_POINTS.HYPHEN_MINUS) this.state = State.COMMENT_LESS_THAN_SIGN_BANG_DASH;
- else {
- this.state = State.COMMENT;
- this._stateComment(cp);
- }
- }
- _stateCommentLessThanSignBangDash(cp) {
- if (cp === CODE_POINTS.HYPHEN_MINUS) this.state = State.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH;
- else {
- this.state = State.COMMENT_END_DASH;
- this._stateCommentEndDash(cp);
- }
- }
- _stateCommentLessThanSignBangDashDash(cp) {
- if (cp !== CODE_POINTS.GREATER_THAN_SIGN && cp !== CODE_POINTS.EOF) this._err(ERR.nestedComment);
- this.state = State.COMMENT_END;
- this._stateCommentEnd(cp);
- }
- _stateCommentEndDash(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.HYPHEN_MINUS:
- this.state = State.COMMENT_END;
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInComment);
- this.emitCurrentComment(token);
- this._emitEOFToken();
- break;
- default:
- token.data += "-";
- this.state = State.COMMENT;
- this._stateComment(cp);
- }
- }
- _stateCommentEnd(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.GREATER_THAN_SIGN:
- this.state = State.DATA;
- this.emitCurrentComment(token);
- break;
- case CODE_POINTS.EXCLAMATION_MARK:
- this.state = State.COMMENT_END_BANG;
- break;
- case CODE_POINTS.HYPHEN_MINUS:
- token.data += "-";
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInComment);
- this.emitCurrentComment(token);
- this._emitEOFToken();
- break;
- default:
- token.data += "--";
- this.state = State.COMMENT;
- this._stateComment(cp);
- }
- }
- _stateCommentEndBang(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.HYPHEN_MINUS:
- token.data += "--!";
- this.state = State.COMMENT_END_DASH;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this._err(ERR.incorrectlyClosedComment);
- this.state = State.DATA;
- this.emitCurrentComment(token);
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInComment);
- this.emitCurrentComment(token);
- this._emitEOFToken();
- break;
- default:
- token.data += "--!";
- this.state = State.COMMENT;
- this._stateComment(cp);
- }
- }
- _stateDoctype(cp) {
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED:
- this.state = State.BEFORE_DOCTYPE_NAME;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this.state = State.BEFORE_DOCTYPE_NAME;
- this._stateBeforeDoctypeName(cp);
- break;
- case CODE_POINTS.EOF: {
- this._err(ERR.eofInDoctype);
- this._createDoctypeToken(null);
- const token = this.currentToken;
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this._emitEOFToken();
- break;
- }
- default:
- this._err(ERR.missingWhitespaceBeforeDoctypeName);
- this.state = State.BEFORE_DOCTYPE_NAME;
- this._stateBeforeDoctypeName(cp);
- }
- }
- _stateBeforeDoctypeName(cp) {
- if (isAsciiUpper(cp)) {
- this._createDoctypeToken(String.fromCharCode(toAsciiLower(cp)));
- this.state = State.DOCTYPE_NAME;
- } else switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED: break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- this._createDoctypeToken(REPLACEMENT_CHARACTER);
- this.state = State.DOCTYPE_NAME;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN: {
- this._err(ERR.missingDoctypeName);
- this._createDoctypeToken(null);
- const token = this.currentToken;
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this.state = State.DATA;
- break;
- }
- case CODE_POINTS.EOF: {
- this._err(ERR.eofInDoctype);
- this._createDoctypeToken(null);
- const token = this.currentToken;
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this._emitEOFToken();
- break;
- }
- default:
- this._createDoctypeToken(String.fromCodePoint(cp));
- this.state = State.DOCTYPE_NAME;
- }
- }
- _stateDoctypeName(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED:
- this.state = State.AFTER_DOCTYPE_NAME;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this.state = State.DATA;
- this.emitCurrentDoctype(token);
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- token.name += REPLACEMENT_CHARACTER;
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInDoctype);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this._emitEOFToken();
- break;
- default: token.name += String.fromCodePoint(isAsciiUpper(cp) ? toAsciiLower(cp) : cp);
- }
- }
- _stateAfterDoctypeName(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED: break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this.state = State.DATA;
- this.emitCurrentDoctype(token);
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInDoctype);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this._emitEOFToken();
- break;
- default: if (this._consumeSequenceIfMatch(SEQUENCES.PUBLIC, false)) this.state = State.AFTER_DOCTYPE_PUBLIC_KEYWORD;
- else if (this._consumeSequenceIfMatch(SEQUENCES.SYSTEM, false)) this.state = State.AFTER_DOCTYPE_SYSTEM_KEYWORD;
- else if (!this._ensureHibernation()) {
- this._err(ERR.invalidCharacterSequenceAfterDoctypeName);
- token.forceQuirks = true;
- this.state = State.BOGUS_DOCTYPE;
- this._stateBogusDoctype(cp);
- }
- }
- }
- _stateAfterDoctypePublicKeyword(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED:
- this.state = State.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;
- break;
- case CODE_POINTS.QUOTATION_MARK:
- this._err(ERR.missingWhitespaceAfterDoctypePublicKeyword);
- token.publicId = "";
- this.state = State.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;
- break;
- case CODE_POINTS.APOSTROPHE:
- this._err(ERR.missingWhitespaceAfterDoctypePublicKeyword);
- token.publicId = "";
- this.state = State.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this._err(ERR.missingDoctypePublicIdentifier);
- token.forceQuirks = true;
- this.state = State.DATA;
- this.emitCurrentDoctype(token);
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInDoctype);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this._emitEOFToken();
- break;
- default:
- this._err(ERR.missingQuoteBeforeDoctypePublicIdentifier);
- token.forceQuirks = true;
- this.state = State.BOGUS_DOCTYPE;
- this._stateBogusDoctype(cp);
- }
- }
- _stateBeforeDoctypePublicIdentifier(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED: break;
- case CODE_POINTS.QUOTATION_MARK:
- token.publicId = "";
- this.state = State.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;
- break;
- case CODE_POINTS.APOSTROPHE:
- token.publicId = "";
- this.state = State.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this._err(ERR.missingDoctypePublicIdentifier);
- token.forceQuirks = true;
- this.state = State.DATA;
- this.emitCurrentDoctype(token);
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInDoctype);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this._emitEOFToken();
- break;
- default:
- this._err(ERR.missingQuoteBeforeDoctypePublicIdentifier);
- token.forceQuirks = true;
- this.state = State.BOGUS_DOCTYPE;
- this._stateBogusDoctype(cp);
- }
- }
- _stateDoctypePublicIdentifierDoubleQuoted(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.QUOTATION_MARK:
- this.state = State.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- token.publicId += REPLACEMENT_CHARACTER;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this._err(ERR.abruptDoctypePublicIdentifier);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this.state = State.DATA;
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInDoctype);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this._emitEOFToken();
- break;
- default: token.publicId += String.fromCodePoint(cp);
- }
- }
- _stateDoctypePublicIdentifierSingleQuoted(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.APOSTROPHE:
- this.state = State.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- token.publicId += REPLACEMENT_CHARACTER;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this._err(ERR.abruptDoctypePublicIdentifier);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this.state = State.DATA;
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInDoctype);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this._emitEOFToken();
- break;
- default: token.publicId += String.fromCodePoint(cp);
- }
- }
- _stateAfterDoctypePublicIdentifier(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED:
- this.state = State.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this.state = State.DATA;
- this.emitCurrentDoctype(token);
- break;
- case CODE_POINTS.QUOTATION_MARK:
- this._err(ERR.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers);
- token.systemId = "";
- this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
- break;
- case CODE_POINTS.APOSTROPHE:
- this._err(ERR.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers);
- token.systemId = "";
- this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInDoctype);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this._emitEOFToken();
- break;
- default:
- this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier);
- token.forceQuirks = true;
- this.state = State.BOGUS_DOCTYPE;
- this._stateBogusDoctype(cp);
- }
- }
- _stateBetweenDoctypePublicAndSystemIdentifiers(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED: break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this.emitCurrentDoctype(token);
- this.state = State.DATA;
- break;
- case CODE_POINTS.QUOTATION_MARK:
- token.systemId = "";
- this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
- break;
- case CODE_POINTS.APOSTROPHE:
- token.systemId = "";
- this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInDoctype);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this._emitEOFToken();
- break;
- default:
- this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier);
- token.forceQuirks = true;
- this.state = State.BOGUS_DOCTYPE;
- this._stateBogusDoctype(cp);
- }
- }
- _stateAfterDoctypeSystemKeyword(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED:
- this.state = State.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;
- break;
- case CODE_POINTS.QUOTATION_MARK:
- this._err(ERR.missingWhitespaceAfterDoctypeSystemKeyword);
- token.systemId = "";
- this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
- break;
- case CODE_POINTS.APOSTROPHE:
- this._err(ERR.missingWhitespaceAfterDoctypeSystemKeyword);
- token.systemId = "";
- this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this._err(ERR.missingDoctypeSystemIdentifier);
- token.forceQuirks = true;
- this.state = State.DATA;
- this.emitCurrentDoctype(token);
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInDoctype);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this._emitEOFToken();
- break;
- default:
- this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier);
- token.forceQuirks = true;
- this.state = State.BOGUS_DOCTYPE;
- this._stateBogusDoctype(cp);
- }
- }
- _stateBeforeDoctypeSystemIdentifier(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED: break;
- case CODE_POINTS.QUOTATION_MARK:
- token.systemId = "";
- this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
- break;
- case CODE_POINTS.APOSTROPHE:
- token.systemId = "";
- this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this._err(ERR.missingDoctypeSystemIdentifier);
- token.forceQuirks = true;
- this.state = State.DATA;
- this.emitCurrentDoctype(token);
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInDoctype);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this._emitEOFToken();
- break;
- default:
- this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier);
- token.forceQuirks = true;
- this.state = State.BOGUS_DOCTYPE;
- this._stateBogusDoctype(cp);
- }
- }
- _stateDoctypeSystemIdentifierDoubleQuoted(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.QUOTATION_MARK:
- this.state = State.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- token.systemId += REPLACEMENT_CHARACTER;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this._err(ERR.abruptDoctypeSystemIdentifier);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this.state = State.DATA;
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInDoctype);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this._emitEOFToken();
- break;
- default: token.systemId += String.fromCodePoint(cp);
- }
- }
- _stateDoctypeSystemIdentifierSingleQuoted(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.APOSTROPHE:
- this.state = State.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- token.systemId += REPLACEMENT_CHARACTER;
- break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this._err(ERR.abruptDoctypeSystemIdentifier);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this.state = State.DATA;
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInDoctype);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this._emitEOFToken();
- break;
- default: token.systemId += String.fromCodePoint(cp);
- }
- }
- _stateAfterDoctypeSystemIdentifier(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.SPACE:
- case CODE_POINTS.LINE_FEED:
- case CODE_POINTS.TABULATION:
- case CODE_POINTS.FORM_FEED: break;
- case CODE_POINTS.GREATER_THAN_SIGN:
- this.emitCurrentDoctype(token);
- this.state = State.DATA;
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInDoctype);
- token.forceQuirks = true;
- this.emitCurrentDoctype(token);
- this._emitEOFToken();
- break;
- default:
- this._err(ERR.unexpectedCharacterAfterDoctypeSystemIdentifier);
- this.state = State.BOGUS_DOCTYPE;
- this._stateBogusDoctype(cp);
- }
- }
- _stateBogusDoctype(cp) {
- const token = this.currentToken;
- switch (cp) {
- case CODE_POINTS.GREATER_THAN_SIGN:
- this.emitCurrentDoctype(token);
- this.state = State.DATA;
- break;
- case CODE_POINTS.NULL:
- this._err(ERR.unexpectedNullCharacter);
- break;
- case CODE_POINTS.EOF:
- this.emitCurrentDoctype(token);
- this._emitEOFToken();
- break;
- default:
- }
- }
- _stateCdataSection(cp) {
- switch (cp) {
- case CODE_POINTS.RIGHT_SQUARE_BRACKET:
- this.state = State.CDATA_SECTION_BRACKET;
- break;
- case CODE_POINTS.EOF:
- this._err(ERR.eofInCdata);
- this._emitEOFToken();
- break;
- default: this._emitCodePoint(cp);
- }
- }
- _stateCdataSectionBracket(cp) {
- if (cp === CODE_POINTS.RIGHT_SQUARE_BRACKET) this.state = State.CDATA_SECTION_END;
- else {
- this._emitChars("]");
- this.state = State.CDATA_SECTION;
- this._stateCdataSection(cp);
- }
- }
- _stateCdataSectionEnd(cp) {
- switch (cp) {
- case CODE_POINTS.GREATER_THAN_SIGN:
- this.state = State.DATA;
- break;
- case CODE_POINTS.RIGHT_SQUARE_BRACKET:
- this._emitChars("]");
- break;
- default:
- this._emitChars("]]");
- this.state = State.CDATA_SECTION;
- this._stateCdataSection(cp);
- }
- }
- _stateCharacterReference() {
- let length = this.entityDecoder.write(this.preprocessor.html, this.preprocessor.pos);
- if (length < 0) if (this.preprocessor.lastChunkWritten) length = this.entityDecoder.end();
- else {
- this.active = false;
- this.preprocessor.pos = this.preprocessor.html.length - 1;
- this.consumedAfterSnapshot = 0;
- this.preprocessor.endOfChunkHit = true;
- return;
- }
- if (length === 0) {
- this.preprocessor.pos = this.entityStartPos;
- this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.AMPERSAND);
- this.state = !this._isCharacterReferenceInAttribute() && isAsciiAlphaNumeric(this.preprocessor.peek(1)) ? State.AMBIGUOUS_AMPERSAND : this.returnState;
- } else this.state = this.returnState;
- }
- _stateAmbiguousAmpersand(cp) {
- if (isAsciiAlphaNumeric(cp)) this._flushCodePointConsumedAsCharacterReference(cp);
- else {
- if (cp === CODE_POINTS.SEMICOLON) this._err(ERR.unknownNamedCharacterReference);
- this.state = this.returnState;
- this._callState(cp);
- }
- }
-};
-
-//#endregion
-//#region ../../node_modules/.pnpm/parse5@8.0.0/node_modules/parse5/dist/parser/open-element-stack.js
-const IMPLICIT_END_TAG_REQUIRED = new Set([
- TAG_ID.DD,
- TAG_ID.DT,
- TAG_ID.LI,
- TAG_ID.OPTGROUP,
- TAG_ID.OPTION,
- TAG_ID.P,
- TAG_ID.RB,
- TAG_ID.RP,
- TAG_ID.RT,
- TAG_ID.RTC
-]);
-const IMPLICIT_END_TAG_REQUIRED_THOROUGHLY = new Set([
- ...IMPLICIT_END_TAG_REQUIRED,
- TAG_ID.CAPTION,
- TAG_ID.COLGROUP,
- TAG_ID.TBODY,
- TAG_ID.TD,
- TAG_ID.TFOOT,
- TAG_ID.TH,
- TAG_ID.THEAD,
- TAG_ID.TR
-]);
-const SCOPING_ELEMENTS_HTML = new Set([
- TAG_ID.APPLET,
- TAG_ID.CAPTION,
- TAG_ID.HTML,
- TAG_ID.MARQUEE,
- TAG_ID.OBJECT,
- TAG_ID.TABLE,
- TAG_ID.TD,
- TAG_ID.TEMPLATE,
- TAG_ID.TH
-]);
-const SCOPING_ELEMENTS_HTML_LIST = new Set([
- ...SCOPING_ELEMENTS_HTML,
- TAG_ID.OL,
- TAG_ID.UL
-]);
-const SCOPING_ELEMENTS_HTML_BUTTON = new Set([...SCOPING_ELEMENTS_HTML, TAG_ID.BUTTON]);
-const SCOPING_ELEMENTS_MATHML = new Set([
- TAG_ID.ANNOTATION_XML,
- TAG_ID.MI,
- TAG_ID.MN,
- TAG_ID.MO,
- TAG_ID.MS,
- TAG_ID.MTEXT
-]);
-const SCOPING_ELEMENTS_SVG = new Set([
- TAG_ID.DESC,
- TAG_ID.FOREIGN_OBJECT,
- TAG_ID.TITLE
-]);
-const TABLE_ROW_CONTEXT = new Set([
- TAG_ID.TR,
- TAG_ID.TEMPLATE,
- TAG_ID.HTML
-]);
-const TABLE_BODY_CONTEXT = new Set([
- TAG_ID.TBODY,
- TAG_ID.TFOOT,
- TAG_ID.THEAD,
- TAG_ID.TEMPLATE,
- TAG_ID.HTML
-]);
-const TABLE_CONTEXT = new Set([
- TAG_ID.TABLE,
- TAG_ID.TEMPLATE,
- TAG_ID.HTML
-]);
-const TABLE_CELLS = new Set([TAG_ID.TD, TAG_ID.TH]);
-var OpenElementStack = class {
- get currentTmplContentOrNode() {
- return this._isInTemplate() ? this.treeAdapter.getTemplateContent(this.current) : this.current;
- }
- constructor(document, treeAdapter, handler) {
- this.treeAdapter = treeAdapter;
- this.handler = handler;
- this.items = [];
- this.tagIDs = [];
- this.stackTop = -1;
- this.tmplCount = 0;
- this.currentTagId = TAG_ID.UNKNOWN;
- this.current = document;
- }
- _indexOf(element) {
- return this.items.lastIndexOf(element, this.stackTop);
- }
- _isInTemplate() {
- return this.currentTagId === TAG_ID.TEMPLATE && this.treeAdapter.getNamespaceURI(this.current) === NS.HTML;
- }
- _updateCurrentElement() {
- this.current = this.items[this.stackTop];
- this.currentTagId = this.tagIDs[this.stackTop];
- }
- push(element, tagID) {
- this.stackTop++;
- this.items[this.stackTop] = element;
- this.current = element;
- this.tagIDs[this.stackTop] = tagID;
- this.currentTagId = tagID;
- if (this._isInTemplate()) this.tmplCount++;
- this.handler.onItemPush(element, tagID, true);
- }
- pop() {
- const popped = this.current;
- if (this.tmplCount > 0 && this._isInTemplate()) this.tmplCount--;
- this.stackTop--;
- this._updateCurrentElement();
- this.handler.onItemPop(popped, true);
- }
- replace(oldElement, newElement) {
- const idx = this._indexOf(oldElement);
- this.items[idx] = newElement;
- if (idx === this.stackTop) this.current = newElement;
- }
- insertAfter(referenceElement, newElement, newElementID) {
- const insertionIdx = this._indexOf(referenceElement) + 1;
- this.items.splice(insertionIdx, 0, newElement);
- this.tagIDs.splice(insertionIdx, 0, newElementID);
- this.stackTop++;
- if (insertionIdx === this.stackTop) this._updateCurrentElement();
- if (this.current && this.currentTagId !== void 0) this.handler.onItemPush(this.current, this.currentTagId, insertionIdx === this.stackTop);
- }
- popUntilTagNamePopped(tagName) {
- let targetIdx = this.stackTop + 1;
- do
- targetIdx = this.tagIDs.lastIndexOf(tagName, targetIdx - 1);
- while (targetIdx > 0 && this.treeAdapter.getNamespaceURI(this.items[targetIdx]) !== NS.HTML);
- this.shortenToLength(Math.max(targetIdx, 0));
- }
- shortenToLength(idx) {
- while (this.stackTop >= idx) {
- const popped = this.current;
- if (this.tmplCount > 0 && this._isInTemplate()) this.tmplCount -= 1;
- this.stackTop--;
- this._updateCurrentElement();
- this.handler.onItemPop(popped, this.stackTop < idx);
- }
- }
- popUntilElementPopped(element) {
- const idx = this._indexOf(element);
- this.shortenToLength(Math.max(idx, 0));
- }
- popUntilPopped(tagNames, targetNS) {
- const idx = this._indexOfTagNames(tagNames, targetNS);
- this.shortenToLength(Math.max(idx, 0));
- }
- popUntilNumberedHeaderPopped() {
- this.popUntilPopped(NUMBERED_HEADERS, NS.HTML);
- }
- popUntilTableCellPopped() {
- this.popUntilPopped(TABLE_CELLS, NS.HTML);
- }
- popAllUpToHtmlElement() {
- this.tmplCount = 0;
- this.shortenToLength(1);
- }
- _indexOfTagNames(tagNames, namespace) {
- for (let i = this.stackTop; i >= 0; i--) if (tagNames.has(this.tagIDs[i]) && this.treeAdapter.getNamespaceURI(this.items[i]) === namespace) return i;
- return -1;
- }
- clearBackTo(tagNames, targetNS) {
- const idx = this._indexOfTagNames(tagNames, targetNS);
- this.shortenToLength(idx + 1);
- }
- clearBackToTableContext() {
- this.clearBackTo(TABLE_CONTEXT, NS.HTML);
- }
- clearBackToTableBodyContext() {
- this.clearBackTo(TABLE_BODY_CONTEXT, NS.HTML);
- }
- clearBackToTableRowContext() {
- this.clearBackTo(TABLE_ROW_CONTEXT, NS.HTML);
- }
- remove(element) {
- const idx = this._indexOf(element);
- if (idx >= 0) if (idx === this.stackTop) this.pop();
- else {
- this.items.splice(idx, 1);
- this.tagIDs.splice(idx, 1);
- this.stackTop--;
- this._updateCurrentElement();
- this.handler.onItemPop(element, false);
- }
- }
- tryPeekProperlyNestedBodyElement() {
- return this.stackTop >= 1 && this.tagIDs[1] === TAG_ID.BODY ? this.items[1] : null;
- }
- contains(element) {
- return this._indexOf(element) > -1;
- }
- getCommonAncestor(element) {
- const elementIdx = this._indexOf(element) - 1;
- return elementIdx >= 0 ? this.items[elementIdx] : null;
- }
- isRootHtmlElementCurrent() {
- return this.stackTop === 0 && this.tagIDs[0] === TAG_ID.HTML;
- }
- hasInDynamicScope(tagName, htmlScope) {
- for (let i = this.stackTop; i >= 0; i--) {
- const tn = this.tagIDs[i];
- switch (this.treeAdapter.getNamespaceURI(this.items[i])) {
- case NS.HTML:
- if (tn === tagName) return true;
- if (htmlScope.has(tn)) return false;
- break;
- case NS.SVG:
- if (SCOPING_ELEMENTS_SVG.has(tn)) return false;
- break;
- case NS.MATHML:
- if (SCOPING_ELEMENTS_MATHML.has(tn)) return false;
- break;
- }
- }
- return true;
- }
- hasInScope(tagName) {
- return this.hasInDynamicScope(tagName, SCOPING_ELEMENTS_HTML);
- }
- hasInListItemScope(tagName) {
- return this.hasInDynamicScope(tagName, SCOPING_ELEMENTS_HTML_LIST);
- }
- hasInButtonScope(tagName) {
- return this.hasInDynamicScope(tagName, SCOPING_ELEMENTS_HTML_BUTTON);
- }
- hasNumberedHeaderInScope() {
- for (let i = this.stackTop; i >= 0; i--) {
- const tn = this.tagIDs[i];
- switch (this.treeAdapter.getNamespaceURI(this.items[i])) {
- case NS.HTML:
- if (NUMBERED_HEADERS.has(tn)) return true;
- if (SCOPING_ELEMENTS_HTML.has(tn)) return false;
- break;
- case NS.SVG:
- if (SCOPING_ELEMENTS_SVG.has(tn)) return false;
- break;
- case NS.MATHML:
- if (SCOPING_ELEMENTS_MATHML.has(tn)) return false;
- break;
- }
- }
- return true;
- }
- hasInTableScope(tagName) {
- for (let i = this.stackTop; i >= 0; i--) {
- if (this.treeAdapter.getNamespaceURI(this.items[i]) !== NS.HTML) continue;
- switch (this.tagIDs[i]) {
- case tagName: return true;
- case TAG_ID.TABLE:
- case TAG_ID.HTML: return false;
- }
- }
- return true;
- }
- hasTableBodyContextInTableScope() {
- for (let i = this.stackTop; i >= 0; i--) {
- if (this.treeAdapter.getNamespaceURI(this.items[i]) !== NS.HTML) continue;
- switch (this.tagIDs[i]) {
- case TAG_ID.TBODY:
- case TAG_ID.THEAD:
- case TAG_ID.TFOOT: return true;
- case TAG_ID.TABLE:
- case TAG_ID.HTML: return false;
- }
- }
- return true;
- }
- hasInSelectScope(tagName) {
- for (let i = this.stackTop; i >= 0; i--) {
- if (this.treeAdapter.getNamespaceURI(this.items[i]) !== NS.HTML) continue;
- switch (this.tagIDs[i]) {
- case tagName: return true;
- case TAG_ID.OPTION:
- case TAG_ID.OPTGROUP: break;
- default: return false;
- }
- }
- return true;
- }
- generateImpliedEndTags() {
- while (this.currentTagId !== void 0 && IMPLICIT_END_TAG_REQUIRED.has(this.currentTagId)) this.pop();
- }
- generateImpliedEndTagsThoroughly() {
- while (this.currentTagId !== void 0 && IMPLICIT_END_TAG_REQUIRED_THOROUGHLY.has(this.currentTagId)) this.pop();
- }
- generateImpliedEndTagsWithExclusion(exclusionId) {
- while (this.currentTagId !== void 0 && this.currentTagId !== exclusionId && IMPLICIT_END_TAG_REQUIRED_THOROUGHLY.has(this.currentTagId)) this.pop();
- }
-};
-
-//#endregion
-//#region ../../node_modules/.pnpm/parse5@8.0.0/node_modules/parse5/dist/parser/formatting-element-list.js
-const NOAH_ARK_CAPACITY = 3;
-var EntryType;
-(function(EntryType$1) {
- EntryType$1[EntryType$1["Marker"] = 0] = "Marker";
- EntryType$1[EntryType$1["Element"] = 1] = "Element";
-})(EntryType || (EntryType = {}));
-const MARKER = { type: EntryType.Marker };
-var FormattingElementList = class {
- constructor(treeAdapter) {
- this.treeAdapter = treeAdapter;
- this.entries = [];
- this.bookmark = null;
- }
- _getNoahArkConditionCandidates(newElement, neAttrs) {
- const candidates = [];
- const neAttrsLength = neAttrs.length;
- const neTagName = this.treeAdapter.getTagName(newElement);
- const neNamespaceURI = this.treeAdapter.getNamespaceURI(newElement);
- for (let i = 0; i < this.entries.length; i++) {
- const entry = this.entries[i];
- if (entry.type === EntryType.Marker) break;
- const { element } = entry;
- if (this.treeAdapter.getTagName(element) === neTagName && this.treeAdapter.getNamespaceURI(element) === neNamespaceURI) {
- const elementAttrs = this.treeAdapter.getAttrList(element);
- if (elementAttrs.length === neAttrsLength) candidates.push({
- idx: i,
- attrs: elementAttrs
- });
- }
- }
- return candidates;
- }
- _ensureNoahArkCondition(newElement) {
- if (this.entries.length < NOAH_ARK_CAPACITY) return;
- const neAttrs = this.treeAdapter.getAttrList(newElement);
- const candidates = this._getNoahArkConditionCandidates(newElement, neAttrs);
- if (candidates.length < NOAH_ARK_CAPACITY) return;
- const neAttrsMap = new Map(neAttrs.map((neAttr) => [neAttr.name, neAttr.value]));
- let validCandidates = 0;
- for (let i = 0; i < candidates.length; i++) {
- const candidate = candidates[i];
- if (candidate.attrs.every((cAttr) => neAttrsMap.get(cAttr.name) === cAttr.value)) {
- validCandidates += 1;
- if (validCandidates >= NOAH_ARK_CAPACITY) this.entries.splice(candidate.idx, 1);
- }
- }
- }
- insertMarker() {
- this.entries.unshift(MARKER);
- }
- pushElement(element, token) {
- this._ensureNoahArkCondition(element);
- this.entries.unshift({
- type: EntryType.Element,
- element,
- token
- });
- }
- insertElementAfterBookmark(element, token) {
- const bookmarkIdx = this.entries.indexOf(this.bookmark);
- this.entries.splice(bookmarkIdx, 0, {
- type: EntryType.Element,
- element,
- token
- });
- }
- removeEntry(entry) {
- const entryIndex = this.entries.indexOf(entry);
- if (entryIndex !== -1) this.entries.splice(entryIndex, 1);
- }
- /**
- * Clears the list of formatting elements up to the last marker.
- *
- * @see https://html.spec.whatwg.org/multipage/parsing.html#clear-the-list-of-active-formatting-elements-up-to-the-last-marker
- */
- clearToLastMarker() {
- const markerIdx = this.entries.indexOf(MARKER);
- if (markerIdx === -1) this.entries.length = 0;
- else this.entries.splice(0, markerIdx + 1);
- }
- getElementEntryInScopeWithTagName(tagName) {
- const entry = this.entries.find((entry$1) => entry$1.type === EntryType.Marker || this.treeAdapter.getTagName(entry$1.element) === tagName);
- return entry && entry.type === EntryType.Element ? entry : null;
- }
- getElementEntry(element) {
- return this.entries.find((entry) => entry.type === EntryType.Element && entry.element === element);
- }
-};
-
-//#endregion
-//#region ../../node_modules/.pnpm/parse5@8.0.0/node_modules/parse5/dist/tree-adapters/default.js
-const defaultTreeAdapter = {
- createDocument() {
- return {
- nodeName: "#document",
- mode: DOCUMENT_MODE.NO_QUIRKS,
- childNodes: []
- };
- },
- createDocumentFragment() {
- return {
- nodeName: "#document-fragment",
- childNodes: []
- };
- },
- createElement(tagName, namespaceURI, attrs) {
- return {
- nodeName: tagName,
- tagName,
- attrs,
- namespaceURI,
- childNodes: [],
- parentNode: null
- };
- },
- createCommentNode(data) {
- return {
- nodeName: "#comment",
- data,
- parentNode: null
- };
- },
- createTextNode(value) {
- return {
- nodeName: "#text",
- value,
- parentNode: null
- };
- },
- appendChild(parentNode, newNode) {
- parentNode.childNodes.push(newNode);
- newNode.parentNode = parentNode;
- },
- insertBefore(parentNode, newNode, referenceNode) {
- const insertionIdx = parentNode.childNodes.indexOf(referenceNode);
- parentNode.childNodes.splice(insertionIdx, 0, newNode);
- newNode.parentNode = parentNode;
- },
- setTemplateContent(templateElement, contentElement) {
- templateElement.content = contentElement;
- },
- getTemplateContent(templateElement) {
- return templateElement.content;
- },
- setDocumentType(document, name, publicId, systemId) {
- const doctypeNode = document.childNodes.find((node) => node.nodeName === "#documentType");
- if (doctypeNode) {
- doctypeNode.name = name;
- doctypeNode.publicId = publicId;
- doctypeNode.systemId = systemId;
- } else defaultTreeAdapter.appendChild(document, {
- nodeName: "#documentType",
- name,
- publicId,
- systemId,
- parentNode: null
- });
- },
- setDocumentMode(document, mode) {
- document.mode = mode;
- },
- getDocumentMode(document) {
- return document.mode;
- },
- detachNode(node) {
- if (node.parentNode) {
- const idx = node.parentNode.childNodes.indexOf(node);
- node.parentNode.childNodes.splice(idx, 1);
- node.parentNode = null;
- }
- },
- insertText(parentNode, text) {
- if (parentNode.childNodes.length > 0) {
- const prevNode = parentNode.childNodes[parentNode.childNodes.length - 1];
- if (defaultTreeAdapter.isTextNode(prevNode)) {
- prevNode.value += text;
- return;
- }
- }
- defaultTreeAdapter.appendChild(parentNode, defaultTreeAdapter.createTextNode(text));
- },
- insertTextBefore(parentNode, text, referenceNode) {
- const prevNode = parentNode.childNodes[parentNode.childNodes.indexOf(referenceNode) - 1];
- if (prevNode && defaultTreeAdapter.isTextNode(prevNode)) prevNode.value += text;
- else defaultTreeAdapter.insertBefore(parentNode, defaultTreeAdapter.createTextNode(text), referenceNode);
- },
- adoptAttributes(recipient, attrs) {
- const recipientAttrsMap = new Set(recipient.attrs.map((attr) => attr.name));
- for (let j = 0; j < attrs.length; j++) if (!recipientAttrsMap.has(attrs[j].name)) recipient.attrs.push(attrs[j]);
- },
- getFirstChild(node) {
- return node.childNodes[0];
- },
- getChildNodes(node) {
- return node.childNodes;
- },
- getParentNode(node) {
- return node.parentNode;
- },
- getAttrList(element) {
- return element.attrs;
- },
- getTagName(element) {
- return element.tagName;
- },
- getNamespaceURI(element) {
- return element.namespaceURI;
- },
- getTextNodeContent(textNode) {
- return textNode.value;
- },
- getCommentNodeContent(commentNode) {
- return commentNode.data;
- },
- getDocumentTypeNodeName(doctypeNode) {
- return doctypeNode.name;
- },
- getDocumentTypeNodePublicId(doctypeNode) {
- return doctypeNode.publicId;
- },
- getDocumentTypeNodeSystemId(doctypeNode) {
- return doctypeNode.systemId;
- },
- isTextNode(node) {
- return node.nodeName === "#text";
- },
- isCommentNode(node) {
- return node.nodeName === "#comment";
- },
- isDocumentTypeNode(node) {
- return node.nodeName === "#documentType";
- },
- isElementNode(node) {
- return Object.prototype.hasOwnProperty.call(node, "tagName");
- },
- setNodeSourceCodeLocation(node, location) {
- node.sourceCodeLocation = location;
- },
- getNodeSourceCodeLocation(node) {
- return node.sourceCodeLocation;
- },
- updateNodeSourceCodeLocation(node, endLocation) {
- node.sourceCodeLocation = {
- ...node.sourceCodeLocation,
- ...endLocation
- };
- }
-};
-
-//#endregion
-//#region ../../node_modules/.pnpm/parse5@8.0.0/node_modules/parse5/dist/common/doctype.js
-const VALID_DOCTYPE_NAME = "html";
-const VALID_SYSTEM_ID = "about:legacy-compat";
-const QUIRKS_MODE_SYSTEM_ID = "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd";
-const QUIRKS_MODE_PUBLIC_ID_PREFIXES = [
- "+//silmaril//dtd html pro v0r11 19970101//",
- "-//as//dtd html 3.0 aswedit + extensions//",
- "-//advasoft ltd//dtd html 3.0 aswedit + extensions//",
- "-//ietf//dtd html 2.0 level 1//",
- "-//ietf//dtd html 2.0 level 2//",
- "-//ietf//dtd html 2.0 strict level 1//",
- "-//ietf//dtd html 2.0 strict level 2//",
- "-//ietf//dtd html 2.0 strict//",
- "-//ietf//dtd html 2.0//",
- "-//ietf//dtd html 2.1e//",
- "-//ietf//dtd html 3.0//",
- "-//ietf//dtd html 3.2 final//",
- "-//ietf//dtd html 3.2//",
- "-//ietf//dtd html 3//",
- "-//ietf//dtd html level 0//",
- "-//ietf//dtd html level 1//",
- "-//ietf//dtd html level 2//",
- "-//ietf//dtd html level 3//",
- "-//ietf//dtd html strict level 0//",
- "-//ietf//dtd html strict level 1//",
- "-//ietf//dtd html strict level 2//",
- "-//ietf//dtd html strict level 3//",
- "-//ietf//dtd html strict//",
- "-//ietf//dtd html//",
- "-//metrius//dtd metrius presentational//",
- "-//microsoft//dtd internet explorer 2.0 html strict//",
- "-//microsoft//dtd internet explorer 2.0 html//",
- "-//microsoft//dtd internet explorer 2.0 tables//",
- "-//microsoft//dtd internet explorer 3.0 html strict//",
- "-//microsoft//dtd internet explorer 3.0 html//",
- "-//microsoft//dtd internet explorer 3.0 tables//",
- "-//netscape comm. corp.//dtd html//",
- "-//netscape comm. corp.//dtd strict html//",
- "-//o'reilly and associates//dtd html 2.0//",
- "-//o'reilly and associates//dtd html extended 1.0//",
- "-//o'reilly and associates//dtd html extended relaxed 1.0//",
- "-//sq//dtd html 2.0 hotmetal + extensions//",
- "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//",
- "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//",
- "-//spyglass//dtd html 2.0 extended//",
- "-//sun microsystems corp.//dtd hotjava html//",
- "-//sun microsystems corp.//dtd hotjava strict html//",
- "-//w3c//dtd html 3 1995-03-24//",
- "-//w3c//dtd html 3.2 draft//",
- "-//w3c//dtd html 3.2 final//",
- "-//w3c//dtd html 3.2//",
- "-//w3c//dtd html 3.2s draft//",
- "-//w3c//dtd html 4.0 frameset//",
- "-//w3c//dtd html 4.0 transitional//",
- "-//w3c//dtd html experimental 19960712//",
- "-//w3c//dtd html experimental 970421//",
- "-//w3c//dtd w3 html//",
- "-//w3o//dtd w3 html 3.0//",
- "-//webtechs//dtd mozilla html 2.0//",
- "-//webtechs//dtd mozilla html//"
-];
-const QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES = [
- ...QUIRKS_MODE_PUBLIC_ID_PREFIXES,
- "-//w3c//dtd html 4.01 frameset//",
- "-//w3c//dtd html 4.01 transitional//"
-];
-const QUIRKS_MODE_PUBLIC_IDS = new Set([
- "-//w3o//dtd w3 html strict 3.0//en//",
- "-/w3c/dtd html 4.0 transitional/en",
- "html"
-]);
-const LIMITED_QUIRKS_PUBLIC_ID_PREFIXES = ["-//w3c//dtd xhtml 1.0 frameset//", "-//w3c//dtd xhtml 1.0 transitional//"];
-const LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES = [
- ...LIMITED_QUIRKS_PUBLIC_ID_PREFIXES,
- "-//w3c//dtd html 4.01 frameset//",
- "-//w3c//dtd html 4.01 transitional//"
-];
-function hasPrefix(publicId, prefixes) {
- return prefixes.some((prefix) => publicId.startsWith(prefix));
-}
-function isConforming(token) {
- return token.name === VALID_DOCTYPE_NAME && token.publicId === null && (token.systemId === null || token.systemId === VALID_SYSTEM_ID);
-}
-function getDocumentMode(token) {
- if (token.name !== VALID_DOCTYPE_NAME) return DOCUMENT_MODE.QUIRKS;
- const { systemId } = token;
- if (systemId && systemId.toLowerCase() === QUIRKS_MODE_SYSTEM_ID) return DOCUMENT_MODE.QUIRKS;
- let { publicId } = token;
- if (publicId !== null) {
- publicId = publicId.toLowerCase();
- if (QUIRKS_MODE_PUBLIC_IDS.has(publicId)) return DOCUMENT_MODE.QUIRKS;
- let prefixes = systemId === null ? QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES : QUIRKS_MODE_PUBLIC_ID_PREFIXES;
- if (hasPrefix(publicId, prefixes)) return DOCUMENT_MODE.QUIRKS;
- prefixes = systemId === null ? LIMITED_QUIRKS_PUBLIC_ID_PREFIXES : LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES;
- if (hasPrefix(publicId, prefixes)) return DOCUMENT_MODE.LIMITED_QUIRKS;
- }
- return DOCUMENT_MODE.NO_QUIRKS;
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/parse5@8.0.0/node_modules/parse5/dist/common/foreign-content.js
-const MIME_TYPES = {
- TEXT_HTML: "text/html",
- APPLICATION_XML: "application/xhtml+xml"
-};
-const DEFINITION_URL_ATTR = "definitionurl";
-const ADJUSTED_DEFINITION_URL_ATTR = "definitionURL";
-const SVG_ATTRS_ADJUSTMENT_MAP = new Map([
- "attributeName",
- "attributeType",
- "baseFrequency",
- "baseProfile",
- "calcMode",
- "clipPathUnits",
- "diffuseConstant",
- "edgeMode",
- "filterUnits",
- "glyphRef",
- "gradientTransform",
- "gradientUnits",
- "kernelMatrix",
- "kernelUnitLength",
- "keyPoints",
- "keySplines",
- "keyTimes",
- "lengthAdjust",
- "limitingConeAngle",
- "markerHeight",
- "markerUnits",
- "markerWidth",
- "maskContentUnits",
- "maskUnits",
- "numOctaves",
- "pathLength",
- "patternContentUnits",
- "patternTransform",
- "patternUnits",
- "pointsAtX",
- "pointsAtY",
- "pointsAtZ",
- "preserveAlpha",
- "preserveAspectRatio",
- "primitiveUnits",
- "refX",
- "refY",
- "repeatCount",
- "repeatDur",
- "requiredExtensions",
- "requiredFeatures",
- "specularConstant",
- "specularExponent",
- "spreadMethod",
- "startOffset",
- "stdDeviation",
- "stitchTiles",
- "surfaceScale",
- "systemLanguage",
- "tableValues",
- "targetX",
- "targetY",
- "textLength",
- "viewBox",
- "viewTarget",
- "xChannelSelector",
- "yChannelSelector",
- "zoomAndPan"
-].map((attr) => [attr.toLowerCase(), attr]));
-const XML_ATTRS_ADJUSTMENT_MAP = new Map([
- ["xlink:actuate", {
- prefix: "xlink",
- name: "actuate",
- namespace: NS.XLINK
- }],
- ["xlink:arcrole", {
- prefix: "xlink",
- name: "arcrole",
- namespace: NS.XLINK
- }],
- ["xlink:href", {
- prefix: "xlink",
- name: "href",
- namespace: NS.XLINK
- }],
- ["xlink:role", {
- prefix: "xlink",
- name: "role",
- namespace: NS.XLINK
- }],
- ["xlink:show", {
- prefix: "xlink",
- name: "show",
- namespace: NS.XLINK
- }],
- ["xlink:title", {
- prefix: "xlink",
- name: "title",
- namespace: NS.XLINK
- }],
- ["xlink:type", {
- prefix: "xlink",
- name: "type",
- namespace: NS.XLINK
- }],
- ["xml:lang", {
- prefix: "xml",
- name: "lang",
- namespace: NS.XML
- }],
- ["xml:space", {
- prefix: "xml",
- name: "space",
- namespace: NS.XML
- }],
- ["xmlns", {
- prefix: "",
- name: "xmlns",
- namespace: NS.XMLNS
- }],
- ["xmlns:xlink", {
- prefix: "xmlns",
- name: "xlink",
- namespace: NS.XMLNS
- }]
-]);
-const SVG_TAG_NAMES_ADJUSTMENT_MAP = new Map([
- "altGlyph",
- "altGlyphDef",
- "altGlyphItem",
- "animateColor",
- "animateMotion",
- "animateTransform",
- "clipPath",
- "feBlend",
- "feColorMatrix",
- "feComponentTransfer",
- "feComposite",
- "feConvolveMatrix",
- "feDiffuseLighting",
- "feDisplacementMap",
- "feDistantLight",
- "feFlood",
- "feFuncA",
- "feFuncB",
- "feFuncG",
- "feFuncR",
- "feGaussianBlur",
- "feImage",
- "feMerge",
- "feMergeNode",
- "feMorphology",
- "feOffset",
- "fePointLight",
- "feSpecularLighting",
- "feSpotLight",
- "feTile",
- "feTurbulence",
- "foreignObject",
- "glyphRef",
- "linearGradient",
- "radialGradient",
- "textPath"
-].map((tn) => [tn.toLowerCase(), tn]));
-const EXITS_FOREIGN_CONTENT = new Set([
- TAG_ID.B,
- TAG_ID.BIG,
- TAG_ID.BLOCKQUOTE,
- TAG_ID.BODY,
- TAG_ID.BR,
- TAG_ID.CENTER,
- TAG_ID.CODE,
- TAG_ID.DD,
- TAG_ID.DIV,
- TAG_ID.DL,
- TAG_ID.DT,
- TAG_ID.EM,
- TAG_ID.EMBED,
- TAG_ID.H1,
- TAG_ID.H2,
- TAG_ID.H3,
- TAG_ID.H4,
- TAG_ID.H5,
- TAG_ID.H6,
- TAG_ID.HEAD,
- TAG_ID.HR,
- TAG_ID.I,
- TAG_ID.IMG,
- TAG_ID.LI,
- TAG_ID.LISTING,
- TAG_ID.MENU,
- TAG_ID.META,
- TAG_ID.NOBR,
- TAG_ID.OL,
- TAG_ID.P,
- TAG_ID.PRE,
- TAG_ID.RUBY,
- TAG_ID.S,
- TAG_ID.SMALL,
- TAG_ID.SPAN,
- TAG_ID.STRONG,
- TAG_ID.STRIKE,
- TAG_ID.SUB,
- TAG_ID.SUP,
- TAG_ID.TABLE,
- TAG_ID.TT,
- TAG_ID.U,
- TAG_ID.UL,
- TAG_ID.VAR
-]);
-function causesExit(startTagToken) {
- const tn = startTagToken.tagID;
- return tn === TAG_ID.FONT && startTagToken.attrs.some(({ name }) => name === ATTRS.COLOR || name === ATTRS.SIZE || name === ATTRS.FACE) || EXITS_FOREIGN_CONTENT.has(tn);
-}
-function adjustTokenMathMLAttrs(token) {
- for (let i = 0; i < token.attrs.length; i++) if (token.attrs[i].name === DEFINITION_URL_ATTR) {
- token.attrs[i].name = ADJUSTED_DEFINITION_URL_ATTR;
- break;
- }
-}
-function adjustTokenSVGAttrs(token) {
- for (let i = 0; i < token.attrs.length; i++) {
- const adjustedAttrName = SVG_ATTRS_ADJUSTMENT_MAP.get(token.attrs[i].name);
- if (adjustedAttrName != null) token.attrs[i].name = adjustedAttrName;
- }
-}
-function adjustTokenXMLAttrs(token) {
- for (let i = 0; i < token.attrs.length; i++) {
- const adjustedAttrEntry = XML_ATTRS_ADJUSTMENT_MAP.get(token.attrs[i].name);
- if (adjustedAttrEntry) {
- token.attrs[i].prefix = adjustedAttrEntry.prefix;
- token.attrs[i].name = adjustedAttrEntry.name;
- token.attrs[i].namespace = adjustedAttrEntry.namespace;
- }
- }
-}
-function adjustTokenSVGTagName(token) {
- const adjustedTagName = SVG_TAG_NAMES_ADJUSTMENT_MAP.get(token.tagName);
- if (adjustedTagName != null) {
- token.tagName = adjustedTagName;
- token.tagID = getTagID(token.tagName);
- }
-}
-function isMathMLTextIntegrationPoint(tn, ns) {
- return ns === NS.MATHML && (tn === TAG_ID.MI || tn === TAG_ID.MO || tn === TAG_ID.MN || tn === TAG_ID.MS || tn === TAG_ID.MTEXT);
-}
-function isHtmlIntegrationPoint(tn, ns, attrs) {
- if (ns === NS.MATHML && tn === TAG_ID.ANNOTATION_XML) {
- for (let i = 0; i < attrs.length; i++) if (attrs[i].name === ATTRS.ENCODING) {
- const value = attrs[i].value.toLowerCase();
- return value === MIME_TYPES.TEXT_HTML || value === MIME_TYPES.APPLICATION_XML;
- }
- }
- return ns === NS.SVG && (tn === TAG_ID.FOREIGN_OBJECT || tn === TAG_ID.DESC || tn === TAG_ID.TITLE);
-}
-function isIntegrationPoint(tn, ns, attrs, foreignNS) {
- return (!foreignNS || foreignNS === NS.HTML) && isHtmlIntegrationPoint(tn, ns, attrs) || (!foreignNS || foreignNS === NS.MATHML) && isMathMLTextIntegrationPoint(tn, ns);
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/parse5@8.0.0/node_modules/parse5/dist/parser/index.js
-const HIDDEN_INPUT_TYPE = "hidden";
-const AA_OUTER_LOOP_ITER = 8;
-const AA_INNER_LOOP_ITER = 3;
-var InsertionMode;
-(function(InsertionMode$1) {
- InsertionMode$1[InsertionMode$1["INITIAL"] = 0] = "INITIAL";
- InsertionMode$1[InsertionMode$1["BEFORE_HTML"] = 1] = "BEFORE_HTML";
- InsertionMode$1[InsertionMode$1["BEFORE_HEAD"] = 2] = "BEFORE_HEAD";
- InsertionMode$1[InsertionMode$1["IN_HEAD"] = 3] = "IN_HEAD";
- InsertionMode$1[InsertionMode$1["IN_HEAD_NO_SCRIPT"] = 4] = "IN_HEAD_NO_SCRIPT";
- InsertionMode$1[InsertionMode$1["AFTER_HEAD"] = 5] = "AFTER_HEAD";
- InsertionMode$1[InsertionMode$1["IN_BODY"] = 6] = "IN_BODY";
- InsertionMode$1[InsertionMode$1["TEXT"] = 7] = "TEXT";
- InsertionMode$1[InsertionMode$1["IN_TABLE"] = 8] = "IN_TABLE";
- InsertionMode$1[InsertionMode$1["IN_TABLE_TEXT"] = 9] = "IN_TABLE_TEXT";
- InsertionMode$1[InsertionMode$1["IN_CAPTION"] = 10] = "IN_CAPTION";
- InsertionMode$1[InsertionMode$1["IN_COLUMN_GROUP"] = 11] = "IN_COLUMN_GROUP";
- InsertionMode$1[InsertionMode$1["IN_TABLE_BODY"] = 12] = "IN_TABLE_BODY";
- InsertionMode$1[InsertionMode$1["IN_ROW"] = 13] = "IN_ROW";
- InsertionMode$1[InsertionMode$1["IN_CELL"] = 14] = "IN_CELL";
- InsertionMode$1[InsertionMode$1["IN_SELECT"] = 15] = "IN_SELECT";
- InsertionMode$1[InsertionMode$1["IN_SELECT_IN_TABLE"] = 16] = "IN_SELECT_IN_TABLE";
- InsertionMode$1[InsertionMode$1["IN_TEMPLATE"] = 17] = "IN_TEMPLATE";
- InsertionMode$1[InsertionMode$1["AFTER_BODY"] = 18] = "AFTER_BODY";
- InsertionMode$1[InsertionMode$1["IN_FRAMESET"] = 19] = "IN_FRAMESET";
- InsertionMode$1[InsertionMode$1["AFTER_FRAMESET"] = 20] = "AFTER_FRAMESET";
- InsertionMode$1[InsertionMode$1["AFTER_AFTER_BODY"] = 21] = "AFTER_AFTER_BODY";
- InsertionMode$1[InsertionMode$1["AFTER_AFTER_FRAMESET"] = 22] = "AFTER_AFTER_FRAMESET";
-})(InsertionMode || (InsertionMode = {}));
-const BASE_LOC = {
- startLine: -1,
- startCol: -1,
- startOffset: -1,
- endLine: -1,
- endCol: -1,
- endOffset: -1
-};
-const TABLE_STRUCTURE_TAGS = new Set([
- TAG_ID.TABLE,
- TAG_ID.TBODY,
- TAG_ID.TFOOT,
- TAG_ID.THEAD,
- TAG_ID.TR
-]);
-const defaultParserOptions = {
- scriptingEnabled: true,
- sourceCodeLocationInfo: false,
- treeAdapter: defaultTreeAdapter,
- onParseError: null
-};
-var Parser = class {
- constructor(options, document, fragmentContext = null, scriptHandler = null) {
- this.fragmentContext = fragmentContext;
- this.scriptHandler = scriptHandler;
- this.currentToken = null;
- this.stopped = false;
- /** @internal */
- this.insertionMode = InsertionMode.INITIAL;
- /** @internal */
- this.originalInsertionMode = InsertionMode.INITIAL;
- /** @internal */
- this.headElement = null;
- /** @internal */
- this.formElement = null;
- /** Indicates that the current node is not an element in the HTML namespace */
- this.currentNotInHTML = false;
- /**
- * The template insertion mode stack is maintained from the left.
- * Ie. the topmost element will always have index 0.
- *
- * @internal
- */
- this.tmplInsertionModeStack = [];
- /** @internal */
- this.pendingCharacterTokens = [];
- /** @internal */
- this.hasNonWhitespacePendingCharacterToken = false;
- /** @internal */
- this.framesetOk = true;
- /** @internal */
- this.skipNextNewLine = false;
- /** @internal */
- this.fosterParentingEnabled = false;
- this.options = {
- ...defaultParserOptions,
- ...options
- };
- this.treeAdapter = this.options.treeAdapter;
- this.onParseError = this.options.onParseError;
- if (this.onParseError) this.options.sourceCodeLocationInfo = true;
- this.document = document !== null && document !== void 0 ? document : this.treeAdapter.createDocument();
- this.tokenizer = new Tokenizer(this.options, this);
- this.activeFormattingElements = new FormattingElementList(this.treeAdapter);
- this.fragmentContextID = fragmentContext ? getTagID(this.treeAdapter.getTagName(fragmentContext)) : TAG_ID.UNKNOWN;
- this._setContextModes(fragmentContext !== null && fragmentContext !== void 0 ? fragmentContext : this.document, this.fragmentContextID);
- this.openElements = new OpenElementStack(this.document, this.treeAdapter, this);
- }
- static parse(html, options) {
- const parser = new this(options);
- parser.tokenizer.write(html, true);
- return parser.document;
- }
- static getFragmentParser(fragmentContext, options) {
- const opts = {
- ...defaultParserOptions,
- ...options
- };
- fragmentContext !== null && fragmentContext !== void 0 || (fragmentContext = opts.treeAdapter.createElement(TAG_NAMES.TEMPLATE, NS.HTML, []));
- const documentMock = opts.treeAdapter.createElement("documentmock", NS.HTML, []);
- const parser = new this(opts, documentMock, fragmentContext);
- if (parser.fragmentContextID === TAG_ID.TEMPLATE) parser.tmplInsertionModeStack.unshift(InsertionMode.IN_TEMPLATE);
- parser._initTokenizerForFragmentParsing();
- parser._insertFakeRootElement();
- parser._resetInsertionMode();
- parser._findFormInFragmentContext();
- return parser;
- }
- getFragment() {
- const rootElement = this.treeAdapter.getFirstChild(this.document);
- const fragment = this.treeAdapter.createDocumentFragment();
- this._adoptNodes(rootElement, fragment);
- return fragment;
- }
- /** @internal */
- _err(token, code, beforeToken) {
- var _a$1;
- if (!this.onParseError) return;
- const loc = (_a$1 = token.location) !== null && _a$1 !== void 0 ? _a$1 : BASE_LOC;
- this.onParseError({
- code,
- startLine: loc.startLine,
- startCol: loc.startCol,
- startOffset: loc.startOffset,
- endLine: beforeToken ? loc.startLine : loc.endLine,
- endCol: beforeToken ? loc.startCol : loc.endCol,
- endOffset: beforeToken ? loc.startOffset : loc.endOffset
- });
- }
- /** @internal */
- onItemPush(node, tid, isTop) {
- var _a$1, _b;
- (_b = (_a$1 = this.treeAdapter).onItemPush) === null || _b === void 0 || _b.call(_a$1, node);
- if (isTop && this.openElements.stackTop > 0) this._setContextModes(node, tid);
- }
- /** @internal */
- onItemPop(node, isTop) {
- var _a$1, _b;
- if (this.options.sourceCodeLocationInfo) this._setEndLocation(node, this.currentToken);
- (_b = (_a$1 = this.treeAdapter).onItemPop) === null || _b === void 0 || _b.call(_a$1, node, this.openElements.current);
- if (isTop) {
- let current;
- let currentTagId;
- if (this.openElements.stackTop === 0 && this.fragmentContext) {
- current = this.fragmentContext;
- currentTagId = this.fragmentContextID;
- } else ({current, currentTagId} = this.openElements);
- this._setContextModes(current, currentTagId);
- }
- }
- _setContextModes(current, tid) {
- const isHTML = current === this.document || current && this.treeAdapter.getNamespaceURI(current) === NS.HTML;
- this.currentNotInHTML = !isHTML;
- this.tokenizer.inForeignNode = !isHTML && current !== void 0 && tid !== void 0 && !this._isIntegrationPoint(tid, current);
- }
- /** @protected */
- _switchToTextParsing(currentToken, nextTokenizerState) {
- this._insertElement(currentToken, NS.HTML);
- this.tokenizer.state = nextTokenizerState;
- this.originalInsertionMode = this.insertionMode;
- this.insertionMode = InsertionMode.TEXT;
- }
- switchToPlaintextParsing() {
- this.insertionMode = InsertionMode.TEXT;
- this.originalInsertionMode = InsertionMode.IN_BODY;
- this.tokenizer.state = TokenizerMode.PLAINTEXT;
- }
- /** @protected */
- _getAdjustedCurrentElement() {
- return this.openElements.stackTop === 0 && this.fragmentContext ? this.fragmentContext : this.openElements.current;
- }
- /** @protected */
- _findFormInFragmentContext() {
- let node = this.fragmentContext;
- while (node) {
- if (this.treeAdapter.getTagName(node) === TAG_NAMES.FORM) {
- this.formElement = node;
- break;
- }
- node = this.treeAdapter.getParentNode(node);
- }
- }
- _initTokenizerForFragmentParsing() {
- if (!this.fragmentContext || this.treeAdapter.getNamespaceURI(this.fragmentContext) !== NS.HTML) return;
- switch (this.fragmentContextID) {
- case TAG_ID.TITLE:
- case TAG_ID.TEXTAREA:
- this.tokenizer.state = TokenizerMode.RCDATA;
- break;
- case TAG_ID.STYLE:
- case TAG_ID.XMP:
- case TAG_ID.IFRAME:
- case TAG_ID.NOEMBED:
- case TAG_ID.NOFRAMES:
- case TAG_ID.NOSCRIPT:
- this.tokenizer.state = TokenizerMode.RAWTEXT;
- break;
- case TAG_ID.SCRIPT:
- this.tokenizer.state = TokenizerMode.SCRIPT_DATA;
- break;
- case TAG_ID.PLAINTEXT:
- this.tokenizer.state = TokenizerMode.PLAINTEXT;
- break;
- default:
- }
- }
- /** @protected */
- _setDocumentType(token) {
- this.treeAdapter.setDocumentType(this.document, token.name || "", token.publicId || "", token.systemId || "");
- if (token.location) {
- const docTypeNode = this.treeAdapter.getChildNodes(this.document).find((node) => this.treeAdapter.isDocumentTypeNode(node));
- if (docTypeNode) this.treeAdapter.setNodeSourceCodeLocation(docTypeNode, token.location);
- }
- }
- /** @protected */
- _attachElementToTree(element, location) {
- if (this.options.sourceCodeLocationInfo) {
- const loc = location && {
- ...location,
- startTag: location
- };
- this.treeAdapter.setNodeSourceCodeLocation(element, loc);
- }
- if (this._shouldFosterParentOnInsertion()) this._fosterParentElement(element);
- else {
- const parent = this.openElements.currentTmplContentOrNode;
- this.treeAdapter.appendChild(parent !== null && parent !== void 0 ? parent : this.document, element);
- }
- }
- /**
- * For self-closing tags. Add an element to the tree, but skip adding it
- * to the stack.
- */
- /** @protected */
- _appendElement(token, namespaceURI) {
- const element = this.treeAdapter.createElement(token.tagName, namespaceURI, token.attrs);
- this._attachElementToTree(element, token.location);
- }
- /** @protected */
- _insertElement(token, namespaceURI) {
- const element = this.treeAdapter.createElement(token.tagName, namespaceURI, token.attrs);
- this._attachElementToTree(element, token.location);
- this.openElements.push(element, token.tagID);
- }
- /** @protected */
- _insertFakeElement(tagName, tagID) {
- const element = this.treeAdapter.createElement(tagName, NS.HTML, []);
- this._attachElementToTree(element, null);
- this.openElements.push(element, tagID);
- }
- /** @protected */
- _insertTemplate(token) {
- const tmpl = this.treeAdapter.createElement(token.tagName, NS.HTML, token.attrs);
- const content = this.treeAdapter.createDocumentFragment();
- this.treeAdapter.setTemplateContent(tmpl, content);
- this._attachElementToTree(tmpl, token.location);
- this.openElements.push(tmpl, token.tagID);
- if (this.options.sourceCodeLocationInfo) this.treeAdapter.setNodeSourceCodeLocation(content, null);
- }
- /** @protected */
- _insertFakeRootElement() {
- const element = this.treeAdapter.createElement(TAG_NAMES.HTML, NS.HTML, []);
- if (this.options.sourceCodeLocationInfo) this.treeAdapter.setNodeSourceCodeLocation(element, null);
- this.treeAdapter.appendChild(this.openElements.current, element);
- this.openElements.push(element, TAG_ID.HTML);
- }
- /** @protected */
- _appendCommentNode(token, parent) {
- const commentNode = this.treeAdapter.createCommentNode(token.data);
- this.treeAdapter.appendChild(parent, commentNode);
- if (this.options.sourceCodeLocationInfo) this.treeAdapter.setNodeSourceCodeLocation(commentNode, token.location);
- }
- /** @protected */
- _insertCharacters(token) {
- let parent;
- let beforeElement;
- if (this._shouldFosterParentOnInsertion()) {
- ({parent, beforeElement} = this._findFosterParentingLocation());
- if (beforeElement) this.treeAdapter.insertTextBefore(parent, token.chars, beforeElement);
- else this.treeAdapter.insertText(parent, token.chars);
- } else {
- parent = this.openElements.currentTmplContentOrNode;
- this.treeAdapter.insertText(parent, token.chars);
- }
- if (!token.location) return;
- const siblings = this.treeAdapter.getChildNodes(parent);
- const textNode = siblings[(beforeElement ? siblings.lastIndexOf(beforeElement) : siblings.length) - 1];
- if (this.treeAdapter.getNodeSourceCodeLocation(textNode)) {
- const { endLine, endCol, endOffset } = token.location;
- this.treeAdapter.updateNodeSourceCodeLocation(textNode, {
- endLine,
- endCol,
- endOffset
- });
- } else if (this.options.sourceCodeLocationInfo) this.treeAdapter.setNodeSourceCodeLocation(textNode, token.location);
- }
- /** @protected */
- _adoptNodes(donor, recipient) {
- for (let child = this.treeAdapter.getFirstChild(donor); child; child = this.treeAdapter.getFirstChild(donor)) {
- this.treeAdapter.detachNode(child);
- this.treeAdapter.appendChild(recipient, child);
- }
- }
- /** @protected */
- _setEndLocation(element, closingToken) {
- if (this.treeAdapter.getNodeSourceCodeLocation(element) && closingToken.location) {
- const ctLoc = closingToken.location;
- const tn = this.treeAdapter.getTagName(element);
- const endLoc = closingToken.type === TokenType.END_TAG && tn === closingToken.tagName ? {
- endTag: { ...ctLoc },
- endLine: ctLoc.endLine,
- endCol: ctLoc.endCol,
- endOffset: ctLoc.endOffset
- } : {
- endLine: ctLoc.startLine,
- endCol: ctLoc.startCol,
- endOffset: ctLoc.startOffset
- };
- this.treeAdapter.updateNodeSourceCodeLocation(element, endLoc);
- }
- }
- shouldProcessStartTagTokenInForeignContent(token) {
- if (!this.currentNotInHTML) return false;
- let current;
- let currentTagId;
- if (this.openElements.stackTop === 0 && this.fragmentContext) {
- current = this.fragmentContext;
- currentTagId = this.fragmentContextID;
- } else ({current, currentTagId} = this.openElements);
- if (token.tagID === TAG_ID.SVG && this.treeAdapter.getTagName(current) === TAG_NAMES.ANNOTATION_XML && this.treeAdapter.getNamespaceURI(current) === NS.MATHML) return false;
- return this.tokenizer.inForeignNode || (token.tagID === TAG_ID.MGLYPH || token.tagID === TAG_ID.MALIGNMARK) && currentTagId !== void 0 && !this._isIntegrationPoint(currentTagId, current, NS.HTML);
- }
- /** @protected */
- _processToken(token) {
- switch (token.type) {
- case TokenType.CHARACTER:
- this.onCharacter(token);
- break;
- case TokenType.NULL_CHARACTER:
- this.onNullCharacter(token);
- break;
- case TokenType.COMMENT:
- this.onComment(token);
- break;
- case TokenType.DOCTYPE:
- this.onDoctype(token);
- break;
- case TokenType.START_TAG:
- this._processStartTag(token);
- break;
- case TokenType.END_TAG:
- this.onEndTag(token);
- break;
- case TokenType.EOF:
- this.onEof(token);
- break;
- case TokenType.WHITESPACE_CHARACTER:
- this.onWhitespaceCharacter(token);
- break;
- }
- }
- /** @protected */
- _isIntegrationPoint(tid, element, foreignNS) {
- const ns = this.treeAdapter.getNamespaceURI(element);
- const attrs = this.treeAdapter.getAttrList(element);
- return isIntegrationPoint(tid, ns, attrs, foreignNS);
- }
- /** @protected */
- _reconstructActiveFormattingElements() {
- const listLength = this.activeFormattingElements.entries.length;
- if (listLength) {
- const endIndex = this.activeFormattingElements.entries.findIndex((entry) => entry.type === EntryType.Marker || this.openElements.contains(entry.element));
- const unopenIdx = endIndex === -1 ? listLength - 1 : endIndex - 1;
- for (let i = unopenIdx; i >= 0; i--) {
- const entry = this.activeFormattingElements.entries[i];
- this._insertElement(entry.token, this.treeAdapter.getNamespaceURI(entry.element));
- entry.element = this.openElements.current;
- }
- }
- }
- /** @protected */
- _closeTableCell() {
- this.openElements.generateImpliedEndTags();
- this.openElements.popUntilTableCellPopped();
- this.activeFormattingElements.clearToLastMarker();
- this.insertionMode = InsertionMode.IN_ROW;
- }
- /** @protected */
- _closePElement() {
- this.openElements.generateImpliedEndTagsWithExclusion(TAG_ID.P);
- this.openElements.popUntilTagNamePopped(TAG_ID.P);
- }
- /** @protected */
- _resetInsertionMode() {
- for (let i = this.openElements.stackTop; i >= 0; i--) switch (i === 0 && this.fragmentContext ? this.fragmentContextID : this.openElements.tagIDs[i]) {
- case TAG_ID.TR:
- this.insertionMode = InsertionMode.IN_ROW;
- return;
- case TAG_ID.TBODY:
- case TAG_ID.THEAD:
- case TAG_ID.TFOOT:
- this.insertionMode = InsertionMode.IN_TABLE_BODY;
- return;
- case TAG_ID.CAPTION:
- this.insertionMode = InsertionMode.IN_CAPTION;
- return;
- case TAG_ID.COLGROUP:
- this.insertionMode = InsertionMode.IN_COLUMN_GROUP;
- return;
- case TAG_ID.TABLE:
- this.insertionMode = InsertionMode.IN_TABLE;
- return;
- case TAG_ID.BODY:
- this.insertionMode = InsertionMode.IN_BODY;
- return;
- case TAG_ID.FRAMESET:
- this.insertionMode = InsertionMode.IN_FRAMESET;
- return;
- case TAG_ID.SELECT:
- this._resetInsertionModeForSelect(i);
- return;
- case TAG_ID.TEMPLATE:
- this.insertionMode = this.tmplInsertionModeStack[0];
- return;
- case TAG_ID.HTML:
- this.insertionMode = this.headElement ? InsertionMode.AFTER_HEAD : InsertionMode.BEFORE_HEAD;
- return;
- case TAG_ID.TD:
- case TAG_ID.TH:
- if (i > 0) {
- this.insertionMode = InsertionMode.IN_CELL;
- return;
- }
- break;
- case TAG_ID.HEAD:
- if (i > 0) {
- this.insertionMode = InsertionMode.IN_HEAD;
- return;
- }
- break;
- }
- this.insertionMode = InsertionMode.IN_BODY;
- }
- /** @protected */
- _resetInsertionModeForSelect(selectIdx) {
- if (selectIdx > 0) for (let i = selectIdx - 1; i > 0; i--) {
- const tn = this.openElements.tagIDs[i];
- if (tn === TAG_ID.TEMPLATE) break;
- else if (tn === TAG_ID.TABLE) {
- this.insertionMode = InsertionMode.IN_SELECT_IN_TABLE;
- return;
- }
- }
- this.insertionMode = InsertionMode.IN_SELECT;
- }
- /** @protected */
- _isElementCausesFosterParenting(tn) {
- return TABLE_STRUCTURE_TAGS.has(tn);
- }
- /** @protected */
- _shouldFosterParentOnInsertion() {
- return this.fosterParentingEnabled && this.openElements.currentTagId !== void 0 && this._isElementCausesFosterParenting(this.openElements.currentTagId);
- }
- /** @protected */
- _findFosterParentingLocation() {
- for (let i = this.openElements.stackTop; i >= 0; i--) {
- const openElement = this.openElements.items[i];
- switch (this.openElements.tagIDs[i]) {
- case TAG_ID.TEMPLATE:
- if (this.treeAdapter.getNamespaceURI(openElement) === NS.HTML) return {
- parent: this.treeAdapter.getTemplateContent(openElement),
- beforeElement: null
- };
- break;
- case TAG_ID.TABLE: {
- const parent = this.treeAdapter.getParentNode(openElement);
- if (parent) return {
- parent,
- beforeElement: openElement
- };
- return {
- parent: this.openElements.items[i - 1],
- beforeElement: null
- };
- }
- default:
- }
- }
- return {
- parent: this.openElements.items[0],
- beforeElement: null
- };
- }
- /** @protected */
- _fosterParentElement(element) {
- const location = this._findFosterParentingLocation();
- if (location.beforeElement) this.treeAdapter.insertBefore(location.parent, element, location.beforeElement);
- else this.treeAdapter.appendChild(location.parent, element);
- }
- /** @protected */
- _isSpecialElement(element, id) {
- return SPECIAL_ELEMENTS[this.treeAdapter.getNamespaceURI(element)].has(id);
- }
- /** @internal */
- onCharacter(token) {
- this.skipNextNewLine = false;
- if (this.tokenizer.inForeignNode) {
- characterInForeignContent(this, token);
- return;
- }
- switch (this.insertionMode) {
- case InsertionMode.INITIAL:
- tokenInInitialMode(this, token);
- break;
- case InsertionMode.BEFORE_HTML:
- tokenBeforeHtml(this, token);
- break;
- case InsertionMode.BEFORE_HEAD:
- tokenBeforeHead(this, token);
- break;
- case InsertionMode.IN_HEAD:
- tokenInHead(this, token);
- break;
- case InsertionMode.IN_HEAD_NO_SCRIPT:
- tokenInHeadNoScript(this, token);
- break;
- case InsertionMode.AFTER_HEAD:
- tokenAfterHead(this, token);
- break;
- case InsertionMode.IN_BODY:
- case InsertionMode.IN_CAPTION:
- case InsertionMode.IN_CELL:
- case InsertionMode.IN_TEMPLATE:
- characterInBody(this, token);
- break;
- case InsertionMode.TEXT:
- case InsertionMode.IN_SELECT:
- case InsertionMode.IN_SELECT_IN_TABLE:
- this._insertCharacters(token);
- break;
- case InsertionMode.IN_TABLE:
- case InsertionMode.IN_TABLE_BODY:
- case InsertionMode.IN_ROW:
- characterInTable(this, token);
- break;
- case InsertionMode.IN_TABLE_TEXT:
- characterInTableText(this, token);
- break;
- case InsertionMode.IN_COLUMN_GROUP:
- tokenInColumnGroup(this, token);
- break;
- case InsertionMode.AFTER_BODY:
- tokenAfterBody(this, token);
- break;
- case InsertionMode.AFTER_AFTER_BODY:
- tokenAfterAfterBody(this, token);
- break;
- default:
- }
- }
- /** @internal */
- onNullCharacter(token) {
- this.skipNextNewLine = false;
- if (this.tokenizer.inForeignNode) {
- nullCharacterInForeignContent(this, token);
- return;
- }
- switch (this.insertionMode) {
- case InsertionMode.INITIAL:
- tokenInInitialMode(this, token);
- break;
- case InsertionMode.BEFORE_HTML:
- tokenBeforeHtml(this, token);
- break;
- case InsertionMode.BEFORE_HEAD:
- tokenBeforeHead(this, token);
- break;
- case InsertionMode.IN_HEAD:
- tokenInHead(this, token);
- break;
- case InsertionMode.IN_HEAD_NO_SCRIPT:
- tokenInHeadNoScript(this, token);
- break;
- case InsertionMode.AFTER_HEAD:
- tokenAfterHead(this, token);
- break;
- case InsertionMode.TEXT:
- this._insertCharacters(token);
- break;
- case InsertionMode.IN_TABLE:
- case InsertionMode.IN_TABLE_BODY:
- case InsertionMode.IN_ROW:
- characterInTable(this, token);
- break;
- case InsertionMode.IN_COLUMN_GROUP:
- tokenInColumnGroup(this, token);
- break;
- case InsertionMode.AFTER_BODY:
- tokenAfterBody(this, token);
- break;
- case InsertionMode.AFTER_AFTER_BODY:
- tokenAfterAfterBody(this, token);
- break;
- default:
- }
- }
- /** @internal */
- onComment(token) {
- this.skipNextNewLine = false;
- if (this.currentNotInHTML) {
- appendComment(this, token);
- return;
- }
- switch (this.insertionMode) {
- case InsertionMode.INITIAL:
- case InsertionMode.BEFORE_HTML:
- case InsertionMode.BEFORE_HEAD:
- case InsertionMode.IN_HEAD:
- case InsertionMode.IN_HEAD_NO_SCRIPT:
- case InsertionMode.AFTER_HEAD:
- case InsertionMode.IN_BODY:
- case InsertionMode.IN_TABLE:
- case InsertionMode.IN_CAPTION:
- case InsertionMode.IN_COLUMN_GROUP:
- case InsertionMode.IN_TABLE_BODY:
- case InsertionMode.IN_ROW:
- case InsertionMode.IN_CELL:
- case InsertionMode.IN_SELECT:
- case InsertionMode.IN_SELECT_IN_TABLE:
- case InsertionMode.IN_TEMPLATE:
- case InsertionMode.IN_FRAMESET:
- case InsertionMode.AFTER_FRAMESET:
- appendComment(this, token);
- break;
- case InsertionMode.IN_TABLE_TEXT:
- tokenInTableText(this, token);
- break;
- case InsertionMode.AFTER_BODY:
- appendCommentToRootHtmlElement(this, token);
- break;
- case InsertionMode.AFTER_AFTER_BODY:
- case InsertionMode.AFTER_AFTER_FRAMESET:
- appendCommentToDocument(this, token);
- break;
- default:
- }
- }
- /** @internal */
- onDoctype(token) {
- this.skipNextNewLine = false;
- switch (this.insertionMode) {
- case InsertionMode.INITIAL:
- doctypeInInitialMode(this, token);
- break;
- case InsertionMode.BEFORE_HEAD:
- case InsertionMode.IN_HEAD:
- case InsertionMode.IN_HEAD_NO_SCRIPT:
- case InsertionMode.AFTER_HEAD:
- this._err(token, ERR.misplacedDoctype);
- break;
- case InsertionMode.IN_TABLE_TEXT:
- tokenInTableText(this, token);
- break;
- default:
- }
- }
- /** @internal */
- onStartTag(token) {
- this.skipNextNewLine = false;
- this.currentToken = token;
- this._processStartTag(token);
- if (token.selfClosing && !token.ackSelfClosing) this._err(token, ERR.nonVoidHtmlElementStartTagWithTrailingSolidus);
- }
- /**
- * Processes a given start tag.
- *
- * `onStartTag` checks if a self-closing tag was recognized. When a token
- * is moved inbetween multiple insertion modes, this check for self-closing
- * could lead to false positives. To avoid this, `_processStartTag` is used
- * for nested calls.
- *
- * @param token The token to process.
- * @protected
- */
- _processStartTag(token) {
- if (this.shouldProcessStartTagTokenInForeignContent(token)) startTagInForeignContent(this, token);
- else this._startTagOutsideForeignContent(token);
- }
- /** @protected */
- _startTagOutsideForeignContent(token) {
- switch (this.insertionMode) {
- case InsertionMode.INITIAL:
- tokenInInitialMode(this, token);
- break;
- case InsertionMode.BEFORE_HTML:
- startTagBeforeHtml(this, token);
- break;
- case InsertionMode.BEFORE_HEAD:
- startTagBeforeHead(this, token);
- break;
- case InsertionMode.IN_HEAD:
- startTagInHead(this, token);
- break;
- case InsertionMode.IN_HEAD_NO_SCRIPT:
- startTagInHeadNoScript(this, token);
- break;
- case InsertionMode.AFTER_HEAD:
- startTagAfterHead(this, token);
- break;
- case InsertionMode.IN_BODY:
- startTagInBody(this, token);
- break;
- case InsertionMode.IN_TABLE:
- startTagInTable(this, token);
- break;
- case InsertionMode.IN_TABLE_TEXT:
- tokenInTableText(this, token);
- break;
- case InsertionMode.IN_CAPTION:
- startTagInCaption(this, token);
- break;
- case InsertionMode.IN_COLUMN_GROUP:
- startTagInColumnGroup(this, token);
- break;
- case InsertionMode.IN_TABLE_BODY:
- startTagInTableBody(this, token);
- break;
- case InsertionMode.IN_ROW:
- startTagInRow(this, token);
- break;
- case InsertionMode.IN_CELL:
- startTagInCell(this, token);
- break;
- case InsertionMode.IN_SELECT:
- startTagInSelect(this, token);
- break;
- case InsertionMode.IN_SELECT_IN_TABLE:
- startTagInSelectInTable(this, token);
- break;
- case InsertionMode.IN_TEMPLATE:
- startTagInTemplate(this, token);
- break;
- case InsertionMode.AFTER_BODY:
- startTagAfterBody(this, token);
- break;
- case InsertionMode.IN_FRAMESET:
- startTagInFrameset(this, token);
- break;
- case InsertionMode.AFTER_FRAMESET:
- startTagAfterFrameset(this, token);
- break;
- case InsertionMode.AFTER_AFTER_BODY:
- startTagAfterAfterBody(this, token);
- break;
- case InsertionMode.AFTER_AFTER_FRAMESET:
- startTagAfterAfterFrameset(this, token);
- break;
- default:
- }
- }
- /** @internal */
- onEndTag(token) {
- this.skipNextNewLine = false;
- this.currentToken = token;
- if (this.currentNotInHTML) endTagInForeignContent(this, token);
- else this._endTagOutsideForeignContent(token);
- }
- /** @protected */
- _endTagOutsideForeignContent(token) {
- switch (this.insertionMode) {
- case InsertionMode.INITIAL:
- tokenInInitialMode(this, token);
- break;
- case InsertionMode.BEFORE_HTML:
- endTagBeforeHtml(this, token);
- break;
- case InsertionMode.BEFORE_HEAD:
- endTagBeforeHead(this, token);
- break;
- case InsertionMode.IN_HEAD:
- endTagInHead(this, token);
- break;
- case InsertionMode.IN_HEAD_NO_SCRIPT:
- endTagInHeadNoScript(this, token);
- break;
- case InsertionMode.AFTER_HEAD:
- endTagAfterHead(this, token);
- break;
- case InsertionMode.IN_BODY:
- endTagInBody(this, token);
- break;
- case InsertionMode.TEXT:
- endTagInText(this, token);
- break;
- case InsertionMode.IN_TABLE:
- endTagInTable(this, token);
- break;
- case InsertionMode.IN_TABLE_TEXT:
- tokenInTableText(this, token);
- break;
- case InsertionMode.IN_CAPTION:
- endTagInCaption(this, token);
- break;
- case InsertionMode.IN_COLUMN_GROUP:
- endTagInColumnGroup(this, token);
- break;
- case InsertionMode.IN_TABLE_BODY:
- endTagInTableBody(this, token);
- break;
- case InsertionMode.IN_ROW:
- endTagInRow(this, token);
- break;
- case InsertionMode.IN_CELL:
- endTagInCell(this, token);
- break;
- case InsertionMode.IN_SELECT:
- endTagInSelect(this, token);
- break;
- case InsertionMode.IN_SELECT_IN_TABLE:
- endTagInSelectInTable(this, token);
- break;
- case InsertionMode.IN_TEMPLATE:
- endTagInTemplate(this, token);
- break;
- case InsertionMode.AFTER_BODY:
- endTagAfterBody(this, token);
- break;
- case InsertionMode.IN_FRAMESET:
- endTagInFrameset(this, token);
- break;
- case InsertionMode.AFTER_FRAMESET:
- endTagAfterFrameset(this, token);
- break;
- case InsertionMode.AFTER_AFTER_BODY:
- tokenAfterAfterBody(this, token);
- break;
- default:
- }
- }
- /** @internal */
- onEof(token) {
- switch (this.insertionMode) {
- case InsertionMode.INITIAL:
- tokenInInitialMode(this, token);
- break;
- case InsertionMode.BEFORE_HTML:
- tokenBeforeHtml(this, token);
- break;
- case InsertionMode.BEFORE_HEAD:
- tokenBeforeHead(this, token);
- break;
- case InsertionMode.IN_HEAD:
- tokenInHead(this, token);
- break;
- case InsertionMode.IN_HEAD_NO_SCRIPT:
- tokenInHeadNoScript(this, token);
- break;
- case InsertionMode.AFTER_HEAD:
- tokenAfterHead(this, token);
- break;
- case InsertionMode.IN_BODY:
- case InsertionMode.IN_TABLE:
- case InsertionMode.IN_CAPTION:
- case InsertionMode.IN_COLUMN_GROUP:
- case InsertionMode.IN_TABLE_BODY:
- case InsertionMode.IN_ROW:
- case InsertionMode.IN_CELL:
- case InsertionMode.IN_SELECT:
- case InsertionMode.IN_SELECT_IN_TABLE:
- eofInBody(this, token);
- break;
- case InsertionMode.TEXT:
- eofInText(this, token);
- break;
- case InsertionMode.IN_TABLE_TEXT:
- tokenInTableText(this, token);
- break;
- case InsertionMode.IN_TEMPLATE:
- eofInTemplate(this, token);
- break;
- case InsertionMode.AFTER_BODY:
- case InsertionMode.IN_FRAMESET:
- case InsertionMode.AFTER_FRAMESET:
- case InsertionMode.AFTER_AFTER_BODY:
- case InsertionMode.AFTER_AFTER_FRAMESET:
- stopParsing(this, token);
- break;
- default:
- }
- }
- /** @internal */
- onWhitespaceCharacter(token) {
- if (this.skipNextNewLine) {
- this.skipNextNewLine = false;
- if (token.chars.charCodeAt(0) === CODE_POINTS.LINE_FEED) {
- if (token.chars.length === 1) return;
- token.chars = token.chars.substr(1);
- }
- }
- if (this.tokenizer.inForeignNode) {
- this._insertCharacters(token);
- return;
- }
- switch (this.insertionMode) {
- case InsertionMode.IN_HEAD:
- case InsertionMode.IN_HEAD_NO_SCRIPT:
- case InsertionMode.AFTER_HEAD:
- case InsertionMode.TEXT:
- case InsertionMode.IN_COLUMN_GROUP:
- case InsertionMode.IN_SELECT:
- case InsertionMode.IN_SELECT_IN_TABLE:
- case InsertionMode.IN_FRAMESET:
- case InsertionMode.AFTER_FRAMESET:
- this._insertCharacters(token);
- break;
- case InsertionMode.IN_BODY:
- case InsertionMode.IN_CAPTION:
- case InsertionMode.IN_CELL:
- case InsertionMode.IN_TEMPLATE:
- case InsertionMode.AFTER_BODY:
- case InsertionMode.AFTER_AFTER_BODY:
- case InsertionMode.AFTER_AFTER_FRAMESET:
- whitespaceCharacterInBody(this, token);
- break;
- case InsertionMode.IN_TABLE:
- case InsertionMode.IN_TABLE_BODY:
- case InsertionMode.IN_ROW:
- characterInTable(this, token);
- break;
- case InsertionMode.IN_TABLE_TEXT:
- whitespaceCharacterInTableText(this, token);
- break;
- default:
- }
- }
-};
-function aaObtainFormattingElementEntry(p, token) {
- let formattingElementEntry = p.activeFormattingElements.getElementEntryInScopeWithTagName(token.tagName);
- if (formattingElementEntry) {
- if (!p.openElements.contains(formattingElementEntry.element)) {
- p.activeFormattingElements.removeEntry(formattingElementEntry);
- formattingElementEntry = null;
- } else if (!p.openElements.hasInScope(token.tagID)) formattingElementEntry = null;
- } else genericEndTagInBody(p, token);
- return formattingElementEntry;
-}
-function aaObtainFurthestBlock(p, formattingElementEntry) {
- let furthestBlock = null;
- let idx = p.openElements.stackTop;
- for (; idx >= 0; idx--) {
- const element = p.openElements.items[idx];
- if (element === formattingElementEntry.element) break;
- if (p._isSpecialElement(element, p.openElements.tagIDs[idx])) furthestBlock = element;
- }
- if (!furthestBlock) {
- p.openElements.shortenToLength(Math.max(idx, 0));
- p.activeFormattingElements.removeEntry(formattingElementEntry);
- }
- return furthestBlock;
-}
-function aaInnerLoop(p, furthestBlock, formattingElement) {
- let lastElement = furthestBlock;
- let nextElement = p.openElements.getCommonAncestor(furthestBlock);
- for (let i = 0, element = nextElement; element !== formattingElement; i++, element = nextElement) {
- nextElement = p.openElements.getCommonAncestor(element);
- const elementEntry = p.activeFormattingElements.getElementEntry(element);
- const counterOverflow = elementEntry && i >= AA_INNER_LOOP_ITER;
- if (!elementEntry || counterOverflow) {
- if (counterOverflow) p.activeFormattingElements.removeEntry(elementEntry);
- p.openElements.remove(element);
- } else {
- element = aaRecreateElementFromEntry(p, elementEntry);
- if (lastElement === furthestBlock) p.activeFormattingElements.bookmark = elementEntry;
- p.treeAdapter.detachNode(lastElement);
- p.treeAdapter.appendChild(element, lastElement);
- lastElement = element;
- }
- }
- return lastElement;
-}
-function aaRecreateElementFromEntry(p, elementEntry) {
- const ns = p.treeAdapter.getNamespaceURI(elementEntry.element);
- const newElement = p.treeAdapter.createElement(elementEntry.token.tagName, ns, elementEntry.token.attrs);
- p.openElements.replace(elementEntry.element, newElement);
- elementEntry.element = newElement;
- return newElement;
-}
-function aaInsertLastNodeInCommonAncestor(p, commonAncestor, lastElement) {
- const tid = getTagID(p.treeAdapter.getTagName(commonAncestor));
- if (p._isElementCausesFosterParenting(tid)) p._fosterParentElement(lastElement);
- else {
- const ns = p.treeAdapter.getNamespaceURI(commonAncestor);
- if (tid === TAG_ID.TEMPLATE && ns === NS.HTML) commonAncestor = p.treeAdapter.getTemplateContent(commonAncestor);
- p.treeAdapter.appendChild(commonAncestor, lastElement);
- }
-}
-function aaReplaceFormattingElement(p, furthestBlock, formattingElementEntry) {
- const ns = p.treeAdapter.getNamespaceURI(formattingElementEntry.element);
- const { token } = formattingElementEntry;
- const newElement = p.treeAdapter.createElement(token.tagName, ns, token.attrs);
- p._adoptNodes(furthestBlock, newElement);
- p.treeAdapter.appendChild(furthestBlock, newElement);
- p.activeFormattingElements.insertElementAfterBookmark(newElement, token);
- p.activeFormattingElements.removeEntry(formattingElementEntry);
- p.openElements.remove(formattingElementEntry.element);
- p.openElements.insertAfter(furthestBlock, newElement, token.tagID);
-}
-function callAdoptionAgency(p, token) {
- for (let i = 0; i < AA_OUTER_LOOP_ITER; i++) {
- const formattingElementEntry = aaObtainFormattingElementEntry(p, token);
- if (!formattingElementEntry) break;
- const furthestBlock = aaObtainFurthestBlock(p, formattingElementEntry);
- if (!furthestBlock) break;
- p.activeFormattingElements.bookmark = formattingElementEntry;
- const lastElement = aaInnerLoop(p, furthestBlock, formattingElementEntry.element);
- const commonAncestor = p.openElements.getCommonAncestor(formattingElementEntry.element);
- p.treeAdapter.detachNode(lastElement);
- if (commonAncestor) aaInsertLastNodeInCommonAncestor(p, commonAncestor, lastElement);
- aaReplaceFormattingElement(p, furthestBlock, formattingElementEntry);
- }
-}
-function appendComment(p, token) {
- p._appendCommentNode(token, p.openElements.currentTmplContentOrNode);
-}
-function appendCommentToRootHtmlElement(p, token) {
- p._appendCommentNode(token, p.openElements.items[0]);
-}
-function appendCommentToDocument(p, token) {
- p._appendCommentNode(token, p.document);
-}
-function stopParsing(p, token) {
- p.stopped = true;
- if (token.location) {
- const target = p.fragmentContext ? 0 : 2;
- for (let i = p.openElements.stackTop; i >= target; i--) p._setEndLocation(p.openElements.items[i], token);
- if (!p.fragmentContext && p.openElements.stackTop >= 0) {
- const htmlElement = p.openElements.items[0];
- const htmlLocation = p.treeAdapter.getNodeSourceCodeLocation(htmlElement);
- if (htmlLocation && !htmlLocation.endTag) {
- p._setEndLocation(htmlElement, token);
- if (p.openElements.stackTop >= 1) {
- const bodyElement = p.openElements.items[1];
- const bodyLocation = p.treeAdapter.getNodeSourceCodeLocation(bodyElement);
- if (bodyLocation && !bodyLocation.endTag) p._setEndLocation(bodyElement, token);
- }
- }
- }
- }
-}
-function doctypeInInitialMode(p, token) {
- p._setDocumentType(token);
- const mode = token.forceQuirks ? DOCUMENT_MODE.QUIRKS : getDocumentMode(token);
- if (!isConforming(token)) p._err(token, ERR.nonConformingDoctype);
- p.treeAdapter.setDocumentMode(p.document, mode);
- p.insertionMode = InsertionMode.BEFORE_HTML;
-}
-function tokenInInitialMode(p, token) {
- p._err(token, ERR.missingDoctype, true);
- p.treeAdapter.setDocumentMode(p.document, DOCUMENT_MODE.QUIRKS);
- p.insertionMode = InsertionMode.BEFORE_HTML;
- p._processToken(token);
-}
-function startTagBeforeHtml(p, token) {
- if (token.tagID === TAG_ID.HTML) {
- p._insertElement(token, NS.HTML);
- p.insertionMode = InsertionMode.BEFORE_HEAD;
- } else tokenBeforeHtml(p, token);
-}
-function endTagBeforeHtml(p, token) {
- const tn = token.tagID;
- if (tn === TAG_ID.HTML || tn === TAG_ID.HEAD || tn === TAG_ID.BODY || tn === TAG_ID.BR) tokenBeforeHtml(p, token);
-}
-function tokenBeforeHtml(p, token) {
- p._insertFakeRootElement();
- p.insertionMode = InsertionMode.BEFORE_HEAD;
- p._processToken(token);
-}
-function startTagBeforeHead(p, token) {
- switch (token.tagID) {
- case TAG_ID.HTML:
- startTagInBody(p, token);
- break;
- case TAG_ID.HEAD:
- p._insertElement(token, NS.HTML);
- p.headElement = p.openElements.current;
- p.insertionMode = InsertionMode.IN_HEAD;
- break;
- default: tokenBeforeHead(p, token);
- }
-}
-function endTagBeforeHead(p, token) {
- const tn = token.tagID;
- if (tn === TAG_ID.HEAD || tn === TAG_ID.BODY || tn === TAG_ID.HTML || tn === TAG_ID.BR) tokenBeforeHead(p, token);
- else p._err(token, ERR.endTagWithoutMatchingOpenElement);
-}
-function tokenBeforeHead(p, token) {
- p._insertFakeElement(TAG_NAMES.HEAD, TAG_ID.HEAD);
- p.headElement = p.openElements.current;
- p.insertionMode = InsertionMode.IN_HEAD;
- p._processToken(token);
-}
-function startTagInHead(p, token) {
- switch (token.tagID) {
- case TAG_ID.HTML:
- startTagInBody(p, token);
- break;
- case TAG_ID.BASE:
- case TAG_ID.BASEFONT:
- case TAG_ID.BGSOUND:
- case TAG_ID.LINK:
- case TAG_ID.META:
- p._appendElement(token, NS.HTML);
- token.ackSelfClosing = true;
- break;
- case TAG_ID.TITLE:
- p._switchToTextParsing(token, TokenizerMode.RCDATA);
- break;
- case TAG_ID.NOSCRIPT:
- if (p.options.scriptingEnabled) p._switchToTextParsing(token, TokenizerMode.RAWTEXT);
- else {
- p._insertElement(token, NS.HTML);
- p.insertionMode = InsertionMode.IN_HEAD_NO_SCRIPT;
- }
- break;
- case TAG_ID.NOFRAMES:
- case TAG_ID.STYLE:
- p._switchToTextParsing(token, TokenizerMode.RAWTEXT);
- break;
- case TAG_ID.SCRIPT:
- p._switchToTextParsing(token, TokenizerMode.SCRIPT_DATA);
- break;
- case TAG_ID.TEMPLATE:
- p._insertTemplate(token);
- p.activeFormattingElements.insertMarker();
- p.framesetOk = false;
- p.insertionMode = InsertionMode.IN_TEMPLATE;
- p.tmplInsertionModeStack.unshift(InsertionMode.IN_TEMPLATE);
- break;
- case TAG_ID.HEAD:
- p._err(token, ERR.misplacedStartTagForHeadElement);
- break;
- default: tokenInHead(p, token);
- }
-}
-function endTagInHead(p, token) {
- switch (token.tagID) {
- case TAG_ID.HEAD:
- p.openElements.pop();
- p.insertionMode = InsertionMode.AFTER_HEAD;
- break;
- case TAG_ID.BODY:
- case TAG_ID.BR:
- case TAG_ID.HTML:
- tokenInHead(p, token);
- break;
- case TAG_ID.TEMPLATE:
- templateEndTagInHead(p, token);
- break;
- default: p._err(token, ERR.endTagWithoutMatchingOpenElement);
- }
-}
-function templateEndTagInHead(p, token) {
- if (p.openElements.tmplCount > 0) {
- p.openElements.generateImpliedEndTagsThoroughly();
- if (p.openElements.currentTagId !== TAG_ID.TEMPLATE) p._err(token, ERR.closingOfElementWithOpenChildElements);
- p.openElements.popUntilTagNamePopped(TAG_ID.TEMPLATE);
- p.activeFormattingElements.clearToLastMarker();
- p.tmplInsertionModeStack.shift();
- p._resetInsertionMode();
- } else p._err(token, ERR.endTagWithoutMatchingOpenElement);
-}
-function tokenInHead(p, token) {
- p.openElements.pop();
- p.insertionMode = InsertionMode.AFTER_HEAD;
- p._processToken(token);
-}
-function startTagInHeadNoScript(p, token) {
- switch (token.tagID) {
- case TAG_ID.HTML:
- startTagInBody(p, token);
- break;
- case TAG_ID.BASEFONT:
- case TAG_ID.BGSOUND:
- case TAG_ID.HEAD:
- case TAG_ID.LINK:
- case TAG_ID.META:
- case TAG_ID.NOFRAMES:
- case TAG_ID.STYLE:
- startTagInHead(p, token);
- break;
- case TAG_ID.NOSCRIPT:
- p._err(token, ERR.nestedNoscriptInHead);
- break;
- default: tokenInHeadNoScript(p, token);
- }
-}
-function endTagInHeadNoScript(p, token) {
- switch (token.tagID) {
- case TAG_ID.NOSCRIPT:
- p.openElements.pop();
- p.insertionMode = InsertionMode.IN_HEAD;
- break;
- case TAG_ID.BR:
- tokenInHeadNoScript(p, token);
- break;
- default: p._err(token, ERR.endTagWithoutMatchingOpenElement);
- }
-}
-function tokenInHeadNoScript(p, token) {
- p._err(token, token.type === TokenType.EOF ? ERR.openElementsLeftAfterEof : ERR.disallowedContentInNoscriptInHead);
- p.openElements.pop();
- p.insertionMode = InsertionMode.IN_HEAD;
- p._processToken(token);
-}
-function startTagAfterHead(p, token) {
- switch (token.tagID) {
- case TAG_ID.HTML:
- startTagInBody(p, token);
- break;
- case TAG_ID.BODY:
- p._insertElement(token, NS.HTML);
- p.framesetOk = false;
- p.insertionMode = InsertionMode.IN_BODY;
- break;
- case TAG_ID.FRAMESET:
- p._insertElement(token, NS.HTML);
- p.insertionMode = InsertionMode.IN_FRAMESET;
- break;
- case TAG_ID.BASE:
- case TAG_ID.BASEFONT:
- case TAG_ID.BGSOUND:
- case TAG_ID.LINK:
- case TAG_ID.META:
- case TAG_ID.NOFRAMES:
- case TAG_ID.SCRIPT:
- case TAG_ID.STYLE:
- case TAG_ID.TEMPLATE:
- case TAG_ID.TITLE:
- p._err(token, ERR.abandonedHeadElementChild);
- p.openElements.push(p.headElement, TAG_ID.HEAD);
- startTagInHead(p, token);
- p.openElements.remove(p.headElement);
- break;
- case TAG_ID.HEAD:
- p._err(token, ERR.misplacedStartTagForHeadElement);
- break;
- default: tokenAfterHead(p, token);
- }
-}
-function endTagAfterHead(p, token) {
- switch (token.tagID) {
- case TAG_ID.BODY:
- case TAG_ID.HTML:
- case TAG_ID.BR:
- tokenAfterHead(p, token);
- break;
- case TAG_ID.TEMPLATE:
- templateEndTagInHead(p, token);
- break;
- default: p._err(token, ERR.endTagWithoutMatchingOpenElement);
- }
-}
-function tokenAfterHead(p, token) {
- p._insertFakeElement(TAG_NAMES.BODY, TAG_ID.BODY);
- p.insertionMode = InsertionMode.IN_BODY;
- modeInBody(p, token);
-}
-function modeInBody(p, token) {
- switch (token.type) {
- case TokenType.CHARACTER:
- characterInBody(p, token);
- break;
- case TokenType.WHITESPACE_CHARACTER:
- whitespaceCharacterInBody(p, token);
- break;
- case TokenType.COMMENT:
- appendComment(p, token);
- break;
- case TokenType.START_TAG:
- startTagInBody(p, token);
- break;
- case TokenType.END_TAG:
- endTagInBody(p, token);
- break;
- case TokenType.EOF:
- eofInBody(p, token);
- break;
- default:
- }
-}
-function whitespaceCharacterInBody(p, token) {
- p._reconstructActiveFormattingElements();
- p._insertCharacters(token);
-}
-function characterInBody(p, token) {
- p._reconstructActiveFormattingElements();
- p._insertCharacters(token);
- p.framesetOk = false;
-}
-function htmlStartTagInBody(p, token) {
- if (p.openElements.tmplCount === 0) p.treeAdapter.adoptAttributes(p.openElements.items[0], token.attrs);
-}
-function bodyStartTagInBody(p, token) {
- const bodyElement = p.openElements.tryPeekProperlyNestedBodyElement();
- if (bodyElement && p.openElements.tmplCount === 0) {
- p.framesetOk = false;
- p.treeAdapter.adoptAttributes(bodyElement, token.attrs);
- }
-}
-function framesetStartTagInBody(p, token) {
- const bodyElement = p.openElements.tryPeekProperlyNestedBodyElement();
- if (p.framesetOk && bodyElement) {
- p.treeAdapter.detachNode(bodyElement);
- p.openElements.popAllUpToHtmlElement();
- p._insertElement(token, NS.HTML);
- p.insertionMode = InsertionMode.IN_FRAMESET;
- }
-}
-function addressStartTagInBody(p, token) {
- if (p.openElements.hasInButtonScope(TAG_ID.P)) p._closePElement();
- p._insertElement(token, NS.HTML);
-}
-function numberedHeaderStartTagInBody(p, token) {
- if (p.openElements.hasInButtonScope(TAG_ID.P)) p._closePElement();
- if (p.openElements.currentTagId !== void 0 && NUMBERED_HEADERS.has(p.openElements.currentTagId)) p.openElements.pop();
- p._insertElement(token, NS.HTML);
-}
-function preStartTagInBody(p, token) {
- if (p.openElements.hasInButtonScope(TAG_ID.P)) p._closePElement();
- p._insertElement(token, NS.HTML);
- p.skipNextNewLine = true;
- p.framesetOk = false;
-}
-function formStartTagInBody(p, token) {
- const inTemplate = p.openElements.tmplCount > 0;
- if (!p.formElement || inTemplate) {
- if (p.openElements.hasInButtonScope(TAG_ID.P)) p._closePElement();
- p._insertElement(token, NS.HTML);
- if (!inTemplate) p.formElement = p.openElements.current;
- }
-}
-function listItemStartTagInBody(p, token) {
- p.framesetOk = false;
- const tn = token.tagID;
- for (let i = p.openElements.stackTop; i >= 0; i--) {
- const elementId = p.openElements.tagIDs[i];
- if (tn === TAG_ID.LI && elementId === TAG_ID.LI || (tn === TAG_ID.DD || tn === TAG_ID.DT) && (elementId === TAG_ID.DD || elementId === TAG_ID.DT)) {
- p.openElements.generateImpliedEndTagsWithExclusion(elementId);
- p.openElements.popUntilTagNamePopped(elementId);
- break;
- }
- if (elementId !== TAG_ID.ADDRESS && elementId !== TAG_ID.DIV && elementId !== TAG_ID.P && p._isSpecialElement(p.openElements.items[i], elementId)) break;
- }
- if (p.openElements.hasInButtonScope(TAG_ID.P)) p._closePElement();
- p._insertElement(token, NS.HTML);
-}
-function plaintextStartTagInBody(p, token) {
- if (p.openElements.hasInButtonScope(TAG_ID.P)) p._closePElement();
- p._insertElement(token, NS.HTML);
- p.tokenizer.state = TokenizerMode.PLAINTEXT;
-}
-function buttonStartTagInBody(p, token) {
- if (p.openElements.hasInScope(TAG_ID.BUTTON)) {
- p.openElements.generateImpliedEndTags();
- p.openElements.popUntilTagNamePopped(TAG_ID.BUTTON);
- }
- p._reconstructActiveFormattingElements();
- p._insertElement(token, NS.HTML);
- p.framesetOk = false;
-}
-function aStartTagInBody(p, token) {
- const activeElementEntry = p.activeFormattingElements.getElementEntryInScopeWithTagName(TAG_NAMES.A);
- if (activeElementEntry) {
- callAdoptionAgency(p, token);
- p.openElements.remove(activeElementEntry.element);
- p.activeFormattingElements.removeEntry(activeElementEntry);
- }
- p._reconstructActiveFormattingElements();
- p._insertElement(token, NS.HTML);
- p.activeFormattingElements.pushElement(p.openElements.current, token);
-}
-function bStartTagInBody(p, token) {
- p._reconstructActiveFormattingElements();
- p._insertElement(token, NS.HTML);
- p.activeFormattingElements.pushElement(p.openElements.current, token);
-}
-function nobrStartTagInBody(p, token) {
- p._reconstructActiveFormattingElements();
- if (p.openElements.hasInScope(TAG_ID.NOBR)) {
- callAdoptionAgency(p, token);
- p._reconstructActiveFormattingElements();
- }
- p._insertElement(token, NS.HTML);
- p.activeFormattingElements.pushElement(p.openElements.current, token);
-}
-function appletStartTagInBody(p, token) {
- p._reconstructActiveFormattingElements();
- p._insertElement(token, NS.HTML);
- p.activeFormattingElements.insertMarker();
- p.framesetOk = false;
-}
-function tableStartTagInBody(p, token) {
- if (p.treeAdapter.getDocumentMode(p.document) !== DOCUMENT_MODE.QUIRKS && p.openElements.hasInButtonScope(TAG_ID.P)) p._closePElement();
- p._insertElement(token, NS.HTML);
- p.framesetOk = false;
- p.insertionMode = InsertionMode.IN_TABLE;
-}
-function areaStartTagInBody(p, token) {
- p._reconstructActiveFormattingElements();
- p._appendElement(token, NS.HTML);
- p.framesetOk = false;
- token.ackSelfClosing = true;
-}
-function isHiddenInput(token) {
- const inputType = getTokenAttr(token, ATTRS.TYPE);
- return inputType != null && inputType.toLowerCase() === HIDDEN_INPUT_TYPE;
-}
-function inputStartTagInBody(p, token) {
- p._reconstructActiveFormattingElements();
- p._appendElement(token, NS.HTML);
- if (!isHiddenInput(token)) p.framesetOk = false;
- token.ackSelfClosing = true;
-}
-function paramStartTagInBody(p, token) {
- p._appendElement(token, NS.HTML);
- token.ackSelfClosing = true;
-}
-function hrStartTagInBody(p, token) {
- if (p.openElements.hasInButtonScope(TAG_ID.P)) p._closePElement();
- p._appendElement(token, NS.HTML);
- p.framesetOk = false;
- token.ackSelfClosing = true;
-}
-function imageStartTagInBody(p, token) {
- token.tagName = TAG_NAMES.IMG;
- token.tagID = TAG_ID.IMG;
- areaStartTagInBody(p, token);
-}
-function textareaStartTagInBody(p, token) {
- p._insertElement(token, NS.HTML);
- p.skipNextNewLine = true;
- p.tokenizer.state = TokenizerMode.RCDATA;
- p.originalInsertionMode = p.insertionMode;
- p.framesetOk = false;
- p.insertionMode = InsertionMode.TEXT;
-}
-function xmpStartTagInBody(p, token) {
- if (p.openElements.hasInButtonScope(TAG_ID.P)) p._closePElement();
- p._reconstructActiveFormattingElements();
- p.framesetOk = false;
- p._switchToTextParsing(token, TokenizerMode.RAWTEXT);
-}
-function iframeStartTagInBody(p, token) {
- p.framesetOk = false;
- p._switchToTextParsing(token, TokenizerMode.RAWTEXT);
-}
-function rawTextStartTagInBody(p, token) {
- p._switchToTextParsing(token, TokenizerMode.RAWTEXT);
-}
-function selectStartTagInBody(p, token) {
- p._reconstructActiveFormattingElements();
- p._insertElement(token, NS.HTML);
- p.framesetOk = false;
- p.insertionMode = p.insertionMode === InsertionMode.IN_TABLE || p.insertionMode === InsertionMode.IN_CAPTION || p.insertionMode === InsertionMode.IN_TABLE_BODY || p.insertionMode === InsertionMode.IN_ROW || p.insertionMode === InsertionMode.IN_CELL ? InsertionMode.IN_SELECT_IN_TABLE : InsertionMode.IN_SELECT;
-}
-function optgroupStartTagInBody(p, token) {
- if (p.openElements.currentTagId === TAG_ID.OPTION) p.openElements.pop();
- p._reconstructActiveFormattingElements();
- p._insertElement(token, NS.HTML);
-}
-function rbStartTagInBody(p, token) {
- if (p.openElements.hasInScope(TAG_ID.RUBY)) p.openElements.generateImpliedEndTags();
- p._insertElement(token, NS.HTML);
-}
-function rtStartTagInBody(p, token) {
- if (p.openElements.hasInScope(TAG_ID.RUBY)) p.openElements.generateImpliedEndTagsWithExclusion(TAG_ID.RTC);
- p._insertElement(token, NS.HTML);
-}
-function mathStartTagInBody(p, token) {
- p._reconstructActiveFormattingElements();
- adjustTokenMathMLAttrs(token);
- adjustTokenXMLAttrs(token);
- if (token.selfClosing) p._appendElement(token, NS.MATHML);
- else p._insertElement(token, NS.MATHML);
- token.ackSelfClosing = true;
-}
-function svgStartTagInBody(p, token) {
- p._reconstructActiveFormattingElements();
- adjustTokenSVGAttrs(token);
- adjustTokenXMLAttrs(token);
- if (token.selfClosing) p._appendElement(token, NS.SVG);
- else p._insertElement(token, NS.SVG);
- token.ackSelfClosing = true;
-}
-function genericStartTagInBody(p, token) {
- p._reconstructActiveFormattingElements();
- p._insertElement(token, NS.HTML);
-}
-function startTagInBody(p, token) {
- switch (token.tagID) {
- case TAG_ID.I:
- case TAG_ID.S:
- case TAG_ID.B:
- case TAG_ID.U:
- case TAG_ID.EM:
- case TAG_ID.TT:
- case TAG_ID.BIG:
- case TAG_ID.CODE:
- case TAG_ID.FONT:
- case TAG_ID.SMALL:
- case TAG_ID.STRIKE:
- case TAG_ID.STRONG:
- bStartTagInBody(p, token);
- break;
- case TAG_ID.A:
- aStartTagInBody(p, token);
- break;
- case TAG_ID.H1:
- case TAG_ID.H2:
- case TAG_ID.H3:
- case TAG_ID.H4:
- case TAG_ID.H5:
- case TAG_ID.H6:
- numberedHeaderStartTagInBody(p, token);
- break;
- case TAG_ID.P:
- case TAG_ID.DL:
- case TAG_ID.OL:
- case TAG_ID.UL:
- case TAG_ID.DIV:
- case TAG_ID.DIR:
- case TAG_ID.NAV:
- case TAG_ID.MAIN:
- case TAG_ID.MENU:
- case TAG_ID.ASIDE:
- case TAG_ID.CENTER:
- case TAG_ID.FIGURE:
- case TAG_ID.FOOTER:
- case TAG_ID.HEADER:
- case TAG_ID.HGROUP:
- case TAG_ID.DIALOG:
- case TAG_ID.DETAILS:
- case TAG_ID.ADDRESS:
- case TAG_ID.ARTICLE:
- case TAG_ID.SEARCH:
- case TAG_ID.SECTION:
- case TAG_ID.SUMMARY:
- case TAG_ID.FIELDSET:
- case TAG_ID.BLOCKQUOTE:
- case TAG_ID.FIGCAPTION:
- addressStartTagInBody(p, token);
- break;
- case TAG_ID.LI:
- case TAG_ID.DD:
- case TAG_ID.DT:
- listItemStartTagInBody(p, token);
- break;
- case TAG_ID.BR:
- case TAG_ID.IMG:
- case TAG_ID.WBR:
- case TAG_ID.AREA:
- case TAG_ID.EMBED:
- case TAG_ID.KEYGEN:
- areaStartTagInBody(p, token);
- break;
- case TAG_ID.HR:
- hrStartTagInBody(p, token);
- break;
- case TAG_ID.RB:
- case TAG_ID.RTC:
- rbStartTagInBody(p, token);
- break;
- case TAG_ID.RT:
- case TAG_ID.RP:
- rtStartTagInBody(p, token);
- break;
- case TAG_ID.PRE:
- case TAG_ID.LISTING:
- preStartTagInBody(p, token);
- break;
- case TAG_ID.XMP:
- xmpStartTagInBody(p, token);
- break;
- case TAG_ID.SVG:
- svgStartTagInBody(p, token);
- break;
- case TAG_ID.HTML:
- htmlStartTagInBody(p, token);
- break;
- case TAG_ID.BASE:
- case TAG_ID.LINK:
- case TAG_ID.META:
- case TAG_ID.STYLE:
- case TAG_ID.TITLE:
- case TAG_ID.SCRIPT:
- case TAG_ID.BGSOUND:
- case TAG_ID.BASEFONT:
- case TAG_ID.TEMPLATE:
- startTagInHead(p, token);
- break;
- case TAG_ID.BODY:
- bodyStartTagInBody(p, token);
- break;
- case TAG_ID.FORM:
- formStartTagInBody(p, token);
- break;
- case TAG_ID.NOBR:
- nobrStartTagInBody(p, token);
- break;
- case TAG_ID.MATH:
- mathStartTagInBody(p, token);
- break;
- case TAG_ID.TABLE:
- tableStartTagInBody(p, token);
- break;
- case TAG_ID.INPUT:
- inputStartTagInBody(p, token);
- break;
- case TAG_ID.PARAM:
- case TAG_ID.TRACK:
- case TAG_ID.SOURCE:
- paramStartTagInBody(p, token);
- break;
- case TAG_ID.IMAGE:
- imageStartTagInBody(p, token);
- break;
- case TAG_ID.BUTTON:
- buttonStartTagInBody(p, token);
- break;
- case TAG_ID.APPLET:
- case TAG_ID.OBJECT:
- case TAG_ID.MARQUEE:
- appletStartTagInBody(p, token);
- break;
- case TAG_ID.IFRAME:
- iframeStartTagInBody(p, token);
- break;
- case TAG_ID.SELECT:
- selectStartTagInBody(p, token);
- break;
- case TAG_ID.OPTION:
- case TAG_ID.OPTGROUP:
- optgroupStartTagInBody(p, token);
- break;
- case TAG_ID.NOEMBED:
- case TAG_ID.NOFRAMES:
- rawTextStartTagInBody(p, token);
- break;
- case TAG_ID.FRAMESET:
- framesetStartTagInBody(p, token);
- break;
- case TAG_ID.TEXTAREA:
- textareaStartTagInBody(p, token);
- break;
- case TAG_ID.NOSCRIPT:
- if (p.options.scriptingEnabled) rawTextStartTagInBody(p, token);
- else genericStartTagInBody(p, token);
- break;
- case TAG_ID.PLAINTEXT:
- plaintextStartTagInBody(p, token);
- break;
- case TAG_ID.COL:
- case TAG_ID.TH:
- case TAG_ID.TD:
- case TAG_ID.TR:
- case TAG_ID.HEAD:
- case TAG_ID.FRAME:
- case TAG_ID.TBODY:
- case TAG_ID.TFOOT:
- case TAG_ID.THEAD:
- case TAG_ID.CAPTION:
- case TAG_ID.COLGROUP: break;
- default: genericStartTagInBody(p, token);
- }
-}
-function bodyEndTagInBody(p, token) {
- if (p.openElements.hasInScope(TAG_ID.BODY)) {
- p.insertionMode = InsertionMode.AFTER_BODY;
- if (p.options.sourceCodeLocationInfo) {
- const bodyElement = p.openElements.tryPeekProperlyNestedBodyElement();
- if (bodyElement) p._setEndLocation(bodyElement, token);
- }
- }
-}
-function htmlEndTagInBody(p, token) {
- if (p.openElements.hasInScope(TAG_ID.BODY)) {
- p.insertionMode = InsertionMode.AFTER_BODY;
- endTagAfterBody(p, token);
- }
-}
-function addressEndTagInBody(p, token) {
- const tn = token.tagID;
- if (p.openElements.hasInScope(tn)) {
- p.openElements.generateImpliedEndTags();
- p.openElements.popUntilTagNamePopped(tn);
- }
-}
-function formEndTagInBody(p) {
- const inTemplate = p.openElements.tmplCount > 0;
- const { formElement } = p;
- if (!inTemplate) p.formElement = null;
- if ((formElement || inTemplate) && p.openElements.hasInScope(TAG_ID.FORM)) {
- p.openElements.generateImpliedEndTags();
- if (inTemplate) p.openElements.popUntilTagNamePopped(TAG_ID.FORM);
- else if (formElement) p.openElements.remove(formElement);
- }
-}
-function pEndTagInBody(p) {
- if (!p.openElements.hasInButtonScope(TAG_ID.P)) p._insertFakeElement(TAG_NAMES.P, TAG_ID.P);
- p._closePElement();
-}
-function liEndTagInBody(p) {
- if (p.openElements.hasInListItemScope(TAG_ID.LI)) {
- p.openElements.generateImpliedEndTagsWithExclusion(TAG_ID.LI);
- p.openElements.popUntilTagNamePopped(TAG_ID.LI);
- }
-}
-function ddEndTagInBody(p, token) {
- const tn = token.tagID;
- if (p.openElements.hasInScope(tn)) {
- p.openElements.generateImpliedEndTagsWithExclusion(tn);
- p.openElements.popUntilTagNamePopped(tn);
- }
-}
-function numberedHeaderEndTagInBody(p) {
- if (p.openElements.hasNumberedHeaderInScope()) {
- p.openElements.generateImpliedEndTags();
- p.openElements.popUntilNumberedHeaderPopped();
- }
-}
-function appletEndTagInBody(p, token) {
- const tn = token.tagID;
- if (p.openElements.hasInScope(tn)) {
- p.openElements.generateImpliedEndTags();
- p.openElements.popUntilTagNamePopped(tn);
- p.activeFormattingElements.clearToLastMarker();
- }
-}
-function brEndTagInBody(p) {
- p._reconstructActiveFormattingElements();
- p._insertFakeElement(TAG_NAMES.BR, TAG_ID.BR);
- p.openElements.pop();
- p.framesetOk = false;
-}
-function genericEndTagInBody(p, token) {
- const tn = token.tagName;
- const tid = token.tagID;
- for (let i = p.openElements.stackTop; i > 0; i--) {
- const element = p.openElements.items[i];
- const elementId = p.openElements.tagIDs[i];
- if (tid === elementId && (tid !== TAG_ID.UNKNOWN || p.treeAdapter.getTagName(element) === tn)) {
- p.openElements.generateImpliedEndTagsWithExclusion(tid);
- if (p.openElements.stackTop >= i) p.openElements.shortenToLength(i);
- break;
- }
- if (p._isSpecialElement(element, elementId)) break;
- }
-}
-function endTagInBody(p, token) {
- switch (token.tagID) {
- case TAG_ID.A:
- case TAG_ID.B:
- case TAG_ID.I:
- case TAG_ID.S:
- case TAG_ID.U:
- case TAG_ID.EM:
- case TAG_ID.TT:
- case TAG_ID.BIG:
- case TAG_ID.CODE:
- case TAG_ID.FONT:
- case TAG_ID.NOBR:
- case TAG_ID.SMALL:
- case TAG_ID.STRIKE:
- case TAG_ID.STRONG:
- callAdoptionAgency(p, token);
- break;
- case TAG_ID.P:
- pEndTagInBody(p);
- break;
- case TAG_ID.DL:
- case TAG_ID.UL:
- case TAG_ID.OL:
- case TAG_ID.DIR:
- case TAG_ID.DIV:
- case TAG_ID.NAV:
- case TAG_ID.PRE:
- case TAG_ID.MAIN:
- case TAG_ID.MENU:
- case TAG_ID.ASIDE:
- case TAG_ID.BUTTON:
- case TAG_ID.CENTER:
- case TAG_ID.FIGURE:
- case TAG_ID.FOOTER:
- case TAG_ID.HEADER:
- case TAG_ID.HGROUP:
- case TAG_ID.DIALOG:
- case TAG_ID.ADDRESS:
- case TAG_ID.ARTICLE:
- case TAG_ID.DETAILS:
- case TAG_ID.SEARCH:
- case TAG_ID.SECTION:
- case TAG_ID.SUMMARY:
- case TAG_ID.LISTING:
- case TAG_ID.FIELDSET:
- case TAG_ID.BLOCKQUOTE:
- case TAG_ID.FIGCAPTION:
- addressEndTagInBody(p, token);
- break;
- case TAG_ID.LI:
- liEndTagInBody(p);
- break;
- case TAG_ID.DD:
- case TAG_ID.DT:
- ddEndTagInBody(p, token);
- break;
- case TAG_ID.H1:
- case TAG_ID.H2:
- case TAG_ID.H3:
- case TAG_ID.H4:
- case TAG_ID.H5:
- case TAG_ID.H6:
- numberedHeaderEndTagInBody(p);
- break;
- case TAG_ID.BR:
- brEndTagInBody(p);
- break;
- case TAG_ID.BODY:
- bodyEndTagInBody(p, token);
- break;
- case TAG_ID.HTML:
- htmlEndTagInBody(p, token);
- break;
- case TAG_ID.FORM:
- formEndTagInBody(p);
- break;
- case TAG_ID.APPLET:
- case TAG_ID.OBJECT:
- case TAG_ID.MARQUEE:
- appletEndTagInBody(p, token);
- break;
- case TAG_ID.TEMPLATE:
- templateEndTagInHead(p, token);
- break;
- default: genericEndTagInBody(p, token);
- }
-}
-function eofInBody(p, token) {
- if (p.tmplInsertionModeStack.length > 0) eofInTemplate(p, token);
- else stopParsing(p, token);
-}
-function endTagInText(p, token) {
- var _a$1;
- if (token.tagID === TAG_ID.SCRIPT) (_a$1 = p.scriptHandler) === null || _a$1 === void 0 || _a$1.call(p, p.openElements.current);
- p.openElements.pop();
- p.insertionMode = p.originalInsertionMode;
-}
-function eofInText(p, token) {
- p._err(token, ERR.eofInElementThatCanContainOnlyText);
- p.openElements.pop();
- p.insertionMode = p.originalInsertionMode;
- p.onEof(token);
-}
-function characterInTable(p, token) {
- if (p.openElements.currentTagId !== void 0 && TABLE_STRUCTURE_TAGS.has(p.openElements.currentTagId)) {
- p.pendingCharacterTokens.length = 0;
- p.hasNonWhitespacePendingCharacterToken = false;
- p.originalInsertionMode = p.insertionMode;
- p.insertionMode = InsertionMode.IN_TABLE_TEXT;
- switch (token.type) {
- case TokenType.CHARACTER:
- characterInTableText(p, token);
- break;
- case TokenType.WHITESPACE_CHARACTER:
- whitespaceCharacterInTableText(p, token);
- break;
- }
- } else tokenInTable(p, token);
-}
-function captionStartTagInTable(p, token) {
- p.openElements.clearBackToTableContext();
- p.activeFormattingElements.insertMarker();
- p._insertElement(token, NS.HTML);
- p.insertionMode = InsertionMode.IN_CAPTION;
-}
-function colgroupStartTagInTable(p, token) {
- p.openElements.clearBackToTableContext();
- p._insertElement(token, NS.HTML);
- p.insertionMode = InsertionMode.IN_COLUMN_GROUP;
-}
-function colStartTagInTable(p, token) {
- p.openElements.clearBackToTableContext();
- p._insertFakeElement(TAG_NAMES.COLGROUP, TAG_ID.COLGROUP);
- p.insertionMode = InsertionMode.IN_COLUMN_GROUP;
- startTagInColumnGroup(p, token);
-}
-function tbodyStartTagInTable(p, token) {
- p.openElements.clearBackToTableContext();
- p._insertElement(token, NS.HTML);
- p.insertionMode = InsertionMode.IN_TABLE_BODY;
-}
-function tdStartTagInTable(p, token) {
- p.openElements.clearBackToTableContext();
- p._insertFakeElement(TAG_NAMES.TBODY, TAG_ID.TBODY);
- p.insertionMode = InsertionMode.IN_TABLE_BODY;
- startTagInTableBody(p, token);
-}
-function tableStartTagInTable(p, token) {
- if (p.openElements.hasInTableScope(TAG_ID.TABLE)) {
- p.openElements.popUntilTagNamePopped(TAG_ID.TABLE);
- p._resetInsertionMode();
- p._processStartTag(token);
- }
-}
-function inputStartTagInTable(p, token) {
- if (isHiddenInput(token)) p._appendElement(token, NS.HTML);
- else tokenInTable(p, token);
- token.ackSelfClosing = true;
-}
-function formStartTagInTable(p, token) {
- if (!p.formElement && p.openElements.tmplCount === 0) {
- p._insertElement(token, NS.HTML);
- p.formElement = p.openElements.current;
- p.openElements.pop();
- }
-}
-function startTagInTable(p, token) {
- switch (token.tagID) {
- case TAG_ID.TD:
- case TAG_ID.TH:
- case TAG_ID.TR:
- tdStartTagInTable(p, token);
- break;
- case TAG_ID.STYLE:
- case TAG_ID.SCRIPT:
- case TAG_ID.TEMPLATE:
- startTagInHead(p, token);
- break;
- case TAG_ID.COL:
- colStartTagInTable(p, token);
- break;
- case TAG_ID.FORM:
- formStartTagInTable(p, token);
- break;
- case TAG_ID.TABLE:
- tableStartTagInTable(p, token);
- break;
- case TAG_ID.TBODY:
- case TAG_ID.TFOOT:
- case TAG_ID.THEAD:
- tbodyStartTagInTable(p, token);
- break;
- case TAG_ID.INPUT:
- inputStartTagInTable(p, token);
- break;
- case TAG_ID.CAPTION:
- captionStartTagInTable(p, token);
- break;
- case TAG_ID.COLGROUP:
- colgroupStartTagInTable(p, token);
- break;
- default: tokenInTable(p, token);
- }
-}
-function endTagInTable(p, token) {
- switch (token.tagID) {
- case TAG_ID.TABLE:
- if (p.openElements.hasInTableScope(TAG_ID.TABLE)) {
- p.openElements.popUntilTagNamePopped(TAG_ID.TABLE);
- p._resetInsertionMode();
- }
- break;
- case TAG_ID.TEMPLATE:
- templateEndTagInHead(p, token);
- break;
- case TAG_ID.BODY:
- case TAG_ID.CAPTION:
- case TAG_ID.COL:
- case TAG_ID.COLGROUP:
- case TAG_ID.HTML:
- case TAG_ID.TBODY:
- case TAG_ID.TD:
- case TAG_ID.TFOOT:
- case TAG_ID.TH:
- case TAG_ID.THEAD:
- case TAG_ID.TR: break;
- default: tokenInTable(p, token);
- }
-}
-function tokenInTable(p, token) {
- const savedFosterParentingState = p.fosterParentingEnabled;
- p.fosterParentingEnabled = true;
- modeInBody(p, token);
- p.fosterParentingEnabled = savedFosterParentingState;
-}
-function whitespaceCharacterInTableText(p, token) {
- p.pendingCharacterTokens.push(token);
-}
-function characterInTableText(p, token) {
- p.pendingCharacterTokens.push(token);
- p.hasNonWhitespacePendingCharacterToken = true;
-}
-function tokenInTableText(p, token) {
- let i = 0;
- if (p.hasNonWhitespacePendingCharacterToken) for (; i < p.pendingCharacterTokens.length; i++) tokenInTable(p, p.pendingCharacterTokens[i]);
- else for (; i < p.pendingCharacterTokens.length; i++) p._insertCharacters(p.pendingCharacterTokens[i]);
- p.insertionMode = p.originalInsertionMode;
- p._processToken(token);
-}
-const TABLE_VOID_ELEMENTS = new Set([
- TAG_ID.CAPTION,
- TAG_ID.COL,
- TAG_ID.COLGROUP,
- TAG_ID.TBODY,
- TAG_ID.TD,
- TAG_ID.TFOOT,
- TAG_ID.TH,
- TAG_ID.THEAD,
- TAG_ID.TR
-]);
-function startTagInCaption(p, token) {
- if (TABLE_VOID_ELEMENTS.has(token.tagID)) {
- if (p.openElements.hasInTableScope(TAG_ID.CAPTION)) {
- p.openElements.generateImpliedEndTags();
- p.openElements.popUntilTagNamePopped(TAG_ID.CAPTION);
- p.activeFormattingElements.clearToLastMarker();
- p.insertionMode = InsertionMode.IN_TABLE;
- startTagInTable(p, token);
- }
- } else startTagInBody(p, token);
-}
-function endTagInCaption(p, token) {
- const tn = token.tagID;
- switch (tn) {
- case TAG_ID.CAPTION:
- case TAG_ID.TABLE:
- if (p.openElements.hasInTableScope(TAG_ID.CAPTION)) {
- p.openElements.generateImpliedEndTags();
- p.openElements.popUntilTagNamePopped(TAG_ID.CAPTION);
- p.activeFormattingElements.clearToLastMarker();
- p.insertionMode = InsertionMode.IN_TABLE;
- if (tn === TAG_ID.TABLE) endTagInTable(p, token);
- }
- break;
- case TAG_ID.BODY:
- case TAG_ID.COL:
- case TAG_ID.COLGROUP:
- case TAG_ID.HTML:
- case TAG_ID.TBODY:
- case TAG_ID.TD:
- case TAG_ID.TFOOT:
- case TAG_ID.TH:
- case TAG_ID.THEAD:
- case TAG_ID.TR: break;
- default: endTagInBody(p, token);
- }
-}
-function startTagInColumnGroup(p, token) {
- switch (token.tagID) {
- case TAG_ID.HTML:
- startTagInBody(p, token);
- break;
- case TAG_ID.COL:
- p._appendElement(token, NS.HTML);
- token.ackSelfClosing = true;
- break;
- case TAG_ID.TEMPLATE:
- startTagInHead(p, token);
- break;
- default: tokenInColumnGroup(p, token);
- }
-}
-function endTagInColumnGroup(p, token) {
- switch (token.tagID) {
- case TAG_ID.COLGROUP:
- if (p.openElements.currentTagId === TAG_ID.COLGROUP) {
- p.openElements.pop();
- p.insertionMode = InsertionMode.IN_TABLE;
- }
- break;
- case TAG_ID.TEMPLATE:
- templateEndTagInHead(p, token);
- break;
- case TAG_ID.COL: break;
- default: tokenInColumnGroup(p, token);
- }
-}
-function tokenInColumnGroup(p, token) {
- if (p.openElements.currentTagId === TAG_ID.COLGROUP) {
- p.openElements.pop();
- p.insertionMode = InsertionMode.IN_TABLE;
- p._processToken(token);
- }
-}
-function startTagInTableBody(p, token) {
- switch (token.tagID) {
- case TAG_ID.TR:
- p.openElements.clearBackToTableBodyContext();
- p._insertElement(token, NS.HTML);
- p.insertionMode = InsertionMode.IN_ROW;
- break;
- case TAG_ID.TH:
- case TAG_ID.TD:
- p.openElements.clearBackToTableBodyContext();
- p._insertFakeElement(TAG_NAMES.TR, TAG_ID.TR);
- p.insertionMode = InsertionMode.IN_ROW;
- startTagInRow(p, token);
- break;
- case TAG_ID.CAPTION:
- case TAG_ID.COL:
- case TAG_ID.COLGROUP:
- case TAG_ID.TBODY:
- case TAG_ID.TFOOT:
- case TAG_ID.THEAD:
- if (p.openElements.hasTableBodyContextInTableScope()) {
- p.openElements.clearBackToTableBodyContext();
- p.openElements.pop();
- p.insertionMode = InsertionMode.IN_TABLE;
- startTagInTable(p, token);
- }
- break;
- default: startTagInTable(p, token);
- }
-}
-function endTagInTableBody(p, token) {
- const tn = token.tagID;
- switch (token.tagID) {
- case TAG_ID.TBODY:
- case TAG_ID.TFOOT:
- case TAG_ID.THEAD:
- if (p.openElements.hasInTableScope(tn)) {
- p.openElements.clearBackToTableBodyContext();
- p.openElements.pop();
- p.insertionMode = InsertionMode.IN_TABLE;
- }
- break;
- case TAG_ID.TABLE:
- if (p.openElements.hasTableBodyContextInTableScope()) {
- p.openElements.clearBackToTableBodyContext();
- p.openElements.pop();
- p.insertionMode = InsertionMode.IN_TABLE;
- endTagInTable(p, token);
- }
- break;
- case TAG_ID.BODY:
- case TAG_ID.CAPTION:
- case TAG_ID.COL:
- case TAG_ID.COLGROUP:
- case TAG_ID.HTML:
- case TAG_ID.TD:
- case TAG_ID.TH:
- case TAG_ID.TR: break;
- default: endTagInTable(p, token);
- }
-}
-function startTagInRow(p, token) {
- switch (token.tagID) {
- case TAG_ID.TH:
- case TAG_ID.TD:
- p.openElements.clearBackToTableRowContext();
- p._insertElement(token, NS.HTML);
- p.insertionMode = InsertionMode.IN_CELL;
- p.activeFormattingElements.insertMarker();
- break;
- case TAG_ID.CAPTION:
- case TAG_ID.COL:
- case TAG_ID.COLGROUP:
- case TAG_ID.TBODY:
- case TAG_ID.TFOOT:
- case TAG_ID.THEAD:
- case TAG_ID.TR:
- if (p.openElements.hasInTableScope(TAG_ID.TR)) {
- p.openElements.clearBackToTableRowContext();
- p.openElements.pop();
- p.insertionMode = InsertionMode.IN_TABLE_BODY;
- startTagInTableBody(p, token);
- }
- break;
- default: startTagInTable(p, token);
- }
-}
-function endTagInRow(p, token) {
- switch (token.tagID) {
- case TAG_ID.TR:
- if (p.openElements.hasInTableScope(TAG_ID.TR)) {
- p.openElements.clearBackToTableRowContext();
- p.openElements.pop();
- p.insertionMode = InsertionMode.IN_TABLE_BODY;
- }
- break;
- case TAG_ID.TABLE:
- if (p.openElements.hasInTableScope(TAG_ID.TR)) {
- p.openElements.clearBackToTableRowContext();
- p.openElements.pop();
- p.insertionMode = InsertionMode.IN_TABLE_BODY;
- endTagInTableBody(p, token);
- }
- break;
- case TAG_ID.TBODY:
- case TAG_ID.TFOOT:
- case TAG_ID.THEAD:
- if (p.openElements.hasInTableScope(token.tagID) || p.openElements.hasInTableScope(TAG_ID.TR)) {
- p.openElements.clearBackToTableRowContext();
- p.openElements.pop();
- p.insertionMode = InsertionMode.IN_TABLE_BODY;
- endTagInTableBody(p, token);
- }
- break;
- case TAG_ID.BODY:
- case TAG_ID.CAPTION:
- case TAG_ID.COL:
- case TAG_ID.COLGROUP:
- case TAG_ID.HTML:
- case TAG_ID.TD:
- case TAG_ID.TH: break;
- default: endTagInTable(p, token);
- }
-}
-function startTagInCell(p, token) {
- if (TABLE_VOID_ELEMENTS.has(token.tagID)) {
- if (p.openElements.hasInTableScope(TAG_ID.TD) || p.openElements.hasInTableScope(TAG_ID.TH)) {
- p._closeTableCell();
- startTagInRow(p, token);
- }
- } else startTagInBody(p, token);
-}
-function endTagInCell(p, token) {
- const tn = token.tagID;
- switch (tn) {
- case TAG_ID.TD:
- case TAG_ID.TH:
- if (p.openElements.hasInTableScope(tn)) {
- p.openElements.generateImpliedEndTags();
- p.openElements.popUntilTagNamePopped(tn);
- p.activeFormattingElements.clearToLastMarker();
- p.insertionMode = InsertionMode.IN_ROW;
- }
- break;
- case TAG_ID.TABLE:
- case TAG_ID.TBODY:
- case TAG_ID.TFOOT:
- case TAG_ID.THEAD:
- case TAG_ID.TR:
- if (p.openElements.hasInTableScope(tn)) {
- p._closeTableCell();
- endTagInRow(p, token);
- }
- break;
- case TAG_ID.BODY:
- case TAG_ID.CAPTION:
- case TAG_ID.COL:
- case TAG_ID.COLGROUP:
- case TAG_ID.HTML: break;
- default: endTagInBody(p, token);
- }
-}
-function startTagInSelect(p, token) {
- switch (token.tagID) {
- case TAG_ID.HTML:
- startTagInBody(p, token);
- break;
- case TAG_ID.OPTION:
- if (p.openElements.currentTagId === TAG_ID.OPTION) p.openElements.pop();
- p._insertElement(token, NS.HTML);
- break;
- case TAG_ID.OPTGROUP:
- if (p.openElements.currentTagId === TAG_ID.OPTION) p.openElements.pop();
- if (p.openElements.currentTagId === TAG_ID.OPTGROUP) p.openElements.pop();
- p._insertElement(token, NS.HTML);
- break;
- case TAG_ID.HR:
- if (p.openElements.currentTagId === TAG_ID.OPTION) p.openElements.pop();
- if (p.openElements.currentTagId === TAG_ID.OPTGROUP) p.openElements.pop();
- p._appendElement(token, NS.HTML);
- token.ackSelfClosing = true;
- break;
- case TAG_ID.INPUT:
- case TAG_ID.KEYGEN:
- case TAG_ID.TEXTAREA:
- case TAG_ID.SELECT:
- if (p.openElements.hasInSelectScope(TAG_ID.SELECT)) {
- p.openElements.popUntilTagNamePopped(TAG_ID.SELECT);
- p._resetInsertionMode();
- if (token.tagID !== TAG_ID.SELECT) p._processStartTag(token);
- }
- break;
- case TAG_ID.SCRIPT:
- case TAG_ID.TEMPLATE:
- startTagInHead(p, token);
- break;
- default:
- }
-}
-function endTagInSelect(p, token) {
- switch (token.tagID) {
- case TAG_ID.OPTGROUP:
- if (p.openElements.stackTop > 0 && p.openElements.currentTagId === TAG_ID.OPTION && p.openElements.tagIDs[p.openElements.stackTop - 1] === TAG_ID.OPTGROUP) p.openElements.pop();
- if (p.openElements.currentTagId === TAG_ID.OPTGROUP) p.openElements.pop();
- break;
- case TAG_ID.OPTION:
- if (p.openElements.currentTagId === TAG_ID.OPTION) p.openElements.pop();
- break;
- case TAG_ID.SELECT:
- if (p.openElements.hasInSelectScope(TAG_ID.SELECT)) {
- p.openElements.popUntilTagNamePopped(TAG_ID.SELECT);
- p._resetInsertionMode();
- }
- break;
- case TAG_ID.TEMPLATE:
- templateEndTagInHead(p, token);
- break;
- default:
- }
-}
-function startTagInSelectInTable(p, token) {
- const tn = token.tagID;
- if (tn === TAG_ID.CAPTION || tn === TAG_ID.TABLE || tn === TAG_ID.TBODY || tn === TAG_ID.TFOOT || tn === TAG_ID.THEAD || tn === TAG_ID.TR || tn === TAG_ID.TD || tn === TAG_ID.TH) {
- p.openElements.popUntilTagNamePopped(TAG_ID.SELECT);
- p._resetInsertionMode();
- p._processStartTag(token);
- } else startTagInSelect(p, token);
-}
-function endTagInSelectInTable(p, token) {
- const tn = token.tagID;
- if (tn === TAG_ID.CAPTION || tn === TAG_ID.TABLE || tn === TAG_ID.TBODY || tn === TAG_ID.TFOOT || tn === TAG_ID.THEAD || tn === TAG_ID.TR || tn === TAG_ID.TD || tn === TAG_ID.TH) {
- if (p.openElements.hasInTableScope(tn)) {
- p.openElements.popUntilTagNamePopped(TAG_ID.SELECT);
- p._resetInsertionMode();
- p.onEndTag(token);
- }
- } else endTagInSelect(p, token);
-}
-function startTagInTemplate(p, token) {
- switch (token.tagID) {
- case TAG_ID.BASE:
- case TAG_ID.BASEFONT:
- case TAG_ID.BGSOUND:
- case TAG_ID.LINK:
- case TAG_ID.META:
- case TAG_ID.NOFRAMES:
- case TAG_ID.SCRIPT:
- case TAG_ID.STYLE:
- case TAG_ID.TEMPLATE:
- case TAG_ID.TITLE:
- startTagInHead(p, token);
- break;
- case TAG_ID.CAPTION:
- case TAG_ID.COLGROUP:
- case TAG_ID.TBODY:
- case TAG_ID.TFOOT:
- case TAG_ID.THEAD:
- p.tmplInsertionModeStack[0] = InsertionMode.IN_TABLE;
- p.insertionMode = InsertionMode.IN_TABLE;
- startTagInTable(p, token);
- break;
- case TAG_ID.COL:
- p.tmplInsertionModeStack[0] = InsertionMode.IN_COLUMN_GROUP;
- p.insertionMode = InsertionMode.IN_COLUMN_GROUP;
- startTagInColumnGroup(p, token);
- break;
- case TAG_ID.TR:
- p.tmplInsertionModeStack[0] = InsertionMode.IN_TABLE_BODY;
- p.insertionMode = InsertionMode.IN_TABLE_BODY;
- startTagInTableBody(p, token);
- break;
- case TAG_ID.TD:
- case TAG_ID.TH:
- p.tmplInsertionModeStack[0] = InsertionMode.IN_ROW;
- p.insertionMode = InsertionMode.IN_ROW;
- startTagInRow(p, token);
- break;
- default:
- p.tmplInsertionModeStack[0] = InsertionMode.IN_BODY;
- p.insertionMode = InsertionMode.IN_BODY;
- startTagInBody(p, token);
- }
-}
-function endTagInTemplate(p, token) {
- if (token.tagID === TAG_ID.TEMPLATE) templateEndTagInHead(p, token);
-}
-function eofInTemplate(p, token) {
- if (p.openElements.tmplCount > 0) {
- p.openElements.popUntilTagNamePopped(TAG_ID.TEMPLATE);
- p.activeFormattingElements.clearToLastMarker();
- p.tmplInsertionModeStack.shift();
- p._resetInsertionMode();
- p.onEof(token);
- } else stopParsing(p, token);
-}
-function startTagAfterBody(p, token) {
- if (token.tagID === TAG_ID.HTML) startTagInBody(p, token);
- else tokenAfterBody(p, token);
-}
-function endTagAfterBody(p, token) {
- var _a$1;
- if (token.tagID === TAG_ID.HTML) {
- if (!p.fragmentContext) p.insertionMode = InsertionMode.AFTER_AFTER_BODY;
- if (p.options.sourceCodeLocationInfo && p.openElements.tagIDs[0] === TAG_ID.HTML) {
- p._setEndLocation(p.openElements.items[0], token);
- const bodyElement = p.openElements.items[1];
- if (bodyElement && !((_a$1 = p.treeAdapter.getNodeSourceCodeLocation(bodyElement)) === null || _a$1 === void 0 ? void 0 : _a$1.endTag)) p._setEndLocation(bodyElement, token);
- }
- } else tokenAfterBody(p, token);
-}
-function tokenAfterBody(p, token) {
- p.insertionMode = InsertionMode.IN_BODY;
- modeInBody(p, token);
-}
-function startTagInFrameset(p, token) {
- switch (token.tagID) {
- case TAG_ID.HTML:
- startTagInBody(p, token);
- break;
- case TAG_ID.FRAMESET:
- p._insertElement(token, NS.HTML);
- break;
- case TAG_ID.FRAME:
- p._appendElement(token, NS.HTML);
- token.ackSelfClosing = true;
- break;
- case TAG_ID.NOFRAMES:
- startTagInHead(p, token);
- break;
- default:
- }
-}
-function endTagInFrameset(p, token) {
- if (token.tagID === TAG_ID.FRAMESET && !p.openElements.isRootHtmlElementCurrent()) {
- p.openElements.pop();
- if (!p.fragmentContext && p.openElements.currentTagId !== TAG_ID.FRAMESET) p.insertionMode = InsertionMode.AFTER_FRAMESET;
- }
-}
-function startTagAfterFrameset(p, token) {
- switch (token.tagID) {
- case TAG_ID.HTML:
- startTagInBody(p, token);
- break;
- case TAG_ID.NOFRAMES:
- startTagInHead(p, token);
- break;
- default:
- }
-}
-function endTagAfterFrameset(p, token) {
- if (token.tagID === TAG_ID.HTML) p.insertionMode = InsertionMode.AFTER_AFTER_FRAMESET;
-}
-function startTagAfterAfterBody(p, token) {
- if (token.tagID === TAG_ID.HTML) startTagInBody(p, token);
- else tokenAfterAfterBody(p, token);
-}
-function tokenAfterAfterBody(p, token) {
- p.insertionMode = InsertionMode.IN_BODY;
- modeInBody(p, token);
-}
-function startTagAfterAfterFrameset(p, token) {
- switch (token.tagID) {
- case TAG_ID.HTML:
- startTagInBody(p, token);
- break;
- case TAG_ID.NOFRAMES:
- startTagInHead(p, token);
- break;
- default:
- }
-}
-function nullCharacterInForeignContent(p, token) {
- token.chars = REPLACEMENT_CHARACTER;
- p._insertCharacters(token);
-}
-function characterInForeignContent(p, token) {
- p._insertCharacters(token);
- p.framesetOk = false;
-}
-function popUntilHtmlOrIntegrationPoint(p) {
- while (p.treeAdapter.getNamespaceURI(p.openElements.current) !== NS.HTML && p.openElements.currentTagId !== void 0 && !p._isIntegrationPoint(p.openElements.currentTagId, p.openElements.current)) p.openElements.pop();
-}
-function startTagInForeignContent(p, token) {
- if (causesExit(token)) {
- popUntilHtmlOrIntegrationPoint(p);
- p._startTagOutsideForeignContent(token);
- } else {
- const current = p._getAdjustedCurrentElement();
- const currentNs = p.treeAdapter.getNamespaceURI(current);
- if (currentNs === NS.MATHML) adjustTokenMathMLAttrs(token);
- else if (currentNs === NS.SVG) {
- adjustTokenSVGTagName(token);
- adjustTokenSVGAttrs(token);
- }
- adjustTokenXMLAttrs(token);
- if (token.selfClosing) p._appendElement(token, currentNs);
- else p._insertElement(token, currentNs);
- token.ackSelfClosing = true;
- }
-}
-function endTagInForeignContent(p, token) {
- if (token.tagID === TAG_ID.P || token.tagID === TAG_ID.BR) {
- popUntilHtmlOrIntegrationPoint(p);
- p._endTagOutsideForeignContent(token);
- return;
- }
- for (let i = p.openElements.stackTop; i > 0; i--) {
- const element = p.openElements.items[i];
- if (p.treeAdapter.getNamespaceURI(element) === NS.HTML) {
- p._endTagOutsideForeignContent(token);
- break;
- }
- const tagName = p.treeAdapter.getTagName(element);
- if (tagName.toLowerCase() === token.tagName) {
- token.tagName = tagName;
- p.openElements.shortenToLength(i);
- break;
- }
- }
-}
-
-//#endregion
-//#region ../../node_modules/.pnpm/parse5@8.0.0/node_modules/parse5/dist/index.js
-/**
-* Parses an HTML string.
-*
-* @param html Input HTML string.
-* @param options Parsing options.
-* @returns Document
-*
-* @example
-*
-* ```js
-* const parse5 = require('parse5');
-*
-* const document = parse5.parse('<!DOCTYPE html><html><head></head><body>Hi there!</body></html>');
-*
-* console.log(document.childNodes[1].tagName); //> 'html'
-*```
-*/
-function parse(html, options) {
- return Parser.parse(html, options);
-}
-
-//#endregion
-export { parse }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/chunks/lib.js b/vanilla/node_modules/vite/dist/node/chunks/lib.js
deleted file mode 100644
index 406b2ed..0000000
--- a/vanilla/node_modules/vite/dist/node/chunks/lib.js
+++ /dev/null
@@ -1,377 +0,0 @@
-import { t as __commonJSMin } from "./chunk.js";
-
-//#region ../../node_modules/.pnpm/postcss-value-parser@4.2.0/node_modules/postcss-value-parser/lib/parse.js
-var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- var openParentheses = "(".charCodeAt(0);
- var closeParentheses = ")".charCodeAt(0);
- var singleQuote = "'".charCodeAt(0);
- var doubleQuote = "\"".charCodeAt(0);
- var backslash = "\\".charCodeAt(0);
- var slash = "/".charCodeAt(0);
- var comma = ",".charCodeAt(0);
- var colon = ":".charCodeAt(0);
- var star = "*".charCodeAt(0);
- var uLower = "u".charCodeAt(0);
- var uUpper = "U".charCodeAt(0);
- var plus$1 = "+".charCodeAt(0);
- var isUnicodeRange = /^[a-f0-9?-]+$/i;
- module.exports = function(input) {
- var tokens = [];
- var value = input;
- var next, quote, prev, token, escape, escapePos, whitespacePos, parenthesesOpenPos;
- var pos = 0;
- var code = value.charCodeAt(pos);
- var max = value.length;
- var stack = [{ nodes: tokens }];
- var balanced = 0;
- var parent;
- var name = "";
- var before = "";
- var after = "";
- while (pos < max) if (code <= 32) {
- next = pos;
- do {
- next += 1;
- code = value.charCodeAt(next);
- } while (code <= 32);
- token = value.slice(pos, next);
- prev = tokens[tokens.length - 1];
- if (code === closeParentheses && balanced) after = token;
- else if (prev && prev.type === "div") {
- prev.after = token;
- prev.sourceEndIndex += token.length;
- } else if (code === comma || code === colon || code === slash && value.charCodeAt(next + 1) !== star && (!parent || parent && parent.type === "function" && parent.value !== "calc")) before = token;
- else tokens.push({
- type: "space",
- sourceIndex: pos,
- sourceEndIndex: next,
- value: token
- });
- pos = next;
- } else if (code === singleQuote || code === doubleQuote) {
- next = pos;
- quote = code === singleQuote ? "'" : "\"";
- token = {
- type: "string",
- sourceIndex: pos,
- quote
- };
- do {
- escape = false;
- next = value.indexOf(quote, next + 1);
- if (~next) {
- escapePos = next;
- while (value.charCodeAt(escapePos - 1) === backslash) {
- escapePos -= 1;
- escape = !escape;
- }
- } else {
- value += quote;
- next = value.length - 1;
- token.unclosed = true;
- }
- } while (escape);
- token.value = value.slice(pos + 1, next);
- token.sourceEndIndex = token.unclosed ? next : next + 1;
- tokens.push(token);
- pos = next + 1;
- code = value.charCodeAt(pos);
- } else if (code === slash && value.charCodeAt(pos + 1) === star) {
- next = value.indexOf("*/", pos);
- token = {
- type: "comment",
- sourceIndex: pos,
- sourceEndIndex: next + 2
- };
- if (next === -1) {
- token.unclosed = true;
- next = value.length;
- token.sourceEndIndex = next;
- }
- token.value = value.slice(pos + 2, next);
- tokens.push(token);
- pos = next + 2;
- code = value.charCodeAt(pos);
- } else if ((code === slash || code === star) && parent && parent.type === "function" && parent.value === "calc") {
- token = value[pos];
- tokens.push({
- type: "word",
- sourceIndex: pos - before.length,
- sourceEndIndex: pos + token.length,
- value: token
- });
- pos += 1;
- code = value.charCodeAt(pos);
- } else if (code === slash || code === comma || code === colon) {
- token = value[pos];
- tokens.push({
- type: "div",
- sourceIndex: pos - before.length,
- sourceEndIndex: pos + token.length,
- value: token,
- before,
- after: ""
- });
- before = "";
- pos += 1;
- code = value.charCodeAt(pos);
- } else if (openParentheses === code) {
- next = pos;
- do {
- next += 1;
- code = value.charCodeAt(next);
- } while (code <= 32);
- parenthesesOpenPos = pos;
- token = {
- type: "function",
- sourceIndex: pos - name.length,
- value: name,
- before: value.slice(parenthesesOpenPos + 1, next)
- };
- pos = next;
- if (name === "url" && code !== singleQuote && code !== doubleQuote) {
- next -= 1;
- do {
- escape = false;
- next = value.indexOf(")", next + 1);
- if (~next) {
- escapePos = next;
- while (value.charCodeAt(escapePos - 1) === backslash) {
- escapePos -= 1;
- escape = !escape;
- }
- } else {
- value += ")";
- next = value.length - 1;
- token.unclosed = true;
- }
- } while (escape);
- whitespacePos = next;
- do {
- whitespacePos -= 1;
- code = value.charCodeAt(whitespacePos);
- } while (code <= 32);
- if (parenthesesOpenPos < whitespacePos) {
- if (pos !== whitespacePos + 1) token.nodes = [{
- type: "word",
- sourceIndex: pos,
- sourceEndIndex: whitespacePos + 1,
- value: value.slice(pos, whitespacePos + 1)
- }];
- else token.nodes = [];
- if (token.unclosed && whitespacePos + 1 !== next) {
- token.after = "";
- token.nodes.push({
- type: "space",
- sourceIndex: whitespacePos + 1,
- sourceEndIndex: next,
- value: value.slice(whitespacePos + 1, next)
- });
- } else {
- token.after = value.slice(whitespacePos + 1, next);
- token.sourceEndIndex = next;
- }
- } else {
- token.after = "";
- token.nodes = [];
- }
- pos = next + 1;
- token.sourceEndIndex = token.unclosed ? next : pos;
- code = value.charCodeAt(pos);
- tokens.push(token);
- } else {
- balanced += 1;
- token.after = "";
- token.sourceEndIndex = pos + 1;
- tokens.push(token);
- stack.push(token);
- tokens = token.nodes = [];
- parent = token;
- }
- name = "";
- } else if (closeParentheses === code && balanced) {
- pos += 1;
- code = value.charCodeAt(pos);
- parent.after = after;
- parent.sourceEndIndex += after.length;
- after = "";
- balanced -= 1;
- stack[stack.length - 1].sourceEndIndex = pos;
- stack.pop();
- parent = stack[balanced];
- tokens = parent.nodes;
- } else {
- next = pos;
- do {
- if (code === backslash) next += 1;
- next += 1;
- code = value.charCodeAt(next);
- } while (next < max && !(code <= 32 || code === singleQuote || code === doubleQuote || code === comma || code === colon || code === slash || code === openParentheses || code === star && parent && parent.type === "function" && parent.value === "calc" || code === slash && parent.type === "function" && parent.value === "calc" || code === closeParentheses && balanced));
- token = value.slice(pos, next);
- if (openParentheses === code) name = token;
- else if ((uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) && plus$1 === token.charCodeAt(1) && isUnicodeRange.test(token.slice(2))) tokens.push({
- type: "unicode-range",
- sourceIndex: pos,
- sourceEndIndex: next,
- value: token
- });
- else tokens.push({
- type: "word",
- sourceIndex: pos,
- sourceEndIndex: next,
- value: token
- });
- pos = next;
- }
- for (pos = stack.length - 1; pos; pos -= 1) {
- stack[pos].unclosed = true;
- stack[pos].sourceEndIndex = value.length;
- }
- return stack[0].nodes;
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-value-parser@4.2.0/node_modules/postcss-value-parser/lib/walk.js
-var require_walk = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = function walk$1(nodes, cb, bubble) {
- var i, max, node, result;
- for (i = 0, max = nodes.length; i < max; i += 1) {
- node = nodes[i];
- if (!bubble) result = cb(node, i, nodes);
- if (result !== false && node.type === "function" && Array.isArray(node.nodes)) walk$1(node.nodes, cb, bubble);
- if (bubble) cb(node, i, nodes);
- }
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-value-parser@4.2.0/node_modules/postcss-value-parser/lib/stringify.js
-var require_stringify = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- function stringifyNode(node, custom) {
- var type = node.type;
- var value = node.value;
- var buf;
- var customResult;
- if (custom && (customResult = custom(node)) !== void 0) return customResult;
- else if (type === "word" || type === "space") return value;
- else if (type === "string") {
- buf = node.quote || "";
- return buf + value + (node.unclosed ? "" : buf);
- } else if (type === "comment") return "/*" + value + (node.unclosed ? "" : "*/");
- else if (type === "div") return (node.before || "") + value + (node.after || "");
- else if (Array.isArray(node.nodes)) {
- buf = stringify$1(node.nodes, custom);
- if (type !== "function") return buf;
- return value + "(" + (node.before || "") + buf + (node.after || "") + (node.unclosed ? "" : ")");
- }
- return value;
- }
- function stringify$1(nodes, custom) {
- var result, i;
- if (Array.isArray(nodes)) {
- result = "";
- for (i = nodes.length - 1; ~i; i -= 1) result = stringifyNode(nodes[i], custom) + result;
- return result;
- }
- return stringifyNode(nodes, custom);
- }
- module.exports = stringify$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-value-parser@4.2.0/node_modules/postcss-value-parser/lib/unit.js
-var require_unit = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- var minus = "-".charCodeAt(0);
- var plus = "+".charCodeAt(0);
- var dot = ".".charCodeAt(0);
- var exp = "e".charCodeAt(0);
- var EXP = "E".charCodeAt(0);
- function likeNumber(value) {
- var code = value.charCodeAt(0);
- var nextCode;
- if (code === plus || code === minus) {
- nextCode = value.charCodeAt(1);
- if (nextCode >= 48 && nextCode <= 57) return true;
- var nextNextCode = value.charCodeAt(2);
- if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) return true;
- return false;
- }
- if (code === dot) {
- nextCode = value.charCodeAt(1);
- if (nextCode >= 48 && nextCode <= 57) return true;
- return false;
- }
- if (code >= 48 && code <= 57) return true;
- return false;
- }
- module.exports = function(value) {
- var pos = 0;
- var length = value.length;
- var code;
- var nextCode;
- var nextNextCode;
- if (length === 0 || !likeNumber(value)) return false;
- code = value.charCodeAt(pos);
- if (code === plus || code === minus) pos++;
- while (pos < length) {
- code = value.charCodeAt(pos);
- if (code < 48 || code > 57) break;
- pos += 1;
- }
- code = value.charCodeAt(pos);
- nextCode = value.charCodeAt(pos + 1);
- if (code === dot && nextCode >= 48 && nextCode <= 57) {
- pos += 2;
- while (pos < length) {
- code = value.charCodeAt(pos);
- if (code < 48 || code > 57) break;
- pos += 1;
- }
- }
- code = value.charCodeAt(pos);
- nextCode = value.charCodeAt(pos + 1);
- nextNextCode = value.charCodeAt(pos + 2);
- if ((code === exp || code === EXP) && (nextCode >= 48 && nextCode <= 57 || (nextCode === plus || nextCode === minus) && nextNextCode >= 48 && nextNextCode <= 57)) {
- pos += nextCode === plus || nextCode === minus ? 3 : 2;
- while (pos < length) {
- code = value.charCodeAt(pos);
- if (code < 48 || code > 57) break;
- pos += 1;
- }
- }
- return {
- number: value.slice(0, pos),
- unit: value.slice(pos)
- };
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-value-parser@4.2.0/node_modules/postcss-value-parser/lib/index.js
-var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- var parse = require_parse();
- var walk = require_walk();
- var stringify = require_stringify();
- function ValueParser(value) {
- if (this instanceof ValueParser) {
- this.nodes = parse(value);
- return this;
- }
- return new ValueParser(value);
- }
- ValueParser.prototype.toString = function() {
- return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
- };
- ValueParser.prototype.walk = function(cb, bubble) {
- walk(this.nodes, cb, bubble);
- return this;
- };
- ValueParser.unit = require_unit();
- ValueParser.walk = walk;
- ValueParser.stringify = stringify;
- module.exports = ValueParser;
-}));
-
-//#endregion
-export { require_lib as t }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/chunks/logger.js b/vanilla/node_modules/vite/dist/node/chunks/logger.js
deleted file mode 100644
index b11e8df..0000000
--- a/vanilla/node_modules/vite/dist/node/chunks/logger.js
+++ /dev/null
@@ -1,329 +0,0 @@
-import { s as __toESM, t as __commonJSMin } from "./chunk.js";
-import { readFileSync } from "node:fs";
-import path, { resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-import readline from "node:readline";
-
-//#region ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
-var require_picocolors = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- let p = process || {}, argv = p.argv || [], env = p.env || {};
- let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
- let formatter = (open, close, replace = open) => (input) => {
- let string = "" + input, index = string.indexOf(close, open.length);
- return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
- };
- let replaceClose = (string, close, replace, index) => {
- let result = "", cursor = 0;
- do {
- result += string.substring(cursor, index) + replace;
- cursor = index + close.length;
- index = string.indexOf(close, cursor);
- } while (~index);
- return result + string.substring(cursor);
- };
- let createColors = (enabled = isColorSupported) => {
- let f = enabled ? formatter : () => String;
- return {
- isColorSupported: enabled,
- reset: f("\x1B[0m", "\x1B[0m"),
- bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
- dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
- italic: f("\x1B[3m", "\x1B[23m"),
- underline: f("\x1B[4m", "\x1B[24m"),
- inverse: f("\x1B[7m", "\x1B[27m"),
- hidden: f("\x1B[8m", "\x1B[28m"),
- strikethrough: f("\x1B[9m", "\x1B[29m"),
- black: f("\x1B[30m", "\x1B[39m"),
- red: f("\x1B[31m", "\x1B[39m"),
- green: f("\x1B[32m", "\x1B[39m"),
- yellow: f("\x1B[33m", "\x1B[39m"),
- blue: f("\x1B[34m", "\x1B[39m"),
- magenta: f("\x1B[35m", "\x1B[39m"),
- cyan: f("\x1B[36m", "\x1B[39m"),
- white: f("\x1B[37m", "\x1B[39m"),
- gray: f("\x1B[90m", "\x1B[39m"),
- bgBlack: f("\x1B[40m", "\x1B[49m"),
- bgRed: f("\x1B[41m", "\x1B[49m"),
- bgGreen: f("\x1B[42m", "\x1B[49m"),
- bgYellow: f("\x1B[43m", "\x1B[49m"),
- bgBlue: f("\x1B[44m", "\x1B[49m"),
- bgMagenta: f("\x1B[45m", "\x1B[49m"),
- bgCyan: f("\x1B[46m", "\x1B[49m"),
- bgWhite: f("\x1B[47m", "\x1B[49m"),
- blackBright: f("\x1B[90m", "\x1B[39m"),
- redBright: f("\x1B[91m", "\x1B[39m"),
- greenBright: f("\x1B[92m", "\x1B[39m"),
- yellowBright: f("\x1B[93m", "\x1B[39m"),
- blueBright: f("\x1B[94m", "\x1B[39m"),
- magentaBright: f("\x1B[95m", "\x1B[39m"),
- cyanBright: f("\x1B[96m", "\x1B[39m"),
- whiteBright: f("\x1B[97m", "\x1B[39m"),
- bgBlackBright: f("\x1B[100m", "\x1B[49m"),
- bgRedBright: f("\x1B[101m", "\x1B[49m"),
- bgGreenBright: f("\x1B[102m", "\x1B[49m"),
- bgYellowBright: f("\x1B[103m", "\x1B[49m"),
- bgBlueBright: f("\x1B[104m", "\x1B[49m"),
- bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
- bgCyanBright: f("\x1B[106m", "\x1B[49m"),
- bgWhiteBright: f("\x1B[107m", "\x1B[49m")
- };
- };
- module.exports = createColors();
- module.exports.createColors = createColors;
-}));
-
-//#endregion
-//#region src/node/constants.ts
-const { version } = JSON.parse(readFileSync(new URL("../../package.json", new URL("../../../src/node/constants.ts", import.meta.url))).toString());
-const ROLLUP_HOOKS = [
- "options",
- "buildStart",
- "buildEnd",
- "renderStart",
- "renderError",
- "renderChunk",
- "writeBundle",
- "generateBundle",
- "banner",
- "footer",
- "augmentChunkHash",
- "outputOptions",
- "renderDynamicImport",
- "resolveFileUrl",
- "resolveImportMeta",
- "intro",
- "outro",
- "closeBundle",
- "closeWatcher",
- "load",
- "moduleParsed",
- "watchChange",
- "resolveDynamicImport",
- "resolveId",
- "shouldTransformCachedModule",
- "transform",
- "onLog"
-];
-const VERSION = version;
-const DEFAULT_MAIN_FIELDS = [
- "browser",
- "module",
- "jsnext:main",
- "jsnext"
-];
-const DEFAULT_CLIENT_MAIN_FIELDS = Object.freeze(DEFAULT_MAIN_FIELDS);
-const DEFAULT_SERVER_MAIN_FIELDS = Object.freeze(DEFAULT_MAIN_FIELDS.filter((f) => f !== "browser"));
-/**
-* A special condition that would be replaced with production or development
-* depending on NODE_ENV env variable
-*/
-const DEV_PROD_CONDITION = `development|production`;
-const DEFAULT_CONDITIONS = [
- "module",
- "browser",
- "node",
- DEV_PROD_CONDITION
-];
-const DEFAULT_CLIENT_CONDITIONS = Object.freeze(DEFAULT_CONDITIONS.filter((c) => c !== "node"));
-const DEFAULT_SERVER_CONDITIONS = Object.freeze(DEFAULT_CONDITIONS.filter((c) => c !== "browser"));
-const DEFAULT_EXTERNAL_CONDITIONS = Object.freeze(["node", "module-sync"]);
-const DEFAULT_EXTENSIONS = [
- ".mjs",
- ".js",
- ".mts",
- ".ts",
- ".jsx",
- ".tsx",
- ".json"
-];
-/**
-* The browser versions that are included in the Baseline Widely Available on 2025-05-01.
-*
-* This value would be bumped on each major release of Vite.
-*
-* The value is generated by `pnpm generate-target` script.
-*/
-const ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET = [
- "chrome107",
- "edge107",
- "firefox104",
- "safari16"
-];
-const DEFAULT_CONFIG_FILES = [
- "vite.config.js",
- "vite.config.mjs",
- "vite.config.ts",
- "vite.config.cjs",
- "vite.config.mts",
- "vite.config.cts"
-];
-const JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/;
-const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
-const OPTIMIZABLE_ENTRY_RE = /\.[cm]?[jt]s$/;
-const SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/;
-/**
-* Prefix for resolved fs paths, since windows paths may not be valid as URLs.
-*/
-const FS_PREFIX = `/@fs/`;
-const CLIENT_PUBLIC_PATH = `/@vite/client`;
-const ENV_PUBLIC_PATH = `/@vite/env`;
-const VITE_PACKAGE_DIR = resolve(fileURLToPath(new URL("../../../src/node/constants.ts", import.meta.url)), "../../..");
-const CLIENT_ENTRY = resolve(VITE_PACKAGE_DIR, "dist/client/client.mjs");
-const ENV_ENTRY = resolve(VITE_PACKAGE_DIR, "dist/client/env.mjs");
-const CLIENT_DIR = path.dirname(CLIENT_ENTRY);
-const KNOWN_ASSET_TYPES = [
- "apng",
- "bmp",
- "png",
- "jpe?g",
- "jfif",
- "pjpeg",
- "pjp",
- "gif",
- "svg",
- "ico",
- "webp",
- "avif",
- "cur",
- "jxl",
- "mp4",
- "webm",
- "ogg",
- "mp3",
- "wav",
- "flac",
- "aac",
- "opus",
- "mov",
- "m4a",
- "vtt",
- "woff2?",
- "eot",
- "ttf",
- "otf",
- "webmanifest",
- "pdf",
- "txt"
-];
-const DEFAULT_ASSETS_RE = new RegExp(`\\.(` + KNOWN_ASSET_TYPES.join("|") + `)(\\?.*)?$`, "i");
-const DEP_VERSION_RE = /[?&](v=[\w.-]+)\b/;
-const loopbackHosts = new Set([
- "localhost",
- "127.0.0.1",
- "::1",
- "0000:0000:0000:0000:0000:0000:0000:0001"
-]);
-const wildcardHosts = new Set([
- "0.0.0.0",
- "::",
- "0000:0000:0000:0000:0000:0000:0000:0000"
-]);
-const DEFAULT_DEV_PORT = 5173;
-const DEFAULT_PREVIEW_PORT = 4173;
-const DEFAULT_ASSETS_INLINE_LIMIT = 4096;
-const defaultAllowedOrigins = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/;
-const METADATA_FILENAME = "_metadata.json";
-const ERR_OPTIMIZE_DEPS_PROCESSING_ERROR = "ERR_OPTIMIZE_DEPS_PROCESSING_ERROR";
-const ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR = "ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR";
-
-//#endregion
-//#region src/node/logger.ts
-var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-const LogLevels = {
- silent: 0,
- error: 1,
- warn: 2,
- info: 3
-};
-let lastType;
-let lastMsg;
-let sameCount = 0;
-function clearScreen() {
- const repeatCount = process.stdout.rows - 2;
- const blank = repeatCount > 0 ? "\n".repeat(repeatCount) : "";
- console.log(blank);
- readline.cursorTo(process.stdout, 0, 0);
- readline.clearScreenDown(process.stdout);
-}
-let timeFormatter;
-function getTimeFormatter() {
- timeFormatter ??= new Intl.DateTimeFormat(void 0, {
- hour: "numeric",
- minute: "numeric",
- second: "numeric"
- });
- return timeFormatter;
-}
-function createLogger(level = "info", options = {}) {
- if (options.customLogger) return options.customLogger;
- const loggedErrors = /* @__PURE__ */ new WeakSet();
- const { prefix = "[vite]", allowClearScreen = true, console: console$1 = globalThis.console } = options;
- const thresh = LogLevels[level];
- const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI;
- const clear = canClearScreen ? clearScreen : () => {};
- function format(type, msg, options$1 = {}) {
- if (options$1.timestamp) {
- let tag = "";
- if (type === "info") tag = import_picocolors.default.cyan(import_picocolors.default.bold(prefix));
- else if (type === "warn") tag = import_picocolors.default.yellow(import_picocolors.default.bold(prefix));
- else tag = import_picocolors.default.red(import_picocolors.default.bold(prefix));
- const environment = options$1.environment ? options$1.environment + " " : "";
- return `${import_picocolors.default.dim(getTimeFormatter().format(/* @__PURE__ */ new Date()))} ${tag} ${environment}${msg}`;
- } else return msg;
- }
- function output(type, msg, options$1 = {}) {
- if (thresh >= LogLevels[type]) {
- const method = type === "info" ? "log" : type;
- if (options$1.error) loggedErrors.add(options$1.error);
- if (canClearScreen) if (type === lastType && msg === lastMsg) {
- sameCount++;
- clear();
- console$1[method](format(type, msg, options$1), import_picocolors.default.yellow(`(x${sameCount + 1})`));
- } else {
- sameCount = 0;
- lastMsg = msg;
- lastType = type;
- if (options$1.clear) clear();
- console$1[method](format(type, msg, options$1));
- }
- else console$1[method](format(type, msg, options$1));
- }
- }
- const warnedMessages = /* @__PURE__ */ new Set();
- const logger = {
- hasWarned: false,
- info(msg, opts) {
- output("info", msg, opts);
- },
- warn(msg, opts) {
- logger.hasWarned = true;
- output("warn", msg, opts);
- },
- warnOnce(msg, opts) {
- if (warnedMessages.has(msg)) return;
- logger.hasWarned = true;
- output("warn", msg, opts);
- warnedMessages.add(msg);
- },
- error(msg, opts) {
- logger.hasWarned = true;
- output("error", msg, opts);
- },
- clearScreen(type) {
- if (thresh >= LogLevels[type]) clear();
- },
- hasErrorLogged(error) {
- return loggedErrors.has(error);
- }
- };
- return logger;
-}
-function printServerUrls(urls, optionsHost, info) {
- const colorUrl = (url) => import_picocolors.default.cyan(url.replace(/:(\d+)\//, (_, port) => `:${import_picocolors.default.bold(port)}/`));
- for (const url of urls.local) info(` ${import_picocolors.default.green("➜")} ${import_picocolors.default.bold("Local")}: ${colorUrl(url)}`);
- for (const url of urls.network) info(` ${import_picocolors.default.green("➜")} ${import_picocolors.default.bold("Network")}: ${colorUrl(url)}`);
- if (urls.network.length === 0 && optionsHost === void 0) info(import_picocolors.default.dim(` ${import_picocolors.default.green("➜")} ${import_picocolors.default.bold("Network")}: use `) + import_picocolors.default.bold("--host") + import_picocolors.default.dim(" to expose"));
-}
-
-//#endregion
-export { OPTIMIZABLE_ENTRY_RE as A, ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR as C, JS_TYPES_RE as D, FS_PREFIX as E, defaultAllowedOrigins as F, loopbackHosts as I, wildcardHosts as L, SPECIAL_QUERY_RE as M, VERSION as N, KNOWN_ASSET_TYPES as O, VITE_PACKAGE_DIR as P, require_picocolors as R, ENV_PUBLIC_PATH as S, ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET as T, DEFAULT_SERVER_CONDITIONS as _, CLIENT_ENTRY as a, DEV_PROD_CONDITION as b, DEFAULT_ASSETS_INLINE_LIMIT as c, DEFAULT_CLIENT_MAIN_FIELDS as d, DEFAULT_CONFIG_FILES as f, DEFAULT_PREVIEW_PORT as g, DEFAULT_EXTERNAL_CONDITIONS as h, CLIENT_DIR as i, ROLLUP_HOOKS as j, METADATA_FILENAME as k, DEFAULT_ASSETS_RE as l, DEFAULT_EXTENSIONS as m, createLogger as n, CLIENT_PUBLIC_PATH as o, DEFAULT_DEV_PORT as p, printServerUrls as r, CSS_LANGS_RE as s, LogLevels as t, DEFAULT_CLIENT_CONDITIONS as u, DEFAULT_SERVER_MAIN_FIELDS as v, ERR_OPTIMIZE_DEPS_PROCESSING_ERROR as w, ENV_ENTRY as x, DEP_VERSION_RE as y }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/chunks/moduleRunnerTransport.d.ts b/vanilla/node_modules/vite/dist/node/chunks/moduleRunnerTransport.d.ts
deleted file mode 100644
index 67b5593..0000000
--- a/vanilla/node_modules/vite/dist/node/chunks/moduleRunnerTransport.d.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-import { HotPayload } from "#types/hmrPayload";
-
-//#region src/shared/invokeMethods.d.ts
-interface FetchFunctionOptions {
- cached?: boolean;
- startOffset?: number;
-}
-type FetchResult = CachedFetchResult | ExternalFetchResult | ViteFetchResult;
-interface CachedFetchResult {
- /**
- * If module cached in the runner, we can just confirm
- * it wasn't invalidated on the server side.
- */
- cache: true;
-}
-interface ExternalFetchResult {
- /**
- * The path to the externalized module starting with file://,
- * by default this will be imported via a dynamic "import"
- * instead of being transformed by vite and loaded with vite runner
- */
- externalize: string;
- /**
- * Type of the module. Will be used to determine if import statement is correct.
- * For example, if Vite needs to throw an error if variable is not actually exported
- */
- type: "module" | "commonjs" | "builtin" | "network";
-}
-interface ViteFetchResult {
- /**
- * Code that will be evaluated by vite runner
- * by default this will be wrapped in an async function
- */
- code: string;
- /**
- * File path of the module on disk.
- * This will be resolved as import.meta.url/filename
- * Will be equal to `null` for virtual modules
- */
- file: string | null;
- /**
- * Module ID in the server module graph.
- */
- id: string;
- /**
- * Module URL used in the import.
- */
- url: string;
- /**
- * Invalidate module on the client side.
- */
- invalidate: boolean;
-}
-type InvokeMethods = {
- fetchModule: (id: string, importer?: string, options?: FetchFunctionOptions) => Promise<FetchResult>;
- getBuiltins: () => Promise<Array<{
- type: "string";
- value: string;
- } | {
- type: "RegExp";
- source: string;
- flags: string;
- }>>;
-};
-//#endregion
-//#region src/shared/moduleRunnerTransport.d.ts
-type ModuleRunnerTransportHandlers = {
- onMessage: (data: HotPayload) => void;
- onDisconnection: () => void;
-};
-/**
-* "send and connect" or "invoke" must be implemented
-*/
-interface ModuleRunnerTransport {
- connect?(handlers: ModuleRunnerTransportHandlers): Promise<void> | void;
- disconnect?(): Promise<void> | void;
- send?(data: HotPayload): Promise<void> | void;
- invoke?(data: HotPayload): Promise<{
- result: any;
- } | {
- error: any;
- }>;
- timeout?: number;
-}
-interface NormalizedModuleRunnerTransport {
- connect?(onMessage?: (data: HotPayload) => void): Promise<void> | void;
- disconnect?(): Promise<void> | void;
- send(data: HotPayload): Promise<void>;
- invoke<T extends keyof InvokeMethods>(name: T, data: Parameters<InvokeMethods[T]>): Promise<ReturnType<Awaited<InvokeMethods[T]>>>;
-}
-declare const createWebSocketModuleRunnerTransport: (options: {
- createConnection: () => WebSocket;
- pingInterval?: number;
-}) => Required<Pick<ModuleRunnerTransport, "connect" | "disconnect" | "send">>;
-//#endregion
-export { ExternalFetchResult as a, ViteFetchResult as c, createWebSocketModuleRunnerTransport as i, ModuleRunnerTransportHandlers as n, FetchFunctionOptions as o, NormalizedModuleRunnerTransport as r, FetchResult as s, ModuleRunnerTransport as t }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/chunks/optimizer.js b/vanilla/node_modules/vite/dist/node/chunks/optimizer.js
deleted file mode 100644
index 5bdc9e2..0000000
--- a/vanilla/node_modules/vite/dist/node/chunks/optimizer.js
+++ /dev/null
@@ -1,4 +0,0 @@
-import "./logger.js";
-import { $ as runOptimizeDeps, B as depsLogString, F as addOptimizedDepInfo, G as initDepsOptimizerMetadata, H as extractExportsData, I as cleanupDepsCacheStaleDirs, J as optimizeDeps, K as isDepOptimizationDisabled, L as createIsOptimizedDepFile, P as addManuallyIncludedOptimizeDeps, Q as optimizedDepNeedsInterop, R as createIsOptimizedDepUrl, U as getDepsCacheDir, V as discoverProjectDependencies, W as getOptimizedDepPath, X as optimizedDepInfoFromFile, Y as optimizeExplicitEnvironmentDeps, Z as optimizedDepInfoFromId, et as toDiscoveredDependencies, q as loadCachedDepOptimizationMetadata, z as depsFromOptimizedDepInfo } from "./config.js";
-
-export { optimizeDeps }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/chunks/postcss-import.js b/vanilla/node_modules/vite/dist/node/chunks/postcss-import.js
deleted file mode 100644
index 62e9825..0000000
--- a/vanilla/node_modules/vite/dist/node/chunks/postcss-import.js
+++ /dev/null
@@ -1,479 +0,0 @@
-import { i as __require, t as __commonJSMin } from "./chunk.js";
-import { t as require_lib } from "./lib.js";
-
-//#region ../../node_modules/.pnpm/postcss-import@16.1.1_postcss@8.5.6/node_modules/postcss-import/lib/format-import-prelude.js
-var require_format_import_prelude = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = function formatImportPrelude$2(layer, media, supports) {
- const parts = [];
- if (typeof layer !== "undefined") {
- let layerParams = "layer";
- if (layer) layerParams = `layer(${layer})`;
- parts.push(layerParams);
- }
- if (typeof supports !== "undefined") parts.push(`supports(${supports})`);
- if (typeof media !== "undefined") parts.push(media);
- return parts.join(" ");
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-import@16.1.1_postcss@8.5.6/node_modules/postcss-import/lib/base64-encoded-import.js
-var require_base64_encoded_import = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const formatImportPrelude$1 = require_format_import_prelude();
- module.exports = function base64EncodedConditionalImport$1(prelude, conditions) {
- if (!conditions?.length) return prelude;
- conditions.reverse();
- const first = conditions.pop();
- let params = `${prelude} ${formatImportPrelude$1(first.layer, first.media, first.supports)}`;
- for (const condition of conditions) params = `'data:text/css;base64,${Buffer.from(`@import ${params}`).toString("base64")}' ${formatImportPrelude$1(condition.layer, condition.media, condition.supports)}`;
- return params;
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-import@16.1.1_postcss@8.5.6/node_modules/postcss-import/lib/apply-conditions.js
-var require_apply_conditions = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const base64EncodedConditionalImport = require_base64_encoded_import();
- module.exports = function applyConditions$1(bundle, atRule) {
- const firstImportStatementIndex = bundle.findIndex((stmt) => stmt.type === "import");
- const lastImportStatementIndex = bundle.findLastIndex((stmt) => stmt.type === "import");
- bundle.forEach((stmt, index) => {
- if (stmt.type === "charset" || stmt.type === "warning") return;
- if (stmt.type === "layer" && (index < lastImportStatementIndex && stmt.conditions?.length || index > firstImportStatementIndex && index < lastImportStatementIndex)) {
- stmt.type = "import";
- stmt.node = stmt.node.clone({
- name: "import",
- params: base64EncodedConditionalImport(`'data:text/css;base64,${Buffer.from(stmt.node.toString()).toString("base64")}'`, stmt.conditions)
- });
- return;
- }
- if (!stmt.conditions?.length) return;
- if (stmt.type === "import") {
- stmt.node.params = base64EncodedConditionalImport(stmt.fullUri, stmt.conditions);
- return;
- }
- let nodes;
- let parent;
- if (stmt.type === "layer") {
- nodes = [stmt.node];
- parent = stmt.node.parent;
- } else {
- nodes = stmt.nodes;
- parent = nodes[0].parent;
- }
- const atRules = [];
- for (const condition of stmt.conditions) {
- if (typeof condition.media !== "undefined") {
- const mediaNode = atRule({
- name: "media",
- params: condition.media,
- source: parent.source
- });
- atRules.push(mediaNode);
- }
- if (typeof condition.supports !== "undefined") {
- const supportsNode = atRule({
- name: "supports",
- params: `(${condition.supports})`,
- source: parent.source
- });
- atRules.push(supportsNode);
- }
- if (typeof condition.layer !== "undefined") {
- const layerNode = atRule({
- name: "layer",
- params: condition.layer,
- source: parent.source
- });
- atRules.push(layerNode);
- }
- }
- const outerAtRule = atRules.shift();
- const innerAtRule = atRules.reduce((previous, next) => {
- previous.append(next);
- return next;
- }, outerAtRule);
- parent.insertBefore(nodes[0], outerAtRule);
- nodes.forEach((node) => {
- node.parent = void 0;
- });
- nodes[0].raws.before = nodes[0].raws.before || "\n";
- innerAtRule.append(nodes);
- stmt.type = "nodes";
- stmt.nodes = [outerAtRule];
- delete stmt.node;
- });
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-import@16.1.1_postcss@8.5.6/node_modules/postcss-import/lib/apply-raws.js
-var require_apply_raws = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = function applyRaws$1(bundle) {
- bundle.forEach((stmt, index) => {
- if (index === 0) return;
- if (stmt.parent) {
- const { before } = stmt.parent.node.raws;
- if (stmt.type === "nodes") stmt.nodes[0].raws.before = before;
- else stmt.node.raws.before = before;
- } else if (stmt.type === "nodes") stmt.nodes[0].raws.before = stmt.nodes[0].raws.before || "\n";
- });
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-import@16.1.1_postcss@8.5.6/node_modules/postcss-import/lib/apply-styles.js
-var require_apply_styles = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- module.exports = function applyStyles$1(bundle, styles) {
- styles.nodes = [];
- bundle.forEach((stmt) => {
- if ([
- "charset",
- "import",
- "layer"
- ].includes(stmt.type)) {
- stmt.node.parent = void 0;
- styles.append(stmt.node);
- } else if (stmt.type === "nodes") stmt.nodes.forEach((node) => {
- node.parent = void 0;
- styles.append(node);
- });
- });
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-import@16.1.1_postcss@8.5.6/node_modules/postcss-import/lib/data-url.js
-var require_data_url = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const anyDataURLRegexp = /^data:text\/css(?:;(base64|plain))?,/i;
- const base64DataURLRegexp = /^data:text\/css;base64,/i;
- const plainDataURLRegexp = /^data:text\/css;plain,/i;
- function isValid(url) {
- return anyDataURLRegexp.test(url);
- }
- function contents(url) {
- if (base64DataURLRegexp.test(url)) return Buffer.from(url.slice(21), "base64").toString();
- if (plainDataURLRegexp.test(url)) return decodeURIComponent(url.slice(20));
- return decodeURIComponent(url.slice(14));
- }
- module.exports = {
- isValid,
- contents
- };
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-import@16.1.1_postcss@8.5.6/node_modules/postcss-import/lib/parse-statements.js
-var require_parse_statements = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const valueParser = require_lib();
- const { stringify } = valueParser;
- module.exports = function parseStatements$1(result, styles, conditions, from) {
- const statements = [];
- let nodes = [];
- let encounteredNonImportNodes = false;
- styles.each((node) => {
- let stmt;
- if (node.type === "atrule") {
- if (node.name === "import") stmt = parseImport(result, node, conditions, from);
- else if (node.name === "charset") stmt = parseCharset(result, node, conditions, from);
- else if (node.name === "layer" && !encounteredNonImportNodes && !node.nodes) stmt = parseLayer(result, node, conditions, from);
- } else if (node.type !== "comment") encounteredNonImportNodes = true;
- if (stmt) {
- if (nodes.length) {
- statements.push({
- type: "nodes",
- nodes,
- conditions: [...conditions],
- from
- });
- nodes = [];
- }
- statements.push(stmt);
- } else nodes.push(node);
- });
- if (nodes.length) statements.push({
- type: "nodes",
- nodes,
- conditions: [...conditions],
- from
- });
- return statements;
- };
- function parseCharset(result, atRule, conditions, from) {
- if (atRule.prev()) return result.warn("@charset must precede all other statements", { node: atRule });
- return {
- type: "charset",
- node: atRule,
- conditions: [...conditions],
- from
- };
- }
- function parseImport(result, atRule, conditions, from) {
- let prev = atRule.prev();
- if (prev) do {
- if (prev.type === "comment" || prev.type === "atrule" && prev.name === "import") {
- prev = prev.prev();
- continue;
- }
- break;
- } while (prev);
- if (prev) do {
- if (prev.type === "comment" || prev.type === "atrule" && (prev.name === "charset" || prev.name === "layer" && !prev.nodes)) {
- prev = prev.prev();
- continue;
- }
- return result.warn("@import must precede all other statements (besides @charset or empty @layer)", { node: atRule });
- } while (prev);
- if (atRule.nodes) return result.warn("It looks like you didn't end your @import statement correctly. Child nodes are attached to it.", { node: atRule });
- const params = valueParser(atRule.params).nodes;
- const stmt = {
- type: "import",
- uri: "",
- fullUri: "",
- node: atRule,
- conditions: [...conditions],
- from
- };
- let layer;
- let media;
- let supports;
- for (let i = 0; i < params.length; i++) {
- const node = params[i];
- if (node.type === "space" || node.type === "comment") continue;
- if (node.type === "string") {
- if (stmt.uri) return result.warn(`Multiple url's in '${atRule.toString()}'`, { node: atRule });
- if (!node.value) return result.warn(`Unable to find uri in '${atRule.toString()}'`, { node: atRule });
- stmt.uri = node.value;
- stmt.fullUri = stringify(node);
- continue;
- }
- if (node.type === "function" && /^url$/i.test(node.value)) {
- if (stmt.uri) return result.warn(`Multiple url's in '${atRule.toString()}'`, { node: atRule });
- if (!node.nodes?.[0]?.value) return result.warn(`Unable to find uri in '${atRule.toString()}'`, { node: atRule });
- stmt.uri = node.nodes[0].value;
- stmt.fullUri = stringify(node);
- continue;
- }
- if (!stmt.uri) return result.warn(`Unable to find uri in '${atRule.toString()}'`, { node: atRule });
- if ((node.type === "word" || node.type === "function") && /^layer$/i.test(node.value)) {
- if (typeof layer !== "undefined") return result.warn(`Multiple layers in '${atRule.toString()}'`, { node: atRule });
- if (typeof supports !== "undefined") return result.warn(`layers must be defined before support conditions in '${atRule.toString()}'`, { node: atRule });
- if (node.nodes) layer = stringify(node.nodes);
- else layer = "";
- continue;
- }
- if (node.type === "function" && /^supports$/i.test(node.value)) {
- if (typeof supports !== "undefined") return result.warn(`Multiple support conditions in '${atRule.toString()}'`, { node: atRule });
- supports = stringify(node.nodes);
- continue;
- }
- media = stringify(params.slice(i));
- break;
- }
- if (!stmt.uri) return result.warn(`Unable to find uri in '${atRule.toString()}'`, { node: atRule });
- if (typeof media !== "undefined" || typeof layer !== "undefined" || typeof supports !== "undefined") stmt.conditions.push({
- layer,
- media,
- supports
- });
- return stmt;
- }
- function parseLayer(result, atRule, conditions, from) {
- return {
- type: "layer",
- node: atRule,
- conditions: [...conditions],
- from
- };
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-import@16.1.1_postcss@8.5.6/node_modules/postcss-import/lib/process-content.js
-var require_process_content = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const path$2 = __require("path");
- let sugarss;
- module.exports = function processContent$1(result, content, filename, options, postcss) {
- const { plugins } = options;
- const ext = path$2.extname(filename);
- const parserList = [];
- if (ext === ".sss") {
- if (!sugarss)
- /* c8 ignore next 3 */
- try {
- sugarss = __require("sugarss");
- } catch {}
- if (sugarss) return runPostcss(postcss, content, filename, plugins, [sugarss]);
- }
- if (result.opts.syntax?.parse) parserList.push(result.opts.syntax.parse);
- if (result.opts.parser) parserList.push(result.opts.parser);
- parserList.push(null);
- return runPostcss(postcss, content, filename, plugins, parserList);
- };
- function runPostcss(postcss, content, filename, plugins, parsers, index) {
- if (!index) index = 0;
- return postcss(plugins).process(content, {
- from: filename,
- parser: parsers[index]
- }).catch((err) => {
- index++;
- if (index === parsers.length) throw err;
- return runPostcss(postcss, content, filename, plugins, parsers, index);
- });
- }
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-import@16.1.1_postcss@8.5.6/node_modules/postcss-import/lib/parse-styles.js
-var require_parse_styles = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const path$1 = __require("path");
- const dataURL = require_data_url();
- const parseStatements = require_parse_statements();
- const processContent = require_process_content();
- const resolveId$1 = (id) => id;
- const formatImportPrelude = require_format_import_prelude();
- async function parseStyles$1(result, styles, options, state, conditions, from, postcss) {
- const statements = parseStatements(result, styles, conditions, from);
- for (const stmt of statements) {
- if (stmt.type !== "import" || !isProcessableURL(stmt.uri)) continue;
- if (options.filter && !options.filter(stmt.uri)) continue;
- await resolveImportId(result, stmt, options, state, postcss);
- }
- let charset;
- const beforeBundle = [];
- const bundle = [];
- function handleCharset(stmt) {
- if (!charset) charset = stmt;
- else if (stmt.node.params.toLowerCase() !== charset.node.params.toLowerCase()) throw stmt.node.error(`Incompatible @charset statements:
- ${stmt.node.params} specified in ${stmt.node.source.input.file}
- ${charset.node.params} specified in ${charset.node.source.input.file}`);
- }
- statements.forEach((stmt) => {
- if (stmt.type === "charset") handleCharset(stmt);
- else if (stmt.type === "import") if (stmt.children) stmt.children.forEach((child, index) => {
- if (child.type === "import") beforeBundle.push(child);
- else if (child.type === "layer") beforeBundle.push(child);
- else if (child.type === "charset") handleCharset(child);
- else bundle.push(child);
- if (index === 0) child.parent = stmt;
- });
- else beforeBundle.push(stmt);
- else if (stmt.type === "layer") beforeBundle.push(stmt);
- else if (stmt.type === "nodes") bundle.push(stmt);
- });
- return charset ? [charset, ...beforeBundle.concat(bundle)] : beforeBundle.concat(bundle);
- }
- async function resolveImportId(result, stmt, options, state, postcss) {
- if (dataURL.isValid(stmt.uri)) {
- stmt.children = await loadImportContent(result, stmt, stmt.uri, options, state, postcss);
- return;
- } else if (dataURL.isValid(stmt.from.slice(-1))) throw stmt.node.error(`Unable to import '${stmt.uri}' from a stylesheet that is embedded in a data url`);
- const atRule = stmt.node;
- let sourceFile;
- if (atRule.source?.input?.file) sourceFile = atRule.source.input.file;
- const base = sourceFile ? path$1.dirname(atRule.source.input.file) : options.root;
- const paths = [await options.resolve(stmt.uri, base, options, atRule)].flat();
- const resolved = await Promise.all(paths.map((file) => {
- return !path$1.isAbsolute(file) ? resolveId$1(file, base, options, atRule) : file;
- }));
- resolved.forEach((file) => {
- result.messages.push({
- type: "dependency",
- plugin: "postcss-import",
- file,
- parent: sourceFile
- });
- });
- stmt.children = (await Promise.all(resolved.map((file) => {
- return loadImportContent(result, stmt, file, options, state, postcss);
- }))).flat().filter((x) => !!x);
- }
- async function loadImportContent(result, stmt, filename, options, state, postcss) {
- const atRule = stmt.node;
- const { conditions, from } = stmt;
- const stmtDuplicateCheckKey = conditions.map((condition) => formatImportPrelude(condition.layer, condition.media, condition.supports)).join(":");
- if (options.skipDuplicates) {
- if (state.importedFiles[filename]?.[stmtDuplicateCheckKey]) return;
- if (!state.importedFiles[filename]) state.importedFiles[filename] = {};
- state.importedFiles[filename][stmtDuplicateCheckKey] = true;
- }
- if (from.includes(filename)) return;
- const content = await options.load(filename, options);
- if (content.trim() === "" && options.warnOnEmpty) {
- result.warn(`${filename} is empty`, { node: atRule });
- return;
- }
- if (options.skipDuplicates && state.hashFiles[content]?.[stmtDuplicateCheckKey]) return;
- const importedResult = await processContent(result, content, filename, options, postcss);
- const styles = importedResult.root;
- result.messages = result.messages.concat(importedResult.messages);
- if (options.skipDuplicates) {
- if (!styles.some((child) => {
- return child.type === "atrule" && child.name === "import";
- })) {
- if (!state.hashFiles[content]) state.hashFiles[content] = {};
- state.hashFiles[content][stmtDuplicateCheckKey] = true;
- }
- }
- return parseStyles$1(result, styles, options, state, conditions, [...from, filename], postcss);
- }
- function isProcessableURL(uri) {
- if (/^(?:[a-z]+:)?\/\//i.test(uri)) return false;
- try {
- if (new URL(uri, "https://example.com").search) return false;
- } catch {}
- return true;
- }
- module.exports = parseStyles$1;
-}));
-
-//#endregion
-//#region ../../node_modules/.pnpm/postcss-import@16.1.1_postcss@8.5.6/node_modules/postcss-import/index.js
-var require_postcss_import = /* @__PURE__ */ __commonJSMin(((exports, module) => {
- const path = __require("path");
- const applyConditions = require_apply_conditions();
- const applyRaws = require_apply_raws();
- const applyStyles = require_apply_styles();
- const loadContent = () => "";
- const parseStyles = require_parse_styles();
- const resolveId = (id) => id;
- function AtImport(options) {
- options = {
- root: process.cwd(),
- path: [],
- skipDuplicates: true,
- resolve: resolveId,
- load: loadContent,
- plugins: [],
- addModulesDirectories: [],
- warnOnEmpty: true,
- ...options
- };
- options.root = path.resolve(options.root);
- if (typeof options.path === "string") options.path = [options.path];
- if (!Array.isArray(options.path)) options.path = [];
- options.path = options.path.map((p) => path.resolve(options.root, p));
- return {
- postcssPlugin: "postcss-import",
- async Once(styles, { result, atRule, postcss }) {
- const state = {
- importedFiles: {},
- hashFiles: {}
- };
- if (styles.source?.input?.file) state.importedFiles[styles.source.input.file] = {};
- if (options.plugins && !Array.isArray(options.plugins)) throw new Error("plugins option must be an array");
- const bundle = await parseStyles(result, styles, options, state, [], [], postcss);
- applyRaws(bundle);
- applyConditions(bundle, atRule);
- applyStyles(bundle, styles);
- }
- };
- }
- AtImport.postcss = true;
- module.exports = AtImport;
-}));
-
-//#endregion
-export default require_postcss_import();
-
-export { }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/chunks/preview.js b/vanilla/node_modules/vite/dist/node/chunks/preview.js
deleted file mode 100644
index 3437cfb..0000000
--- a/vanilla/node_modules/vite/dist/node/chunks/preview.js
+++ /dev/null
@@ -1,4 +0,0 @@
-import "./logger.js";
-import { d as resolvePreviewOptions, u as preview } from "./config.js";
-
-export { preview }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/chunks/server.js b/vanilla/node_modules/vite/dist/node/chunks/server.js
deleted file mode 100644
index bbf7d8b..0000000
--- a/vanilla/node_modules/vite/dist/node/chunks/server.js
+++ /dev/null
@@ -1,4 +0,0 @@
-import "./logger.js";
-import { at as _createServer, ct as resolveServerOptions, lt as restartServerWithUrls, ot as createServer, st as createServerCloseFn, ut as serverConfigDefaults } from "./config.js";
-
-export { createServer }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/cli.js b/vanilla/node_modules/vite/dist/node/cli.js
deleted file mode 100644
index fbac6a8..0000000
--- a/vanilla/node_modules/vite/dist/node/cli.js
+++ /dev/null
@@ -1,698 +0,0 @@
-import { s as __toESM } from "./chunks/chunk.js";
-import { N as VERSION, R as require_picocolors, n as createLogger } from "./chunks/logger.js";
-import fs from "node:fs";
-import path from "node:path";
-import { performance } from "node:perf_hooks";
-import { EventEmitter } from "events";
-
-//#region ../../node_modules/.pnpm/cac@6.7.14/node_modules/cac/dist/index.mjs
-function toArr(any) {
- return any == null ? [] : Array.isArray(any) ? any : [any];
-}
-function toVal(out, key, val, opts) {
- var x, old = out[key], nxt = !!~opts.string.indexOf(key) ? val == null || val === true ? "" : String(val) : typeof val === "boolean" ? val : !!~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val;
- out[key] = old == null ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt];
-}
-function mri2(args, opts) {
- args = args || [];
- opts = opts || {};
- var k, arr, arg, name, val, out = { _: [] };
- var i = 0, j = 0, idx = 0, len = args.length;
- const alibi = opts.alias !== void 0;
- const strict = opts.unknown !== void 0;
- const defaults = opts.default !== void 0;
- opts.alias = opts.alias || {};
- opts.string = toArr(opts.string);
- opts.boolean = toArr(opts.boolean);
- if (alibi) for (k in opts.alias) {
- arr = opts.alias[k] = toArr(opts.alias[k]);
- for (i = 0; i < arr.length; i++) (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
- }
- for (i = opts.boolean.length; i-- > 0;) {
- arr = opts.alias[opts.boolean[i]] || [];
- for (j = arr.length; j-- > 0;) opts.boolean.push(arr[j]);
- }
- for (i = opts.string.length; i-- > 0;) {
- arr = opts.alias[opts.string[i]] || [];
- for (j = arr.length; j-- > 0;) opts.string.push(arr[j]);
- }
- if (defaults) for (k in opts.default) {
- name = typeof opts.default[k];
- arr = opts.alias[k] = opts.alias[k] || [];
- if (opts[name] !== void 0) {
- opts[name].push(k);
- for (i = 0; i < arr.length; i++) opts[name].push(arr[i]);
- }
- }
- const keys = strict ? Object.keys(opts.alias) : [];
- for (i = 0; i < len; i++) {
- arg = args[i];
- if (arg === "--") {
- out._ = out._.concat(args.slice(++i));
- break;
- }
- for (j = 0; j < arg.length; j++) if (arg.charCodeAt(j) !== 45) break;
- if (j === 0) out._.push(arg);
- else if (arg.substring(j, j + 3) === "no-") {
- name = arg.substring(j + 3);
- if (strict && !~keys.indexOf(name)) return opts.unknown(arg);
- out[name] = false;
- } else {
- for (idx = j + 1; idx < arg.length; idx++) if (arg.charCodeAt(idx) === 61) break;
- name = arg.substring(j, idx);
- val = arg.substring(++idx) || i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i];
- arr = j === 2 ? [name] : name;
- for (idx = 0; idx < arr.length; idx++) {
- name = arr[idx];
- if (strict && !~keys.indexOf(name)) return opts.unknown("-".repeat(j) + name);
- toVal(out, name, idx + 1 < arr.length || val, opts);
- }
- }
- }
- if (defaults) {
- for (k in opts.default) if (out[k] === void 0) out[k] = opts.default[k];
- }
- if (alibi) for (k in out) {
- arr = opts.alias[k] || [];
- while (arr.length > 0) out[arr.shift()] = out[k];
- }
- return out;
-}
-const removeBrackets = (v) => v.replace(/[<[].+/, "").trim();
-const findAllBrackets = (v) => {
- const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
- const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
- const res = [];
- const parse = (match) => {
- let variadic = false;
- let value = match[1];
- if (value.startsWith("...")) {
- value = value.slice(3);
- variadic = true;
- }
- return {
- required: match[0].startsWith("<"),
- value,
- variadic
- };
- };
- let angledMatch;
- while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) res.push(parse(angledMatch));
- let squareMatch;
- while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) res.push(parse(squareMatch));
- return res;
-};
-const getMriOptions = (options) => {
- const result = {
- alias: {},
- boolean: []
- };
- for (const [index, option] of options.entries()) {
- if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1);
- if (option.isBoolean) if (option.negated) {
- if (!options.some((o, i) => {
- return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
- })) result.boolean.push(option.names[0]);
- } else result.boolean.push(option.names[0]);
- }
- return result;
-};
-const findLongest = (arr) => {
- return arr.sort((a, b) => {
- return a.length > b.length ? -1 : 1;
- })[0];
-};
-const padRight = (str, length) => {
- return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
-};
-const camelcase = (input) => {
- return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
- return p1 + p2.toUpperCase();
- });
-};
-const setDotProp = (obj, keys, val) => {
- let i = 0;
- let length = keys.length;
- let t = obj;
- let x;
- for (; i < length; ++i) {
- x = t[keys[i]];
- t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
- }
-};
-const setByType = (obj, transforms) => {
- for (const key of Object.keys(transforms)) {
- const transform = transforms[key];
- if (transform.shouldTransform) {
- obj[key] = Array.prototype.concat.call([], obj[key]);
- if (typeof transform.transformFunction === "function") obj[key] = obj[key].map(transform.transformFunction);
- }
- }
-};
-const getFileName = (input) => {
- const m = /([^\\\/]+)$/.exec(input);
- return m ? m[1] : "";
-};
-const camelcaseOptionName = (name) => {
- return name.split(".").map((v, i) => {
- return i === 0 ? camelcase(v) : v;
- }).join(".");
-};
-var CACError = class extends Error {
- constructor(message) {
- super(message);
- this.name = this.constructor.name;
- if (typeof Error.captureStackTrace === "function") Error.captureStackTrace(this, this.constructor);
- else this.stack = new Error(message).stack;
- }
-};
-var Option = class {
- constructor(rawName, description, config) {
- this.rawName = rawName;
- this.description = description;
- this.config = Object.assign({}, config);
- rawName = rawName.replace(/\.\*/g, "");
- this.negated = false;
- this.names = removeBrackets(rawName).split(",").map((v) => {
- let name = v.trim().replace(/^-{1,2}/, "");
- if (name.startsWith("no-")) {
- this.negated = true;
- name = name.replace(/^no-/, "");
- }
- return camelcaseOptionName(name);
- }).sort((a, b) => a.length > b.length ? 1 : -1);
- this.name = this.names[this.names.length - 1];
- if (this.negated && this.config.default == null) this.config.default = true;
- if (rawName.includes("<")) this.required = true;
- else if (rawName.includes("[")) this.required = false;
- else this.isBoolean = true;
- }
-};
-const processArgs = process.argv;
-const platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
-var Command = class {
- constructor(rawName, description, config = {}, cli$1) {
- this.rawName = rawName;
- this.description = description;
- this.config = config;
- this.cli = cli$1;
- this.options = [];
- this.aliasNames = [];
- this.name = removeBrackets(rawName);
- this.args = findAllBrackets(rawName);
- this.examples = [];
- }
- usage(text) {
- this.usageText = text;
- return this;
- }
- allowUnknownOptions() {
- this.config.allowUnknownOptions = true;
- return this;
- }
- ignoreOptionDefaultValue() {
- this.config.ignoreOptionDefaultValue = true;
- return this;
- }
- version(version, customFlags = "-v, --version") {
- this.versionNumber = version;
- this.option(customFlags, "Display version number");
- return this;
- }
- example(example) {
- this.examples.push(example);
- return this;
- }
- option(rawName, description, config) {
- const option = new Option(rawName, description, config);
- this.options.push(option);
- return this;
- }
- alias(name) {
- this.aliasNames.push(name);
- return this;
- }
- action(callback) {
- this.commandAction = callback;
- return this;
- }
- isMatched(name) {
- return this.name === name || this.aliasNames.includes(name);
- }
- get isDefaultCommand() {
- return this.name === "" || this.aliasNames.includes("!");
- }
- get isGlobalCommand() {
- return this instanceof GlobalCommand;
- }
- hasOption(name) {
- name = name.split(".")[0];
- return this.options.find((option) => {
- return option.names.includes(name);
- });
- }
- outputHelp() {
- const { name, commands } = this.cli;
- const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand;
- let sections = [{ body: `${name}${versionNumber ? `/${versionNumber}` : ""}` }];
- sections.push({
- title: "Usage",
- body: ` $ ${name} ${this.usageText || this.rawName}`
- });
- if ((this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0) {
- const longestCommandName = findLongest(commands.map((command) => command.rawName));
- sections.push({
- title: "Commands",
- body: commands.map((command) => {
- return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
- }).join("\n")
- });
- sections.push({
- title: `For more info, run any command with the \`--help\` flag`,
- body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
- });
- }
- let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
- if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option) => option.name !== "version");
- if (options.length > 0) {
- const longestOptionName = findLongest(options.map((option) => option.rawName));
- sections.push({
- title: "Options",
- body: options.map((option) => {
- return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
- }).join("\n")
- });
- }
- if (this.examples.length > 0) sections.push({
- title: "Examples",
- body: this.examples.map((example) => {
- if (typeof example === "function") return example(name);
- return example;
- }).join("\n")
- });
- if (helpCallback) sections = helpCallback(sections) || sections;
- console.log(sections.map((section) => {
- return section.title ? `${section.title}:
-${section.body}` : section.body;
- }).join("\n\n"));
- }
- outputVersion() {
- const { name } = this.cli;
- const { versionNumber } = this.cli.globalCommand;
- if (versionNumber) console.log(`${name}/${versionNumber} ${platformInfo}`);
- }
- checkRequiredArgs() {
- const minimalArgsCount = this.args.filter((arg) => arg.required).length;
- if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
- }
- checkUnknownOptions() {
- const { options, globalCommand } = this.cli;
- if (!this.config.allowUnknownOptions) {
- for (const name of Object.keys(options)) if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
- }
- }
- checkOptionValue() {
- const { options: parsedOptions, globalCommand } = this.cli;
- const options = [...globalCommand.options, ...this.options];
- for (const option of options) {
- const value = parsedOptions[option.name.split(".")[0]];
- if (option.required) {
- const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
- if (value === true || value === false && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
- }
- }
- }
-};
-var GlobalCommand = class extends Command {
- constructor(cli$1) {
- super("@@global@@", "", {}, cli$1);
- }
-};
-var __assign = Object.assign;
-var CAC = class extends EventEmitter {
- constructor(name = "") {
- super();
- this.name = name;
- this.commands = [];
- this.rawArgs = [];
- this.args = [];
- this.options = {};
- this.globalCommand = new GlobalCommand(this);
- this.globalCommand.usage("<command> [options]");
- }
- usage(text) {
- this.globalCommand.usage(text);
- return this;
- }
- command(rawName, description, config) {
- const command = new Command(rawName, description || "", config, this);
- command.globalCommand = this.globalCommand;
- this.commands.push(command);
- return command;
- }
- option(rawName, description, config) {
- this.globalCommand.option(rawName, description, config);
- return this;
- }
- help(callback) {
- this.globalCommand.option("-h, --help", "Display this message");
- this.globalCommand.helpCallback = callback;
- this.showHelpOnExit = true;
- return this;
- }
- version(version, customFlags = "-v, --version") {
- this.globalCommand.version(version, customFlags);
- this.showVersionOnExit = true;
- return this;
- }
- example(example) {
- this.globalCommand.example(example);
- return this;
- }
- outputHelp() {
- if (this.matchedCommand) this.matchedCommand.outputHelp();
- else this.globalCommand.outputHelp();
- }
- outputVersion() {
- this.globalCommand.outputVersion();
- }
- setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
- this.args = args;
- this.options = options;
- if (matchedCommand) this.matchedCommand = matchedCommand;
- if (matchedCommandName) this.matchedCommandName = matchedCommandName;
- return this;
- }
- unsetMatchedCommand() {
- this.matchedCommand = void 0;
- this.matchedCommandName = void 0;
- }
- parse(argv = processArgs, { run = true } = {}) {
- this.rawArgs = argv;
- if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli";
- let shouldParse = true;
- for (const command of this.commands) {
- const parsed = this.mri(argv.slice(2), command);
- const commandName = parsed.args[0];
- if (command.isMatched(commandName)) {
- shouldParse = false;
- const parsedInfo = __assign(__assign({}, parsed), { args: parsed.args.slice(1) });
- this.setParsedInfo(parsedInfo, command, commandName);
- this.emit(`command:${commandName}`, command);
- }
- }
- if (shouldParse) {
- for (const command of this.commands) if (command.name === "") {
- shouldParse = false;
- const parsed = this.mri(argv.slice(2), command);
- this.setParsedInfo(parsed, command);
- this.emit(`command:!`, command);
- }
- }
- if (shouldParse) {
- const parsed = this.mri(argv.slice(2));
- this.setParsedInfo(parsed);
- }
- if (this.options.help && this.showHelpOnExit) {
- this.outputHelp();
- run = false;
- this.unsetMatchedCommand();
- }
- if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
- this.outputVersion();
- run = false;
- this.unsetMatchedCommand();
- }
- const parsedArgv = {
- args: this.args,
- options: this.options
- };
- if (run) this.runMatchedCommand();
- if (!this.matchedCommand && this.args[0]) this.emit("command:*");
- return parsedArgv;
- }
- mri(argv, command) {
- const cliOptions = [...this.globalCommand.options, ...command ? command.options : []];
- const mriOptions = getMriOptions(cliOptions);
- let argsAfterDoubleDashes = [];
- const doubleDashesIndex = argv.indexOf("--");
- if (doubleDashesIndex > -1) {
- argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
- argv = argv.slice(0, doubleDashesIndex);
- }
- let parsed = mri2(argv, mriOptions);
- parsed = Object.keys(parsed).reduce((res, name) => {
- return __assign(__assign({}, res), { [camelcaseOptionName(name)]: parsed[name] });
- }, { _: [] });
- const args = parsed._;
- const options = { "--": argsAfterDoubleDashes };
- const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
- let transforms = Object.create(null);
- for (const cliOption of cliOptions) {
- if (!ignoreDefault && cliOption.config.default !== void 0) for (const name of cliOption.names) options[name] = cliOption.config.default;
- if (Array.isArray(cliOption.config.type)) {
- if (transforms[cliOption.name] === void 0) {
- transforms[cliOption.name] = Object.create(null);
- transforms[cliOption.name]["shouldTransform"] = true;
- transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
- }
- }
- }
- for (const key of Object.keys(parsed)) if (key !== "_") {
- setDotProp(options, key.split("."), parsed[key]);
- setByType(options, transforms);
- }
- return {
- args,
- options
- };
- }
- runMatchedCommand() {
- const { args, options, matchedCommand: command } = this;
- if (!command || !command.commandAction) return;
- command.checkUnknownOptions();
- command.checkOptionValue();
- command.checkRequiredArgs();
- const actionArgs = [];
- command.args.forEach((arg, index) => {
- if (arg.variadic) actionArgs.push(args.slice(index));
- else actionArgs.push(args[index]);
- });
- actionArgs.push(options);
- return command.commandAction.apply(this, actionArgs);
- }
-};
-const cac = (name = "") => new CAC(name);
-
-//#endregion
-//#region src/node/cli.ts
-var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
-function checkNodeVersion(nodeVersion) {
- const currentVersion = nodeVersion.split(".");
- const major = parseInt(currentVersion[0], 10);
- const minor = parseInt(currentVersion[1], 10);
- return major === 20 && minor >= 19 || major === 22 && minor >= 12 || major > 22;
-}
-if (!checkNodeVersion(process.versions.node)) console.warn(import_picocolors.default.yellow(`You are using Node.js ${process.versions.node}. Vite requires Node.js version 20.19+ or 22.12+. Please upgrade your Node.js version.`));
-const cli = cac("vite");
-let profileSession = global.__vite_profile_session;
-let profileCount = 0;
-const stopProfiler = (log) => {
- if (!profileSession) return;
- return new Promise((res, rej) => {
- profileSession.post("Profiler.stop", (err, { profile }) => {
- if (!err) {
- const outPath = path.resolve(`./vite-profile-${profileCount++}.cpuprofile`);
- fs.writeFileSync(outPath, JSON.stringify(profile));
- log(import_picocolors.default.yellow(`CPU profile written to ${import_picocolors.default.white(import_picocolors.default.dim(outPath))}`));
- profileSession = void 0;
- res();
- } else rej(err);
- });
- });
-};
-const filterDuplicateOptions = (options) => {
- for (const [key, value] of Object.entries(options)) if (Array.isArray(value)) options[key] = value[value.length - 1];
-};
-/**
-* removing global flags before passing as command specific sub-configs
-*/
-function cleanGlobalCLIOptions(options) {
- const ret = { ...options };
- delete ret["--"];
- delete ret.c;
- delete ret.config;
- delete ret.base;
- delete ret.l;
- delete ret.logLevel;
- delete ret.clearScreen;
- delete ret.configLoader;
- delete ret.d;
- delete ret.debug;
- delete ret.f;
- delete ret.filter;
- delete ret.m;
- delete ret.mode;
- delete ret.force;
- delete ret.w;
- if ("sourcemap" in ret) {
- const sourcemap = ret.sourcemap;
- ret.sourcemap = sourcemap === "true" ? true : sourcemap === "false" ? false : ret.sourcemap;
- }
- if ("watch" in ret) ret.watch = ret.watch ? {} : void 0;
- return ret;
-}
-/**
-* removing builder flags before passing as command specific sub-configs
-*/
-function cleanBuilderCLIOptions(options) {
- const ret = { ...options };
- delete ret.app;
- return ret;
-}
-/**
-* host may be a number (like 0), should convert to string
-*/
-const convertHost = (v) => {
- if (typeof v === "number") return String(v);
- return v;
-};
-/**
-* base may be a number (like 0), should convert to empty string
-*/
-const convertBase = (v) => {
- if (v === 0) return "";
- return v;
-};
-cli.option("-c, --config <file>", `[string] use specified config file`).option("--base <path>", `[string] public base path (default: /)`, { type: [convertBase] }).option("-l, --logLevel <level>", `[string] info | warn | error | silent`).option("--clearScreen", `[boolean] allow/disable clear screen when logging`).option("--configLoader <loader>", `[string] use 'bundle' to bundle the config with esbuild, or 'runner' (experimental) to process it on the fly, or 'native' (experimental) to load using the native runtime (default: bundle)`).option("-d, --debug [feat]", `[string | boolean] show debug logs`).option("-f, --filter <filter>", `[string] filter debug logs`).option("-m, --mode <mode>", `[string] set env mode`);
-cli.command("[root]", "start dev server").alias("serve").alias("dev").option("--host [host]", `[string] specify hostname`, { type: [convertHost] }).option("--port <port>", `[number] specify port`).option("--open [path]", `[boolean | string] open browser on startup`).option("--cors", `[boolean] enable CORS`).option("--strictPort", `[boolean] exit if specified port is already in use`).option("--force", `[boolean] force the optimizer to ignore the cache and re-bundle`).action(async (root, options) => {
- filterDuplicateOptions(options);
- const { createServer } = await import("./chunks/server.js");
- try {
- const server = await createServer({
- root,
- base: options.base,
- mode: options.mode,
- configFile: options.config,
- configLoader: options.configLoader,
- logLevel: options.logLevel,
- clearScreen: options.clearScreen,
- server: cleanGlobalCLIOptions(options),
- forceOptimizeDeps: options.force
- });
- if (!server.httpServer) throw new Error("HTTP server not available");
- await server.listen();
- const info = server.config.logger.info;
- const modeString = options.mode && options.mode !== "development" ? ` ${import_picocolors.default.bgGreen(` ${import_picocolors.default.bold(options.mode)} `)}` : "";
- const viteStartTime = global.__vite_start_time ?? false;
- const startupDurationString = viteStartTime ? import_picocolors.default.dim(`ready in ${import_picocolors.default.reset(import_picocolors.default.bold(Math.ceil(performance.now() - viteStartTime)))} ms`) : "";
- const hasExistingLogs = process.stdout.bytesWritten > 0 || process.stderr.bytesWritten > 0;
- info(`\n ${import_picocolors.default.green(`${import_picocolors.default.bold("VITE")} v${VERSION}`)}${modeString} ${startupDurationString}\n`, { clear: !hasExistingLogs });
- server.printUrls();
- const customShortcuts = [];
- if (profileSession) customShortcuts.push({
- key: "p",
- description: "start/stop the profiler",
- async action(server$1) {
- if (profileSession) await stopProfiler(server$1.config.logger.info);
- else {
- const inspector = await import("node:inspector").then((r) => r.default);
- await new Promise((res) => {
- profileSession = new inspector.Session();
- profileSession.connect();
- profileSession.post("Profiler.enable", () => {
- profileSession.post("Profiler.start", () => {
- server$1.config.logger.info("Profiler started");
- res();
- });
- });
- });
- }
- }
- });
- server.bindCLIShortcuts({
- print: true,
- customShortcuts
- });
- } catch (e) {
- const logger = createLogger(options.logLevel);
- logger.error(import_picocolors.default.red(`error when starting dev server:\n${e.stack}`), { error: e });
- await stopProfiler(logger.info);
- process.exit(1);
- }
-});
-cli.command("build [root]", "build for production").option("--target <target>", `[string] transpile target (default: 'baseline-widely-available')`).option("--outDir <dir>", `[string] output directory (default: dist)`).option("--assetsDir <dir>", `[string] directory under outDir to place assets in (default: assets)`).option("--assetsInlineLimit <number>", `[number] static asset base64 inline threshold in bytes (default: 4096)`).option("--ssr [entry]", `[string] build specified entry for server-side rendering`).option("--sourcemap [output]", `[boolean | "inline" | "hidden"] output source maps for build (default: false)`).option("--minify [minifier]", "[boolean | \"terser\" | \"esbuild\"] enable/disable minification, or specify minifier to use (default: esbuild)").option("--manifest [name]", `[boolean | string] emit build manifest json`).option("--ssrManifest [name]", `[boolean | string] emit ssr manifest json`).option("--emptyOutDir", `[boolean] force empty outDir when it's outside of root`).option("-w, --watch", `[boolean] rebuilds when modules have changed on disk`).option("--app", `[boolean] same as \`builder: {}\``).action(async (root, options) => {
- filterDuplicateOptions(options);
- const { createBuilder } = await import("./chunks/build.js");
- const buildOptions = cleanGlobalCLIOptions(cleanBuilderCLIOptions(options));
- try {
- await (await createBuilder({
- root,
- base: options.base,
- mode: options.mode,
- configFile: options.config,
- configLoader: options.configLoader,
- logLevel: options.logLevel,
- clearScreen: options.clearScreen,
- build: buildOptions,
- ...options.app ? { builder: {} } : {}
- }, null)).buildApp();
- } catch (e) {
- createLogger(options.logLevel).error(import_picocolors.default.red(`error during build:\n${e.stack}`), { error: e });
- process.exit(1);
- } finally {
- await stopProfiler((message) => createLogger(options.logLevel).info(message));
- }
-});
-cli.command("optimize [root]", "pre-bundle dependencies (deprecated, the pre-bundle process runs automatically and does not need to be called)").option("--force", `[boolean] force the optimizer to ignore the cache and re-bundle`).action(async (root, options) => {
- filterDuplicateOptions(options);
- const { resolveConfig } = await import("./chunks/config2.js");
- const { optimizeDeps } = await import("./chunks/optimizer.js");
- try {
- await optimizeDeps(await resolveConfig({
- root,
- base: options.base,
- configFile: options.config,
- configLoader: options.configLoader,
- logLevel: options.logLevel,
- mode: options.mode
- }, "serve"), options.force, true);
- } catch (e) {
- createLogger(options.logLevel).error(import_picocolors.default.red(`error when optimizing deps:\n${e.stack}`), { error: e });
- process.exit(1);
- }
-});
-cli.command("preview [root]", "locally preview production build").option("--host [host]", `[string] specify hostname`, { type: [convertHost] }).option("--port <port>", `[number] specify port`).option("--strictPort", `[boolean] exit if specified port is already in use`).option("--open [path]", `[boolean | string] open browser on startup`).option("--outDir <dir>", `[string] output directory (default: dist)`).action(async (root, options) => {
- filterDuplicateOptions(options);
- const { preview } = await import("./chunks/preview.js");
- try {
- const server = await preview({
- root,
- base: options.base,
- configFile: options.config,
- configLoader: options.configLoader,
- logLevel: options.logLevel,
- mode: options.mode,
- build: { outDir: options.outDir },
- preview: {
- port: options.port,
- strictPort: options.strictPort,
- host: options.host,
- open: options.open
- }
- });
- server.printUrls();
- server.bindCLIShortcuts({ print: true });
- } catch (e) {
- createLogger(options.logLevel).error(import_picocolors.default.red(`error when starting preview server:\n${e.stack}`), { error: e });
- process.exit(1);
- } finally {
- await stopProfiler((message) => createLogger(options.logLevel).info(message));
- }
-});
-cli.help();
-cli.version(VERSION);
-cli.parse();
-
-//#endregion
-export { stopProfiler }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/index.d.ts b/vanilla/node_modules/vite/dist/node/index.d.ts
deleted file mode 100644
index c15c60f..0000000
--- a/vanilla/node_modules/vite/dist/node/index.d.ts
+++ /dev/null
@@ -1,3713 +0,0 @@
-/// <reference types="node" />
-import { t as ModuleRunnerTransport } from "./chunks/moduleRunnerTransport.js";
-import { ConnectedPayload, CustomPayload, CustomPayload as hmrPayload_CustomPayload, ErrorPayload, FullReloadPayload, HMRPayload, HotPayload, HotPayload as hmrPayload_HotPayload, PrunePayload, Update, UpdatePayload } from "#types/hmrPayload";
-import { CustomEventMap, InferCustomEventPayload, InferCustomEventPayload as hmrPayload_InferCustomEventPayload, InvalidatePayload } from "#types/customEvent";
-import * as Rollup from "rollup";
-import { CustomPluginOptions, ExistingRawSourceMap, InputOption, InputOptions, LoadResult, MinimalPluginContext, ModuleFormat, ModuleInfo, ObjectHook, OutputBundle, OutputChunk, PartialResolvedId, PluginContext, PluginContextMeta, PluginHooks, ResolveIdResult, RollupError, RollupLog, RollupOptions, RollupOutput, RollupWatcher, SourceDescription, SourceMap, SourceMapInput, TransformPluginContext, WatcherOptions } from "rollup";
-import { parseAst, parseAstAsync } from "rollup/parseAst";
-import * as http from "node:http";
-import { Agent, ClientRequest, ClientRequestArgs, OutgoingHttpHeaders, ServerResponse } from "node:http";
-import { Http2SecureServer } from "node:http2";
-import * as fs from "node:fs";
-import { EventEmitter } from "node:events";
-import { Server as HttpsServer, ServerOptions as HttpsServerOptions } from "node:https";
-import * as net from "node:net";
-import { Duplex, DuplexOptions, Stream } from "node:stream";
-import { FetchFunction, FetchFunctionOptions, FetchResult, FetchResult as moduleRunner_FetchResult, ModuleEvaluator, ModuleRunner, ModuleRunnerHmr, ModuleRunnerOptions } from "vite/module-runner";
-import { BuildOptions as esbuild_BuildOptions, TransformOptions as EsbuildTransformOptions, TransformOptions as esbuild_TransformOptions, TransformResult as esbuild_TransformResult, version as esbuildVersion } from "esbuild";
-import { SecureContextOptions } from "node:tls";
-import { URL as url_URL } from "node:url";
-import { ZlibOptions } from "node:zlib";
-import { Terser, TerserMinifyOptions } from "#types/internal/terserOptions";
-import * as PostCSS from "postcss";
-import { LessPreprocessorBaseOptions, SassModernPreprocessBaseOptions, StylusPreprocessorBaseOptions } from "#types/internal/cssPreprocessorOptions";
-import { LightningCSSOptions, LightningCSSOptions as lightningcssOptions_LightningCSSOptions } from "#types/internal/lightningcssOptions";
-import { GeneralImportGlobOptions, ImportGlobFunction, ImportGlobOptions, KnownAsTypeMap } from "#types/importGlob";
-import { ChunkMetadata, CustomPluginOptionsVite } from "#types/metadata";
-
-//#region rolldown:runtime
-
-//#endregion
-//#region src/types/alias.d.ts
-interface Alias {
- find: string | RegExp;
- replacement: string;
- /**
- * Instructs the plugin to use an alternative resolving algorithm,
- * rather than the Rollup's resolver.
- * @default null
- */
- customResolver?: ResolverFunction | ResolverObject | null;
-}
-type MapToFunction<T$1> = T$1 extends Function ? T$1 : never;
-type ResolverFunction = MapToFunction<PluginHooks['resolveId']>;
-interface ResolverObject {
- buildStart?: PluginHooks['buildStart'];
- resolveId: ResolverFunction;
-}
-/**
- * Specifies an `Object`, or an `Array` of `Object`,
- * which defines aliases used to replace values in `import` or `require` statements.
- * With either format, the order of the entries is important,
- * in that the first defined rules are applied first.
- *
- * This is passed to \@rollup/plugin-alias as the "entries" field
- * https://github.com/rollup/plugins/tree/master/packages/alias#entries
- */
-type AliasOptions = readonly Alias[] | {
- [find: string]: string;
-};
-//#endregion
-//#region src/types/anymatch.d.ts
-type AnymatchFn = (testString: string) => boolean;
-type AnymatchPattern = string | RegExp | AnymatchFn;
-type AnymatchMatcher = AnymatchPattern | AnymatchPattern[];
-//#endregion
-//#region src/types/chokidar.d.ts
-declare class FSWatcher extends EventEmitter implements fs.FSWatcher {
- options: WatchOptions;
-
- /**
- * Constructs a new FSWatcher instance with optional WatchOptions parameter.
- */
- constructor(options?: WatchOptions);
-
- /**
- * When called, requests that the Node.js event loop not exit so long as the fs.FSWatcher is active.
- * Calling watcher.ref() multiple times will have no effect.
- */
- ref(): this;
-
- /**
- * When called, the active fs.FSWatcher object will not require the Node.js event loop to remain active.
- * If there is no other activity keeping the event loop running, the process may exit before the fs.FSWatcher object's callback is invoked.
- * Calling watcher.unref() multiple times will have no effect.
- */
- unref(): this;
-
- /**
- * Add files, directories, or glob patterns for tracking. Takes an array of strings or just one
- * string.
- */
- add(paths: string | ReadonlyArray<string>): this;
-
- /**
- * Stop watching files, directories, or glob patterns. Takes an array of strings or just one
- * string.
- */
- unwatch(paths: string | ReadonlyArray<string>): this;
-
- /**
- * Returns an object representing all the paths on the file system being watched by this
- * `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless
- * the `cwd` option was used), and the values are arrays of the names of the items contained in
- * each directory.
- */
- getWatched(): {
- [directory: string]: string[];
- };
-
- /**
- * Removes all listeners from watched files.
- */
- close(): Promise<void>;
- on(event: 'add' | 'addDir' | 'change', listener: (path: string, stats?: fs.Stats) => void): this;
- on(event: 'all', listener: (eventName: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir', path: string, stats?: fs.Stats) => void): this;
-
- /**
- * Error occurred
- */
- on(event: 'error', listener: (error: Error) => void): this;
-
- /**
- * Exposes the native Node `fs.FSWatcher events`
- */
- on(event: 'raw', listener: (eventName: string, path: string, details: any) => void): this;
-
- /**
- * Fires when the initial scan is complete
- */
- on(event: 'ready', listener: () => void): this;
- on(event: 'unlink' | 'unlinkDir', listener: (path: string) => void): this;
- on(event: string, listener: (...args: any[]) => void): this;
-}
-interface WatchOptions {
- /**
- * Indicates whether the process should continue to run as long as files are being watched. If
- * set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`,
- * even if the process continues to run.
- */
- persistent?: boolean;
-
- /**
- * ([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to
- * be ignored. The whole relative or absolute path is tested, not just filename. If a function
- * with two arguments is provided, it gets called twice per path - once with a single argument
- * (the path), second time with two arguments (the path and the
- * [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path).
- */
- ignored?: AnymatchMatcher;
-
- /**
- * If set to `false` then `add`/`addDir` events are also emitted for matching paths while
- * instantiating the watching as chokidar discovers these file paths (before the `ready` event).
- */
- ignoreInitial?: boolean;
-
- /**
- * When `false`, only the symlinks themselves will be watched for changes instead of following
- * the link references and bubbling events through the link's path.
- */
- followSymlinks?: boolean;
-
- /**
- * The base directory from which watch `paths` are to be derived. Paths emitted with events will
- * be relative to this.
- */
- cwd?: string;
-
- /**
- * If set to true then the strings passed to .watch() and .add() are treated as literal path
- * names, even if they look like globs.
- *
- * @default false
- */
- disableGlobbing?: boolean;
-
- /**
- * Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU
- * utilization, consider setting this to `false`. It is typically necessary to **set this to
- * `true` to successfully watch files over a network**, and it may be necessary to successfully
- * watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides
- * the `useFsEvents` default.
- */
- usePolling?: boolean;
-
- /**
- * Whether to use the `fsevents` watching interface if available. When set to `true` explicitly
- * and `fsevents` is available this supersedes the `usePolling` setting. When set to `false` on
- * OS X, `usePolling: true` becomes the default.
- */
- useFsEvents?: boolean;
-
- /**
- * If relying upon the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that
- * may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is
- * provided even in cases where it wasn't already available from the underlying watch events.
- */
- alwaysStat?: boolean;
-
- /**
- * If set, limits how many levels of subdirectories will be traversed.
- */
- depth?: number;
-
- /**
- * Interval of file system polling.
- */
- interval?: number;
-
- /**
- * Interval of file system polling for binary files. ([see list of binary extensions](https://gi
- * thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
- */
- binaryInterval?: number;
-
- /**
- * Indicates whether to watch files that don't have read permissions if possible. If watching
- * fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed
- * silently.
- */
- ignorePermissionErrors?: boolean;
-
- /**
- * `true` if `useFsEvents` and `usePolling` are `false`. Automatically filters out artifacts
- * that occur when using editors that use "atomic writes" instead of writing directly to the
- * source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change`
- * event rather than `unlink` then `add`. If the default of 100 ms does not work well for you,
- * you can override it by setting `atomic` to a custom value, in milliseconds.
- */
- atomic?: boolean | number;
-
- /**
- * can be set to an object in order to adjust timing params:
- */
- awaitWriteFinish?: AwaitWriteFinishOptions | boolean;
-}
-interface AwaitWriteFinishOptions {
- /**
- * Amount of time in milliseconds for a file size to remain constant before emitting its event.
- */
- stabilityThreshold?: number;
-
- /**
- * File size polling interval.
- */
- pollInterval?: number;
-}
-//#endregion
-//#region src/types/connect.d.ts
-declare namespace Connect {
- export type ServerHandle = HandleFunction | http.Server;
- export class IncomingMessage extends http.IncomingMessage {
- originalUrl?: http.IncomingMessage['url'] | undefined;
- }
- export type NextFunction = (err?: any) => void;
- export type SimpleHandleFunction = (req: IncomingMessage, res: http.ServerResponse) => void;
- export type NextHandleFunction = (req: IncomingMessage, res: http.ServerResponse, next: NextFunction) => void;
- export type ErrorHandleFunction = (err: any, req: IncomingMessage, res: http.ServerResponse, next: NextFunction) => void;
- export type HandleFunction = SimpleHandleFunction | NextHandleFunction | ErrorHandleFunction;
- export interface ServerStackItem {
- route: string;
- handle: ServerHandle;
- }
- export interface Server extends NodeJS.EventEmitter {
- (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void;
- route: string;
- stack: ServerStackItem[];
-
- /**
- * Utilize the given middleware `handle` to the given `route`,
- * defaulting to _/_. This "route" is the mount-point for the
- * middleware, when given a value other than _/_ the middleware
- * is only effective when that segment is present in the request's
- * pathname.
- *
- * For example if we were to mount a function at _/admin_, it would
- * be invoked on _/admin_, and _/admin/settings_, however it would
- * not be invoked for _/_, or _/posts_.
- */
- use(fn: NextHandleFunction): Server;
- use(fn: HandleFunction): Server;
- use(route: string, fn: NextHandleFunction): Server;
- use(route: string, fn: HandleFunction): Server;
-
- /**
- * Handle server requests, punting them down
- * the middleware stack.
- */
- handle(req: http.IncomingMessage, res: http.ServerResponse, next: Function): void;
-
- /**
- * Listen for connections.
- *
- * This method takes the same arguments
- * as node's `http.Server#listen()`.
- *
- * HTTP and HTTPS:
- *
- * If you run your application both as HTTP
- * and HTTPS you may wrap them individually,
- * since your Connect "server" is really just
- * a JavaScript `Function`.
- *
- * var connect = require('connect')
- * , http = require('http')
- * , https = require('https');
- *
- * var app = connect();
- *
- * http.createServer(app).listen(80);
- * https.createServer(options, app).listen(443);
- */
- listen(port: number, hostname?: string, backlog?: number, callback?: Function): http.Server;
- listen(port: number, hostname?: string, callback?: Function): http.Server;
- listen(path: string, callback?: Function): http.Server;
- listen(handle: any, listeningListener?: Function): http.Server;
- }
-}
-//#endregion
-//#region ../../node_modules/.pnpm/http-proxy-3@1.22.0_patch_hash=d89dff5a0afc2cb277080ad056a3baf7feeeeac19144878abc17f4c91ad89095_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/index.d.ts
-interface ProxyTargetDetailed {
- host: string;
- port: number;
- protocol?: string;
- hostname?: string;
- socketPath?: string;
- key?: string;
- passphrase?: string;
- pfx?: Buffer | string;
- cert?: string;
- ca?: string;
- ciphers?: string;
- secureProtocol?: string;
-}
-type ProxyType = "ws" | "web";
-type ProxyTarget = ProxyTargetUrl | ProxyTargetDetailed;
-type ProxyTargetUrl = URL | string | {
- port: number;
- host: string;
- protocol?: string;
-};
-type NormalizeProxyTarget<T$1 extends ProxyTargetUrl> = Exclude<T$1, string> | URL;
-interface ServerOptions$3 {
- /** URL string to be parsed with the url module. */
- target?: ProxyTarget;
- /** URL string to be parsed with the url module or a URL object. */
- forward?: ProxyTargetUrl;
- /** Object to be passed to http(s).request. */
- agent?: any;
- /** Object to be passed to https.createServer(). */
- ssl?: any;
- /** If you want to proxy websockets. */
- ws?: boolean;
- /** Adds x- forward headers. */
- xfwd?: boolean;
- /** Verify SSL certificate. */
- secure?: boolean;
- /** Explicitly specify if we are proxying to another proxy. */
- toProxy?: boolean;
- /** Specify whether you want to prepend the target's path to the proxy path. */
- prependPath?: boolean;
- /** Specify whether you want to ignore the proxy path of the incoming request. */
- ignorePath?: boolean;
- /** Local interface string to bind for outgoing connections. */
- localAddress?: string;
- /** Changes the origin of the host header to the target URL. */
- changeOrigin?: boolean;
- /** specify whether you want to keep letter case of response header key */
- preserveHeaderKeyCase?: boolean;
- /** Basic authentication i.e. 'user:password' to compute an Authorization header. */
- auth?: string;
- /** Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null. */
- hostRewrite?: string;
- /** Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false. */
- autoRewrite?: boolean;
- /** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */
- protocolRewrite?: string;
- /** rewrites domain of set-cookie headers. */
- cookieDomainRewrite?: false | string | {
- [oldDomain: string]: string;
- };
- /** rewrites path of set-cookie headers. Default: false */
- cookiePathRewrite?: false | string | {
- [oldPath: string]: string;
- };
- /** object with extra headers to be added to target requests. */
- headers?: {
- [header: string]: string | string[] | undefined;
- };
- /** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */
- proxyTimeout?: number;
- /** Timeout (in milliseconds) for incoming requests */
- timeout?: number;
- /** Specify whether you want to follow redirects. Default: false */
- followRedirects?: boolean;
- /** If set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event */
- selfHandleResponse?: boolean;
- /** Buffer */
- buffer?: Stream;
- /** Explicitly set the method type of the ProxyReq */
- method?: string;
- /**
- * Optionally override the trusted CA certificates.
- * This is passed to https.request.
- */
- ca?: string;
-}
-interface NormalizedServerOptions extends ServerOptions$3 {
- target?: NormalizeProxyTarget<ProxyTarget>;
- forward?: NormalizeProxyTarget<ProxyTargetUrl>;
-}
-type ErrorCallback<TIncomingMessage extends typeof http.IncomingMessage = typeof http.IncomingMessage, TServerResponse extends typeof http.ServerResponse = typeof http.ServerResponse, TError = Error> = (err: TError, req: InstanceType<TIncomingMessage>, res: InstanceType<TServerResponse> | net.Socket, target?: ProxyTargetUrl) => void;
-type ProxyServerEventMap<TIncomingMessage extends typeof http.IncomingMessage = typeof http.IncomingMessage, TServerResponse extends typeof http.ServerResponse = typeof http.ServerResponse, TError = Error> = {
- error: Parameters<ErrorCallback<TIncomingMessage, TServerResponse, TError>>;
- start: [req: InstanceType<TIncomingMessage>, res: InstanceType<TServerResponse>, target: ProxyTargetUrl];
- open: [socket: net.Socket];
- proxyReq: [proxyReq: http.ClientRequest, req: InstanceType<TIncomingMessage>, res: InstanceType<TServerResponse>, options: ServerOptions$3, socket: net.Socket];
- proxyRes: [proxyRes: InstanceType<TIncomingMessage>, req: InstanceType<TIncomingMessage>, res: InstanceType<TServerResponse>];
- proxyReqWs: [proxyReq: http.ClientRequest, req: InstanceType<TIncomingMessage>, socket: net.Socket, options: ServerOptions$3, head: any];
- econnreset: [err: Error, req: InstanceType<TIncomingMessage>, res: InstanceType<TServerResponse>, target: ProxyTargetUrl];
- end: [req: InstanceType<TIncomingMessage>, res: InstanceType<TServerResponse>, proxyRes: InstanceType<TIncomingMessage>];
- close: [proxyRes: InstanceType<TIncomingMessage>, proxySocket: net.Socket, proxyHead: any];
-};
-type ProxyMethodArgs<TIncomingMessage extends typeof http.IncomingMessage = typeof http.IncomingMessage, TServerResponse extends typeof http.ServerResponse = typeof http.ServerResponse, TError = Error> = {
- ws: [req: InstanceType<TIncomingMessage>, socket: any, head: any, ...args: [options?: ServerOptions$3, callback?: ErrorCallback<TIncomingMessage, TServerResponse, TError>] | [callback?: ErrorCallback<TIncomingMessage, TServerResponse, TError>]];
- web: [req: InstanceType<TIncomingMessage>, res: InstanceType<TServerResponse>, ...args: [options: ServerOptions$3, callback?: ErrorCallback<TIncomingMessage, TServerResponse, TError>] | [callback?: ErrorCallback<TIncomingMessage, TServerResponse, TError>]];
-};
-type PassFunctions<TIncomingMessage extends typeof http.IncomingMessage = typeof http.IncomingMessage, TServerResponse extends typeof http.ServerResponse = typeof http.ServerResponse, TError = Error> = {
- ws: (req: InstanceType<TIncomingMessage>, socket: net.Socket, options: NormalizedServerOptions, head: Buffer | undefined, server: ProxyServer<TIncomingMessage, TServerResponse, TError>, cb?: ErrorCallback<TIncomingMessage, TServerResponse, TError>) => unknown;
- web: (req: InstanceType<TIncomingMessage>, res: InstanceType<TServerResponse>, options: NormalizedServerOptions, head: Buffer | undefined, server: ProxyServer<TIncomingMessage, TServerResponse, TError>, cb?: ErrorCallback<TIncomingMessage, TServerResponse, TError>) => unknown;
-};
-declare class ProxyServer<TIncomingMessage extends typeof http.IncomingMessage = typeof http.IncomingMessage, TServerResponse extends typeof http.ServerResponse = typeof http.ServerResponse, TError = Error> extends EventEmitter<ProxyServerEventMap<TIncomingMessage, TServerResponse, TError>> {
- /**
- * Used for proxying WS(S) requests
- * @param req - Client request.
- * @param socket - Client socket.
- * @param head - Client head.
- * @param options - Additional options.
- */
- readonly ws: (...args: ProxyMethodArgs<TIncomingMessage, TServerResponse, TError>["ws"]) => void;
- /**
- * Used for proxying regular HTTP(S) requests
- * @param req - Client request.
- * @param res - Client response.
- * @param options - Additional options.
- */
- readonly web: (...args: ProxyMethodArgs<TIncomingMessage, TServerResponse, TError>["web"]) => void;
- private options;
- private webPasses;
- private wsPasses;
- private _server?;
- /**
- * Creates the proxy server with specified options.
- * @param options - Config object passed to the proxy
- */
- constructor(options?: ServerOptions$3);
- /**
- * Creates the proxy server with specified options.
- * @param options Config object passed to the proxy
- * @returns Proxy object with handlers for `ws` and `web` requests
- */
- static createProxyServer<TIncomingMessage extends typeof http.IncomingMessage, TServerResponse extends typeof http.ServerResponse, TError = Error>(options?: ServerOptions$3): ProxyServer<TIncomingMessage, TServerResponse, TError>;
- /**
- * Creates the proxy server with specified options.
- * @param options Config object passed to the proxy
- * @returns Proxy object with handlers for `ws` and `web` requests
- */
- static createServer<TIncomingMessage extends typeof http.IncomingMessage, TServerResponse extends typeof http.ServerResponse, TError = Error>(options?: ServerOptions$3): ProxyServer<TIncomingMessage, TServerResponse, TError>;
- /**
- * Creates the proxy server with specified options.
- * @param options Config object passed to the proxy
- * @returns Proxy object with handlers for `ws` and `web` requests
- */
- static createProxy<TIncomingMessage extends typeof http.IncomingMessage, TServerResponse extends typeof http.ServerResponse, TError = Error>(options?: ServerOptions$3): ProxyServer<TIncomingMessage, TServerResponse, TError>;
- createRightProxy: <PT extends ProxyType>(type: PT) => Function;
- onError: (err: TError) => void;
- /**
- * A function that wraps the object in a webserver, for your convenience
- * @param port - Port to listen on
- * @param hostname - The hostname to listen on
- */
- listen: (port: number, hostname?: string) => this;
- address: () => string | net.AddressInfo | null | undefined;
- /**
- * A function that closes the inner webserver and stops listening on given port
- */
- close: (cb?: Function) => void;
- before: <PT extends ProxyType>(type: PT, passName: string, cb: PassFunctions<TIncomingMessage, TServerResponse, TError>[PT]) => void;
- after: <PT extends ProxyType>(type: PT, passName: string, cb: PassFunctions<TIncomingMessage, TServerResponse, TError>[PT]) => void;
-}
-//#endregion
-//#region ../../node_modules/.pnpm/http-proxy-3@1.22.0_patch_hash=d89dff5a0afc2cb277080ad056a3baf7feeeeac19144878abc17f4c91ad89095_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/passes/ws-incoming.d.ts
-declare function numOpenSockets(): number;
-declare namespace index_d_exports {
- export { ErrorCallback, ProxyServer, ProxyTarget, ProxyTargetUrl, ServerOptions$3 as ServerOptions, createProxyServer as createProxy, createProxyServer, createProxyServer as createServer, ProxyServer as default, numOpenSockets };
-}
-/**
- * Creates the proxy server.
- *
- * Examples:
- *
- * httpProxy.createProxyServer({ .. }, 8000)
- * // => '{ web: [Function], ws: [Function] ... }'
- *
- * @param {Object} Options Config object passed to the proxy
- *
- * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests
- *
- * @api public
- */
-declare function createProxyServer<TIncomingMessage extends typeof http.IncomingMessage = typeof http.IncomingMessage, TServerResponse extends typeof http.ServerResponse = typeof http.ServerResponse, TError = Error>(options?: ServerOptions$3): ProxyServer<TIncomingMessage, TServerResponse, TError>;
-//#endregion
-//#region src/node/server/middlewares/proxy.d.ts
-interface ProxyOptions extends ServerOptions$3 {
- /**
- * rewrite path
- */
- rewrite?: (path: string) => string;
- /**
- * configure the proxy server (e.g. listen to events)
- */
- configure?: (proxy: ProxyServer, options: ProxyOptions) => void;
- /**
- * webpack-dev-server style bypass function
- */
- bypass?: (req: http.IncomingMessage, res: http.ServerResponse | undefined, options: ProxyOptions) => void | null | undefined | false | string | Promise<void | null | undefined | boolean | string>;
- /**
- * rewrite the Origin header of a WebSocket request to match the target
- *
- * **Exercise caution as rewriting the Origin can leave the proxying open to [CSRF attacks](https://owasp.org/www-community/attacks/csrf).**
- */
- rewriteWsOrigin?: boolean | undefined;
-}
-//#endregion
-//#region src/node/logger.d.ts
-type LogType = "error" | "warn" | "info";
-type LogLevel = LogType | "silent";
-interface Logger {
- info(msg: string, options?: LogOptions): void;
- warn(msg: string, options?: LogOptions): void;
- warnOnce(msg: string, options?: LogOptions): void;
- error(msg: string, options?: LogErrorOptions): void;
- clearScreen(type: LogType): void;
- hasErrorLogged(error: Error | RollupError): boolean;
- hasWarned: boolean;
-}
-interface LogOptions {
- clear?: boolean;
- timestamp?: boolean;
- environment?: string;
-}
-interface LogErrorOptions extends LogOptions {
- error?: Error | RollupError | null;
-}
-interface LoggerOptions {
- prefix?: string;
- allowClearScreen?: boolean;
- customLogger?: Logger;
- console?: Console;
-}
-declare function createLogger(level?: LogLevel, options?: LoggerOptions): Logger;
-//#endregion
-//#region src/node/http.d.ts
-interface CommonServerOptions {
- /**
- * Specify server port. Note if the port is already being used, Vite will
- * automatically try the next available port so this may not be the actual
- * port the server ends up listening on.
- */
- port?: number;
- /**
- * If enabled, vite will exit if specified port is already in use
- */
- strictPort?: boolean;
- /**
- * Specify which IP addresses the server should listen on.
- * Set to 0.0.0.0 to listen on all addresses, including LAN and public addresses.
- */
- host?: string | boolean;
- /**
- * The hostnames that Vite is allowed to respond to.
- * `localhost` and subdomains under `.localhost` and all IP addresses are allowed by default.
- * When using HTTPS, this check is skipped.
- *
- * If a string starts with `.`, it will allow that hostname without the `.` and all subdomains under the hostname.
- * For example, `.example.com` will allow `example.com`, `foo.example.com`, and `foo.bar.example.com`.
- *
- * If set to `true`, the server is allowed to respond to requests for any hosts.
- * This is not recommended as it will be vulnerable to DNS rebinding attacks.
- */
- allowedHosts?: string[] | true;
- /**
- * Enable TLS + HTTP/2.
- * Note: this downgrades to TLS only when the proxy option is also used.
- */
- https?: HttpsServerOptions;
- /**
- * Open browser window on startup
- */
- open?: boolean | string;
- /**
- * Configure custom proxy rules for the dev server. Expects an object
- * of `{ key: options }` pairs.
- * Uses [`http-proxy-3`](https://github.com/sagemathinc/http-proxy-3).
- * Full options [here](https://github.com/sagemathinc/http-proxy-3#options).
- *
- * Example `vite.config.js`:
- * ``` js
- * module.exports = {
- * proxy: {
- * // string shorthand: /foo -> http://localhost:4567/foo
- * '/foo': 'http://localhost:4567',
- * // with options
- * '/api': {
- * target: 'http://jsonplaceholder.typicode.com',
- * changeOrigin: true,
- * rewrite: path => path.replace(/^\/api/, '')
- * }
- * }
- * }
- * ```
- */
- proxy?: Record<string, string | ProxyOptions>;
- /**
- * Configure CORS for the dev server.
- * Uses https://github.com/expressjs/cors.
- *
- * When enabling this option, **we recommend setting a specific value
- * rather than `true`** to avoid exposing the source code to untrusted origins.
- *
- * Set to `true` to allow all methods from any origin, or configure separately
- * using an object.
- *
- * @default false
- */
- cors?: CorsOptions | boolean;
- /**
- * Specify server response headers.
- */
- headers?: OutgoingHttpHeaders;
-}
-/**
-* https://github.com/expressjs/cors#configuration-options
-*/
-interface CorsOptions {
- /**
- * Configures the Access-Control-Allow-Origin CORS header.
- *
- * **We recommend setting a specific value rather than
- * `true`** to avoid exposing the source code to untrusted origins.
- */
- origin?: CorsOrigin | ((origin: string | undefined, cb: (err: Error, origins: CorsOrigin) => void) => void);
- methods?: string | string[];
- allowedHeaders?: string | string[];
- exposedHeaders?: string | string[];
- credentials?: boolean;
- maxAge?: number;
- preflightContinue?: boolean;
- optionsSuccessStatus?: number;
-}
-type CorsOrigin = boolean | string | RegExp | (string | RegExp)[];
-//#endregion
-//#region src/node/typeUtils.d.ts
-type RequiredExceptFor<T$1, K$1 extends keyof T$1> = Pick<T$1, K$1> & Required<Omit<T$1, K$1>>;
-//#endregion
-//#region src/node/preview.d.ts
-interface PreviewOptions extends CommonServerOptions {}
-interface ResolvedPreviewOptions extends RequiredExceptFor<PreviewOptions, "host" | "https" | "proxy"> {}
-interface PreviewServer {
- /**
- * The resolved vite config object
- */
- config: ResolvedConfig;
- /**
- * Stop the server.
- */
- close(): Promise<void>;
- /**
- * A connect app instance.
- * - Can be used to attach custom middlewares to the preview server.
- * - Can also be used as the handler function of a custom http server
- * or as a middleware in any connect-style Node.js frameworks
- *
- * https://github.com/senchalabs/connect#use-middleware
- */
- middlewares: Connect.Server;
- /**
- * native Node http server instance
- */
- httpServer: HttpServer;
- /**
- * The resolved urls Vite prints on the CLI (URL-encoded). Returns `null`
- * if the server is not listening on any port.
- */
- resolvedUrls: ResolvedServerUrls | null;
- /**
- * Print server urls
- */
- printUrls(): void;
- /**
- * Bind CLI shortcuts
- */
- bindCLIShortcuts(options?: BindCLIShortcutsOptions<PreviewServer>): void;
-}
-type PreviewServerHook = (this: MinimalPluginContextWithoutEnvironment, server: PreviewServer) => (() => void) | void | Promise<(() => void) | void>;
-/**
-* Starts the Vite server in preview mode, to simulate a production deployment
-*/
-declare function preview(inlineConfig?: InlineConfig): Promise<PreviewServer>;
-//#endregion
-//#region src/node/shortcuts.d.ts
-type BindCLIShortcutsOptions<Server$3 = ViteDevServer | PreviewServer> = {
- /**
- * Print a one-line shortcuts "help" hint to the terminal
- */
- print?: boolean;
- /**
- * Custom shortcuts to run when a key is pressed. These shortcuts take priority
- * over the default shortcuts if they have the same keys (except the `h` key).
- * To disable a default shortcut, define the same key but with `action: undefined`.
- */
- customShortcuts?: CLIShortcut<Server$3>[];
-};
-type CLIShortcut<Server$3 = ViteDevServer | PreviewServer> = {
- key: string;
- description: string;
- action?(server: Server$3): void | Promise<void>;
-};
-//#endregion
-//#region src/node/baseEnvironment.d.ts
-declare class PartialEnvironment {
- name: string;
- getTopLevelConfig(): ResolvedConfig;
- config: ResolvedConfig & ResolvedEnvironmentOptions;
- logger: Logger;
- constructor(name: string, topLevelConfig: ResolvedConfig, options?: ResolvedEnvironmentOptions);
-}
-declare class BaseEnvironment extends PartialEnvironment {
- get plugins(): readonly Plugin[];
- constructor(name: string, config: ResolvedConfig, options?: ResolvedEnvironmentOptions);
-}
-/**
-* This class discourages users from inversely checking the `mode`
-* to determine the type of environment, e.g.
-*
-* ```js
-* const isDev = environment.mode !== 'build' // bad
-* const isDev = environment.mode === 'dev' // good
-* ```
-*
-* You should also not check against `"unknown"` specifically. It's
-* a placeholder for more possible environment types.
-*/
-declare class UnknownEnvironment extends BaseEnvironment {
- mode: "unknown";
-}
-//#endregion
-//#region src/node/optimizer/scan.d.ts
-declare class ScanEnvironment extends BaseEnvironment {
- mode: "scan";
- get pluginContainer(): EnvironmentPluginContainer;
- init(): Promise<void>;
-}
-//#endregion
-//#region src/node/optimizer/index.d.ts
-type ExportsData = {
- hasModuleSyntax: boolean;
- exports: readonly string[];
- jsxLoader?: boolean;
-};
-interface DepsOptimizer {
- init: () => Promise<void>;
- metadata: DepOptimizationMetadata;
- scanProcessing?: Promise<void>;
- registerMissingImport: (id: string, resolved: string) => OptimizedDepInfo;
- run: () => void;
- isOptimizedDepFile: (id: string) => boolean;
- isOptimizedDepUrl: (url: string) => boolean;
- getOptimizedDepId: (depInfo: OptimizedDepInfo) => string;
- close: () => Promise<void>;
- options: DepOptimizationOptions;
-}
-interface DepOptimizationConfig {
- /**
- * Force optimize listed dependencies (must be resolvable import paths,
- * cannot be globs).
- */
- include?: string[];
- /**
- * Do not optimize these dependencies (must be resolvable import paths,
- * cannot be globs).
- */
- exclude?: string[];
- /**
- * Forces ESM interop when importing these dependencies. Some legacy
- * packages advertise themselves as ESM but use `require` internally
- * @experimental
- */
- needsInterop?: string[];
- /**
- * Options to pass to esbuild during the dep scanning and optimization
- *
- * Certain options are omitted since changing them would not be compatible
- * with Vite's dep optimization.
- *
- * - `external` is also omitted, use Vite's `optimizeDeps.exclude` option
- * - `plugins` are merged with Vite's dep plugin
- *
- * https://esbuild.github.io/api
- */
- esbuildOptions?: Omit<esbuild_BuildOptions, "bundle" | "entryPoints" | "external" | "write" | "watch" | "outdir" | "outfile" | "outbase" | "outExtension" | "metafile">;
- /**
- * List of file extensions that can be optimized. A corresponding esbuild
- * plugin must exist to handle the specific extension.
- *
- * By default, Vite can optimize `.mjs`, `.js`, `.ts`, and `.mts` files. This option
- * allows specifying additional extensions.
- *
- * @experimental
- */
- extensions?: string[];
- /**
- * Deps optimization during build was removed in Vite 5.1. This option is
- * now redundant and will be removed in a future version. Switch to using
- * `optimizeDeps.noDiscovery` and an empty or undefined `optimizeDeps.include`.
- * true or 'dev' disables the optimizer, false or 'build' leaves it enabled.
- * @default 'build'
- * @deprecated
- * @experimental
- */
- disabled?: boolean | "build" | "dev";
- /**
- * Automatic dependency discovery. When `noDiscovery` is true, only dependencies
- * listed in `include` will be optimized. The scanner isn't run for cold start
- * in this case. CJS-only dependencies must be present in `include` during dev.
- * @default false
- */
- noDiscovery?: boolean;
- /**
- * When enabled, it will hold the first optimized deps results until all static
- * imports are crawled on cold start. This avoids the need for full-page reloads
- * when new dependencies are discovered and they trigger the generation of new
- * common chunks. If all dependencies are found by the scanner plus the explicitly
- * defined ones in `include`, it is better to disable this option to let the
- * browser process more requests in parallel.
- * @default true
- * @experimental
- */
- holdUntilCrawlEnd?: boolean;
- /**
- * When enabled, Vite will not throw an error when an outdated optimized
- * dependency is requested. Enabling this option may cause a single module
- * to have a multiple reference.
- * @default false
- * @experimental
- */
- ignoreOutdatedRequests?: boolean;
-}
-type DepOptimizationOptions = DepOptimizationConfig & {
- /**
- * By default, Vite will crawl your `index.html` to detect dependencies that
- * need to be pre-bundled. If `build.rollupOptions.input` is specified, Vite
- * will crawl those entry points instead.
- *
- * If neither of these fit your needs, you can specify custom entries using
- * this option - the value should be a tinyglobby pattern or array of patterns
- * (https://github.com/SuperchupuDev/tinyglobby) that are relative from
- * vite project root. This will overwrite default entries inference.
- */
- entries?: string | string[];
- /**
- * Force dep pre-optimization regardless of whether deps have changed.
- * @experimental
- */
- force?: boolean;
-};
-interface OptimizedDepInfo {
- id: string;
- file: string;
- src?: string;
- needsInterop?: boolean;
- browserHash?: string;
- fileHash?: string;
- /**
- * During optimization, ids can still be resolved to their final location
- * but the bundles may not yet be saved to disk
- */
- processing?: Promise<void>;
- /**
- * ExportData cache, discovered deps will parse the src entry to get exports
- * data used both to define if interop is needed and when pre-bundling
- */
- exportsData?: Promise<ExportsData>;
-}
-interface DepOptimizationMetadata {
- /**
- * The main hash is determined by user config and dependency lockfiles.
- * This is checked on server startup to avoid unnecessary re-bundles.
- */
- hash: string;
- /**
- * This hash is determined by dependency lockfiles.
- * This is checked on server startup to avoid unnecessary re-bundles.
- */
- lockfileHash: string;
- /**
- * This hash is determined by user config.
- * This is checked on server startup to avoid unnecessary re-bundles.
- */
- configHash: string;
- /**
- * The browser hash is determined by the main hash plus additional dependencies
- * discovered at runtime. This is used to invalidate browser requests to
- * optimized deps.
- */
- browserHash: string;
- /**
- * Metadata for each already optimized dependency
- */
- optimized: Record<string, OptimizedDepInfo>;
- /**
- * Metadata for non-entry optimized chunks and dynamic imports
- */
- chunks: Record<string, OptimizedDepInfo>;
- /**
- * Metadata for each newly discovered dependency after processing
- */
- discovered: Record<string, OptimizedDepInfo>;
- /**
- * OptimizedDepInfo list
- */
- depInfoList: OptimizedDepInfo[];
-}
-/**
-* Scan and optimize dependencies within a project.
-* Used by Vite CLI when running `vite optimize`.
-*
-* @deprecated the optimization process runs automatically and does not need to be called
-*/
-declare function optimizeDeps(config: ResolvedConfig, force?: boolean | undefined, asCommand?: boolean): Promise<DepOptimizationMetadata>;
-//#endregion
-//#region src/node/server/transformRequest.d.ts
-interface TransformResult {
- code: string;
- map: SourceMap | {
- mappings: "";
- } | null;
- ssr?: boolean;
- etag?: string;
- deps?: string[];
- dynamicDeps?: string[];
-}
-interface TransformOptions {
- /**
- * @deprecated inferred from environment
- */
- ssr?: boolean;
-}
-interface TransformOptionsInternal {}
-//#endregion
-//#region src/node/server/moduleGraph.d.ts
-declare class EnvironmentModuleNode {
- environment: string;
- /**
- * Public served url path, starts with /
- */
- url: string;
- /**
- * Resolved file system path + query
- */
- id: string | null;
- file: string | null;
- type: "js" | "css" | "asset";
- info?: ModuleInfo;
- meta?: Record<string, any>;
- importers: Set<EnvironmentModuleNode>;
- importedModules: Set<EnvironmentModuleNode>;
- acceptedHmrDeps: Set<EnvironmentModuleNode>;
- acceptedHmrExports: Set<string> | null;
- importedBindings: Map<string, Set<string>> | null;
- isSelfAccepting?: boolean;
- transformResult: TransformResult | null;
- ssrModule: Record<string, any> | null;
- ssrError: Error | null;
- lastHMRTimestamp: number;
- lastInvalidationTimestamp: number;
- /**
- * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870
- */
- constructor(url: string, environment: string, setIsSelfAccepting?: boolean);
-}
-type ResolvedUrl = [url: string, resolvedId: string, meta: object | null | undefined];
-declare class EnvironmentModuleGraph {
- environment: string;
- urlToModuleMap: Map<string, EnvironmentModuleNode>;
- idToModuleMap: Map<string, EnvironmentModuleNode>;
- etagToModuleMap: Map<string, EnvironmentModuleNode>;
- fileToModulesMap: Map<string, Set<EnvironmentModuleNode>>;
- constructor(environment: string, resolveId: (url: string) => Promise<PartialResolvedId | null>);
- getModuleByUrl(rawUrl: string): Promise<EnvironmentModuleNode | undefined>;
- getModuleById(id: string): EnvironmentModuleNode | undefined;
- getModulesByFile(file: string): Set<EnvironmentModuleNode> | undefined;
- onFileChange(file: string): void;
- onFileDelete(file: string): void;
- invalidateModule(mod: EnvironmentModuleNode, seen?: Set<EnvironmentModuleNode>, timestamp?: number, isHmr?: boolean, softInvalidate?: boolean): void;
- invalidateAll(): void;
- /**
- * Update the module graph based on a module's updated imports information
- * If there are dependencies that no longer have any importers, they are
- * returned as a Set.
- *
- * @param staticImportedUrls Subset of `importedModules` where they're statically imported in code.
- * This is only used for soft invalidations so `undefined` is fine but may cause more runtime processing.
- */
- updateModuleInfo(mod: EnvironmentModuleNode, importedModules: Set<string | EnvironmentModuleNode>, importedBindings: Map<string, Set<string>> | null, acceptedModules: Set<string | EnvironmentModuleNode>, acceptedExports: Set<string> | null, isSelfAccepting: boolean, staticImportedUrls?: Set<string>): Promise<Set<EnvironmentModuleNode> | undefined>;
- ensureEntryFromUrl(rawUrl: string, setIsSelfAccepting?: boolean): Promise<EnvironmentModuleNode>;
- createFileOnlyEntry(file: string): EnvironmentModuleNode;
- resolveUrl(url: string): Promise<ResolvedUrl>;
- updateModuleTransformResult(mod: EnvironmentModuleNode, result: TransformResult | null): void;
- getModuleByEtag(etag: string): EnvironmentModuleNode | undefined;
-}
-//#endregion
-//#region src/node/server/mixedModuleGraph.d.ts
-declare class ModuleNode {
- _moduleGraph: ModuleGraph;
- _clientModule: EnvironmentModuleNode | undefined;
- _ssrModule: EnvironmentModuleNode | undefined;
- constructor(moduleGraph: ModuleGraph, clientModule?: EnvironmentModuleNode, ssrModule?: EnvironmentModuleNode);
- _get<T$1 extends keyof EnvironmentModuleNode>(prop: T$1): EnvironmentModuleNode[T$1];
- _set<T$1 extends keyof EnvironmentModuleNode>(prop: T$1, value: EnvironmentModuleNode[T$1]): void;
- _wrapModuleSet(prop: ModuleSetNames, module: EnvironmentModuleNode | undefined): Set<ModuleNode>;
- _getModuleSetUnion(prop: "importedModules" | "importers"): Set<ModuleNode>;
- _getModuleInfoUnion(prop: "info"): ModuleInfo | undefined;
- _getModuleObjectUnion(prop: "meta"): Record<string, any> | undefined;
- get url(): string;
- set url(value: string);
- get id(): string | null;
- set id(value: string | null);
- get file(): string | null;
- set file(value: string | null);
- get type(): "js" | "css" | "asset";
- get info(): ModuleInfo | undefined;
- get meta(): Record<string, any> | undefined;
- get importers(): Set<ModuleNode>;
- get clientImportedModules(): Set<ModuleNode>;
- get ssrImportedModules(): Set<ModuleNode>;
- get importedModules(): Set<ModuleNode>;
- get acceptedHmrDeps(): Set<ModuleNode>;
- get acceptedHmrExports(): Set<string> | null;
- get importedBindings(): Map<string, Set<string>> | null;
- get isSelfAccepting(): boolean | undefined;
- get transformResult(): TransformResult | null;
- set transformResult(value: TransformResult | null);
- get ssrTransformResult(): TransformResult | null;
- set ssrTransformResult(value: TransformResult | null);
- get ssrModule(): Record<string, any> | null;
- get ssrError(): Error | null;
- get lastHMRTimestamp(): number;
- set lastHMRTimestamp(value: number);
- get lastInvalidationTimestamp(): number;
- get invalidationState(): TransformResult | "HARD_INVALIDATED" | undefined;
- get ssrInvalidationState(): TransformResult | "HARD_INVALIDATED" | undefined;
-}
-declare class ModuleGraph {
- urlToModuleMap: Map<string, ModuleNode>;
- idToModuleMap: Map<string, ModuleNode>;
- etagToModuleMap: Map<string, ModuleNode>;
- fileToModulesMap: Map<string, Set<ModuleNode>>;
- private moduleNodeCache;
- constructor(moduleGraphs: {
- client: () => EnvironmentModuleGraph;
- ssr: () => EnvironmentModuleGraph;
- });
- getModuleById(id: string): ModuleNode | undefined;
- getModuleByUrl(url: string, _ssr?: boolean): Promise<ModuleNode | undefined>;
- getModulesByFile(file: string): Set<ModuleNode> | undefined;
- onFileChange(file: string): void;
- onFileDelete(file: string): void;
- invalidateModule(mod: ModuleNode, seen?: Set<ModuleNode>, timestamp?: number, isHmr?: boolean, softInvalidate?: boolean): void;
- invalidateAll(): void;
- ensureEntryFromUrl(rawUrl: string, ssr?: boolean, setIsSelfAccepting?: boolean): Promise<ModuleNode>;
- createFileOnlyEntry(file: string): ModuleNode;
- resolveUrl(url: string, ssr?: boolean): Promise<ResolvedUrl>;
- updateModuleTransformResult(mod: ModuleNode, result: TransformResult | null, ssr?: boolean): void;
- getModuleByEtag(etag: string): ModuleNode | undefined;
- getBackwardCompatibleBrowserModuleNode(clientModule: EnvironmentModuleNode): ModuleNode;
- getBackwardCompatibleServerModuleNode(ssrModule: EnvironmentModuleNode): ModuleNode;
- getBackwardCompatibleModuleNode(mod: EnvironmentModuleNode): ModuleNode;
- getBackwardCompatibleModuleNodeDual(clientModule?: EnvironmentModuleNode, ssrModule?: EnvironmentModuleNode): ModuleNode;
-}
-type ModuleSetNames = "acceptedHmrDeps" | "importedModules";
-//#endregion
-//#region src/node/server/hmr.d.ts
-interface HmrOptions {
- protocol?: string;
- host?: string;
- port?: number;
- clientPort?: number;
- path?: string;
- timeout?: number;
- overlay?: boolean;
- server?: HttpServer;
-}
-interface HotUpdateOptions {
- type: "create" | "update" | "delete";
- file: string;
- timestamp: number;
- modules: Array<EnvironmentModuleNode>;
- read: () => string | Promise<string>;
- server: ViteDevServer;
-}
-interface HmrContext {
- file: string;
- timestamp: number;
- modules: Array<ModuleNode>;
- read: () => string | Promise<string>;
- server: ViteDevServer;
-}
-interface HotChannelClient {
- send(payload: hmrPayload_HotPayload): void;
-}
-type HotChannelListener<T$1 extends string = string> = (data: InferCustomEventPayload<T$1>, client: HotChannelClient) => void;
-interface HotChannel<Api = any> {
- /**
- * Broadcast events to all clients
- */
- send?(payload: hmrPayload_HotPayload): void;
- /**
- * Handle custom event emitted by `import.meta.hot.send`
- */
- on?<T$1 extends string>(event: T$1, listener: HotChannelListener<T$1>): void;
- on?(event: "connection", listener: () => void): void;
- /**
- * Unregister event listener
- */
- off?(event: string, listener: Function): void;
- /**
- * Start listening for messages
- */
- listen?(): void;
- /**
- * Disconnect all clients, called when server is closed or restarted.
- */
- close?(): Promise<unknown> | void;
- api?: Api;
-}
-interface NormalizedHotChannelClient {
- /**
- * Send event to the client
- */
- send(payload: hmrPayload_HotPayload): void;
- /**
- * Send custom event
- */
- send(event: string, payload?: hmrPayload_CustomPayload["data"]): void;
-}
-interface NormalizedHotChannel<Api = any> {
- /**
- * Broadcast events to all clients
- */
- send(payload: hmrPayload_HotPayload): void;
- /**
- * Send custom event
- */
- send<T$1 extends string>(event: T$1, payload?: InferCustomEventPayload<T$1>): void;
- /**
- * Handle custom event emitted by `import.meta.hot.send`
- */
- on<T$1 extends string>(event: T$1, listener: (data: InferCustomEventPayload<T$1>, client: NormalizedHotChannelClient) => void): void;
- /**
- * @deprecated use `vite:client:connect` event instead
- */
- on(event: "connection", listener: () => void): void;
- /**
- * Unregister event listener
- */
- off(event: string, listener: Function): void;
- handleInvoke(payload: hmrPayload_HotPayload): Promise<{
- result: any;
- } | {
- error: any;
- }>;
- /**
- * Start listening for messages
- */
- listen(): void;
- /**
- * Disconnect all clients, called when server is closed or restarted.
- */
- close(): Promise<unknown> | void;
- api?: Api;
-}
-type ServerHotChannelApi = {
- innerEmitter: EventEmitter;
- outsideEmitter: EventEmitter;
-};
-type ServerHotChannel = HotChannel<ServerHotChannelApi>;
-type NormalizedServerHotChannel = NormalizedHotChannel<ServerHotChannelApi>;
-declare function createServerHotChannel(): ServerHotChannel;
-//#endregion
-//#region src/types/ws.d.ts
-// WebSocket socket.
-declare class WebSocket extends EventEmitter {
- /** The connection is not yet open. */
- static readonly CONNECTING: 0;
- /** The connection is open and ready to communicate. */
- static readonly OPEN: 1;
- /** The connection is in the process of closing. */
- static readonly CLOSING: 2;
- /** The connection is closed. */
- static readonly CLOSED: 3;
- binaryType: 'nodebuffer' | 'arraybuffer' | 'fragments';
- readonly bufferedAmount: number;
- readonly extensions: string;
- /** Indicates whether the websocket is paused */
- readonly isPaused: boolean;
- readonly protocol: string;
- /** The current state of the connection */
- readonly readyState: typeof WebSocket.CONNECTING | typeof WebSocket.OPEN | typeof WebSocket.CLOSING | typeof WebSocket.CLOSED;
- readonly url: string;
-
- /** The connection is not yet open. */
- readonly CONNECTING: 0;
- /** The connection is open and ready to communicate. */
- readonly OPEN: 1;
- /** The connection is in the process of closing. */
- readonly CLOSING: 2;
- /** The connection is closed. */
- readonly CLOSED: 3;
- onopen: ((event: WebSocket.Event) => void) | null;
- onerror: ((event: WebSocket.ErrorEvent) => void) | null;
- onclose: ((event: WebSocket.CloseEvent) => void) | null;
- onmessage: ((event: WebSocket.MessageEvent) => void) | null;
- constructor(address: null);
- constructor(address: string | url_URL, options?: WebSocket.ClientOptions | ClientRequestArgs);
- constructor(address: string | url_URL, protocols?: string | string[], options?: WebSocket.ClientOptions | ClientRequestArgs);
- close(code?: number, data?: string | Buffer): void;
- ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void;
- pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void;
- send(data: any, cb?: (err?: Error) => void): void;
- send(data: any, options: {
- mask?: boolean | undefined;
- binary?: boolean | undefined;
- compress?: boolean | undefined;
- fin?: boolean | undefined;
- }, cb?: (err?: Error) => void): void;
- terminate(): void;
-
- /**
- * Pause the websocket causing it to stop emitting events. Some events can still be
- * emitted after this is called, until all buffered data is consumed. This method
- * is a noop if the ready state is `CONNECTING` or `CLOSED`.
- */
- pause(): void;
- /**
- * Make a paused socket resume emitting events. This method is a noop if the ready
- * state is `CONNECTING` or `CLOSED`.
- */
- resume(): void;
-
- // HTML5 WebSocket events
- addEventListener(method: 'message', cb: (event: WebSocket.MessageEvent) => void, options?: WebSocket.EventListenerOptions): void;
- addEventListener(method: 'close', cb: (event: WebSocket.CloseEvent) => void, options?: WebSocket.EventListenerOptions): void;
- addEventListener(method: 'error', cb: (event: WebSocket.ErrorEvent) => void, options?: WebSocket.EventListenerOptions): void;
- addEventListener(method: 'open', cb: (event: WebSocket.Event) => void, options?: WebSocket.EventListenerOptions): void;
- removeEventListener(method: 'message', cb: (event: WebSocket.MessageEvent) => void): void;
- removeEventListener(method: 'close', cb: (event: WebSocket.CloseEvent) => void): void;
- removeEventListener(method: 'error', cb: (event: WebSocket.ErrorEvent) => void): void;
- removeEventListener(method: 'open', cb: (event: WebSocket.Event) => void): void;
-
- // Events
- on(event: 'close', listener: (this: WebSocket, code: number, reason: Buffer) => void): this;
- on(event: 'error', listener: (this: WebSocket, err: Error) => void): this;
- on(event: 'upgrade', listener: (this: WebSocket, request: http.IncomingMessage) => void): this;
- on(event: 'message', listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this;
- on(event: 'open', listener: (this: WebSocket) => void): this;
- on(event: 'ping' | 'pong', listener: (this: WebSocket, data: Buffer) => void): this;
- on(event: 'unexpected-response', listener: (this: WebSocket, request: ClientRequest, response: http.IncomingMessage) => void): this;
- on(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this;
- once(event: 'close', listener: (this: WebSocket, code: number, reason: Buffer) => void): this;
- once(event: 'error', listener: (this: WebSocket, err: Error) => void): this;
- once(event: 'upgrade', listener: (this: WebSocket, request: http.IncomingMessage) => void): this;
- once(event: 'message', listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this;
- once(event: 'open', listener: (this: WebSocket) => void): this;
- once(event: 'ping' | 'pong', listener: (this: WebSocket, data: Buffer) => void): this;
- once(event: 'unexpected-response', listener: (this: WebSocket, request: ClientRequest, response: http.IncomingMessage) => void): this;
- once(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this;
- off(event: 'close', listener: (this: WebSocket, code: number, reason: Buffer) => void): this;
- off(event: 'error', listener: (this: WebSocket, err: Error) => void): this;
- off(event: 'upgrade', listener: (this: WebSocket, request: http.IncomingMessage) => void): this;
- off(event: 'message', listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this;
- off(event: 'open', listener: (this: WebSocket) => void): this;
- off(event: 'ping' | 'pong', listener: (this: WebSocket, data: Buffer) => void): this;
- off(event: 'unexpected-response', listener: (this: WebSocket, request: ClientRequest, response: http.IncomingMessage) => void): this;
- off(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this;
- addListener(event: 'close', listener: (code: number, reason: Buffer) => void): this;
- addListener(event: 'error', listener: (err: Error) => void): this;
- addListener(event: 'upgrade', listener: (request: http.IncomingMessage) => void): this;
- addListener(event: 'message', listener: (data: WebSocket.RawData, isBinary: boolean) => void): this;
- addListener(event: 'open', listener: () => void): this;
- addListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this;
- addListener(event: 'unexpected-response', listener: (request: ClientRequest, response: http.IncomingMessage) => void): this;
- addListener(event: string | symbol, listener: (...args: any[]) => void): this;
- removeListener(event: 'close', listener: (code: number, reason: Buffer) => void): this;
- removeListener(event: 'error', listener: (err: Error) => void): this;
- removeListener(event: 'upgrade', listener: (request: http.IncomingMessage) => void): this;
- removeListener(event: 'message', listener: (data: WebSocket.RawData, isBinary: boolean) => void): this;
- removeListener(event: 'open', listener: () => void): this;
- removeListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this;
- removeListener(event: 'unexpected-response', listener: (request: ClientRequest, response: http.IncomingMessage) => void): this;
- removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
-}
-declare const WebSocketAlias: typeof WebSocket;
-interface WebSocketAlias extends WebSocket {}
-declare namespace WebSocket {
- /**
- * Data represents the raw message payload received over the WebSocket.
- */
- type RawData = Buffer | ArrayBuffer | Buffer[];
-
- /**
- * Data represents the message payload received over the WebSocket.
- */
- type Data = string | Buffer | ArrayBuffer | Buffer[];
-
- /**
- * CertMeta represents the accepted types for certificate & key data.
- */
- type CertMeta = string | string[] | Buffer | Buffer[];
-
- /**
- * VerifyClientCallbackSync is a synchronous callback used to inspect the
- * incoming message. The return value (boolean) of the function determines
- * whether or not to accept the handshake.
- */
- type VerifyClientCallbackSync = (info: {
- origin: string;
- secure: boolean;
- req: http.IncomingMessage;
- }) => boolean;
-
- /**
- * VerifyClientCallbackAsync is an asynchronous callback used to inspect the
- * incoming message. The return value (boolean) of the function determines
- * whether or not to accept the handshake.
- */
- type VerifyClientCallbackAsync = (info: {
- origin: string;
- secure: boolean;
- req: http.IncomingMessage;
- }, callback: (res: boolean, code?: number, message?: string, headers?: OutgoingHttpHeaders) => void) => void;
- interface ClientOptions extends SecureContextOptions {
- protocol?: string | undefined;
- followRedirects?: boolean | undefined;
- generateMask?(mask: Buffer): void;
- handshakeTimeout?: number | undefined;
- maxRedirects?: number | undefined;
- perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined;
- localAddress?: string | undefined;
- protocolVersion?: number | undefined;
- headers?: {
- [key: string]: string;
- } | undefined;
- origin?: string | undefined;
- agent?: Agent | undefined;
- host?: string | undefined;
- family?: number | undefined;
- checkServerIdentity?(servername: string, cert: CertMeta): boolean;
- rejectUnauthorized?: boolean | undefined;
- maxPayload?: number | undefined;
- skipUTF8Validation?: boolean | undefined;
- }
- interface PerMessageDeflateOptions {
- serverNoContextTakeover?: boolean | undefined;
- clientNoContextTakeover?: boolean | undefined;
- serverMaxWindowBits?: number | undefined;
- clientMaxWindowBits?: number | undefined;
- zlibDeflateOptions?: {
- flush?: number | undefined;
- finishFlush?: number | undefined;
- chunkSize?: number | undefined;
- windowBits?: number | undefined;
- level?: number | undefined;
- memLevel?: number | undefined;
- strategy?: number | undefined;
- dictionary?: Buffer | Buffer[] | DataView | undefined;
- info?: boolean | undefined;
- } | undefined;
- zlibInflateOptions?: ZlibOptions | undefined;
- threshold?: number | undefined;
- concurrencyLimit?: number | undefined;
- }
- interface Event {
- type: string;
- target: WebSocket;
- }
- interface ErrorEvent {
- error: any;
- message: string;
- type: string;
- target: WebSocket;
- }
- interface CloseEvent {
- wasClean: boolean;
- code: number;
- reason: string;
- type: string;
- target: WebSocket;
- }
- interface MessageEvent {
- data: Data;
- type: string;
- target: WebSocket;
- }
- interface EventListenerOptions {
- once?: boolean | undefined;
- }
- interface ServerOptions {
- host?: string | undefined;
- port?: number | undefined;
- backlog?: number | undefined;
- server?: http.Server | HttpsServer | undefined;
- verifyClient?: VerifyClientCallbackAsync | VerifyClientCallbackSync | undefined;
- handleProtocols?: (protocols: Set<string>, request: http.IncomingMessage) => string | false;
- path?: string | undefined;
- noServer?: boolean | undefined;
- clientTracking?: boolean | undefined;
- perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined;
- maxPayload?: number | undefined;
- skipUTF8Validation?: boolean | undefined;
- WebSocket?: typeof WebSocket.WebSocket | undefined;
- }
- interface AddressInfo {
- address: string;
- family: string;
- port: number;
- }
-
- // WebSocket Server
- class Server<T$1 extends WebSocket = WebSocket> extends EventEmitter {
- options: ServerOptions;
- path: string;
- clients: Set<T$1>;
- constructor(options?: ServerOptions, callback?: () => void);
- address(): AddressInfo | string;
- close(cb?: (err?: Error) => void): void;
- handleUpgrade(request: http.IncomingMessage, socket: Duplex, upgradeHead: Buffer, callback: (client: T$1, request: http.IncomingMessage) => void): void;
- shouldHandle(request: http.IncomingMessage): boolean | Promise<boolean>;
-
- // Events
- on(event: 'connection', cb: (this: Server<T$1>, socket: T$1, request: http.IncomingMessage) => void): this;
- on(event: 'error', cb: (this: Server<T$1>, error: Error) => void): this;
- on(event: 'headers', cb: (this: Server<T$1>, headers: string[], request: http.IncomingMessage) => void): this;
- on(event: 'close' | 'listening', cb: (this: Server<T$1>) => void): this;
- on(event: string | symbol, listener: (this: Server<T$1>, ...args: any[]) => void): this;
- once(event: 'connection', cb: (this: Server<T$1>, socket: T$1, request: http.IncomingMessage) => void): this;
- once(event: 'error', cb: (this: Server<T$1>, error: Error) => void): this;
- once(event: 'headers', cb: (this: Server<T$1>, headers: string[], request: http.IncomingMessage) => void): this;
- once(event: 'close' | 'listening', cb: (this: Server<T$1>) => void): this;
- once(event: string | symbol, listener: (this: Server<T$1>, ...args: any[]) => void): this;
- off(event: 'connection', cb: (this: Server<T$1>, socket: T$1, request: http.IncomingMessage) => void): this;
- off(event: 'error', cb: (this: Server<T$1>, error: Error) => void): this;
- off(event: 'headers', cb: (this: Server<T$1>, headers: string[], request: http.IncomingMessage) => void): this;
- off(event: 'close' | 'listening', cb: (this: Server<T$1>) => void): this;
- off(event: string | symbol, listener: (this: Server<T$1>, ...args: any[]) => void): this;
- addListener(event: 'connection', cb: (client: T$1, request: http.IncomingMessage) => void): this;
- addListener(event: 'error', cb: (err: Error) => void): this;
- addListener(event: 'headers', cb: (headers: string[], request: http.IncomingMessage) => void): this;
- addListener(event: 'close' | 'listening', cb: () => void): this;
- addListener(event: string | symbol, listener: (...args: any[]) => void): this;
- removeListener(event: 'connection', cb: (client: T$1) => void): this;
- removeListener(event: 'error', cb: (err: Error) => void): this;
- removeListener(event: 'headers', cb: (headers: string[], request: http.IncomingMessage) => void): this;
- removeListener(event: 'close' | 'listening', cb: () => void): this;
- removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
- }
- const WebSocketServer: typeof Server;
- interface WebSocketServer extends Server {}
- const WebSocket: typeof WebSocketAlias;
- interface WebSocket extends WebSocketAlias {}
-
- // WebSocket stream
- function createWebSocketStream(websocket: WebSocket, options?: DuplexOptions): Duplex;
-}
-
-// export = WebSocket
-//#endregion
-//#region src/node/server/ws.d.ts
-type WebSocketCustomListener<T$1> = (data: T$1, client: WebSocketClient) => void;
-declare const isWebSocketServer: unique symbol;
-interface WebSocketServer extends NormalizedHotChannel {
- /**
- * Handle custom event emitted by `import.meta.hot.send`
- */
- on: WebSocket.Server["on"] & {
- <T$1 extends string>(event: T$1, listener: WebSocketCustomListener<hmrPayload_InferCustomEventPayload<T$1>>): void;
- };
- /**
- * Unregister event listener.
- */
- off: WebSocket.Server["off"] & {
- (event: string, listener: Function): void;
- };
- /**
- * Listen on port and host
- */
- listen(): void;
- /**
- * Disconnect all clients and terminate the server.
- */
- close(): Promise<void>;
- [isWebSocketServer]: true;
- /**
- * Get all connected clients.
- */
- clients: Set<WebSocketClient>;
-}
-interface WebSocketClient extends NormalizedHotChannelClient {
- /**
- * The raw WebSocket instance
- * @advanced
- */
- socket: WebSocket;
-}
-//#endregion
-//#region src/node/server/environment.d.ts
-interface DevEnvironmentContext {
- hot: boolean;
- transport?: HotChannel | WebSocketServer;
- options?: EnvironmentOptions;
- remoteRunner?: {
- inlineSourceMap?: boolean;
- };
- depsOptimizer?: DepsOptimizer;
-}
-declare class DevEnvironment extends BaseEnvironment {
- mode: "dev";
- moduleGraph: EnvironmentModuleGraph;
- depsOptimizer?: DepsOptimizer;
- get pluginContainer(): EnvironmentPluginContainer<DevEnvironment>;
- /**
- * Hot channel for this environment. If not provided or disabled,
- * it will be a noop channel that does nothing.
- *
- * @example
- * environment.hot.send({ type: 'full-reload' })
- */
- hot: NormalizedHotChannel;
- constructor(name: string, config: ResolvedConfig, context: DevEnvironmentContext);
- init(options?: {
- watcher?: FSWatcher;
- /**
- * the previous instance used for the environment with the same name
- *
- * when using, the consumer should check if it's an instance generated from the same class or factory function
- */
- previousInstance?: DevEnvironment;
- }): Promise<void>;
- /**
- * When the dev server is restarted, the methods are called in the following order:
- * - new instance `init`
- * - previous instance `close`
- * - new instance `listen`
- */
- listen(server: ViteDevServer): Promise<void>;
- fetchModule(id: string, importer?: string, options?: FetchFunctionOptions): Promise<moduleRunner_FetchResult>;
- reloadModule(module: EnvironmentModuleNode): Promise<void>;
- transformRequest(url: string, options?: TransformOptionsInternal): Promise<TransformResult | null>;
- warmupRequest(url: string): Promise<void>;
- close(): Promise<void>;
- /**
- * Calling `await environment.waitForRequestsIdle(id)` will wait until all static imports
- * are processed after the first transformRequest call. If called from a load or transform
- * plugin hook, the id needs to be passed as a parameter to avoid deadlocks.
- * Calling this function after the first static imports section of the module graph has been
- * processed will resolve immediately.
- * @experimental
- */
- waitForRequestsIdle(ignoredId?: string): Promise<void>;
-}
-//#endregion
-//#region src/types/commonjs.d.ts
-
-interface RollupCommonJSOptions {
- /**
- * A minimatch pattern, or array of patterns, which specifies the files in
- * the build the plugin should operate on. By default, all files with
- * extension `".cjs"` or those in `extensions` are included, but you can
- * narrow this list by only including specific files. These files will be
- * analyzed and transpiled if either the analysis does not find ES module
- * specific statements or `transformMixedEsModules` is `true`.
- * @default undefined
- */
- include?: string | RegExp | readonly (string | RegExp)[];
- /**
- * A minimatch pattern, or array of patterns, which specifies the files in
- * the build the plugin should _ignore_. By default, all files with
- * extensions other than those in `extensions` or `".cjs"` are ignored, but you
- * can exclude additional files. See also the `include` option.
- * @default undefined
- */
- exclude?: string | RegExp | readonly (string | RegExp)[];
- /**
- * For extensionless imports, search for extensions other than .js in the
- * order specified. Note that you need to make sure that non-JavaScript files
- * are transpiled by another plugin first.
- * @default [ '.js' ]
- */
- extensions?: ReadonlyArray<string>;
- /**
- * If true then uses of `global` won't be dealt with by this plugin
- * @default false
- */
- ignoreGlobal?: boolean;
- /**
- * If false, skips source map generation for CommonJS modules. This will
- * improve performance.
- * @default true
- */
- sourceMap?: boolean;
- /**
- * Some `require` calls cannot be resolved statically to be translated to
- * imports.
- * When this option is set to `false`, the generated code will either
- * directly throw an error when such a call is encountered or, when
- * `dynamicRequireTargets` is used, when such a call cannot be resolved with a
- * configured dynamic require target.
- * Setting this option to `true` will instead leave the `require` call in the
- * code or use it as a fallback for `dynamicRequireTargets`.
- * @default false
- */
- ignoreDynamicRequires?: boolean;
- /**
- * Instructs the plugin whether to enable mixed module transformations. This
- * is useful in scenarios with modules that contain a mix of ES `import`
- * statements and CommonJS `require` expressions. Set to `true` if `require`
- * calls should be transformed to imports in mixed modules, or `false` if the
- * `require` expressions should survive the transformation. The latter can be
- * important if the code contains environment detection, or you are coding
- * for an environment with special treatment for `require` calls such as
- * ElectronJS. See also the `ignore` option.
- * @default false
- */
- transformMixedEsModules?: boolean;
- /**
- * By default, this plugin will try to hoist `require` statements as imports
- * to the top of each file. While this works well for many code bases and
- * allows for very efficient ESM output, it does not perfectly capture
- * CommonJS semantics as the order of side effects like log statements may
- * change. But it is especially problematic when there are circular `require`
- * calls between CommonJS modules as those often rely on the lazy execution of
- * nested `require` calls.
- *
- * Setting this option to `true` will wrap all CommonJS files in functions
- * which are executed when they are required for the first time, preserving
- * NodeJS semantics. Note that this can have an impact on the size and
- * performance of the generated code.
- *
- * The default value of `"auto"` will only wrap CommonJS files when they are
- * part of a CommonJS dependency cycle, e.g. an index file that is required by
- * many of its dependencies. All other CommonJS files are hoisted. This is the
- * recommended setting for most code bases.
- *
- * `false` will entirely prevent wrapping and hoist all files. This may still
- * work depending on the nature of cyclic dependencies but will often cause
- * problems.
- *
- * You can also provide a minimatch pattern, or array of patterns, to only
- * specify a subset of files which should be wrapped in functions for proper
- * `require` semantics.
- *
- * `"debug"` works like `"auto"` but after bundling, it will display a warning
- * containing a list of ids that have been wrapped which can be used as
- * minimatch pattern for fine-tuning.
- * @default "auto"
- */
- strictRequires?: boolean | string | RegExp | readonly (string | RegExp)[];
- /**
- * Sometimes you have to leave require statements unconverted. Pass an array
- * containing the IDs or a `id => boolean` function.
- * @default []
- */
- ignore?: ReadonlyArray<string> | ((id: string) => boolean);
- /**
- * In most cases, where `require` calls are inside a `try-catch` clause,
- * they should be left unconverted as it requires an optional dependency
- * that may or may not be installed beside the rolled up package.
- * Due to the conversion of `require` to a static `import` - the call is
- * hoisted to the top of the file, outside the `try-catch` clause.
- *
- * - `true`: Default. All `require` calls inside a `try` will be left unconverted.
- * - `false`: All `require` calls inside a `try` will be converted as if the
- * `try-catch` clause is not there.
- * - `remove`: Remove all `require` calls from inside any `try` block.
- * - `string[]`: Pass an array containing the IDs to left unconverted.
- * - `((id: string) => boolean|'remove')`: Pass a function that controls
- * individual IDs.
- *
- * @default true
- */
- ignoreTryCatch?: boolean | 'remove' | ReadonlyArray<string> | ((id: string) => boolean | 'remove');
- /**
- * Controls how to render imports from external dependencies. By default,
- * this plugin assumes that all external dependencies are CommonJS. This
- * means they are rendered as default imports to be compatible with e.g.
- * NodeJS where ES modules can only import a default export from a CommonJS
- * dependency.
- *
- * If you set `esmExternals` to `true`, this plugin assumes that all
- * external dependencies are ES modules and respect the
- * `requireReturnsDefault` option. If that option is not set, they will be
- * rendered as namespace imports.
- *
- * You can also supply an array of ids to be treated as ES modules, or a
- * function that will be passed each external id to determine whether it is
- * an ES module.
- * @default false
- */
- esmExternals?: boolean | ReadonlyArray<string> | ((id: string) => boolean);
- /**
- * Controls what is returned when requiring an ES module from a CommonJS file.
- * When using the `esmExternals` option, this will also apply to external
- * modules. By default, this plugin will render those imports as namespace
- * imports i.e.
- *
- * ```js
- * // input
- * const foo = require('foo');
- *
- * // output
- * import * as foo from 'foo';
- * ```
- *
- * However, there are some situations where this may not be desired.
- * For these situations, you can change Rollup's behaviour either globally or
- * per module. To change it globally, set the `requireReturnsDefault` option
- * to one of the following values:
- *
- * - `false`: This is the default, requiring an ES module returns its
- * namespace. This is the only option that will also add a marker
- * `__esModule: true` to the namespace to support interop patterns in
- * CommonJS modules that are transpiled ES modules.
- * - `"namespace"`: Like `false`, requiring an ES module returns its
- * namespace, but the plugin does not add the `__esModule` marker and thus
- * creates more efficient code. For external dependencies when using
- * `esmExternals: true`, no additional interop code is generated.
- * - `"auto"`: This is complementary to how `output.exports: "auto"` works in
- * Rollup: If a module has a default export and no named exports, requiring
- * that module returns the default export. In all other cases, the namespace
- * is returned. For external dependencies when using `esmExternals: true`, a
- * corresponding interop helper is added.
- * - `"preferred"`: If a module has a default export, requiring that module
- * always returns the default export, no matter whether additional named
- * exports exist. This is similar to how previous versions of this plugin
- * worked. Again for external dependencies when using `esmExternals: true`,
- * an interop helper is added.
- * - `true`: This will always try to return the default export on require
- * without checking if it actually exists. This can throw at build time if
- * there is no default export. This is how external dependencies are handled
- * when `esmExternals` is not used. The advantage over the other options is
- * that, like `false`, this does not add an interop helper for external
- * dependencies, keeping the code lean.
- *
- * To change this for individual modules, you can supply a function for
- * `requireReturnsDefault` instead. This function will then be called once for
- * each required ES module or external dependency with the corresponding id
- * and allows you to return different values for different modules.
- * @default false
- */
- requireReturnsDefault?: boolean | 'auto' | 'preferred' | 'namespace' | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace');
-
- /**
- * @default "auto"
- */
- defaultIsModuleExports?: boolean | 'auto' | ((id: string) => boolean | 'auto');
- /**
- * Some modules contain dynamic `require` calls, or require modules that
- * contain circular dependencies, which are not handled well by static
- * imports. Including those modules as `dynamicRequireTargets` will simulate a
- * CommonJS (NodeJS-like) environment for them with support for dynamic
- * dependencies. It also enables `strictRequires` for those modules.
- *
- * Note: In extreme cases, this feature may result in some paths being
- * rendered as absolute in the final bundle. The plugin tries to avoid
- * exposing paths from the local machine, but if you are `dynamicRequirePaths`
- * with paths that are far away from your project's folder, that may require
- * replacing strings like `"/Users/John/Desktop/foo-project/"` -\> `"/"`.
- */
- dynamicRequireTargets?: string | ReadonlyArray<string>;
- /**
- * To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory
- * that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/`
- * may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your
- * home directory name. By default, it uses the current working directory.
- */
- dynamicRequireRoot?: string;
-}
-//#endregion
-//#region src/types/dynamicImportVars.d.ts
-interface RollupDynamicImportVarsOptions {
- /**
- * Files to include in this plugin (default all).
- * @default []
- */
- include?: string | RegExp | (string | RegExp)[];
- /**
- * Files to exclude in this plugin (default none).
- * @default []
- */
- exclude?: string | RegExp | (string | RegExp)[];
- /**
- * By default, the plugin quits the build process when it encounters an error. If you set this option to true, it will throw a warning instead and leave the code untouched.
- * @default false
- */
- warnOnError?: boolean;
-}
-//#endregion
-//#region src/node/plugins/terser.d.ts
-interface TerserOptions extends TerserMinifyOptions {
- /**
- * Vite-specific option to specify the max number of workers to spawn
- * when minifying files with terser.
- *
- * @default number of CPUs minus 1
- */
- maxWorkers?: number;
-}
-//#endregion
-//#region src/node/plugins/resolve.d.ts
-interface EnvironmentResolveOptions {
- /**
- * @default ['browser', 'module', 'jsnext:main', 'jsnext']
- */
- mainFields?: string[];
- conditions?: string[];
- externalConditions?: string[];
- /**
- * @default ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json']
- */
- extensions?: string[];
- dedupe?: string[];
- /**
- * Prevent listed dependencies from being externalized and will get bundled in build.
- * Only works in server environments for now. Previously this was `ssr.noExternal`.
- * @experimental
- */
- noExternal?: string | RegExp | (string | RegExp)[] | true;
- /**
- * Externalize the given dependencies and their transitive dependencies.
- * Only works in server environments for now. Previously this was `ssr.external`.
- * @experimental
- */
- external?: string[] | true;
- /**
- * Array of strings or regular expressions that indicate what modules are builtin for the environment.
- */
- builtins?: (string | RegExp)[];
-}
-interface ResolveOptions extends EnvironmentResolveOptions {
- /**
- * @default false
- */
- preserveSymlinks?: boolean;
-}
-interface ResolvePluginOptions {
- root: string;
- isBuild: boolean;
- isProduction: boolean;
- packageCache?: PackageCache;
- /**
- * src code mode also attempts the following:
- * - resolving /xxx as URLs
- * - resolving bare imports from optimized deps
- */
- asSrc?: boolean;
- tryIndex?: boolean;
- tryPrefix?: string;
- preferRelative?: boolean;
- isRequire?: boolean;
- scan?: boolean;
-}
-interface InternalResolveOptions extends Required<ResolveOptions>, ResolvePluginOptions {}
-//#endregion
-//#region src/node/packages.d.ts
-/** Cache for package.json resolution and package.json contents */
-type PackageCache = Map<string, PackageData>;
-interface PackageData {
- dir: string;
- hasSideEffects: (id: string) => boolean | "no-treeshake" | null;
- setResolvedCache: (key: string, entry: string, options: InternalResolveOptions) => void;
- getResolvedCache: (key: string, options: InternalResolveOptions) => string | undefined;
- data: {
- [field: string]: any;
- name: string;
- type: string;
- version: string;
- main: string;
- module: string;
- browser: string | Record<string, string | false>;
- exports: string | Record<string, any> | string[];
- imports: Record<string, any>;
- dependencies: Record<string, string>;
- };
-}
-//#endregion
-//#region src/node/plugins/license.d.ts
-interface LicenseOptions {
- /**
- * The output file name of the license file relative to the output directory.
- * Specify a path that ends with `.json` to output the raw JSON metadata.
- *
- * @default '.vite/license.md'
- */
- fileName: string;
-}
-//#endregion
-//#region src/node/build.d.ts
-interface BuildEnvironmentOptions {
- /**
- * Compatibility transform target. The transform is performed with esbuild
- * and the lowest supported target is es2015. Note this only handles
- * syntax transformation and does not cover polyfills
- *
- * Default: 'baseline-widely-available' - transpile targeting browsers that
- * are included in the Baseline Widely Available on 2025-05-01.
- * (Chrome 107+, Edge 107+, Firefox 104+, Safari 16+).
- *
- * Another special value is 'esnext' - which only performs minimal transpiling
- * (for minification compat).
- *
- * For custom targets, see https://esbuild.github.io/api/#target and
- * https://esbuild.github.io/content-types/#javascript for more details.
- * @default 'baseline-widely-available'
- */
- target?: "baseline-widely-available" | esbuild_TransformOptions["target"] | false;
- /**
- * whether to inject module preload polyfill.
- * Note: does not apply to library mode.
- * @default true
- * @deprecated use `modulePreload.polyfill` instead
- */
- polyfillModulePreload?: boolean;
- /**
- * Configure module preload
- * Note: does not apply to library mode.
- * @default true
- */
- modulePreload?: boolean | ModulePreloadOptions;
- /**
- * Directory relative from `root` where build output will be placed. If the
- * directory exists, it will be removed before the build.
- * @default 'dist'
- */
- outDir?: string;
- /**
- * Directory relative from `outDir` where the built js/css/image assets will
- * be placed.
- * @default 'assets'
- */
- assetsDir?: string;
- /**
- * Static asset files smaller than this number (in bytes) will be inlined as
- * base64 strings. If a callback is passed, a boolean can be returned to opt-in
- * or opt-out of inlining. If nothing is returned the default logic applies.
- *
- * Default limit is `4096` (4 KiB). Set to `0` to disable.
- * @default 4096
- */
- assetsInlineLimit?: number | ((filePath: string, content: Buffer) => boolean | undefined);
- /**
- * Whether to code-split CSS. When enabled, CSS in async chunks will be
- * inlined as strings in the chunk and inserted via dynamically created
- * style tags when the chunk is loaded.
- * @default true
- */
- cssCodeSplit?: boolean;
- /**
- * An optional separate target for CSS minification.
- * As esbuild only supports configuring targets to mainstream
- * browsers, users may need this option when they are targeting
- * a niche browser that comes with most modern JavaScript features
- * but has poor CSS support, e.g. Android WeChat WebView, which
- * doesn't support the #RGBA syntax.
- * @default target
- */
- cssTarget?: esbuild_TransformOptions["target"] | false;
- /**
- * Override CSS minification specifically instead of defaulting to `build.minify`,
- * so you can configure minification for JS and CSS separately.
- * @default 'esbuild'
- */
- cssMinify?: boolean | "esbuild" | "lightningcss";
- /**
- * If `true`, a separate sourcemap file will be created. If 'inline', the
- * sourcemap will be appended to the resulting output file as data URI.
- * 'hidden' works like `true` except that the corresponding sourcemap
- * comments in the bundled files are suppressed.
- * @default false
- */
- sourcemap?: boolean | "inline" | "hidden";
- /**
- * Set to `false` to disable minification, or specify the minifier to use.
- * Available options are 'terser' or 'esbuild'.
- * @default 'esbuild'
- */
- minify?: boolean | "terser" | "esbuild";
- /**
- * Options for terser
- * https://terser.org/docs/api-reference#minify-options
- *
- * In addition, you can also pass a `maxWorkers: number` option to specify the
- * max number of workers to spawn. Defaults to the number of CPUs minus 1.
- */
- terserOptions?: TerserOptions;
- /**
- * Will be merged with internal rollup options.
- * https://rollupjs.org/configuration-options/
- */
- rollupOptions?: RollupOptions;
- /**
- * Options to pass on to `@rollup/plugin-commonjs`
- */
- commonjsOptions?: RollupCommonJSOptions;
- /**
- * Options to pass on to `@rollup/plugin-dynamic-import-vars`
- */
- dynamicImportVarsOptions?: RollupDynamicImportVarsOptions;
- /**
- * Whether to write bundle to disk
- * @default true
- */
- write?: boolean;
- /**
- * Empty outDir on write.
- * @default true when outDir is a sub directory of project root
- */
- emptyOutDir?: boolean | null;
- /**
- * Copy the public directory to outDir on write.
- * @default true
- */
- copyPublicDir?: boolean;
- /**
- * Whether to emit a `.vite/license.md` file that includes all bundled dependencies'
- * licenses. Pass an object to customize the output file name.
- * @default false
- */
- license?: boolean | LicenseOptions;
- /**
- * Whether to emit a .vite/manifest.json in the output dir to map hash-less filenames
- * to their hashed versions. Useful when you want to generate your own HTML
- * instead of using the one generated by Vite.
- *
- * Example:
- *
- * ```json
- * {
- * "main.js": {
- * "file": "main.68fe3fad.js",
- * "css": "main.e6b63442.css",
- * "imports": [...],
- * "dynamicImports": [...]
- * }
- * }
- * ```
- * @default false
- */
- manifest?: boolean | string;
- /**
- * Build in library mode. The value should be the global name of the lib in
- * UMD mode. This will produce esm + cjs + umd bundle formats with default
- * configurations that are suitable for distributing libraries.
- * @default false
- */
- lib?: LibraryOptions | false;
- /**
- * Produce SSR oriented build. Note this requires specifying SSR entry via
- * `rollupOptions.input`.
- * @default false
- */
- ssr?: boolean | string;
- /**
- * Generate SSR manifest for determining style links and asset preload
- * directives in production.
- * @default false
- */
- ssrManifest?: boolean | string;
- /**
- * Emit assets during SSR.
- * @default false
- */
- ssrEmitAssets?: boolean;
- /**
- * Emit assets during build. Frameworks can set environments.ssr.build.emitAssets
- * By default, it is true for the client and false for other environments.
- */
- emitAssets?: boolean;
- /**
- * Set to false to disable reporting compressed chunk sizes.
- * Can slightly improve build speed.
- * @default true
- */
- reportCompressedSize?: boolean;
- /**
- * Adjust chunk size warning limit (in kB).
- * @default 500
- */
- chunkSizeWarningLimit?: number;
- /**
- * Rollup watch options
- * https://rollupjs.org/configuration-options/#watch
- * @default null
- */
- watch?: WatcherOptions | null;
- /**
- * create the Build Environment instance
- */
- createEnvironment?: (name: string, config: ResolvedConfig) => Promise<BuildEnvironment> | BuildEnvironment;
-}
-type BuildOptions = BuildEnvironmentOptions;
-interface LibraryOptions {
- /**
- * Path of library entry
- */
- entry: InputOption;
- /**
- * The name of the exposed global variable. Required when the `formats` option includes
- * `umd` or `iife`
- */
- name?: string;
- /**
- * Output bundle formats
- * @default ['es', 'umd']
- */
- formats?: LibraryFormats[];
- /**
- * The name of the package file output. The default file name is the name option
- * of the project package.json. It can also be defined as a function taking the
- * format as an argument.
- */
- fileName?: string | ((format: ModuleFormat, entryName: string) => string);
- /**
- * The name of the CSS file output if the library imports CSS. Defaults to the
- * same value as `build.lib.fileName` if it's set a string, otherwise it falls
- * back to the name option of the project package.json.
- */
- cssFileName?: string;
-}
-type LibraryFormats = "es" | "cjs" | "umd" | "iife" | "system";
-interface ModulePreloadOptions {
- /**
- * Whether to inject a module preload polyfill.
- * Note: does not apply to library mode.
- * @default true
- */
- polyfill?: boolean;
- /**
- * Resolve the list of dependencies to preload for a given dynamic import
- * @experimental
- */
- resolveDependencies?: ResolveModulePreloadDependenciesFn;
-}
-interface ResolvedModulePreloadOptions {
- polyfill: boolean;
- resolveDependencies?: ResolveModulePreloadDependenciesFn;
-}
-type ResolveModulePreloadDependenciesFn = (filename: string, deps: string[], context: {
- hostId: string;
- hostType: "html" | "js";
-}) => string[];
-interface ResolvedBuildEnvironmentOptions extends Required<Omit<BuildEnvironmentOptions, "polyfillModulePreload">> {
- modulePreload: false | ResolvedModulePreloadOptions;
-}
-interface ResolvedBuildOptions extends Required<Omit<BuildOptions, "polyfillModulePreload">> {
- modulePreload: false | ResolvedModulePreloadOptions;
-}
-/**
-* Bundles a single environment for production.
-* Returns a Promise containing the build result.
-*/
-declare function build(inlineConfig?: InlineConfig): Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
-type RenderBuiltAssetUrl = (filename: string, type: {
- type: "asset" | "public";
- hostId: string;
- hostType: "js" | "css" | "html";
- ssr: boolean;
-}) => string | {
- relative?: boolean;
- runtime?: string;
-} | undefined;
-declare class BuildEnvironment extends BaseEnvironment {
- mode: "build";
- isBuilt: boolean;
- constructor(name: string, config: ResolvedConfig, setup?: {
- options?: EnvironmentOptions;
- });
- init(): Promise<void>;
-}
-interface ViteBuilder {
- environments: Record<string, BuildEnvironment>;
- config: ResolvedConfig;
- buildApp(): Promise<void>;
- build(environment: BuildEnvironment): Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
-}
-interface BuilderOptions {
- /**
- * Whether to share the config instance among environments to align with the behavior of dev server.
- *
- * @default false
- * @experimental
- */
- sharedConfigBuild?: boolean;
- /**
- * Whether to share the plugin instances among environments to align with the behavior of dev server.
- *
- * @default false
- * @experimental
- */
- sharedPlugins?: boolean;
- buildApp?: (builder: ViteBuilder) => Promise<void>;
-}
-type ResolvedBuilderOptions = Required<BuilderOptions>;
-/**
-* Creates a ViteBuilder to orchestrate building multiple environments.
-* @experimental
-*/
-declare function createBuilder(inlineConfig?: InlineConfig, useLegacyBuilder?: null | boolean): Promise<ViteBuilder>;
-type BuildAppHook = (this: MinimalPluginContextWithoutEnvironment, builder: ViteBuilder) => Promise<void>;
-//#endregion
-//#region src/node/environment.d.ts
-type Environment = DevEnvironment | BuildEnvironment | ScanEnvironment | UnknownEnvironment;
-/**
-* Creates a function that hides the complexities of a WeakMap with an initial value
-* to implement object metadata. Used by plugins to implement cross hooks per
-* environment metadata
-*
-* @experimental
-*/
-declare function perEnvironmentState<State>(initial: (environment: Environment) => State): (context: PluginContext) => State;
-//#endregion
-//#region src/node/server/pluginContainer.d.ts
-type SkipInformation = {
- id: string;
- importer: string | undefined;
- plugin: Plugin;
- called?: boolean;
-};
-declare class EnvironmentPluginContainer<Env extends Environment = Environment> {
- private _pluginContextMap;
- private _resolvedRollupOptions?;
- private _processesing;
- private _seenResolves;
- private _moduleNodeToLoadAddedImports;
- getSortedPluginHooks: PluginHookUtils["getSortedPluginHooks"];
- getSortedPlugins: PluginHookUtils["getSortedPlugins"];
- moduleGraph: EnvironmentModuleGraph | undefined;
- watchFiles: Set<string>;
- minimalContext: MinimalPluginContext$1<Env>;
- private _started;
- private _buildStartPromise;
- private _closed;
- private _updateModuleLoadAddedImports;
- private _getAddedImports;
- getModuleInfo(id: string): ModuleInfo | null;
- private handleHookPromise;
- get options(): InputOptions;
- resolveRollupOptions(): Promise<InputOptions>;
- private _getPluginContext;
- private hookParallel;
- buildStart(_options?: InputOptions): Promise<void>;
- resolveId(rawId: string, importer?: string | undefined, options?: {
- attributes?: Record<string, string>;
- custom?: CustomPluginOptions;
- /** @deprecated use `skipCalls` instead */
- skip?: Set<Plugin>;
- skipCalls?: readonly SkipInformation[];
-
- isEntry?: boolean;
- }): Promise<PartialResolvedId | null>;
- load(id: string): Promise<LoadResult | null>;
- transform(code: string, id: string, options?: {
- inMap?: SourceDescription["map"];
- }): Promise<{
- code: string;
- map: SourceMap | {
- mappings: "";
- } | null;
- }>;
- watchChange(id: string, change: {
- event: "create" | "update" | "delete";
- }): Promise<void>;
- close(): Promise<void>;
-}
-declare class BasicMinimalPluginContext<Meta = PluginContextMeta> {
- meta: Meta;
- private _logger;
- constructor(meta: Meta, _logger: Logger);
- debug(rawLog: string | RollupLog | (() => string | RollupLog)): void;
- info(rawLog: string | RollupLog | (() => string | RollupLog)): void;
- warn(rawLog: string | RollupLog | (() => string | RollupLog)): void;
- error(e: string | RollupError): never;
- private _normalizeRawLog;
-}
-declare class MinimalPluginContext$1<T$1 extends Environment = Environment> extends BasicMinimalPluginContext implements MinimalPluginContext {
- environment: T$1;
- constructor(meta: PluginContextMeta, environment: T$1);
-}
-declare class PluginContainer {
- private environments;
- constructor(environments: Record<string, Environment>);
- private _getEnvironment;
- private _getPluginContainer;
- getModuleInfo(id: string): ModuleInfo | null;
- get options(): InputOptions;
- buildStart(_options?: InputOptions): Promise<void>;
- watchChange(id: string, change: {
- event: "create" | "update" | "delete";
- }): Promise<void>;
- resolveId(rawId: string, importer?: string, options?: {
- attributes?: Record<string, string>;
- custom?: CustomPluginOptions;
- /** @deprecated use `skipCalls` instead */
- skip?: Set<Plugin>;
- skipCalls?: readonly SkipInformation[];
- ssr?: boolean;
-
- isEntry?: boolean;
- }): Promise<PartialResolvedId | null>;
- load(id: string, options?: {
- ssr?: boolean;
- }): Promise<LoadResult | null>;
- transform(code: string, id: string, options?: {
- ssr?: boolean;
- environment?: Environment;
- inMap?: SourceDescription["map"];
- }): Promise<{
- code: string;
- map: SourceMap | {
- mappings: "";
- } | null;
- }>;
- close(): Promise<void>;
-}
-/**
-* server.pluginContainer compatibility
-*
-* The default environment is in buildStart, buildEnd, watchChange, and closeBundle hooks,
-* which are called once for all environments, or when no environment is passed in other hooks.
-* The ssrEnvironment is needed for backward compatibility when the ssr flag is passed without
-* an environment. The defaultEnvironment in the main pluginContainer in the server should be
-* the client environment for backward compatibility.
-**/
-//#endregion
-//#region src/node/server/index.d.ts
-interface ServerOptions$1 extends CommonServerOptions {
- /**
- * Configure HMR-specific options (port, host, path & protocol)
- */
- hmr?: HmrOptions | boolean;
- /**
- * Do not start the websocket connection.
- * @experimental
- */
- ws?: false;
- /**
- * Warm-up files to transform and cache the results in advance. This improves the
- * initial page load during server starts and prevents transform waterfalls.
- */
- warmup?: {
- /**
- * The files to be transformed and used on the client-side. Supports glob patterns.
- */
- clientFiles?: string[];
- /**
- * The files to be transformed and used in SSR. Supports glob patterns.
- */
- ssrFiles?: string[];
- };
- /**
- * chokidar watch options or null to disable FS watching
- * https://github.com/paulmillr/chokidar/tree/3.6.0#api
- */
- watch?: WatchOptions | null;
- /**
- * Create Vite dev server to be used as a middleware in an existing server
- * @default false
- */
- middlewareMode?: boolean | {
- /**
- * Parent server instance to attach to
- *
- * This is needed to proxy WebSocket connections to the parent server.
- */
- server: HttpServer;
- };
- /**
- * Options for files served via '/\@fs/'.
- */
- fs?: FileSystemServeOptions;
- /**
- * Origin for the generated asset URLs.
- *
- * @example `http://127.0.0.1:8080`
- */
- origin?: string;
- /**
- * Pre-transform known direct imports
- * @default true
- */
- preTransformRequests?: boolean;
- /**
- * Whether or not to ignore-list source files in the dev server sourcemap, used to populate
- * the [`x_google_ignoreList` source map extension](https://developer.chrome.com/blog/devtools-better-angular-debugging/#the-x_google_ignorelist-source-map-extension).
- *
- * By default, it excludes all paths containing `node_modules`. You can pass `false` to
- * disable this behavior, or, for full control, a function that takes the source path and
- * sourcemap path and returns whether to ignore the source path.
- */
- sourcemapIgnoreList?: false | ((sourcePath: string, sourcemapPath: string) => boolean);
- /**
- * Backward compatibility. The buildStart and buildEnd hooks were called only once for
- * the client environment. This option enables per-environment buildStart and buildEnd hooks.
- * @default false
- * @experimental
- */
- perEnvironmentStartEndDuringDev?: boolean;
- /**
- * Backward compatibility. The watchChange hook was called only once for the client environment.
- * This option enables per-environment watchChange hooks.
- * @default false
- * @experimental
- */
- perEnvironmentWatchChangeDuringDev?: boolean;
- /**
- * Run HMR tasks, by default the HMR propagation is done in parallel for all environments
- * @experimental
- */
- hotUpdateEnvironments?: (server: ViteDevServer, hmr: (environment: DevEnvironment) => Promise<void>) => Promise<void>;
-}
-interface ResolvedServerOptions extends Omit<RequiredExceptFor<ServerOptions$1, "host" | "https" | "proxy" | "hmr" | "ws" | "watch" | "origin" | "hotUpdateEnvironments">, "fs" | "middlewareMode" | "sourcemapIgnoreList"> {
- fs: Required<FileSystemServeOptions>;
- middlewareMode: NonNullable<ServerOptions$1["middlewareMode"]>;
- sourcemapIgnoreList: Exclude<ServerOptions$1["sourcemapIgnoreList"], false | undefined>;
-}
-interface FileSystemServeOptions {
- /**
- * Strictly restrict file accessing outside of allowing paths.
- *
- * Set to `false` to disable the warning
- *
- * @default true
- */
- strict?: boolean;
- /**
- * Restrict accessing files outside the allowed directories.
- *
- * Accepts absolute path or a path relative to project root.
- * Will try to search up for workspace root by default.
- */
- allow?: string[];
- /**
- * Restrict accessing files that matches the patterns.
- *
- * This will have higher priority than `allow`.
- * picomatch patterns are supported.
- *
- * @default ['.env', '.env.*', '*.{crt,pem}', '**\/.git/**']
- */
- deny?: string[];
-}
-type ServerHook = (this: MinimalPluginContextWithoutEnvironment, server: ViteDevServer) => (() => void) | void | Promise<(() => void) | void>;
-type HttpServer = http.Server | Http2SecureServer;
-interface ViteDevServer {
- /**
- * The resolved vite config object
- */
- config: ResolvedConfig;
- /**
- * A connect app instance.
- * - Can be used to attach custom middlewares to the dev server.
- * - Can also be used as the handler function of a custom http server
- * or as a middleware in any connect-style Node.js frameworks
- *
- * https://github.com/senchalabs/connect#use-middleware
- */
- middlewares: Connect.Server;
- /**
- * native Node http server instance
- * will be null in middleware mode
- */
- httpServer: HttpServer | null;
- /**
- * Chokidar watcher instance. If `config.server.watch` is set to `null`,
- * it will not watch any files and calling `add` or `unwatch` will have no effect.
- * https://github.com/paulmillr/chokidar/tree/3.6.0#api
- */
- watcher: FSWatcher;
- /**
- * WebSocket server with `send(payload)` method
- */
- ws: WebSocketServer;
- /**
- * An alias to `server.environments.client.hot`.
- * If you want to interact with all environments, loop over `server.environments`.
- */
- hot: NormalizedHotChannel;
- /**
- * Rollup plugin container that can run plugin hooks on a given file
- */
- pluginContainer: PluginContainer;
- /**
- * Module execution environments attached to the Vite server.
- */
- environments: Record<"client" | "ssr" | (string & {}), DevEnvironment>;
- /**
- * Module graph that tracks the import relationships, url to file mapping
- * and hmr state.
- */
- moduleGraph: ModuleGraph;
- /**
- * The resolved urls Vite prints on the CLI (URL-encoded). Returns `null`
- * in middleware mode or if the server is not listening on any port.
- */
- resolvedUrls: ResolvedServerUrls | null;
- /**
- * Programmatically resolve, load and transform a URL and get the result
- * without going through the http request pipeline.
- */
- transformRequest(url: string, options?: TransformOptions): Promise<TransformResult | null>;
- /**
- * Same as `transformRequest` but only warm up the URLs so the next request
- * will already be cached. The function will never throw as it handles and
- * reports errors internally.
- */
- warmupRequest(url: string, options?: TransformOptions): Promise<void>;
- /**
- * Apply vite built-in HTML transforms and any plugin HTML transforms.
- */
- transformIndexHtml(url: string, html: string, originalUrl?: string): Promise<string>;
- /**
- * Transform module code into SSR format.
- */
- ssrTransform(code: string, inMap: SourceMap | {
- mappings: "";
- } | null, url: string, originalCode?: string): Promise<TransformResult | null>;
- /**
- * Load a given URL as an instantiated module for SSR.
- */
- ssrLoadModule(url: string, opts?: {
- fixStacktrace?: boolean;
- }): Promise<Record<string, any>>;
- /**
- * Returns a fixed version of the given stack
- */
- ssrRewriteStacktrace(stack: string): string;
- /**
- * Mutates the given SSR error by rewriting the stacktrace
- */
- ssrFixStacktrace(e: Error): void;
- /**
- * Triggers HMR for a module in the module graph. You can use the `server.moduleGraph`
- * API to retrieve the module to be reloaded. If `hmr` is false, this is a no-op.
- */
- reloadModule(module: ModuleNode): Promise<void>;
- /**
- * Start the server.
- */
- listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>;
- /**
- * Stop the server.
- */
- close(): Promise<void>;
- /**
- * Print server urls
- */
- printUrls(): void;
- /**
- * Bind CLI shortcuts
- */
- bindCLIShortcuts(options?: BindCLIShortcutsOptions<ViteDevServer>): void;
- /**
- * Restart the server.
- *
- * @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag
- */
- restart(forceOptimize?: boolean): Promise<void>;
- /**
- * Open browser
- */
- openBrowser(): void;
- /**
- * Calling `await server.waitForRequestsIdle(id)` will wait until all static imports
- * are processed. If called from a load or transform plugin hook, the id needs to be
- * passed as a parameter to avoid deadlocks. Calling this function after the first
- * static imports section of the module graph has been processed will resolve immediately.
- */
- waitForRequestsIdle: (ignoredId?: string) => Promise<void>;
-}
-interface ResolvedServerUrls {
- local: string[];
- network: string[];
-}
-declare function createServer(inlineConfig?: InlineConfig | ResolvedConfig): Promise<ViteDevServer>;
-//#endregion
-//#region src/node/plugins/html.d.ts
-interface HtmlTagDescriptor {
- tag: string;
- /**
- * attribute values will be escaped automatically if needed
- */
- attrs?: Record<string, string | boolean | undefined>;
- children?: string | HtmlTagDescriptor[];
- /**
- * default: 'head-prepend'
- */
- injectTo?: "head" | "body" | "head-prepend" | "body-prepend";
-}
-type IndexHtmlTransformResult = string | HtmlTagDescriptor[] | {
- html: string;
- tags: HtmlTagDescriptor[];
-};
-interface IndexHtmlTransformContext {
- /**
- * public path when served
- */
- path: string;
- /**
- * filename on disk
- */
- filename: string;
- server?: ViteDevServer;
- bundle?: OutputBundle;
- chunk?: OutputChunk;
- originalUrl?: string;
-}
-type IndexHtmlTransformHook = (this: MinimalPluginContextWithoutEnvironment, html: string, ctx: IndexHtmlTransformContext) => IndexHtmlTransformResult | void | Promise<IndexHtmlTransformResult | void>;
-type IndexHtmlTransform = IndexHtmlTransformHook | {
- order?: "pre" | "post" | null;
- handler: IndexHtmlTransformHook;
-};
-//#endregion
-//#region src/node/plugins/pluginFilter.d.ts
-type StringFilter<Value = string | RegExp> = Value | Array<Value> | {
- include?: Value | Array<Value>;
- exclude?: Value | Array<Value>;
-};
-//#endregion
-//#region src/node/plugin.d.ts
-/**
-* Vite plugins extends the Rollup plugin interface with a few extra
-* vite-specific options. A valid vite plugin is also a valid Rollup plugin.
-* On the contrary, a Rollup plugin may or may NOT be a valid vite universal
-* plugin, since some Rollup features do not make sense in an unbundled
-* dev server context. That said, as long as a rollup plugin doesn't have strong
-* coupling between its bundle phase and output phase hooks then it should
-* just work (that means, most of them).
-*
-* By default, the plugins are run during both serve and build. When a plugin
-* is applied during serve, it will only run **non output plugin hooks** (see
-* rollup type definition of {@link rollup#PluginHooks}). You can think of the
-* dev server as only running `const bundle = rollup.rollup()` but never calling
-* `bundle.generate()`.
-*
-* A plugin that expects to have different behavior depending on serve/build can
-* export a factory function that receives the command being run via options.
-*
-* If a plugin should be applied only for server or build, a function format
-* config file can be used to conditional determine the plugins to use.
-*
-* The current environment can be accessed from the context for the all non-global
-* hooks (it is not available in config, configResolved, configureServer, etc).
-* It can be a dev, build, or scan environment.
-* Plugins can use this.environment.mode === 'dev' to guard for dev specific APIs.
-*/
-interface PluginContextExtension {
- /**
- * Vite-specific environment instance
- */
- environment: Environment;
-}
-interface PluginContextMetaExtension {
- viteVersion: string;
-}
-interface ConfigPluginContext extends Omit<MinimalPluginContext, "meta" | "environment"> {
- meta: Omit<PluginContextMeta, "watchMode">;
-}
-interface MinimalPluginContextWithoutEnvironment extends Omit<MinimalPluginContext, "environment"> {}
-declare module "rollup" {
- interface MinimalPluginContext extends PluginContextExtension {}
- interface PluginContextMeta extends PluginContextMetaExtension {}
-}
-/**
-* There are two types of plugins in Vite. App plugins and environment plugins.
-* Environment Plugins are defined by a constructor function that will be called
-* once per each environment allowing users to have completely different plugins
-* for each of them. The constructor gets the resolved environment after the server
-* and builder has already been created simplifying config access and cache
-* management for for environment specific plugins.
-* Environment Plugins are closer to regular rollup plugins. They can't define
-* app level hooks (like config, configResolved, configureServer, etc).
-*/
-interface Plugin<A = any> extends Rollup.Plugin<A> {
- /**
- * Perform custom handling of HMR updates.
- * The handler receives an options containing changed filename, timestamp, a
- * list of modules affected by the file change, and the dev server instance.
- *
- * - The hook can return a filtered list of modules to narrow down the update.
- * e.g. for a Vue SFC, we can narrow down the part to update by comparing
- * the descriptors.
- *
- * - The hook can also return an empty array and then perform custom updates
- * by sending a custom hmr payload via environment.hot.send().
- *
- * - If the hook doesn't return a value, the hmr update will be performed as
- * normal.
- */
- hotUpdate?: ObjectHook<(this: MinimalPluginContext & {
- environment: DevEnvironment;
- }, options: HotUpdateOptions) => Array<EnvironmentModuleNode> | void | Promise<Array<EnvironmentModuleNode> | void>>;
- /**
- * extend hooks with ssr flag
- */
- resolveId?: ObjectHook<(this: PluginContext, source: string, importer: string | undefined, options: {
- attributes: Record<string, string>;
- custom?: CustomPluginOptions;
- ssr?: boolean | undefined;
-
- isEntry: boolean;
- }) => Promise<ResolveIdResult> | ResolveIdResult, {
- filter?: {
- id?: StringFilter<RegExp>;
- };
- }>;
- load?: ObjectHook<(this: PluginContext, id: string, options?: {
- ssr?: boolean | undefined;
- }) => Promise<LoadResult> | LoadResult, {
- filter?: {
- id?: StringFilter;
- };
- }>;
- transform?: ObjectHook<(this: TransformPluginContext, code: string, id: string, options?: {
- ssr?: boolean | undefined;
- }) => Promise<Rollup.TransformResult> | Rollup.TransformResult, {
- filter?: {
- id?: StringFilter;
- code?: StringFilter;
- };
- }>;
- /**
- * Opt-in this plugin into the shared plugins pipeline.
- * For backward-compatibility, plugins are re-recreated for each environment
- * during `vite build --app`
- * We have an opt-in per plugin, and a general `builder.sharedPlugins`
- * In a future major, we'll flip the default to be shared by default
- * @experimental
- */
- sharedDuringBuild?: boolean;
- /**
- * Opt-in this plugin into per-environment buildStart and buildEnd during dev.
- * For backward-compatibility, the buildStart hook is called only once during
- * dev, for the client environment. Plugins can opt-in to be called
- * per-environment, aligning with the build hook behavior.
- * @experimental
- */
- perEnvironmentStartEndDuringDev?: boolean;
- /**
- * Opt-in this plugin into per-environment watchChange during dev.
- * For backward-compatibility, the watchChange hook is called only once during
- * dev, for the client environment. Plugins can opt-in to be called
- * per-environment, aligning with the watchChange hook behavior.
- * @experimental
- */
- perEnvironmentWatchChangeDuringDev?: boolean;
- /**
- * Enforce plugin invocation tier similar to webpack loaders. Hooks ordering
- * is still subject to the `order` property in the hook object.
- *
- * Plugin invocation order:
- * - alias resolution
- * - `enforce: 'pre'` plugins
- * - vite core plugins
- * - normal plugins
- * - vite build plugins
- * - `enforce: 'post'` plugins
- * - vite build post plugins
- */
- enforce?: "pre" | "post";
- /**
- * Apply the plugin only for serve or build, or on certain conditions.
- */
- apply?: "serve" | "build" | ((this: void, config: UserConfig, env: ConfigEnv) => boolean);
- /**
- * Define environments where this plugin should be active
- * By default, the plugin is active in all environments
- * @experimental
- */
- applyToEnvironment?: (environment: PartialEnvironment) => boolean | Promise<boolean> | PluginOption;
- /**
- * Modify vite config before it's resolved. The hook can either mutate the
- * passed-in config directly, or return a partial config object that will be
- * deeply merged into existing config.
- *
- * Note: User plugins are resolved before running this hook so injecting other
- * plugins inside the `config` hook will have no effect.
- */
- config?: ObjectHook<(this: ConfigPluginContext, config: UserConfig, env: ConfigEnv) => Omit<UserConfig, "plugins"> | null | void | Promise<Omit<UserConfig, "plugins"> | null | void>>;
- /**
- * Modify environment configs before it's resolved. The hook can either mutate the
- * passed-in environment config directly, or return a partial config object that will be
- * deeply merged into existing config.
- * This hook is called for each environment with a partially resolved environment config
- * that already accounts for the default environment config values set at the root level.
- * If plugins need to modify the config of a given environment, they should do it in this
- * hook instead of the config hook. Leaving the config hook only for modifying the root
- * default environment config.
- */
- configEnvironment?: ObjectHook<(this: ConfigPluginContext, name: string, config: EnvironmentOptions, env: ConfigEnv & {
- /**
- * Whether this environment is SSR environment and `ssr.target` is set to `'webworker'`.
- * Only intended to be used for backward compatibility.
- */
- isSsrTargetWebworker?: boolean;
- }) => EnvironmentOptions | null | void | Promise<EnvironmentOptions | null | void>>;
- /**
- * Use this hook to read and store the final resolved vite config.
- */
- configResolved?: ObjectHook<(this: MinimalPluginContextWithoutEnvironment, config: ResolvedConfig) => void | Promise<void>>;
- /**
- * Configure the vite server. The hook receives the {@link ViteDevServer}
- * instance. This can also be used to store a reference to the server
- * for use in other hooks.
- *
- * The hooks will be called before internal middlewares are applied. A hook
- * can return a post hook that will be called after internal middlewares
- * are applied. Hook can be async functions and will be called in series.
- */
- configureServer?: ObjectHook<ServerHook>;
- /**
- * Configure the preview server. The hook receives the {@link PreviewServer}
- * instance. This can also be used to store a reference to the server
- * for use in other hooks.
- *
- * The hooks are called before other middlewares are applied. A hook can
- * return a post hook that will be called after other middlewares are
- * applied. Hooks can be async functions and will be called in series.
- */
- configurePreviewServer?: ObjectHook<PreviewServerHook>;
- /**
- * Transform index.html.
- * The hook receives the following arguments:
- *
- * - html: string
- * - ctx: IndexHtmlTransformContext, which contains:
- * - path: public path when served
- * - filename: filename on disk
- * - server?: ViteDevServer (only present during serve)
- * - bundle?: rollup.OutputBundle (only present during build)
- * - chunk?: rollup.OutputChunk
- * - originalUrl?: string
- *
- * It can either return a transformed string, or a list of html tag
- * descriptors that will be injected into the `<head>` or `<body>`.
- *
- * By default the transform is applied **after** vite's internal html
- * transform. If you need to apply the transform before vite, use an object:
- * `{ order: 'pre', handler: hook }`
- */
- transformIndexHtml?: IndexHtmlTransform;
- /**
- * Build Environments
- *
- * @experimental
- */
- buildApp?: ObjectHook<BuildAppHook>;
- /**
- * Perform custom handling of HMR updates.
- * The handler receives a context containing changed filename, timestamp, a
- * list of modules affected by the file change, and the dev server instance.
- *
- * - The hook can return a filtered list of modules to narrow down the update.
- * e.g. for a Vue SFC, we can narrow down the part to update by comparing
- * the descriptors.
- *
- * - The hook can also return an empty array and then perform custom updates
- * by sending a custom hmr payload via server.ws.send().
- *
- * - If the hook doesn't return a value, the hmr update will be performed as
- * normal.
- */
- handleHotUpdate?: ObjectHook<(this: MinimalPluginContextWithoutEnvironment, ctx: HmrContext) => Array<ModuleNode> | void | Promise<Array<ModuleNode> | void>>;
-}
-type HookHandler<T$1> = T$1 extends ObjectHook<infer H> ? H : T$1;
-type PluginWithRequiredHook<K$1 extends keyof Plugin> = Plugin & { [P in K$1]: NonNullable<Plugin[P]> };
-type Thenable<T$1> = T$1 | Promise<T$1>;
-type FalsyPlugin = false | null | undefined;
-type PluginOption = Thenable<Plugin | FalsyPlugin | PluginOption[]>;
-/**
-* @experimental
-*/
-declare function perEnvironmentPlugin(name: string, applyToEnvironment: (environment: PartialEnvironment) => boolean | Promise<boolean> | PluginOption): Plugin;
-//#endregion
-//#region src/node/plugins/css.d.ts
-interface CSSOptions {
- /**
- * Using lightningcss is an experimental option to handle CSS modules,
- * assets and imports via Lightning CSS. It requires to install it as a
- * peer dependency.
- *
- * @default 'postcss'
- * @experimental
- */
- transformer?: "postcss" | "lightningcss";
- /**
- * https://github.com/css-modules/postcss-modules
- */
- modules?: CSSModulesOptions | false;
- /**
- * Options for preprocessors.
- *
- * In addition to options specific to each processors, Vite supports `additionalData` option.
- * The `additionalData` option can be used to inject extra code for each style content.
- */
- preprocessorOptions?: {
- scss?: SassPreprocessorOptions;
- sass?: SassPreprocessorOptions;
- less?: LessPreprocessorOptions;
- styl?: StylusPreprocessorOptions;
- stylus?: StylusPreprocessorOptions;
- };
- /**
- * If this option is set, preprocessors will run in workers when possible.
- * `true` means the number of CPUs minus 1.
- *
- * @default true
- */
- preprocessorMaxWorkers?: number | true;
- postcss?: string | (PostCSS.ProcessOptions & {
- plugins?: PostCSS.AcceptedPlugin[];
- });
- /**
- * Enables css sourcemaps during dev
- * @default false
- * @experimental
- */
- devSourcemap?: boolean;
- /**
- * @experimental
- */
- lightningcss?: lightningcssOptions_LightningCSSOptions;
-}
-interface CSSModulesOptions {
- getJSON?: (cssFileName: string, json: Record<string, string>, outputFileName: string) => void;
- scopeBehaviour?: "global" | "local";
- globalModulePaths?: RegExp[];
- exportGlobals?: boolean;
- generateScopedName?: string | ((name: string, filename: string, css: string) => string);
- hashPrefix?: string;
- /**
- * default: undefined
- */
- localsConvention?: "camelCase" | "camelCaseOnly" | "dashes" | "dashesOnly" | ((originalClassName: string, generatedClassName: string, inputFile: string) => string);
-}
-type ResolvedCSSOptions = Omit<CSSOptions, "lightningcss"> & Required<Pick<CSSOptions, "transformer" | "devSourcemap">> & {
- lightningcss?: lightningcssOptions_LightningCSSOptions;
-};
-interface PreprocessCSSResult {
- code: string;
- map?: SourceMapInput;
- modules?: Record<string, string>;
- deps?: Set<string>;
-}
-/**
-* @experimental
-*/
-declare function preprocessCSS(code: string, filename: string, config: ResolvedConfig): Promise<PreprocessCSSResult>;
-declare function formatPostcssSourceMap(rawMap: ExistingRawSourceMap, file: string): Promise<ExistingRawSourceMap>;
-type PreprocessorAdditionalDataResult = string | {
- content: string;
- map?: ExistingRawSourceMap;
-};
-type PreprocessorAdditionalData = string | ((source: string, filename: string) => PreprocessorAdditionalDataResult | Promise<PreprocessorAdditionalDataResult>);
-type SassPreprocessorOptions = {
- additionalData?: PreprocessorAdditionalData;
-} & SassModernPreprocessBaseOptions;
-type LessPreprocessorOptions = {
- additionalData?: PreprocessorAdditionalData;
-} & LessPreprocessorBaseOptions;
-type StylusPreprocessorOptions = {
- additionalData?: PreprocessorAdditionalData;
-} & StylusPreprocessorBaseOptions;
-//#endregion
-//#region src/node/plugins/esbuild.d.ts
-interface ESBuildOptions extends esbuild_TransformOptions {
- include?: string | RegExp | ReadonlyArray<string | RegExp>;
- exclude?: string | RegExp | ReadonlyArray<string | RegExp>;
- jsxInject?: string;
- /**
- * This option is not respected. Use `build.minify` instead.
- */
- minify?: never;
-}
-type ESBuildTransformResult = Omit<esbuild_TransformResult, "map"> & {
- map: SourceMap;
-};
-declare function transformWithEsbuild(code: string, filename: string, options?: esbuild_TransformOptions, inMap?: object, config?: ResolvedConfig, watcher?: FSWatcher): Promise<ESBuildTransformResult>;
-//#endregion
-//#region src/node/plugins/json.d.ts
-interface JsonOptions {
- /**
- * Generate a named export for every property of the JSON object
- * @default true
- */
- namedExports?: boolean;
- /**
- * Generate performant output as JSON.parse("stringified").
- *
- * When set to 'auto', the data will be stringified only if the data is bigger than 10kB.
- * @default 'auto'
- */
- stringify?: boolean | "auto";
-}
-//#endregion
-//#region src/node/ssr/index.d.ts
-type SSRTarget = "node" | "webworker";
-type SsrDepOptimizationConfig = DepOptimizationConfig;
-interface SSROptions {
- noExternal?: string | RegExp | (string | RegExp)[] | true;
- external?: string[] | true;
- /**
- * Define the target for the ssr build. The browser field in package.json
- * is ignored for node but used if webworker is the target
- * This option will be removed in a future major version
- * @default 'node'
- */
- target?: SSRTarget;
- /**
- * Control over which dependencies are optimized during SSR and esbuild options
- * During build:
- * no external CJS dependencies are optimized by default
- * During dev:
- * explicit no external CJS dependencies are optimized by default
- * @experimental
- */
- optimizeDeps?: SsrDepOptimizationConfig;
- resolve?: {
- /**
- * Conditions that are used in the plugin pipeline. The default value is the root config's `resolve.conditions`.
- *
- * Use this to override the default ssr conditions for the ssr build.
- *
- * @default rootConfig.resolve.conditions
- */
- conditions?: string[];
- /**
- * Conditions that are used during ssr import (including `ssrLoadModule`) of externalized dependencies.
- *
- * @default ['node', 'module-sync']
- */
- externalConditions?: string[];
- mainFields?: string[];
- };
-}
-interface ResolvedSSROptions extends SSROptions {
- target: SSRTarget;
- optimizeDeps: SsrDepOptimizationConfig;
-}
-//#endregion
-//#region src/node/config.d.ts
-interface ConfigEnv {
- /**
- * 'serve': during dev (`vite` command)
- * 'build': when building for production (`vite build` command)
- */
- command: "build" | "serve";
- mode: string;
- isSsrBuild?: boolean;
- isPreview?: boolean;
-}
-/**
-* spa: include SPA fallback middleware and configure sirv with `single: true` in preview
-*
-* mpa: only include non-SPA HTML middlewares
-*
-* custom: don't include HTML middlewares
-*/
-type AppType = "spa" | "mpa" | "custom";
-type UserConfigFnObject = (env: ConfigEnv) => UserConfig;
-type UserConfigFnPromise = (env: ConfigEnv) => Promise<UserConfig>;
-type UserConfigFn = (env: ConfigEnv) => UserConfig | Promise<UserConfig>;
-type UserConfigExport = UserConfig | Promise<UserConfig> | UserConfigFnObject | UserConfigFnPromise | UserConfigFn;
-/**
-* Type helper to make it easier to use vite.config.ts
-* accepts a direct {@link UserConfig} object, or a function that returns it.
-* The function receives a {@link ConfigEnv} object.
-*/
-declare function defineConfig(config: UserConfig): UserConfig;
-declare function defineConfig(config: Promise<UserConfig>): Promise<UserConfig>;
-declare function defineConfig(config: UserConfigFnObject): UserConfigFnObject;
-declare function defineConfig(config: UserConfigFnPromise): UserConfigFnPromise;
-declare function defineConfig(config: UserConfigFn): UserConfigFn;
-declare function defineConfig(config: UserConfigExport): UserConfigExport;
-interface CreateDevEnvironmentContext {
- ws: WebSocketServer;
-}
-interface DevEnvironmentOptions {
- /**
- * Files to be pre-transformed. Supports glob patterns.
- */
- warmup?: string[];
- /**
- * Pre-transform known direct imports
- * defaults to true for the client environment, false for the rest
- */
- preTransformRequests?: boolean;
- /**
- * Enables sourcemaps during dev
- * @default { js: true }
- * @experimental
- */
- sourcemap?: boolean | {
- js?: boolean;
- css?: boolean;
- };
- /**
- * Whether or not to ignore-list source files in the dev server sourcemap, used to populate
- * the [`x_google_ignoreList` source map extension](https://developer.chrome.com/blog/devtools-better-angular-debugging/#the-x_google_ignorelist-source-map-extension).
- *
- * By default, it excludes all paths containing `node_modules`. You can pass `false` to
- * disable this behavior, or, for full control, a function that takes the source path and
- * sourcemap path and returns whether to ignore the source path.
- */
- sourcemapIgnoreList?: false | ((sourcePath: string, sourcemapPath: string) => boolean);
- /**
- * create the Dev Environment instance
- */
- createEnvironment?: (name: string, config: ResolvedConfig, context: CreateDevEnvironmentContext) => Promise<DevEnvironment> | DevEnvironment;
- /**
- * For environments that support a full-reload, like the client, we can short-circuit when
- * restarting the server throwing early to stop processing current files. We avoided this for
- * SSR requests. Maybe this is no longer needed.
- * @experimental
- */
- recoverable?: boolean;
- /**
- * For environments associated with a module runner.
- * By default, it is false for the client environment and true for non-client environments.
- * This option can also be used instead of the removed config.experimental.skipSsrTransform.
- */
- moduleRunnerTransform?: boolean;
-}
-type ResolvedDevEnvironmentOptions = Omit<Required<DevEnvironmentOptions>, "sourcemapIgnoreList"> & {
- sourcemapIgnoreList: Exclude<DevEnvironmentOptions["sourcemapIgnoreList"], false | undefined>;
-};
-type AllResolveOptions = ResolveOptions & {
- alias?: AliasOptions;
-};
-interface SharedEnvironmentOptions {
- /**
- * Define global variable replacements.
- * Entries will be defined on `window` during dev and replaced during build.
- */
- define?: Record<string, any>;
- /**
- * Configure resolver
- */
- resolve?: EnvironmentResolveOptions;
- /**
- * Define if this environment is used for Server-Side Rendering
- * @default 'server' if it isn't the client environment
- */
- consumer?: "client" | "server";
- /**
- * If true, `process.env` referenced in code will be preserved as-is and evaluated in runtime.
- * Otherwise, it is statically replaced as an empty object.
- */
- keepProcessEnv?: boolean;
- /**
- * Optimize deps config
- */
- optimizeDeps?: DepOptimizationOptions;
-}
-interface EnvironmentOptions extends SharedEnvironmentOptions {
- /**
- * Dev specific options
- */
- dev?: DevEnvironmentOptions;
- /**
- * Build specific options
- */
- build?: BuildEnvironmentOptions;
-}
-type ResolvedResolveOptions = Required<ResolveOptions>;
-type ResolvedEnvironmentOptions = {
- define?: Record<string, any>;
- resolve: ResolvedResolveOptions;
- consumer: "client" | "server";
- keepProcessEnv?: boolean;
- optimizeDeps: DepOptimizationOptions;
- dev: ResolvedDevEnvironmentOptions;
- build: ResolvedBuildEnvironmentOptions;
- plugins: readonly Plugin[];
-};
-type DefaultEnvironmentOptions = Omit<EnvironmentOptions, "consumer" | "resolve" | "keepProcessEnv"> & {
- resolve?: AllResolveOptions;
-};
-interface UserConfig extends DefaultEnvironmentOptions {
- /**
- * Project root directory. Can be an absolute path, or a path relative from
- * the location of the config file itself.
- * @default process.cwd()
- */
- root?: string;
- /**
- * Base public path when served in development or production.
- * @default '/'
- */
- base?: string;
- /**
- * Directory to serve as plain static assets. Files in this directory are
- * served and copied to build dist dir as-is without transform. The value
- * can be either an absolute file system path or a path relative to project root.
- *
- * Set to `false` or an empty string to disable copied static assets to build dist dir.
- * @default 'public'
- */
- publicDir?: string | false;
- /**
- * Directory to save cache files. Files in this directory are pre-bundled
- * deps or some other cache files that generated by vite, which can improve
- * the performance. You can use `--force` flag or manually delete the directory
- * to regenerate the cache files. The value can be either an absolute file
- * system path or a path relative to project root.
- * Default to `.vite` when no `package.json` is detected.
- * @default 'node_modules/.vite'
- */
- cacheDir?: string;
- /**
- * Explicitly set a mode to run in. This will override the default mode for
- * each command, and can be overridden by the command line --mode option.
- */
- mode?: string;
- /**
- * Array of vite plugins to use.
- */
- plugins?: PluginOption[];
- /**
- * HTML related options
- */
- html?: HTMLOptions;
- /**
- * CSS related options (preprocessors and CSS modules)
- */
- css?: CSSOptions;
- /**
- * JSON loading options
- */
- json?: JsonOptions;
- /**
- * Transform options to pass to esbuild.
- * Or set to `false` to disable esbuild.
- */
- esbuild?: ESBuildOptions | false;
- /**
- * Specify additional picomatch patterns to be treated as static assets.
- */
- assetsInclude?: string | RegExp | (string | RegExp)[];
- /**
- * Builder specific options
- * @experimental
- */
- builder?: BuilderOptions;
- /**
- * Server specific options, e.g. host, port, https...
- */
- server?: ServerOptions$1;
- /**
- * Preview specific options, e.g. host, port, https...
- */
- preview?: PreviewOptions;
- /**
- * Experimental features
- *
- * Features under this field could change in the future and might NOT follow semver.
- * Please be careful and always pin Vite's version when using them.
- * @experimental
- */
- experimental?: ExperimentalOptions;
- /**
- * Options to opt-in to future behavior
- */
- future?: FutureOptions | "warn";
- /**
- * Legacy options
- *
- * Features under this field only follow semver for patches, they could be removed in a
- * future minor version. Please always pin Vite's version to a minor when using them.
- */
- legacy?: LegacyOptions;
- /**
- * Log level.
- * @default 'info'
- */
- logLevel?: LogLevel;
- /**
- * Custom logger.
- */
- customLogger?: Logger;
- /**
- * @default true
- */
- clearScreen?: boolean;
- /**
- * Environment files directory. Can be an absolute path, or a path relative from
- * root.
- * @default root
- */
- envDir?: string | false;
- /**
- * Env variables starts with `envPrefix` will be exposed to your client source code via import.meta.env.
- * @default 'VITE_'
- */
- envPrefix?: string | string[];
- /**
- * Worker bundle options
- */
- worker?: {
- /**
- * Output format for worker bundle
- * @default 'iife'
- */
- format?: "es" | "iife";
- /**
- * Vite plugins that apply to worker bundle. The plugins returned by this function
- * should be new instances every time it is called, because they are used for each
- * rollup worker bundling process.
- */
- plugins?: () => PluginOption[];
- /**
- * Rollup options to build worker bundle
- */
- rollupOptions?: Omit<RollupOptions, "plugins" | "input" | "onwarn" | "preserveEntrySignatures">;
- };
- /**
- * Dep optimization options
- */
- optimizeDeps?: DepOptimizationOptions;
- /**
- * SSR specific options
- * We could make SSROptions be a EnvironmentOptions if we can abstract
- * external/noExternal for environments in general.
- */
- ssr?: SSROptions;
- /**
- * Environment overrides
- */
- environments?: Record<string, EnvironmentOptions>;
- /**
- * Whether your application is a Single Page Application (SPA),
- * a Multi-Page Application (MPA), or Custom Application (SSR
- * and frameworks with custom HTML handling)
- * @default 'spa'
- */
- appType?: AppType;
-}
-interface HTMLOptions {
- /**
- * A nonce value placeholder that will be used when generating script/style tags.
- *
- * Make sure that this placeholder will be replaced with a unique value for each request by the server.
- */
- cspNonce?: string;
-}
-interface FutureOptions {
- removePluginHookHandleHotUpdate?: "warn";
- removePluginHookSsrArgument?: "warn";
- removeServerModuleGraph?: "warn";
- removeServerReloadModule?: "warn";
- removeServerPluginContainer?: "warn";
- removeServerHot?: "warn";
- removeServerTransformRequest?: "warn";
- removeServerWarmupRequest?: "warn";
- removeSsrLoadModule?: "warn";
-}
-interface ExperimentalOptions {
- /**
- * Append fake `&lang.(ext)` when queries are specified, to preserve the file extension for following plugins to process.
- *
- * @experimental
- * @default false
- */
- importGlobRestoreExtension?: boolean;
- /**
- * Allow finegrain control over assets and public files paths
- *
- * @experimental
- */
- renderBuiltUrl?: RenderBuiltAssetUrl;
- /**
- * Enables support of HMR partial accept via `import.meta.hot.acceptExports`.
- *
- * @experimental
- * @default false
- */
- hmrPartialAccept?: boolean;
-}
-interface LegacyOptions {
- /**
- * In Vite 6.0.8 and below, WebSocket server was able to connect from any web pages. However,
- * that could be exploited by a malicious web page.
- *
- * In Vite 6.0.9+, the WebSocket server now requires a token to connect from a web page.
- * But this may break some plugins and frameworks that connects to the WebSocket server
- * on their own. Enabling this option will make Vite skip the token check.
- *
- * **We do not recommend enabling this option unless you are sure that you are fine with
- * that security weakness.**
- */
- skipWebSocketTokenCheck?: boolean;
-}
-interface ResolvedWorkerOptions {
- format: "es" | "iife";
- plugins: (bundleChain: string[]) => Promise<ResolvedConfig>;
- rollupOptions: RollupOptions;
-}
-interface InlineConfig extends UserConfig {
- configFile?: string | false;
- /** @experimental */
- configLoader?: "bundle" | "runner" | "native";
- /** @deprecated */
- envFile?: false;
- forceOptimizeDeps?: boolean;
-}
-interface ResolvedConfig extends Readonly<Omit<UserConfig, "plugins" | "css" | "json" | "assetsInclude" | "optimizeDeps" | "worker" | "build" | "dev" | "environments" | "experimental" | "future" | "server" | "preview"> & {
- configFile: string | undefined;
- configFileDependencies: string[];
- inlineConfig: InlineConfig;
- root: string;
- base: string;
- publicDir: string;
- cacheDir: string;
- command: "build" | "serve";
- mode: string;
- isWorker: boolean;
- isProduction: boolean;
- envDir: string | false;
- env: Record<string, any>;
- resolve: Required<ResolveOptions> & {
- alias: Alias[];
- };
- plugins: readonly Plugin[];
- css: ResolvedCSSOptions;
- json: Required<JsonOptions>;
- esbuild: ESBuildOptions | false;
- server: ResolvedServerOptions;
- dev: ResolvedDevEnvironmentOptions;
- /** @experimental */
- builder: ResolvedBuilderOptions | undefined;
- build: ResolvedBuildOptions;
- preview: ResolvedPreviewOptions;
- ssr: ResolvedSSROptions;
- assetsInclude: (file: string) => boolean;
- logger: Logger;
- /**
- * Create an internal resolver to be used in special scenarios, e.g.
- * optimizer & handling css `@imports`.
- *
- * This API is deprecated. It only works for the client and ssr
- * environments. The `aliasOnly` option is also not being used anymore.
- * Plugins should move to `createIdResolver(environment.config)` instead.
- *
- * @deprecated Use `createIdResolver` from `vite` instead.
- */
- createResolver: (options?: Partial<InternalResolveOptions>) => ResolveFn;
- optimizeDeps: DepOptimizationOptions;
- worker: ResolvedWorkerOptions;
- appType: AppType;
- experimental: RequiredExceptFor<ExperimentalOptions, "renderBuiltUrl">;
- future: FutureOptions | undefined;
- environments: Record<string, ResolvedEnvironmentOptions>;
- /**
- * The token to connect to the WebSocket server from browsers.
- *
- * We recommend using `import.meta.hot` rather than connecting
- * to the WebSocket server directly.
- * If you have a usecase that requires connecting to the WebSocket
- * server, please create an issue so that we can discuss.
- *
- * @deprecated
- */
- webSocketToken: string;
-} & PluginHookUtils> {}
-interface PluginHookUtils {
- getSortedPlugins: <K$1 extends keyof Plugin>(hookName: K$1) => PluginWithRequiredHook<K$1>[];
- getSortedPluginHooks: <K$1 extends keyof Plugin>(hookName: K$1) => NonNullable<HookHandler<Plugin[K$1]>>[];
-}
-type ResolveFn = (id: string, importer?: string, aliasOnly?: boolean, ssr?: boolean) => Promise<string | undefined>;
-declare function resolveConfig(inlineConfig: InlineConfig, command: "build" | "serve", defaultMode?: string, defaultNodeEnv?: string, isPreview?: boolean, patchConfig?: ((config: ResolvedConfig) => void) | undefined, patchPlugins?: ((resolvedPlugins: Plugin[]) => void) | undefined): Promise<ResolvedConfig>;
-declare function sortUserPlugins(plugins: (Plugin | Plugin[])[] | undefined): [Plugin[], Plugin[], Plugin[]];
-declare function loadConfigFromFile(configEnv: ConfigEnv, configFile?: string, configRoot?: string, logLevel?: LogLevel, customLogger?: Logger, configLoader?: "bundle" | "runner" | "native"): Promise<{
- path: string;
- config: UserConfig;
- dependencies: string[];
-} | null>;
-//#endregion
-//#region src/node/idResolver.d.ts
-type ResolveIdFn = (environment: PartialEnvironment, id: string, importer?: string, aliasOnly?: boolean) => Promise<string | undefined>;
-/**
-* Create an internal resolver to be used in special scenarios, e.g.
-* optimizer and handling css @imports
-*/
-declare function createIdResolver(config: ResolvedConfig, options?: Partial<InternalResolveOptions>): ResolveIdFn;
-//#endregion
-//#region src/node/server/middlewares/error.d.ts
-declare function buildErrorMessage(err: RollupError, args?: string[], includeStack?: boolean): string;
-//#endregion
-//#region src/node/ssr/runtime/serverModuleRunner.d.ts
-/**
-* @experimental
-*/
-interface ServerModuleRunnerOptions extends Omit<ModuleRunnerOptions, "root" | "fetchModule" | "hmr" | "transport"> {
- /**
- * Disable HMR or configure HMR logger.
- */
- hmr?: false | {
- logger?: ModuleRunnerHmr["logger"];
- };
- /**
- * Provide a custom module evaluator. This controls how the code is executed.
- */
- evaluator?: ModuleEvaluator;
-}
-declare const createServerModuleRunnerTransport: (options: {
- channel: NormalizedServerHotChannel;
-}) => ModuleRunnerTransport;
-/**
-* Create an instance of the Vite SSR runtime that support HMR.
-* @experimental
-*/
-declare function createServerModuleRunner(environment: DevEnvironment, options?: ServerModuleRunnerOptions): ModuleRunner;
-//#endregion
-//#region src/node/server/environments/runnableEnvironment.d.ts
-declare function createRunnableDevEnvironment(name: string, config: ResolvedConfig, context?: RunnableDevEnvironmentContext): RunnableDevEnvironment;
-interface RunnableDevEnvironmentContext extends Omit<DevEnvironmentContext, "hot"> {
- runner?: (environment: RunnableDevEnvironment, options?: ServerModuleRunnerOptions) => ModuleRunner;
- runnerOptions?: ServerModuleRunnerOptions;
- hot?: boolean;
-}
-declare function isRunnableDevEnvironment(environment: Environment): environment is RunnableDevEnvironment;
-declare class RunnableDevEnvironment extends DevEnvironment {
- private _runner;
- private _runnerFactory;
- private _runnerOptions;
- constructor(name: string, config: ResolvedConfig, context: RunnableDevEnvironmentContext);
- get runner(): ModuleRunner;
- close(): Promise<void>;
-}
-//#endregion
-//#region src/node/server/environments/fetchableEnvironments.d.ts
-interface FetchableDevEnvironmentContext extends DevEnvironmentContext {
- handleRequest(request: Request): Promise<Response> | Response;
-}
-declare function createFetchableDevEnvironment(name: string, config: ResolvedConfig, context: FetchableDevEnvironmentContext): FetchableDevEnvironment;
-declare function isFetchableDevEnvironment(environment: Environment): environment is FetchableDevEnvironment;
-declare class FetchableDevEnvironment extends DevEnvironment {
- private _handleRequest;
- constructor(name: string, config: ResolvedConfig, context: FetchableDevEnvironmentContext);
- dispatchFetch(request: Request): Promise<Response>;
-}
-//#endregion
-//#region src/node/ssr/runnerImport.d.ts
-interface RunnerImportResult<T$1> {
- module: T$1;
- dependencies: string[];
-}
-/**
-* Import any file using the default Vite environment.
-* @experimental
-*/
-declare function runnerImport<T$1>(moduleId: string, inlineConfig?: InlineConfig): Promise<RunnerImportResult<T$1>>;
-//#endregion
-//#region src/node/ssr/fetchModule.d.ts
-interface FetchModuleOptions {
- cached?: boolean;
- inlineSourceMap?: boolean;
- startOffset?: number;
-}
-/**
-* Fetch module information for Vite runner.
-* @experimental
-*/
-declare function fetchModule(environment: DevEnvironment, url: string, importer?: string, options?: FetchModuleOptions): Promise<moduleRunner_FetchResult>;
-//#endregion
-//#region src/node/ssr/ssrTransform.d.ts
-interface ModuleRunnerTransformOptions {
- json?: {
- stringify?: boolean;
- };
-}
-declare function ssrTransform(code: string, inMap: SourceMap | {
- mappings: "";
-} | null, url: string, originalCode: string, options?: ModuleRunnerTransformOptions): Promise<TransformResult | null>;
-//#endregion
-//#region src/node/constants.d.ts
-declare const VERSION: string;
-declare const DEFAULT_CLIENT_MAIN_FIELDS: readonly string[];
-declare const DEFAULT_SERVER_MAIN_FIELDS: readonly string[];
-declare const DEFAULT_CLIENT_CONDITIONS: readonly string[];
-declare const DEFAULT_SERVER_CONDITIONS: readonly string[];
-declare const DEFAULT_EXTERNAL_CONDITIONS: readonly string[];
-declare const defaultAllowedOrigins: RegExp;
-//#endregion
-//#region src/node/utils.d.ts
-/**
-* Inlined to keep `@rollup/pluginutils` in devDependencies
-*/
-type FilterPattern = ReadonlyArray<string | RegExp> | string | RegExp | null;
-declare const createFilter: (include?: FilterPattern, exclude?: FilterPattern, options?: {
- resolve?: string | false | null;
-}) => (id: string | unknown) => boolean;
-declare const rollupVersion: string;
-declare function normalizePath(id: string): string;
-declare const isCSSRequest: (request: string) => boolean;
-declare function mergeConfig<D extends Record<string, any>, O extends Record<string, any>>(defaults: D extends Function ? never : D, overrides: O extends Function ? never : O, isRoot?: boolean): Record<string, any>;
-declare function mergeAlias(a?: AliasOptions, b?: AliasOptions): AliasOptions | undefined;
-//#endregion
-//#region src/node/server/send.d.ts
-interface SendOptions {
- etag?: string;
- cacheControl?: string;
- headers?: OutgoingHttpHeaders;
- map?: SourceMap | {
- mappings: "";
- } | null;
-}
-declare function send(req: http.IncomingMessage, res: ServerResponse, content: string | Buffer, type: string, options: SendOptions): void;
-//#endregion
-//#region src/node/server/searchRoot.d.ts
-/**
-* Search up for the nearest workspace root
-*/
-declare function searchForWorkspaceRoot(current: string, root?: string): string;
-//#endregion
-//#region src/node/server/middlewares/static.d.ts
-/**
-* Check if the url is allowed to be served, via the `server.fs` config.
-* @deprecated Use the `isFileLoadingAllowed` function instead.
-*/
-declare function isFileServingAllowed(config: ResolvedConfig, url: string): boolean;
-declare function isFileServingAllowed(url: string, server: ViteDevServer): boolean;
-/**
-* Warning: parameters are not validated, only works with normalized absolute paths
-*/
-declare function isFileLoadingAllowed(config: ResolvedConfig, filePath: string): boolean;
-//#endregion
-//#region src/node/env.d.ts
-declare function loadEnv(mode: string, envDir: string | false, prefixes?: string | string[]): Record<string, string>;
-declare function resolveEnvPrefix({
- envPrefix
-}: UserConfig): string[];
-//#endregion
-//#region src/node/plugins/manifest.d.ts
-type Manifest = Record<string, ManifestChunk>;
-interface ManifestChunk {
- /**
- * The input file name of this chunk / asset if known
- */
- src?: string;
- /**
- * The output file name of this chunk / asset
- */
- file: string;
- /**
- * The list of CSS files imported by this chunk
- *
- * This field is only present in JS chunks.
- */
- css?: string[];
- /**
- * The list of asset files imported by this chunk, excluding CSS files
- *
- * This field is only present in JS chunks.
- */
- assets?: string[];
- /**
- * Whether this chunk or asset is an entry point
- */
- isEntry?: boolean;
- /**
- * The name of this chunk / asset if known
- */
- name?: string;
- /**
- * Whether this chunk is a dynamic entry point
- *
- * This field is only present in JS chunks.
- */
- isDynamicEntry?: boolean;
- /**
- * The list of statically imported chunks by this chunk
- *
- * The values are the keys of the manifest. This field is only present in JS chunks.
- */
- imports?: string[];
- /**
- * The list of dynamically imported chunks by this chunk
- *
- * The values are the keys of the manifest. This field is only present in JS chunks.
- */
- dynamicImports?: string[];
-}
-//#endregion
-export { type Alias, type AliasOptions, type AnymatchFn, type AnymatchPattern, type AppType, type BindCLIShortcutsOptions, type BuildAppHook, BuildEnvironment, type BuildEnvironmentOptions, type BuildOptions, type BuilderOptions, type CLIShortcut, type CSSModulesOptions, type CSSOptions, type ChunkMetadata, type CommonServerOptions, type ConfigEnv, type ConfigPluginContext, type Connect, type ConnectedPayload, type CorsOptions, type CorsOrigin, type CustomEventMap, type CustomPayload, type CustomPluginOptionsVite, type DepOptimizationConfig, type DepOptimizationMetadata, type DepOptimizationOptions, DevEnvironment, type DevEnvironmentContext, type DevEnvironmentOptions, type ESBuildOptions, type ESBuildTransformResult, type Environment, type EnvironmentModuleGraph, type EnvironmentModuleNode, type EnvironmentOptions, type ErrorPayload, type EsbuildTransformOptions, type ExperimentalOptions, type ExportsData, type FSWatcher, type FetchFunction, type FetchModuleOptions, type FetchResult, type FetchableDevEnvironment, type FetchableDevEnvironmentContext, type FileSystemServeOptions, type FilterPattern, type FullReloadPayload, type GeneralImportGlobOptions, type HMRPayload, type HTMLOptions, type HmrContext, type HmrOptions, type HookHandler, type HotChannel, type HotChannelClient, type HotChannelListener, type HotPayload, type HotUpdateOptions, type HtmlTagDescriptor, type index_d_exports as HttpProxy, type HttpServer, type ImportGlobFunction, type ImportGlobOptions, type IndexHtmlTransform, type IndexHtmlTransformContext, type IndexHtmlTransformHook, type IndexHtmlTransformResult, type InferCustomEventPayload, type InlineConfig, type InternalResolveOptions, type InvalidatePayload, type JsonOptions, type KnownAsTypeMap, type LegacyOptions, type LessPreprocessorOptions, type LibraryFormats, type LibraryOptions, type LightningCSSOptions, type LogErrorOptions, type LogLevel, type LogOptions, type LogType, type Logger, type LoggerOptions, type Manifest, type ManifestChunk, type MapToFunction, type AnymatchMatcher as Matcher, type MinimalPluginContextWithoutEnvironment, type ModuleGraph, type ModuleNode, type ModulePreloadOptions, type ModuleRunnerTransformOptions, type NormalizedHotChannel, type NormalizedHotChannelClient, type NormalizedServerHotChannel, type OptimizedDepInfo, type Plugin, type PluginContainer, type PluginHookUtils, type PluginOption, type PreprocessCSSResult, type PreviewOptions, type PreviewServer, type PreviewServerHook, type ProxyOptions, type PrunePayload, type RenderBuiltAssetUrl, type ResolveFn, type ResolveModulePreloadDependenciesFn, type ResolveOptions, type ResolvedBuildEnvironmentOptions, type ResolvedBuildOptions, type ResolvedCSSOptions, type ResolvedConfig, type ResolvedDevEnvironmentOptions, type ResolvedModulePreloadOptions, type ResolvedPreviewOptions, type ResolvedSSROptions, type ResolvedServerOptions, type ResolvedServerUrls, type ResolvedUrl, type ResolvedWorkerOptions, type ResolverFunction, type ResolverObject, type Rollup, type RollupCommonJSOptions, type RollupDynamicImportVarsOptions, type RunnableDevEnvironment, type RunnableDevEnvironmentContext, type SSROptions, type SSRTarget, type SassPreprocessorOptions, type SendOptions, type ServerHook, type ServerHotChannel, type ServerModuleRunnerOptions, type ServerOptions$1 as ServerOptions, type SkipInformation, type SsrDepOptimizationConfig, type StylusPreprocessorOptions, type Terser, type TerserOptions, type TransformOptions, type TransformResult, type Update, type UpdatePayload, type UserConfig, type UserConfigExport, type UserConfigFn, type UserConfigFnObject, type UserConfigFnPromise, type ViteBuilder, type ViteDevServer, type WatchOptions, type WebSocket, type WebSocketAlias, type WebSocketClient, type WebSocketCustomListener, type WebSocketServer, build, buildErrorMessage, createBuilder, createFetchableDevEnvironment, createFilter, createIdResolver, createLogger, createRunnableDevEnvironment, createServer, createServerHotChannel, createServerModuleRunner, createServerModuleRunnerTransport, defaultAllowedOrigins, DEFAULT_CLIENT_CONDITIONS as defaultClientConditions, DEFAULT_CLIENT_MAIN_FIELDS as defaultClientMainFields, DEFAULT_EXTERNAL_CONDITIONS as defaultExternalConditions, DEFAULT_SERVER_CONDITIONS as defaultServerConditions, DEFAULT_SERVER_MAIN_FIELDS as defaultServerMainFields, defineConfig, esbuildVersion, fetchModule, formatPostcssSourceMap, isCSSRequest, isFetchableDevEnvironment, isFileLoadingAllowed, isFileServingAllowed, isRunnableDevEnvironment, loadConfigFromFile, loadEnv, mergeAlias, mergeConfig, ssrTransform as moduleRunnerTransform, normalizePath, optimizeDeps, parseAst, parseAstAsync, perEnvironmentPlugin, perEnvironmentState, preprocessCSS, preview, resolveConfig, resolveEnvPrefix, rollupVersion, runnerImport, searchForWorkspaceRoot, send, sortUserPlugins, transformWithEsbuild, VERSION as version }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/index.js b/vanilla/node_modules/vite/dist/node/index.js
deleted file mode 100644
index 7323b09..0000000
--- a/vanilla/node_modules/vite/dist/node/index.js
+++ /dev/null
@@ -1,30 +0,0 @@
-import { F as defaultAllowedOrigins, N as VERSION, _ as DEFAULT_SERVER_CONDITIONS, d as DEFAULT_CLIENT_MAIN_FIELDS, h as DEFAULT_EXTERNAL_CONDITIONS, n as createLogger, u as DEFAULT_CLIENT_CONDITIONS, v as DEFAULT_SERVER_MAIN_FIELDS } from "./chunks/logger.js";
-import { Ct as perEnvironmentPlugin, Dt as mergeConfig, Et as mergeAlias, J as optimizeDeps, Ot as normalizePath, St as perEnvironmentState, Tt as isCSSRequest, _ as build, _t as createServerModuleRunnerTransport, b as createBuilder, bt as resolveEnvPrefix, c as sortUserPlugins, dt as searchForWorkspaceRoot, f as createRunnableDevEnvironment, ft as isFileLoadingAllowed, g as BuildEnvironment, gt as createServerModuleRunner, h as fetchModule, ht as ssrTransform, i as loadConfigFromFile, it as createServerHotChannel, kt as rollupVersion, l as runnerImport, m as DevEnvironment, mt as send, nt as preprocessCSS, o as resolveConfig, ot as createServer, p as isRunnableDevEnvironment, pt as isFileServingAllowed, rt as createIdResolver, t as defineConfig, tt as formatPostcssSourceMap, u as preview, vt as buildErrorMessage, wt as createFilter, xt as transformWithEsbuild, yt as loadEnv } from "./chunks/config.js";
-import { parseAst, parseAstAsync } from "rollup/parseAst";
-import { version as esbuildVersion } from "esbuild";
-
-//#region src/node/server/environments/fetchableEnvironments.ts
-function createFetchableDevEnvironment(name, config, context) {
- if (typeof Request === "undefined" || typeof Response === "undefined") throw new TypeError("FetchableDevEnvironment requires a global `Request` and `Response` object.");
- if (!context.handleRequest) throw new TypeError("FetchableDevEnvironment requires a `handleRequest` method during initialisation.");
- return new FetchableDevEnvironment(name, config, context);
-}
-function isFetchableDevEnvironment(environment) {
- return environment instanceof FetchableDevEnvironment;
-}
-var FetchableDevEnvironment = class extends DevEnvironment {
- _handleRequest;
- constructor(name, config, context) {
- super(name, config, context);
- this._handleRequest = context.handleRequest;
- }
- async dispatchFetch(request) {
- if (!(request instanceof Request)) throw new TypeError("FetchableDevEnvironment `dispatchFetch` must receive a `Request` object.");
- const response = await this._handleRequest(request);
- if (!(response instanceof Response)) throw new TypeError("FetchableDevEnvironment `context.handleRequest` must return a `Response` object.");
- return response;
- }
-};
-
-//#endregion
-export { BuildEnvironment, DevEnvironment, build, buildErrorMessage, createBuilder, createFetchableDevEnvironment, createFilter, createIdResolver, createLogger, createRunnableDevEnvironment, createServer, createServerHotChannel, createServerModuleRunner, createServerModuleRunnerTransport, defaultAllowedOrigins, DEFAULT_CLIENT_CONDITIONS as defaultClientConditions, DEFAULT_CLIENT_MAIN_FIELDS as defaultClientMainFields, DEFAULT_EXTERNAL_CONDITIONS as defaultExternalConditions, DEFAULT_SERVER_CONDITIONS as defaultServerConditions, DEFAULT_SERVER_MAIN_FIELDS as defaultServerMainFields, defineConfig, esbuildVersion, fetchModule, formatPostcssSourceMap, isCSSRequest, isFetchableDevEnvironment, isFileLoadingAllowed, isFileServingAllowed, isRunnableDevEnvironment, loadConfigFromFile, loadEnv, mergeAlias, mergeConfig, ssrTransform as moduleRunnerTransform, normalizePath, optimizeDeps, parseAst, parseAstAsync, perEnvironmentPlugin, perEnvironmentState, preprocessCSS, preview, resolveConfig, resolveEnvPrefix, rollupVersion, runnerImport, searchForWorkspaceRoot, send, sortUserPlugins, transformWithEsbuild, VERSION as version }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/module-runner.d.ts b/vanilla/node_modules/vite/dist/node/module-runner.d.ts
deleted file mode 100644
index 511f6af..0000000
--- a/vanilla/node_modules/vite/dist/node/module-runner.d.ts
+++ /dev/null
@@ -1,311 +0,0 @@
-import { a as ExternalFetchResult, c as ViteFetchResult, i as createWebSocketModuleRunnerTransport, n as ModuleRunnerTransportHandlers, o as FetchFunctionOptions, r as NormalizedModuleRunnerTransport, s as FetchResult, t as ModuleRunnerTransport } from "./chunks/moduleRunnerTransport.js";
-import { ModuleNamespace, ViteHotContext } from "#types/hot";
-import { HotPayload, Update } from "#types/hmrPayload";
-import { InferCustomEventPayload } from "#types/customEvent";
-
-//#region src/module-runner/sourcemap/decoder.d.ts
-interface SourceMapLike {
- version: number;
- mappings?: string;
- names?: string[];
- sources?: string[];
- sourcesContent?: string[];
-}
-declare class DecodedMap {
- map: SourceMapLike;
- _encoded: string;
- _decoded: undefined | number[][][];
- _decodedMemo: Stats;
- url: string;
- file: string;
- version: number;
- names: string[];
- resolvedSources: string[];
- constructor(map: SourceMapLike, from: string);
-}
-interface Stats {
- lastKey: number;
- lastNeedle: number;
- lastIndex: number;
-}
-//#endregion
-//#region src/shared/hmr.d.ts
-type CustomListenersMap = Map<string, ((data: any) => void)[]>;
-interface HotModule {
- id: string;
- callbacks: HotCallback[];
-}
-interface HotCallback {
- deps: string[];
- fn: (modules: Array<ModuleNamespace | undefined>) => void;
-}
-interface HMRLogger {
- error(msg: string | Error): void;
- debug(...msg: unknown[]): void;
-}
-declare class HMRClient {
- logger: HMRLogger;
- private transport;
- private importUpdatedModule;
- hotModulesMap: Map<string, HotModule>;
- disposeMap: Map<string, (data: any) => void | Promise<void>>;
- pruneMap: Map<string, (data: any) => void | Promise<void>>;
- dataMap: Map<string, any>;
- customListenersMap: CustomListenersMap;
- ctxToListenersMap: Map<string, CustomListenersMap>;
- currentFirstInvalidatedBy: string | undefined;
- constructor(logger: HMRLogger, transport: NormalizedModuleRunnerTransport, importUpdatedModule: (update: Update) => Promise<ModuleNamespace>);
- notifyListeners<T extends string>(event: T, data: InferCustomEventPayload<T>): Promise<void>;
- send(payload: HotPayload): void;
- clear(): void;
- prunePaths(paths: string[]): Promise<void>;
- protected warnFailedUpdate(err: Error, path: string | string[]): void;
- private updateQueue;
- private pendingUpdateQueue;
- /**
- * buffer multiple hot updates triggered by the same src change
- * so that they are invoked in the same order they were sent.
- * (otherwise the order may be inconsistent because of the http request round trip)
- */
- queueUpdate(payload: Update): Promise<void>;
- private fetchUpdate;
-}
-//#endregion
-//#region src/shared/ssrTransform.d.ts
-interface DefineImportMetadata {
- /**
- * Imported names before being transformed to `ssrImportKey`
- *
- * import foo, { bar as baz, qux } from 'hello'
- * => ['default', 'bar', 'qux']
- *
- * import * as namespace from 'world
- * => undefined
- */
- importedNames?: string[];
-}
-interface SSRImportMetadata extends DefineImportMetadata {
- isDynamicImport?: boolean;
-}
-//#endregion
-//#region src/module-runner/constants.d.ts
-declare const ssrModuleExportsKey = "__vite_ssr_exports__";
-declare const ssrImportKey = "__vite_ssr_import__";
-declare const ssrDynamicImportKey = "__vite_ssr_dynamic_import__";
-declare const ssrExportAllKey = "__vite_ssr_exportAll__";
-declare const ssrExportNameKey = "__vite_ssr_exportName__";
-declare const ssrImportMetaKey = "__vite_ssr_import_meta__";
-//#endregion
-//#region src/module-runner/runner.d.ts
-interface ModuleRunnerDebugger {
- (formatter: unknown, ...args: unknown[]): void;
-}
-declare class ModuleRunner {
- options: ModuleRunnerOptions;
- evaluator: ModuleEvaluator;
- private debug?;
- evaluatedModules: EvaluatedModules;
- hmrClient?: HMRClient;
- private readonly transport;
- private readonly resetSourceMapSupport?;
- private readonly concurrentModuleNodePromises;
- private isBuiltin?;
- private builtinsPromise?;
- private closed;
- constructor(options: ModuleRunnerOptions, evaluator?: ModuleEvaluator, debug?: ModuleRunnerDebugger | undefined);
- /**
- * URL to execute. Accepts file path, server path or id relative to the root.
- */
- import<T = any>(url: string): Promise<T>;
- /**
- * Clear all caches including HMR listeners.
- */
- clearCache(): void;
- /**
- * Clears all caches, removes all HMR listeners, and resets source map support.
- * This method doesn't stop the HMR connection.
- */
- close(): Promise<void>;
- /**
- * Returns `true` if the runtime has been closed by calling `close()` method.
- */
- isClosed(): boolean;
- private processImport;
- private isCircularModule;
- private isCircularImport;
- private cachedRequest;
- private cachedModule;
- private ensureBuiltins;
- private getModuleInformation;
- protected directRequest(url: string, mod: EvaluatedModuleNode, _callstack: string[]): Promise<any>;
-}
-//#endregion
-//#region src/module-runner/sourcemap/interceptor.d.ts
-interface RetrieveFileHandler {
- (path: string): string | null | undefined | false;
-}
-interface RetrieveSourceMapHandler {
- (path: string): null | {
- url: string;
- map: any;
- };
-}
-interface InterceptorOptions {
- retrieveFile?: RetrieveFileHandler;
- retrieveSourceMap?: RetrieveSourceMapHandler;
-}
-//#endregion
-//#region src/module-runner/types.d.ts
-interface ModuleRunnerImportMeta extends ImportMeta {
- url: string;
- env: ImportMetaEnv;
- hot?: ViteHotContext;
- [key: string]: any;
-}
-interface ModuleRunnerContext {
- [ssrModuleExportsKey]: Record<string, any>;
- [ssrImportKey]: (id: string, metadata?: DefineImportMetadata) => Promise<any>;
- [ssrDynamicImportKey]: (id: string, options?: ImportCallOptions) => Promise<any>;
- [ssrExportAllKey]: (obj: any) => void;
- [ssrExportNameKey]: (name: string, getter: () => unknown) => void;
- [ssrImportMetaKey]: ModuleRunnerImportMeta;
-}
-interface ModuleEvaluator {
- /**
- * Number of prefixed lines in the transformed code.
- */
- startOffset?: number;
- /**
- * Run code that was transformed by Vite.
- * @param context Function context
- * @param code Transformed code
- * @param module The module node
- */
- runInlinedModule(context: ModuleRunnerContext, code: string, module: Readonly<EvaluatedModuleNode>): Promise<any>;
- /**
- * Run externalized module.
- * @param file File URL to the external module
- */
- runExternalModule(file: string): Promise<any>;
-}
-type ResolvedResult = (ExternalFetchResult | ViteFetchResult) & {
- url: string;
- id: string;
-};
-type FetchFunction = (id: string, importer?: string, options?: FetchFunctionOptions) => Promise<FetchResult>;
-interface ModuleRunnerHmr {
- /**
- * Configure HMR logger.
- */
- logger?: false | HMRLogger;
-}
-interface ModuleRunnerOptions {
- /**
- * A set of methods to communicate with the server.
- */
- transport: ModuleRunnerTransport;
- /**
- * Configure how source maps are resolved. Prefers `node` if `process.setSourceMapsEnabled` is available.
- * Otherwise it will use `prepareStackTrace` by default which overrides `Error.prepareStackTrace` method.
- * You can provide an object to configure how file contents and source maps are resolved for files that were not processed by Vite.
- */
- sourcemapInterceptor?: false | "node" | "prepareStackTrace" | InterceptorOptions;
- /**
- * Disable HMR or configure HMR options.
- *
- * @default true
- */
- hmr?: boolean | ModuleRunnerHmr;
- /**
- * Create import.meta object for the module.
- *
- * @default createDefaultImportMeta
- */
- createImportMeta?: (modulePath: string) => ModuleRunnerImportMeta | Promise<ModuleRunnerImportMeta>;
- /**
- * Custom module cache. If not provided, creates a separate module cache for each ModuleRunner instance.
- */
- evaluatedModules?: EvaluatedModules;
-}
-interface ImportMetaEnv {
- [key: string]: any;
- BASE_URL: string;
- MODE: string;
- DEV: boolean;
- PROD: boolean;
- SSR: boolean;
-}
-//#endregion
-//#region src/module-runner/evaluatedModules.d.ts
-declare class EvaluatedModuleNode {
- id: string;
- url: string;
- importers: Set<string>;
- imports: Set<string>;
- evaluated: boolean;
- meta: ResolvedResult | undefined;
- promise: Promise<any> | undefined;
- exports: any | undefined;
- file: string;
- map: DecodedMap | undefined;
- constructor(id: string, url: string);
-}
-declare class EvaluatedModules {
- readonly idToModuleMap: Map<string, EvaluatedModuleNode>;
- readonly fileToModulesMap: Map<string, Set<EvaluatedModuleNode>>;
- readonly urlToIdModuleMap: Map<string, EvaluatedModuleNode>;
- /**
- * Returns the module node by the resolved module ID. Usually, module ID is
- * the file system path with query and/or hash. It can also be a virtual module.
- *
- * Module runner graph will have 1 to 1 mapping with the server module graph.
- * @param id Resolved module ID
- */
- getModuleById(id: string): EvaluatedModuleNode | undefined;
- /**
- * Returns all modules related to the file system path. Different modules
- * might have different query parameters or hash, so it's possible to have
- * multiple modules for the same file.
- * @param file The file system path of the module
- */
- getModulesByFile(file: string): Set<EvaluatedModuleNode> | undefined;
- /**
- * Returns the module node by the URL that was used in the import statement.
- * Unlike module graph on the server, the URL is not resolved and is used as is.
- * @param url Server URL that was used in the import statement
- */
- getModuleByUrl(url: string): EvaluatedModuleNode | undefined;
- /**
- * Ensure that module is in the graph. If the module is already in the graph,
- * it will return the existing module node. Otherwise, it will create a new
- * module node and add it to the graph.
- * @param id Resolved module ID
- * @param url URL that was used in the import statement
- */
- ensureModule(id: string, url: string): EvaluatedModuleNode;
- invalidateModule(node: EvaluatedModuleNode): void;
- /**
- * Extracts the inlined source map from the module code and returns the decoded
- * source map. If the source map is not inlined, it will return null.
- * @param id Resolved module ID
- */
- getModuleSourceMapById(id: string): DecodedMap | null;
- clear(): void;
-}
-declare function normalizeModuleId(file: string): string;
-//#endregion
-//#region src/module-runner/esmEvaluator.d.ts
-declare class ESModulesEvaluator implements ModuleEvaluator {
- readonly startOffset: number;
- runInlinedModule(context: ModuleRunnerContext, code: string): Promise<any>;
- runExternalModule(filepath: string): Promise<any>;
-}
-//#endregion
-//#region src/module-runner/createImportMeta.d.ts
-declare function createDefaultImportMeta(modulePath: string): ModuleRunnerImportMeta;
-/**
-* Create import.meta object for Node.js.
-*/
-declare function createNodeImportMeta(modulePath: string): Promise<ModuleRunnerImportMeta>;
-//#endregion
-export { ESModulesEvaluator, type EvaluatedModuleNode, EvaluatedModules, type FetchFunction, type FetchFunctionOptions, type FetchResult, type HMRLogger, type InterceptorOptions, type ModuleEvaluator, ModuleRunner, type ModuleRunnerContext, type ModuleRunnerHmr, type ModuleRunnerImportMeta, type ModuleRunnerOptions, type ModuleRunnerTransport, type ModuleRunnerTransportHandlers, type ResolvedResult, type SSRImportMetadata, createDefaultImportMeta, createNodeImportMeta, createWebSocketModuleRunnerTransport, normalizeModuleId, ssrDynamicImportKey, ssrExportAllKey, ssrExportNameKey, ssrImportKey, ssrImportMetaKey, ssrModuleExportsKey }; \ No newline at end of file
diff --git a/vanilla/node_modules/vite/dist/node/module-runner.js b/vanilla/node_modules/vite/dist/node/module-runner.js
deleted file mode 100644
index 90a2850..0000000
--- a/vanilla/node_modules/vite/dist/node/module-runner.js
+++ /dev/null
@@ -1,1160 +0,0 @@
-let SOURCEMAPPING_URL = "sourceMa";
-SOURCEMAPPING_URL += "ppingURL";
-const isWindows = typeof process < "u" && process.platform === "win32";
-function unwrapId(id) {
- return id.startsWith("/@id/") ? id.slice(5).replace("__x00__", "\0") : id;
-}
-const windowsSlashRE = /\\/g;
-function slash(p) {
- return p.replace(windowsSlashRE, "/");
-}
-const postfixRE = /[?#].*$/;
-function cleanUrl(url) {
- return url.replace(postfixRE, "");
-}
-function isPrimitive(value) {
- return !value || typeof value != "object" && typeof value != "function";
-}
-const AsyncFunction = async function() {}.constructor;
-let asyncFunctionDeclarationPaddingLineCount;
-function getAsyncFunctionDeclarationPaddingLineCount() {
- if (asyncFunctionDeclarationPaddingLineCount === void 0) {
- let body = "/*code*/", source = new AsyncFunction("a", "b", body).toString();
- asyncFunctionDeclarationPaddingLineCount = source.slice(0, source.indexOf(body)).split("\n").length - 1;
- }
- return asyncFunctionDeclarationPaddingLineCount;
-}
-function promiseWithResolvers() {
- let resolve$1, reject;
- return {
- promise: new Promise((_resolve, _reject) => {
- resolve$1 = _resolve, reject = _reject;
- }),
- resolve: resolve$1,
- reject
- };
-}
-const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
-function normalizeWindowsPath(input = "") {
- return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
-}
-const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
-function cwd() {
- return typeof process < "u" && typeof process.cwd == "function" ? process.cwd().replace(/\\/g, "/") : "/";
-}
-const resolve = function(...arguments_) {
- arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
- let resolvedPath = "", resolvedAbsolute = !1;
- for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
- let path = index >= 0 ? arguments_[index] : cwd();
- !path || path.length === 0 || (resolvedPath = `${path}/${resolvedPath}`, resolvedAbsolute = isAbsolute(path));
- }
- return resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute), resolvedAbsolute && !isAbsolute(resolvedPath) ? `/${resolvedPath}` : resolvedPath.length > 0 ? resolvedPath : ".";
-};
-function normalizeString(path, allowAboveRoot) {
- let res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, char = null;
- for (let index = 0; index <= path.length; ++index) {
- if (index < path.length) char = path[index];
- else if (char === "/") break;
- else char = "/";
- if (char === "/") {
- if (!(lastSlash === index - 1 || dots === 1)) if (dots === 2) {
- if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
- if (res.length > 2) {
- let lastSlashIndex = res.lastIndexOf("/");
- lastSlashIndex === -1 ? (res = "", lastSegmentLength = 0) : (res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/")), lastSlash = index, dots = 0;
- continue;
- } else if (res.length > 0) {
- res = "", lastSegmentLength = 0, lastSlash = index, dots = 0;
- continue;
- }
- }
- allowAboveRoot && (res += res.length > 0 ? "/.." : "..", lastSegmentLength = 2);
- } else res.length > 0 ? res += `/${path.slice(lastSlash + 1, index)}` : res = path.slice(lastSlash + 1, index), lastSegmentLength = index - lastSlash - 1;
- lastSlash = index, dots = 0;
- } else char === "." && dots !== -1 ? ++dots : dots = -1;
- }
- return res;
-}
-const isAbsolute = function(p) {
- return _IS_ABSOLUTE_RE.test(p);
-}, dirname = function(p) {
- let segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
- return segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0]) && (segments[0] += "/"), segments.join("/") || (isAbsolute(p) ? "/" : ".");
-}, decodeBase64 = typeof atob < "u" ? atob : (str) => Buffer.from(str, "base64").toString("utf-8"), percentRegEx = /%/g, backslashRegEx = /\\/g, newlineRegEx = /\n/g, carriageReturnRegEx = /\r/g, tabRegEx = /\t/g, questionRegex = /\?/g, hashRegex = /#/g;
-function encodePathChars(filepath) {
- return filepath.indexOf("%") !== -1 && (filepath = filepath.replace(percentRegEx, "%25")), !isWindows && filepath.indexOf("\\") !== -1 && (filepath = filepath.replace(backslashRegEx, "%5C")), filepath.indexOf("\n") !== -1 && (filepath = filepath.replace(newlineRegEx, "%0A")), filepath.indexOf("\r") !== -1 && (filepath = filepath.replace(carriageReturnRegEx, "%0D")), filepath.indexOf(" ") !== -1 && (filepath = filepath.replace(tabRegEx, "%09")), filepath;
-}
-const posixDirname = dirname, posixResolve = resolve;
-function posixPathToFileHref(posixPath) {
- let resolved = posixResolve(posixPath), filePathLast = posixPath.charCodeAt(posixPath.length - 1);
- return (filePathLast === 47 || isWindows && filePathLast === 92) && resolved[resolved.length - 1] !== "/" && (resolved += "/"), resolved = encodePathChars(resolved), resolved.indexOf("?") !== -1 && (resolved = resolved.replace(questionRegex, "%3F")), resolved.indexOf("#") !== -1 && (resolved = resolved.replace(hashRegex, "%23")), new URL(`file://${resolved}`).href;
-}
-function toWindowsPath(path) {
- return path.replace(/\//g, "\\");
-}
-var comma = 44, chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", intToChar = new Uint8Array(64), charToInt = new Uint8Array(128);
-for (let i = 0; i < chars.length; i++) {
- let c = chars.charCodeAt(i);
- intToChar[i] = c, charToInt[c] = i;
-}
-function decodeInteger(reader, relative) {
- let value = 0, shift = 0, integer = 0;
- do
- integer = charToInt[reader.next()], value |= (integer & 31) << shift, shift += 5;
- while (integer & 32);
- let shouldNegate = value & 1;
- return value >>>= 1, shouldNegate && (value = -2147483648 | -value), relative + value;
-}
-function hasMoreVlq(reader, max) {
- return reader.pos >= max ? !1 : reader.peek() !== comma;
-}
-var StringReader = class {
- constructor(buffer) {
- this.pos = 0, this.buffer = buffer;
- }
- next() {
- return this.buffer.charCodeAt(this.pos++);
- }
- peek() {
- return this.buffer.charCodeAt(this.pos);
- }
- indexOf(char) {
- let { buffer, pos } = this, idx = buffer.indexOf(char, pos);
- return idx === -1 ? buffer.length : idx;
- }
-};
-function decode(mappings) {
- let { length } = mappings, reader = new StringReader(mappings), decoded = [], genColumn = 0, sourcesIndex = 0, sourceLine = 0, sourceColumn = 0, namesIndex = 0;
- do {
- let semi = reader.indexOf(";"), line = [], sorted = !0, lastCol = 0;
- for (genColumn = 0; reader.pos < semi;) {
- let seg;
- genColumn = decodeInteger(reader, genColumn), genColumn < lastCol && (sorted = !1), lastCol = genColumn, hasMoreVlq(reader, semi) ? (sourcesIndex = decodeInteger(reader, sourcesIndex), sourceLine = decodeInteger(reader, sourceLine), sourceColumn = decodeInteger(reader, sourceColumn), hasMoreVlq(reader, semi) ? (namesIndex = decodeInteger(reader, namesIndex), seg = [
- genColumn,
- sourcesIndex,
- sourceLine,
- sourceColumn,
- namesIndex
- ]) : seg = [
- genColumn,
- sourcesIndex,
- sourceLine,
- sourceColumn
- ]) : seg = [genColumn], line.push(seg), reader.pos++;
- }
- sorted || sort(line), decoded.push(line), reader.pos = semi + 1;
- } while (reader.pos <= length);
- return decoded;
-}
-function sort(line) {
- line.sort(sortComparator);
-}
-function sortComparator(a, b) {
- return a[0] - b[0];
-}
-var COLUMN = 0, SOURCES_INDEX = 1, SOURCE_LINE = 2, SOURCE_COLUMN = 3, NAMES_INDEX = 4, found = !1;
-function binarySearch(haystack, needle, low, high) {
- for (; low <= high;) {
- let mid = low + (high - low >> 1), cmp = haystack[mid][COLUMN] - needle;
- if (cmp === 0) return found = !0, mid;
- cmp < 0 ? low = mid + 1 : high = mid - 1;
- }
- return found = !1, low - 1;
-}
-function upperBound(haystack, needle, index) {
- for (let i = index + 1; i < haystack.length && haystack[i][COLUMN] === needle; index = i++);
- return index;
-}
-function lowerBound(haystack, needle, index) {
- for (let i = index - 1; i >= 0 && haystack[i][COLUMN] === needle; index = i--);
- return index;
-}
-function memoizedBinarySearch(haystack, needle, state, key) {
- let { lastKey, lastNeedle, lastIndex } = state, low = 0, high = haystack.length - 1;
- if (key === lastKey) {
- if (needle === lastNeedle) return found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle, lastIndex;
- needle >= lastNeedle ? low = lastIndex === -1 ? 0 : lastIndex : high = lastIndex;
- }
- return state.lastKey = key, state.lastNeedle = needle, state.lastIndex = binarySearch(haystack, needle, low, high);
-}
-var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)", COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)", LEAST_UPPER_BOUND = -1, GREATEST_LOWER_BOUND = 1;
-function cast(map) {
- return map;
-}
-function decodedMappings(map) {
- var _a;
- return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
-}
-function originalPositionFor(map, needle) {
- let { line, column, bias } = needle;
- if (line--, line < 0) throw Error(LINE_GTR_ZERO);
- if (column < 0) throw Error(COL_GTR_EQ_ZERO);
- let decoded = decodedMappings(map);
- if (line >= decoded.length) return OMapping(null, null, null, null);
- let segments = decoded[line], index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
- if (index === -1) return OMapping(null, null, null, null);
- let segment = segments[index];
- if (segment.length === 1) return OMapping(null, null, null, null);
- let { names, resolvedSources } = map;
- return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
-}
-function OMapping(source, line, column, name) {
- return {
- source,
- line,
- column,
- name
- };
-}
-function traceSegmentInternal(segments, memo, line, column, bias) {
- let index = memoizedBinarySearch(segments, column, memo, line);
- return found ? index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index) : bias === LEAST_UPPER_BOUND && index++, index === -1 || index === segments.length ? -1 : index;
-}
-var DecodedMap = class {
- _encoded;
- _decoded;
- _decodedMemo;
- url;
- file;
- version;
- names = [];
- resolvedSources;
- constructor(map, from) {
- this.map = map;
- let { mappings, names, sources } = map;
- this.version = map.version, this.names = names || [], this._encoded = mappings || "", this._decodedMemo = memoizedState(), this.url = from, this.file = from;
- let originDir = posixDirname(from);
- this.resolvedSources = (sources || []).map((s) => posixResolve(originDir, s || ""));
- }
-};
-function memoizedState() {
- return {
- lastKey: -1,
- lastNeedle: -1,
- lastIndex: -1
- };
-}
-function getOriginalPosition(map, needle) {
- let result = originalPositionFor(map, needle);
- return result.column == null ? null : result;
-}
-const MODULE_RUNNER_SOURCEMAPPING_REGEXP = /* @__PURE__ */ RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json;base64,(.+)`);
-var EvaluatedModuleNode = class {
- importers = /* @__PURE__ */ new Set();
- imports = /* @__PURE__ */ new Set();
- evaluated = !1;
- meta;
- promise;
- exports;
- file;
- map;
- constructor(id, url) {
- this.id = id, this.url = url, this.file = cleanUrl(id);
- }
-}, EvaluatedModules = class {
- idToModuleMap = /* @__PURE__ */ new Map();
- fileToModulesMap = /* @__PURE__ */ new Map();
- urlToIdModuleMap = /* @__PURE__ */ new Map();
- getModuleById(id) {
- return this.idToModuleMap.get(id);
- }
- getModulesByFile(file) {
- return this.fileToModulesMap.get(file);
- }
- getModuleByUrl(url) {
- return this.urlToIdModuleMap.get(unwrapId(url));
- }
- ensureModule(id, url) {
- if (id = normalizeModuleId(id), this.idToModuleMap.has(id)) {
- let moduleNode$1 = this.idToModuleMap.get(id);
- return this.urlToIdModuleMap.set(url, moduleNode$1), moduleNode$1;
- }
- let moduleNode = new EvaluatedModuleNode(id, url);
- this.idToModuleMap.set(id, moduleNode), this.urlToIdModuleMap.set(url, moduleNode);
- let fileModules = this.fileToModulesMap.get(moduleNode.file) || /* @__PURE__ */ new Set();
- return fileModules.add(moduleNode), this.fileToModulesMap.set(moduleNode.file, fileModules), moduleNode;
- }
- invalidateModule(node) {
- node.evaluated = !1, node.meta = void 0, node.map = void 0, node.promise = void 0, node.exports = void 0, node.imports.clear();
- }
- getModuleSourceMapById(id) {
- let mod = this.getModuleById(id);
- if (!mod) return null;
- if (mod.map) return mod.map;
- if (!mod.meta || !("code" in mod.meta)) return null;
- let pattern = `//# ${SOURCEMAPPING_URL}=data:application/json;base64,`, lastIndex = mod.meta.code.lastIndexOf(pattern);
- if (lastIndex === -1) return null;
- let mapString = MODULE_RUNNER_SOURCEMAPPING_REGEXP.exec(mod.meta.code.slice(lastIndex))?.[1];
- return mapString ? (mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), mod.file), mod.map) : null;
- }
- clear() {
- this.idToModuleMap.clear(), this.fileToModulesMap.clear(), this.urlToIdModuleMap.clear();
- }
-};
-const prefixedBuiltins = new Set([
- "node:sea",
- "node:sqlite",
- "node:test",
- "node:test/reporters"
-]);
-function normalizeModuleId(file) {
- return prefixedBuiltins.has(file) ? file : slash(file).replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/").replace(/^file:\/+/, isWindows ? "" : "/");
-}
-var HMRContext = class {
- newListeners;
- constructor(hmrClient, ownerPath) {
- this.hmrClient = hmrClient, this.ownerPath = ownerPath, hmrClient.dataMap.has(ownerPath) || hmrClient.dataMap.set(ownerPath, {});
- let mod = hmrClient.hotModulesMap.get(ownerPath);
- mod && (mod.callbacks = []);
- let staleListeners = hmrClient.ctxToListenersMap.get(ownerPath);
- if (staleListeners) for (let [event, staleFns] of staleListeners) {
- let listeners = hmrClient.customListenersMap.get(event);
- listeners && hmrClient.customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l)));
- }
- this.newListeners = /* @__PURE__ */ new Map(), hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners);
- }
- get data() {
- return this.hmrClient.dataMap.get(this.ownerPath);
- }
- accept(deps, callback) {
- if (typeof deps == "function" || !deps) this.acceptDeps([this.ownerPath], ([mod]) => deps?.(mod));
- else if (typeof deps == "string") this.acceptDeps([deps], ([mod]) => callback?.(mod));
- else if (Array.isArray(deps)) this.acceptDeps(deps, callback);
- else throw Error("invalid hot.accept() usage.");
- }
- acceptExports(_, callback) {
- this.acceptDeps([this.ownerPath], ([mod]) => callback?.(mod));
- }
- dispose(cb) {
- this.hmrClient.disposeMap.set(this.ownerPath, cb);
- }
- prune(cb) {
- this.hmrClient.pruneMap.set(this.ownerPath, cb);
- }
- decline() {}
- invalidate(message) {
- let firstInvalidatedBy = this.hmrClient.currentFirstInvalidatedBy ?? this.ownerPath;
- this.hmrClient.notifyListeners("vite:invalidate", {
- path: this.ownerPath,
- message,
- firstInvalidatedBy
- }), this.send("vite:invalidate", {
- path: this.ownerPath,
- message,
- firstInvalidatedBy
- }), this.hmrClient.logger.debug(`invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`);
- }
- on(event, cb) {
- let addToMap = (map) => {
- let existing = map.get(event) || [];
- existing.push(cb), map.set(event, existing);
- };
- addToMap(this.hmrClient.customListenersMap), addToMap(this.newListeners);
- }
- off(event, cb) {
- let removeFromMap = (map) => {
- let existing = map.get(event);
- if (existing === void 0) return;
- let pruned = existing.filter((l) => l !== cb);
- if (pruned.length === 0) {
- map.delete(event);
- return;
- }
- map.set(event, pruned);
- };
- removeFromMap(this.hmrClient.customListenersMap), removeFromMap(this.newListeners);
- }
- send(event, data) {
- this.hmrClient.send({
- type: "custom",
- event,
- data
- });
- }
- acceptDeps(deps, callback = () => {}) {
- let mod = this.hmrClient.hotModulesMap.get(this.ownerPath) || {
- id: this.ownerPath,
- callbacks: []
- };
- mod.callbacks.push({
- deps,
- fn: callback
- }), this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
- }
-}, HMRClient = class {
- hotModulesMap = /* @__PURE__ */ new Map();
- disposeMap = /* @__PURE__ */ new Map();
- pruneMap = /* @__PURE__ */ new Map();
- dataMap = /* @__PURE__ */ new Map();
- customListenersMap = /* @__PURE__ */ new Map();
- ctxToListenersMap = /* @__PURE__ */ new Map();
- currentFirstInvalidatedBy;
- constructor(logger, transport, importUpdatedModule) {
- this.logger = logger, this.transport = transport, this.importUpdatedModule = importUpdatedModule;
- }
- async notifyListeners(event, data) {
- let cbs = this.customListenersMap.get(event);
- cbs && await Promise.allSettled(cbs.map((cb) => cb(data)));
- }
- send(payload) {
- this.transport.send(payload).catch((err) => {
- this.logger.error(err);
- });
- }
- clear() {
- this.hotModulesMap.clear(), this.disposeMap.clear(), this.pruneMap.clear(), this.dataMap.clear(), this.customListenersMap.clear(), this.ctxToListenersMap.clear();
- }
- async prunePaths(paths) {
- await Promise.all(paths.map((path) => {
- let disposer = this.disposeMap.get(path);
- if (disposer) return disposer(this.dataMap.get(path));
- })), await Promise.all(paths.map((path) => {
- let fn = this.pruneMap.get(path);
- if (fn) return fn(this.dataMap.get(path));
- }));
- }
- warnFailedUpdate(err, path) {
- (!(err instanceof Error) || !err.message.includes("fetch")) && this.logger.error(err), this.logger.error(`Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`);
- }
- updateQueue = [];
- pendingUpdateQueue = !1;
- async queueUpdate(payload) {
- if (this.updateQueue.push(this.fetchUpdate(payload)), !this.pendingUpdateQueue) {
- this.pendingUpdateQueue = !0, await Promise.resolve(), this.pendingUpdateQueue = !1;
- let loading = [...this.updateQueue];
- this.updateQueue = [], (await Promise.all(loading)).forEach((fn) => fn && fn());
- }
- }
- async fetchUpdate(update) {
- let { path, acceptedPath, firstInvalidatedBy } = update, mod = this.hotModulesMap.get(path);
- if (!mod) return;
- let fetchedModule, isSelfUpdate = path === acceptedPath, qualifiedCallbacks = mod.callbacks.filter(({ deps }) => deps.includes(acceptedPath));
- if (isSelfUpdate || qualifiedCallbacks.length > 0) {
- let disposer = this.disposeMap.get(acceptedPath);
- disposer && await disposer(this.dataMap.get(acceptedPath));
- try {
- fetchedModule = await this.importUpdatedModule(update);
- } catch (e) {
- this.warnFailedUpdate(e, acceptedPath);
- }
- }
- return () => {
- try {
- this.currentFirstInvalidatedBy = firstInvalidatedBy;
- for (let { deps, fn } of qualifiedCallbacks) fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
- let loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
- this.logger.debug(`hot updated: ${loggedPath}`);
- } finally {
- this.currentFirstInvalidatedBy = void 0;
- }
- };
- }
-};
-function analyzeImportedModDifference(mod, rawId, moduleType, metadata) {
- if (!metadata?.isDynamicImport && metadata?.importedNames?.length) {
- let missingBindings = metadata.importedNames.filter((s) => !(s in mod));
- if (missingBindings.length) {
- let lastBinding = missingBindings[missingBindings.length - 1];
- throw moduleType === "module" ? SyntaxError(`[vite] The requested module '${rawId}' does not provide an export named '${lastBinding}'`) : SyntaxError(`\
-[vite] Named export '${lastBinding}' not found. The requested module '${rawId}' is a CommonJS module, which may not support all module.exports as named exports.
-CommonJS modules can always be imported via the default export, for example using:
-
-import pkg from '${rawId}';
-const {${missingBindings.join(", ")}} = pkg;
-`);
- }
- }
-}
-let nanoid = (size = 21) => {
- let id = "", i = size | 0;
- for (; i--;) id += "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[Math.random() * 64 | 0];
- return id;
-};
-function reviveInvokeError(e) {
- let error = Error(e.message || "Unknown invoke error");
- return Object.assign(error, e, { runnerError: /* @__PURE__ */ Error("RunnerError") }), error;
-}
-const createInvokeableTransport = (transport) => {
- if (transport.invoke) return {
- ...transport,
- async invoke(name, data) {
- let result = await transport.invoke({
- type: "custom",
- event: "vite:invoke",
- data: {
- id: "send",
- name,
- data
- }
- });
- if ("error" in result) throw reviveInvokeError(result.error);
- return result.result;
- }
- };
- if (!transport.send || !transport.connect) throw Error("transport must implement send and connect when invoke is not implemented");
- let rpcPromises = /* @__PURE__ */ new Map();
- return {
- ...transport,
- connect({ onMessage, onDisconnection }) {
- return transport.connect({
- onMessage(payload) {
- if (payload.type === "custom" && payload.event === "vite:invoke") {
- let data = payload.data;
- if (data.id.startsWith("response:")) {
- let invokeId = data.id.slice(9), promise = rpcPromises.get(invokeId);
- if (!promise) return;
- promise.timeoutId && clearTimeout(promise.timeoutId), rpcPromises.delete(invokeId);
- let { error, result } = data.data;
- error ? promise.reject(error) : promise.resolve(result);
- return;
- }
- }
- onMessage(payload);
- },
- onDisconnection
- });
- },
- disconnect() {
- return rpcPromises.forEach((promise) => {
- promise.reject(/* @__PURE__ */ Error(`transport was disconnected, cannot call ${JSON.stringify(promise.name)}`));
- }), rpcPromises.clear(), transport.disconnect?.();
- },
- send(data) {
- return transport.send(data);
- },
- async invoke(name, data) {
- let promiseId = nanoid(), wrappedData = {
- type: "custom",
- event: "vite:invoke",
- data: {
- name,
- id: `send:${promiseId}`,
- data
- }
- }, sendPromise = transport.send(wrappedData), { promise, resolve: resolve$1, reject } = promiseWithResolvers(), timeout = transport.timeout ?? 6e4, timeoutId;
- timeout > 0 && (timeoutId = setTimeout(() => {
- rpcPromises.delete(promiseId), reject(/* @__PURE__ */ Error(`transport invoke timed out after ${timeout}ms (data: ${JSON.stringify(wrappedData)})`));
- }, timeout), timeoutId?.unref?.()), rpcPromises.set(promiseId, {
- resolve: resolve$1,
- reject,
- name,
- timeoutId
- }), sendPromise && sendPromise.catch((err) => {
- clearTimeout(timeoutId), rpcPromises.delete(promiseId), reject(err);
- });
- try {
- return await promise;
- } catch (err) {
- throw reviveInvokeError(err);
- }
- }
- };
-}, normalizeModuleRunnerTransport = (transport) => {
- let invokeableTransport = createInvokeableTransport(transport), isConnected = !invokeableTransport.connect, connectingPromise;
- return {
- ...transport,
- ...invokeableTransport.connect ? { async connect(onMessage) {
- if (isConnected) return;
- if (connectingPromise) {
- await connectingPromise;
- return;
- }
- let maybePromise = invokeableTransport.connect({
- onMessage: onMessage ?? (() => {}),
- onDisconnection() {
- isConnected = !1;
- }
- });
- maybePromise && (connectingPromise = maybePromise, await connectingPromise, connectingPromise = void 0), isConnected = !0;
- } } : {},
- ...invokeableTransport.disconnect ? { async disconnect() {
- isConnected && (connectingPromise && await connectingPromise, isConnected = !1, await invokeableTransport.disconnect());
- } } : {},
- async send(data) {
- if (invokeableTransport.send) {
- if (!isConnected) if (connectingPromise) await connectingPromise;
- else throw Error("send was called before connect");
- await invokeableTransport.send(data);
- }
- },
- async invoke(name, data) {
- if (!isConnected) if (connectingPromise) await connectingPromise;
- else throw Error("invoke was called before connect");
- return invokeableTransport.invoke(name, data);
- }
- };
-}, createWebSocketModuleRunnerTransport = (options) => {
- let pingInterval = options.pingInterval ?? 3e4, ws, pingIntervalId;
- return {
- async connect({ onMessage, onDisconnection }) {
- let socket = options.createConnection();
- socket.addEventListener("message", async ({ data }) => {
- onMessage(JSON.parse(data));
- });
- let isOpened = socket.readyState === socket.OPEN;
- isOpened || await new Promise((resolve$1, reject) => {
- socket.addEventListener("open", () => {
- isOpened = !0, resolve$1();
- }, { once: !0 }), socket.addEventListener("close", async () => {
- if (!isOpened) {
- reject(/* @__PURE__ */ Error("WebSocket closed without opened."));
- return;
- }
- onMessage({
- type: "custom",
- event: "vite:ws:disconnect",
- data: { webSocket: socket }
- }), onDisconnection();
- });
- }), onMessage({
- type: "custom",
- event: "vite:ws:connect",
- data: { webSocket: socket }
- }), ws = socket, pingIntervalId = setInterval(() => {
- socket.readyState === socket.OPEN && socket.send(JSON.stringify({ type: "ping" }));
- }, pingInterval);
- },
- disconnect() {
- clearInterval(pingIntervalId), ws?.close();
- },
- send(data) {
- ws.send(JSON.stringify(data));
- }
- };
-};
-function createIsBuiltin(builtins) {
- let plainBuiltinsSet = new Set(builtins.filter((builtin) => typeof builtin == "string")), regexBuiltins = builtins.filter((builtin) => typeof builtin != "string");
- return (id) => plainBuiltinsSet.has(id) || regexBuiltins.some((regexp) => regexp.test(id));
-}
-const ssrModuleExportsKey = "__vite_ssr_exports__", ssrImportKey = "__vite_ssr_import__", ssrDynamicImportKey = "__vite_ssr_dynamic_import__", ssrExportAllKey = "__vite_ssr_exportAll__", ssrExportNameKey = "__vite_ssr_exportName__", ssrImportMetaKey = "__vite_ssr_import_meta__", noop = () => {}, silentConsole = {
- debug: noop,
- error: noop
-}, hmrLogger = {
- debug: (...msg) => console.log("[vite]", ...msg),
- error: (error) => console.log("[vite]", error)
-};
-function createHMRHandler(handler) {
- let queue = new Queue();
- return (payload) => queue.enqueue(() => handler(payload));
-}
-var Queue = class {
- queue = [];
- pending = !1;
- enqueue(promise) {
- return new Promise((resolve$1, reject) => {
- this.queue.push({
- promise,
- resolve: resolve$1,
- reject
- }), this.dequeue();
- });
- }
- dequeue() {
- if (this.pending) return !1;
- let item = this.queue.shift();
- return item ? (this.pending = !0, item.promise().then(item.resolve).catch(item.reject).finally(() => {
- this.pending = !1, this.dequeue();
- }), !0) : !1;
- }
-};
-function createHMRHandlerForRunner(runner) {
- return createHMRHandler(async (payload) => {
- let hmrClient = runner.hmrClient;
- if (!(!hmrClient || runner.isClosed())) switch (payload.type) {
- case "connected":
- hmrClient.logger.debug("connected.");
- break;
- case "update":
- await hmrClient.notifyListeners("vite:beforeUpdate", payload), await Promise.all(payload.updates.map(async (update) => {
- if (update.type === "js-update") return update.acceptedPath = unwrapId(update.acceptedPath), update.path = unwrapId(update.path), hmrClient.queueUpdate(update);
- hmrClient.logger.error("css hmr is not supported in runner mode.");
- })), await hmrClient.notifyListeners("vite:afterUpdate", payload);
- break;
- case "custom":
- await hmrClient.notifyListeners(payload.event, payload.data);
- break;
- case "full-reload": {
- let { triggeredBy } = payload, clearEntrypointUrls = triggeredBy ? getModulesEntrypoints(runner, getModulesByFile(runner, slash(triggeredBy))) : findAllEntrypoints(runner);
- if (!clearEntrypointUrls.size) break;
- hmrClient.logger.debug("program reload"), await hmrClient.notifyListeners("vite:beforeFullReload", payload), runner.evaluatedModules.clear();
- for (let url of clearEntrypointUrls) try {
- await runner.import(url);
- } catch (err) {
- err.code !== "ERR_OUTDATED_OPTIMIZED_DEP" && hmrClient.logger.error(`An error happened during full reload\n${err.message}\n${err.stack}`);
- }
- break;
- }
- case "prune":
- await hmrClient.notifyListeners("vite:beforePrune", payload), await hmrClient.prunePaths(payload.paths);
- break;
- case "error": {
- await hmrClient.notifyListeners("vite:error", payload);
- let err = payload.err;
- hmrClient.logger.error(`Internal Server Error\n${err.message}\n${err.stack}`);
- break;
- }
- case "ping": break;
- default: return payload;
- }
- });
-}
-function getModulesByFile(runner, file) {
- let nodes = runner.evaluatedModules.getModulesByFile(file);
- return nodes ? [...nodes].map((node) => node.id) : [];
-}
-function getModulesEntrypoints(runner, modules, visited = /* @__PURE__ */ new Set(), entrypoints = /* @__PURE__ */ new Set()) {
- for (let moduleId of modules) {
- if (visited.has(moduleId)) continue;
- visited.add(moduleId);
- let module = runner.evaluatedModules.getModuleById(moduleId);
- if (module) {
- if (!module.importers.size) {
- entrypoints.add(module.url);
- continue;
- }
- for (let importer of module.importers) getModulesEntrypoints(runner, [importer], visited, entrypoints);
- }
- }
- return entrypoints;
-}
-function findAllEntrypoints(runner, entrypoints = /* @__PURE__ */ new Set()) {
- for (let mod of runner.evaluatedModules.idToModuleMap.values()) mod.importers.size || entrypoints.add(mod.url);
- return entrypoints;
-}
-const sourceMapCache = {}, fileContentsCache = {}, evaluatedModulesCache = /* @__PURE__ */ new Set(), retrieveFileHandlers = /* @__PURE__ */ new Set(), retrieveSourceMapHandlers = /* @__PURE__ */ new Set(), createExecHandlers = (handlers) => ((...args) => {
- for (let handler of handlers) {
- let result = handler(...args);
- if (result) return result;
- }
- return null;
-}), retrieveFileFromHandlers = createExecHandlers(retrieveFileHandlers), retrieveSourceMapFromHandlers = createExecHandlers(retrieveSourceMapHandlers);
-let overridden = !1;
-const originalPrepare = Error.prepareStackTrace;
-function resetInterceptor(runner, options) {
- evaluatedModulesCache.delete(runner.evaluatedModules), options.retrieveFile && retrieveFileHandlers.delete(options.retrieveFile), options.retrieveSourceMap && retrieveSourceMapHandlers.delete(options.retrieveSourceMap), evaluatedModulesCache.size === 0 && (Error.prepareStackTrace = originalPrepare, overridden = !1);
-}
-function interceptStackTrace(runner, options = {}) {
- return overridden ||= (Error.prepareStackTrace = prepareStackTrace, !0), evaluatedModulesCache.add(runner.evaluatedModules), options.retrieveFile && retrieveFileHandlers.add(options.retrieveFile), options.retrieveSourceMap && retrieveSourceMapHandlers.add(options.retrieveSourceMap), () => resetInterceptor(runner, options);
-}
-function supportRelativeURL(file, url) {
- if (!file) return url;
- let dir = posixDirname(slash(file)), match = /^\w+:\/\/[^/]*/.exec(dir), protocol = match ? match[0] : "", startPath = dir.slice(protocol.length);
- return protocol && /^\/\w:/.test(startPath) ? (protocol += "/", protocol + slash(posixResolve(startPath, url))) : protocol + posixResolve(startPath, url);
-}
-function getRunnerSourceMap(position) {
- for (let moduleGraph of evaluatedModulesCache) {
- let sourceMap = moduleGraph.getModuleSourceMapById(position.source);
- if (sourceMap) return {
- url: position.source,
- map: sourceMap,
- vite: !0
- };
- }
- return null;
-}
-function retrieveFile(path) {
- if (path in fileContentsCache) return fileContentsCache[path];
- let content = retrieveFileFromHandlers(path);
- return typeof content == "string" ? (fileContentsCache[path] = content, content) : null;
-}
-function retrieveSourceMapURL(source) {
- let fileData = retrieveFile(source);
- if (!fileData) return null;
- let re = /\/\/[@#]\s*sourceMappingURL=([^\s'"]+)\s*$|\/\*[@#]\s*sourceMappingURL=[^\s*'"]+\s*\*\/\s*$/gm, lastMatch, match;
- for (; match = re.exec(fileData);) lastMatch = match;
- return lastMatch ? lastMatch[1] : null;
-}
-const reSourceMap = /^data:application\/json[^,]+base64,/;
-function retrieveSourceMap(source) {
- let urlAndMap = retrieveSourceMapFromHandlers(source);
- if (urlAndMap) return urlAndMap;
- let sourceMappingURL = retrieveSourceMapURL(source);
- if (!sourceMappingURL) return null;
- let sourceMapData;
- if (reSourceMap.test(sourceMappingURL)) {
- let rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
- sourceMapData = Buffer.from(rawData, "base64").toString(), sourceMappingURL = source;
- } else sourceMappingURL = supportRelativeURL(source, sourceMappingURL), sourceMapData = retrieveFile(sourceMappingURL);
- return sourceMapData ? {
- url: sourceMappingURL,
- map: sourceMapData
- } : null;
-}
-function mapSourcePosition(position) {
- if (!position.source) return position;
- let sourceMap = getRunnerSourceMap(position);
- if (sourceMap ||= sourceMapCache[position.source], !sourceMap) {
- let urlAndMap = retrieveSourceMap(position.source);
- if (urlAndMap && urlAndMap.map) {
- let url = urlAndMap.url;
- sourceMap = sourceMapCache[position.source] = {
- url,
- map: new DecodedMap(typeof urlAndMap.map == "string" ? JSON.parse(urlAndMap.map) : urlAndMap.map, url)
- };
- let contents = sourceMap.map?.map.sourcesContent;
- sourceMap.map && contents && sourceMap.map.resolvedSources.forEach((source, i) => {
- let content = contents[i];
- if (content && source && url) {
- let contentUrl = supportRelativeURL(url, source);
- fileContentsCache[contentUrl] = content;
- }
- });
- } else sourceMap = sourceMapCache[position.source] = {
- url: null,
- map: null
- };
- }
- if (sourceMap.map && sourceMap.url) {
- let originalPosition = getOriginalPosition(sourceMap.map, position);
- if (originalPosition && originalPosition.source != null) return originalPosition.source = supportRelativeURL(sourceMap.url, originalPosition.source), sourceMap.vite && (originalPosition._vite = !0), originalPosition;
- }
- return position;
-}
-function mapEvalOrigin(origin) {
- let match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
- if (match) {
- let position = mapSourcePosition({
- name: null,
- source: match[2],
- line: +match[3],
- column: match[4] - 1
- });
- return `eval at ${match[1]} (${position.source}:${position.line}:${position.column + 1})`;
- }
- return match = /^eval at ([^(]+) \((.+)\)$/.exec(origin), match ? `eval at ${match[1]} (${mapEvalOrigin(match[2])})` : origin;
-}
-function CallSiteToString() {
- let fileName, fileLocation = "";
- if (this.isNative()) fileLocation = "native";
- else {
- fileName = this.getScriptNameOrSourceURL(), !fileName && this.isEval() && (fileLocation = this.getEvalOrigin(), fileLocation += ", "), fileName ? fileLocation += fileName : fileLocation += "<anonymous>";
- let lineNumber = this.getLineNumber();
- if (lineNumber != null) {
- fileLocation += `:${lineNumber}`;
- let columnNumber = this.getColumnNumber();
- columnNumber && (fileLocation += `:${columnNumber}`);
- }
- }
- let line = "", functionName = this.getFunctionName(), addSuffix = !0, isConstructor = this.isConstructor();
- if (this.isToplevel() || isConstructor) isConstructor ? line += `new ${functionName || "<anonymous>"}` : functionName ? line += functionName : (line += fileLocation, addSuffix = !1);
- else {
- let typeName = this.getTypeName();
- typeName === "[object Object]" && (typeName = "null");
- let methodName = this.getMethodName();
- functionName ? (typeName && functionName.indexOf(typeName) !== 0 && (line += `${typeName}.`), line += functionName, methodName && functionName.indexOf(`.${methodName}`) !== functionName.length - methodName.length - 1 && (line += ` [as ${methodName}]`)) : line += `${typeName}.${methodName || "<anonymous>"}`;
- }
- return addSuffix && (line += ` (${fileLocation})`), line;
-}
-function cloneCallSite(frame) {
- let object = {};
- return Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach((name) => {
- let key = name;
- object[key] = /^(?:is|get)/.test(name) ? function() {
- return frame[key].call(frame);
- } : frame[key];
- }), object.toString = CallSiteToString, object;
-}
-function wrapCallSite(frame, state) {
- if (state === void 0 && (state = {
- nextPosition: null,
- curPosition: null
- }), frame.isNative()) return state.curPosition = null, frame;
- let source = frame.getFileName() || frame.getScriptNameOrSourceURL();
- if (source) {
- let line = frame.getLineNumber(), column = frame.getColumnNumber() - 1;
- line === 1 && column > 62 && !frame.isEval() && (column -= 62);
- let position = mapSourcePosition({
- name: null,
- source,
- line,
- column
- });
- state.curPosition = position, frame = cloneCallSite(frame);
- let originalFunctionName = frame.getFunctionName;
- return frame.getFunctionName = function() {
- let name = (() => state.nextPosition == null ? originalFunctionName() : state.nextPosition.name || originalFunctionName())();
- return name === "eval" && "_vite" in position ? null : name;
- }, frame.getFileName = function() {
- return position.source ?? null;
- }, frame.getLineNumber = function() {
- return position.line;
- }, frame.getColumnNumber = function() {
- return position.column + 1;
- }, frame.getScriptNameOrSourceURL = function() {
- return position.source;
- }, frame;
- }
- let origin = frame.isEval() && frame.getEvalOrigin();
- return origin ? (origin = mapEvalOrigin(origin), frame = cloneCallSite(frame), frame.getEvalOrigin = function() {
- return origin || void 0;
- }, frame) : frame;
-}
-function prepareStackTrace(error, stack) {
- let errorString = `${error.name || "Error"}: ${error.message || ""}`, state = {
- nextPosition: null,
- curPosition: null
- }, processedStack = [];
- for (let i = stack.length - 1; i >= 0; i--) processedStack.push(`\n at ${wrapCallSite(stack[i], state)}`), state.nextPosition = state.curPosition;
- return state.curPosition = state.nextPosition = null, errorString + processedStack.reverse().join("");
-}
-function enableSourceMapSupport(runner) {
- if (runner.options.sourcemapInterceptor === "node") {
- if (typeof process > "u") throw TypeError("Cannot use \"sourcemapInterceptor: 'node'\" because global \"process\" variable is not available.");
- if (typeof process.setSourceMapsEnabled != "function") throw TypeError("Cannot use \"sourcemapInterceptor: 'node'\" because \"process.setSourceMapsEnabled\" function is not available. Please use Node >= 16.6.0.");
- let isEnabledAlready = process.sourceMapsEnabled ?? !1;
- return process.setSourceMapsEnabled(!0), () => !isEnabledAlready && process.setSourceMapsEnabled(!1);
- }
- return interceptStackTrace(runner, typeof runner.options.sourcemapInterceptor == "object" ? runner.options.sourcemapInterceptor : void 0);
-}
-var ESModulesEvaluator = class {
- startOffset = getAsyncFunctionDeclarationPaddingLineCount();
- async runInlinedModule(context, code) {
- await new AsyncFunction(ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, ssrExportNameKey, "\"use strict\";" + code)(context[ssrModuleExportsKey], context[ssrImportMetaKey], context[ssrImportKey], context[ssrDynamicImportKey], context[ssrExportAllKey], context[ssrExportNameKey]), Object.seal(context[ssrModuleExportsKey]);
- }
- runExternalModule(filepath) {
- return import(filepath);
- }
-};
-const customizationHookNamespace = "vite-module-runner:import-meta-resolve/v1/", customizationHooksModule = `
-
-export async function resolve(specifier, context, nextResolve) {
- if (specifier.startsWith(${JSON.stringify(customizationHookNamespace)})) {
- const data = specifier.slice(${JSON.stringify(customizationHookNamespace)}.length)
- const [parsedSpecifier, parsedImporter] = JSON.parse(data)
- specifier = parsedSpecifier
- context.parentURL = parsedImporter
- }
- return nextResolve(specifier, context)
-}
-
-`;
-function customizationHookResolve(specifier, context, nextResolve) {
- if (specifier.startsWith(customizationHookNamespace)) {
- let data = specifier.slice(42), [parsedSpecifier, parsedImporter] = JSON.parse(data);
- specifier = parsedSpecifier, context.parentURL = parsedImporter;
- }
- return nextResolve(specifier, context);
-}
-async function createImportMetaResolver() {
- let module;
- try {
- module = (await import("node:module")).Module;
- } catch {
- return;
- }
- if (module) {
- if (module.registerHooks) return module.registerHooks({ resolve: customizationHookResolve }), importMetaResolveWithCustomHook;
- if (module.register) {
- try {
- let hookModuleContent = `data:text/javascript,${encodeURI(customizationHooksModule)}`;
- module.register(hookModuleContent);
- } catch (e) {
- if ("code" in e && e.code === "ERR_NETWORK_IMPORT_DISALLOWED") return;
- throw e;
- }
- return importMetaResolveWithCustomHook;
- }
- }
-}
-function importMetaResolveWithCustomHook(specifier, importer) {
- return import.meta.resolve(`${customizationHookNamespace}${JSON.stringify([specifier, importer])}`);
-}
-`${customizationHookNamespace}`;
-const envProxy = new Proxy({}, { get(_, p) {
- throw Error(`[module runner] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`);
-} });
-function createDefaultImportMeta(modulePath) {
- let href = posixPathToFileHref(modulePath), filename = modulePath, dirname$1 = posixDirname(modulePath);
- return {
- filename: isWindows ? toWindowsPath(filename) : filename,
- dirname: isWindows ? toWindowsPath(dirname$1) : dirname$1,
- url: href,
- env: envProxy,
- resolve(_id, _parent) {
- throw Error("[module runner] \"import.meta.resolve\" is not supported.");
- },
- glob() {
- throw Error("[module runner] \"import.meta.glob\" is statically replaced during file transformation. Make sure to reference it by the full name.");
- }
- };
-}
-let importMetaResolverCache;
-async function createNodeImportMeta(modulePath) {
- let defaultMeta = createDefaultImportMeta(modulePath), href = defaultMeta.url;
- importMetaResolverCache ??= createImportMetaResolver();
- let importMetaResolver = await importMetaResolverCache;
- return {
- ...defaultMeta,
- main: !1,
- resolve(id, parent) {
- return (importMetaResolver ?? defaultMeta.resolve)(id, parent ?? href);
- }
- };
-}
-var ModuleRunner = class {
- evaluatedModules;
- hmrClient;
- transport;
- resetSourceMapSupport;
- concurrentModuleNodePromises = /* @__PURE__ */ new Map();
- isBuiltin;
- builtinsPromise;
- closed = !1;
- constructor(options, evaluator = new ESModulesEvaluator(), debug) {
- if (this.options = options, this.evaluator = evaluator, this.debug = debug, this.evaluatedModules = options.evaluatedModules ?? new EvaluatedModules(), this.transport = normalizeModuleRunnerTransport(options.transport), options.hmr !== !1) {
- let optionsHmr = options.hmr ?? !0;
- if (this.hmrClient = new HMRClient(optionsHmr === !0 || optionsHmr.logger === void 0 ? hmrLogger : optionsHmr.logger === !1 ? silentConsole : optionsHmr.logger, this.transport, ({ acceptedPath }) => this.import(acceptedPath)), !this.transport.connect) throw Error("HMR is not supported by this runner transport, but `hmr` option was set to true");
- this.transport.connect(createHMRHandlerForRunner(this));
- } else this.transport.connect?.();
- options.sourcemapInterceptor !== !1 && (this.resetSourceMapSupport = enableSourceMapSupport(this));
- }
- async import(url) {
- let fetchedModule = await this.cachedModule(url);
- return await this.cachedRequest(url, fetchedModule);
- }
- clearCache() {
- this.evaluatedModules.clear(), this.hmrClient?.clear();
- }
- async close() {
- this.resetSourceMapSupport?.(), this.clearCache(), this.hmrClient = void 0, this.closed = !0, await this.transport.disconnect?.();
- }
- isClosed() {
- return this.closed;
- }
- processImport(exports, fetchResult, metadata) {
- if (!("externalize" in fetchResult)) return exports;
- let { url, type } = fetchResult;
- return type !== "module" && type !== "commonjs" || analyzeImportedModDifference(exports, url, type, metadata), exports;
- }
- isCircularModule(mod) {
- for (let importedFile of mod.imports) if (mod.importers.has(importedFile)) return !0;
- return !1;
- }
- isCircularImport(importers, moduleUrl, visited = /* @__PURE__ */ new Set()) {
- for (let importer of importers) {
- if (visited.has(importer)) continue;
- if (visited.add(importer), importer === moduleUrl) return !0;
- let mod = this.evaluatedModules.getModuleById(importer);
- if (mod && mod.importers.size && this.isCircularImport(mod.importers, moduleUrl, visited)) return !0;
- }
- return !1;
- }
- async cachedRequest(url, mod, callstack = [], metadata) {
- let meta = mod.meta, moduleId = meta.id, { importers } = mod, importee = callstack[callstack.length - 1];
- if (importee && importers.add(importee), (callstack.includes(moduleId) || this.isCircularModule(mod) || this.isCircularImport(importers, moduleId)) && mod.exports) return this.processImport(mod.exports, meta, metadata);
- let debugTimer;
- this.debug && (debugTimer = setTimeout(() => {
- this.debug(`[module runner] module ${moduleId} takes over 2s to load.\n${(() => `stack:\n${[...callstack, moduleId].reverse().map((p) => ` - ${p}`).join("\n")}`)()}`);
- }, 2e3));
- try {
- if (mod.promise) return this.processImport(await mod.promise, meta, metadata);
- let promise = this.directRequest(url, mod, callstack);
- return mod.promise = promise, mod.evaluated = !1, this.processImport(await promise, meta, metadata);
- } finally {
- mod.evaluated = !0, debugTimer && clearTimeout(debugTimer);
- }
- }
- async cachedModule(url, importer) {
- let cached = this.concurrentModuleNodePromises.get(url);
- if (cached) this.debug?.("[module runner] using cached module info for", url);
- else {
- let cachedModule = this.evaluatedModules.getModuleByUrl(url);
- cached = this.getModuleInformation(url, importer, cachedModule).finally(() => {
- this.concurrentModuleNodePromises.delete(url);
- }), this.concurrentModuleNodePromises.set(url, cached);
- }
- return cached;
- }
- ensureBuiltins() {
- if (!this.isBuiltin) return this.builtinsPromise ??= (async () => {
- try {
- this.debug?.("[module runner] fetching builtins from server");
- let builtins = (await this.transport.invoke("getBuiltins", [])).map((builtin) => typeof builtin == "object" && builtin && "type" in builtin ? builtin.type === "string" ? builtin.value : new RegExp(builtin.source, builtin.flags) : builtin);
- this.isBuiltin = createIsBuiltin(builtins), this.debug?.("[module runner] builtins loaded:", builtins);
- } finally {
- this.builtinsPromise = void 0;
- }
- })(), this.builtinsPromise;
- }
- async getModuleInformation(url, importer, cachedModule) {
- if (this.closed) throw Error("Vite module runner has been closed.");
- await this.ensureBuiltins(), this.debug?.("[module runner] fetching", url);
- let isCached = !!(typeof cachedModule == "object" && cachedModule.meta), fetchedModule = url.startsWith("data:") || this.isBuiltin?.(url) ? {
- externalize: url,
- type: "builtin"
- } : await this.transport.invoke("fetchModule", [
- url,
- importer,
- {
- cached: isCached,
- startOffset: this.evaluator.startOffset
- }
- ]);
- if ("cache" in fetchedModule) {
- if (!cachedModule || !cachedModule.meta) throw Error(`Module "${url}" was mistakenly invalidated during fetch phase.`);
- return cachedModule;
- }
- let moduleId = "externalize" in fetchedModule ? fetchedModule.externalize : fetchedModule.id, moduleUrl = "url" in fetchedModule ? fetchedModule.url : url, module = this.evaluatedModules.ensureModule(moduleId, moduleUrl);
- return "invalidate" in fetchedModule && fetchedModule.invalidate && this.evaluatedModules.invalidateModule(module), fetchedModule.url = moduleUrl, fetchedModule.id = moduleId, module.meta = fetchedModule, module;
- }
- async directRequest(url, mod, _callstack) {
- let fetchResult = mod.meta, moduleId = fetchResult.id, callstack = [..._callstack, moduleId], request = async (dep, metadata) => {
- let importer = "file" in fetchResult && fetchResult.file || moduleId, depMod = await this.cachedModule(dep, importer);
- return depMod.importers.add(moduleId), mod.imports.add(depMod.id), this.cachedRequest(dep, depMod, callstack, metadata);
- }, dynamicRequest = async (dep) => (dep = String(dep), dep[0] === "." && (dep = posixResolve(posixDirname(url), dep)), request(dep, { isDynamicImport: !0 }));
- if ("externalize" in fetchResult) {
- let { externalize } = fetchResult;
- this.debug?.("[module runner] externalizing", externalize);
- let exports$1 = await this.evaluator.runExternalModule(externalize);
- return mod.exports = exports$1, exports$1;
- }
- let { code, file } = fetchResult;
- if (code == null) {
- let importer = callstack[callstack.length - 2];
- throw Error(`[module runner] Failed to load "${url}"${importer ? ` imported from ${importer}` : ""}`);
- }
- let createImportMeta = this.options.createImportMeta ?? createDefaultImportMeta, modulePath = cleanUrl(file || moduleId), href = posixPathToFileHref(modulePath), meta = await createImportMeta(modulePath), exports = Object.create(null);
- Object.defineProperty(exports, Symbol.toStringTag, {
- value: "Module",
- enumerable: !1,
- configurable: !1
- }), mod.exports = exports;
- let hotContext;
- this.hmrClient && Object.defineProperty(meta, "hot", {
- enumerable: !0,
- get: () => {
- if (!this.hmrClient) throw Error("[module runner] HMR client was closed.");
- return this.debug?.("[module runner] creating hmr context for", mod.url), hotContext ||= new HMRContext(this.hmrClient, mod.url), hotContext;
- },
- set: (value) => {
- hotContext = value;
- }
- });
- let context = {
- [ssrImportKey]: request,
- [ssrDynamicImportKey]: dynamicRequest,
- [ssrModuleExportsKey]: exports,
- [ssrExportAllKey]: (obj) => exportAll(exports, obj),
- [ssrExportNameKey]: (name, getter) => Object.defineProperty(exports, name, {
- enumerable: !0,
- configurable: !0,
- get: getter
- }),
- [ssrImportMetaKey]: meta
- };
- return this.debug?.("[module runner] executing", href), await this.evaluator.runInlinedModule(context, code, mod), exports;
- }
-};
-function exportAll(exports, sourceModule) {
- if (exports !== sourceModule && !(isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise)) {
- for (let key in sourceModule) if (key !== "default" && key !== "__esModule" && !(key in exports)) try {
- Object.defineProperty(exports, key, {
- enumerable: !0,
- configurable: !0,
- get: () => sourceModule[key]
- });
- } catch {}
- }
-}
-export { ESModulesEvaluator, EvaluatedModules, ModuleRunner, createDefaultImportMeta, createNodeImportMeta, createWebSocketModuleRunnerTransport, normalizeModuleId, ssrDynamicImportKey, ssrExportAllKey, ssrExportNameKey, ssrImportKey, ssrImportMetaKey, ssrModuleExportsKey };
diff --git a/vanilla/node_modules/vite/misc/false.js b/vanilla/node_modules/vite/misc/false.js
deleted file mode 100644
index 2693369..0000000
--- a/vanilla/node_modules/vite/misc/false.js
+++ /dev/null
@@ -1 +0,0 @@
-export default false
diff --git a/vanilla/node_modules/vite/misc/true.js b/vanilla/node_modules/vite/misc/true.js
deleted file mode 100644
index 186b120..0000000
--- a/vanilla/node_modules/vite/misc/true.js
+++ /dev/null
@@ -1 +0,0 @@
-export default true
diff --git a/vanilla/node_modules/vite/package.json b/vanilla/node_modules/vite/package.json
deleted file mode 100644
index 68a2789..0000000
--- a/vanilla/node_modules/vite/package.json
+++ /dev/null
@@ -1,199 +0,0 @@
-{
- "name": "vite",
- "version": "7.3.1",
- "type": "module",
- "license": "MIT",
- "author": "Evan You",
- "description": "Native-ESM powered web dev build tool",
- "bin": {
- "vite": "bin/vite.js"
- },
- "keywords": [
- "frontend",
- "framework",
- "hmr",
- "dev-server",
- "build-tool",
- "vite"
- ],
- "main": "./dist/node/index.js",
- "types": "./dist/node/index.d.ts",
- "exports": {
- ".": "./dist/node/index.js",
- "./client": {
- "types": "./client.d.ts"
- },
- "./module-runner": "./dist/node/module-runner.js",
- "./dist/client/*": "./dist/client/*",
- "./types/*": {
- "types": "./types/*"
- },
- "./types/internal/*": null,
- "./package.json": "./package.json"
- },
- "typesVersions": {
- "*": {
- "module-runner": [
- "dist/node/module-runner.d.ts"
- ]
- }
- },
- "imports": {
- "#module-sync-enabled": {
- "module-sync": "./misc/true.js",
- "default": "./misc/false.js"
- },
- "#types/*": "./types/*.d.ts",
- "#dep-types/*": "./src/types/*.d.ts"
- },
- "files": [
- "bin",
- "dist",
- "misc/**/*.js",
- "client.d.ts",
- "types"
- ],
- "engines": {
- "node": "^20.19.0 || >=22.12.0"
- },
- "repository": {
- "type": "git",
- "url": "git+https://github.com/vitejs/vite.git",
- "directory": "packages/vite"
- },
- "bugs": {
- "url": "https://github.com/vitejs/vite/issues"
- },
- "homepage": "https://vite.dev",
- "funding": "https://github.com/vitejs/vite?sponsor=1",
- "//": "READ CONTRIBUTING.md to understand what to put under deps vs. devDeps!",
- "dependencies": {
- "esbuild": "^0.27.0",
- "fdir": "^6.5.0",
- "picomatch": "^4.0.3",
- "postcss": "^8.5.6",
- "rollup": "^4.43.0",
- "tinyglobby": "^0.2.15"
- },
- "optionalDependencies": {
- "fsevents": "~2.3.3"
- },
- "devDependencies": {
- "@babel/parser": "^7.28.5",
- "@jridgewell/remapping": "^2.3.5",
- "@jridgewell/trace-mapping": "^0.3.31",
- "@oxc-project/types": "0.95.0",
- "@polka/compression": "^1.0.0-next.25",
- "@rolldown/pluginutils": "^1.0.0-beta.52",
- "@rollup/plugin-alias": "^5.1.1",
- "@rollup/plugin-commonjs": "^29.0.0",
- "@rollup/plugin-dynamic-import-vars": "2.1.4",
- "@rollup/pluginutils": "^5.3.0",
- "@types/escape-html": "^1.0.4",
- "@types/pnpapi": "^0.0.5",
- "artichokie": "^0.4.2",
- "baseline-browser-mapping": "^2.8.32",
- "cac": "^6.7.14",
- "chokidar": "^3.6.0",
- "connect": "^3.7.0",
- "convert-source-map": "^2.0.0",
- "cors": "^2.8.5",
- "cross-spawn": "^7.0.6",
- "obug": "^1.0.2",
- "dotenv": "^17.2.3",
- "dotenv-expand": "^12.0.3",
- "es-module-lexer": "^1.7.0",
- "escape-html": "^1.0.3",
- "estree-walker": "^3.0.3",
- "etag": "^1.8.1",
- "host-validation-middleware": "^0.1.2",
- "http-proxy-3": "^1.22.0",
- "launch-editor-middleware": "^2.12.0",
- "lightningcss": "^1.30.2",
- "magic-string": "^0.30.21",
- "mlly": "^1.8.0",
- "mrmime": "^2.0.1",
- "nanoid": "^5.1.6",
- "open": "^10.2.0",
- "parse5": "^8.0.0",
- "pathe": "^2.0.3",
- "periscopic": "^4.0.2",
- "picocolors": "^1.1.1",
- "postcss-import": "^16.1.1",
- "postcss-load-config": "^6.0.1",
- "postcss-modules": "^6.0.1",
- "premove": "^4.0.0",
- "resolve.exports": "^2.0.3",
- "rolldown": "^1.0.0-beta.52",
- "rolldown-plugin-dts": "^0.18.1",
- "rollup-plugin-license": "^3.6.0",
- "sass": "^1.94.2",
- "sass-embedded": "^1.93.3",
- "sirv": "^3.0.2",
- "strip-literal": "^3.1.0",
- "terser": "^5.44.1",
- "tsconfck": "^3.1.6",
- "ufo": "^1.6.1",
- "ws": "^8.18.3"
- },
- "peerDependencies": {
- "@types/node": "^20.19.0 || >=22.12.0",
- "jiti": ">=1.21.0",
- "less": "^4.0.0",
- "lightningcss": "^1.21.0",
- "sass": "^1.70.0",
- "sass-embedded": "^1.70.0",
- "stylus": ">=0.54.8",
- "sugarss": "^5.0.0",
- "terser": "^5.16.0",
- "tsx": "^4.8.1",
- "yaml": "^2.4.2"
- },
- "peerDependenciesMeta": {
- "@types/node": {
- "optional": true
- },
- "jiti": {
- "optional": true
- },
- "sass": {
- "optional": true
- },
- "sass-embedded": {
- "optional": true
- },
- "stylus": {
- "optional": true
- },
- "less": {
- "optional": true
- },
- "sugarss": {
- "optional": true
- },
- "lightningcss": {
- "optional": true
- },
- "terser": {
- "optional": true
- },
- "tsx": {
- "optional": true
- },
- "yaml": {
- "optional": true
- }
- },
- "scripts": {
- "dev": "premove dist && pnpm build-bundle -w",
- "build": "premove dist && pnpm build-bundle && pnpm build-types",
- "build-bundle": "rolldown --config rolldown.config.ts",
- "build-types": "pnpm build-types-roll && pnpm build-types-check",
- "build-types-roll": "rolldown --config rolldown.dts.config.ts",
- "build-types-check": "tsc --project tsconfig.check.json",
- "typecheck": "tsc && tsc -p src/node && tsc -p src/module-runner && tsc -p src/shared && tsc -p src/node/__tests_dts__",
- "lint": "eslint --cache --ext .ts src/**",
- "format": "prettier --write --cache --parser typescript \"src/**/*.ts\"",
- "generate-target": "tsx scripts/generateTarget.ts"
- }
-} \ No newline at end of file
diff --git a/vanilla/node_modules/vite/types/customEvent.d.ts b/vanilla/node_modules/vite/types/customEvent.d.ts
deleted file mode 100644
index 489d78e..0000000
--- a/vanilla/node_modules/vite/types/customEvent.d.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import type {
- ErrorPayload,
- FullReloadPayload,
- PrunePayload,
- UpdatePayload,
-} from './hmrPayload'
-
-export interface CustomEventMap {
- // client events
- 'vite:beforeUpdate': UpdatePayload
- 'vite:afterUpdate': UpdatePayload
- 'vite:beforePrune': PrunePayload
- 'vite:beforeFullReload': FullReloadPayload
- 'vite:error': ErrorPayload
- 'vite:invalidate': InvalidatePayload
- 'vite:ws:connect': WebSocketConnectionPayload
- 'vite:ws:disconnect': WebSocketConnectionPayload
-
- // server events
- 'vite:client:connect': undefined
- 'vite:client:disconnect': undefined
-}
-
-export interface WebSocketConnectionPayload {
- /**
- * @experimental
- * We expose this instance experimentally to see potential usage.
- * This might be removed in the future if we didn't find reasonable use cases.
- * If you find this useful, please open an issue with details so we can discuss and make it stable API.
- */
- // eslint-disable-next-line n/no-unsupported-features/node-builtins
- webSocket: WebSocket
-}
-
-export interface InvalidatePayload {
- path: string
- message: string | undefined
- firstInvalidatedBy: string
-}
-
-/**
- * provides types for payloads of built-in Vite events
- */
-export type InferCustomEventPayload<T extends string> =
- T extends keyof CustomEventMap ? CustomEventMap[T] : any
-
-/**
- * provides types for names of built-in Vite events
- */
-export type CustomEventName = keyof CustomEventMap | (string & {})
diff --git a/vanilla/node_modules/vite/types/hmrPayload.d.ts b/vanilla/node_modules/vite/types/hmrPayload.d.ts
deleted file mode 100644
index 0cbd649..0000000
--- a/vanilla/node_modules/vite/types/hmrPayload.d.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-/** @deprecated use HotPayload */
-export type HMRPayload = HotPayload
-export type HotPayload =
- | ConnectedPayload
- | PingPayload
- | UpdatePayload
- | FullReloadPayload
- | CustomPayload
- | ErrorPayload
- | PrunePayload
-
-export interface ConnectedPayload {
- type: 'connected'
-}
-
-export interface PingPayload {
- type: 'ping'
-}
-
-export interface UpdatePayload {
- type: 'update'
- updates: Update[]
-}
-
-export interface Update {
- type: 'js-update' | 'css-update'
- path: string
- acceptedPath: string
- timestamp: number
- /** @internal */
- explicitImportRequired?: boolean
- /** @internal */
- isWithinCircularImport?: boolean
- /** @internal */
- firstInvalidatedBy?: string
- /** @internal */
- invalidates?: string[]
-}
-
-export interface PrunePayload {
- type: 'prune'
- paths: string[]
-}
-
-export interface FullReloadPayload {
- type: 'full-reload'
- path?: string
- /** @internal */
- triggeredBy?: string
-}
-
-export interface CustomPayload {
- type: 'custom'
- event: string
- data?: any
-}
-
-export interface ErrorPayload {
- type: 'error'
- err: {
- [name: string]: any
- message: string
- stack: string
- id?: string
- frame?: string
- plugin?: string
- pluginCode?: string
- loc?: {
- file?: string
- line: number
- column: number
- }
- }
-}
diff --git a/vanilla/node_modules/vite/types/hot.d.ts b/vanilla/node_modules/vite/types/hot.d.ts
deleted file mode 100644
index bc09e99..0000000
--- a/vanilla/node_modules/vite/types/hot.d.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import type { CustomEventName, InferCustomEventPayload } from './customEvent'
-
-export type ModuleNamespace = Record<string, any> & {
- [Symbol.toStringTag]: 'Module'
-}
-
-export interface ViteHotContext {
- readonly data: any
-
- accept(): void
- accept(cb: (mod: ModuleNamespace | undefined) => void): void
- accept(dep: string, cb: (mod: ModuleNamespace | undefined) => void): void
- accept(
- deps: readonly string[],
- cb: (mods: Array<ModuleNamespace | undefined>) => void,
- ): void
-
- acceptExports(
- exportNames: string | readonly string[],
- cb?: (mod: ModuleNamespace | undefined) => void,
- ): void
-
- dispose(cb: (data: any) => void): void
- prune(cb: (data: any) => void): void
- invalidate(message?: string): void
-
- on<T extends CustomEventName>(
- event: T,
- cb: (payload: InferCustomEventPayload<T>) => void,
- ): void
- off<T extends CustomEventName>(
- event: T,
- cb: (payload: InferCustomEventPayload<T>) => void,
- ): void
- send<T extends CustomEventName>(
- event: T,
- data?: InferCustomEventPayload<T>,
- ): void
-}
diff --git a/vanilla/node_modules/vite/types/import-meta.d.ts b/vanilla/node_modules/vite/types/import-meta.d.ts
deleted file mode 100644
index ee00ff5..0000000
--- a/vanilla/node_modules/vite/types/import-meta.d.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-/// <reference path="./importMeta.d.ts" />
-
-// https://github.com/microsoft/TypeScript/issues/45096
-// TypeScript has a bug that makes <reference types="vite/types/importMeta" />
-// not possible in userland. This file provides a workaround for now.
diff --git a/vanilla/node_modules/vite/types/importGlob.d.ts b/vanilla/node_modules/vite/types/importGlob.d.ts
deleted file mode 100644
index dfd6f6f..0000000
--- a/vanilla/node_modules/vite/types/importGlob.d.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-export interface ImportGlobOptions<
- Eager extends boolean,
- AsType extends string,
-> {
- /**
- * Import type for the import url.
- *
- * @deprecated Use `query` instead, e.g. `as: 'url'` -> `query: '?url', import: 'default'`
- */
- as?: AsType
- /**
- * Import as static or dynamic
- *
- * @default false
- */
- eager?: Eager
- /**
- * Import only the specific named export. Set to `default` to import the default export.
- */
- import?: string
- /**
- * Custom queries
- */
- query?: string | Record<string, string | number | boolean>
- /**
- * Search files also inside `node_modules/` and hidden directories (e.g. `.git/`). This might have impact on performance.
- *
- * @default false
- */
- exhaustive?: boolean
- /**
- * Base path to resolve relative paths.
- */
- base?: string
-}
-
-export type GeneralImportGlobOptions = ImportGlobOptions<boolean, string>
-
-/**
- * Declare Worker in case DOM is not added to the tsconfig lib causing
- * Worker interface is not defined. For developers with DOM lib added,
- * the Worker interface will be merged correctly.
- */
-declare global {
- // eslint-disable-next-line @typescript-eslint/no-empty-object-type
- interface Worker {}
-}
-
-export interface KnownAsTypeMap {
- raw: string
- url: string
- worker: Worker
-}
-
-export interface ImportGlobFunction {
- /**
- * Import a list of files with a glob pattern.
- *
- * Overload 1: No generic provided, infer the type from `eager` and `as`
- */
- <
- Eager extends boolean,
- As extends string,
- T = As extends keyof KnownAsTypeMap ? KnownAsTypeMap[As] : unknown,
- >(
- glob: string | string[],
- options?: ImportGlobOptions<Eager, As>,
- ): (Eager extends true ? true : false) extends true
- ? Record<string, T>
- : Record<string, () => Promise<T>>
- /**
- * Import a list of files with a glob pattern.
- *
- * Overload 2: Module generic provided, infer the type from `eager: false`
- */
- <M>(
- glob: string | string[],
- options?: ImportGlobOptions<false, string>,
- ): Record<string, () => Promise<M>>
- /**
- * Import a list of files with a glob pattern.
- *
- * Overload 3: Module generic provided, infer the type from `eager: true`
- */
- <M>(
- glob: string | string[],
- options: ImportGlobOptions<true, string>,
- ): Record<string, M>
-}
diff --git a/vanilla/node_modules/vite/types/importMeta.d.ts b/vanilla/node_modules/vite/types/importMeta.d.ts
deleted file mode 100644
index 01d9d39..0000000
--- a/vanilla/node_modules/vite/types/importMeta.d.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-// This file is an augmentation to the built-in ImportMeta interface
-// Thus cannot contain any top-level imports
-// <https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation>
-
-// This is tested in `packages/vite/src/node/__tests_dts__/typeOptions.ts`
-// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- to allow extending by users
-interface ViteTypeOptions {
- // strictImportMetaEnv: unknown
-}
-
-type ImportMetaEnvFallbackKey =
- 'strictImportMetaEnv' extends keyof ViteTypeOptions ? never : string
-
-interface ImportMetaEnv extends Record<ImportMetaEnvFallbackKey, any> {
- BASE_URL: string
- MODE: string
- DEV: boolean
- PROD: boolean
- SSR: boolean
-}
-
-interface ImportMeta {
- url: string
-
- readonly hot?: import('./hot').ViteHotContext
-
- readonly env: ImportMetaEnv
-
- glob: import('./importGlob').ImportGlobFunction
-}
diff --git a/vanilla/node_modules/vite/types/internal/cssPreprocessorOptions.d.ts b/vanilla/node_modules/vite/types/internal/cssPreprocessorOptions.d.ts
deleted file mode 100644
index ca87ba8..0000000
--- a/vanilla/node_modules/vite/types/internal/cssPreprocessorOptions.d.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-/* eslint-disable @typescript-eslint/ban-ts-comment */
-
-// @ts-ignore `sass` may not be installed
-import type DartSass from 'sass'
-// @ts-ignore `sass-embedded` may not be installed
-import type SassEmbedded from 'sass-embedded'
-// @ts-ignore `less` may not be installed
-import type Less from 'less'
-// @ts-ignore `stylus` may not be installed
-import type Stylus from 'stylus'
-
-/* eslint-enable @typescript-eslint/ban-ts-comment */
-
-// https://github.com/type-challenges/type-challenges/issues/29285
-type IsAny<T> = boolean extends (T extends never ? true : false) ? true : false
-
-type DartSassStringOptionsAsync = DartSass.StringOptions<'async'>
-type SassEmbeddedStringOptionsAsync = SassEmbedded.StringOptions<'async'>
-type SassStringOptionsAsync =
- IsAny<SassEmbeddedStringOptionsAsync> extends false
- ? SassEmbeddedStringOptionsAsync
- : DartSassStringOptionsAsync
-
-export type SassModernPreprocessBaseOptions = Omit<
- SassStringOptionsAsync,
- 'url' | 'sourceMap'
->
-
-export type LessPreprocessorBaseOptions = Omit<
- Less.Options,
- 'sourceMap' | 'filename'
->
-
-export type StylusPreprocessorBaseOptions = Omit<
- Stylus.RenderOptions,
- 'filename'
-> & { define?: Record<string, any> }
-
-declare global {
- // LESS' types somewhat references this which doesn't make sense in Node,
- // so we have to shim it
- // eslint-disable-next-line @typescript-eslint/no-empty-object-type
- interface HTMLLinkElement {}
-}
diff --git a/vanilla/node_modules/vite/types/internal/lightningcssOptions.d.ts b/vanilla/node_modules/vite/types/internal/lightningcssOptions.d.ts
deleted file mode 100644
index 48d7114..0000000
--- a/vanilla/node_modules/vite/types/internal/lightningcssOptions.d.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/* eslint-disable @typescript-eslint/ban-ts-comment */
-
-// @ts-ignore `lightningcss` may not be installed
-import type Lightningcss from 'lightningcss'
-
-/* eslint-enable @typescript-eslint/ban-ts-comment */
-
-export type LightningCSSOptions = Omit<
- Lightningcss.BundleAsyncOptions<Lightningcss.CustomAtRules>,
- | 'filename'
- | 'resolver'
- | 'minify'
- | 'sourceMap'
- | 'analyzeDependencies'
- // properties not overridden by Vite, but does not make sense to set by end users
- | 'inputSourceMap'
- | 'projectRoot'
->
diff --git a/vanilla/node_modules/vite/types/internal/terserOptions.d.ts b/vanilla/node_modules/vite/types/internal/terserOptions.d.ts
deleted file mode 100644
index 3d5e08f..0000000
--- a/vanilla/node_modules/vite/types/internal/terserOptions.d.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/* eslint-disable @typescript-eslint/ban-ts-comment */
-
-// @ts-ignore `terser` may not be installed
-export type * as Terser from 'terser'
-// @ts-ignore `terser` may not be installed
-import type * as Terser from 'terser'
-
-/* eslint-enable @typescript-eslint/ban-ts-comment */
-
-export type TerserMinifyOptions = Terser.MinifyOptions
-export type TerserMinifyOutput = Terser.MinifyOutput
diff --git a/vanilla/node_modules/vite/types/metadata.d.ts b/vanilla/node_modules/vite/types/metadata.d.ts
deleted file mode 100644
index 8765291..0000000
--- a/vanilla/node_modules/vite/types/metadata.d.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-export interface ChunkMetadata {
- importedAssets: Set<string>
- importedCss: Set<string>
-}
-
-export interface CustomPluginOptionsVite {
- /**
- * If this is a CSS Rollup module, you can scope to its importer's exports
- * so that if those exports are treeshaken away, the CSS module will also
- * be treeshaken.
- *
- * The "importerId" must import the CSS Rollup module statically.
- *
- * Example config if the CSS id is `/src/App.vue?vue&type=style&lang.css`:
- * ```js
- * cssScopeTo: ['/src/App.vue', 'default']
- * ```
- */
- cssScopeTo?: readonly [importerId: string, exportName: string | undefined]
-
- /** @deprecated no-op since Vite 6.1 */
- lang?: string
-}
-
-declare module 'rollup' {
- export interface RenderedChunk {
- viteMetadata?: ChunkMetadata
- }
-
- export interface CustomPluginOptions {
- vite?: CustomPluginOptionsVite
- }
-}
diff --git a/vanilla/node_modules/vite/types/package.json b/vanilla/node_modules/vite/types/package.json
deleted file mode 100644
index 00efc39..0000000
--- a/vanilla/node_modules/vite/types/package.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "//": "this file is here to make typescript happy when moduleResolution=node16+",
- "version": "0.0.0"
-}