diff --git a/config/routes.php b/config/routes.php index 40a4c9e..016e3f0 100644 --- a/config/routes.php +++ b/config/routes.php @@ -10,5 +10,8 @@ ]) ->methods(['POST']) ->controller('storybook.controller.render_story') + ->add('storybook_preview', '/_storybook/preview') + ->methods(['GET']) + ->controller('storybook.controller.preview') ; }; diff --git a/docs/configuration.md b/docs/configuration.md index bd6b0aa..5b5a389 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -255,12 +255,17 @@ const config: StorybookConfig = { /** * Symfony framework options. - * - * These options only applies to the dev environment. */ - symfony: { + symfony: { + /** + * Mandatory, the absolute path of the Storybook cache path. + * + * @var string + */ + storybookCachePath: path.resolve(__dirname, '../var/cache/dev/storybook'), + /** - * Mandatory, the URL of the Symfony development server. + * Mandatory, the URL of the Symfony application server. * * @var string */ @@ -287,9 +292,9 @@ const config: StorybookConfig = { * @var string[] */ additionalWatchPaths: [ - 'assets', - 'var/tailwind/tailwind.built.css' - ] + '/assets', + '/var/tailwind/tailwind.built.css' + ], } }, }, diff --git a/docs/static-build.md b/docs/static-build.md index 39365d8..6de70c4 100644 --- a/docs/static-build.md +++ b/docs/static-build.md @@ -2,6 +2,9 @@ Storybook can be built in a static application, to be deployed on a simple web server. The build will contain all stories metadata and the JavaScript used to render the Storybook UI. +> ⚠️ In order to build Storybook, you need to have a running Symfony server. +> The Symfony server is used to generate "preview.html.twig" iframe. + ## Build Storybook To build Storybook, use: diff --git a/sandbox/.storybook/main.ts b/sandbox/.storybook/main.ts index 4ca78ee..9886d85 100644 --- a/sandbox/.storybook/main.ts +++ b/sandbox/.storybook/main.ts @@ -1,3 +1,4 @@ +import 'dotenv/config'; import type { StorybookConfig } from "@sensiolabs/storybook-symfony-webpack5"; const config: StorybookConfig = { @@ -57,18 +58,17 @@ const config: StorybookConfig = { options: { // 👇 Here configure the framework symfony: - process.env.NODE_ENV === 'development' - ? { - server: 'http://localhost:8000', - proxyPaths: [ - '/assets', - '/_components', - ], - additionalWatchPaths: [ - 'assets', - ] - } - : {} + { + storybookCachePath: `var/cache/${process.env.APP_ENV}/storybook`, + server: 'http://localhost:8000', + proxyPaths: [ + '/assets', + '/_components', + ], + additionalWatchPaths: [ + '/assets', + ] + } }, }, previewAnnotations: ['./templates/components/Storybook', './template-stories/lib/preview-api/preview.ts', './template-stories/addons/toolbars/preview.ts'], diff --git a/sandbox/package.json b/sandbox/package.json index 1d0d4a2..ea8e0d3 100644 --- a/sandbox/package.json +++ b/sandbox/package.json @@ -10,6 +10,7 @@ "@storybook/global": "5.0.0", "@storybook/test": "^8.1.3", "@storybook/test-runner": "^0.18.2", + "dotenv": "^16.4.7", "esbuild-loader": "^4.1.0", "typescript": "^5.4.2", "wait-on": "^7.2.0", diff --git a/src/CacheWarmer/StorybookCacheWarmer.php b/src/CacheWarmer/StorybookCacheWarmer.php new file mode 100644 index 0000000..f8b9f9f --- /dev/null +++ b/src/CacheWarmer/StorybookCacheWarmer.php @@ -0,0 +1,90 @@ +getConfigCacheFactory()->cache( + $this->cacheDir.'/symfony_parameters.json', + function (ConfigCacheInterface $cache) { + $this->generateSymfonyParameters($cache); + } + ); + + return []; + } + + /** + * Provides the ConfigCache factory implementation, falling back to a + * default implementation if necessary. + */ + private function getConfigCacheFactory(): ConfigCacheFactoryInterface + { + $this->configCacheFactory ??= new ConfigCacheFactory($this->debug); + + return $this->configCacheFactory; + } + + private function generateSymfonyParameters(ConfigCacheInterface $cache): void + { + $parameters = [ + 'twig_config' => [ + 'default_path' => $this->twigConfig['default_path'], + 'paths' => $this->twigConfig['paths'], + ], + 'twig_component_config' => [ + 'anonymous_template_directory' => $this->twigComponentConfig['anonymous_template_directory'], + 'defaults' => $this->twigComponentConfig['defaults'], + ], + ]; + + $cache->write(json_encode($this->stripProjectDirectory($parameters), JSON_PRETTY_PRINT)); + } + + private function stripProjectDirectory(array $array): array + { + $sanitizedArray = []; + foreach ($array as $key => $value) { + if (is_string($value) && str_starts_with($value, $this->projectDir)) { + $value = str_replace($this->projectDir, '', $value); + } + + if (is_string($key) && str_starts_with($key, $this->projectDir)) { + $key = str_replace($this->projectDir, '', $key); + $sanitizedArray[$key] = $value; + } elseif (is_array($value)) { + $sanitizedArray[$key] = $this->stripProjectDirectory($value); + } else { + $sanitizedArray[$key] = $value; + } + + } + + return $sanitizedArray; + } +} diff --git a/src/Command/GeneratePreviewCommand.php b/src/Command/GeneratePreviewCommand.php deleted file mode 100644 index 00391a7..0000000 --- a/src/Command/GeneratePreviewCommand.php +++ /dev/null @@ -1,38 +0,0 @@ -eventDispatcher->dispatch(new GeneratePreviewEvent()); - - $content = $this->twig->render('@Storybook/preview.html.twig'); - - $output->writeln($content); - - return self::SUCCESS; - } -} diff --git a/src/Command/StorybookInitCommand.php b/src/Command/StorybookInitCommand.php index bf1a256..b23e6ac 100644 --- a/src/Command/StorybookInitCommand.php +++ b/src/Command/StorybookInitCommand.php @@ -146,6 +146,7 @@ private function setupStorybookConfig(): void options: { // 👇 Here configure the framework symfony: { + storybookCachePath: path.resolve(__dirname, `../var/cache/\${process.env.APP_ENV}/storybook`), server: 'https://localhost', proxyPaths: [ '/assets', @@ -160,12 +161,12 @@ private function setupStorybookConfig(): void $mainFile .= <<isTailwindInstalled()) { $mainFile .= <<eventDispatcher->dispatch(new GeneratePreviewEvent()); + + $content = $this->twig->render('@Storybook/preview.html.twig'); + + return new Response($content); + } +} diff --git a/src/DependencyInjection/Compiler/CacheWarmerPass.php b/src/DependencyInjection/Compiler/CacheWarmerPass.php new file mode 100644 index 0000000..408ff64 --- /dev/null +++ b/src/DependencyInjection/Compiler/CacheWarmerPass.php @@ -0,0 +1,50 @@ +getDefinition('storybook.cache_warmer'); + + $cacheWarmerDefinition + ->setArgument(3, $this->getConfig($container, $container->getExtension('twig'))) + ->setArgument(4, $this->getConfig($container, $container->getExtension('twig_component'))) + ; + } + + private function getConfigForExtension(ExtensionInterface $extension, ContainerBuilder $container) + { + $extensionAlias = $extension->getAlias(); + + if (isset($this->extensionConfig[$extensionAlias])) { + return $this->extensionConfig[$extensionAlias]; + } + + $configs = $container->getExtensionConfig($extensionAlias); + + $configuration = $extension instanceof ConfigurationInterface ? $extension : $extension->getConfiguration($configs, $container); + + return $this->extensionConfig[$extensionAlias] = (new Processor())->processConfiguration($configuration, $configs); + } + + private function getConfig(ContainerBuilder $container, ExtensionInterface $extension): array + { + return $container->resolveEnvPlaceholders( + $container->getParameterBag()->resolveValue( + $this->getConfigForExtension($extension, $container) + ), true + ); + } +} diff --git a/src/DependencyInjection/StorybookExtension.php b/src/DependencyInjection/StorybookExtension.php index e1e5728..60cd614 100644 --- a/src/DependencyInjection/StorybookExtension.php +++ b/src/DependencyInjection/StorybookExtension.php @@ -5,9 +5,11 @@ use Storybook\ArgsProcessor\StorybookArgsProcessor; use Storybook\Attributes\AsArgsProcessor; use Storybook\Attributes\AsComponentMock; -use Storybook\Command\GeneratePreviewCommand; +use Storybook\CacheWarmer\StorybookCacheWarmer; use Storybook\Command\StorybookInitCommand; use Storybook\Controller\StorybookController; +use Storybook\Controller\StorybookPreviewController; +use Storybook\DependencyInjection\Compiler\CacheWarmerPass; use Storybook\DependencyInjection\Compiler\ComponentMockPass; use Storybook\EventListener\ProxyRequestListener; use Storybook\Exception\UnauthorizedStoryException; @@ -81,6 +83,13 @@ static function (ChildDefinition $definition, AsComponentMock $attributeInstance ->addTag('controller.service_arguments') ; + // Preview controller + $container->register('storybook.controller.preview', StorybookPreviewController::class) + ->setArgument(0, new Reference('twig')) + ->setArgument(1, new Reference('event_dispatcher')) + ->addTag('controller.service_arguments') + ; + // Story renderer $defaultSandboxConfig = [ 'allowedTags' => ['component'], @@ -142,13 +151,6 @@ static function (ChildDefinition $definition, AsComponentMock $attributeInstance $container->register('storybook.component_proxy_factory', ComponentProxyFactory::class) ->setArgument(0, new AbstractArgument(\sprintf('Provided in "%s".', ComponentMockPass::class))); - // Internal commands - $container->register('storybook.generate_preview_command', GeneratePreviewCommand::class) - ->setArgument(0, new Reference('twig')) - ->setArgument(1, new Reference('event_dispatcher')) - ->addTag('console.command', ['name' => 'storybook:generate-preview']) - ; - // Init command $container->register('storybook.init_command', StorybookInitCommand::class) ->setArgument(0, $container->getParameter('kernel.project_dir')) @@ -159,6 +161,14 @@ static function (ChildDefinition $definition, AsComponentMock $attributeInstance ->setArgument(0, new Reference('request_stack')) ->setArgument(1, new Reference('event_dispatcher')) ->addTag('kernel.event_subscriber'); + + $container->register('storybook.cache_warmer', StorybookCacheWarmer::class) + ->setArgument(0, $container->getParameter('kernel.cache_dir').'/storybook') + ->setArgument(1, $container->getParameter('kernel.debug')) + ->setArgument(2, $container->getParameter('kernel.project_dir')) + ->setArgument(3, new AbstractArgument(\sprintf('Provided in "%s".', CacheWarmerPass::class))) + ->setArgument(4, new AbstractArgument(\sprintf('Provided in "%s".', CacheWarmerPass::class))) + ->addTag('kernel.cache_warmer'); } public function getConfigTreeBuilder(): TreeBuilder diff --git a/src/StorybookBundle.php b/src/StorybookBundle.php index 8d4a032..49fd91e 100644 --- a/src/StorybookBundle.php +++ b/src/StorybookBundle.php @@ -3,8 +3,10 @@ namespace Storybook; use Storybook\DependencyInjection\Compiler\ArgsProcessorPass; +use Storybook\DependencyInjection\Compiler\CacheWarmerPass; use Storybook\DependencyInjection\Compiler\ComponentMockPass; use Storybook\DependencyInjection\StorybookExtension; +use Symfony\Component\DependencyInjection\Compiler\PassConfig; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; use Symfony\Component\HttpKernel\Bundle\Bundle; @@ -18,6 +20,7 @@ public function build(ContainerBuilder $container): void { $container->addCompilerPass(new ArgsProcessorPass()); $container->addCompilerPass(new ComponentMockPass()); + $container->addCompilerPass(new CacheWarmerPass()); } public function getContainerExtension(): ?ExtensionInterface diff --git a/storybook/dist/builders/webpack-builder.js b/storybook/dist/builders/webpack-builder.js index 74184e3..51cbd10 100644 --- a/storybook/dist/builders/webpack-builder.js +++ b/storybook/dist/builders/webpack-builder.js @@ -27,17 +27,17 @@ function h(o){for(var u=[],t=1;t{let u=o.options.configType==="PRODUCTION",{symfony:t}=await o.options.presets.apply("frameworkOptions");if(!t.server)throw new Error(l` +`).map(function(i,l){return l===0?i:""+f+i}).join(` +`)),c+=a+r[d+1];}),c}var y=h;var P=e__namespace.getConfig,B=e__namespace.bail,w=async o=>{let u=o.options.configType==="PRODUCTION",{symfony:t}=await o.options.presets.apply("frameworkOptions");if(!t.server)throw new Error(y` Cannot configure dev server. "server" option in "framework.options.symfony" is required for Storybook dev server to run. Update your main.ts|js file accordingly. - `);let r=["/_storybook/render"];if(t.proxyPaths){let s=Array.isArray(t.proxyPaths)?t.proxyPaths:[t.proxyPaths];r.push(...s);}for(let s of r)o.router.use(s,httpProxyMiddleware.createProxyMiddleware({target:t.server,changeOrigin:!0,secure:u,headers:{"X-Storybook-Proxy":"true"}}));return e__namespace.start(o)},O=e__namespace.build,k=e__namespace.corePresets,C=e__namespace.overridePresets; + `);let r=["/_storybook/render","/_storybook/preview"];if(t.proxyPaths){let s=Array.isArray(t.proxyPaths)?t.proxyPaths:[t.proxyPaths];r.push(...s);}for(let s of r)o.router.use(s,httpProxyMiddleware.createProxyMiddleware({target:t.server,changeOrigin:!0,secure:u,headers:{"X-Storybook-Proxy":"true"}}));return e__namespace.start(o)},k=e__namespace.build,O=e__namespace.corePresets,C=e__namespace.overridePresets; exports.bail = B; -exports.build = O; -exports.corePresets = k; +exports.build = k; +exports.corePresets = O; exports.getConfig = P; exports.overridePresets = C; exports.start = w; diff --git a/storybook/dist/builders/webpack-builder.js.map b/storybook/dist/builders/webpack-builder.js.map index d7d2d57..1d0b3fa 100644 --- a/storybook/dist/builders/webpack-builder.js.map +++ b/storybook/dist/builders/webpack-builder.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/builders/webpack-builder.ts","../../node_modules/ts-dedent/src/index.ts"],"names":["createProxyMiddleware","baseBuilder","dedent","templ","values","_i","strings","indentLengths","arr","str","matches","match","_a","_b","pattern_1","string","value","i","endentations","endentation","indentedValue","esm_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AYA,EAAM,SAAS;CAAI,IAClDI,EAAgB,OAAOJ,CAAK,EACzB,MAAM;CAAI,EACV,IAAI,SAACP,EAAKQ,EAAC,CACV,OAAOA,IAAM,EAAIR,EAAM,GAAGU,EAAcV,CAC1C,CAAC,EACA,KAAK;CAAI,GAGdM,GAAUK,EAAgBd,EAAQW,EAAI,CAAC,CACzC,CAAC,EAEMF,CACT,CAEA,IAAAM,EAAenB,ED/CR,IAAMoB,EAAwB,YAExBC,EAAmB,OAEnBC,EAAkC,MAAOC,GAAY,CAC9D,IAAMC,EAASD,EAAQ,QAAQ,aAAe,aAExC,CAAE,QAAAE,CAAQ,EAAI,MAAMF,EAAQ,QAAQ,QAAQ,MAE/C,kBAAkB,EAErB,GAAI,CAACE,EAAQ,OACT,MAAM,IAAI,MAAMN;AAAA;AAAA;AAAA;AAAA;AAAA,SAKf,EAGL,IAAMO,EAAa,CAAC,oBAAoB,EAExC,GAAID,EAAQ,WAAY,CACpB,IAAME,EAAS,MAAM,QAAQF,EAAQ,UAAU,EAA2BA,EAAQ,WAA/B,CAACA,EAAQ,UAAU,EACtEC,EAAW,KAAK,GAAGC,CAAK,CAC5B,CAEA,QAAWC,KAAQF,EACfH,EAAQ,OAAO,IACXK,EACA9B,EAAsB,CAClB,OAAQ2B,EAAQ,OAChB,aAAc,GACd,OAAQD,EACR,QAAS,CACL,oBAAqB,MACzB,CACJ,CAAC,CACL,EAGJ,OAAmB,QAAMD,CAAO,CACpC,EAEaM,EAAoB,QAEpBC,EAA0B,cAC1BC,EAA8B","sourcesContent":["import { createProxyMiddleware } from 'http-proxy-middleware';\n\nimport * as baseBuilder from '@storybook/builder-webpack5';\nimport dedent from 'ts-dedent';\n\nexport type BuilderOptions = {\n server?: string;\n proxyPaths?: string | string[];\n};\n\nexport const getConfig = baseBuilder.getConfig;\n\nexport const bail = baseBuilder.bail;\n\nexport const start: typeof baseBuilder.start = async (options) => {\n const isProd = options.options.configType === 'PRODUCTION';\n\n const { symfony } = await options.options.presets.apply<{\n symfony: BuilderOptions;\n }>('frameworkOptions');\n\n if (!symfony.server) {\n throw new Error(dedent`\n Cannot configure dev server.\n \n \"server\" option in \"framework.options.symfony\" is required for Storybook dev server to run.\n Update your main.ts|js file accordingly.\n `);\n }\n\n const proxyPaths = ['/_storybook/render'];\n\n if (symfony.proxyPaths) {\n const paths = !Array.isArray(symfony.proxyPaths) ? [symfony.proxyPaths] : symfony.proxyPaths;\n proxyPaths.push(...paths);\n }\n\n for (const path of proxyPaths) {\n options.router.use(\n path,\n createProxyMiddleware({\n target: symfony.server,\n changeOrigin: true,\n secure: isProd,\n headers: {\n 'X-Storybook-Proxy': 'true',\n },\n })\n );\n }\n\n return baseBuilder.start(options);\n};\n\nexport const build = baseBuilder.build;\n\nexport const corePresets = baseBuilder.corePresets;\nexport const overridePresets = baseBuilder.overridePresets;\n","export function dedent(\n templ: TemplateStringsArray | string,\n ...values: unknown[]\n): string {\n let strings = Array.from(typeof templ === 'string' ? [templ] : templ);\n\n // 1. Remove trailing whitespace.\n strings[strings.length - 1] = strings[strings.length - 1].replace(\n /\\r?\\n([\\t ]*)$/,\n '',\n );\n\n // 2. Find all line breaks to determine the highest common indentation level.\n const indentLengths = strings.reduce((arr, str) => {\n const matches = str.match(/\\n([\\t ]+|(?!\\s).)/g);\n if (matches) {\n return arr.concat(\n matches.map((match) => match.match(/[\\t ]/g)?.length ?? 0),\n );\n }\n return arr;\n }, []);\n\n // 3. Remove the common indentation from all strings.\n if (indentLengths.length) {\n const pattern = new RegExp(`\\n[\\t ]{${Math.min(...indentLengths)}}`, 'g');\n\n strings = strings.map((str) => str.replace(pattern, '\\n'));\n }\n\n // 4. Remove leading whitespace.\n strings[0] = strings[0].replace(/^\\r?\\n/, '');\n\n // 5. Perform interpolation.\n let string = strings[0];\n\n values.forEach((value, i) => {\n // 5.1 Read current indentation level\n const endentations = string.match(/(?:^|\\n)( *)$/)\n const endentation = endentations ? endentations[1] : ''\n let indentedValue = value\n // 5.2 Add indentation to values with multiline strings\n if (typeof value === 'string' && value.includes('\\n')) {\n indentedValue = String(value)\n .split('\\n')\n .map((str, i) => {\n return i === 0 ? str : `${endentation}${str}`\n })\n .join('\\n');\n }\n\n string += indentedValue + strings[i + 1];\n });\n\n return string;\n}\n\nexport default dedent;\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/builders/webpack-builder.ts","../../node_modules/ts-dedent/src/index.ts"],"names":["createProxyMiddleware","baseBuilder","dedent","templ","values","_i","strings","indentLengths","arr","str","matches","match","_a","_b","pattern_1","string","value","i","endentations","endentation","indentedValue","esm_default","getConfig","bail","start","options","isProd","symfony","proxyPaths","paths","path","build","corePresets","overridePresets"],"mappings":"AAAA,OAAS,yBAAAA,MAA6B,wBAEtC,UAAYC,MAAiB,8BCFvB,SAAUC,EACdC,EAAoC,SACpCC,EAAA,CAAA,EAAAC,EAAA,EAAAA,EAAA,UAAA,OAAAA,IAAAD,EAAAC,EAAA,CAAA,EAAA,UAAAA,CAAA,EAEA,IAAIC,EAAU,MAAM,KAAK,OAAOH,GAAU,SAAW,CAACA,CAAK,EAAIA,CAAK,EAGpEG,EAAQA,EAAQ,OAAS,CAAC,EAAIA,EAAQA,EAAQ,OAAS,CAAC,EAAE,QACxD,iBACA,EAAE,EAIJ,IAAMC,EAAgBD,EAAQ,OAAO,SAACE,EAAKC,EAAG,CAC5C,IAAMC,EAAUD,EAAI,MAAM,qBAAqB,EAC/C,OAAIC,EACKF,EAAI,OACTE,EAAQ,IAAI,SAACC,EAAK,CAAA,IAAAC,EAAAC,EAAK,OAAAA,GAAAD,EAAAD,EAAM,MAAM,QAAQ,KAAC,MAAAC,IAAA,OAAA,OAAAA,EAAE,UAAM,MAAAC,IAAA,OAAAA,EAAI,CAAC,CAAA,CAAC,EAGvDL,CACT,EAAa,CAAA,CAAE,EAGf,GAAID,EAAc,OAAQ,CACxB,IAAMO,EAAU,IAAI,OAAO;OAAW,KAAK,IAAG,MAAR,KAAYP,CAAa,EAAA,IAAM,GAAG,EAExED,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ACL,EAGJ,OAAmB,QAAMD,CAAO,CACpC,EAEaM,EAAoB,QAEpBC,EAA0B,cAC1BC,EAA8B","sourcesContent":["import { createProxyMiddleware } from 'http-proxy-middleware';\n\nimport * as baseBuilder from '@storybook/builder-webpack5';\nimport dedent from 'ts-dedent';\n\nexport type BuilderOptions = {\n storybookCachePath?: string;\n server?: string;\n proxyPaths?: string | string[];\n};\n\nexport const getConfig = baseBuilder.getConfig;\n\nexport const bail = baseBuilder.bail;\n\nexport const start: typeof baseBuilder.start = async (options) => {\n const isProd = options.options.configType === 'PRODUCTION';\n\n const { symfony } = await options.options.presets.apply<{\n symfony: BuilderOptions;\n }>('frameworkOptions');\n\n if (!symfony.server) {\n throw new Error(dedent`\n Cannot configure dev server.\n \n \"server\" option in \"framework.options.symfony\" is required for Storybook dev server to run.\n Update your main.ts|js file accordingly.\n `);\n }\n\n const proxyPaths = ['/_storybook/render', '/_storybook/preview'];\n\n if (symfony.proxyPaths) {\n const paths = !Array.isArray(symfony.proxyPaths) ? [symfony.proxyPaths] : symfony.proxyPaths;\n proxyPaths.push(...paths);\n }\n\n for (const path of proxyPaths) {\n options.router.use(\n path,\n createProxyMiddleware({\n target: symfony.server,\n changeOrigin: true,\n secure: isProd,\n headers: {\n 'X-Storybook-Proxy': 'true',\n },\n })\n );\n }\n\n return baseBuilder.start(options);\n};\n\nexport const build = baseBuilder.build;\n\nexport const corePresets = baseBuilder.corePresets;\nexport const overridePresets = baseBuilder.overridePresets;\n","export function dedent(\n templ: TemplateStringsArray | string,\n ...values: unknown[]\n): string {\n let strings = Array.from(typeof templ === 'string' ? [templ] : templ);\n\n // 1. Remove trailing whitespace.\n strings[strings.length - 1] = strings[strings.length - 1].replace(\n /\\r?\\n([\\t ]*)$/,\n '',\n );\n\n // 2. Find all line breaks to determine the highest common indentation level.\n const indentLengths = strings.reduce((arr, str) => {\n const matches = str.match(/\\n([\\t ]+|(?!\\s).)/g);\n if (matches) {\n return arr.concat(\n matches.map((match) => match.match(/[\\t ]/g)?.length ?? 0),\n );\n }\n return arr;\n }, []);\n\n // 3. Remove the common indentation from all strings.\n if (indentLengths.length) {\n const pattern = new RegExp(`\\n[\\t ]{${Math.min(...indentLengths)}}`, 'g');\n\n strings = strings.map((str) => str.replace(pattern, '\\n'));\n }\n\n // 4. Remove leading whitespace.\n strings[0] = strings[0].replace(/^\\r?\\n/, '');\n\n // 5. Perform interpolation.\n let string = strings[0];\n\n values.forEach((value, i) => {\n // 5.1 Read current indentation level\n const endentations = string.match(/(?:^|\\n)( *)$/)\n const endentation = endentations ? endentations[1] : ''\n let indentedValue = value\n // 5.2 Add indentation to values with multiline strings\n if (typeof value === 'string' && value.includes('\\n')) {\n indentedValue = String(value)\n .split('\\n')\n .map((str, i) => {\n return i === 0 ? str : `${endentation}${str}`\n })\n .join('\\n');\n }\n\n string += indentedValue + strings[i + 1];\n });\n\n return string;\n}\n\nexport default dedent;\n"]} \ No newline at end of file diff --git a/storybook/dist/index.d.mts b/storybook/dist/index.d.mts index fa6082d..34031c8 100644 --- a/storybook/dist/index.d.mts +++ b/storybook/dist/index.d.mts @@ -34,6 +34,10 @@ type FrameworkName = '@sensiolabs/storybook-symfony-webpack5'; type BuilderName = '@storybook/builder-webpack5'; type ProxyPaths = string[] | string; type SymfonyOptions = { + /** + * Storybook cache directory. + */ + storybookCachePath: string; /** * Symfony server URL. */ diff --git a/storybook/dist/index.d.ts b/storybook/dist/index.d.ts index fa6082d..34031c8 100644 --- a/storybook/dist/index.d.ts +++ b/storybook/dist/index.d.ts @@ -34,6 +34,10 @@ type FrameworkName = '@sensiolabs/storybook-symfony-webpack5'; type BuilderName = '@storybook/builder-webpack5'; type ProxyPaths = string[] | string; type SymfonyOptions = { + /** + * Storybook cache directory. + */ + storybookCachePath: string; /** * Symfony server URL. */ diff --git a/storybook/dist/server/framework-preset.js b/storybook/dist/server/framework-preset.js index 7f2f78b..9f253f2 100644 --- a/storybook/dist/server/framework-preset.js +++ b/storybook/dist/server/framework-preset.js @@ -1,18 +1,17 @@ 'use strict'; -var child_process = require('child_process'); -var qe = require('path'); +var ce = require('fs'); +var Xe = require('path'); var unplugin = require('unplugin'); -var hn = require('html-webpack-plugin'); +var sn = require('html-webpack-plugin'); var nodeLogger = require('@storybook/node-logger'); var jsdom = require('jsdom'); var url = require('url'); -var li = require('fs'); var promises = require('fs/promises'); var events = require('events'); -var Hs = require('stream'); +var Us = require('stream'); var string_decoder = require('string_decoder'); -var fa = require('crypto'); +var oa = require('crypto'); function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } @@ -34,43 +33,34 @@ function _interopNamespace(e) { return Object.freeze(n); } -var qe__default = /*#__PURE__*/_interopDefault(qe); -var hn__default = /*#__PURE__*/_interopDefault(hn); -var li__namespace = /*#__PURE__*/_interopNamespace(li); -var Hs__default = /*#__PURE__*/_interopDefault(Hs); -var fa__default = /*#__PURE__*/_interopDefault(fa); +var ce__namespace = /*#__PURE__*/_interopNamespace(ce); +var Xe__default = /*#__PURE__*/_interopDefault(Xe); +var sn__default = /*#__PURE__*/_interopDefault(sn); +var Us__default = /*#__PURE__*/_interopDefault(Us); +var oa__default = /*#__PURE__*/_interopDefault(oa); -var Ki=Object.create;var Xe=Object.defineProperty;var Zi=Object.getOwnPropertyDescriptor;var Ji=Object.getOwnPropertyNames;var Qi=Object.getPrototypeOf,tn=Object.prototype.hasOwnProperty;var $t=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var C=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports);var en=(s,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ji(t))!tn.call(s,n)&&n!==e&&Xe(s,n,{get:()=>t[n],enumerable:!(i=Zi(t,n))||i.enumerable});return s};var zt=(s,t,e)=>(e=s!=null?Ki(Qi(s)):{},en(t||!s||!s.__esModule?Xe(e,"default",{value:s,enumerable:!0}):e,s));var ss=C(ot=>{var cn=ot&&ot.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ot,"__esModule",{value:!0});ot.VirtualStats=void 0;var J=cn($t("constants")),pe=class{constructor(t){for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(this[e]=t[e]);}_checkModeProperty(t){return (this.mode&J.default.S_IFMT)===t}isDirectory(){return this._checkModeProperty(J.default.S_IFDIR)}isFile(){return this._checkModeProperty(J.default.S_IFREG)}isBlockDevice(){return this._checkModeProperty(J.default.S_IFBLK)}isCharacterDevice(){return this._checkModeProperty(J.default.S_IFCHR)}isSymbolicLink(){return this._checkModeProperty(J.default.S_IFLNK)}isFIFO(){return this._checkModeProperty(J.default.S_IFIFO)}isSocket(){return this._checkModeProperty(J.default.S_IFSOCK)}};ot.VirtualStats=pe;});var os=C((ye,rs)=>{var fn=ye&&ye.__importDefault||function(s){return s&&s.__esModule?s:{default:s}},Ht=fn($t("path")),is=ss(),ns=45e6,ge="all",un="static",dn="dynamic";function pn(s){if(!s._compiler)throw new Error("You must use this plugin only after creating webpack instance!")}function gn(s,t){return Ht.default.isAbsolute(s)?s:Ht.default.join(t.context,s)}function mt(s){return t=>{if(t._data){let e=t._currentLevel,i=t._levels[e];return {result:s,level:i}}return [null,s]}}function mn(s,t){return s._data instanceof Map?s._data.get(t):s._data?s.data[t]:s.data instanceof Map?s.data.get(t):s.data[t]}function wt(s,t,e){let i=e(s);s._data instanceof Map?s._data.set(t,i):s._data?s.data[t]=i:s.data instanceof Map?s.data.set(t,i):s.data[t]=i;}function wn(s){if(s._statStorage)return s._statStorage;if(s._statBackend)return s._statBackend;throw new Error("Couldn't find a stat storage")}function yn(s){if(s._readFileStorage)return s._readFileStorage;if(s._readFileBackend)return s._readFileBackend;throw new Error("Couldn't find a readFileStorage")}function me(s){if(s._readdirBackend)return s._readdirBackend;if(s._readdirStorage)return s._readdirStorage;throw new Error("Couldn't find a readDirStorage from Webpack Internals")}var we=class{constructor(t){this._compiler=null,this._watcher=null,this._staticModules=t||null;}getModuleList(t=ge){var e,i;let n={},r=t===ge||t===un,o=t===ge||t===dn;if(r&&(n=Object.assign(Object.assign({},n),this._staticModules)),o){let h=(e=this._compiler)===null||e===void 0?void 0:e.inputFileSystem,a=(i=h?._virtualFiles)!==null&&i!==void 0?i:{},l={};Object.keys(a).forEach(c=>{l[c]=a[c].contents;}),n=Object.assign(Object.assign({},n),l);}return n}writeModule(t,e){if(!this._compiler)throw new Error("Plugin has not been initialized");pn(this);let i=e?e.length:0,n=Date.now(),r=new Date(n),o=new is.VirtualStats({dev:8675309,nlink:0,uid:1e3,gid:1e3,rdev:0,blksize:4096,ino:ns++,mode:33188,size:i,blocks:Math.floor(i/4096),atime:r,mtime:r,ctime:r,birthtime:r}),h=gn(t,this._compiler);process.env.WVM_DEBUG&&console.log(this._compiler.name,"Write virtual module:",h,e);let a=this._watcher&&this._watcher.watchFileSystem;for(;a&&a.wfs;)a=a.wfs;let l=this._compiler.inputFileSystem;for(;l&&l._inputFileSystem;)l=l._inputFileSystem;if(l._writeVirtualFile(h,o,e),a&&a.watcher&&(a.watcher.fileWatchers.size||a.watcher.fileWatchers.length)){let c=a.watcher.fileWatchers instanceof Map?Array.from(a.watcher.fileWatchers.values()):a.watcher.fileWatchers;for(let f of c)"watcher"in f&&(f=f.watcher),f.path===h&&(process.env.DEBUG&&console.log(this._compiler.name,"Emit file change:",h,n),delete f.directoryWatcher._cachedTimeInfoEntries,f.emit("change",n,null));}}apply(t){this._compiler=t;let e=()=>{let o=t.inputFileSystem;for(;o&&o._inputFileSystem;)o=o._inputFileSystem;if(!o._writeVirtualFile){let h=o.purge;o.purge=()=>{h.apply(o,[]),o._virtualFiles&&Object.keys(o._virtualFiles).forEach(a=>{let l=o._virtualFiles[a];o._writeVirtualFile(a,l.stats,l.contents);});},o._writeVirtualFile=(a,l,c)=>{let f=wn(o),u=yn(o),d=me(o);o._virtualFiles=o._virtualFiles||{},o._virtualFiles[a]={stats:l,contents:c},wt(f,a,mt(l)),wt(u,a,mt(c));let g=a.split(/[\\/]/),p=g.length-1,w=g[0]?1:0;for(;p>w;){let m=g.slice(0,p).join(Ht.default.sep)||Ht.default.sep;try{o.readdirSync(m);}catch{let E=Date.now(),v=new is.VirtualStats({dev:8675309,nlink:0,uid:1e3,gid:1e3,rdev:0,blksize:4096,ino:ns++,mode:16877,size:l.size,blocks:Math.floor(l.size/4096),atime:E,mtime:E,ctime:E,birthtime:E});wt(d,m,mt([])),wt(f,m,mt(v));}let b=mn(me(o),m);b=b[1]||b.result;let S=g[p];if(b.indexOf(S)<0){let y=b.concat([S]).sort();wt(me(o),m,mt(y));}else break;p--;}};}},i=()=>{if(this._staticModules){for(let[o,h]of Object.entries(this._staticModules))this.writeModule(o,h);this._staticModules=null;}},n=typeof t.webpack>"u"?4:5,r=(o,h)=>{this._watcher=o.compiler||o;let a=t.inputFileSystem._virtualFiles,l=t.fileTimestamps;a&&l&&typeof l.set=="function"&&Object.keys(a).forEach(c=>{let f=+a[c].stats.mtime;l.set(c,n===4?f:{safeTime:f,timestamp:f});}),h();};t.hooks?(t.hooks.afterEnvironment.tap("VirtualModulesPlugin",e),t.hooks.afterResolvers.tap("VirtualModulesPlugin",i),t.hooks.watchRun.tapAsync("VirtualModulesPlugin",r)):(t.plugin("after-environment",e),t.plugin("after-resolvers",i),t.plugin("watch-run",r));}};rs.exports=we;});var hs=C((_a,as)=>{as.exports=function(t){if(typeof t!="string"||t==="")return !1;for(var e;e=/(\\).|([@?!+*]\(.*\))/g.exec(t);){if(e[2])return !0;t=t.slice(e.index+e[0].length);}return !1};});var fs=C((ka,cs)=>{var bn=hs(),ls={"{":"}","(":")","[":"]"},Sn=function(s){if(s[0]==="!")return !0;for(var t=0,e=-2,i=-2,n=-2,r=-2,o=-2;tt&&(o===-1||o>i||(o=s.indexOf("\\",t),o===-1||o>i)))||n!==-1&&s[t]==="{"&&s[t+1]!=="}"&&(n=s.indexOf("}",t),n>t&&(o=s.indexOf("\\",t),o===-1||o>n))||r!==-1&&s[t]==="("&&s[t+1]==="?"&&/[:!=]/.test(s[t+2])&&s[t+3]!==")"&&(r=s.indexOf(")",t),r>t&&(o=s.indexOf("\\",t),o===-1||o>r))||e!==-1&&s[t]==="("&&s[t+1]!=="|"&&(ee&&(o=s.indexOf("\\",e),o===-1||o>r))))return !0;if(s[t]==="\\"){var h=s[t+1];t+=2;var a=ls[h];if(a){var l=s.indexOf(a,t);l!==-1&&(t=l+1);}if(s[t]==="!")return !0}else t++;}return !1},En=function(s){if(s[0]==="!")return !0;for(var t=0;t{gs.exports=ds;function ds(s,t,e){s instanceof RegExp&&(s=us(s,e)),t instanceof RegExp&&(t=us(t,e));var i=ps(s,t,e);return i&&{start:i[0],end:i[1],pre:e.slice(0,i[0]),body:e.slice(i[0]+s.length,i[1]),post:e.slice(i[1]+t.length)}}function us(s,t){var e=t.match(s);return e?e[0]:null}ds.range=ps;function ps(s,t,e){var i,n,r,o,h,a=e.indexOf(s),l=e.indexOf(t,a+1),c=a;if(a>=0&&l>0){if(s===t)return [a,l];for(i=[],r=e.length;c>=0&&!h;)c==a?(i.push(c),a=e.indexOf(s,c+1)):i.length==1?h=[i.pop(),l]:(n=i.pop(),n=0?a:l;i.length&&(h=[r,o]);}return h}});var Ts=C((Fa,Ns)=>{var ws=ms();Ns.exports=Tn;var ys="\0SLASH"+Math.random()+"\0",bs="\0OPEN"+Math.random()+"\0",Se="\0CLOSE"+Math.random()+"\0",Ss="\0COMMA"+Math.random()+"\0",Es="\0PERIOD"+Math.random()+"\0";function be(s){return parseInt(s,10)==s?parseInt(s,10):s.charCodeAt(0)}function vn(s){return s.split("\\\\").join(ys).split("\\{").join(bs).split("\\}").join(Se).split("\\,").join(Ss).split("\\.").join(Es)}function Nn(s){return s.split(ys).join("\\").split(bs).join("{").split(Se).join("}").split(Ss).join(",").split(Es).join(".")}function vs(s){if(!s)return [""];var t=[],e=ws("{","}",s);if(!e)return s.split(",");var i=e.pre,n=e.body,r=e.post,o=i.split(",");o[o.length-1]+="{"+n+"}";var h=vs(r);return r.length&&(o[o.length-1]+=h.shift(),o.push.apply(o,h)),t.push.apply(t,o),t}function Tn(s){return s?(s.substr(0,2)==="{}"&&(s="\\{\\}"+s.substr(2)),yt(vn(s),!0).map(Nn)):[]}function xn(s){return "{"+s+"}"}function Cn(s){return /^-?0\d/.test(s)}function An(s,t){return s<=t}function On(s,t){return s>=t}function yt(s,t){var e=[],i=ws("{","}",s);if(!i)return [s];var n=i.pre,r=i.post.length?yt(i.post,!1):[""];if(/\$$/.test(i.pre))for(var o=0;o=0;if(!c&&!f)return i.post.match(/,.*\}/)?(s=i.pre+"{"+i.body+Se+i.post,yt(s)):[s];var u;if(c)u=i.body.split(/\.\./);else if(u=vs(i.body),u.length===1&&(u=yt(u[0],!1).map(xn),u.length===1))return r.map(function(Bt){return i.pre+u[0]+Bt});var d;if(c){var g=be(u[0]),p=be(u[1]),w=Math.max(u[0].length,u[1].length),m=u.length==3?Math.abs(be(u[2])):1,b=An,S=p0){var Wt=new Array(z+1).join("0");E<0?v="-"+Wt+v.slice(1):v=Wt+v;}}d.push(v);}}else {d=[];for(var D=0;D{var pi=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",to=pi+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",gi="["+pi+"]["+to+"]*",eo=new RegExp("^"+gi+"$"),so=function(s,t){let e=[],i=t.exec(s);for(;i;){let n=[];n.startIndex=t.lastIndex-i[0].length;let r=i.length;for(let o=0;o"u")};Z.isExist=function(s){return typeof s<"u"};Z.isEmptyObject=function(s){return Object.keys(s).length===0};Z.merge=function(s,t,e){if(t){let i=Object.keys(t),n=i.length;for(let r=0;r{var Be=fe(),no={allowBooleanAttributes:!1,unpairedTags:[]};Si.validate=function(s,t){t=Object.assign({},no,t);let e=[],i=!1,n=!1;s[0]==="\uFEFF"&&(s=s.substr(1));for(let r=0;r"&&s[r]!==" "&&s[r]!==" "&&s[r]!==` -`&&s[r]!=="\r";r++)a+=s[r];if(a=a.trim(),a[a.length-1]==="/"&&(a=a.substring(0,a.length-1),r--),!uo(a)){let f;return a.trim().length===0?f="Invalid space after '<'.":f="Tag '"+a+"' is an invalid name.",x("InvalidTag",f,M(s,r))}let l=ao(s,r);if(l===!1)return x("InvalidAttr","Attributes for '"+a+"' have open quote.",M(s,r));let c=l.value;if(r=l.index,c[c.length-1]==="/"){let f=r-c.length;c=c.substring(0,c.length-1);let u=bi(c,t);if(u===!0)i=!0;else return x(u.err.code,u.err.msg,M(s,f+u.err.line))}else if(h)if(l.tagClosed){if(c.trim().length>0)return x("InvalidTag","Closing tag '"+a+"' can't have attributes or invalid starting.",M(s,o));{let f=e.pop();if(a!==f.tagName){let u=M(s,f.tagStartPos);return x("InvalidTag","Expected closing tag '"+f.tagName+"' (opened in line "+u.line+", col "+u.col+") instead of closing tag '"+a+"'.",M(s,o))}e.length==0&&(n=!0);}}else return x("InvalidTag","Closing tag '"+a+"' doesn't have proper closing.",M(s,r));else {let f=bi(c,t);if(f!==!0)return x(f.err.code,f.err.msg,M(s,r-c.length+f.err.line));if(n===!0)return x("InvalidXml","Multiple possible root nodes found.",M(s,r));t.unpairedTags.indexOf(a)!==-1||e.push({tagName:a,tagStartPos:o}),i=!0;}for(r++;r0)return x("InvalidXml","Invalid '"+JSON.stringify(e.map(r=>r.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return x("InvalidXml","Start tag expected.",1);return !0};function mi(s){return s===" "||s===" "||s===` -`||s==="\r"}function wi(s,t){let e=t;for(;t5&&i==="xml")return x("InvalidXml","XML declaration allowed only at the start of the document.",M(s,t));if(s[t]=="?"&&s[t+1]==">"){t++;break}else continue}return t}function yi(s,t){if(s.length>t+5&&s[t+1]==="-"&&s[t+2]==="-"){for(t+=3;t"){t+=2;break}}else if(s.length>t+8&&s[t+1]==="D"&&s[t+2]==="O"&&s[t+3]==="C"&&s[t+4]==="T"&&s[t+5]==="Y"&&s[t+6]==="P"&&s[t+7]==="E"){let e=1;for(t+=8;t"&&(e--,e===0))break}else if(s.length>t+9&&s[t+1]==="["&&s[t+2]==="C"&&s[t+3]==="D"&&s[t+4]==="A"&&s[t+5]==="T"&&s[t+6]==="A"&&s[t+7]==="["){for(t+=8;t"){t+=2;break}}return t}var ro='"',oo="'";function ao(s,t){let e="",i="",n=!1;for(;t"&&i===""){n=!0;break}e+=s[t];}return i!==""?!1:{value:e,index:t,tagClosed:n}}var ho=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function bi(s,t){let e=Be.getAllMatches(s,ho),i={};for(let n=0;n{var Ei={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(s,t){return t},attributeValueProcessor:function(s,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(s,t,e){return s}},po=function(s){return Object.assign({},Ei,s)};ze.buildOptions=po;ze.defaultOptions=Ei;});var Ti=C((el,Ni)=>{var Ue=class{constructor(t){this.tagname=t,this.child=[],this[":@"]={};}add(t,e){t==="__proto__"&&(t="#__proto__"),this.child.push({[t]:e});}addChild(t){t.tagname==="__proto__"&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child});}};Ni.exports=Ue;});var Ci=C((sl,xi)=>{var go=fe();function mo(s,t){let e={};if(s[t+3]==="O"&&s[t+4]==="C"&&s[t+5]==="T"&&s[t+6]==="Y"&&s[t+7]==="P"&&s[t+8]==="E"){t=t+9;let i=1,n=!1,r=!1,o="";for(;t"){if(r?s[t-1]==="-"&&s[t-2]==="-"&&(r=!1,i--):i--,i===0)break}else s[t]==="["?n=!0:o+=s[t];if(i!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return {entities:e,i:t}}function wo(s,t){let e="";for(;t{var To=/^[-+]?0x[a-fA-F0-9]+$/,xo=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt);!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var Co={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Ao(s,t={}){if(t=Object.assign({},Co,t),!s||typeof s!="string")return s;let e=s.trim();if(t.skipLike!==void 0&&t.skipLike.test(e))return s;if(t.hex&&To.test(e))return Number.parseInt(e,16);{let i=xo.exec(e);if(i){let n=i[1],r=i[2],o=Oo(i[3]),h=i[4]||i[6];if(!t.leadingZeros&&r.length>0&&n&&e[2]!==".")return s;if(!t.leadingZeros&&r.length>0&&!n&&e[1]!==".")return s;{let a=Number(e),l=""+a;return l.search(/[eE]/)!==-1||h?t.eNotation?a:s:e.indexOf(".")!==-1?l==="0"&&o===""||l===o||n&&l==="-"+o?a:s:r?o===l||n+o===l?a:s:e===l||e===n+l?a:s}}else return s}}function Oo(s){return s&&s.indexOf(".")!==-1&&(s=s.replace(/0+$/,""),s==="."?s="0":s[0]==="."?s="0"+s:s[s.length-1]==="."&&(s=s.substr(0,s.length-1))),s}Ai.exports=Ao;});var Pi=C((nl,ki)=>{var _i=fe(),jt=Ti(),_o=Ci(),ko=Oi(),Ge=class{constructor(t){this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,i)=>String.fromCharCode(Number.parseInt(i,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,i)=>String.fromCharCode(Number.parseInt(i,16))}},this.addExternalEntities=Po,this.parseXml=Lo,this.parseTextData=Fo,this.resolveNameSpace=Ro,this.buildAttributesMap=Mo,this.isItStopNode=$o,this.replaceEntitiesValue=Wo,this.readStopNodeData=Uo,this.saveTextToParentTag=Bo,this.addChild=jo;}};function Po(s){let t=Object.keys(s);for(let e=0;e0)){o||(s=this.replaceEntitiesValue(s));let h=this.options.tagValueProcessor(t,s,e,n,r);return h==null?s:typeof h!=typeof s||h!==s?h:this.options.trimValues?He(s,this.options.parseTagValue,this.options.numberParseOptions):s.trim()===s?He(s,this.options.parseTagValue,this.options.numberParseOptions):s}}function Ro(s){if(this.options.removeNSPrefix){let t=s.split(":"),e=s.charAt(0)==="/"?"/":"";if(t[0]==="xmlns")return "";t.length===2&&(s=e+t[1]);}return s}var Io=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function Mo(s,t,e){if(!this.options.ignoreAttributes&&typeof s=="string"){let i=_i.getAllMatches(s,Io),n=i.length,r={};for(let o=0;o",r,"Closing Tag is not closed."),a=s.substring(r+2,h).trim();if(this.options.removeNSPrefix){let f=a.indexOf(":");f!==-1&&(a=a.substr(f+1));}this.options.transformTagName&&(a=this.options.transformTagName(a)),e&&(i=this.saveTextToParentTag(i,e,n));let l=n.substring(n.lastIndexOf(".")+1);if(a&&this.options.unpairedTags.indexOf(a)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: `);let c=0;l&&this.options.unpairedTags.indexOf(l)!==-1?(c=n.lastIndexOf(".",n.lastIndexOf(".")-1),this.tagsNodeStack.pop()):c=n.lastIndexOf("."),n=n.substring(0,c),e=this.tagsNodeStack.pop(),i="",r=h;}else if(s[r+1]==="?"){let h=Ve(s,r,!1,"?>");if(!h)throw new Error("Pi Tag is not closed.");if(i=this.saveTextToParentTag(i,e,n),!(this.options.ignoreDeclaration&&h.tagName==="?xml"||this.options.ignorePiTags)){let a=new jt(h.tagName);a.add(this.options.textNodeName,""),h.tagName!==h.tagExp&&h.attrExpPresent&&(a[":@"]=this.buildAttributesMap(h.tagExp,n,h.tagName)),this.addChild(e,a,n);}r=h.closeIndex+1;}else if(s.substr(r+1,3)==="!--"){let h=rt(s,"-->",r+4,"Comment is not closed.");if(this.options.commentPropName){let a=s.substring(r+4,h-2);i=this.saveTextToParentTag(i,e,n),e.add(this.options.commentPropName,[{[this.options.textNodeName]:a}]);}r=h;}else if(s.substr(r+1,2)==="!D"){let h=_o(s,r);this.docTypeEntities=h.entities,r=h.i;}else if(s.substr(r+1,2)==="!["){let h=rt(s,"]]>",r,"CDATA is not closed.")-2,a=s.substring(r+9,h);i=this.saveTextToParentTag(i,e,n);let l=this.parseTextData(a,e.tagname,n,!0,!1,!0,!0);l==null&&(l=""),this.options.cdataPropName?e.add(this.options.cdataPropName,[{[this.options.textNodeName]:a}]):e.add(this.options.textNodeName,l),r=h+2;}else {let h=Ve(s,r,this.options.removeNSPrefix),a=h.tagName,l=h.rawTagName,c=h.tagExp,f=h.attrExpPresent,u=h.closeIndex;this.options.transformTagName&&(a=this.options.transformTagName(a)),e&&i&&e.tagname!=="!xml"&&(i=this.saveTextToParentTag(i,e,n,!1));let d=e;if(d&&this.options.unpairedTags.indexOf(d.tagname)!==-1&&(e=this.tagsNodeStack.pop(),n=n.substring(0,n.lastIndexOf("."))),a!==t.tagname&&(n+=n?"."+a:a),this.isItStopNode(this.options.stopNodes,n,a)){let g="";if(c.length>0&&c.lastIndexOf("/")===c.length-1)r=h.closeIndex;else if(this.options.unpairedTags.indexOf(a)!==-1)r=h.closeIndex;else {let w=this.readStopNodeData(s,l,u+1);if(!w)throw new Error(`Unexpected end of ${l}`);r=w.i,g=w.tagContent;}let p=new jt(a);a!==c&&f&&(p[":@"]=this.buildAttributesMap(c,n,a)),g&&(g=this.parseTextData(g,a,n,!0,f,!0,!0)),n=n.substr(0,n.lastIndexOf(".")),p.add(this.options.textNodeName,g),this.addChild(e,p,n);}else {if(c.length>0&&c.lastIndexOf("/")===c.length-1){a[a.length-1]==="/"?(a=a.substr(0,a.length-1),n=n.substr(0,n.length-1),c=a):c=c.substr(0,c.length-1),this.options.transformTagName&&(a=this.options.transformTagName(a));let g=new jt(a);a!==c&&f&&(g[":@"]=this.buildAttributesMap(c,n,a)),this.addChild(e,g,n),n=n.substr(0,n.lastIndexOf("."));}else {let g=new jt(a);this.tagsNodeStack.push(e),a!==c&&f&&(g[":@"]=this.buildAttributesMap(c,n,a)),this.addChild(e,g,n),e=g;}i="",r=u;}}else i+=s[r];return t.child};function jo(s,t,e){let i=this.options.updateTag(t.tagname,e,t[":@"]);i===!1||(typeof i=="string"&&(t.tagname=i),s.addChild(t));}var Wo=function(s){if(this.options.processEntities){for(let t in this.docTypeEntities){let e=this.docTypeEntities[t];s=s.replace(e.regx,e.val);}for(let t in this.lastEntities){let e=this.lastEntities[t];s=s.replace(e.regex,e.val);}if(this.options.htmlEntities)for(let t in this.htmlEntities){let e=this.htmlEntities[t];s=s.replace(e.regex,e.val);}s=s.replace(this.ampEntity.regex,this.ampEntity.val);}return s};function Bo(s,t,e,i){return s&&(i===void 0&&(i=Object.keys(t.child).length===0),s=this.parseTextData(s,t.tagname,e,!1,t[":@"]?Object.keys(t[":@"]).length!==0:!1,i),s!==void 0&&s!==""&&t.add(this.options.textNodeName,s),s=""),s}function $o(s,t,e){let i="*."+e;for(let n in s){let r=s[n];if(i===r||t===r)return !0}return !1}function zo(s,t,e=">"){let i,n="";for(let r=t;r",e,`${t} is not closed`);if(s.substring(e+2,r).trim()===t&&(n--,n===0))return {tagContent:s.substring(i,e),i:r};e=r;}else if(s[e+1]==="?")e=rt(s,"?>",e+1,"StopNode is not closed.");else if(s.substr(e+1,3)==="!--")e=rt(s,"-->",e+3,"StopNode is not closed.");else if(s.substr(e+1,2)==="![")e=rt(s,"]]>",e,"StopNode is not closed.")-2;else {let r=Ve(s,e,">");r&&((r&&r.tagName)===t&&r.tagExp[r.tagExp.length-1]!=="/"&&n++,e=r.closeIndex);}}function He(s,t,e){if(t&&typeof s=="string"){let i=s.trim();return i==="true"?!0:i==="false"?!1:ko(s,e)}else return _i.isExist(s)?s:""}ki.exports=Ge;});var Ii=C(Ri=>{function Go(s,t){return Fi(s,t)}function Fi(s,t,e){let i,n={};for(let r=0;r0&&(n[t.textNodeName]=i):i!==void 0&&(n[t.textNodeName]=i),n}function Vo(s){let t=Object.keys(s);for(let e=0;e{var{buildOptions:qo}=vi(),Xo=Pi(),{prettify:Yo}=Ii(),Ko=$e(),De=class{constructor(t){this.externalEntities={},this.options=qo(t);}parse(t,e){if(typeof t!="string")if(t.toString)t=t.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(e){e===!0&&(e={});let r=Ko.validate(t,e);if(r!==!0)throw Error(`${r.err.msg}:${r.err.line}:${r.err.col}`)}let i=new Xo(this.options);i.addExternalEntities(this.externalEntities);let n=i.parseXml(t);return this.options.preserveOrder||n===void 0?n:Yo(n,this.options)}addEntity(t,e){if(e.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(t.indexOf("&")!==-1||t.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '");if(e==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e;}};Mi.exports=De;});var zi=C((al,$i)=>{var Zo=` -`;function Jo(s,t){let e="";return t.format&&t.indentBy.length>0&&(e=Zo),Wi(s,t,"",e)}function Wi(s,t,e,i){let n="",r=!1;for(let o=0;o`,r=!1;continue}else if(a===t.commentPropName){n+=i+``,r=!0;continue}else if(a[0]==="?"){let g=ji(h[":@"],t),p=a==="?xml"?"":i,w=h[a][0][t.textNodeName];w=w.length!==0?" "+w:"",n+=p+`<${a}${w}${g}?>`,r=!0;continue}let c=i;c!==""&&(c+=t.indentBy);let f=ji(h[":@"],t),u=i+`<${a}${f}`,d=Wi(h[a],t,l,c);t.unpairedTags.indexOf(a)!==-1?t.suppressUnpairedNode?n+=u+">":n+=u+"/>":(!d||d.length===0)&&t.suppressEmptyNode?n+=u+"/>":d&&d.endsWith(">")?n+=u+`>${d}${i}`:(n+=u+">",d&&i!==""&&(d.includes("/>")||d.includes("`),r=!0;}return n}function Qo(s){let t=Object.keys(s);for(let e=0;e0&&t.processEntities)for(let e=0;e{var ea=zi(),sa={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(s,t){return t},attributeValueProcessor:function(s,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function st(s){this.options=Object.assign({},sa,s),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return !1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=ra),this.processTextOrObjNode=ia,this.options.format?(this.indentate=na,this.tagEndChar=`> +var Di=Object.create;var Ke=Object.defineProperty;var qi=Object.getOwnPropertyDescriptor;var Xi=Object.getOwnPropertyNames;var Yi=Object.getPrototypeOf,Ki=Object.prototype.hasOwnProperty;var $t=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var T=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports);var Zi=(s,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Xi(t))!Ki.call(s,n)&&n!==e&&Ke(s,n,{get:()=>t[n],enumerable:!(i=qi(t,n))||i.enumerable});return s};var zt=(s,t,e)=>(e=s!=null?Di(Yi(s)):{},Zi(t||!s||!s.__esModule?Ke(e,"default",{value:s,enumerable:!0}):e,s));var Qe=T(ot=>{var rn=ot&&ot.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ot,"__esModule",{value:!0});ot.VirtualStats=void 0;var J=rn($t("constants")),ge=class{constructor(t){for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(this[e]=t[e]);}_checkModeProperty(t){return (this.mode&J.default.S_IFMT)===t}isDirectory(){return this._checkModeProperty(J.default.S_IFDIR)}isFile(){return this._checkModeProperty(J.default.S_IFREG)}isBlockDevice(){return this._checkModeProperty(J.default.S_IFBLK)}isCharacterDevice(){return this._checkModeProperty(J.default.S_IFCHR)}isSymbolicLink(){return this._checkModeProperty(J.default.S_IFLNK)}isFIFO(){return this._checkModeProperty(J.default.S_IFIFO)}isSocket(){return this._checkModeProperty(J.default.S_IFSOCK)}};ot.VirtualStats=ge;});var is=T((be,ss)=>{var on=be&&be.__importDefault||function(s){return s&&s.__esModule?s:{default:s}},Vt=on($t("path")),ts=Qe(),es=45e6,me="all",an="static",hn="dynamic";function ln(s){if(!s._compiler)throw new Error("You must use this plugin only after creating webpack instance!")}function cn(s,t){return Vt.default.isAbsolute(s)?s:Vt.default.join(t.context,s)}function mt(s){return t=>{if(t._data){let e=t._currentLevel,i=t._levels[e];return {result:s,level:i}}return [null,s]}}function fn(s,t){return s._data instanceof Map?s._data.get(t):s._data?s.data[t]:s.data instanceof Map?s.data.get(t):s.data[t]}function wt(s,t,e){let i=e(s);s._data instanceof Map?s._data.set(t,i):s._data?s.data[t]=i:s.data instanceof Map?s.data.set(t,i):s.data[t]=i;}function un(s){if(s._statStorage)return s._statStorage;if(s._statBackend)return s._statBackend;throw new Error("Couldn't find a stat storage")}function dn(s){if(s._readFileStorage)return s._readFileStorage;if(s._readFileBackend)return s._readFileBackend;throw new Error("Couldn't find a readFileStorage")}function we(s){if(s._readdirBackend)return s._readdirBackend;if(s._readdirStorage)return s._readdirStorage;throw new Error("Couldn't find a readDirStorage from Webpack Internals")}var ye=class{constructor(t){this._compiler=null,this._watcher=null,this._staticModules=t||null;}getModuleList(t=me){var e,i;let n={},r=t===me||t===an,o=t===me||t===hn;if(r&&(n=Object.assign(Object.assign({},n),this._staticModules)),o){let h=(e=this._compiler)===null||e===void 0?void 0:e.inputFileSystem,a=(i=h?._virtualFiles)!==null&&i!==void 0?i:{},l={};Object.keys(a).forEach(c=>{l[c]=a[c].contents;}),n=Object.assign(Object.assign({},n),l);}return n}writeModule(t,e){if(!this._compiler)throw new Error("Plugin has not been initialized");ln(this);let i=e?e.length:0,n=Date.now(),r=new Date(n),o=new ts.VirtualStats({dev:8675309,nlink:0,uid:1e3,gid:1e3,rdev:0,blksize:4096,ino:es++,mode:33188,size:i,blocks:Math.floor(i/4096),atime:r,mtime:r,ctime:r,birthtime:r}),h=cn(t,this._compiler);process.env.WVM_DEBUG&&console.log(this._compiler.name,"Write virtual module:",h,e);let a=this._watcher&&this._watcher.watchFileSystem;for(;a&&a.wfs;)a=a.wfs;let l=this._compiler.inputFileSystem;for(;l&&l._inputFileSystem;)l=l._inputFileSystem;if(l._writeVirtualFile(h,o,e),a&&a.watcher&&(a.watcher.fileWatchers.size||a.watcher.fileWatchers.length)){let c=a.watcher.fileWatchers instanceof Map?Array.from(a.watcher.fileWatchers.values()):a.watcher.fileWatchers;for(let f of c)"watcher"in f&&(f=f.watcher),f.path===h&&(process.env.DEBUG&&console.log(this._compiler.name,"Emit file change:",h,n),delete f.directoryWatcher._cachedTimeInfoEntries,f.emit("change",n,null));}}apply(t){this._compiler=t;let e=()=>{let o=t.inputFileSystem;for(;o&&o._inputFileSystem;)o=o._inputFileSystem;if(!o._writeVirtualFile){let h=o.purge;o.purge=()=>{h.apply(o,[]),o._virtualFiles&&Object.keys(o._virtualFiles).forEach(a=>{let l=o._virtualFiles[a];o._writeVirtualFile(a,l.stats,l.contents);});},o._writeVirtualFile=(a,l,c)=>{let f=un(o),u=dn(o),d=we(o);o._virtualFiles=o._virtualFiles||{},o._virtualFiles[a]={stats:l,contents:c},wt(f,a,mt(l)),wt(u,a,mt(c));let g=a.split(/[\\/]/),p=g.length-1,w=g[0]?1:0;for(;p>w;){let m=g.slice(0,p).join(Vt.default.sep)||Vt.default.sep;try{o.readdirSync(m);}catch{let S=Date.now(),v=new ts.VirtualStats({dev:8675309,nlink:0,uid:1e3,gid:1e3,rdev:0,blksize:4096,ino:es++,mode:16877,size:l.size,blocks:Math.floor(l.size/4096),atime:S,mtime:S,ctime:S,birthtime:S});wt(d,m,mt([])),wt(f,m,mt(v));}let b=fn(we(o),m);b=b[1]||b.result;let E=g[p];if(b.indexOf(E)<0){let y=b.concat([E]).sort();wt(we(o),m,mt(y));}else break;p--;}};}},i=()=>{if(this._staticModules){for(let[o,h]of Object.entries(this._staticModules))this.writeModule(o,h);this._staticModules=null;}},n=typeof t.webpack>"u"?4:5,r=(o,h)=>{this._watcher=o.compiler||o;let a=t.inputFileSystem._virtualFiles,l=t.fileTimestamps;a&&l&&typeof l.set=="function"&&Object.keys(a).forEach(c=>{let f=+a[c].stats.mtime;l.set(c,n===4?f:{safeTime:f,timestamp:f});}),h();};t.hooks?(t.hooks.afterEnvironment.tap("VirtualModulesPlugin",e),t.hooks.afterResolvers.tap("VirtualModulesPlugin",i),t.hooks.watchRun.tapAsync("VirtualModulesPlugin",r)):(t.plugin("after-environment",e),t.plugin("after-resolvers",i),t.plugin("watch-run",r));}};ss.exports=ye;});var rs=T((Na,ns)=>{ns.exports=function(t){if(typeof t!="string"||t==="")return !1;for(var e;e=/(\\).|([@?!+*]\(.*\))/g.exec(t);){if(e[2])return !0;t=t.slice(e.index+e[0].length);}return !1};});var hs=T((xa,as)=>{var pn=rs(),os={"{":"}","(":")","[":"]"},gn=function(s){if(s[0]==="!")return !0;for(var t=0,e=-2,i=-2,n=-2,r=-2,o=-2;tt&&(o===-1||o>i||(o=s.indexOf("\\",t),o===-1||o>i)))||n!==-1&&s[t]==="{"&&s[t+1]!=="}"&&(n=s.indexOf("}",t),n>t&&(o=s.indexOf("\\",t),o===-1||o>n))||r!==-1&&s[t]==="("&&s[t+1]==="?"&&/[:!=]/.test(s[t+2])&&s[t+3]!==")"&&(r=s.indexOf(")",t),r>t&&(o=s.indexOf("\\",t),o===-1||o>r))||e!==-1&&s[t]==="("&&s[t+1]!=="|"&&(ee&&(o=s.indexOf("\\",e),o===-1||o>r))))return !0;if(s[t]==="\\"){var h=s[t+1];t+=2;var a=os[h];if(a){var l=s.indexOf(a,t);l!==-1&&(t=l+1);}if(s[t]==="!")return !0}else t++;}return !1},mn=function(s){if(s[0]==="!")return !0;for(var t=0;t{us.exports=cs;function cs(s,t,e){s instanceof RegExp&&(s=ls(s,e)),t instanceof RegExp&&(t=ls(t,e));var i=fs(s,t,e);return i&&{start:i[0],end:i[1],pre:e.slice(0,i[0]),body:e.slice(i[0]+s.length,i[1]),post:e.slice(i[1]+t.length)}}function ls(s,t){var e=t.match(s);return e?e[0]:null}cs.range=fs;function fs(s,t,e){var i,n,r,o,h,a=e.indexOf(s),l=e.indexOf(t,a+1),c=a;if(a>=0&&l>0){if(s===t)return [a,l];for(i=[],r=e.length;c>=0&&!h;)c==a?(i.push(c),a=e.indexOf(s,c+1)):i.length==1?h=[i.pop(),l]:(n=i.pop(),n=0?a:l;i.length&&(h=[r,o]);}return h}});var Ss=T((Ca,Es)=>{var ps=ds();Es.exports=bn;var gs="\0SLASH"+Math.random()+"\0",ms="\0OPEN"+Math.random()+"\0",Se="\0CLOSE"+Math.random()+"\0",ws="\0COMMA"+Math.random()+"\0",ys="\0PERIOD"+Math.random()+"\0";function Ee(s){return parseInt(s,10)==s?parseInt(s,10):s.charCodeAt(0)}function wn(s){return s.split("\\\\").join(gs).split("\\{").join(ms).split("\\}").join(Se).split("\\,").join(ws).split("\\.").join(ys)}function yn(s){return s.split(gs).join("\\").split(ms).join("{").split(Se).join("}").split(ws).join(",").split(ys).join(".")}function bs(s){if(!s)return [""];var t=[],e=ps("{","}",s);if(!e)return s.split(",");var i=e.pre,n=e.body,r=e.post,o=i.split(",");o[o.length-1]+="{"+n+"}";var h=bs(r);return r.length&&(o[o.length-1]+=h.shift(),o.push.apply(o,h)),t.push.apply(t,o),t}function bn(s){return s?(s.substr(0,2)==="{}"&&(s="\\{\\}"+s.substr(2)),yt(wn(s),!0).map(yn)):[]}function En(s){return "{"+s+"}"}function Sn(s){return /^-?0\d/.test(s)}function vn(s,t){return s<=t}function Nn(s,t){return s>=t}function yt(s,t){var e=[],i=ps("{","}",s);if(!i)return [s];var n=i.pre,r=i.post.length?yt(i.post,!1):[""];if(/\$$/.test(i.pre))for(var o=0;o=0;if(!c&&!f)return i.post.match(/,.*\}/)?(s=i.pre+"{"+i.body+Se+i.post,yt(s)):[s];var u;if(c)u=i.body.split(/\.\./);else if(u=bs(i.body),u.length===1&&(u=yt(u[0],!1).map(En),u.length===1))return r.map(function(Bt){return i.pre+u[0]+Bt});var d;if(c){var g=Ee(u[0]),p=Ee(u[1]),w=Math.max(u[0].length,u[1].length),m=u.length==3?Math.abs(Ee(u[2])):1,b=vn,E=p0){var jt=new Array(z+1).join("0");S<0?v="-"+jt+v.slice(1):v=jt+v;}}d.push(v);}}else {d=[];for(var D=0;D{var ci=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",Yr=ci+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",fi="["+ci+"]["+Yr+"]*",Kr=new RegExp("^"+fi+"$"),Zr=function(s,t){let e=[],i=t.exec(s);for(;i;){let n=[];n.startIndex=t.lastIndex-i[0].length;let r=i.length;for(let o=0;o"u")};Z.isExist=function(s){return typeof s<"u"};Z.isEmptyObject=function(s){return Object.keys(s).length===0};Z.merge=function(s,t,e){if(t){let i=Object.keys(t),n=i.length;for(let r=0;r{var $e=fe(),Qr={allowBooleanAttributes:!1,unpairedTags:[]};mi.validate=function(s,t){t=Object.assign({},Qr,t);let e=[],i=!1,n=!1;s[0]==="\uFEFF"&&(s=s.substr(1));for(let r=0;r"&&s[r]!==" "&&s[r]!==" "&&s[r]!==` +`&&s[r]!=="\r";r++)a+=s[r];if(a=a.trim(),a[a.length-1]==="/"&&(a=a.substring(0,a.length-1),r--),!ao(a)){let f;return a.trim().length===0?f="Invalid space after '<'.":f="Tag '"+a+"' is an invalid name.",x("InvalidTag",f,M(s,r))}let l=so(s,r);if(l===!1)return x("InvalidAttr","Attributes for '"+a+"' have open quote.",M(s,r));let c=l.value;if(r=l.index,c[c.length-1]==="/"){let f=r-c.length;c=c.substring(0,c.length-1);let u=gi(c,t);if(u===!0)i=!0;else return x(u.err.code,u.err.msg,M(s,f+u.err.line))}else if(h)if(l.tagClosed){if(c.trim().length>0)return x("InvalidTag","Closing tag '"+a+"' can't have attributes or invalid starting.",M(s,o));{let f=e.pop();if(a!==f.tagName){let u=M(s,f.tagStartPos);return x("InvalidTag","Expected closing tag '"+f.tagName+"' (opened in line "+u.line+", col "+u.col+") instead of closing tag '"+a+"'.",M(s,o))}e.length==0&&(n=!0);}}else return x("InvalidTag","Closing tag '"+a+"' doesn't have proper closing.",M(s,r));else {let f=gi(c,t);if(f!==!0)return x(f.err.code,f.err.msg,M(s,r-c.length+f.err.line));if(n===!0)return x("InvalidXml","Multiple possible root nodes found.",M(s,r));t.unpairedTags.indexOf(a)!==-1||e.push({tagName:a,tagStartPos:o}),i=!0;}for(r++;r0)return x("InvalidXml","Invalid '"+JSON.stringify(e.map(r=>r.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return x("InvalidXml","Start tag expected.",1);return !0};function ui(s){return s===" "||s===" "||s===` +`||s==="\r"}function di(s,t){let e=t;for(;t5&&i==="xml")return x("InvalidXml","XML declaration allowed only at the start of the document.",M(s,t));if(s[t]=="?"&&s[t+1]==">"){t++;break}else continue}return t}function pi(s,t){if(s.length>t+5&&s[t+1]==="-"&&s[t+2]==="-"){for(t+=3;t"){t+=2;break}}else if(s.length>t+8&&s[t+1]==="D"&&s[t+2]==="O"&&s[t+3]==="C"&&s[t+4]==="T"&&s[t+5]==="Y"&&s[t+6]==="P"&&s[t+7]==="E"){let e=1;for(t+=8;t"&&(e--,e===0))break}else if(s.length>t+9&&s[t+1]==="["&&s[t+2]==="C"&&s[t+3]==="D"&&s[t+4]==="A"&&s[t+5]==="T"&&s[t+6]==="A"&&s[t+7]==="["){for(t+=8;t"){t+=2;break}}return t}var to='"',eo="'";function so(s,t){let e="",i="",n=!1;for(;t"&&i===""){n=!0;break}e+=s[t];}return i!==""?!1:{value:e,index:t,tagClosed:n}}var io=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function gi(s,t){let e=$e.getAllMatches(s,io),i={};for(let n=0;n{var wi={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(s,t){return t},attributeValueProcessor:function(s,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(s,t,e){return s}},ho=function(s){return Object.assign({},wi,s)};Ue.buildOptions=ho;Ue.defaultOptions=wi;});var Ei=T((Yh,bi)=>{var Ge=class{constructor(t){this.tagname=t,this.child=[],this[":@"]={};}add(t,e){t==="__proto__"&&(t="#__proto__"),this.child.push({[t]:e});}addChild(t){t.tagname==="__proto__"&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child});}};bi.exports=Ge;});var vi=T((Kh,Si)=>{var lo=fe();function co(s,t){let e={};if(s[t+3]==="O"&&s[t+4]==="C"&&s[t+5]==="T"&&s[t+6]==="Y"&&s[t+7]==="P"&&s[t+8]==="E"){t=t+9;let i=1,n=!1,r=!1,o="";for(;t"){if(r?s[t-1]==="-"&&s[t-2]==="-"&&(r=!1,i--):i--,i===0)break}else s[t]==="["?n=!0:o+=s[t];if(i!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return {entities:e,i:t}}function fo(s,t){let e="";for(;t{var bo=/^[-+]?0x[a-fA-F0-9]+$/,Eo=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt);!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var So={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function vo(s,t={}){if(t=Object.assign({},So,t),!s||typeof s!="string")return s;let e=s.trim();if(t.skipLike!==void 0&&t.skipLike.test(e))return s;if(t.hex&&bo.test(e))return Number.parseInt(e,16);{let i=Eo.exec(e);if(i){let n=i[1],r=i[2],o=No(i[3]),h=i[4]||i[6];if(!t.leadingZeros&&r.length>0&&n&&e[2]!==".")return s;if(!t.leadingZeros&&r.length>0&&!n&&e[1]!==".")return s;{let a=Number(e),l=""+a;return l.search(/[eE]/)!==-1||h?t.eNotation?a:s:e.indexOf(".")!==-1?l==="0"&&o===""||l===o||n&&l==="-"+o?a:s:r?o===l||n+o===l?a:s:e===l||e===n+l?a:s}}else return s}}function No(s){return s&&s.indexOf(".")!==-1&&(s=s.replace(/0+$/,""),s==="."?s="0":s[0]==="."?s="0"+s:s[s.length-1]==="."&&(s=s.substr(0,s.length-1))),s}Ni.exports=vo;});var Ai=T((Jh,Ci)=>{var Ti=fe(),Wt=Ei(),xo=vi(),To=xi(),Ve=class{constructor(t){this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,i)=>String.fromCharCode(Number.parseInt(i,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,i)=>String.fromCharCode(Number.parseInt(i,16))}},this.addExternalEntities=Co,this.parseXml=ko,this.parseTextData=Ao,this.resolveNameSpace=Oo,this.buildAttributesMap=Po,this.isItStopNode=Mo,this.replaceEntitiesValue=Ro,this.readStopNodeData=Wo,this.saveTextToParentTag=Io,this.addChild=Fo;}};function Co(s){let t=Object.keys(s);for(let e=0;e0)){o||(s=this.replaceEntitiesValue(s));let h=this.options.tagValueProcessor(t,s,e,n,r);return h==null?s:typeof h!=typeof s||h!==s?h:this.options.trimValues?De(s,this.options.parseTagValue,this.options.numberParseOptions):s.trim()===s?De(s,this.options.parseTagValue,this.options.numberParseOptions):s}}function Oo(s){if(this.options.removeNSPrefix){let t=s.split(":"),e=s.charAt(0)==="/"?"/":"";if(t[0]==="xmlns")return "";t.length===2&&(s=e+t[1]);}return s}var _o=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function Po(s,t,e){if(!this.options.ignoreAttributes&&typeof s=="string"){let i=Ti.getAllMatches(s,_o),n=i.length,r={};for(let o=0;o",r,"Closing Tag is not closed."),a=s.substring(r+2,h).trim();if(this.options.removeNSPrefix){let f=a.indexOf(":");f!==-1&&(a=a.substr(f+1));}this.options.transformTagName&&(a=this.options.transformTagName(a)),e&&(i=this.saveTextToParentTag(i,e,n));let l=n.substring(n.lastIndexOf(".")+1);if(a&&this.options.unpairedTags.indexOf(a)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: `);let c=0;l&&this.options.unpairedTags.indexOf(l)!==-1?(c=n.lastIndexOf(".",n.lastIndexOf(".")-1),this.tagsNodeStack.pop()):c=n.lastIndexOf("."),n=n.substring(0,c),e=this.tagsNodeStack.pop(),i="",r=h;}else if(s[r+1]==="?"){let h=He(s,r,!1,"?>");if(!h)throw new Error("Pi Tag is not closed.");if(i=this.saveTextToParentTag(i,e,n),!(this.options.ignoreDeclaration&&h.tagName==="?xml"||this.options.ignorePiTags)){let a=new Wt(h.tagName);a.add(this.options.textNodeName,""),h.tagName!==h.tagExp&&h.attrExpPresent&&(a[":@"]=this.buildAttributesMap(h.tagExp,n,h.tagName)),this.addChild(e,a,n);}r=h.closeIndex+1;}else if(s.substr(r+1,3)==="!--"){let h=rt(s,"-->",r+4,"Comment is not closed.");if(this.options.commentPropName){let a=s.substring(r+4,h-2);i=this.saveTextToParentTag(i,e,n),e.add(this.options.commentPropName,[{[this.options.textNodeName]:a}]);}r=h;}else if(s.substr(r+1,2)==="!D"){let h=xo(s,r);this.docTypeEntities=h.entities,r=h.i;}else if(s.substr(r+1,2)==="!["){let h=rt(s,"]]>",r,"CDATA is not closed.")-2,a=s.substring(r+9,h);i=this.saveTextToParentTag(i,e,n);let l=this.parseTextData(a,e.tagname,n,!0,!1,!0,!0);l==null&&(l=""),this.options.cdataPropName?e.add(this.options.cdataPropName,[{[this.options.textNodeName]:a}]):e.add(this.options.textNodeName,l),r=h+2;}else {let h=He(s,r,this.options.removeNSPrefix),a=h.tagName,l=h.rawTagName,c=h.tagExp,f=h.attrExpPresent,u=h.closeIndex;this.options.transformTagName&&(a=this.options.transformTagName(a)),e&&i&&e.tagname!=="!xml"&&(i=this.saveTextToParentTag(i,e,n,!1));let d=e;if(d&&this.options.unpairedTags.indexOf(d.tagname)!==-1&&(e=this.tagsNodeStack.pop(),n=n.substring(0,n.lastIndexOf("."))),a!==t.tagname&&(n+=n?"."+a:a),this.isItStopNode(this.options.stopNodes,n,a)){let g="";if(c.length>0&&c.lastIndexOf("/")===c.length-1)r=h.closeIndex;else if(this.options.unpairedTags.indexOf(a)!==-1)r=h.closeIndex;else {let w=this.readStopNodeData(s,l,u+1);if(!w)throw new Error(`Unexpected end of ${l}`);r=w.i,g=w.tagContent;}let p=new Wt(a);a!==c&&f&&(p[":@"]=this.buildAttributesMap(c,n,a)),g&&(g=this.parseTextData(g,a,n,!0,f,!0,!0)),n=n.substr(0,n.lastIndexOf(".")),p.add(this.options.textNodeName,g),this.addChild(e,p,n);}else {if(c.length>0&&c.lastIndexOf("/")===c.length-1){a[a.length-1]==="/"?(a=a.substr(0,a.length-1),n=n.substr(0,n.length-1),c=a):c=c.substr(0,c.length-1),this.options.transformTagName&&(a=this.options.transformTagName(a));let g=new Wt(a);a!==c&&f&&(g[":@"]=this.buildAttributesMap(c,n,a)),this.addChild(e,g,n),n=n.substr(0,n.lastIndexOf("."));}else {let g=new Wt(a);this.tagsNodeStack.push(e),a!==c&&f&&(g[":@"]=this.buildAttributesMap(c,n,a)),this.addChild(e,g,n),e=g;}i="",r=u;}}else i+=s[r];return t.child};function Fo(s,t,e){let i=this.options.updateTag(t.tagname,e,t[":@"]);i===!1||(typeof i=="string"&&(t.tagname=i),s.addChild(t));}var Ro=function(s){if(this.options.processEntities){for(let t in this.docTypeEntities){let e=this.docTypeEntities[t];s=s.replace(e.regx,e.val);}for(let t in this.lastEntities){let e=this.lastEntities[t];s=s.replace(e.regex,e.val);}if(this.options.htmlEntities)for(let t in this.htmlEntities){let e=this.htmlEntities[t];s=s.replace(e.regex,e.val);}s=s.replace(this.ampEntity.regex,this.ampEntity.val);}return s};function Io(s,t,e,i){return s&&(i===void 0&&(i=Object.keys(t.child).length===0),s=this.parseTextData(s,t.tagname,e,!1,t[":@"]?Object.keys(t[":@"]).length!==0:!1,i),s!==void 0&&s!==""&&t.add(this.options.textNodeName,s),s=""),s}function Mo(s,t,e){let i="*."+e;for(let n in s){let r=s[n];if(i===r||t===r)return !0}return !1}function Lo(s,t,e=">"){let i,n="";for(let r=t;r",e,`${t} is not closed`);if(s.substring(e+2,r).trim()===t&&(n--,n===0))return {tagContent:s.substring(i,e),i:r};e=r;}else if(s[e+1]==="?")e=rt(s,"?>",e+1,"StopNode is not closed.");else if(s.substr(e+1,3)==="!--")e=rt(s,"-->",e+3,"StopNode is not closed.");else if(s.substr(e+1,2)==="![")e=rt(s,"]]>",e,"StopNode is not closed.")-2;else {let r=He(s,e,">");r&&((r&&r.tagName)===t&&r.tagExp[r.tagExp.length-1]!=="/"&&n++,e=r.closeIndex);}}function De(s,t,e){if(t&&typeof s=="string"){let i=s.trim();return i==="true"?!0:i==="false"?!1:To(s,e)}else return Ti.isExist(s)?s:""}Ci.exports=Ve;});var Pi=T(_i=>{function jo(s,t){return Oi(s,t)}function Oi(s,t,e){let i,n={};for(let r=0;r0&&(n[t.textNodeName]=i):i!==void 0&&(n[t.textNodeName]=i),n}function Bo(s){let t=Object.keys(s);for(let e=0;e{var{buildOptions:Uo}=yi(),Go=Ai(),{prettify:Vo}=Pi(),Ho=ze(),qe=class{constructor(t){this.externalEntities={},this.options=Uo(t);}parse(t,e){if(typeof t!="string")if(t.toString)t=t.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(e){e===!0&&(e={});let r=Ho.validate(t,e);if(r!==!0)throw Error(`${r.err.msg}:${r.err.line}:${r.err.col}`)}let i=new Go(this.options);i.addExternalEntities(this.externalEntities);let n=i.parseXml(t);return this.options.preserveOrder||n===void 0?n:Vo(n,this.options)}addEntity(t,e){if(e.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(t.indexOf("&")!==-1||t.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '");if(e==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e;}};ki.exports=qe;});var Wi=T((el,Li)=>{var Do=` +`;function qo(s,t){let e="";return t.format&&t.indentBy.length>0&&(e=Do),Ii(s,t,"",e)}function Ii(s,t,e,i){let n="",r=!1;for(let o=0;o`,r=!1;continue}else if(a===t.commentPropName){n+=i+``,r=!0;continue}else if(a[0]==="?"){let g=Ri(h[":@"],t),p=a==="?xml"?"":i,w=h[a][0][t.textNodeName];w=w.length!==0?" "+w:"",n+=p+`<${a}${w}${g}?>`,r=!0;continue}let c=i;c!==""&&(c+=t.indentBy);let f=Ri(h[":@"],t),u=i+`<${a}${f}`,d=Ii(h[a],t,l,c);t.unpairedTags.indexOf(a)!==-1?t.suppressUnpairedNode?n+=u+">":n+=u+"/>":(!d||d.length===0)&&t.suppressEmptyNode?n+=u+"/>":d&&d.endsWith(">")?n+=u+`>${d}${i}`:(n+=u+">",d&&i!==""&&(d.includes("/>")||d.includes("`),r=!0;}return n}function Xo(s){let t=Object.keys(s);for(let e=0;e0&&t.processEntities)for(let e=0;e{var Ko=Wi(),Zo={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(s,t){return t},attributeValueProcessor:function(s,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function st(s){this.options=Object.assign({},Zo,s),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return !1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=ta),this.processTextOrObjNode=Jo,this.options.format?(this.indentate=Qo,this.tagEndChar=`> `,this.newLine=` -`):(this.indentate=function(){return ""},this.tagEndChar=">",this.newLine="");}st.prototype.build=function(s){return this.options.preserveOrder?ea(s,this.options):(Array.isArray(s)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(s={[this.options.arrayNodeName]:s}),this.j2x(s,0).val)};st.prototype.j2x=function(s,t){let e="",i="";for(let n in s)if(Object.prototype.hasOwnProperty.call(s,n))if(typeof s[n]>"u")this.isAttribute(n)&&(i+="");else if(s[n]===null)this.isAttribute(n)?i+="":n[0]==="?"?i+=this.indentate(t)+"<"+n+"?"+this.tagEndChar:i+=this.indentate(t)+"<"+n+"/"+this.tagEndChar;else if(s[n]instanceof Date)i+=this.buildTextValNode(s[n],n,"",t);else if(typeof s[n]!="object"){let r=this.isAttribute(n);if(r)e+=this.buildAttrPairStr(r,""+s[n]);else if(n===this.options.textNodeName){let o=this.options.tagValueProcessor(n,""+s[n]);i+=this.replaceEntitiesValue(o);}else i+=this.buildTextValNode(s[n],n,"",t);}else if(Array.isArray(s[n])){let r=s[n].length,o="";for(let h=0;h"u"||(a===null?n[0]==="?"?i+=this.indentate(t)+"<"+n+"?"+this.tagEndChar:i+=this.indentate(t)+"<"+n+"/"+this.tagEndChar:typeof a=="object"?this.options.oneListGroup?o+=this.j2x(a,t+1).val:o+=this.processTextOrObjNode(a,n,t):o+=this.buildTextValNode(a,n,"",t));}this.options.oneListGroup&&(o=this.buildObjectNode(o,n,"",t)),i+=o;}else if(this.options.attributesGroupName&&n===this.options.attributesGroupName){let r=Object.keys(s[n]),o=r.length;for(let h=0;h"+s+n:this.options.commentPropName!==!1&&t===this.options.commentPropName&&r.length===0?this.indentate(i)+``+this.newLine:this.indentate(i)+"<"+t+e+r+this.tagEndChar+s+this.indentate(i)+n}};st.prototype.closeTag=function(s){let t="";return this.options.unpairedTags.indexOf(s)!==-1?this.options.suppressUnpairedNode||(t="/"):this.options.suppressEmptyNode?t="/":t=`>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(i)+``+this.newLine;if(t[0]==="?")return this.indentate(i)+"<"+t+e+"?"+this.tagEndChar;{let n=this.options.tagValueProcessor(t,s);return n=this.replaceEntitiesValue(n),n===""?this.indentate(i)+"<"+t+e+this.closeTag(t)+this.tagEndChar:this.indentate(i)+"<"+t+e+">"+n+"0&&this.options.processEntities)for(let t=0;t{var oa=$e(),aa=Li(),ha=Gi();Vi.exports={XMLParser:aa,XMLValidator:oa,XMLBuilder:ha};});function sn(s){for(var t=[],e=1;e1&&(s={[this.options.arrayNodeName]:s}),this.j2x(s,0).val)};st.prototype.j2x=function(s,t){let e="",i="";for(let n in s)if(Object.prototype.hasOwnProperty.call(s,n))if(typeof s[n]>"u")this.isAttribute(n)&&(i+="");else if(s[n]===null)this.isAttribute(n)?i+="":n[0]==="?"?i+=this.indentate(t)+"<"+n+"?"+this.tagEndChar:i+=this.indentate(t)+"<"+n+"/"+this.tagEndChar;else if(s[n]instanceof Date)i+=this.buildTextValNode(s[n],n,"",t);else if(typeof s[n]!="object"){let r=this.isAttribute(n);if(r)e+=this.buildAttrPairStr(r,""+s[n]);else if(n===this.options.textNodeName){let o=this.options.tagValueProcessor(n,""+s[n]);i+=this.replaceEntitiesValue(o);}else i+=this.buildTextValNode(s[n],n,"",t);}else if(Array.isArray(s[n])){let r=s[n].length,o="";for(let h=0;h"u"||(a===null?n[0]==="?"?i+=this.indentate(t)+"<"+n+"?"+this.tagEndChar:i+=this.indentate(t)+"<"+n+"/"+this.tagEndChar:typeof a=="object"?this.options.oneListGroup?o+=this.j2x(a,t+1).val:o+=this.processTextOrObjNode(a,n,t):o+=this.buildTextValNode(a,n,"",t));}this.options.oneListGroup&&(o=this.buildObjectNode(o,n,"",t)),i+=o;}else if(this.options.attributesGroupName&&n===this.options.attributesGroupName){let r=Object.keys(s[n]),o=r.length;for(let h=0;h"+s+n:this.options.commentPropName!==!1&&t===this.options.commentPropName&&r.length===0?this.indentate(i)+``+this.newLine:this.indentate(i)+"<"+t+e+r+this.tagEndChar+s+this.indentate(i)+n}};st.prototype.closeTag=function(s){let t="";return this.options.unpairedTags.indexOf(s)!==-1?this.options.suppressUnpairedNode||(t="/"):this.options.suppressEmptyNode?t="/":t=`>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(i)+``+this.newLine;if(t[0]==="?")return this.indentate(i)+"<"+t+e+"?"+this.tagEndChar;{let n=this.options.tagValueProcessor(t,s);return n=this.replaceEntitiesValue(n),n===""?this.indentate(i)+"<"+t+e+this.closeTag(t)+this.tagEndChar:this.indentate(i)+"<"+t+e+">"+n+"0&&this.options.processEntities)for(let t=0;t{var ea=ze(),sa=Fi(),ia=Bi();$i.exports={XMLParser:sa,XMLValidator:ea,XMLBuilder:ia};});var de=class extends Error{constructor(e){super("Unable to render preview.");this.errorPage=e;}},Ut=async s=>{let t=new URL(`${s}/_storybook/preview`),e=await fetch(t,{method:"GET",headers:{Accept:"text/html"}}),i=await e.text();if(!e.ok)throw new de(i);return i},Ze=async s=>{let t=`${s}/symfony_parameters.json`;return JSON.parse(ce__namespace.default.readFileSync(t,"utf8"))};function Qi(s){for(var t=[],e=1;e{let i={...rn,...e};return [i.php,i.script,s].concat([...t,"-v"]).map(n=>`'${n}'`).join(" ")},Ke=async s=>new Promise((t,e)=>{child_process.exec(s,(i,n,r)=>{i&&e(new Error(T` - Symfony console failed with exit status ${i.code}: - CMD: ${i.cmd} - Output: ${n} - Error output: ${r} - `)),t(n);});}),Ut=async(s,t=[],e={})=>{let i=Ye(s,t,e);return Ke(i)},Gt=async(s,t=[],e={})=>{let i=Ye(s,[...t,"--format=json"],e),n=await Ke(i);try{return JSON.parse(n)}catch{throw new Error(T` - Failed to process JSON output for Symfony command. - CMD: ${i} - Raw output: ${n} - `)}},Ze=async()=>(await Gt("debug:container",["--parameter=kernel.project_dir"]))["kernel.project_dir"],Je=async()=>(await Gt("debug:config",["storybook"])).storybook,Qe=async()=>(await Gt("debug:config",["twig_component","--resolve-env"])).twig_component,ts=async()=>(await Gt("debug:config",["twig","--resolve-env"])).twig;var Vt=(s,t)=>{let e=new jsdom.JSDOM(s),i=e.window.document.head,n=e.window.document.body;return t.replace("",i.innerHTML).replace("",n.innerHTML)};var de="preview-plugin",es=unplugin.createUnplugin(()=>({name:de,webpack(s){s.hooks.thisCompilation.tap(de,t=>{hn__default.default.getHooks(t).afterTemplateExecution.tapPromise(de,async e=>{try{let i=await Ut("storybook:generate-preview");return e.html=Vt(i,e.html),e}catch(i){return nodeLogger.logger.error(T` +`)),o+=f+i[a+1];}),o}var _=Qi;var Gt=(s,t)=>{let e=new jsdom.JSDOM(s),i=e.window.document.head,n=e.window.document.body;return t.replace("",i.innerHTML).replace("",n.innerHTML)};var pe="preview-plugin",Je=unplugin.createUnplugin(s=>{let{server:t}=s;return {name:pe,webpack(e){e.hooks.thisCompilation.tap(pe,i=>{sn__default.default.getHooks(i).afterTemplateExecution.tapPromise(pe,async n=>{try{let r=await Ut(t);return n.html=Gt(r,n.html),n}catch(r){return nodeLogger.logger.error(_` Failed to inject Symfony preview template in main iframe.html. - ERR: ${i} - `),e}});});}}));var ui=zt(os());var ci=zt(fs());var Fs=zt(Ts(),1);var bt=s=>{if(typeof s!="string")throw new TypeError("invalid pattern");if(s.length>65536)throw new TypeError("pattern is too long")};var _n={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},St=s=>s.replace(/[[\]\\-]/g,"\\$&"),kn=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),xs=s=>s.join(""),Cs=(s,t)=>{let e=t;if(s.charAt(e)!=="[")throw new Error("not in a brace expression");let i=[],n=[],r=e+1,o=!1,h=!1,a=!1,l=!1,c=e,f="";t:for(;rf?i.push(St(f)+"-"+St(p)):p===f&&i.push(St(p)),f="",r++;continue}if(s.startsWith("-]",r+1)){i.push(St(p+"-")),r+=2;continue}if(s.startsWith("-",r+1)){f=p,r+=2;continue}i.push(St(p)),r++;}if(ct?s.replace(/\[([^\/\\])\]/g,"$1"):s.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var Pn=new Set(["!","?","+","*","@"]),As=s=>Pn.has(s),Fn="(?!(?:^|/)\\.\\.?(?:$|/))",Dt="(?!\\.)",Rn=new Set(["[","."]),In=new Set(["..","."]),Mn=new Set("().*{}+?[]^$\\!"),Ln=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ee="[^/]",Os=Ee+"*?",_s=Ee+"+?",at=class s{type;#t;#s;#r=!1;#i=[];#a;#l;#f;#h=!1;#o;#e;#g=!1;constructor(t,e,i={}){this.type=t,t&&(this.#s=!0),this.#a=e,this.#t=this.#a?this.#a.#t:this,this.#o=this.#t===this?i:this.#t.#o,this.#f=this.#t===this?[]:this.#t.#f,t==="!"&&!this.#t.#h&&this.#f.push(this),this.#l=this.#a?this.#a.#i.length:0;}get hasMagic(){if(this.#s!==void 0)return this.#s;for(let t of this.#i)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#s=!0;return this.#s}toString(){return this.#e!==void 0?this.#e:this.type?this.#e=this.type+"("+this.#i.map(t=>String(t)).join("|")+")":this.#e=this.#i.map(t=>String(t)).join("")}#w(){if(this!==this.#t)throw new Error("should only call on root");if(this.#h)return this;this.toString(),this.#h=!0;let t;for(;t=this.#f.pop();){if(t.type!=="!")continue;let e=t,i=e.#a;for(;i;){for(let n=e.#l+1;!i.type&&ntypeof e=="string"?e:e.toJSON()):[this.type,...this.#i.map(e=>e.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#h&&this.#a?.type==="!")&&t.push({}),t}isStart(){if(this.#t===this)return !0;if(!this.#a?.isStart())return !1;if(this.#l===0)return !0;let t=this.#a;for(let e=0;e{let[g,p,w,m]=typeof d=="string"?s.#S(d,this.#s,a):d.toRegExpSource(t);return this.#s=this.#s||w,this.#r=this.#r||m,g}).join(""),c="";if(this.isStart()&&typeof this.#i[0]=="string"&&!(this.#i.length===1&&In.has(this.#i[0]))){let g=Rn,p=e&&g.has(l.charAt(0))||l.startsWith("\\.")&&g.has(l.charAt(2))||l.startsWith("\\.\\.")&&g.has(l.charAt(4)),w=!e&&!t&&g.has(l.charAt(0));c=p?Fn:w?Dt:"";}let f="";return this.isEnd()&&this.#t.#h&&this.#a?.type==="!"&&(f="(?:$|\\/)"),[c+l+f,U(l),this.#s=!!this.#s,this.#r]}let i=this.type==="*"||this.type==="+",n=this.type==="!"?"(?:(?!(?:":"(?:",r=this.#u(e);if(this.isStart()&&this.isEnd()&&!r&&this.type!=="!"){let a=this.toString();return this.#i=[a],this.type=null,this.#s=void 0,[a,U(this.toString()),!1,!1]}let o=!i||t||e||!Dt?"":this.#u(!0);o===r&&(o=""),o&&(r=`(?:${r})(?:${o})*?`);let h="";if(this.type==="!"&&this.#g)h=(this.isStart()&&!e?Dt:"")+_s;else {let a=this.type==="!"?"))"+(this.isStart()&&!e&&!t?Dt:"")+Os+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;h=n+r+a;}return [h,U(r),this.#s=!!this.#s,this.#r]}#u(t){return this.#i.map(e=>{if(typeof e=="string")throw new Error("string type in extglob ast??");let[i,n,r,o]=e.toRegExpSource(t);return this.#r=this.#r||o,i}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join("|")}static#S(t,e,i=!1){let n=!1,r="",o=!1;for(let h=0;ht?s.replace(/[?*()[\]]/g,"[$&]"):s.replace(/[?*()[\]\\]/g,"\\$&");var R=(s,t,e={})=>(bt(t),!e.nocomment&&t.charAt(0)==="#"?!1:new L(t,e).match(s)),jn=/^\*+([^+@!?\*\[\(]*)$/,Wn=s=>t=>!t.startsWith(".")&&t.endsWith(s),Bn=s=>t=>t.endsWith(s),$n=s=>(s=s.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(s)),zn=s=>(s=s.toLowerCase(),t=>t.toLowerCase().endsWith(s)),Un=/^\*+\.\*+$/,Gn=s=>!s.startsWith(".")&&s.includes("."),Vn=s=>s!=="."&&s!==".."&&s.includes("."),Hn=/^\.\*+$/,Dn=s=>s!=="."&&s!==".."&&s.startsWith("."),qn=/^\*+$/,Xn=s=>s.length!==0&&!s.startsWith("."),Yn=s=>s.length!==0&&s!=="."&&s!=="..",Kn=/^\?+([^+@!?\*\[\(]*)?$/,Zn=([s,t=""])=>{let e=Rs([s]);return t?(t=t.toLowerCase(),i=>e(i)&&i.toLowerCase().endsWith(t)):e},Jn=([s,t=""])=>{let e=Is([s]);return t?(t=t.toLowerCase(),i=>e(i)&&i.toLowerCase().endsWith(t)):e},Qn=([s,t=""])=>{let e=Is([s]);return t?i=>e(i)&&i.endsWith(t):e},tr=([s,t=""])=>{let e=Rs([s]);return t?i=>e(i)&&i.endsWith(t):e},Rs=([s])=>{let t=s.length;return e=>e.length===t&&!e.startsWith(".")},Is=([s])=>{let t=s.length;return e=>e.length===t&&e!=="."&&e!==".."},Ms=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",ks={win32:{sep:"\\"},posix:{sep:"/"}},er=Ms==="win32"?ks.win32.sep:ks.posix.sep;R.sep=er;var k=Symbol("globstar **");R.GLOBSTAR=k;var sr="[^/]",ir=sr+"*?",nr="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",rr="(?:(?!(?:\\/|^)\\.).)*?",or=(s,t={})=>e=>R(e,s,t);R.filter=or;var W=(s,t={})=>Object.assign({},s,t),ar=s=>{if(!s||typeof s!="object"||!Object.keys(s).length)return R;let t=R;return Object.assign((i,n,r={})=>t(i,n,W(s,r)),{Minimatch:class extends t.Minimatch{constructor(n,r={}){super(n,W(s,r));}static defaults(n){return t.defaults(W(s,n)).Minimatch}},AST:class extends t.AST{constructor(n,r,o={}){super(n,r,W(s,o));}static fromGlob(n,r={}){return t.AST.fromGlob(n,W(s,r))}},unescape:(i,n={})=>t.unescape(i,W(s,n)),escape:(i,n={})=>t.escape(i,W(s,n)),filter:(i,n={})=>t.filter(i,W(s,n)),defaults:i=>t.defaults(W(s,i)),makeRe:(i,n={})=>t.makeRe(i,W(s,n)),braceExpand:(i,n={})=>t.braceExpand(i,W(s,n)),match:(i,n,r={})=>t.match(i,n,W(s,r)),sep:t.sep,GLOBSTAR:k})};R.defaults=ar;var Ls=(s,t={})=>(bt(s),t.nobrace||!/\{(?:(?!\{).)*\}/.test(s)?[s]:(0, Fs.default)(s));R.braceExpand=Ls;var hr=(s,t={})=>new L(s,t).makeRe();R.makeRe=hr;var lr=(s,t,e={})=>{let i=new L(t,e);return s=s.filter(n=>i.match(n)),i.options.nonull&&!s.length&&s.push(t),s};R.match=lr;var Ps=/[?*]|[+@!]\(.*?\)|\[|\]/,cr=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),L=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){bt(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||Ms,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make();}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return !0;for(let t of this.set)for(let e of t)if(typeof e!="string")return !0;return !1}debug(...t){}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,this.globSet);let i=this.globSet.map(r=>this.slashSplit(r));this.globParts=this.preprocess(i),this.debug(this.pattern,this.globParts);let n=this.globParts.map((r,o,h)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=r[0]===""&&r[1]===""&&(r[2]==="?"||!Ps.test(r[2]))&&!Ps.test(r[3]),l=/^[a-z]:/i.test(r[0]);if(a)return [...r.slice(0,4),...r.slice(4).map(c=>this.parse(c))];if(l)return [r[0],...r.slice(1).map(c=>this.parse(c))]}return r.map(a=>this.parse(a))});if(this.debug(this.pattern,n),this.set=n.filter(r=>r.indexOf(!1)===-1),this.isWindows)for(let r=0;r=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let i=-1;for(;(i=e.indexOf("**",i+1))!==-1;){let n=i;for(;e[n+1]==="**";)n++;n!==i&&e.splice(i,n-i);}return e})}levelOneOptimize(t){return t.map(e=>(e=e.reduce((i,n)=>{let r=i[i.length-1];return n==="**"&&r==="**"?i:n===".."&&r&&r!==".."&&r!=="."&&r!=="**"?(i.pop(),i):(i.push(n),i)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let e=!1;do{if(e=!1,!this.preserveMultipleSlashes){for(let n=1;nn&&i.splice(n+1,o-n);let h=i[n+1],a=i[n+2],l=i[n+3];if(h!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;e=!0,i.splice(n,1);let c=i.slice(0);c[n]="**",t.push(c),n--;}if(!this.preserveMultipleSlashes){for(let o=1;oe.length)}partsMatch(t,e,i=!1){let n=0,r=0,o=[],h="";for(;nS?e=e.slice(y):S>y&&(t=t.slice(S)));}}let{optimizationLevel:r=1}=this.options;r>=2&&(t=this.levelTwoFileOptimize(t)),this.debug("matchOne",this,{file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var o=0,h=0,a=t.length,l=e.length;o{if(typeof s!="string")throw new TypeError("invalid pattern");if(s.length>65536)throw new TypeError("pattern is too long")};var xn={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},Et=s=>s.replace(/[[\]\\-]/g,"\\$&"),Tn=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),vs=s=>s.join(""),Ns=(s,t)=>{let e=t;if(s.charAt(e)!=="[")throw new Error("not in a brace expression");let i=[],n=[],r=e+1,o=!1,h=!1,a=!1,l=!1,c=e,f="";t:for(;rf?i.push(Et(f)+"-"+Et(p)):p===f&&i.push(Et(p)),f="",r++;continue}if(s.startsWith("-]",r+1)){i.push(Et(p+"-")),r+=2;continue}if(s.startsWith("-",r+1)){f=p,r+=2;continue}i.push(Et(p)),r++;}if(ct?s.replace(/\[([^\/\\])\]/g,"$1"):s.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var Cn=new Set(["!","?","+","*","@"]),xs=s=>Cn.has(s),An="(?!(?:^|/)\\.\\.?(?:$|/))",Ht="(?!\\.)",On=new Set(["[","."]),_n=new Set(["..","."]),Pn=new Set("().*{}+?[]^$\\!"),kn=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ve="[^/]",Ts=ve+"*?",Cs=ve+"+?",at=class s{type;#t;#s;#r=!1;#i=[];#a;#l;#f;#h=!1;#o;#e;#g=!1;constructor(t,e,i={}){this.type=t,t&&(this.#s=!0),this.#a=e,this.#t=this.#a?this.#a.#t:this,this.#o=this.#t===this?i:this.#t.#o,this.#f=this.#t===this?[]:this.#t.#f,t==="!"&&!this.#t.#h&&this.#f.push(this),this.#l=this.#a?this.#a.#i.length:0;}get hasMagic(){if(this.#s!==void 0)return this.#s;for(let t of this.#i)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#s=!0;return this.#s}toString(){return this.#e!==void 0?this.#e:this.type?this.#e=this.type+"("+this.#i.map(t=>String(t)).join("|")+")":this.#e=this.#i.map(t=>String(t)).join("")}#w(){if(this!==this.#t)throw new Error("should only call on root");if(this.#h)return this;this.toString(),this.#h=!0;let t;for(;t=this.#f.pop();){if(t.type!=="!")continue;let e=t,i=e.#a;for(;i;){for(let n=e.#l+1;!i.type&&ntypeof e=="string"?e:e.toJSON()):[this.type,...this.#i.map(e=>e.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#h&&this.#a?.type==="!")&&t.push({}),t}isStart(){if(this.#t===this)return !0;if(!this.#a?.isStart())return !1;if(this.#l===0)return !0;let t=this.#a;for(let e=0;e{let[g,p,w,m]=typeof d=="string"?s.#E(d,this.#s,a):d.toRegExpSource(t);return this.#s=this.#s||w,this.#r=this.#r||m,g}).join(""),c="";if(this.isStart()&&typeof this.#i[0]=="string"&&!(this.#i.length===1&&_n.has(this.#i[0]))){let g=On,p=e&&g.has(l.charAt(0))||l.startsWith("\\.")&&g.has(l.charAt(2))||l.startsWith("\\.\\.")&&g.has(l.charAt(4)),w=!e&&!t&&g.has(l.charAt(0));c=p?An:w?Ht:"";}let f="";return this.isEnd()&&this.#t.#h&&this.#a?.type==="!"&&(f="(?:$|\\/)"),[c+l+f,U(l),this.#s=!!this.#s,this.#r]}let i=this.type==="*"||this.type==="+",n=this.type==="!"?"(?:(?!(?:":"(?:",r=this.#u(e);if(this.isStart()&&this.isEnd()&&!r&&this.type!=="!"){let a=this.toString();return this.#i=[a],this.type=null,this.#s=void 0,[a,U(this.toString()),!1,!1]}let o=!i||t||e||!Ht?"":this.#u(!0);o===r&&(o=""),o&&(r=`(?:${r})(?:${o})*?`);let h="";if(this.type==="!"&&this.#g)h=(this.isStart()&&!e?Ht:"")+Cs;else {let a=this.type==="!"?"))"+(this.isStart()&&!e&&!t?Ht:"")+Ts+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;h=n+r+a;}return [h,U(r),this.#s=!!this.#s,this.#r]}#u(t){return this.#i.map(e=>{if(typeof e=="string")throw new Error("string type in extglob ast??");let[i,n,r,o]=e.toRegExpSource(t);return this.#r=this.#r||o,i}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join("|")}static#E(t,e,i=!1){let n=!1,r="",o=!1;for(let h=0;ht?s.replace(/[?*()[\]]/g,"[$&]"):s.replace(/[?*()[\]\\]/g,"\\$&");var R=(s,t,e={})=>(bt(t),!e.nocomment&&t.charAt(0)==="#"?!1:new L(t,e).match(s)),Fn=/^\*+([^+@!?\*\[\(]*)$/,Rn=s=>t=>!t.startsWith(".")&&t.endsWith(s),In=s=>t=>t.endsWith(s),Mn=s=>(s=s.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(s)),Ln=s=>(s=s.toLowerCase(),t=>t.toLowerCase().endsWith(s)),Wn=/^\*+\.\*+$/,jn=s=>!s.startsWith(".")&&s.includes("."),Bn=s=>s!=="."&&s!==".."&&s.includes("."),$n=/^\.\*+$/,zn=s=>s!=="."&&s!==".."&&s.startsWith("."),Un=/^\*+$/,Gn=s=>s.length!==0&&!s.startsWith("."),Vn=s=>s.length!==0&&s!=="."&&s!=="..",Hn=/^\?+([^+@!?\*\[\(]*)?$/,Dn=([s,t=""])=>{let e=Ps([s]);return t?(t=t.toLowerCase(),i=>e(i)&&i.toLowerCase().endsWith(t)):e},qn=([s,t=""])=>{let e=ks([s]);return t?(t=t.toLowerCase(),i=>e(i)&&i.toLowerCase().endsWith(t)):e},Xn=([s,t=""])=>{let e=ks([s]);return t?i=>e(i)&&i.endsWith(t):e},Yn=([s,t=""])=>{let e=Ps([s]);return t?i=>e(i)&&i.endsWith(t):e},Ps=([s])=>{let t=s.length;return e=>e.length===t&&!e.startsWith(".")},ks=([s])=>{let t=s.length;return e=>e.length===t&&e!=="."&&e!==".."},Fs=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",As={win32:{sep:"\\"},posix:{sep:"/"}},Kn=Fs==="win32"?As.win32.sep:As.posix.sep;R.sep=Kn;var P=Symbol("globstar **");R.GLOBSTAR=P;var Zn="[^/]",Jn=Zn+"*?",Qn="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",tr="(?:(?!(?:\\/|^)\\.).)*?",er=(s,t={})=>e=>R(e,s,t);R.filter=er;var j=(s,t={})=>Object.assign({},s,t),sr=s=>{if(!s||typeof s!="object"||!Object.keys(s).length)return R;let t=R;return Object.assign((i,n,r={})=>t(i,n,j(s,r)),{Minimatch:class extends t.Minimatch{constructor(n,r={}){super(n,j(s,r));}static defaults(n){return t.defaults(j(s,n)).Minimatch}},AST:class extends t.AST{constructor(n,r,o={}){super(n,r,j(s,o));}static fromGlob(n,r={}){return t.AST.fromGlob(n,j(s,r))}},unescape:(i,n={})=>t.unescape(i,j(s,n)),escape:(i,n={})=>t.escape(i,j(s,n)),filter:(i,n={})=>t.filter(i,j(s,n)),defaults:i=>t.defaults(j(s,i)),makeRe:(i,n={})=>t.makeRe(i,j(s,n)),braceExpand:(i,n={})=>t.braceExpand(i,j(s,n)),match:(i,n,r={})=>t.match(i,n,j(s,r)),sep:t.sep,GLOBSTAR:P})};R.defaults=sr;var Rs=(s,t={})=>(bt(s),t.nobrace||!/\{(?:(?!\{).)*\}/.test(s)?[s]:(0, _s.default)(s));R.braceExpand=Rs;var ir=(s,t={})=>new L(s,t).makeRe();R.makeRe=ir;var nr=(s,t,e={})=>{let i=new L(t,e);return s=s.filter(n=>i.match(n)),i.options.nonull&&!s.length&&s.push(t),s};R.match=nr;var Os=/[?*]|[+@!]\(.*?\)|\[|\]/,rr=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),L=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){bt(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||Fs,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make();}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return !0;for(let t of this.set)for(let e of t)if(typeof e!="string")return !0;return !1}debug(...t){}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,this.globSet);let i=this.globSet.map(r=>this.slashSplit(r));this.globParts=this.preprocess(i),this.debug(this.pattern,this.globParts);let n=this.globParts.map((r,o,h)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=r[0]===""&&r[1]===""&&(r[2]==="?"||!Os.test(r[2]))&&!Os.test(r[3]),l=/^[a-z]:/i.test(r[0]);if(a)return [...r.slice(0,4),...r.slice(4).map(c=>this.parse(c))];if(l)return [r[0],...r.slice(1).map(c=>this.parse(c))]}return r.map(a=>this.parse(a))});if(this.debug(this.pattern,n),this.set=n.filter(r=>r.indexOf(!1)===-1),this.isWindows)for(let r=0;r=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let i=-1;for(;(i=e.indexOf("**",i+1))!==-1;){let n=i;for(;e[n+1]==="**";)n++;n!==i&&e.splice(i,n-i);}return e})}levelOneOptimize(t){return t.map(e=>(e=e.reduce((i,n)=>{let r=i[i.length-1];return n==="**"&&r==="**"?i:n===".."&&r&&r!==".."&&r!=="."&&r!=="**"?(i.pop(),i):(i.push(n),i)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let e=!1;do{if(e=!1,!this.preserveMultipleSlashes){for(let n=1;nn&&i.splice(n+1,o-n);let h=i[n+1],a=i[n+2],l=i[n+3];if(h!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;e=!0,i.splice(n,1);let c=i.slice(0);c[n]="**",t.push(c),n--;}if(!this.preserveMultipleSlashes){for(let o=1;oe.length)}partsMatch(t,e,i=!1){let n=0,r=0,o=[],h="";for(;nE?e=e.slice(y):E>y&&(t=t.slice(E)));}}let{optimizationLevel:r=1}=this.options;r>=2&&(t=this.levelTwoFileOptimize(t)),this.debug("matchOne",this,{file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var o=0,h=0,a=t.length,l=e.length;o>> no match, partial?`,t,u,e,d),u===a))}let p;if(typeof c=="string"?(p=f===c,this.debug("string match",c,f,p)):(p=c.test(f),this.debug("pattern match",c,f,p)),!p)return !1}if(o===a&&h===l)return !0;if(o===a)return i;if(h===l)return o===a-1&&t[o]==="";throw new Error("wtf?")}braceExpand(){return Ls(this.pattern,this.options)}parse(t){bt(t);let e=this.options;if(t==="**")return k;if(t==="")return "";let i,n=null;(i=t.match(qn))?n=e.dot?Yn:Xn:(i=t.match(jn))?n=(e.nocase?e.dot?zn:$n:e.dot?Bn:Wn)(i[1]):(i=t.match(Kn))?n=(e.nocase?e.dot?Jn:Zn:e.dot?Qn:tr)(i):(i=t.match(Un))?n=e.dot?Vn:Gn:(i=t.match(Hn))&&(n=Dn);let r=at.fromGlob(t,this.options).toMMPattern();return n?Object.assign(r,{test:n}):r}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let e=this.options,i=e.noglobstar?ir:e.dot?nr:rr,n=new Set(e.nocase?["i"]:[]),r=t.map(a=>{let l=a.map(c=>{if(c instanceof RegExp)for(let f of c.flags.split(""))n.add(f);return typeof c=="string"?cr(c):c===k?k:c._src});return l.forEach((c,f)=>{let u=l[f+1],d=l[f-1];c!==k||d===k||(d===void 0?u!==void 0&&u!==k?l[f+1]="(?:\\/|"+i+"\\/)?"+u:l[f]=i:u===void 0?l[f-1]=d+"(?:\\/|"+i+")?":u!==k&&(l[f-1]=d+"(?:\\/|\\/"+i+"\\/)"+u,l[f+1]=k));}),l.filter(c=>c!==k).join("/")}).join("|"),[o,h]=t.length>1?["(?:",")"]:["",""];r="^"+o+r+h+"$",this.negate&&(r="^(?!"+r+").+$");try{this.regexp=new RegExp(r,[...n].join(""));}catch{this.regexp=!1;}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,e=this.partial){if(this.debug("match",t,this.pattern),this.comment)return !1;if(this.empty)return t==="";if(t==="/"&&e)return !0;let i=this.options;this.isWindows&&(t=t.split("\\").join("/"));let n=this.slashSplit(t);this.debug(this.pattern,"split",n);let r=this.set;this.debug(this.pattern,"set",r);let o=n[n.length-1];if(!o)for(let h=n.length-2;!o&&h>=0;h--)o=n[h];for(let h=0;h{typeof ve.emitWarning=="function"?ve.emitWarning(s,t,e,i):console.error(`[${e}] ${t}: ${s}`);},qt=globalThis.AbortController,js=globalThis.AbortSignal;if(typeof qt>"u"){js=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(i,n){this._onabort.push(n);}},qt=class{constructor(){t();}signal=new js;abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=!0;for(let n of this.signal._onabort)n(i);this.signal.onabort?.(i);}}};let s=ve.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{s&&(s=!1,Bs("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t));};}var fr=s=>!Ws.has(s),Q=s=>s&&s===Math.floor(s)&&s>0&&isFinite(s),$s=s=>Q(s)?s<=Math.pow(2,8)?Uint8Array:s<=Math.pow(2,16)?Uint16Array:s<=Math.pow(2,32)?Uint32Array:s<=Number.MAX_SAFE_INTEGER?ct:null:null,ct=class extends Array{constructor(t){super(t),this.fill(0);}},Ne=class s{heap;length;static#t=!1;static create(t){let e=$s(t);if(!e)return [];s.#t=!0;let i=new s(t,e);return s.#t=!1,i}constructor(t,e){if(!s.#t)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0;}push(t){this.heap[this.length++]=t;}pop(){return this.heap[--this.length]}},Et=class s{#t;#s;#r;#i;#a;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#l;#f;#h;#o;#e;#g;#w;#d;#u;#S;#m;#x;#C;#E;#b;#O;#p;static unsafeExposeInternals(t){return {starts:t.#C,ttls:t.#E,sizes:t.#x,keyMap:t.#h,keyList:t.#o,valList:t.#e,next:t.#g,prev:t.#w,get head(){return t.#d},get tail(){return t.#u},free:t.#S,isBackgroundFetch:e=>t.#c(e),backgroundFetch:(e,i,n,r)=>t.#I(e,i,n,r),moveToTail:e=>t.#R(e),indexes:e=>t.#T(e),rindexes:e=>t.#_(e),isStale:e=>t.#y(e)}}get max(){return this.#t}get maxSize(){return this.#s}get calculatedSize(){return this.#f}get size(){return this.#l}get fetchMethod(){return this.#a}get dispose(){return this.#r}get disposeAfter(){return this.#i}constructor(t){let{max:e=0,ttl:i,ttlResolution:n=1,ttlAutopurge:r,updateAgeOnGet:o,updateAgeOnHas:h,allowStale:a,dispose:l,disposeAfter:c,noDisposeOnSet:f,noUpdateTTL:u,maxSize:d=0,maxEntrySize:g=0,sizeCalculation:p,fetchMethod:w,noDeleteOnFetchRejection:m,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:S,allowStaleOnFetchAbort:y,ignoreFetchAbort:E}=t;if(e!==0&&!Q(e))throw new TypeError("max option must be a nonnegative integer");let v=e?$s(e):Array;if(!v)throw new Error("invalid max value: "+e);if(this.#t=e,this.#s=d,this.maxEntrySize=g||this.#s,this.sizeCalculation=p,this.sizeCalculation){if(!this.#s&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(w!==void 0&&typeof w!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#a=w,this.#O=!!w,this.#h=new Map,this.#o=new Array(e).fill(void 0),this.#e=new Array(e).fill(void 0),this.#g=new v(e),this.#w=new v(e),this.#d=0,this.#u=0,this.#S=Ne.create(e),this.#l=0,this.#f=0,typeof l=="function"&&(this.#r=l),typeof c=="function"?(this.#i=c,this.#m=[]):(this.#i=void 0,this.#m=void 0),this.#b=!!this.#r,this.#p=!!this.#i,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!m,this.allowStaleOnFetchRejection=!!S,this.allowStaleOnFetchAbort=!!y,this.ignoreFetchAbort=!!E,this.maxEntrySize!==0){if(this.#s!==0&&!Q(this.#s))throw new TypeError("maxSize must be a positive integer if specified");if(!Q(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#P();}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!h,this.ttlResolution=Q(n)||n===0?n:1,this.ttlAutopurge=!!r,this.ttl=i||0,this.ttl){if(!Q(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#k();}if(this.#t===0&&this.ttl===0&&this.#s===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#s){let z="LRU_CACHE_UNBOUNDED";fr(z)&&(Ws.add(z),Bs("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",z,s));}}getRemainingTTL(t){return this.#h.has(t)?1/0:0}#k(){let t=new ct(this.#t),e=new ct(this.#t);this.#E=t,this.#C=e,this.#n=(r,o,h=lt.now())=>{if(e[r]=o!==0?h:0,t[r]=o,o!==0&&this.ttlAutopurge){let a=setTimeout(()=>{this.#y(r)&&this.delete(this.#o[r]);},o+1);a.unref&&a.unref();}},this.#A=r=>{e[r]=t[r]!==0?lt.now():0;},this.#v=(r,o)=>{if(t[o]){let h=t[o],a=e[o];if(!h||!a)return;r.ttl=h,r.start=a,r.now=i||n();let l=r.now-a;r.remainingTTL=h-l;}};let i=0,n=()=>{let r=lt.now();if(this.ttlResolution>0){i=r;let o=setTimeout(()=>i=0,this.ttlResolution);o.unref&&o.unref();}return r};this.getRemainingTTL=r=>{let o=this.#h.get(r);if(o===void 0)return 0;let h=t[o],a=e[o];if(!h||!a)return 1/0;let l=(i||n())-a;return h-l},this.#y=r=>{let o=e[r],h=t[r];return !!h&&!!o&&(i||n())-o>h};}#A=()=>{};#v=()=>{};#n=()=>{};#y=()=>!1;#P(){let t=new ct(this.#t);this.#f=0,this.#x=t,this.#N=e=>{this.#f-=t[e],t[e]=0;},this.#L=(e,i,n,r)=>{if(this.#c(i))return 0;if(!Q(n))if(r){if(typeof r!="function")throw new TypeError("sizeCalculation must be a function");if(n=r(i,e),!Q(n))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return n},this.#M=(e,i,n)=>{if(t[e]=i,this.#s){let r=this.#s-t[e];for(;this.#f>r;)this.#F(!0);}this.#f+=t[e],n&&(n.entrySize=i,n.totalCalculatedSize=this.#f);};}#N=t=>{};#M=(t,e,i)=>{};#L=(t,e,i,n)=>{if(i||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#T({allowStale:t=this.allowStale}={}){if(this.#l)for(let e=this.#u;!(!this.#j(e)||((t||!this.#y(e))&&(yield e),e===this.#d));)e=this.#w[e];}*#_({allowStale:t=this.allowStale}={}){if(this.#l)for(let e=this.#d;!(!this.#j(e)||((t||!this.#y(e))&&(yield e),e===this.#u));)e=this.#g[e];}#j(t){return t!==void 0&&this.#h.get(this.#o[t])===t}*entries(){for(let t of this.#T())this.#e[t]!==void 0&&this.#o[t]!==void 0&&!this.#c(this.#e[t])&&(yield [this.#o[t],this.#e[t]]);}*rentries(){for(let t of this.#_())this.#e[t]!==void 0&&this.#o[t]!==void 0&&!this.#c(this.#e[t])&&(yield [this.#o[t],this.#e[t]]);}*keys(){for(let t of this.#T()){let e=this.#o[t];e!==void 0&&!this.#c(this.#e[t])&&(yield e);}}*rkeys(){for(let t of this.#_()){let e=this.#o[t];e!==void 0&&!this.#c(this.#e[t])&&(yield e);}}*values(){for(let t of this.#T())this.#e[t]!==void 0&&!this.#c(this.#e[t])&&(yield this.#e[t]);}*rvalues(){for(let t of this.#_())this.#e[t]!==void 0&&!this.#c(this.#e[t])&&(yield this.#e[t]);}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let i of this.#T()){let n=this.#e[i],r=this.#c(n)?n.__staleWhileFetching:n;if(r!==void 0&&t(r,this.#o[i],this))return this.get(this.#o[i],e)}}forEach(t,e=this){for(let i of this.#T()){let n=this.#e[i],r=this.#c(n)?n.__staleWhileFetching:n;r!==void 0&&t.call(e,r,this.#o[i],this);}}rforEach(t,e=this){for(let i of this.#_()){let n=this.#e[i],r=this.#c(n)?n.__staleWhileFetching:n;r!==void 0&&t.call(e,r,this.#o[i],this);}}purgeStale(){let t=!1;for(let e of this.#_({allowStale:!0}))this.#y(e)&&(this.delete(this.#o[e]),t=!0);return t}info(t){let e=this.#h.get(t);if(e===void 0)return;let i=this.#e[e],n=this.#c(i)?i.__staleWhileFetching:i;if(n===void 0)return;let r={value:n};if(this.#E&&this.#C){let o=this.#E[e],h=this.#C[e];if(o&&h){let a=o-(lt.now()-h);r.ttl=a,r.start=Date.now();}}return this.#x&&(r.size=this.#x[e]),r}dump(){let t=[];for(let e of this.#T({allowStale:!0})){let i=this.#o[e],n=this.#e[e],r=this.#c(n)?n.__staleWhileFetching:n;if(r===void 0||i===void 0)continue;let o={value:r};if(this.#E&&this.#C){o.ttl=this.#E[e];let h=lt.now()-this.#C[e];o.start=Math.floor(Date.now()-h);}this.#x&&(o.size=this.#x[e]),t.unshift([i,o]);}return t}load(t){this.clear();for(let[e,i]of t){if(i.start){let n=Date.now()-i.start;i.start=lt.now()-n;}this.set(e,i.value,i);}}set(t,e,i={}){if(e===void 0)return this.delete(t),this;let{ttl:n=this.ttl,start:r,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:h=this.sizeCalculation,status:a}=i,{noUpdateTTL:l=this.noUpdateTTL}=i,c=this.#L(t,e,i.size||0,h);if(this.maxEntrySize&&c>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.delete(t),this;let f=this.#l===0?void 0:this.#h.get(t);if(f===void 0)f=this.#l===0?this.#u:this.#S.length!==0?this.#S.pop():this.#l===this.#t?this.#F(!1):this.#l,this.#o[f]=t,this.#e[f]=e,this.#h.set(t,f),this.#g[this.#u]=f,this.#w[f]=this.#u,this.#u=f,this.#l++,this.#M(f,c,a),a&&(a.set="add"),l=!1;else {this.#R(f);let u=this.#e[f];if(e!==u){if(this.#O&&this.#c(u)){u.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:d}=u;d!==void 0&&!o&&(this.#b&&this.#r?.(d,t,"set"),this.#p&&this.#m?.push([d,t,"set"]));}else o||(this.#b&&this.#r?.(u,t,"set"),this.#p&&this.#m?.push([u,t,"set"]));if(this.#N(f),this.#M(f,c,a),this.#e[f]=e,a){a.set="replace";let d=u&&this.#c(u)?u.__staleWhileFetching:u;d!==void 0&&(a.oldValue=d);}}else a&&(a.set="update");}if(n!==0&&!this.#E&&this.#k(),this.#E&&(l||this.#n(f,n,r),a&&this.#v(a,f)),!o&&this.#p&&this.#m){let u=this.#m,d;for(;d=u?.shift();)this.#i?.(...d);}return this}pop(){try{for(;this.#l;){let t=this.#e[this.#d];if(this.#F(!0),this.#c(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#p&&this.#m){let t=this.#m,e;for(;e=t?.shift();)this.#i?.(...e);}}}#F(t){let e=this.#d,i=this.#o[e],n=this.#e[e];return this.#O&&this.#c(n)?n.__abortController.abort(new Error("evicted")):(this.#b||this.#p)&&(this.#b&&this.#r?.(n,i,"evict"),this.#p&&this.#m?.push([n,i,"evict"])),this.#N(e),t&&(this.#o[e]=void 0,this.#e[e]=void 0,this.#S.push(e)),this.#l===1?(this.#d=this.#u=0,this.#S.length=0):this.#d=this.#g[e],this.#h.delete(i),this.#l--,e}has(t,e={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:n}=e,r=this.#h.get(t);if(r!==void 0){let o=this.#e[r];if(this.#c(o)&&o.__staleWhileFetching===void 0)return !1;if(this.#y(r))n&&(n.has="stale",this.#v(n,r));else return i&&this.#A(r),n&&(n.has="hit",this.#v(n,r)),!0}else n&&(n.has="miss");return !1}peek(t,e={}){let{allowStale:i=this.allowStale}=e,n=this.#h.get(t);if(n===void 0||!i&&this.#y(n))return;let r=this.#e[n];return this.#c(r)?r.__staleWhileFetching:r}#I(t,e,i,n){let r=e===void 0?void 0:this.#e[e];if(this.#c(r))return r;let o=new qt,{signal:h}=i;h?.addEventListener("abort",()=>o.abort(h.reason),{signal:o.signal});let a={signal:o.signal,options:i,context:n},l=(p,w=!1)=>{let{aborted:m}=o.signal,b=i.ignoreFetchAbort&&p!==void 0;if(i.status&&(m&&!w?(i.status.fetchAborted=!0,i.status.fetchError=o.signal.reason,b&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),m&&!b&&!w)return f(o.signal.reason);let S=d;return this.#e[e]===d&&(p===void 0?S.__staleWhileFetching?this.#e[e]=S.__staleWhileFetching:this.delete(t):(i.status&&(i.status.fetchUpdated=!0),this.set(t,p,a.options))),p},c=p=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=p),f(p)),f=p=>{let{aborted:w}=o.signal,m=w&&i.allowStaleOnFetchAbort,b=m||i.allowStaleOnFetchRejection,S=b||i.noDeleteOnFetchRejection,y=d;if(this.#e[e]===d&&(!S||y.__staleWhileFetching===void 0?this.delete(t):m||(this.#e[e]=y.__staleWhileFetching)),b)return i.status&&y.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),y.__staleWhileFetching;if(y.__returned===y)throw p},u=(p,w)=>{let m=this.#a?.(t,r,a);m&&m instanceof Promise&&m.then(b=>p(b===void 0?void 0:b),w),o.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(p(void 0),i.allowStaleOnFetchAbort&&(p=b=>l(b,!0)));});};i.status&&(i.status.fetchDispatched=!0);let d=new Promise(u).then(l,c),g=Object.assign(d,{__abortController:o,__staleWhileFetching:r,__returned:void 0});return e===void 0?(this.set(t,g,{...a.options,status:void 0}),e=this.#h.get(t)):this.#e[e]=g,g}#c(t){if(!this.#O)return !1;let e=t;return !!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof qt}async fetch(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:h=this.noDisposeOnSet,size:a=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:c=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:u=this.allowStaleOnFetchRejection,ignoreFetchAbort:d=this.ignoreFetchAbort,allowStaleOnFetchAbort:g=this.allowStaleOnFetchAbort,context:p,forceRefresh:w=!1,status:m,signal:b}=e;if(!this.#O)return m&&(m.fetch="get"),this.get(t,{allowStale:i,updateAgeOnGet:n,noDeleteOnStaleGet:r,status:m});let S={allowStale:i,updateAgeOnGet:n,noDeleteOnStaleGet:r,ttl:o,noDisposeOnSet:h,size:a,sizeCalculation:l,noUpdateTTL:c,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:g,ignoreFetchAbort:d,status:m,signal:b},y=this.#h.get(t);if(y===void 0){m&&(m.fetch="miss");let E=this.#I(t,y,S,p);return E.__returned=E}else {let E=this.#e[y];if(this.#c(E)){let Bt=i&&E.__staleWhileFetching!==void 0;return m&&(m.fetch="inflight",Bt&&(m.returnedStale=!0)),Bt?E.__staleWhileFetching:E.__returned=E}let v=this.#y(y);if(!w&&!v)return m&&(m.fetch="hit"),this.#R(y),n&&this.#A(y),m&&this.#v(m,y),E;let z=this.#I(t,y,S,p),D=z.__staleWhileFetching!==void 0&&i;return m&&(m.fetch=v?"stale":"refresh",D&&v&&(m.returnedStale=!0)),D?z.__staleWhileFetching:z.__returned=z}}get(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,status:o}=e,h=this.#h.get(t);if(h!==void 0){let a=this.#e[h],l=this.#c(a);return o&&this.#v(o,h),this.#y(h)?(o&&(o.get="stale"),l?(o&&i&&a.__staleWhileFetching!==void 0&&(o.returnedStale=!0),i?a.__staleWhileFetching:void 0):(r||this.delete(t),o&&i&&(o.returnedStale=!0),i?a:void 0)):(o&&(o.get="hit"),l?a.__staleWhileFetching:(this.#R(h),n&&this.#A(h),a))}else o&&(o.get="miss");}#W(t,e){this.#w[e]=t,this.#g[t]=e;}#R(t){t!==this.#u&&(t===this.#d?this.#d=this.#g[t]:this.#W(this.#w[t],this.#g[t]),this.#W(this.#u,t),this.#u=t);}delete(t){let e=!1;if(this.#l!==0){let i=this.#h.get(t);if(i!==void 0)if(e=!0,this.#l===1)this.clear();else {this.#N(i);let n=this.#e[i];if(this.#c(n)?n.__abortController.abort(new Error("deleted")):(this.#b||this.#p)&&(this.#b&&this.#r?.(n,t,"delete"),this.#p&&this.#m?.push([n,t,"delete"])),this.#h.delete(t),this.#o[i]=void 0,this.#e[i]=void 0,i===this.#u)this.#u=this.#w[i];else if(i===this.#d)this.#d=this.#g[i];else {let r=this.#w[i];this.#g[r]=this.#g[i];let o=this.#g[i];this.#w[o]=this.#w[i];}this.#l--,this.#S.push(i);}}if(this.#p&&this.#m?.length){let i=this.#m,n;for(;n=i?.shift();)this.#i?.(...n);}return e}clear(){for(let t of this.#_({allowStale:!0})){let e=this.#e[t];if(this.#c(e))e.__abortController.abort(new Error("deleted"));else {let i=this.#o[t];this.#b&&this.#r?.(e,i,"delete"),this.#p&&this.#m?.push([e,i,"delete"]);}}if(this.#h.clear(),this.#e.fill(void 0),this.#o.fill(void 0),this.#E&&this.#C&&(this.#E.fill(0),this.#C.fill(0)),this.#x&&this.#x.fill(0),this.#d=0,this.#u=0,this.#S.length=0,this.#f=0,this.#l=0,this.#p&&this.#m){let t=this.#m,e;for(;e=t?.shift();)this.#i?.(...e);}}};var zs=typeof process=="object"&&process?process:{stdout:null,stderr:null},dr=s=>!!s&&typeof s=="object"&&(s instanceof et||s instanceof Hs__default.default||pr(s)||gr(s)),pr=s=>!!s&&typeof s=="object"&&s instanceof events.EventEmitter&&typeof s.pipe=="function"&&s.pipe!==Hs__default.default.Writable.prototype.pipe,gr=s=>!!s&&typeof s=="object"&&s instanceof events.EventEmitter&&typeof s.write=="function"&&typeof s.end=="function",Y=Symbol("EOF"),K=Symbol("maybeEmitEnd"),tt=Symbol("emittedEnd"),Xt=Symbol("emittingEnd"),vt=Symbol("emittedError"),Yt=Symbol("closed"),Us=Symbol("read"),Kt=Symbol("flush"),Gs=Symbol("flushChunk"),G=Symbol("encoding"),ft=Symbol("decoder"),A=Symbol("flowing"),Nt=Symbol("paused"),ut=Symbol("resume"),O=Symbol("buffer"),I=Symbol("pipes"),_=Symbol("bufferLength"),Te=Symbol("bufferPush"),Zt=Symbol("bufferShift"),P=Symbol("objectMode"),N=Symbol("destroyed"),xe=Symbol("error"),Ce=Symbol("emitData"),Vs=Symbol("emitEnd"),Ae=Symbol("emitEnd2"),q=Symbol("async"),Oe=Symbol("abort"),Jt=Symbol("aborted"),Tt=Symbol("signal"),it=Symbol("dataListeners"),j=Symbol("discarded"),xt=s=>Promise.resolve().then(s),mr=s=>s(),wr=s=>s==="end"||s==="finish"||s==="prefinish",yr=s=>s instanceof ArrayBuffer||!!s&&typeof s=="object"&&s.constructor&&s.constructor.name==="ArrayBuffer"&&s.byteLength>=0,br=s=>!Buffer.isBuffer(s)&&ArrayBuffer.isView(s),Qt=class{src;dest;opts;ondrain;constructor(t,e,i){this.src=t,this.dest=e,this.opts=i,this.ondrain=()=>t[ut](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},_e=class extends Qt{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(t,e,i){super(t,e,i),this.proxyErrors=n=>e.emit("error",n),t.on("error",this.proxyErrors);}},Sr=s=>!!s.objectMode,Er=s=>!s.objectMode&&!!s.encoding&&s.encoding!=="buffer",et=class extends events.EventEmitter{[A]=!1;[Nt]=!1;[I]=[];[O]=[];[P];[G];[q];[ft];[Y]=!1;[tt]=!1;[Xt]=!1;[Yt]=!1;[vt]=null;[_]=0;[N]=!1;[Tt];[Jt]=!1;[it]=0;[j]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Sr(e)?(this[P]=!0,this[G]=null):Er(e)?(this[G]=e.encoding,this[P]=!1):(this[P]=!1,this[G]=null),this[q]=!!e.async,this[ft]=this[G]?new string_decoder.StringDecoder(this[G]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[O]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[I]});let{signal:i}=e;i&&(this[Tt]=i,i.aborted?this[Oe]():i.addEventListener("abort",()=>this[Oe]()));}get bufferLength(){return this[_]}get encoding(){return this[G]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[P]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[q]}set async(t){this[q]=this[q]||!!t;}[Oe](){this[Jt]=!0,this.emit("abort",this[Tt]?.reason),this.destroy(this[Tt]?.reason);}get aborted(){return this[Jt]}set aborted(t){}write(t,e,i){if(this[Jt])return !1;if(this[Y])throw new Error("write after end");if(this[N])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(i=e,e="utf8"),e||(e="utf8");let n=this[q]?xt:mr;if(!this[P]&&!Buffer.isBuffer(t)){if(br(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(yr(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[P]?(this[A]&&this[_]!==0&&this[Kt](!0),this[A]?this.emit("data",t):this[Te](t),this[_]!==0&&this.emit("readable"),i&&n(i),this[A]):t.length?(typeof t=="string"&&!(e===this[G]&&!this[ft]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[G]&&(t=this[ft].write(t)),this[A]&&this[_]!==0&&this[Kt](!0),this[A]?this.emit("data",t):this[Te](t),this[_]!==0&&this.emit("readable"),i&&n(i),this[A]):(this[_]!==0&&this.emit("readable"),i&&n(i),this[A])}read(t){if(this[N])return null;if(this[j]=!1,this[_]===0||t===0||t&&t>this[_])return this[K](),null;this[P]&&(t=null),this[O].length>1&&!this[P]&&(this[O]=[this[G]?this[O].join(""):Buffer.concat(this[O],this[_])]);let e=this[Us](t||null,this[O][0]);return this[K](),e}[Us](t,e){if(this[P])this[Zt]();else {let i=e;t===i.length||t===null?this[Zt]():typeof i=="string"?(this[O][0]=i.slice(t),e=i.slice(0,t),this[_]-=t):(this[O][0]=i.subarray(t),e=i.subarray(0,t),this[_]-=t);}return this.emit("data",e),!this[O].length&&!this[Y]&&this.emit("drain"),e}end(t,e,i){return typeof t=="function"&&(i=t,t=void 0),typeof e=="function"&&(i=e,e="utf8"),t!==void 0&&this.write(t,e),i&&this.once("end",i),this[Y]=!0,this.writable=!1,(this[A]||!this[Nt])&&this[K](),this}[ut](){this[N]||(!this[it]&&!this[I].length&&(this[j]=!0),this[Nt]=!1,this[A]=!0,this.emit("resume"),this[O].length?this[Kt]():this[Y]?this[K]():this.emit("drain"));}resume(){return this[ut]()}pause(){this[A]=!1,this[Nt]=!0,this[j]=!1;}get destroyed(){return this[N]}get flowing(){return this[A]}get paused(){return this[Nt]}[Te](t){this[P]?this[_]+=1:this[_]+=t.length,this[O].push(t);}[Zt](){return this[P]?this[_]-=1:this[_]-=this[O][0].length,this[O].shift()}[Kt](t=!1){do;while(this[Gs](this[Zt]())&&this[O].length);!t&&!this[O].length&&!this[Y]&&this.emit("drain");}[Gs](t){return this.emit("data",t),this[A]}pipe(t,e){if(this[N])return t;this[j]=!1;let i=this[tt];return e=e||{},t===zs.stdout||t===zs.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,i?e.end&&t.end():(this[I].push(e.proxyErrors?new _e(this,t,e):new Qt(this,t,e)),this[q]?xt(()=>this[ut]()):this[ut]()),t}unpipe(t){let e=this[I].find(i=>i.dest===t);e&&(this[I].length===1?(this[A]&&this[it]===0&&(this[A]=!1),this[I]=[]):this[I].splice(this[I].indexOf(e),1),e.unpipe());}addListener(t,e){return this.on(t,e)}on(t,e){let i=super.on(t,e);if(t==="data")this[j]=!1,this[it]++,!this[I].length&&!this[A]&&this[ut]();else if(t==="readable"&&this[_]!==0)super.emit("readable");else if(wr(t)&&this[tt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[vt]){let n=e;this[q]?xt(()=>n.call(this,this[vt])):n.call(this,this[vt]);}return i}removeListener(t,e){return this.off(t,e)}off(t,e){let i=super.off(t,e);return t==="data"&&(this[it]=this.listeners("data").length,this[it]===0&&!this[j]&&!this[I].length&&(this[A]=!1)),i}removeAllListeners(t){let e=super.removeAllListeners(t);return (t==="data"||t===void 0)&&(this[it]=0,!this[j]&&!this[I].length&&(this[A]=!1)),e}get emittedEnd(){return this[tt]}[K](){!this[Xt]&&!this[tt]&&!this[N]&&this[O].length===0&&this[Y]&&(this[Xt]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Yt]&&this.emit("close"),this[Xt]=!1);}emit(t,...e){let i=e[0];if(t!=="error"&&t!=="close"&&t!==N&&this[N])return !1;if(t==="data")return !this[P]&&!i?!1:this[q]?(xt(()=>this[Ce](i)),!0):this[Ce](i);if(t==="end")return this[Vs]();if(t==="close"){if(this[Yt]=!0,!this[tt]&&!this[N])return !1;let r=super.emit("close");return this.removeAllListeners("close"),r}else if(t==="error"){this[vt]=i,super.emit(xe,i);let r=!this[Tt]||this.listeners("error").length?super.emit("error",i):!1;return this[K](),r}else if(t==="resume"){let r=super.emit("resume");return this[K](),r}else if(t==="finish"||t==="prefinish"){let r=super.emit(t);return this.removeAllListeners(t),r}let n=super.emit(t,...e);return this[K](),n}[Ce](t){for(let i of this[I])i.dest.write(t)===!1&&this.pause();let e=this[j]?!1:super.emit("data",t);return this[K](),e}[Vs](){return this[tt]?!1:(this[tt]=!0,this.readable=!1,this[q]?(xt(()=>this[Ae]()),!0):this[Ae]())}[Ae](){if(this[ft]){let e=this[ft].end();if(e){for(let i of this[I])i.dest.write(e);this[j]||super.emit("data",e);}}for(let e of this[I])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[P]||(t.dataLength=0);let e=this.promise();return this.on("data",i=>{t.push(i),this[P]||(t.dataLength+=i.length);}),await e,t}async concat(){if(this[P])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[G]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(N,()=>e(new Error("stream destroyed"))),this.on("error",i=>e(i)),this.on("end",()=>t());})}[Symbol.asyncIterator](){this[j]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return {next:()=>{if(t)return e();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[Y])return e();let r,o,h=f=>{this.off("data",a),this.off("end",l),this.off(N,c),e(),o(f);},a=f=>{this.off("error",h),this.off("end",l),this.off(N,c),this.pause(),r({value:f,done:!!this[Y]});},l=()=>{this.off("error",h),this.off("data",a),this.off(N,c),e(),r({done:!0,value:void 0});},c=()=>h(new Error("stream destroyed"));return new Promise((f,u)=>{o=u,r=f,this.once(N,c),this.once("error",h),this.once("end",l),this.once("data",a);})},throw:e,return:e,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[j]=!1;let t=!1,e=()=>(this.pause(),this.off(xe,e),this.off(N,e),this.off("end",e),t=!0,{done:!0,value:void 0}),i=()=>{if(t)return e();let n=this.read();return n===null?e():{done:!1,value:n}};return this.once("end",e),this.once(xe,e),this.once(N,e),{next:i,throw:e,return:e,[Symbol.iterator](){return this}}}destroy(t){if(this[N])return t?this.emit("error",t):this.emit(N),this;this[N]=!0,this[j]=!0,this[O].length=0,this[_]=0;let e=this;return typeof e.close=="function"&&!this[Yt]&&e.close(),t?this.emit("error",t):this.emit(N),this}static get isStream(){return dr}};var kr=li.realpathSync.native,At={lstatSync:li.lstatSync,readdir:li.readdir,readdirSync:li.readdirSync,readlinkSync:li.readlinkSync,realpathSync:kr,promises:{lstat:promises.lstat,readdir:promises.readdir,readlink:promises.readlink,realpath:promises.realpath}},Ks=s=>!s||s===At||s===li__namespace?At:{...At,...s,promises:{...At.promises,...s.promises||{}}},Zs=/^\\\\\?\\([a-z]:)\\?$/i,Mr=s=>s.replace(/\//g,"\\").replace(Zs,"$1\\"),Lr=/[\\\/]/,$=0,Js=1,Qs=2,X=4,ti=6,ei=8,nt=10,si=12,B=15,Ct=~B,Pe=16,Ds=32,Ot=64,V=128,te=256,se=512,qs=Ot|V|se,jr=1023,Fe=s=>s.isFile()?ei:s.isDirectory()?X:s.isSymbolicLink()?nt:s.isCharacterDevice()?Qs:s.isBlockDevice()?ti:s.isSocket()?si:s.isFIFO()?Js:$,Xs=new Map,_t=s=>{let t=Xs.get(s);if(t)return t;let e=s.normalize("NFKD");return Xs.set(s,e),e},Ys=new Map,ee=s=>{let t=Ys.get(s);if(t)return t;let e=_t(s.toLowerCase());return Ys.set(s,e),e},ie=class extends Et{constructor(){super({max:256});}},Ie=class extends Et{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1});}},ii=Symbol("PathScurry setAsCwd"),F=class{name;root;roots;parent;nocase;#t;#s;get dev(){return this.#s}#r;get mode(){return this.#r}#i;get nlink(){return this.#i}#a;get uid(){return this.#a}#l;get gid(){return this.#l}#f;get rdev(){return this.#f}#h;get blksize(){return this.#h}#o;get ino(){return this.#o}#e;get size(){return this.#e}#g;get blocks(){return this.#g}#w;get atimeMs(){return this.#w}#d;get mtimeMs(){return this.#d}#u;get ctimeMs(){return this.#u}#S;get birthtimeMs(){return this.#S}#m;get atime(){return this.#m}#x;get mtime(){return this.#x}#C;get ctime(){return this.#C}#E;get birthtime(){return this.#E}#b;#O;#p;#k;#A;#v;#n;#y;#P;#N;get path(){return (this.parent||this).fullpath()}constructor(t,e=$,i,n,r,o,h){this.name=t,this.#b=r?ee(t):_t(t),this.#n=e&jr,this.nocase=r,this.roots=n,this.root=i||this,this.#y=o,this.#p=h.fullpath,this.#A=h.relative,this.#v=h.relativePosix,this.parent=h.parent,this.parent?this.#t=this.parent.#t:this.#t=Ks(h.fs);}depth(){return this.#O!==void 0?this.#O:this.parent?this.#O=this.parent.depth()+1:this.#O=0}childrenCache(){return this.#y}resolve(t){if(!t)return this;let e=this.getRootString(t),n=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#M(n):this.#M(n)}#M(t){let e=this;for(let i of t)e=e.child(i);return e}children(){let t=this.#y.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#y.set(this,e),this.#n&=~Pe,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let i=this.children(),n=this.nocase?ee(t):_t(t);for(let a of i)if(a.#b===n)return a;let r=this.parent?this.sep:"",o=this.#p?this.#p+r+t:void 0,h=this.newChild(t,$,{...e,parent:this,fullpath:o});return this.canReaddir()||(h.#n|=V),i.push(h),h}relative(){if(this.#A!==void 0)return this.#A;let t=this.name,e=this.parent;if(!e)return this.#A=this.name;let i=e.relative();return i+(!i||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.#v!==void 0)return this.#v;let t=this.name,e=this.parent;if(!e)return this.#v=this.fullpathPosix();let i=e.relativePosix();return i+(!i||!e.parent?"":"/")+t}fullpath(){if(this.#p!==void 0)return this.#p;let t=this.name,e=this.parent;if(!e)return this.#p=this.name;let n=e.fullpath()+(e.parent?this.sep:"")+t;return this.#p=n}fullpathPosix(){if(this.#k!==void 0)return this.#k;if(this.sep==="/")return this.#k=this.fullpath();if(!this.parent){let n=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(n)?this.#k=`//?/${n}`:this.#k=n}let t=this.parent,e=t.fullpathPosix(),i=e+(!e||!t.parent?"":"/")+this.name;return this.#k=i}isUnknown(){return (this.#n&B)===$}isType(t){return this[`is${t}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return (this.#n&B)===ei}isDirectory(){return (this.#n&B)===X}isCharacterDevice(){return (this.#n&B)===Qs}isBlockDevice(){return (this.#n&B)===ti}isFIFO(){return (this.#n&B)===Js}isSocket(){return (this.#n&B)===si}isSymbolicLink(){return (this.#n&nt)===nt}lstatCached(){return this.#n&Ds?this:void 0}readlinkCached(){return this.#P}realpathCached(){return this.#N}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#P)return !0;if(!this.parent)return !1;let t=this.#n&B;return !(t!==$&&t!==nt||this.#n&te||this.#n&V)}calledReaddir(){return !!(this.#n&Pe)}isENOENT(){return !!(this.#n&V)}isNamed(t){return this.nocase?this.#b===ee(t):this.#b===_t(t)}async readlink(){let t=this.#P;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#t.promises.readlink(this.fullpath()),i=this.parent.resolve(e);if(i)return this.#P=i}catch(e){this.#W(e.code);return}}readlinkSync(){let t=this.#P;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#t.readlinkSync(this.fullpath()),i=this.parent.resolve(e);if(i)return this.#P=i}catch(e){this.#W(e.code);return}}#L(t){this.#n|=Pe;for(let e=t.provisional;ei(null,t));}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let i=this.children();if(this.calledReaddir()){let r=i.slice(0,i.provisional);e?t(null,r):queueMicrotask(()=>t(null,r));return}if(this.#$.push(t),this.#z)return;this.#z=!0;let n=this.fullpath();this.#t.readdir(n,{withFileTypes:!0},(r,o)=>{if(r)this.#I(r.code),i.provisional=0;else {for(let h of o)this.#R(h,i);this.#L(i);}this.#D(i.slice(0,i.provisional));});}#B;async readdir(){if(!this.canReaddir())return [];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#B)await this.#B;else {let i=()=>{};this.#B=new Promise(n=>i=n);try{for(let n of await this.#t.promises.readdir(e,{withFileTypes:!0}))this.#R(n,t);this.#L(t);}catch(n){this.#I(n.code),t.provisional=0;}this.#B=void 0,i();}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return [];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let i of this.#t.readdirSync(e,{withFileTypes:!0}))this.#R(i,t);this.#L(t);}catch(i){this.#I(i.code),t.provisional=0;}return t.slice(0,t.provisional)}canReaddir(){if(this.#n&qs)return !1;let t=B&this.#n;return t===$||t===X||t===nt}shouldWalk(t,e){return (this.#n&X)===X&&!(this.#n&qs)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#N)return this.#N;if(!((se|te|V)&this.#n))try{let t=await this.#t.promises.realpath(this.fullpath());return this.#N=this.resolve(t)}catch{this.#j();}}realpathSync(){if(this.#N)return this.#N;if(!((se|te|V)&this.#n))try{let t=this.#t.realpathSync(this.fullpath());return this.#N=this.resolve(t)}catch{this.#j();}}[ii](t){if(t===this)return;let e=new Set([]),i=[],n=this;for(;n&&n.parent;)e.add(n),n.#A=i.join(this.sep),n.#v=i.join("/"),n=n.parent,i.push("..");for(n=t;n&&n.parent&&!e.has(n);)n.#A=void 0,n.#v=void 0,n=n.parent;}},ne=class s extends F{sep="\\";splitSep=Lr;constructor(t,e=$,i,n,r,o,h){super(t,e,i,n,r,o,h);}newChild(t,e=$,i={}){return new s(t,e,this.root,this.roots,this.nocase,this.childrenCache(),i)}getRootString(t){return qe.win32.parse(t).root}getRoot(t){if(t=Mr(t.toUpperCase()),t===this.root.name)return this.root;for(let[e,i]of Object.entries(this.roots))if(this.sameRoot(t,e))return this.roots[t]=i;return this.roots[t]=new dt(t,this).root}sameRoot(t,e=this.root.name){return t=t.toUpperCase().replace(/\//g,"\\").replace(Zs,"$1\\"),t===e}},re=class s extends F{splitSep="/";sep="/";constructor(t,e=$,i,n,r,o,h){super(t,e,i,n,r,o,h);}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,e=$,i={}){return new s(t,e,this.root,this.roots,this.nocase,this.childrenCache(),i)}},oe=class{root;rootPath;roots;cwd;#t;#s;#r;nocase;#i;constructor(t=process.cwd(),e,i,{nocase:n,childrenCacheSize:r=16*1024,fs:o=At}={}){this.#i=Ks(o),(t instanceof URL||t.startsWith("file://"))&&(t=url.fileURLToPath(t));let h=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(h),this.#t=new ie,this.#s=new ie,this.#r=new Ie(r);let a=h.substring(this.rootPath.length).split(i);if(a.length===1&&!a[0]&&a.pop(),n===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=n,this.root=this.newRoot(this.#i),this.roots[this.rootPath]=this.root;let l=this.root,c=a.length-1,f=e.sep,u=this.rootPath,d=!1;for(let g of a){let p=c--;l=l.child(g,{relative:new Array(p).fill("..").join(f),relativePosix:new Array(p).fill("..").join("/"),fullpath:u+=(d?"":f)+g}),d=!0;}this.cwd=l;}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#r}resolve(...t){let e="";for(let r=t.length-1;r>=0;r--){let o=t[r];if(!(!o||o===".")&&(e=e?`${o}/${e}`:o,this.isAbsolute(o)))break}let i=this.#t.get(e);if(i!==void 0)return i;let n=this.cwd.resolve(e).fullpath();return this.#t.set(e,n),n}resolvePosix(...t){let e="";for(let r=t.length-1;r>=0;r--){let o=t[r];if(!(!o||o===".")&&(e=e?`${o}/${e}`:o,this.isAbsolute(o)))break}let i=this.#s.get(e);if(i!==void 0)return i;let n=this.cwd.resolve(e).fullpathPosix();return this.#s.set(e,n),n}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t,t=this.cwd);let{withFileTypes:i}=e;if(t.canReaddir()){let n=await t.readdir();return i?n:n.map(r=>r.name)}else return []}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t,t=this.cwd);let{withFileTypes:i=!0}=e;return t.canReaddir()?i?t.readdirSync():t.readdirSync().map(n=>n.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t.withFileTypes,t=this.cwd);let i=await t.readlink();return e?i:i?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t.withFileTypes,t=this.cwd);let i=t.readlinkSync();return e?i:i?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t.withFileTypes,t=this.cwd);let i=await t.realpath();return e?i:i?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t.withFileTypes,t=this.cwd);let i=t.realpathSync();return e?i:i?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t,t=this.cwd);let{withFileTypes:i=!0,follow:n=!1,filter:r,walkFilter:o}=e,h=[];(!r||r(t))&&h.push(i?t:t.fullpath());let a=new Set,l=(f,u)=>{a.add(f),f.readdirCB((d,g)=>{if(d)return u(d);let p=g.length;if(!p)return u();let w=()=>{--p===0&&u();};for(let m of g)(!r||r(m))&&h.push(i?m:m.fullpath()),n&&m.isSymbolicLink()?m.realpath().then(b=>b?.isUnknown()?b.lstat():b).then(b=>b?.shouldWalk(a,o)?l(b,w):w()):m.shouldWalk(a,o)?l(m,w):w();},!0);},c=t;return new Promise((f,u)=>{l(c,d=>{if(d)return u(d);f(h);});})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t,t=this.cwd);let{withFileTypes:i=!0,follow:n=!1,filter:r,walkFilter:o}=e,h=[];(!r||r(t))&&h.push(i?t:t.fullpath());let a=new Set([t]);for(let l of a){let c=l.readdirSync();for(let f of c){(!r||r(f))&&h.push(i?f:f.fullpath());let u=f;if(f.isSymbolicLink()){if(!(n&&(u=f.realpathSync())))continue;u.isUnknown()&&u.lstatSync();}u.shouldWalk(a,o)&&a.add(u);}}return h}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t,t=this.cwd);let{withFileTypes:i=!0,follow:n=!1,filter:r,walkFilter:o}=e;(!r||r(t))&&(yield i?t:t.fullpath());let h=new Set([t]);for(let a of h){let l=a.readdirSync();for(let c of l){(!r||r(c))&&(yield i?c:c.fullpath());let f=c;if(c.isSymbolicLink()){if(!(n&&(f=c.realpathSync())))continue;f.isUnknown()&&f.lstatSync();}f.shouldWalk(h,o)&&h.add(f);}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t,t=this.cwd);let{withFileTypes:i=!0,follow:n=!1,filter:r,walkFilter:o}=e,h=new et({objectMode:!0});(!r||r(t))&&h.write(i?t:t.fullpath());let a=new Set,l=[t],c=0,f=()=>{let u=!1;for(;!u;){let d=l.shift();if(!d){c===0&&h.end();return}c++,a.add(d);let g=(w,m,b=!1)=>{if(w)return h.emit("error",w);if(n&&!b){let S=[];for(let y of m)y.isSymbolicLink()&&S.push(y.realpath().then(E=>E?.isUnknown()?E.lstat():E));if(S.length){Promise.all(S).then(()=>g(null,m,!0));return}}for(let S of m)S&&(!r||r(S))&&(h.write(i?S:S.fullpath())||(u=!0));c--;for(let S of m){let y=S.realpathCached()||S;y.shouldWalk(a,o)&&l.push(y);}u&&!h.flowing?h.once("drain",f):p||f();},p=!0;d.readdirCB(g,!0),p=!1;}};return f(),h}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t,t=this.cwd);let{withFileTypes:i=!0,follow:n=!1,filter:r,walkFilter:o}=e,h=new et({objectMode:!0}),a=new Set;(!r||r(t))&&h.write(i?t:t.fullpath());let l=[t],c=0,f=()=>{let u=!1;for(;!u;){let d=l.shift();if(!d){c===0&&h.end();return}c++,a.add(d);let g=d.readdirSync();for(let p of g)(!r||r(p))&&(h.write(i?p:p.fullpath())||(u=!0));c--;for(let p of g){let w=p;if(p.isSymbolicLink()){if(!(n&&(w=p.realpathSync())))continue;w.isUnknown()&&w.lstatSync();}w.shouldWalk(a,o)&&l.push(w);}}u&&!h.flowing&&h.once("drain",f);};return f(),h}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[ii](e);}},dt=class extends oe{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:i=!0}=e;super(t,qe.win32,"\\",{...e,nocase:i}),this.nocase=i;for(let n=this.cwd;n;n=n.parent)n.nocase=this.nocase;}parseRootPath(t){return qe.win32.parse(t).root.toUpperCase()}newRoot(t){return new ne(this.rootPath,X,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},pt=class extends oe{sep="/";constructor(t=process.cwd(),e={}){let{nocase:i=!1}=e;super(t,qe.posix,"/",{...e,nocase:i}),this.nocase=i;}parseRootPath(t){return "/"}newRoot(t){return new re(this.rootPath,X,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},kt=class extends pt{constructor(t=process.cwd(),e={}){let{nocase:i=!0}=e;super(t,{...e,nocase:i});}};process.platform==="win32"?ne:re;var ni=process.platform==="win32"?dt:process.platform==="darwin"?kt:pt;var Wr=s=>s.length>=1,Br=s=>s.length>=1,gt=class s{#t;#s;#r;length;#i;#a;#l;#f;#h;#o;#e=!0;constructor(t,e,i,n){if(!Wr(t))throw new TypeError("empty pattern list");if(!Br(e))throw new TypeError("empty glob list");if(e.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,i<0||i>=this.length)throw new TypeError("index out of range");if(this.#t=t,this.#s=e,this.#r=i,this.#i=n,this.#r===0){if(this.isUNC()){let[r,o,h,a,...l]=this.#t,[c,f,u,d,...g]=this.#s;l[0]===""&&(l.shift(),g.shift());let p=[r,o,h,a,""].join("/"),w=[c,f,u,d,""].join("/");this.#t=[p,...l],this.#s=[w,...g],this.length=this.#t.length;}else if(this.isDrive()||this.isAbsolute()){let[r,...o]=this.#t,[h,...a]=this.#s;o[0]===""&&(o.shift(),a.shift());let l=r+"/",c=h+"/";this.#t=[l,...o],this.#s=[c,...a],this.length=this.#t.length;}}}pattern(){return this.#t[this.#r]}isString(){return typeof this.#t[this.#r]=="string"}isGlobstar(){return this.#t[this.#r]===k}isRegExp(){return this.#t[this.#r]instanceof RegExp}globString(){return this.#l=this.#l||(this.#r===0?this.isAbsolute()?this.#s[0]+this.#s.slice(1).join("/"):this.#s.join("/"):this.#s.slice(this.#r).join("/"))}hasMore(){return this.length>this.#r+1}rest(){return this.#a!==void 0?this.#a:this.hasMore()?(this.#a=new s(this.#t,this.#s,this.#r+1,this.#i),this.#a.#o=this.#o,this.#a.#h=this.#h,this.#a.#f=this.#f,this.#a):this.#a=null}isUNC(){let t=this.#t;return this.#h!==void 0?this.#h:this.#h=this.#i==="win32"&&this.#r===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3]}isDrive(){let t=this.#t;return this.#f!==void 0?this.#f:this.#f=this.#i==="win32"&&this.#r===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0])}isAbsolute(){let t=this.#t;return this.#o!==void 0?this.#o:this.#o=t[0]===""&&t.length>1||this.isDrive()||this.isUNC()}root(){let t=this.#t[0];return typeof t=="string"&&this.isAbsolute()&&this.#r===0?t:""}checkFollowGlobstar(){return !(this.#r===0||!this.isGlobstar()||!this.#e)}markFollowGlobstar(){return this.#r===0||!this.isGlobstar()||!this.#e?!1:(this.#e=!1,!0)}};var $r=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Pt=class{relative;relativeChildren;absolute;absoluteChildren;constructor(t,{nobrace:e,nocase:i,noext:n,noglobstar:r,platform:o=$r}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[];let h={dot:!0,nobrace:e,nocase:i,noext:n,noglobstar:r,optimizationLevel:2,platform:o,nocomment:!0,nonegate:!0};for(let a of t){let l=new L(a,h);for(let c=0;c[t,!!(e&2),!!(e&1)])}},je=class{store=new Map;add(t,e){if(!t.canReaddir())return;let i=this.store.get(t);i?i.find(n=>n.globString()===e.globString())||i.push(e):this.store.set(t,[e]);}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return [...this.store.keys()].filter(t=>t.canReaddir())}},Ft=class s{hasWalkedCache;matches=new Le;subwalks=new je;patterns;follow;dot;opts;constructor(t,e){this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=e?e.copy():new Me;}processPatterns(t,e){this.patterns=e;let i=e.map(n=>[t,n]);for(let[n,r]of i){this.hasWalkedCache.storeWalked(n,r);let o=r.root(),h=r.isAbsolute()&&this.opts.absolute!==!1;if(o){n=n.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let f=r.rest();if(f)r=f;else {this.matches.add(n,!0,!1);continue}}if(n.isENOENT())continue;let a,l,c=!1;for(;typeof(a=r.pattern())=="string"&&(l=r.rest());)n=n.resolve(a),r=l,c=!0;if(a=r.pattern(),l=r.rest(),c){if(this.hasWalkedCache.hasWalked(n,r))continue;this.hasWalkedCache.storeWalked(n,r);}if(typeof a=="string"){let f=a===".."||a===""||a===".";this.matches.add(n.resolve(a),h,f);continue}else if(a===k){(!n.isSymbolicLink()||this.follow||r.checkFollowGlobstar())&&this.subwalks.add(n,r);let f=l?.pattern(),u=l?.rest();if(!l||(f===""||f===".")&&!u)this.matches.add(n,h,f===""||f===".");else if(f===".."){let d=n.parent||n;u?this.hasWalkedCache.hasWalked(d,u)||this.subwalks.add(d,u):this.matches.add(d,h,!0);}}else a instanceof RegExp&&this.subwalks.add(n,r);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new s(this.opts,this.hasWalkedCache)}filterEntries(t,e){let i=this.subwalks.get(t),n=this.child();for(let r of e)for(let o of i){let h=o.isAbsolute(),a=o.pattern(),l=o.rest();a===k?n.testGlobstar(r,o,l,h):a instanceof RegExp?n.testRegExp(r,a,l,h):n.testString(r,a,l,h);}return n}testGlobstar(t,e,i,n){if((this.dot||!t.name.startsWith("."))&&(e.hasMore()||this.matches.add(t,n,!1),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,e):t.isSymbolicLink()&&(i&&e.checkFollowGlobstar()?this.subwalks.add(t,i):e.markFollowGlobstar()&&this.subwalks.add(t,e)))),i){let r=i.pattern();if(typeof r=="string"&&r!==".."&&r!==""&&r!==".")this.testString(t,r,i.rest(),n);else if(r===".."){let o=t.parent||t;this.subwalks.add(o,i);}else r instanceof RegExp&&this.testRegExp(t,r,i.rest(),n);}}testRegExp(t,e,i,n){e.test(t.name)&&(i?this.subwalks.add(t,i):this.matches.add(t,n,!1));}testString(t,e,i,n){t.isNamed(e)&&(i?this.subwalks.add(t,i):this.matches.add(t,n,!1));}};var zr=(s,t)=>typeof s=="string"?new Pt([s],t):Array.isArray(s)?new Pt(s,t):s,ae=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#t=[];#s;#r;signal;maxDepth;constructor(t,e,i){this.patterns=t,this.path=e,this.opts=i,this.#r=!i.posix&&i.platform==="win32"?"\\":"/",i.ignore&&(this.#s=zr(i.ignore,i)),this.maxDepth=i.maxDepth||1/0,i.signal&&(this.signal=i.signal,this.signal.addEventListener("abort",()=>{this.#t.length=0;}));}#i(t){return this.seen.has(t)||!!this.#s?.ignored?.(t)}#a(t){return !!this.#s?.childrenIgnored?.(t)}pause(){this.paused=!0;}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#t.shift());)t();}onResume(t){this.signal?.aborted||(this.paused?this.#t.push(t):t());}async matchCheck(t,e){if(e&&this.opts.nodir)return;let i;if(this.opts.realpath){if(i=t.realpathCached()||await t.realpath(),!i)return;t=i;}let n=t.isUnknown()||this.opts.stat;return this.matchCheckTest(n?await t.lstat():t,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&!this.#i(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let i;if(this.opts.realpath){if(i=t.realpathCached()||t.realpathSync(),!i)return;t=i;}let n=t.isUnknown()||this.opts.stat;return this.matchCheckTest(n?t.lstatSync():t,e)}matchFinish(t,e){if(this.#i(t))return;let i=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let n=this.opts.mark&&t.isDirectory()?this.#r:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(i){let r=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(r+n);}else {let r=this.opts.posix?t.relativePosix():t.relative(),o=this.opts.dotRelative&&!r.startsWith(".."+this.#r)?"."+this.#r:"";this.matchEmit(r?o+r+n:"."+n);}}async match(t,e,i){let n=await this.matchCheck(t,i);n&&this.matchFinish(n,e);}matchSync(t,e,i){let n=this.matchCheckSync(t,i);n&&this.matchFinish(n,e);}walkCB(t,e,i){this.signal?.aborted&&i(),this.walkCB2(t,e,new Ft(this.opts),i);}walkCB2(t,e,i,n){if(this.#a(t))return n();if(this.signal?.aborted&&n(),this.paused){this.onResume(()=>this.walkCB2(t,e,i,n));return}i.processPatterns(t,e);let r=1,o=()=>{--r===0&&n();};for(let[h,a,l]of i.matches.entries())this.#i(h)||(r++,this.match(h,a,l).then(()=>o()));for(let h of i.subwalkTargets()){if(this.maxDepth!==1/0&&h.depth()>=this.maxDepth)continue;r++;let a=h.readdirCached();h.calledReaddir()?this.walkCB3(h,a,i,o):h.readdirCB((l,c)=>this.walkCB3(h,c,i,o),!0);}o();}walkCB3(t,e,i,n){i=i.filterEntries(t,e);let r=1,o=()=>{--r===0&&n();};for(let[h,a,l]of i.matches.entries())this.#i(h)||(r++,this.match(h,a,l).then(()=>o()));for(let[h,a]of i.subwalks.entries())r++,this.walkCB2(h,a,i.child(),o);o();}walkCBSync(t,e,i){this.signal?.aborted&&i(),this.walkCB2Sync(t,e,new Ft(this.opts),i);}walkCB2Sync(t,e,i,n){if(this.#a(t))return n();if(this.signal?.aborted&&n(),this.paused){this.onResume(()=>this.walkCB2Sync(t,e,i,n));return}i.processPatterns(t,e);let r=1,o=()=>{--r===0&&n();};for(let[h,a,l]of i.matches.entries())this.#i(h)||this.matchSync(h,a,l);for(let h of i.subwalkTargets()){if(this.maxDepth!==1/0&&h.depth()>=this.maxDepth)continue;r++;let a=h.readdirSync();this.walkCB3Sync(h,a,i,o);}o();}walkCB3Sync(t,e,i,n){i=i.filterEntries(t,e);let r=1,o=()=>{--r===0&&n();};for(let[h,a,l]of i.matches.entries())this.#i(h)||this.matchSync(h,a,l);for(let[h,a]of i.subwalks.entries())r++,this.walkCB2Sync(h,a,i.child(),o);o();}},Rt=class extends ae{matches;constructor(t,e,i){super(t,e,i),this.matches=new Set;}matchEmit(t){this.matches.add(t);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches);});}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},It=class extends ae{results;constructor(t,e,i){super(t,e,i),this.results=new et({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume());}matchEmit(t){this.results.write(t),this.results.flowing||this.pause();}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end());}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};var Gr=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",H=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;opts;patterns;constructor(t,e){if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=url.fileURLToPath(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof t=="string"&&(t=[t]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(t=t.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");t=t.map(a=>a.includes("/")?a:`./**/${a}`);}if(this.pattern=t,this.platform=e.platform||Gr,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else {let a=e.platform==="win32"?dt:e.platform==="darwin"?kt:e.platform?pt:ni;this.scurry=new a(this.cwd,{nocase:e.nocase,fs:e.fs});}this.nocase=this.scurry.nocase;let i=this.platform==="darwin"||this.platform==="win32",n={...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:i,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},r=this.pattern.map(a=>new L(a,n)),[o,h]=r.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=o.map((a,l)=>{let c=h[l];if(!c)throw new Error("invalid pattern object");return new gt(a,c,0,this.platform)});}async walk(){return [...await new Rt(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase}).walk()]}walkSync(){return [...new Rt(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase}).walkSync()]}stream(){return new It(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase}).stream()}streamSync(){return new It(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};var We=(s,t={})=>{Array.isArray(s)||(s=[s]);for(let e of s)if(new L(e,t).hasMagic())return !0;return !1};function le(s,t={}){return new H(s,t).streamSync()}function oi(s,t={}){return new H(s,t).stream()}function ai(s,t={}){return new H(s,t).walkSync()}async function ri(s,t={}){return new H(s,t).walk()}function ce(s,t={}){return new H(s,t).iterateSync()}function hi(s,t={}){return new H(s,t).iterate()}var Vr=le,Hr=Object.assign(oi,{sync:le}),Dr=ce,qr=Object.assign(hi,{sync:ce}),Xr=Object.assign(ai,{stream:le,iterate:ce}),he=Object.assign(ri,{glob:ri,globSync:ai,sync:Xr,globStream:oi,stream:Hr,globStreamSync:le,streamSync:Vr,globIterate:hi,iterate:qr,globIterateSync:ce,iterateSync:Dr,Glob:H,hasMagic:We,escape:ht,unescape:U});he.glob=he;var fi=(s,t)=>{let e={dirs:[],files:[]};return s.map(i=>qe.join(t,i)).forEach(i=>{(0, ci.default)(i)?e.files.push(...he.sync(i,{dot:!0,absolute:!0})):li__namespace.default.existsSync(i)?(li__namespace.default.lstatSync(i).isDirectory()?e.dirs:e.files).push(i):nodeLogger.logger.warn(T` +>>> no match, partial?`,t,u,e,d),u===a))}let p;if(typeof c=="string"?(p=f===c,this.debug("string match",c,f,p)):(p=c.test(f),this.debug("pattern match",c,f,p)),!p)return !1}if(o===a&&h===l)return !0;if(o===a)return i;if(h===l)return o===a-1&&t[o]==="";throw new Error("wtf?")}braceExpand(){return Rs(this.pattern,this.options)}parse(t){bt(t);let e=this.options;if(t==="**")return P;if(t==="")return "";let i,n=null;(i=t.match(Un))?n=e.dot?Vn:Gn:(i=t.match(Fn))?n=(e.nocase?e.dot?Ln:Mn:e.dot?In:Rn)(i[1]):(i=t.match(Hn))?n=(e.nocase?e.dot?qn:Dn:e.dot?Xn:Yn)(i):(i=t.match(Wn))?n=e.dot?Bn:jn:(i=t.match($n))&&(n=zn);let r=at.fromGlob(t,this.options).toMMPattern();return n?Object.assign(r,{test:n}):r}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let e=this.options,i=e.noglobstar?Jn:e.dot?Qn:tr,n=new Set(e.nocase?["i"]:[]),r=t.map(a=>{let l=a.map(c=>{if(c instanceof RegExp)for(let f of c.flags.split(""))n.add(f);return typeof c=="string"?rr(c):c===P?P:c._src});return l.forEach((c,f)=>{let u=l[f+1],d=l[f-1];c!==P||d===P||(d===void 0?u!==void 0&&u!==P?l[f+1]="(?:\\/|"+i+"\\/)?"+u:l[f]=i:u===void 0?l[f-1]=d+"(?:\\/|"+i+")?":u!==P&&(l[f-1]=d+"(?:\\/|\\/"+i+"\\/)"+u,l[f+1]=P));}),l.filter(c=>c!==P).join("/")}).join("|"),[o,h]=t.length>1?["(?:",")"]:["",""];r="^"+o+r+h+"$",this.negate&&(r="^(?!"+r+").+$");try{this.regexp=new RegExp(r,[...n].join(""));}catch{this.regexp=!1;}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,e=this.partial){if(this.debug("match",t,this.pattern),this.comment)return !1;if(this.empty)return t==="";if(t==="/"&&e)return !0;let i=this.options;this.isWindows&&(t=t.split("\\").join("/"));let n=this.slashSplit(t);this.debug(this.pattern,"split",n);let r=this.set;this.debug(this.pattern,"set",r);let o=n[n.length-1];if(!o)for(let h=n.length-2;!o&&h>=0;h--)o=n[h];for(let h=0;h{typeof Ne.emitWarning=="function"?Ne.emitWarning(s,t,e,i):console.error(`[${e}] ${t}: ${s}`);},Dt=globalThis.AbortController,Is=globalThis.AbortSignal;if(typeof Dt>"u"){Is=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(i,n){this._onabort.push(n);}},Dt=class{constructor(){t();}signal=new Is;abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=!0;for(let n of this.signal._onabort)n(i);this.signal.onabort?.(i);}}};let s=Ne.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{s&&(s=!1,Ls("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t));};}var or=s=>!Ms.has(s),Q=s=>s&&s===Math.floor(s)&&s>0&&isFinite(s),Ws=s=>Q(s)?s<=Math.pow(2,8)?Uint8Array:s<=Math.pow(2,16)?Uint16Array:s<=Math.pow(2,32)?Uint32Array:s<=Number.MAX_SAFE_INTEGER?ct:null:null,ct=class extends Array{constructor(t){super(t),this.fill(0);}},xe=class s{heap;length;static#t=!1;static create(t){let e=Ws(t);if(!e)return [];s.#t=!0;let i=new s(t,e);return s.#t=!1,i}constructor(t,e){if(!s.#t)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0;}push(t){this.heap[this.length++]=t;}pop(){return this.heap[--this.length]}},St=class s{#t;#s;#r;#i;#a;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#l;#f;#h;#o;#e;#g;#w;#d;#u;#E;#m;#T;#C;#S;#b;#O;#p;static unsafeExposeInternals(t){return {starts:t.#C,ttls:t.#S,sizes:t.#T,keyMap:t.#h,keyList:t.#o,valList:t.#e,next:t.#g,prev:t.#w,get head(){return t.#d},get tail(){return t.#u},free:t.#E,isBackgroundFetch:e=>t.#c(e),backgroundFetch:(e,i,n,r)=>t.#I(e,i,n,r),moveToTail:e=>t.#R(e),indexes:e=>t.#x(e),rindexes:e=>t.#_(e),isStale:e=>t.#y(e)}}get max(){return this.#t}get maxSize(){return this.#s}get calculatedSize(){return this.#f}get size(){return this.#l}get fetchMethod(){return this.#a}get dispose(){return this.#r}get disposeAfter(){return this.#i}constructor(t){let{max:e=0,ttl:i,ttlResolution:n=1,ttlAutopurge:r,updateAgeOnGet:o,updateAgeOnHas:h,allowStale:a,dispose:l,disposeAfter:c,noDisposeOnSet:f,noUpdateTTL:u,maxSize:d=0,maxEntrySize:g=0,sizeCalculation:p,fetchMethod:w,noDeleteOnFetchRejection:m,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:y,ignoreFetchAbort:S}=t;if(e!==0&&!Q(e))throw new TypeError("max option must be a nonnegative integer");let v=e?Ws(e):Array;if(!v)throw new Error("invalid max value: "+e);if(this.#t=e,this.#s=d,this.maxEntrySize=g||this.#s,this.sizeCalculation=p,this.sizeCalculation){if(!this.#s&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(w!==void 0&&typeof w!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#a=w,this.#O=!!w,this.#h=new Map,this.#o=new Array(e).fill(void 0),this.#e=new Array(e).fill(void 0),this.#g=new v(e),this.#w=new v(e),this.#d=0,this.#u=0,this.#E=xe.create(e),this.#l=0,this.#f=0,typeof l=="function"&&(this.#r=l),typeof c=="function"?(this.#i=c,this.#m=[]):(this.#i=void 0,this.#m=void 0),this.#b=!!this.#r,this.#p=!!this.#i,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!m,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!y,this.ignoreFetchAbort=!!S,this.maxEntrySize!==0){if(this.#s!==0&&!Q(this.#s))throw new TypeError("maxSize must be a positive integer if specified");if(!Q(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#k();}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!h,this.ttlResolution=Q(n)||n===0?n:1,this.ttlAutopurge=!!r,this.ttl=i||0,this.ttl){if(!Q(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P();}if(this.#t===0&&this.ttl===0&&this.#s===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#s){let z="LRU_CACHE_UNBOUNDED";or(z)&&(Ms.add(z),Ls("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",z,s));}}getRemainingTTL(t){return this.#h.has(t)?1/0:0}#P(){let t=new ct(this.#t),e=new ct(this.#t);this.#S=t,this.#C=e,this.#n=(r,o,h=lt.now())=>{if(e[r]=o!==0?h:0,t[r]=o,o!==0&&this.ttlAutopurge){let a=setTimeout(()=>{this.#y(r)&&this.delete(this.#o[r]);},o+1);a.unref&&a.unref();}},this.#A=r=>{e[r]=t[r]!==0?lt.now():0;},this.#v=(r,o)=>{if(t[o]){let h=t[o],a=e[o];if(!h||!a)return;r.ttl=h,r.start=a,r.now=i||n();let l=r.now-a;r.remainingTTL=h-l;}};let i=0,n=()=>{let r=lt.now();if(this.ttlResolution>0){i=r;let o=setTimeout(()=>i=0,this.ttlResolution);o.unref&&o.unref();}return r};this.getRemainingTTL=r=>{let o=this.#h.get(r);if(o===void 0)return 0;let h=t[o],a=e[o];if(!h||!a)return 1/0;let l=(i||n())-a;return h-l},this.#y=r=>{let o=e[r],h=t[r];return !!h&&!!o&&(i||n())-o>h};}#A=()=>{};#v=()=>{};#n=()=>{};#y=()=>!1;#k(){let t=new ct(this.#t);this.#f=0,this.#T=t,this.#N=e=>{this.#f-=t[e],t[e]=0;},this.#L=(e,i,n,r)=>{if(this.#c(i))return 0;if(!Q(n))if(r){if(typeof r!="function")throw new TypeError("sizeCalculation must be a function");if(n=r(i,e),!Q(n))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return n},this.#M=(e,i,n)=>{if(t[e]=i,this.#s){let r=this.#s-t[e];for(;this.#f>r;)this.#F(!0);}this.#f+=t[e],n&&(n.entrySize=i,n.totalCalculatedSize=this.#f);};}#N=t=>{};#M=(t,e,i)=>{};#L=(t,e,i,n)=>{if(i||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#x({allowStale:t=this.allowStale}={}){if(this.#l)for(let e=this.#u;!(!this.#W(e)||((t||!this.#y(e))&&(yield e),e===this.#d));)e=this.#w[e];}*#_({allowStale:t=this.allowStale}={}){if(this.#l)for(let e=this.#d;!(!this.#W(e)||((t||!this.#y(e))&&(yield e),e===this.#u));)e=this.#g[e];}#W(t){return t!==void 0&&this.#h.get(this.#o[t])===t}*entries(){for(let t of this.#x())this.#e[t]!==void 0&&this.#o[t]!==void 0&&!this.#c(this.#e[t])&&(yield [this.#o[t],this.#e[t]]);}*rentries(){for(let t of this.#_())this.#e[t]!==void 0&&this.#o[t]!==void 0&&!this.#c(this.#e[t])&&(yield [this.#o[t],this.#e[t]]);}*keys(){for(let t of this.#x()){let e=this.#o[t];e!==void 0&&!this.#c(this.#e[t])&&(yield e);}}*rkeys(){for(let t of this.#_()){let e=this.#o[t];e!==void 0&&!this.#c(this.#e[t])&&(yield e);}}*values(){for(let t of this.#x())this.#e[t]!==void 0&&!this.#c(this.#e[t])&&(yield this.#e[t]);}*rvalues(){for(let t of this.#_())this.#e[t]!==void 0&&!this.#c(this.#e[t])&&(yield this.#e[t]);}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let i of this.#x()){let n=this.#e[i],r=this.#c(n)?n.__staleWhileFetching:n;if(r!==void 0&&t(r,this.#o[i],this))return this.get(this.#o[i],e)}}forEach(t,e=this){for(let i of this.#x()){let n=this.#e[i],r=this.#c(n)?n.__staleWhileFetching:n;r!==void 0&&t.call(e,r,this.#o[i],this);}}rforEach(t,e=this){for(let i of this.#_()){let n=this.#e[i],r=this.#c(n)?n.__staleWhileFetching:n;r!==void 0&&t.call(e,r,this.#o[i],this);}}purgeStale(){let t=!1;for(let e of this.#_({allowStale:!0}))this.#y(e)&&(this.delete(this.#o[e]),t=!0);return t}info(t){let e=this.#h.get(t);if(e===void 0)return;let i=this.#e[e],n=this.#c(i)?i.__staleWhileFetching:i;if(n===void 0)return;let r={value:n};if(this.#S&&this.#C){let o=this.#S[e],h=this.#C[e];if(o&&h){let a=o-(lt.now()-h);r.ttl=a,r.start=Date.now();}}return this.#T&&(r.size=this.#T[e]),r}dump(){let t=[];for(let e of this.#x({allowStale:!0})){let i=this.#o[e],n=this.#e[e],r=this.#c(n)?n.__staleWhileFetching:n;if(r===void 0||i===void 0)continue;let o={value:r};if(this.#S&&this.#C){o.ttl=this.#S[e];let h=lt.now()-this.#C[e];o.start=Math.floor(Date.now()-h);}this.#T&&(o.size=this.#T[e]),t.unshift([i,o]);}return t}load(t){this.clear();for(let[e,i]of t){if(i.start){let n=Date.now()-i.start;i.start=lt.now()-n;}this.set(e,i.value,i);}}set(t,e,i={}){if(e===void 0)return this.delete(t),this;let{ttl:n=this.ttl,start:r,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:h=this.sizeCalculation,status:a}=i,{noUpdateTTL:l=this.noUpdateTTL}=i,c=this.#L(t,e,i.size||0,h);if(this.maxEntrySize&&c>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.delete(t),this;let f=this.#l===0?void 0:this.#h.get(t);if(f===void 0)f=this.#l===0?this.#u:this.#E.length!==0?this.#E.pop():this.#l===this.#t?this.#F(!1):this.#l,this.#o[f]=t,this.#e[f]=e,this.#h.set(t,f),this.#g[this.#u]=f,this.#w[f]=this.#u,this.#u=f,this.#l++,this.#M(f,c,a),a&&(a.set="add"),l=!1;else {this.#R(f);let u=this.#e[f];if(e!==u){if(this.#O&&this.#c(u)){u.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:d}=u;d!==void 0&&!o&&(this.#b&&this.#r?.(d,t,"set"),this.#p&&this.#m?.push([d,t,"set"]));}else o||(this.#b&&this.#r?.(u,t,"set"),this.#p&&this.#m?.push([u,t,"set"]));if(this.#N(f),this.#M(f,c,a),this.#e[f]=e,a){a.set="replace";let d=u&&this.#c(u)?u.__staleWhileFetching:u;d!==void 0&&(a.oldValue=d);}}else a&&(a.set="update");}if(n!==0&&!this.#S&&this.#P(),this.#S&&(l||this.#n(f,n,r),a&&this.#v(a,f)),!o&&this.#p&&this.#m){let u=this.#m,d;for(;d=u?.shift();)this.#i?.(...d);}return this}pop(){try{for(;this.#l;){let t=this.#e[this.#d];if(this.#F(!0),this.#c(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#p&&this.#m){let t=this.#m,e;for(;e=t?.shift();)this.#i?.(...e);}}}#F(t){let e=this.#d,i=this.#o[e],n=this.#e[e];return this.#O&&this.#c(n)?n.__abortController.abort(new Error("evicted")):(this.#b||this.#p)&&(this.#b&&this.#r?.(n,i,"evict"),this.#p&&this.#m?.push([n,i,"evict"])),this.#N(e),t&&(this.#o[e]=void 0,this.#e[e]=void 0,this.#E.push(e)),this.#l===1?(this.#d=this.#u=0,this.#E.length=0):this.#d=this.#g[e],this.#h.delete(i),this.#l--,e}has(t,e={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:n}=e,r=this.#h.get(t);if(r!==void 0){let o=this.#e[r];if(this.#c(o)&&o.__staleWhileFetching===void 0)return !1;if(this.#y(r))n&&(n.has="stale",this.#v(n,r));else return i&&this.#A(r),n&&(n.has="hit",this.#v(n,r)),!0}else n&&(n.has="miss");return !1}peek(t,e={}){let{allowStale:i=this.allowStale}=e,n=this.#h.get(t);if(n===void 0||!i&&this.#y(n))return;let r=this.#e[n];return this.#c(r)?r.__staleWhileFetching:r}#I(t,e,i,n){let r=e===void 0?void 0:this.#e[e];if(this.#c(r))return r;let o=new Dt,{signal:h}=i;h?.addEventListener("abort",()=>o.abort(h.reason),{signal:o.signal});let a={signal:o.signal,options:i,context:n},l=(p,w=!1)=>{let{aborted:m}=o.signal,b=i.ignoreFetchAbort&&p!==void 0;if(i.status&&(m&&!w?(i.status.fetchAborted=!0,i.status.fetchError=o.signal.reason,b&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),m&&!b&&!w)return f(o.signal.reason);let E=d;return this.#e[e]===d&&(p===void 0?E.__staleWhileFetching?this.#e[e]=E.__staleWhileFetching:this.delete(t):(i.status&&(i.status.fetchUpdated=!0),this.set(t,p,a.options))),p},c=p=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=p),f(p)),f=p=>{let{aborted:w}=o.signal,m=w&&i.allowStaleOnFetchAbort,b=m||i.allowStaleOnFetchRejection,E=b||i.noDeleteOnFetchRejection,y=d;if(this.#e[e]===d&&(!E||y.__staleWhileFetching===void 0?this.delete(t):m||(this.#e[e]=y.__staleWhileFetching)),b)return i.status&&y.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),y.__staleWhileFetching;if(y.__returned===y)throw p},u=(p,w)=>{let m=this.#a?.(t,r,a);m&&m instanceof Promise&&m.then(b=>p(b===void 0?void 0:b),w),o.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(p(void 0),i.allowStaleOnFetchAbort&&(p=b=>l(b,!0)));});};i.status&&(i.status.fetchDispatched=!0);let d=new Promise(u).then(l,c),g=Object.assign(d,{__abortController:o,__staleWhileFetching:r,__returned:void 0});return e===void 0?(this.set(t,g,{...a.options,status:void 0}),e=this.#h.get(t)):this.#e[e]=g,g}#c(t){if(!this.#O)return !1;let e=t;return !!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof Dt}async fetch(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:h=this.noDisposeOnSet,size:a=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:c=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:u=this.allowStaleOnFetchRejection,ignoreFetchAbort:d=this.ignoreFetchAbort,allowStaleOnFetchAbort:g=this.allowStaleOnFetchAbort,context:p,forceRefresh:w=!1,status:m,signal:b}=e;if(!this.#O)return m&&(m.fetch="get"),this.get(t,{allowStale:i,updateAgeOnGet:n,noDeleteOnStaleGet:r,status:m});let E={allowStale:i,updateAgeOnGet:n,noDeleteOnStaleGet:r,ttl:o,noDisposeOnSet:h,size:a,sizeCalculation:l,noUpdateTTL:c,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:g,ignoreFetchAbort:d,status:m,signal:b},y=this.#h.get(t);if(y===void 0){m&&(m.fetch="miss");let S=this.#I(t,y,E,p);return S.__returned=S}else {let S=this.#e[y];if(this.#c(S)){let Bt=i&&S.__staleWhileFetching!==void 0;return m&&(m.fetch="inflight",Bt&&(m.returnedStale=!0)),Bt?S.__staleWhileFetching:S.__returned=S}let v=this.#y(y);if(!w&&!v)return m&&(m.fetch="hit"),this.#R(y),n&&this.#A(y),m&&this.#v(m,y),S;let z=this.#I(t,y,E,p),D=z.__staleWhileFetching!==void 0&&i;return m&&(m.fetch=v?"stale":"refresh",D&&v&&(m.returnedStale=!0)),D?z.__staleWhileFetching:z.__returned=z}}get(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,status:o}=e,h=this.#h.get(t);if(h!==void 0){let a=this.#e[h],l=this.#c(a);return o&&this.#v(o,h),this.#y(h)?(o&&(o.get="stale"),l?(o&&i&&a.__staleWhileFetching!==void 0&&(o.returnedStale=!0),i?a.__staleWhileFetching:void 0):(r||this.delete(t),o&&i&&(o.returnedStale=!0),i?a:void 0)):(o&&(o.get="hit"),l?a.__staleWhileFetching:(this.#R(h),n&&this.#A(h),a))}else o&&(o.get="miss");}#j(t,e){this.#w[e]=t,this.#g[t]=e;}#R(t){t!==this.#u&&(t===this.#d?this.#d=this.#g[t]:this.#j(this.#w[t],this.#g[t]),this.#j(this.#u,t),this.#u=t);}delete(t){let e=!1;if(this.#l!==0){let i=this.#h.get(t);if(i!==void 0)if(e=!0,this.#l===1)this.clear();else {this.#N(i);let n=this.#e[i];if(this.#c(n)?n.__abortController.abort(new Error("deleted")):(this.#b||this.#p)&&(this.#b&&this.#r?.(n,t,"delete"),this.#p&&this.#m?.push([n,t,"delete"])),this.#h.delete(t),this.#o[i]=void 0,this.#e[i]=void 0,i===this.#u)this.#u=this.#w[i];else if(i===this.#d)this.#d=this.#g[i];else {let r=this.#w[i];this.#g[r]=this.#g[i];let o=this.#g[i];this.#w[o]=this.#w[i];}this.#l--,this.#E.push(i);}}if(this.#p&&this.#m?.length){let i=this.#m,n;for(;n=i?.shift();)this.#i?.(...n);}return e}clear(){for(let t of this.#_({allowStale:!0})){let e=this.#e[t];if(this.#c(e))e.__abortController.abort(new Error("deleted"));else {let i=this.#o[t];this.#b&&this.#r?.(e,i,"delete"),this.#p&&this.#m?.push([e,i,"delete"]);}}if(this.#h.clear(),this.#e.fill(void 0),this.#o.fill(void 0),this.#S&&this.#C&&(this.#S.fill(0),this.#C.fill(0)),this.#T&&this.#T.fill(0),this.#d=0,this.#u=0,this.#E.length=0,this.#f=0,this.#l=0,this.#p&&this.#m){let t=this.#m,e;for(;e=t?.shift();)this.#i?.(...e);}}};var js=typeof process=="object"&&process?process:{stdout:null,stderr:null},hr=s=>!!s&&typeof s=="object"&&(s instanceof et||s instanceof Us__default.default||lr(s)||cr(s)),lr=s=>!!s&&typeof s=="object"&&s instanceof events.EventEmitter&&typeof s.pipe=="function"&&s.pipe!==Us__default.default.Writable.prototype.pipe,cr=s=>!!s&&typeof s=="object"&&s instanceof events.EventEmitter&&typeof s.write=="function"&&typeof s.end=="function",Y=Symbol("EOF"),K=Symbol("maybeEmitEnd"),tt=Symbol("emittedEnd"),qt=Symbol("emittingEnd"),vt=Symbol("emittedError"),Xt=Symbol("closed"),Bs=Symbol("read"),Yt=Symbol("flush"),$s=Symbol("flushChunk"),G=Symbol("encoding"),ft=Symbol("decoder"),C=Symbol("flowing"),Nt=Symbol("paused"),ut=Symbol("resume"),A=Symbol("buffer"),I=Symbol("pipes"),O=Symbol("bufferLength"),Te=Symbol("bufferPush"),Kt=Symbol("bufferShift"),k=Symbol("objectMode"),N=Symbol("destroyed"),Ce=Symbol("error"),Ae=Symbol("emitData"),zs=Symbol("emitEnd"),Oe=Symbol("emitEnd2"),q=Symbol("async"),_e=Symbol("abort"),Zt=Symbol("aborted"),xt=Symbol("signal"),it=Symbol("dataListeners"),W=Symbol("discarded"),Tt=s=>Promise.resolve().then(s),fr=s=>s(),ur=s=>s==="end"||s==="finish"||s==="prefinish",dr=s=>s instanceof ArrayBuffer||!!s&&typeof s=="object"&&s.constructor&&s.constructor.name==="ArrayBuffer"&&s.byteLength>=0,pr=s=>!Buffer.isBuffer(s)&&ArrayBuffer.isView(s),Jt=class{src;dest;opts;ondrain;constructor(t,e,i){this.src=t,this.dest=e,this.opts=i,this.ondrain=()=>t[ut](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},Pe=class extends Jt{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(t,e,i){super(t,e,i),this.proxyErrors=n=>e.emit("error",n),t.on("error",this.proxyErrors);}},gr=s=>!!s.objectMode,mr=s=>!s.objectMode&&!!s.encoding&&s.encoding!=="buffer",et=class extends events.EventEmitter{[C]=!1;[Nt]=!1;[I]=[];[A]=[];[k];[G];[q];[ft];[Y]=!1;[tt]=!1;[qt]=!1;[Xt]=!1;[vt]=null;[O]=0;[N]=!1;[xt];[Zt]=!1;[it]=0;[W]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");gr(e)?(this[k]=!0,this[G]=null):mr(e)?(this[G]=e.encoding,this[k]=!1):(this[k]=!1,this[G]=null),this[q]=!!e.async,this[ft]=this[G]?new string_decoder.StringDecoder(this[G]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[A]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[I]});let{signal:i}=e;i&&(this[xt]=i,i.aborted?this[_e]():i.addEventListener("abort",()=>this[_e]()));}get bufferLength(){return this[O]}get encoding(){return this[G]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[k]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[q]}set async(t){this[q]=this[q]||!!t;}[_e](){this[Zt]=!0,this.emit("abort",this[xt]?.reason),this.destroy(this[xt]?.reason);}get aborted(){return this[Zt]}set aborted(t){}write(t,e,i){if(this[Zt])return !1;if(this[Y])throw new Error("write after end");if(this[N])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(i=e,e="utf8"),e||(e="utf8");let n=this[q]?Tt:fr;if(!this[k]&&!Buffer.isBuffer(t)){if(pr(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(dr(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[k]?(this[C]&&this[O]!==0&&this[Yt](!0),this[C]?this.emit("data",t):this[Te](t),this[O]!==0&&this.emit("readable"),i&&n(i),this[C]):t.length?(typeof t=="string"&&!(e===this[G]&&!this[ft]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[G]&&(t=this[ft].write(t)),this[C]&&this[O]!==0&&this[Yt](!0),this[C]?this.emit("data",t):this[Te](t),this[O]!==0&&this.emit("readable"),i&&n(i),this[C]):(this[O]!==0&&this.emit("readable"),i&&n(i),this[C])}read(t){if(this[N])return null;if(this[W]=!1,this[O]===0||t===0||t&&t>this[O])return this[K](),null;this[k]&&(t=null),this[A].length>1&&!this[k]&&(this[A]=[this[G]?this[A].join(""):Buffer.concat(this[A],this[O])]);let e=this[Bs](t||null,this[A][0]);return this[K](),e}[Bs](t,e){if(this[k])this[Kt]();else {let i=e;t===i.length||t===null?this[Kt]():typeof i=="string"?(this[A][0]=i.slice(t),e=i.slice(0,t),this[O]-=t):(this[A][0]=i.subarray(t),e=i.subarray(0,t),this[O]-=t);}return this.emit("data",e),!this[A].length&&!this[Y]&&this.emit("drain"),e}end(t,e,i){return typeof t=="function"&&(i=t,t=void 0),typeof e=="function"&&(i=e,e="utf8"),t!==void 0&&this.write(t,e),i&&this.once("end",i),this[Y]=!0,this.writable=!1,(this[C]||!this[Nt])&&this[K](),this}[ut](){this[N]||(!this[it]&&!this[I].length&&(this[W]=!0),this[Nt]=!1,this[C]=!0,this.emit("resume"),this[A].length?this[Yt]():this[Y]?this[K]():this.emit("drain"));}resume(){return this[ut]()}pause(){this[C]=!1,this[Nt]=!0,this[W]=!1;}get destroyed(){return this[N]}get flowing(){return this[C]}get paused(){return this[Nt]}[Te](t){this[k]?this[O]+=1:this[O]+=t.length,this[A].push(t);}[Kt](){return this[k]?this[O]-=1:this[O]-=this[A][0].length,this[A].shift()}[Yt](t=!1){do;while(this[$s](this[Kt]())&&this[A].length);!t&&!this[A].length&&!this[Y]&&this.emit("drain");}[$s](t){return this.emit("data",t),this[C]}pipe(t,e){if(this[N])return t;this[W]=!1;let i=this[tt];return e=e||{},t===js.stdout||t===js.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,i?e.end&&t.end():(this[I].push(e.proxyErrors?new Pe(this,t,e):new Jt(this,t,e)),this[q]?Tt(()=>this[ut]()):this[ut]()),t}unpipe(t){let e=this[I].find(i=>i.dest===t);e&&(this[I].length===1?(this[C]&&this[it]===0&&(this[C]=!1),this[I]=[]):this[I].splice(this[I].indexOf(e),1),e.unpipe());}addListener(t,e){return this.on(t,e)}on(t,e){let i=super.on(t,e);if(t==="data")this[W]=!1,this[it]++,!this[I].length&&!this[C]&&this[ut]();else if(t==="readable"&&this[O]!==0)super.emit("readable");else if(ur(t)&&this[tt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[vt]){let n=e;this[q]?Tt(()=>n.call(this,this[vt])):n.call(this,this[vt]);}return i}removeListener(t,e){return this.off(t,e)}off(t,e){let i=super.off(t,e);return t==="data"&&(this[it]=this.listeners("data").length,this[it]===0&&!this[W]&&!this[I].length&&(this[C]=!1)),i}removeAllListeners(t){let e=super.removeAllListeners(t);return (t==="data"||t===void 0)&&(this[it]=0,!this[W]&&!this[I].length&&(this[C]=!1)),e}get emittedEnd(){return this[tt]}[K](){!this[qt]&&!this[tt]&&!this[N]&&this[A].length===0&&this[Y]&&(this[qt]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Xt]&&this.emit("close"),this[qt]=!1);}emit(t,...e){let i=e[0];if(t!=="error"&&t!=="close"&&t!==N&&this[N])return !1;if(t==="data")return !this[k]&&!i?!1:this[q]?(Tt(()=>this[Ae](i)),!0):this[Ae](i);if(t==="end")return this[zs]();if(t==="close"){if(this[Xt]=!0,!this[tt]&&!this[N])return !1;let r=super.emit("close");return this.removeAllListeners("close"),r}else if(t==="error"){this[vt]=i,super.emit(Ce,i);let r=!this[xt]||this.listeners("error").length?super.emit("error",i):!1;return this[K](),r}else if(t==="resume"){let r=super.emit("resume");return this[K](),r}else if(t==="finish"||t==="prefinish"){let r=super.emit(t);return this.removeAllListeners(t),r}let n=super.emit(t,...e);return this[K](),n}[Ae](t){for(let i of this[I])i.dest.write(t)===!1&&this.pause();let e=this[W]?!1:super.emit("data",t);return this[K](),e}[zs](){return this[tt]?!1:(this[tt]=!0,this.readable=!1,this[q]?(Tt(()=>this[Oe]()),!0):this[Oe]())}[Oe](){if(this[ft]){let e=this[ft].end();if(e){for(let i of this[I])i.dest.write(e);this[W]||super.emit("data",e);}}for(let e of this[I])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[k]||(t.dataLength=0);let e=this.promise();return this.on("data",i=>{t.push(i),this[k]||(t.dataLength+=i.length);}),await e,t}async concat(){if(this[k])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[G]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(N,()=>e(new Error("stream destroyed"))),this.on("error",i=>e(i)),this.on("end",()=>t());})}[Symbol.asyncIterator](){this[W]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return {next:()=>{if(t)return e();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[Y])return e();let r,o,h=f=>{this.off("data",a),this.off("end",l),this.off(N,c),e(),o(f);},a=f=>{this.off("error",h),this.off("end",l),this.off(N,c),this.pause(),r({value:f,done:!!this[Y]});},l=()=>{this.off("error",h),this.off("data",a),this.off(N,c),e(),r({done:!0,value:void 0});},c=()=>h(new Error("stream destroyed"));return new Promise((f,u)=>{o=u,r=f,this.once(N,c),this.once("error",h),this.once("end",l),this.once("data",a);})},throw:e,return:e,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[W]=!1;let t=!1,e=()=>(this.pause(),this.off(Ce,e),this.off(N,e),this.off("end",e),t=!0,{done:!0,value:void 0}),i=()=>{if(t)return e();let n=this.read();return n===null?e():{done:!1,value:n}};return this.once("end",e),this.once(Ce,e),this.once(N,e),{next:i,throw:e,return:e,[Symbol.iterator](){return this}}}destroy(t){if(this[N])return t?this.emit("error",t):this.emit(N),this;this[N]=!0,this[W]=!0,this[A].length=0,this[O]=0;let e=this;return typeof e.close=="function"&&!this[Xt]&&e.close(),t?this.emit("error",t):this.emit(N),this}static get isStream(){return hr}};var Tr=ce.realpathSync.native,At={lstatSync:ce.lstatSync,readdir:ce.readdir,readdirSync:ce.readdirSync,readlinkSync:ce.readlinkSync,realpathSync:Tr,promises:{lstat:promises.lstat,readdir:promises.readdir,readlink:promises.readlink,realpath:promises.realpath}},qs=s=>!s||s===At||s===ce__namespace?At:{...At,...s,promises:{...At.promises,...s.promises||{}}},Xs=/^\\\\\?\\([a-z]:)\\?$/i,Pr=s=>s.replace(/\//g,"\\").replace(Xs,"$1\\"),kr=/[\\\/]/,$=0,Ys=1,Ks=2,X=4,Zs=6,Js=8,nt=10,Qs=12,B=15,Ct=~B,Fe=16,Gs=32,Ot=64,V=128,Qt=256,ee=512,Vs=Ot|V|ee,Fr=1023,Re=s=>s.isFile()?Js:s.isDirectory()?X:s.isSymbolicLink()?nt:s.isCharacterDevice()?Ks:s.isBlockDevice()?Zs:s.isSocket()?Qs:s.isFIFO()?Ys:$,Hs=new Map,_t=s=>{let t=Hs.get(s);if(t)return t;let e=s.normalize("NFKD");return Hs.set(s,e),e},Ds=new Map,te=s=>{let t=Ds.get(s);if(t)return t;let e=_t(s.toLowerCase());return Ds.set(s,e),e},se=class extends St{constructor(){super({max:256});}},Me=class extends St{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1});}},ti=Symbol("PathScurry setAsCwd"),F=class{name;root;roots;parent;nocase;#t;#s;get dev(){return this.#s}#r;get mode(){return this.#r}#i;get nlink(){return this.#i}#a;get uid(){return this.#a}#l;get gid(){return this.#l}#f;get rdev(){return this.#f}#h;get blksize(){return this.#h}#o;get ino(){return this.#o}#e;get size(){return this.#e}#g;get blocks(){return this.#g}#w;get atimeMs(){return this.#w}#d;get mtimeMs(){return this.#d}#u;get ctimeMs(){return this.#u}#E;get birthtimeMs(){return this.#E}#m;get atime(){return this.#m}#T;get mtime(){return this.#T}#C;get ctime(){return this.#C}#S;get birthtime(){return this.#S}#b;#O;#p;#P;#A;#v;#n;#y;#k;#N;get path(){return (this.parent||this).fullpath()}constructor(t,e=$,i,n,r,o,h){this.name=t,this.#b=r?te(t):_t(t),this.#n=e&Fr,this.nocase=r,this.roots=n,this.root=i||this,this.#y=o,this.#p=h.fullpath,this.#A=h.relative,this.#v=h.relativePosix,this.parent=h.parent,this.parent?this.#t=this.parent.#t:this.#t=qs(h.fs);}depth(){return this.#O!==void 0?this.#O:this.parent?this.#O=this.parent.depth()+1:this.#O=0}childrenCache(){return this.#y}resolve(t){if(!t)return this;let e=this.getRootString(t),n=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#M(n):this.#M(n)}#M(t){let e=this;for(let i of t)e=e.child(i);return e}children(){let t=this.#y.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#y.set(this,e),this.#n&=~Fe,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let i=this.children(),n=this.nocase?te(t):_t(t);for(let a of i)if(a.#b===n)return a;let r=this.parent?this.sep:"",o=this.#p?this.#p+r+t:void 0,h=this.newChild(t,$,{...e,parent:this,fullpath:o});return this.canReaddir()||(h.#n|=V),i.push(h),h}relative(){if(this.#A!==void 0)return this.#A;let t=this.name,e=this.parent;if(!e)return this.#A=this.name;let i=e.relative();return i+(!i||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.#v!==void 0)return this.#v;let t=this.name,e=this.parent;if(!e)return this.#v=this.fullpathPosix();let i=e.relativePosix();return i+(!i||!e.parent?"":"/")+t}fullpath(){if(this.#p!==void 0)return this.#p;let t=this.name,e=this.parent;if(!e)return this.#p=this.name;let n=e.fullpath()+(e.parent?this.sep:"")+t;return this.#p=n}fullpathPosix(){if(this.#P!==void 0)return this.#P;if(this.sep==="/")return this.#P=this.fullpath();if(!this.parent){let n=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(n)?this.#P=`//?/${n}`:this.#P=n}let t=this.parent,e=t.fullpathPosix(),i=e+(!e||!t.parent?"":"/")+this.name;return this.#P=i}isUnknown(){return (this.#n&B)===$}isType(t){return this[`is${t}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return (this.#n&B)===Js}isDirectory(){return (this.#n&B)===X}isCharacterDevice(){return (this.#n&B)===Ks}isBlockDevice(){return (this.#n&B)===Zs}isFIFO(){return (this.#n&B)===Ys}isSocket(){return (this.#n&B)===Qs}isSymbolicLink(){return (this.#n&nt)===nt}lstatCached(){return this.#n&Gs?this:void 0}readlinkCached(){return this.#k}realpathCached(){return this.#N}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#k)return !0;if(!this.parent)return !1;let t=this.#n&B;return !(t!==$&&t!==nt||this.#n&Qt||this.#n&V)}calledReaddir(){return !!(this.#n&Fe)}isENOENT(){return !!(this.#n&V)}isNamed(t){return this.nocase?this.#b===te(t):this.#b===_t(t)}async readlink(){let t=this.#k;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#t.promises.readlink(this.fullpath()),i=this.parent.resolve(e);if(i)return this.#k=i}catch(e){this.#j(e.code);return}}readlinkSync(){let t=this.#k;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#t.readlinkSync(this.fullpath()),i=this.parent.resolve(e);if(i)return this.#k=i}catch(e){this.#j(e.code);return}}#L(t){this.#n|=Fe;for(let e=t.provisional;ei(null,t));}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let i=this.children();if(this.calledReaddir()){let r=i.slice(0,i.provisional);e?t(null,r):queueMicrotask(()=>t(null,r));return}if(this.#$.push(t),this.#z)return;this.#z=!0;let n=this.fullpath();this.#t.readdir(n,{withFileTypes:!0},(r,o)=>{if(r)this.#I(r.code),i.provisional=0;else {for(let h of o)this.#R(h,i);this.#L(i);}this.#D(i.slice(0,i.provisional));});}#B;async readdir(){if(!this.canReaddir())return [];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#B)await this.#B;else {let i=()=>{};this.#B=new Promise(n=>i=n);try{for(let n of await this.#t.promises.readdir(e,{withFileTypes:!0}))this.#R(n,t);this.#L(t);}catch(n){this.#I(n.code),t.provisional=0;}this.#B=void 0,i();}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return [];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let i of this.#t.readdirSync(e,{withFileTypes:!0}))this.#R(i,t);this.#L(t);}catch(i){this.#I(i.code),t.provisional=0;}return t.slice(0,t.provisional)}canReaddir(){if(this.#n&Vs)return !1;let t=B&this.#n;return t===$||t===X||t===nt}shouldWalk(t,e){return (this.#n&X)===X&&!(this.#n&Vs)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#N)return this.#N;if(!((ee|Qt|V)&this.#n))try{let t=await this.#t.promises.realpath(this.fullpath());return this.#N=this.resolve(t)}catch{this.#W();}}realpathSync(){if(this.#N)return this.#N;if(!((ee|Qt|V)&this.#n))try{let t=this.#t.realpathSync(this.fullpath());return this.#N=this.resolve(t)}catch{this.#W();}}[ti](t){if(t===this)return;let e=new Set([]),i=[],n=this;for(;n&&n.parent;)e.add(n),n.#A=i.join(this.sep),n.#v=i.join("/"),n=n.parent,i.push("..");for(n=t;n&&n.parent&&!e.has(n);)n.#A=void 0,n.#v=void 0,n=n.parent;}},ie=class s extends F{sep="\\";splitSep=kr;constructor(t,e=$,i,n,r,o,h){super(t,e,i,n,r,o,h);}newChild(t,e=$,i={}){return new s(t,e,this.root,this.roots,this.nocase,this.childrenCache(),i)}getRootString(t){return Xe.win32.parse(t).root}getRoot(t){if(t=Pr(t.toUpperCase()),t===this.root.name)return this.root;for(let[e,i]of Object.entries(this.roots))if(this.sameRoot(t,e))return this.roots[t]=i;return this.roots[t]=new dt(t,this).root}sameRoot(t,e=this.root.name){return t=t.toUpperCase().replace(/\//g,"\\").replace(Xs,"$1\\"),t===e}},ne=class s extends F{splitSep="/";sep="/";constructor(t,e=$,i,n,r,o,h){super(t,e,i,n,r,o,h);}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,e=$,i={}){return new s(t,e,this.root,this.roots,this.nocase,this.childrenCache(),i)}},re=class{root;rootPath;roots;cwd;#t;#s;#r;nocase;#i;constructor(t=process.cwd(),e,i,{nocase:n,childrenCacheSize:r=16*1024,fs:o=At}={}){this.#i=qs(o),(t instanceof URL||t.startsWith("file://"))&&(t=url.fileURLToPath(t));let h=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(h),this.#t=new se,this.#s=new se,this.#r=new Me(r);let a=h.substring(this.rootPath.length).split(i);if(a.length===1&&!a[0]&&a.pop(),n===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=n,this.root=this.newRoot(this.#i),this.roots[this.rootPath]=this.root;let l=this.root,c=a.length-1,f=e.sep,u=this.rootPath,d=!1;for(let g of a){let p=c--;l=l.child(g,{relative:new Array(p).fill("..").join(f),relativePosix:new Array(p).fill("..").join("/"),fullpath:u+=(d?"":f)+g}),d=!0;}this.cwd=l;}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#r}resolve(...t){let e="";for(let r=t.length-1;r>=0;r--){let o=t[r];if(!(!o||o===".")&&(e=e?`${o}/${e}`:o,this.isAbsolute(o)))break}let i=this.#t.get(e);if(i!==void 0)return i;let n=this.cwd.resolve(e).fullpath();return this.#t.set(e,n),n}resolvePosix(...t){let e="";for(let r=t.length-1;r>=0;r--){let o=t[r];if(!(!o||o===".")&&(e=e?`${o}/${e}`:o,this.isAbsolute(o)))break}let i=this.#s.get(e);if(i!==void 0)return i;let n=this.cwd.resolve(e).fullpathPosix();return this.#s.set(e,n),n}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t,t=this.cwd);let{withFileTypes:i}=e;if(t.canReaddir()){let n=await t.readdir();return i?n:n.map(r=>r.name)}else return []}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t,t=this.cwd);let{withFileTypes:i=!0}=e;return t.canReaddir()?i?t.readdirSync():t.readdirSync().map(n=>n.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t.withFileTypes,t=this.cwd);let i=await t.readlink();return e?i:i?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t.withFileTypes,t=this.cwd);let i=t.readlinkSync();return e?i:i?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t.withFileTypes,t=this.cwd);let i=await t.realpath();return e?i:i?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t.withFileTypes,t=this.cwd);let i=t.realpathSync();return e?i:i?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t,t=this.cwd);let{withFileTypes:i=!0,follow:n=!1,filter:r,walkFilter:o}=e,h=[];(!r||r(t))&&h.push(i?t:t.fullpath());let a=new Set,l=(f,u)=>{a.add(f),f.readdirCB((d,g)=>{if(d)return u(d);let p=g.length;if(!p)return u();let w=()=>{--p===0&&u();};for(let m of g)(!r||r(m))&&h.push(i?m:m.fullpath()),n&&m.isSymbolicLink()?m.realpath().then(b=>b?.isUnknown()?b.lstat():b).then(b=>b?.shouldWalk(a,o)?l(b,w):w()):m.shouldWalk(a,o)?l(m,w):w();},!0);},c=t;return new Promise((f,u)=>{l(c,d=>{if(d)return u(d);f(h);});})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t,t=this.cwd);let{withFileTypes:i=!0,follow:n=!1,filter:r,walkFilter:o}=e,h=[];(!r||r(t))&&h.push(i?t:t.fullpath());let a=new Set([t]);for(let l of a){let c=l.readdirSync();for(let f of c){(!r||r(f))&&h.push(i?f:f.fullpath());let u=f;if(f.isSymbolicLink()){if(!(n&&(u=f.realpathSync())))continue;u.isUnknown()&&u.lstatSync();}u.shouldWalk(a,o)&&a.add(u);}}return h}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t,t=this.cwd);let{withFileTypes:i=!0,follow:n=!1,filter:r,walkFilter:o}=e;(!r||r(t))&&(yield i?t:t.fullpath());let h=new Set([t]);for(let a of h){let l=a.readdirSync();for(let c of l){(!r||r(c))&&(yield i?c:c.fullpath());let f=c;if(c.isSymbolicLink()){if(!(n&&(f=c.realpathSync())))continue;f.isUnknown()&&f.lstatSync();}f.shouldWalk(h,o)&&h.add(f);}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t,t=this.cwd);let{withFileTypes:i=!0,follow:n=!1,filter:r,walkFilter:o}=e,h=new et({objectMode:!0});(!r||r(t))&&h.write(i?t:t.fullpath());let a=new Set,l=[t],c=0,f=()=>{let u=!1;for(;!u;){let d=l.shift();if(!d){c===0&&h.end();return}c++,a.add(d);let g=(w,m,b=!1)=>{if(w)return h.emit("error",w);if(n&&!b){let E=[];for(let y of m)y.isSymbolicLink()&&E.push(y.realpath().then(S=>S?.isUnknown()?S.lstat():S));if(E.length){Promise.all(E).then(()=>g(null,m,!0));return}}for(let E of m)E&&(!r||r(E))&&(h.write(i?E:E.fullpath())||(u=!0));c--;for(let E of m){let y=E.realpathCached()||E;y.shouldWalk(a,o)&&l.push(y);}u&&!h.flowing?h.once("drain",f):p||f();},p=!0;d.readdirCB(g,!0),p=!1;}};return f(),h}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof F||(e=t,t=this.cwd);let{withFileTypes:i=!0,follow:n=!1,filter:r,walkFilter:o}=e,h=new et({objectMode:!0}),a=new Set;(!r||r(t))&&h.write(i?t:t.fullpath());let l=[t],c=0,f=()=>{let u=!1;for(;!u;){let d=l.shift();if(!d){c===0&&h.end();return}c++,a.add(d);let g=d.readdirSync();for(let p of g)(!r||r(p))&&(h.write(i?p:p.fullpath())||(u=!0));c--;for(let p of g){let w=p;if(p.isSymbolicLink()){if(!(n&&(w=p.realpathSync())))continue;w.isUnknown()&&w.lstatSync();}w.shouldWalk(a,o)&&l.push(w);}}u&&!h.flowing&&h.once("drain",f);};return f(),h}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[ti](e);}},dt=class extends re{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:i=!0}=e;super(t,Xe.win32,"\\",{...e,nocase:i}),this.nocase=i;for(let n=this.cwd;n;n=n.parent)n.nocase=this.nocase;}parseRootPath(t){return Xe.win32.parse(t).root.toUpperCase()}newRoot(t){return new ie(this.rootPath,X,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},pt=class extends re{sep="/";constructor(t=process.cwd(),e={}){let{nocase:i=!1}=e;super(t,Xe.posix,"/",{...e,nocase:i}),this.nocase=i;}parseRootPath(t){return "/"}newRoot(t){return new ne(this.rootPath,X,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},Pt=class extends pt{constructor(t=process.cwd(),e={}){let{nocase:i=!0}=e;super(t,{...e,nocase:i});}};process.platform==="win32"?ie:ne;var ei=process.platform==="win32"?dt:process.platform==="darwin"?Pt:pt;var Rr=s=>s.length>=1,Ir=s=>s.length>=1,gt=class s{#t;#s;#r;length;#i;#a;#l;#f;#h;#o;#e=!0;constructor(t,e,i,n){if(!Rr(t))throw new TypeError("empty pattern list");if(!Ir(e))throw new TypeError("empty glob list");if(e.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,i<0||i>=this.length)throw new TypeError("index out of range");if(this.#t=t,this.#s=e,this.#r=i,this.#i=n,this.#r===0){if(this.isUNC()){let[r,o,h,a,...l]=this.#t,[c,f,u,d,...g]=this.#s;l[0]===""&&(l.shift(),g.shift());let p=[r,o,h,a,""].join("/"),w=[c,f,u,d,""].join("/");this.#t=[p,...l],this.#s=[w,...g],this.length=this.#t.length;}else if(this.isDrive()||this.isAbsolute()){let[r,...o]=this.#t,[h,...a]=this.#s;o[0]===""&&(o.shift(),a.shift());let l=r+"/",c=h+"/";this.#t=[l,...o],this.#s=[c,...a],this.length=this.#t.length;}}}pattern(){return this.#t[this.#r]}isString(){return typeof this.#t[this.#r]=="string"}isGlobstar(){return this.#t[this.#r]===P}isRegExp(){return this.#t[this.#r]instanceof RegExp}globString(){return this.#l=this.#l||(this.#r===0?this.isAbsolute()?this.#s[0]+this.#s.slice(1).join("/"):this.#s.join("/"):this.#s.slice(this.#r).join("/"))}hasMore(){return this.length>this.#r+1}rest(){return this.#a!==void 0?this.#a:this.hasMore()?(this.#a=new s(this.#t,this.#s,this.#r+1,this.#i),this.#a.#o=this.#o,this.#a.#h=this.#h,this.#a.#f=this.#f,this.#a):this.#a=null}isUNC(){let t=this.#t;return this.#h!==void 0?this.#h:this.#h=this.#i==="win32"&&this.#r===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3]}isDrive(){let t=this.#t;return this.#f!==void 0?this.#f:this.#f=this.#i==="win32"&&this.#r===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0])}isAbsolute(){let t=this.#t;return this.#o!==void 0?this.#o:this.#o=t[0]===""&&t.length>1||this.isDrive()||this.isUNC()}root(){let t=this.#t[0];return typeof t=="string"&&this.isAbsolute()&&this.#r===0?t:""}checkFollowGlobstar(){return !(this.#r===0||!this.isGlobstar()||!this.#e)}markFollowGlobstar(){return this.#r===0||!this.isGlobstar()||!this.#e?!1:(this.#e=!1,!0)}};var Mr=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",kt=class{relative;relativeChildren;absolute;absoluteChildren;constructor(t,{nobrace:e,nocase:i,noext:n,noglobstar:r,platform:o=Mr}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[];let h={dot:!0,nobrace:e,nocase:i,noext:n,noglobstar:r,optimizationLevel:2,platform:o,nocomment:!0,nonegate:!0};for(let a of t){let l=new L(a,h);for(let c=0;c[t,!!(e&2),!!(e&1)])}},je=class{store=new Map;add(t,e){if(!t.canReaddir())return;let i=this.store.get(t);i?i.find(n=>n.globString()===e.globString())||i.push(e):this.store.set(t,[e]);}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return [...this.store.keys()].filter(t=>t.canReaddir())}},Ft=class s{hasWalkedCache;matches=new We;subwalks=new je;patterns;follow;dot;opts;constructor(t,e){this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=e?e.copy():new Le;}processPatterns(t,e){this.patterns=e;let i=e.map(n=>[t,n]);for(let[n,r]of i){this.hasWalkedCache.storeWalked(n,r);let o=r.root(),h=r.isAbsolute()&&this.opts.absolute!==!1;if(o){n=n.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let f=r.rest();if(f)r=f;else {this.matches.add(n,!0,!1);continue}}if(n.isENOENT())continue;let a,l,c=!1;for(;typeof(a=r.pattern())=="string"&&(l=r.rest());)n=n.resolve(a),r=l,c=!0;if(a=r.pattern(),l=r.rest(),c){if(this.hasWalkedCache.hasWalked(n,r))continue;this.hasWalkedCache.storeWalked(n,r);}if(typeof a=="string"){let f=a===".."||a===""||a===".";this.matches.add(n.resolve(a),h,f);continue}else if(a===P){(!n.isSymbolicLink()||this.follow||r.checkFollowGlobstar())&&this.subwalks.add(n,r);let f=l?.pattern(),u=l?.rest();if(!l||(f===""||f===".")&&!u)this.matches.add(n,h,f===""||f===".");else if(f===".."){let d=n.parent||n;u?this.hasWalkedCache.hasWalked(d,u)||this.subwalks.add(d,u):this.matches.add(d,h,!0);}}else a instanceof RegExp&&this.subwalks.add(n,r);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new s(this.opts,this.hasWalkedCache)}filterEntries(t,e){let i=this.subwalks.get(t),n=this.child();for(let r of e)for(let o of i){let h=o.isAbsolute(),a=o.pattern(),l=o.rest();a===P?n.testGlobstar(r,o,l,h):a instanceof RegExp?n.testRegExp(r,a,l,h):n.testString(r,a,l,h);}return n}testGlobstar(t,e,i,n){if((this.dot||!t.name.startsWith("."))&&(e.hasMore()||this.matches.add(t,n,!1),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,e):t.isSymbolicLink()&&(i&&e.checkFollowGlobstar()?this.subwalks.add(t,i):e.markFollowGlobstar()&&this.subwalks.add(t,e)))),i){let r=i.pattern();if(typeof r=="string"&&r!==".."&&r!==""&&r!==".")this.testString(t,r,i.rest(),n);else if(r===".."){let o=t.parent||t;this.subwalks.add(o,i);}else r instanceof RegExp&&this.testRegExp(t,r,i.rest(),n);}}testRegExp(t,e,i,n){e.test(t.name)&&(i?this.subwalks.add(t,i):this.matches.add(t,n,!1));}testString(t,e,i,n){t.isNamed(e)&&(i?this.subwalks.add(t,i):this.matches.add(t,n,!1));}};var Lr=(s,t)=>typeof s=="string"?new kt([s],t):Array.isArray(s)?new kt(s,t):s,oe=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#t=[];#s;#r;signal;maxDepth;constructor(t,e,i){this.patterns=t,this.path=e,this.opts=i,this.#r=!i.posix&&i.platform==="win32"?"\\":"/",i.ignore&&(this.#s=Lr(i.ignore,i)),this.maxDepth=i.maxDepth||1/0,i.signal&&(this.signal=i.signal,this.signal.addEventListener("abort",()=>{this.#t.length=0;}));}#i(t){return this.seen.has(t)||!!this.#s?.ignored?.(t)}#a(t){return !!this.#s?.childrenIgnored?.(t)}pause(){this.paused=!0;}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#t.shift());)t();}onResume(t){this.signal?.aborted||(this.paused?this.#t.push(t):t());}async matchCheck(t,e){if(e&&this.opts.nodir)return;let i;if(this.opts.realpath){if(i=t.realpathCached()||await t.realpath(),!i)return;t=i;}let n=t.isUnknown()||this.opts.stat;return this.matchCheckTest(n?await t.lstat():t,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&!this.#i(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let i;if(this.opts.realpath){if(i=t.realpathCached()||t.realpathSync(),!i)return;t=i;}let n=t.isUnknown()||this.opts.stat;return this.matchCheckTest(n?t.lstatSync():t,e)}matchFinish(t,e){if(this.#i(t))return;let i=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let n=this.opts.mark&&t.isDirectory()?this.#r:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(i){let r=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(r+n);}else {let r=this.opts.posix?t.relativePosix():t.relative(),o=this.opts.dotRelative&&!r.startsWith(".."+this.#r)?"."+this.#r:"";this.matchEmit(r?o+r+n:"."+n);}}async match(t,e,i){let n=await this.matchCheck(t,i);n&&this.matchFinish(n,e);}matchSync(t,e,i){let n=this.matchCheckSync(t,i);n&&this.matchFinish(n,e);}walkCB(t,e,i){this.signal?.aborted&&i(),this.walkCB2(t,e,new Ft(this.opts),i);}walkCB2(t,e,i,n){if(this.#a(t))return n();if(this.signal?.aborted&&n(),this.paused){this.onResume(()=>this.walkCB2(t,e,i,n));return}i.processPatterns(t,e);let r=1,o=()=>{--r===0&&n();};for(let[h,a,l]of i.matches.entries())this.#i(h)||(r++,this.match(h,a,l).then(()=>o()));for(let h of i.subwalkTargets()){if(this.maxDepth!==1/0&&h.depth()>=this.maxDepth)continue;r++;let a=h.readdirCached();h.calledReaddir()?this.walkCB3(h,a,i,o):h.readdirCB((l,c)=>this.walkCB3(h,c,i,o),!0);}o();}walkCB3(t,e,i,n){i=i.filterEntries(t,e);let r=1,o=()=>{--r===0&&n();};for(let[h,a,l]of i.matches.entries())this.#i(h)||(r++,this.match(h,a,l).then(()=>o()));for(let[h,a]of i.subwalks.entries())r++,this.walkCB2(h,a,i.child(),o);o();}walkCBSync(t,e,i){this.signal?.aborted&&i(),this.walkCB2Sync(t,e,new Ft(this.opts),i);}walkCB2Sync(t,e,i,n){if(this.#a(t))return n();if(this.signal?.aborted&&n(),this.paused){this.onResume(()=>this.walkCB2Sync(t,e,i,n));return}i.processPatterns(t,e);let r=1,o=()=>{--r===0&&n();};for(let[h,a,l]of i.matches.entries())this.#i(h)||this.matchSync(h,a,l);for(let h of i.subwalkTargets()){if(this.maxDepth!==1/0&&h.depth()>=this.maxDepth)continue;r++;let a=h.readdirSync();this.walkCB3Sync(h,a,i,o);}o();}walkCB3Sync(t,e,i,n){i=i.filterEntries(t,e);let r=1,o=()=>{--r===0&&n();};for(let[h,a,l]of i.matches.entries())this.#i(h)||this.matchSync(h,a,l);for(let[h,a]of i.subwalks.entries())r++,this.walkCB2Sync(h,a,i.child(),o);o();}},Rt=class extends oe{matches;constructor(t,e,i){super(t,e,i),this.matches=new Set;}matchEmit(t){this.matches.add(t);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches);});}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},It=class extends oe{results;constructor(t,e,i){super(t,e,i),this.results=new et({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume());}matchEmit(t){this.results.write(t),this.results.flowing||this.pause();}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end());}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};var jr=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",H=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;opts;patterns;constructor(t,e){if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=url.fileURLToPath(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof t=="string"&&(t=[t]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(t=t.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");t=t.map(a=>a.includes("/")?a:`./**/${a}`);}if(this.pattern=t,this.platform=e.platform||jr,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else {let a=e.platform==="win32"?dt:e.platform==="darwin"?Pt:e.platform?pt:ei;this.scurry=new a(this.cwd,{nocase:e.nocase,fs:e.fs});}this.nocase=this.scurry.nocase;let i=this.platform==="darwin"||this.platform==="win32",n={...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:i,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},r=this.pattern.map(a=>new L(a,n)),[o,h]=r.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=o.map((a,l)=>{let c=h[l];if(!c)throw new Error("invalid pattern object");return new gt(a,c,0,this.platform)});}async walk(){return [...await new Rt(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase}).walk()]}walkSync(){return [...new Rt(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase}).walkSync()]}stream(){return new It(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase}).stream()}streamSync(){return new It(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};var Be=(s,t={})=>{Array.isArray(s)||(s=[s]);for(let e of s)if(new L(e,t).hasMagic())return !0;return !1};function he(s,t={}){return new H(s,t).streamSync()}function ii(s,t={}){return new H(s,t).stream()}function ni(s,t={}){return new H(s,t).walkSync()}async function si(s,t={}){return new H(s,t).walk()}function le(s,t={}){return new H(s,t).iterateSync()}function ri(s,t={}){return new H(s,t).iterate()}var Br=he,$r=Object.assign(ii,{sync:he}),zr=le,Ur=Object.assign(ri,{sync:le}),Gr=Object.assign(ni,{stream:he,iterate:le}),ae=Object.assign(si,{glob:si,globSync:ni,sync:Gr,globStream:ii,stream:$r,globStreamSync:he,streamSync:Br,globIterate:ri,iterate:Ur,globIterateSync:le,iterateSync:zr,Glob:H,hasMagic:Be,escape:ht,unescape:U});ae.glob=ae;var ai=(s,t)=>{let e={dirs:[],files:[]};return s.forEach(i=>{let n=Xe.join(t,i);(0, oi.default)(n)?e.files.push(...ae.sync(n,{dot:!0,absolute:!0})):ce__namespace.default.existsSync(i)?(ce__namespace.default.lstatSync(i).isDirectory()?e.dirs:e.files).push(i):ce__namespace.default.existsSync(n)?(ce__namespace.default.lstatSync(n).isDirectory()?e.dirs:e.files).push(n):nodeLogger.logger.warn(_` Ignoring additional watch path '${i}': path doesn't exists. - `);}),e};var Mt="dev-preview-plugin",di=unplugin.createUnplugin(s=>{let{projectDir:t,additionalWatchPaths:e}=s;return {name:Mt,enforce:"post",transformInclude(i){return /storybook-config-entry\.js$/.test(i)},async transform(i){return T` + `);}),e};var Mt="dev-preview-plugin",li=unplugin.createUnplugin(s=>{let{projectDir:t,server:e,additionalWatchPaths:i}=s;return {name:Mt,enforce:"post",transformInclude(n){return /storybook-config-entry\.js$/.test(n)},async transform(n){return _` import { symfonyPreview } from './symfony-preview.js'; - ${i} + ${n} window.__SYMFONY_PREVIEW__ = symfonyPreview; if (import.meta.webpackHot) { @@ -81,25 +71,25 @@ globstar while`,t,u,e,d,g),this.matchOne(t.slice(u),e.slice(d),i))return this.de } }); } - `},webpack(i){let n=new ui.default;n.apply(i);let r="";i.hooks.watchRun.tapPromise(Mt,async()=>{r=await Ut("storybook:generate-preview"),n.writeModule("./symfony-preview.js",T` + `},webpack(n){let r=new hi.default;r.apply(n);let o="";n.hooks.watchRun.tapPromise(Mt,async()=>{o=await Ut(e),r.writeModule("./symfony-preview.js",_` export const symfonyPreview = { - html: \`${r}\`, - };`);}),i.hooks.afterCompile.tap(Mt,o=>{if(o.name=="HtmlWebpackCompiler"){let h=fi(e,t);o.contextDependencies.addAll(h.dirs),o.fileDependencies.addAll(h.files);}}),i.hooks.thisCompilation.tap(Mt,o=>{hn__default.default.getHooks(o).afterTemplateExecution.tapPromise(Mt,async h=>{try{return h.html=Vt(r,h.html),h}catch(a){return nodeLogger.logger.error(T` + html: \`${o}\`, + };`);}),n.hooks.afterCompile.tap(Mt,h=>{if(h.name=="HtmlWebpackCompiler"){let a=ai(i,t);h.contextDependencies.addAll(a.dirs),h.fileDependencies.addAll(a.files);}}),n.hooks.thisCompilation.tap(Mt,h=>{sn__default.default.getHooks(h).afterTemplateExecution.tapPromise(Mt,async a=>{try{return a.html=Gt(o,a.html),a}catch(l){return nodeLogger.logger.error(_` Failed to inject Symfony preview template in main iframe.html. - ERR: ${a} - `),h}});});}}});var Di=zt(Hi()),qi=s=>{let t=["block"],e=new RegExp(/twig:[A-Za-z]+(?::[A-Za-z]+)*/),i=new RegExp(/component\(\s*'([A-Za-z]+(?::[A-Za-z]+)*)'\s*(?:,.*)?\)/,"gs"),n=r=>Object.entries(r).reduce((o,[h,a])=>{if(a!==null&&typeof a=="object")o.push(...n(a));else if(typeof a=="string")for(let l of a.matchAll(i))o.push([...l][1]);return e.test(h)&&o.push(h.replace("twig:","")),o},[]);try{let r=new Di.XMLParser().parse(`
${s}
`);return n(r).filter(o=>!t.includes(o))}catch(r){throw new Error("Invalid XML.",{cause:{parserError:r,template:s}})}};var ue=class{constructor(t){this.config=t;}resolveNameFromFile(t){let e=(i,n)=>i.replace(n,"").replace(/^\//,"").replaceAll("/",":").replace(".html.twig","");for(let[i,n]of Object.entries(this.config.namespaces)){let r=n.find(o=>t.startsWith(o));if(r){let o=e(t,r);return i?`${i}:${o}`:o}}for(let i of this.config.anonymousTemplateDirectory)if(t.startsWith(i))return e(t,i);throw new Error(T`Unable to determine template name for file "${t}":`)}resolveFileFromName(t){let e=t.split(":"),i=e.length>1?e[0]:"",n=e.slice(0,-1),r=`${e.slice(-1)}.html.twig`,o=[];if(i&&this.config.namespaces[i]&&this.config.namespaces[i].length>0)for(let a of this.config.namespaces[i])o.push(qe__default.default.join(a,n.slice(1).join("/")));if(this.config.namespaces[""]&&this.config.namespaces[""].length>0)for(let h of this.config.namespaces[""])o.push(qe__default.default.join(h,n.join("/")));if(this.config.anonymousTemplateDirectory.length>0)for(let h of this.config.anonymousTemplateDirectory)o.push(qe__default.default.join(h,n.join("/")));try{return $t.resolve(`./${r}`,{paths:o})}catch(h){throw new Error(T`Unable to find template file for component "${t}": ${h}`)}}};var ua="twig-loader",Xi=unplugin.createUnplugin(s=>{let{twigComponentConfiguration:t}=s,e=new ue(t);return {name:ua,enforce:"pre",transformInclude:i=>/\.html\.twig$/.test(i),transform:async(i,n)=>{let r=[];try{new Set(qi(i)).forEach(a=>{r.push(e.resolveFileFromName(a));});}catch(h){nodeLogger.logger.warn(T` - Failed to parse template in '${n}': ${h} - `);}let o=e.resolveNameFromFile(n);return T` - ${r.map(h=>`import '${h}';`).join(` + ERR: ${l} + `),a}});});}}});var Ui=zt(zi()),Gi=s=>{let t=["block"],e=new RegExp(/twig:[A-Za-z]+(?::[A-Za-z]+)*/),i=new RegExp(/component\(\s*'([A-Za-z]+(?::[A-Za-z]+)*)'\s*(?:,.*)?\)/,"gs"),n=r=>Object.entries(r).reduce((o,[h,a])=>{if(a!==null&&typeof a=="object")o.push(...n(a));else if(typeof a=="string")for(let l of a.matchAll(i))o.push([...l][1]);return e.test(h)&&o.push(h.replace("twig:","")),o},[]);try{let r=new Ui.XMLParser().parse(`
${s}
`);return n(r).filter(o=>!t.includes(o))}catch(r){throw new Error("Invalid XML.",{cause:{parserError:r,template:s}})}};var ue=class{constructor(t,e){this.config=t;this.projectDir=e;}resolveNameFromFile(t){let e=(n,r)=>n.replace(r,"").replace(/^\//,"").replaceAll("/",":").replace(".html.twig",""),i=this.resolveRelativePath(t);for(let[n,r]of Object.entries(this.config.namespaces)){let o=r.find(h=>i.startsWith(h));if(o){let h=e(i,o);return n?`${n}:${h}`:h}}for(let n of this.config.anonymousTemplateDirectory)if(i.startsWith(n))return e(i,n);throw new Error(_`Unable to determine template name for file "${t}":`)}resolveFileFromName(t){let e=t.split(":"),i=e.length>1?e[0]:"",n=e.slice(0,-1),r=`${e.slice(-1)}.html.twig`,o=[];if(i&&this.config.namespaces[i]&&this.config.namespaces[i].length>0)for(let a of this.config.namespaces[i])o.push(Xe__default.default.join(this.resolveRelativePath(a),n.slice(1).join("/")));if(this.config.namespaces[""]&&this.config.namespaces[""].length>0)for(let h of this.config.namespaces[""])o.push(Xe__default.default.join(this.resolveRelativePath(h),n.join("/")));if(this.config.anonymousTemplateDirectory.length>0)for(let h of this.config.anonymousTemplateDirectory)o.push(Xe__default.default.join(this.resolveRelativePath(h),n.join("/")));try{return $t.resolve(`./${r}`,{paths:o})}catch(h){throw new Error(_`Unable to find template file for component "${t}": ${h}`)}}resolveRelativePath(t){return t.replace(this.projectDir,"")}};var aa="twig-loader",Vi=unplugin.createUnplugin(s=>{let{twigComponentConfiguration:t,projectDir:e}=s,i=new ue(t,e);return {name:aa,enforce:"pre",transformInclude:n=>/\.html\.twig$/.test(n),transform:async(n,r)=>{let o=[];try{new Set(Gi(n)).forEach(l=>{o.push(i.resolveFileFromName(l));});}catch(a){nodeLogger.logger.warn(_` + Failed to parse template in '${r}': ${a} + `);}let h=i.resolveNameFromFile(r);return _` + ${o.map(a=>`import '${a}';`).join(` `)} export default { - name: \'${o}\', - hash: \`${fa__default.default.createHash("sha1").update(i).digest("hex")}\`, + name: \'${h}\', + hash: \`${oa__default.default.createHash("sha1").update(n).digest("hex")}\`, }; - `}}});var da=async s=>{let t=await Ze(),e=await Qe(),i=await ts(),n={},r=Object.keys(i.paths).map(a=>`${t}/${a}/`);r.length===0&&r.push(`${t}/templates`);for(let{name_prefix:a,template_directory:l}of Object.values(e.defaults))n[a]=r.map(c=>qe.join(c,l));let o=r.map(a=>qe.join(a,e.anonymous_template_directory)),h=(await Je()).runtime_dir;return {twigComponent:{anonymousTemplateDirectory:o,namespaces:n},twig:{paths:r},runtimeDir:h,projectDir:t,additionalWatchPaths:s.additionalWatchPaths||[]}},kl=async(s,t)=>{let e=await t.presets.apply("framework"),i=typeof e=="string"?{}:e.options,n=await da(i.symfony);return {...s,plugins:[...s.plugins||[],t.configType==="PRODUCTION"?es.webpack():di.webpack({projectDir:n.projectDir,additionalWatchPaths:n.additionalWatchPaths}),Xi.webpack({twigComponentConfiguration:n.twigComponent})],module:{...s.module,rules:[...s.module?.rules||[]]}}},Pl=async s=>T` + `}}});var ha=async s=>{let{twig_config:t,twig_component_config:e}=await Ze(s.storybookCachePath),i={},n=Object.keys(t.paths);n.length===0&&n.push("templates");for(let{name_prefix:o,template_directory:h}of Object.values(e.defaults))i[o]=[Xe.join(t.default_path,h)];return Object.entries(t.paths).forEach(([o,h])=>{i[h]=[Xe.join(o,e.anonymous_template_directory)];}),{twigComponent:{anonymousTemplateDirectory:[Xe.join(t.default_path,e.anonymous_template_directory)],namespaces:i},twig:{paths:n},additionalWatchPaths:s.additionalWatchPaths||[]}},xl=async(s,t)=>{let e=await t.presets.apply("framework"),i=typeof e=="string"?{}:e.options,n=await ha(i.symfony);return {...s,plugins:[...s.plugins||[],t.configType==="PRODUCTION"?Je.webpack({server:i.symfony.server}):li.webpack({projectDir:Xe.resolve(),server:i.symfony.server,additionalWatchPaths:n.additionalWatchPaths}),Vi.webpack({projectDir:Xe.resolve(),twigComponentConfiguration:n.twigComponent})],module:{...s.module,rules:[...s.module?.rules||[]]}}},Tl=async s=>_` ${s} - `,Fl=async s=>T` + `,Cl=async s=>_` ${s} `;/*! Bundled license information: @@ -121,8 +111,8 @@ is-glob/index.js: *) */ -exports.previewBody = Fl; -exports.previewHead = Pl; -exports.webpack = kl; +exports.previewBody = Cl; +exports.previewHead = Tl; +exports.webpack = xl; //# sourceMappingURL=out.js.map //# sourceMappingURL=framework-preset.js.map \ No newline at end of file diff --git a/storybook/dist/server/framework-preset.js.map b/storybook/dist/server/framework-preset.js.map index 497d30a..d8ea3fa 100644 --- a/storybook/dist/server/framework-preset.js.map +++ b/storybook/dist/server/framework-preset.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../node_modules/webpack-virtual-modules/src/virtual-stats.ts","../../node_modules/webpack-virtual-modules/src/index.ts","../../node_modules/is-extglob/index.js","../../node_modules/is-glob/index.js","../../node_modules/balanced-match/index.js","../../node_modules/brace-expansion/index.js","../../node_modules/fast-xml-parser/src/util.js","../../node_modules/fast-xml-parser/src/validator.js","../../node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js","../../node_modules/fast-xml-parser/src/xmlparser/xmlNode.js","../../node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js","../../node_modules/strnum/strnum.js","../../node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js","../../node_modules/fast-xml-parser/src/xmlparser/node2json.js","../../node_modules/fast-xml-parser/src/xmlparser/XMLParser.js","../../node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js","../../node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js","../../node_modules/fast-xml-parser/src/fxp.js","../../src/server/lib/symfony.ts","../../node_modules/ts-dedent/src/index.ts","../../src/server/framework-preset.ts","../../src/server/lib/preview-compiler-plugin.ts","../../src/server/lib/injectPreviewHtml.ts","../../src/server/lib/dev-preview-compiler-plugin.ts","../../src/server/lib/computeAdditionalWatchPaths.ts","../../node_modules/glob/node_modules/minimatch/src/index.ts","../../node_modules/glob/node_modules/minimatch/src/assert-valid-pattern.ts","../../node_modules/glob/node_modules/minimatch/src/brace-expressions.ts","../../node_modules/glob/node_modules/minimatch/src/unescape.ts","../../node_modules/glob/node_modules/minimatch/src/ast.ts","../../node_modules/glob/node_modules/minimatch/src/escape.ts","../../node_modules/lru-cache/src/index.ts","../../node_modules/path-scurry/src/index.ts","../../node_modules/minipass/src/index.ts","../../node_modules/glob/src/glob.ts","../../node_modules/glob/src/pattern.ts","../../node_modules/glob/src/ignore.ts","../../node_modules/glob/src/processor.ts","../../node_modules/glob/src/walker.ts","../../node_modules/glob/src/has-magic.ts","../../node_modules/glob/src/index.ts","../../src/server/lib/twig-loader-plugin.ts","../../src/server/lib/extractComponentsFromTemplate.ts","../../src/server/lib/TwigComponentResolver.ts"],"names":["constants_1","__importDefault","VirtualStats","config","key","property","exports","path_1","virtual_stats_1","inode","ALL","STATIC","DYNAMIC","checkActivation","instance","getModulePath","filePath","compiler","createWebpackData","result","backendOrStorage","curLevelIdx","curLevel","getData","storage","setData","valueFactory","value","getStatStorage","fileSystem","getFileStorage","getReadDirBackend","VirtualModulesPlugin","modules","filter","shouldGetStaticModules","shouldGetDynamicModules","finalInputFileSystem","_a","virtualFiles","_b","dynamicModules","contents","len","time","date","stats","modulePath","finalWatchFileSystem","fileWatchers","fileWatcher","afterEnvironmentHook","originalPurge","file","data","statStorage","fileStorage","readDirStorage","segments","count","minCount","dir","dirStats","dirData","filename","files","afterResolversHook","version","watchRunHook","watcher","callback","fts","mtime","module","require_is_extglob","__commonJSMin","str","match","require_is_glob","isExtglob","chars","strictCheck","index","pipeIndex","closeSquareIndex","closeCurlyIndex","closeParenIndex","backSlashIndex","open","close","n","relaxedCheck","options","check","require_balanced_match","balanced","a","b","maybeMatch","r","range","reg","m","begs","beg","left","right","ai","bi","i","require_brace_expansion","expandTop","escSlash","escOpen","escClose","escComma","escPeriod","numeric","escapeBraces","unescapeBraces","parseCommaParts","parts","pre","body","post","p","postParts","expand","embrace","isPadded","el","lte","y","gte","isTop","expansions","k","expansion","isNumericSequence","isAlphaSequence","isSequence","isOptions","N","x","width","incr","test","reverse","pad","c","need","z","j","require_util","nameStartChar","nameChar","nameRegexp","regexName","getAllMatches","string","regex","matches","allmatches","isName","v","obj","target","arrayMode","keys","require_validator","util","defaultOptions","xmlData","tags","tagFound","reachedRoot","readPI","tagStartPos","readCommentAndCDATA","closingTag","tagName","validateTagName","msg","getErrorObject","getLineNumberForPosition","readAttributeStr","attrStr","attrStrStart","isValid","validateAttributeString","otg","openPos","afterAmp","validateAmpersand","isWhiteSpace","t","char","start","tagname","angleBracketsCount","doubleQuote","singleQuote","startChar","tagClosed","validAttrStrRegxp","attrNames","getPositionFromMatch","attrName","validateAttrName","validateNumberAmpersand","re","code","message","lineNumber","lines","require_OptionsBuilder","val","jPath","attrs","buildOptions","require_xmlNode","XmlNode","node","require_DocTypeReader","readDocType","entities","hasBody","comment","exp","isEntity","readEntityExp","validateEntityName","isElement","isAttlist","isNotation","isComment","entityName","name","require_strnum","hexRegex","numRegex","consider","toNumber","trimmedStr","sign","leadingZeros","numTrimmedByZeros","trimZeros","eNotation","num","numStr","require_OrderedObjParser","xmlNode","OrderedObjParser","_","addExternalEntities","parseXml","parseTextData","resolveNameSpace","buildAttributesMap","isItStopNode","replaceEntitiesValue","readStopNodeData","saveTextToParentTag","addChild","externalEntities","entKeys","ent","dontTrim","hasAttributes","isLeafNode","escapeEntities","newval","parseValue","prefix","attrsRegx","oldVal","aName","newVal","attrCollection","xmlObj","currentNode","textData","closeIndex","findClosingIndex","colonIndex","lastTagName","propIndex","tagData","readTagExp","childNode","endIndex","tagExp","rawTagName","attrExpPresent","lastTag","tagContent","entity","stopNodes","currentTagName","allNodesExp","stopNodePath","stopNodeExp","tagExpWithClosingIndex","closingChar","attrBoundary","ch","errMsg","closingIndex","removeNSPrefix","separatorIndex","startIndex","openTagCount","shouldParse","require_node2json","prettify","compress","arr","text","compressedObj","tagObj","propName","newJpath","isLeaf","isLeafTag","assignAttributes","attrMap","jpath","atrrName","textNodeName","propCount","require_XMLParser","validator","XMLParser","validationOption","orderedObjParser","orderedResult","require_orderedJs2Xml","EOL","toXml","jArray","indentation","arrToStr","xmlStr","isPreviousElementTag","newJPath","tagText","isStopNode","attStr","attr_to_str","tempInd","piTextNodeName","newIdentation","tagStart","tagValue","attr","attrVal","textValue","require_json2xml","buildFromOrderedJs","Builder","isAttribute","processTextOrObjNode","indentate","jObj","level","arrLen","listTagVal","item","Ks","L","object","tagEndExp","piClosingChar","closeTag","require_fxp","XMLBuilder","exec","dedent","templ","values","_i","strings","indentLengths","pattern_1","endentations","endentation","indentedValue","esm_default","prepareSymfonyCommand","command","inputs","finalOptions","part","execSymfonyCommand","finalCommand","resolve","reject","error","stdout","stderr","runSymfonyCommand","runSymfonyCommandJson","getKernelProjectDir","getBundleConfig","getTwigComponentConfiguration","getTwigConfiguration","join","createUnplugin","HtmlWebpackPlugin","logger","JSDOM","injectPreviewHtml","previewHtml","targetHtml","previewDom","previewHead","previewBody","PLUGIN_NAME","PreviewCompilerPlugin","compilation","params","err","import_webpack_virtual_modules","import_is_glob","import_brace_expansion","assertValidPattern","pattern","posixClasses","braceEscape","regexpEscape","rangesToString","ranges","parseClass","glob","position","pos","negs","sawStart","uflag","escaping","negate","endPos","rangeStart","WHILE","cls","unip","u","neg","sranges","snegs","unescape","windowsPathsNoEscape","types","isExtglobType","startNoTraversal","startNoDot","addPatternStart","justDots","reSpecials","regExpEscape","qmark","star","starNoEmpty","AST","_AST","#root","#hasMagic","#uflag","#parts","#parent","#parentIndex","#negs","#filledNegs","#options","#toString","#emptyExt","type","parent","#fillNegs","pp","ret","pl","#parseAST","ast","opt","inBrace","braceStart","braceNeg","acc","ext","hasMagic","flags","allowDot","dot","noEmpty","src","#parseGlob","aps","needNoTrav","needNoDot","end","repeated","#partsToRegExp","s","bodyDotAllowed","final","_hasMagic","needUflag","consumed","magic","escape","minimatch","Minimatch","starDotExtRE","starDotExtTest","f","starDotExtTestDot","starDotExtTestNocase","starDotExtTestNocaseDot","starDotStarRE","starDotStarTest","starDotStarTestDot","dotStarRE","dotStarTest","starRE","starTest","starTestDot","qmarksRE","qmarksTestNocase","$0","noext","qmarksTestNoExt","qmarksTestNocaseDot","qmarksTestNoExtDot","qmarksTestDot","qmarksTest","defaultPlatform","path","sep","GLOBSTAR","twoStarDot","twoStarNoDot","defaults","def","orig","list","braceExpand","makeRe","mm","globMagic","args","rawGlobParts","set","__","isUNC","isDrive","ss","globParts","optimizationLevel","gs","prev","didSomething","dd","gss","next","p2","other","splin","matched","emptyGSMatch","which","negateOffset","partial","fileDrive","fileUNC","patternDrive","patternUNC","fdi","pdi","fd","pd","fi","pi","fl","fr","pr","swallowee","hit","fastTest","twoStar","ff","perf","warned","PROCESS","emitWarning","fn","AC","AS","warnACPolyfill","reason","printACPolyfillWarning","shouldWarn","TYPE","isPosInt","getUintArray","max","ZeroArray","size","Stack","_Stack","#constructing","HeapCls","LRUCache","_LRUCache","#max","#maxSize","#dispose","#disposeAfter","#fetchMethod","#size","#calculatedSize","#keyMap","#keyList","#valList","#next","#prev","#head","#tail","#free","#disposed","#sizes","#starts","#ttls","#hasDispose","#hasFetchMethod","#hasDisposeAfter","#isBackgroundFetch","context","#backgroundFetch","#moveToTail","#indexes","#rindexes","#isStale","ttl","ttlResolution","ttlAutopurge","updateAgeOnGet","updateAgeOnHas","allowStale","dispose","disposeAfter","noDisposeOnSet","noUpdateTTL","maxSize","maxEntrySize","sizeCalculation","fetchMethod","noDeleteOnFetchRejection","noDeleteOnStaleGet","allowStaleOnFetchRejection","allowStaleOnFetchAbort","ignoreFetchAbort","UintArray","#initializeSizeTracking","#initializeTTLTracking","ttls","starts","#setItemTTL","#updateItemAge","#statusTTL","status","cachedNow","getNow","age","sizes","#removeItemSize","#requireSize","#addItemSize","#evict","_s","_st","_k","_v","#isValidIndex","getOptions","thisp","deleted","entry","remain","setOptions","oldValue","dt","task","free","head","hasOptions","peekOptions","ac","signal","fetchOpts","cb","updateCache","aborted","ignoreAbort","fetchFail","bf","eb","er","allowStaleAborted","noDelete","pcall","res","rej","fmp","fetchOptions","forceRefresh","stale","isStale","staleVal","fetching","#connect","ni","posix","win32","fileURLToPath","actualFS","lstatSync","readdirCB","readdirSync","readlinkSync","rps","lstat","readdir","readlink","realpath","EventEmitter","Stream","StringDecoder","proc","isStream","Minipass","isReadable","isWritable","EOF","MAYBE_EMIT_END","EMITTED_END","EMITTING_END","EMITTED_ERROR","CLOSED","READ","FLUSH","FLUSHCHUNK","ENCODING","DECODER","FLOWING","PAUSED","RESUME","BUFFER","PIPES","BUFFERLENGTH","BUFFERPUSH","BUFFERSHIFT","OBJECTMODE","DESTROYED","ERROR","EMITDATA","EMITEND","EMITEND2","ASYNC","ABORT","ABORTED","SIGNAL","DATALISTENERS","DISCARDED","defer","nodefer","isEndish","ev","isArrayBufferLike","isArrayBufferView","Pipe","dest","opts","_er","PipeProxyErrors","isObjectModeOptions","o","isEncodingOptions","_enc","_om","chunk","encoding","noDrain","ended","handler","h","buf","stopped","stop","onerr","ondata","onend","ondestroy","wc","realpathSync","defaultFS","fsFromOption","fsOption","uncDriveRegexp","uncToDrive","rootPath","eitherSep","UNKNOWN","IFIFO","IFCHR","IFDIR","IFBLK","IFREG","IFLNK","IFSOCK","IFMT","IFMT_UNKNOWN","READDIR_CALLED","LSTAT_CALLED","ENOTDIR","ENOENT","ENOREADLINK","ENOREALPATH","ENOCHILD","TYPEMASK","entToType","normalizeCache","normalize","normalizeNocaseCache","normalizeNocase","ResolveCache","ChildrenCache","setAsCwd","PathBase","#fs","#dev","#mode","#nlink","#uid","#gid","#rdev","#blksize","#ino","#blocks","#atimeMs","#mtimeMs","#ctimeMs","#birthtimeMs","#atime","#mtime","#ctime","#birthtime","#matchName","#depth","#fullpath","#fullpathPosix","#relative","#relativePosix","#type","#children","#linkTarget","#realpath","root","roots","nocase","children","dirParts","#resolveParts","cached","pathPart","fullpath","pchild","pv","fp","pfpp","fpp","ifmt","read","linkTarget","#readlinkFail","#readdirSuccess","#markENOENT","#markChildrenENOENT","#markENOREALPATH","#markENOTDIR","#readdirFail","#lstatFail","ter","#readdirAddChild","e","#readdirMaybePromoteChild","#readdirAddNewChild","child","#readdirPromoteChild","#applyStat","st","atime","atimeMs","birthtime","birthtimeMs","blksize","blocks","ctime","ctimeMs","dev","gid","ino","mode","mtimeMs","nlink","rdev","uid","#onReaddirCB","#readdirCBInFlight","#callOnReaddirCB","cbs","allowZalgo","entries","#asyncReaddirInFlight","dirs","walkFilter","rp","oldCwd","changed","PathWin32","_PathWin32","compare","PathScurryWin32","PathPosix","_PathPosix","_rootPath","PathScurryBase","#resolveCache","#resolvePosixCache","cwd","pathImpl","childrenCacheSize","fs","cwdPath","split","joinSep","abs","sawFirst","l","paths","withFileTypes","follow","results","walk","queue","processing","process","paused","onReaddir","didRealpaths","promises","sync","PathScurryPosix","_dir","PathScurryDarwin","Path","PathScurry","isPatternList","isGlobList","gl","Pattern","_Pattern","#patternList","#globList","#index","#platform","#rest","#globString","#isDrive","#isUNC","#isAbsolute","#followGlobstar","patternList","globList","platform","p0","p1","p3","prest","g0","g1","g2","g3","grest","g","Ignore","ignored","nobrace","noglobstar","mmopts","ign","parsed","absolute","fullpaths","relative","relatives","HasWalkedCache","_HasWalkedCache","store","MatchRecord","ifDir","current","SubWalks","subs","Processor","_Processor","hasWalkedCache","patterns","processingSet","rest","rrest","tp","ep","makeIgnore","ignore","GlobUtil","#onResume","#ignore","#sep","#ignored","#childrenIgnored","rpc","needStat","mark","rel","processor","tasks","childrenCached","GlobWalker","GlobStream","Glob","Scurry","nocaseMagicOnly","mmo","mms","matchSet","globStreamSync","globStream","globSync","glob_","globIterateSync","globIterate","streamSync","stream","iterateSync","iterate","computeAdditionalWatchPaths","baseDir","watchPath","isGlob","DevPreviewCompilerPlugin","projectDir","additionalWatchPaths","id","resolvedWatchPaths","import_fast_xml_parser","extractComponentsFromTemplate","source","reservedNames","tagRe","functionRe","lookupComponents","names","documentObj","TwigComponentResolver","stripDirectory","namespace","twigDirectories","matchingDirectory","trimmedPath","anonymousDir","nameParts","lookupPaths","namespacePath","__require","crypto","TwigLoaderPlugin","twigComponentConfiguration","resolver","imports","getBuildOptions","symfonyOptions","twigComponentsConfig","twigConfig","componentNamespaces","twigPaths","namePrefix","templateDirectory","twigPath","anonymousNamespace","runtimeDir","webpack","framework","frameworkOptions","base"],"mappings":"w8BASA,IAAAA,EAAAC,GAAA,GAAA,WAAA,CAAA,EAEaC,GAAb,KAAyB,CAMvB,YAAmBC,EAAM,CACvB,QAAWC,KAAOD,EACX,OAAO,UAAU,eAAe,KAAKA,EAAQC,CAAG,IAGrD,KAAKA,CAAG,EAAID,EAAOC,CAAG,EAE1B,CAKQ,mBAAmBC,EAAQ,CACjC,OAAS,KAAa,KAAOL,EAAA,QAAU,UAAYK,CACrD,CAEO,aAAW,CAChB,OAAO,KAAK,mBAAmBL,EAAA,QAAU,OAAO,CAClD,CAEO,QAAM,CACX,OAAO,KAAK,mBAAmBA,EAAA,QAAU,OAAO,CAClD,CAEO,eAAa,CAClB,OAAO,KAAK,mBAAmBA,EAAA,QAAU,OAAO,CAClD,CAEO,mBAAiB,CACtB,OAAO,KAAK,mBAAmBA,EAAA,QAAU,OAAO,CAClD,CAEO,gBAAc,CACnB,OAAO,KAAK,mBAAmBA,EAAA,QAAU,OAAO,CAClD,CAEO,QAAM,CACX,OAAO,KAAK,mBAAmBA,EAAA,QAAU,OAAO,CAClD,CAEO,UAAQ,CACb,OAAO,KAAK,mBAAmBA,EAAA,QAAU,QAAQ,CACnD,GAhDFM,GAAA,aAAAJ,sHCXAK,GAAAN,GAAA,GAAA,MAAA,CAAA,EACAO,GAAA,KAGIC,GAAQ,KACNC,GAAM,MACNC,GAAS,SACTC,GAAU,UAIhB,SAASC,GAAgBC,EAAQ,CAC/B,GAAI,CAACA,EAAS,UACZ,MAAM,IAAI,MAAM,gEAAgE,CAEpF,CAEA,SAASC,GAAcC,EAAUC,EAAQ,CACvC,OAAOV,GAAA,QAAK,WAAWS,CAAQ,EAAIA,EAAWT,GAAA,QAAK,KAAKU,EAAS,QAASD,CAAQ,CACpF,CAEA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K,EAAe,aAC/C,CAAC,CAET,EACA,OAAQ,CACJ,GAAGjkC,EAAO,OACV,MAAO,CAAC,GAAIA,EAAO,QAAQ,OAAS,CAAC,CAAE,CAC3C,CACJ,CACJ,EAEa6Z,GAA6C,MAAOirB,GAAc7sB;AAAA,MACzE6sB,CAAI;AAAA;AAAA,MAIGhrB,GAA6C,MAAOgrB,GAAc7sB;AAAA,MACzE6sB,CAAI;AAAA","sourcesContent":["/**\n * Used to cache a stats object for the virtual file.\n * Extracted from the `mock-fs` package.\n *\n * @author Tim Schaub http://tschaub.net/\n * @author `webpack-virtual-modules` Contributors\n * @link https://github.com/tschaub/mock-fs/blob/master/lib/binding.js\n * @link https://github.com/tschaub/mock-fs/blob/master/license.md\n */\nimport constants from 'constants';\n\nexport class VirtualStats {\n /**\n * Create a new stats object.\n *\n * @param config Stats properties.\n */\n public constructor(config) {\n for (const key in config) {\n if (!Object.prototype.hasOwnProperty.call(config, key)) {\n continue;\n }\n this[key] = config[key];\n }\n }\n\n /**\n * Check if mode indicates property.\n */\n private _checkModeProperty(property): boolean {\n return ((this as any).mode & constants.S_IFMT) === property;\n }\n\n public isDirectory(): boolean {\n return this._checkModeProperty(constants.S_IFDIR);\n }\n\n public isFile(): boolean {\n return this._checkModeProperty(constants.S_IFREG);\n }\n\n public isBlockDevice(): boolean {\n return this._checkModeProperty(constants.S_IFBLK);\n }\n\n public isCharacterDevice(): boolean {\n return this._checkModeProperty(constants.S_IFCHR);\n }\n\n public isSymbolicLink(): boolean {\n return this._checkModeProperty(constants.S_IFLNK);\n }\n\n public isFIFO(): boolean {\n return this._checkModeProperty(constants.S_IFIFO);\n }\n\n public isSocket(): boolean {\n return this._checkModeProperty(constants.S_IFSOCK);\n }\n}\n","import path from 'path';\nimport { VirtualStats } from './virtual-stats';\nimport type { Compiler } from 'webpack';\n\nlet inode = 45000000;\nconst ALL = 'all';\nconst STATIC = 'static';\nconst DYNAMIC = 'dynamic';\n\ntype AvailableModules = typeof ALL | typeof STATIC | typeof DYNAMIC;\n\nfunction checkActivation(instance) {\n if (!instance._compiler) {\n throw new Error('You must use this plugin only after creating webpack instance!');\n }\n}\n\nfunction getModulePath(filePath, compiler) {\n return path.isAbsolute(filePath) ? filePath : path.join(compiler.context, filePath);\n}\n\nfunction createWebpackData(result) {\n return (backendOrStorage) => {\n // In Webpack v5, this variable is a \"Backend\", and has the data stored in a field\n // _data. In V4, the `_` prefix isn't present.\n if (backendOrStorage._data) {\n const curLevelIdx = backendOrStorage._currentLevel;\n const curLevel = backendOrStorage._levels[curLevelIdx];\n return {\n result,\n level: curLevel,\n };\n }\n // Webpack 4\n return [null, result];\n };\n}\n\nfunction getData(storage, key) {\n // Webpack 5\n if (storage._data instanceof Map) {\n return storage._data.get(key);\n } else if (storage._data) {\n return storage.data[key];\n } else if (storage.data instanceof Map) {\n // Webpack v4\n return storage.data.get(key);\n } else {\n return storage.data[key];\n }\n}\n\nfunction setData(backendOrStorage, key, valueFactory) {\n const value = valueFactory(backendOrStorage);\n\n // Webpack v5\n if (backendOrStorage._data instanceof Map) {\n backendOrStorage._data.set(key, value);\n } else if (backendOrStorage._data) {\n backendOrStorage.data[key] = value;\n } else if (backendOrStorage.data instanceof Map) {\n // Webpack 4\n backendOrStorage.data.set(key, value);\n } else {\n backendOrStorage.data[key] = value;\n }\n}\n\nfunction getStatStorage(fileSystem) {\n if (fileSystem._statStorage) {\n // Webpack v4\n return fileSystem._statStorage;\n } else if (fileSystem._statBackend) {\n // webpack v5\n return fileSystem._statBackend;\n } else {\n // Unknown version?\n throw new Error(\"Couldn't find a stat storage\");\n }\n}\n\nfunction getFileStorage(fileSystem) {\n if (fileSystem._readFileStorage) {\n // Webpack v4\n return fileSystem._readFileStorage;\n } else if (fileSystem._readFileBackend) {\n // Webpack v5\n return fileSystem._readFileBackend;\n } else {\n throw new Error(\"Couldn't find a readFileStorage\");\n }\n}\n\nfunction getReadDirBackend(fileSystem) {\n if (fileSystem._readdirBackend) {\n return fileSystem._readdirBackend;\n } else if (fileSystem._readdirStorage) {\n return fileSystem._readdirStorage;\n } else {\n throw new Error(\"Couldn't find a readDirStorage from Webpack Internals\");\n }\n}\n\nclass VirtualModulesPlugin {\n private _staticModules: Record | null;\n private _compiler: Compiler | null = null;\n private _watcher: any = null;\n\n public constructor(modules?: Record) {\n this._staticModules = modules || null;\n }\n\n public getModuleList(filter: AvailableModules = ALL) {\n let modules = {};\n const shouldGetStaticModules = filter === ALL || filter === STATIC;\n const shouldGetDynamicModules = filter === ALL || filter === DYNAMIC;\n\n if (shouldGetStaticModules) {\n // Get static modules\n modules = {\n ...modules,\n ...this._staticModules,\n };\n }\n\n if (shouldGetDynamicModules) {\n // Get dynamic modules\n const finalInputFileSystem: any = this._compiler?.inputFileSystem;\n const virtualFiles = finalInputFileSystem?._virtualFiles ?? {};\n\n const dynamicModules: Record = {};\n Object.keys(virtualFiles).forEach((key: string) => {\n dynamicModules[key] = virtualFiles[key].contents;\n });\n\n modules = {\n ...modules,\n ...dynamicModules,\n };\n }\n\n return modules;\n }\n\n public writeModule(filePath: string, contents: string): void {\n if (!this._compiler) {\n throw new Error(`Plugin has not been initialized`);\n }\n\n checkActivation(this);\n\n const len = contents ? contents.length : 0;\n const time = Date.now();\n const date = new Date(time);\n\n const stats = new VirtualStats({\n dev: 8675309,\n nlink: 0,\n uid: 1000,\n gid: 1000,\n rdev: 0,\n blksize: 4096,\n ino: inode++,\n mode: 33188,\n size: len,\n blocks: Math.floor(len / 4096),\n atime: date,\n mtime: date,\n ctime: date,\n birthtime: date,\n });\n const modulePath = getModulePath(filePath, this._compiler);\n\n if (process.env.WVM_DEBUG)\n // eslint-disable-next-line no-console\n console.log(this._compiler.name, 'Write virtual module:', modulePath, contents);\n\n // When using the WatchIgnorePlugin (https://github.com/webpack/webpack/blob/52184b897f40c75560b3630e43ca642fcac7e2cf/lib/WatchIgnorePlugin.js),\n // the original watchFileSystem is stored in `wfs`. The following \"unwraps\" the ignoring\n // wrappers, giving us access to the \"real\" watchFileSystem.\n let finalWatchFileSystem = this._watcher && this._watcher.watchFileSystem;\n\n while (finalWatchFileSystem && finalWatchFileSystem.wfs) {\n finalWatchFileSystem = finalWatchFileSystem.wfs;\n }\n\n let finalInputFileSystem: any = this._compiler.inputFileSystem;\n while (finalInputFileSystem && finalInputFileSystem._inputFileSystem) {\n finalInputFileSystem = finalInputFileSystem._inputFileSystem;\n }\n\n finalInputFileSystem._writeVirtualFile(modulePath, stats, contents);\n if (\n finalWatchFileSystem &&\n finalWatchFileSystem.watcher &&\n (finalWatchFileSystem.watcher.fileWatchers.size || finalWatchFileSystem.watcher.fileWatchers.length)\n ) {\n const fileWatchers =\n finalWatchFileSystem.watcher.fileWatchers instanceof Map\n ? Array.from(finalWatchFileSystem.watcher.fileWatchers.values())\n : finalWatchFileSystem.watcher.fileWatchers;\n for (let fileWatcher of fileWatchers) {\n if ('watcher' in fileWatcher) {\n fileWatcher = fileWatcher.watcher;\n }\n if (fileWatcher.path === modulePath) {\n if (process.env.DEBUG)\n // eslint-disable-next-line no-console\n console.log(this._compiler.name, 'Emit file change:', modulePath, time);\n delete fileWatcher.directoryWatcher._cachedTimeInfoEntries;\n fileWatcher.emit('change', time, null);\n }\n }\n }\n }\n\n public apply(compiler: Compiler) {\n this._compiler = compiler;\n\n const afterEnvironmentHook = () => {\n let finalInputFileSystem: any = compiler.inputFileSystem;\n while (finalInputFileSystem && finalInputFileSystem._inputFileSystem) {\n finalInputFileSystem = finalInputFileSystem._inputFileSystem;\n }\n\n if (!finalInputFileSystem._writeVirtualFile) {\n const originalPurge = finalInputFileSystem.purge;\n\n finalInputFileSystem.purge = () => {\n originalPurge.apply(finalInputFileSystem, []);\n if (finalInputFileSystem._virtualFiles) {\n Object.keys(finalInputFileSystem._virtualFiles).forEach((file) => {\n const data = finalInputFileSystem._virtualFiles[file];\n finalInputFileSystem._writeVirtualFile(file, data.stats, data.contents);\n });\n }\n };\n\n finalInputFileSystem._writeVirtualFile = (file, stats, contents) => {\n const statStorage = getStatStorage(finalInputFileSystem);\n const fileStorage = getFileStorage(finalInputFileSystem);\n const readDirStorage = getReadDirBackend(finalInputFileSystem);\n finalInputFileSystem._virtualFiles = finalInputFileSystem._virtualFiles || {};\n finalInputFileSystem._virtualFiles[file] = { stats: stats, contents: contents };\n setData(statStorage, file, createWebpackData(stats));\n setData(fileStorage, file, createWebpackData(contents));\n const segments = file.split(/[\\\\/]/);\n let count = segments.length - 1;\n const minCount = segments[0] ? 1 : 0;\n while (count > minCount) {\n const dir = segments.slice(0, count).join(path.sep) || path.sep;\n try {\n finalInputFileSystem.readdirSync(dir);\n } catch (e) {\n const time = Date.now();\n const dirStats = new VirtualStats({\n dev: 8675309,\n nlink: 0,\n uid: 1000,\n gid: 1000,\n rdev: 0,\n blksize: 4096,\n ino: inode++,\n mode: 16877,\n size: stats.size,\n blocks: Math.floor(stats.size / 4096),\n atime: time,\n mtime: time,\n ctime: time,\n birthtime: time,\n });\n\n setData(readDirStorage, dir, createWebpackData([]));\n setData(statStorage, dir, createWebpackData(dirStats));\n }\n let dirData = getData(getReadDirBackend(finalInputFileSystem), dir);\n // Webpack v4 returns an array, webpack v5 returns an object\n dirData = dirData[1] || dirData.result;\n const filename = segments[count];\n if (dirData.indexOf(filename) < 0) {\n const files = dirData.concat([filename]).sort();\n setData(getReadDirBackend(finalInputFileSystem), dir, createWebpackData(files));\n } else {\n break;\n }\n count--;\n }\n };\n }\n };\n const afterResolversHook = () => {\n if (this._staticModules) {\n for (const [filePath, contents] of Object.entries(this._staticModules)) {\n this.writeModule(filePath, contents);\n }\n this._staticModules = null;\n }\n };\n\n // The webpack property is not exposed in webpack v4\n const version = typeof (compiler as any).webpack === 'undefined' ? 4 : 5;\n\n const watchRunHook = (watcher, callback) => {\n this._watcher = watcher.compiler || watcher;\n const virtualFiles = (compiler as any).inputFileSystem._virtualFiles;\n const fts = compiler.fileTimestamps as any;\n\n if (virtualFiles && fts && typeof fts.set === 'function') {\n Object.keys(virtualFiles).forEach((file) => {\n const mtime = +virtualFiles[file].stats.mtime;\n // fts is\n // Map in webpack 4\n // Map in webpack 5\n fts.set(\n file,\n version === 4\n ? mtime\n : {\n safeTime: mtime,\n timestamp: mtime,\n }\n );\n });\n }\n callback();\n };\n\n if (compiler.hooks) {\n compiler.hooks.afterEnvironment.tap('VirtualModulesPlugin', afterEnvironmentHook);\n compiler.hooks.afterResolvers.tap('VirtualModulesPlugin', afterResolversHook);\n compiler.hooks.watchRun.tapAsync('VirtualModulesPlugin', watchRunHook);\n } else {\n (compiler as any).plugin('after-environment', afterEnvironmentHook);\n (compiler as any).plugin('after-resolvers', afterResolversHook);\n (compiler as any).plugin('watch-run', watchRunHook);\n }\n }\n}\n\nexport = VirtualModulesPlugin;\n","/*!\n * is-extglob \n *\n * Copyright (c) 2014-2016, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\nmodule.exports = function isExtglob(str) {\n if (typeof str !== 'string' || str === '') {\n return false;\n }\n\n var match;\n while ((match = /(\\\\).|([@?!+*]\\(.*\\))/g.exec(str))) {\n if (match[2]) return true;\n str = str.slice(match.index + match[0].length);\n }\n\n return false;\n};\n","/*!\n * is-glob \n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\nvar isExtglob = require('is-extglob');\nvar chars = { '{': '}', '(': ')', '[': ']'};\nvar strictCheck = function(str) {\n if (str[0] === '!') {\n return true;\n }\n var index = 0;\n var pipeIndex = -2;\n var closeSquareIndex = -2;\n var closeCurlyIndex = -2;\n var closeParenIndex = -2;\n var backSlashIndex = -2;\n while (index < str.length) {\n if (str[index] === '*') {\n return true;\n }\n\n if (str[index + 1] === '?' && /[\\].+)]/.test(str[index])) {\n return true;\n }\n\n if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {\n if (closeSquareIndex < index) {\n closeSquareIndex = str.indexOf(']', index);\n }\n if (closeSquareIndex > index) {\n if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {\n return true;\n }\n backSlashIndex = str.indexOf('\\\\', index);\n if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {\n return true;\n }\n }\n }\n\n if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {\n closeCurlyIndex = str.indexOf('}', index);\n if (closeCurlyIndex > index) {\n backSlashIndex = str.indexOf('\\\\', index);\n if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {\n return true;\n }\n }\n }\n\n if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {\n closeParenIndex = str.indexOf(')', index);\n if (closeParenIndex > index) {\n backSlashIndex = str.indexOf('\\\\', index);\n if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {\n return true;\n }\n }\n }\n\n if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {\n if (pipeIndex < index) {\n pipeIndex = str.indexOf('|', index);\n }\n if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {\n closeParenIndex = str.indexOf(')', pipeIndex);\n if (closeParenIndex > pipeIndex) {\n backSlashIndex = str.indexOf('\\\\', pipeIndex);\n if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {\n return true;\n }\n }\n }\n }\n\n if (str[index] === '\\\\') {\n var open = str[index + 1];\n index += 2;\n var close = chars[open];\n\n if (close) {\n var n = str.indexOf(close, index);\n if (n !== -1) {\n index = n + 1;\n }\n }\n\n if (str[index] === '!') {\n return true;\n }\n } else {\n index++;\n }\n }\n return false;\n};\n\nvar relaxedCheck = function(str) {\n if (str[0] === '!') {\n return true;\n }\n var index = 0;\n while (index < str.length) {\n if (/[*?{}()[\\]]/.test(str[index])) {\n return true;\n }\n\n if (str[index] === '\\\\') {\n var open = str[index + 1];\n index += 2;\n var close = chars[open];\n\n if (close) {\n var n = str.indexOf(close, index);\n if (n !== -1) {\n index = n + 1;\n }\n }\n\n if (str[index] === '!') {\n return true;\n }\n } else {\n index++;\n }\n }\n return false;\n};\n\nmodule.exports = function isGlob(str, options) {\n if (typeof str !== 'string' || str === '') {\n return false;\n }\n\n if (isExtglob(str)) {\n return true;\n }\n\n var check = strictCheck;\n\n // optionally relax check\n if (options && options.strict === false) {\n check = relaxedCheck;\n }\n\n return check(str);\n};\n","'use strict';\nmodule.exports = balanced;\nfunction balanced(a, b, str) {\n if (a instanceof RegExp) a = maybeMatch(a, str);\n if (b instanceof RegExp) b = maybeMatch(b, str);\n\n var r = range(a, b, str);\n\n return r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + a.length, r[1]),\n post: str.slice(r[1] + b.length)\n };\n}\n\nfunction maybeMatch(reg, str) {\n var m = str.match(reg);\n return m ? m[0] : null;\n}\n\nbalanced.range = range;\nfunction range(a, b, str) {\n var begs, beg, left, right, result;\n var ai = str.indexOf(a);\n var bi = str.indexOf(b, ai + 1);\n var i = ai;\n\n if (ai >= 0 && bi > 0) {\n if(a===b) {\n return [ai, bi];\n }\n begs = [];\n left = str.length;\n\n while (i >= 0 && !result) {\n if (i == ai) {\n begs.push(i);\n ai = str.indexOf(a, i + 1);\n } else if (begs.length == 1) {\n result = [ begs.pop(), bi ];\n } else {\n beg = begs.pop();\n if (beg < left) {\n left = beg;\n right = bi;\n }\n\n bi = str.indexOf(b, i + 1);\n }\n\n i = ai < bi && ai >= 0 ? ai : bi;\n }\n\n if (begs.length) {\n result = [ left, right ];\n }\n }\n\n return result;\n}\n","var balanced = require('balanced-match');\n\nmodule.exports = expandTop;\n\nvar escSlash = '\\0SLASH'+Math.random()+'\\0';\nvar escOpen = '\\0OPEN'+Math.random()+'\\0';\nvar escClose = '\\0CLOSE'+Math.random()+'\\0';\nvar escComma = '\\0COMMA'+Math.random()+'\\0';\nvar escPeriod = '\\0PERIOD'+Math.random()+'\\0';\n\nfunction numeric(str) {\n return parseInt(str, 10) == str\n ? parseInt(str, 10)\n : str.charCodeAt(0);\n}\n\nfunction escapeBraces(str) {\n return str.split('\\\\\\\\').join(escSlash)\n .split('\\\\{').join(escOpen)\n .split('\\\\}').join(escClose)\n .split('\\\\,').join(escComma)\n .split('\\\\.').join(escPeriod);\n}\n\nfunction unescapeBraces(str) {\n return str.split(escSlash).join('\\\\')\n .split(escOpen).join('{')\n .split(escClose).join('}')\n .split(escComma).join(',')\n .split(escPeriod).join('.');\n}\n\n\n// Basically just str.split(\",\"), but handling cases\n// where we have nested braced sections, which should be\n// treated as individual members, like {a,{b,c},d}\nfunction parseCommaParts(str) {\n if (!str)\n return [''];\n\n var parts = [];\n var m = balanced('{', '}', str);\n\n if (!m)\n return str.split(',');\n\n var pre = m.pre;\n var body = m.body;\n var post = m.post;\n var p = pre.split(',');\n\n p[p.length-1] += '{' + body + '}';\n var postParts = parseCommaParts(post);\n if (post.length) {\n p[p.length-1] += postParts.shift();\n p.push.apply(p, postParts);\n }\n\n parts.push.apply(parts, p);\n\n return parts;\n}\n\nfunction expandTop(str) {\n if (!str)\n return [];\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.substr(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.substr(2);\n }\n\n return expand(escapeBraces(str), true).map(unescapeBraces);\n}\n\nfunction embrace(str) {\n return '{' + str + '}';\n}\nfunction isPadded(el) {\n return /^-?0\\d/.test(el);\n}\n\nfunction lte(i, y) {\n return i <= y;\n}\nfunction gte(i, y) {\n return i >= y;\n}\n\nfunction expand(str, isTop) {\n var expansions = [];\n\n var m = balanced('{', '}', str);\n if (!m) return [str];\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n var pre = m.pre;\n var post = m.post.length\n ? expand(m.post, false)\n : [''];\n\n if (/\\$$/.test(m.pre)) { \n for (var k = 0; k < post.length; k++) {\n var expansion = pre+ '{' + m.body + '}' + post[k];\n expansions.push(expansion);\n }\n } else {\n var isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body);\n var isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body);\n var isSequence = isNumericSequence || isAlphaSequence;\n var isOptions = m.body.indexOf(',') >= 0;\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,.*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post;\n return expand(str);\n }\n return [str];\n }\n\n var n;\n if (isSequence) {\n n = m.body.split(/\\.\\./);\n } else {\n n = parseCommaParts(m.body);\n if (n.length === 1) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand(n[0], false).map(embrace);\n if (n.length === 1) {\n return post.map(function(p) {\n return m.pre + n[0] + p;\n });\n }\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n var N;\n\n if (isSequence) {\n var x = numeric(n[0]);\n var y = numeric(n[1]);\n var width = Math.max(n[0].length, n[1].length)\n var incr = n.length == 3\n ? Math.abs(numeric(n[2]))\n : 1;\n var test = lte;\n var reverse = y < x;\n if (reverse) {\n incr *= -1;\n test = gte;\n }\n var pad = n.some(isPadded);\n\n N = [];\n\n for (var i = x; test(i, y); i += incr) {\n var c;\n if (isAlphaSequence) {\n c = String.fromCharCode(i);\n if (c === '\\\\')\n c = '';\n } else {\n c = String(i);\n if (pad) {\n var need = width - c.length;\n if (need > 0) {\n var z = new Array(need + 1).join('0');\n if (i < 0)\n c = '-' + z + c.slice(1);\n else\n c = z + c;\n }\n }\n }\n N.push(c);\n }\n } else {\n N = [];\n\n for (var j = 0; j < n.length; j++) {\n N.push.apply(N, expand(n[j], false));\n }\n }\n\n for (var j = 0; j < N.length; j++) {\n for (var k = 0; k < post.length; k++) {\n var expansion = pre + N[j] + post[k];\n if (!isTop || isSequence || expansion)\n expansions.push(expansion);\n }\n }\n }\n\n return expansions;\n}\n\n","'use strict';\n\nconst nameStartChar = ':A-Za-z_\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD';\nconst nameChar = nameStartChar + '\\\\-.\\\\d\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040';\nconst nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*'\nconst regexName = new RegExp('^' + nameRegexp + '$');\n\nconst getAllMatches = function(string, regex) {\n const matches = [];\n let match = regex.exec(string);\n while (match) {\n const allmatches = [];\n allmatches.startIndex = regex.lastIndex - match[0].length;\n const len = match.length;\n for (let index = 0; index < len; index++) {\n allmatches.push(match[index]);\n }\n matches.push(allmatches);\n match = regex.exec(string);\n }\n return matches;\n};\n\nconst isName = function(string) {\n const match = regexName.exec(string);\n return !(match === null || typeof match === 'undefined');\n};\n\nexports.isExist = function(v) {\n return typeof v !== 'undefined';\n};\n\nexports.isEmptyObject = function(obj) {\n return Object.keys(obj).length === 0;\n};\n\n/**\n * Copy all the properties of a into b.\n * @param {*} target\n * @param {*} a\n */\nexports.merge = function(target, a, arrayMode) {\n if (a) {\n const keys = Object.keys(a); // will return an array of own properties\n const len = keys.length; //don't make it inline\n for (let i = 0; i < len; i++) {\n if (arrayMode === 'strict') {\n target[keys[i]] = [ a[keys[i]] ];\n } else {\n target[keys[i]] = a[keys[i]];\n }\n }\n }\n};\n/* exports.merge =function (b,a){\n return Object.assign(b,a);\n} */\n\nexports.getValue = function(v) {\n if (exports.isExist(v)) {\n return v;\n } else {\n return '';\n }\n};\n\n// const fakeCall = function(a) {return a;};\n// const fakeCallNoReturn = function() {};\n\nexports.isName = isName;\nexports.getAllMatches = getAllMatches;\nexports.nameRegexp = nameRegexp;\n","'use strict';\n\nconst util = require('./util');\n\nconst defaultOptions = {\n allowBooleanAttributes: false, //A tag can have attributes without any value\n unpairedTags: []\n};\n\n//const tagsPattern = new RegExp(\"<\\\\/?([\\\\w:\\\\-_\\.]+)\\\\s*\\/?>\",\"g\");\nexports.validate = function (xmlData, options) {\n options = Object.assign({}, defaultOptions, options);\n\n //xmlData = xmlData.replace(/(\\r\\n|\\n|\\r)/gm,\"\");//make it single line\n //xmlData = xmlData.replace(/(^\\s*<\\?xml.*?\\?>)/g,\"\");//Remove XML starting tag\n //xmlData = xmlData.replace(/()/g,\"\");//Remove DOCTYPE\n const tags = [];\n let tagFound = false;\n\n //indicates that the root tag has been closed (aka. depth 0 has been reached)\n let reachedRoot = false;\n\n if (xmlData[0] === '\\ufeff') {\n // check for byte order mark (BOM)\n xmlData = xmlData.substr(1);\n }\n \n for (let i = 0; i < xmlData.length; i++) {\n\n if (xmlData[i] === '<' && xmlData[i+1] === '?') {\n i+=2;\n i = readPI(xmlData,i);\n if (i.err) return i;\n }else if (xmlData[i] === '<') {\n //starting of tag\n //read until you reach to '>' avoiding any '>' in attribute value\n let tagStartPos = i;\n i++;\n \n if (xmlData[i] === '!') {\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else {\n let closingTag = false;\n if (xmlData[i] === '/') {\n //closing tag\n closingTag = true;\n i++;\n }\n //read tagname\n let tagName = '';\n for (; i < xmlData.length &&\n xmlData[i] !== '>' &&\n xmlData[i] !== ' ' &&\n xmlData[i] !== '\\t' &&\n xmlData[i] !== '\\n' &&\n xmlData[i] !== '\\r'; i++\n ) {\n tagName += xmlData[i];\n }\n tagName = tagName.trim();\n //console.log(tagName);\n\n if (tagName[tagName.length - 1] === '/') {\n //self closing tag without attributes\n tagName = tagName.substring(0, tagName.length - 1);\n //continue;\n i--;\n }\n if (!validateTagName(tagName)) {\n let msg;\n if (tagName.trim().length === 0) {\n msg = \"Invalid space after '<'.\";\n } else {\n msg = \"Tag '\"+tagName+\"' is an invalid name.\";\n }\n return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));\n }\n\n const result = readAttributeStr(xmlData, i);\n if (result === false) {\n return getErrorObject('InvalidAttr', \"Attributes for '\"+tagName+\"' have open quote.\", getLineNumberForPosition(xmlData, i));\n }\n let attrStr = result.value;\n i = result.index;\n\n if (attrStr[attrStr.length - 1] === '/') {\n //self closing tag\n const attrStrStart = i - attrStr.length;\n attrStr = attrStr.substring(0, attrStr.length - 1);\n const isValid = validateAttributeString(attrStr, options);\n if (isValid === true) {\n tagFound = true;\n //continue; //text may presents after self closing tag\n } else {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));\n }\n } else if (closingTag) {\n if (!result.tagClosed) {\n return getErrorObject('InvalidTag', \"Closing tag '\"+tagName+\"' doesn't have proper closing.\", getLineNumberForPosition(xmlData, i));\n } else if (attrStr.trim().length > 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\"+tagName+\"' can't have attributes or invalid starting.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else {\n const otg = tags.pop();\n if (tagName !== otg.tagName) {\n let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);\n return getErrorObject('InvalidTag',\n \"Expected closing tag '\"+otg.tagName+\"' (opened in line \"+openPos.line+\", col \"+openPos.col+\") instead of closing tag '\"+tagName+\"'.\",\n getLineNumberForPosition(xmlData, tagStartPos));\n }\n\n //when there are no more tags, we reached the root level.\n if (tags.length == 0) {\n reachedRoot = true;\n }\n }\n } else {\n const isValid = validateAttributeString(attrStr, options);\n if (isValid !== true) {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));\n }\n\n //if the root level has been reached before ...\n if (reachedRoot === true) {\n return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));\n } else if(options.unpairedTags.indexOf(tagName) !== -1){\n //don't push into stack\n } else {\n tags.push({tagName, tagStartPos});\n }\n tagFound = true;\n }\n\n //skip tag text value\n //It may include comments and CDATA value\n for (i++; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n if (xmlData[i + 1] === '!') {\n //comment or CADATA\n i++;\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else if (xmlData[i+1] === '?') {\n i = readPI(xmlData, ++i);\n if (i.err) return i;\n } else{\n break;\n }\n } else if (xmlData[i] === '&') {\n const afterAmp = validateAmpersand(xmlData, i);\n if (afterAmp == -1)\n return getErrorObject('InvalidChar', \"char '&' is not expected.\", getLineNumberForPosition(xmlData, i));\n i = afterAmp;\n }else{\n if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {\n return getErrorObject('InvalidXml', \"Extra text at the end\", getLineNumberForPosition(xmlData, i));\n }\n }\n } //end of reading tag text value\n if (xmlData[i] === '<') {\n i--;\n }\n }\n } else {\n if ( isWhiteSpace(xmlData[i])) {\n continue;\n }\n return getErrorObject('InvalidChar', \"char '\"+xmlData[i]+\"' is not expected.\", getLineNumberForPosition(xmlData, i));\n }\n }\n\n if (!tagFound) {\n return getErrorObject('InvalidXml', 'Start tag expected.', 1);\n }else if (tags.length == 1) {\n return getErrorObject('InvalidTag', \"Unclosed tag '\"+tags[0].tagName+\"'.\", getLineNumberForPosition(xmlData, tags[0].tagStartPos));\n }else if (tags.length > 0) {\n return getErrorObject('InvalidXml', \"Invalid '\"+\n JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\\r?\\n/g, '')+\n \"' found.\", {line: 1, col: 1});\n }\n\n return true;\n};\n\nfunction isWhiteSpace(char){\n return char === ' ' || char === '\\t' || char === '\\n' || char === '\\r';\n}\n/**\n * Read Processing insstructions and skip\n * @param {*} xmlData\n * @param {*} i\n */\nfunction readPI(xmlData, i) {\n const start = i;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] == '?' || xmlData[i] == ' ') {\n //tagname\n const tagname = xmlData.substr(start, i - start);\n if (i > 5 && tagname === 'xml') {\n return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));\n } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {\n //check if valid attribut string\n i++;\n break;\n } else {\n continue;\n }\n }\n }\n return i;\n}\n\nfunction readCommentAndCDATA(xmlData, i) {\n if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {\n //comment\n for (i += 3; i < xmlData.length; i++) {\n if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n } else if (\n xmlData.length > i + 8 &&\n xmlData[i + 1] === 'D' &&\n xmlData[i + 2] === 'O' &&\n xmlData[i + 3] === 'C' &&\n xmlData[i + 4] === 'T' &&\n xmlData[i + 5] === 'Y' &&\n xmlData[i + 6] === 'P' &&\n xmlData[i + 7] === 'E'\n ) {\n let angleBracketsCount = 1;\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n angleBracketsCount++;\n } else if (xmlData[i] === '>') {\n angleBracketsCount--;\n if (angleBracketsCount === 0) {\n break;\n }\n }\n }\n } else if (\n xmlData.length > i + 9 &&\n xmlData[i + 1] === '[' &&\n xmlData[i + 2] === 'C' &&\n xmlData[i + 3] === 'D' &&\n xmlData[i + 4] === 'A' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'A' &&\n xmlData[i + 7] === '['\n ) {\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n }\n\n return i;\n}\n\nconst doubleQuote = '\"';\nconst singleQuote = \"'\";\n\n/**\n * Keep reading xmlData until '<' is found outside the attribute value.\n * @param {string} xmlData\n * @param {number} i\n */\nfunction readAttributeStr(xmlData, i) {\n let attrStr = '';\n let startChar = '';\n let tagClosed = false;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {\n if (startChar === '') {\n startChar = xmlData[i];\n } else if (startChar !== xmlData[i]) {\n //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa\n } else {\n startChar = '';\n }\n } else if (xmlData[i] === '>') {\n if (startChar === '') {\n tagClosed = true;\n break;\n }\n }\n attrStr += xmlData[i];\n }\n if (startChar !== '') {\n return false;\n }\n\n return {\n value: attrStr,\n index: i,\n tagClosed: tagClosed\n };\n}\n\n/**\n * Select all the attributes whether valid or invalid.\n */\nconst validAttrStrRegxp = new RegExp('(\\\\s*)([^\\\\s=]+)(\\\\s*=)?(\\\\s*([\\'\"])(([\\\\s\\\\S])*?)\\\\5)?', 'g');\n\n//attr, =\"sd\", a=\"amit's\", a=\"sd\"b=\"saf\", ab cd=\"\"\n\nfunction validateAttributeString(attrStr, options) {\n //console.log(\"start:\"+attrStr+\":end\");\n\n //if(attrStr.trim().length === 0) return true; //empty string\n\n const matches = util.getAllMatches(attrStr, validAttrStrRegxp);\n const attrNames = {};\n\n for (let i = 0; i < matches.length; i++) {\n if (matches[i][1].length === 0) {\n //nospace before attribute name: a=\"sd\"b=\"saf\"\n return getErrorObject('InvalidAttr', \"Attribute '\"+matches[i][2]+\"' has no space in starting.\", getPositionFromMatch(matches[i]))\n } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {\n return getErrorObject('InvalidAttr', \"Attribute '\"+matches[i][2]+\"' is without value.\", getPositionFromMatch(matches[i]));\n } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {\n //independent attribute: ab\n return getErrorObject('InvalidAttr', \"boolean attribute '\"+matches[i][2]+\"' is not allowed.\", getPositionFromMatch(matches[i]));\n }\n /* else if(matches[i][6] === undefined){//attribute without value: ab=\n return { err: { code:\"InvalidAttr\",msg:\"attribute \" + matches[i][2] + \" has no value assigned.\"}};\n } */\n const attrName = matches[i][2];\n if (!validateAttrName(attrName)) {\n return getErrorObject('InvalidAttr', \"Attribute '\"+attrName+\"' is an invalid name.\", getPositionFromMatch(matches[i]));\n }\n if (!attrNames.hasOwnProperty(attrName)) {\n //check for duplicate attribute.\n attrNames[attrName] = 1;\n } else {\n return getErrorObject('InvalidAttr', \"Attribute '\"+attrName+\"' is repeated.\", getPositionFromMatch(matches[i]));\n }\n }\n\n return true;\n}\n\nfunction validateNumberAmpersand(xmlData, i) {\n let re = /\\d/;\n if (xmlData[i] === 'x') {\n i++;\n re = /[\\da-fA-F]/;\n }\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === ';')\n return i;\n if (!xmlData[i].match(re))\n break;\n }\n return -1;\n}\n\nfunction validateAmpersand(xmlData, i) {\n // https://www.w3.org/TR/xml/#dt-charref\n i++;\n if (xmlData[i] === ';')\n return -1;\n if (xmlData[i] === '#') {\n i++;\n return validateNumberAmpersand(xmlData, i);\n }\n let count = 0;\n for (; i < xmlData.length; i++, count++) {\n if (xmlData[i].match(/\\w/) && count < 20)\n continue;\n if (xmlData[i] === ';')\n break;\n return -1;\n }\n return i;\n}\n\nfunction getErrorObject(code, message, lineNumber) {\n return {\n err: {\n code: code,\n msg: message,\n line: lineNumber.line || lineNumber,\n col: lineNumber.col,\n },\n };\n}\n\nfunction validateAttrName(attrName) {\n return util.isName(attrName);\n}\n\n// const startsWithXML = /^xml/i;\n\nfunction validateTagName(tagname) {\n return util.isName(tagname) /* && !tagname.match(startsWithXML) */;\n}\n\n//this function returns the line number for the character at the given index\nfunction getLineNumberForPosition(xmlData, index) {\n const lines = xmlData.substring(0, index).split(/\\r?\\n/);\n return {\n line: lines.length,\n\n // column number is last line's length + 1, because column numbering starts at 1:\n col: lines[lines.length - 1].length + 1\n };\n}\n\n//this function returns the position of the first character of match within attrStr\nfunction getPositionFromMatch(match) {\n return match.startIndex + match[1].length;\n}\n","\nconst defaultOptions = {\n preserveOrder: false,\n attributeNamePrefix: '@_',\n attributesGroupName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n removeNSPrefix: false, // remove NS from tag name or attribute name if true\n allowBooleanAttributes: false, //a tag can have attributes without any value\n //ignoreRootElement : false,\n parseTagValue: true,\n parseAttributeValue: false,\n trimValues: true, //Trim string values of tag and attributes\n cdataPropName: false,\n numberParseOptions: {\n hex: true,\n leadingZeros: true,\n eNotation: true\n },\n tagValueProcessor: function(tagName, val) {\n return val;\n },\n attributeValueProcessor: function(attrName, val) {\n return val;\n },\n stopNodes: [], //nested tags will not be parsed even for errors\n alwaysCreateTextNode: false,\n isArray: () => false,\n commentPropName: false,\n unpairedTags: [],\n processEntities: true,\n htmlEntities: false,\n ignoreDeclaration: false,\n ignorePiTags: false,\n transformTagName: false,\n transformAttributeName: false,\n updateTag: function(tagName, jPath, attrs){\n return tagName\n },\n // skipEmptyListItem: false\n};\n \nconst buildOptions = function(options) {\n return Object.assign({}, defaultOptions, options);\n};\n\nexports.buildOptions = buildOptions;\nexports.defaultOptions = defaultOptions;","'use strict';\n\nclass XmlNode{\n constructor(tagname) {\n this.tagname = tagname;\n this.child = []; //nested tags, text, cdata, comments in order\n this[\":@\"] = {}; //attributes map\n }\n add(key,val){\n // this.child.push( {name : key, val: val, isCdata: isCdata });\n if(key === \"__proto__\") key = \"#__proto__\";\n this.child.push( {[key]: val });\n }\n addChild(node) {\n if(node.tagname === \"__proto__\") node.tagname = \"#__proto__\";\n if(node[\":@\"] && Object.keys(node[\":@\"]).length > 0){\n this.child.push( { [node.tagname]: node.child, [\":@\"]: node[\":@\"] });\n }else{\n this.child.push( { [node.tagname]: node.child });\n }\n };\n};\n\n\nmodule.exports = XmlNode;","const util = require('../util');\n\n//TODO: handle comments\nfunction readDocType(xmlData, i){\n \n const entities = {};\n if( xmlData[i + 3] === 'O' &&\n xmlData[i + 4] === 'C' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'Y' &&\n xmlData[i + 7] === 'P' &&\n xmlData[i + 8] === 'E')\n { \n i = i+9;\n let angleBracketsCount = 1;\n let hasBody = false, comment = false;\n let exp = \"\";\n for(;i') { //Read tag content\n if(comment){\n if( xmlData[i - 1] === \"-\" && xmlData[i - 2] === \"-\"){\n comment = false;\n angleBracketsCount--;\n }\n }else{\n angleBracketsCount--;\n }\n if (angleBracketsCount === 0) {\n break;\n }\n }else if( xmlData[i] === '['){\n hasBody = true;\n }else{\n exp += xmlData[i];\n }\n }\n if(angleBracketsCount !== 0){\n throw new Error(`Unclosed DOCTYPE`);\n }\n }else{\n throw new Error(`Invalid Tag instead of DOCTYPE`);\n }\n return {entities, i};\n}\n\nfunction readEntityExp(xmlData,i){\n //External entities are not supported\n // \n\n //Parameter entities are not supported\n // \n\n //Internal entities are supported\n // \n \n //read EntityName\n let entityName = \"\";\n for (; i < xmlData.length && (xmlData[i] !== \"'\" && xmlData[i] !== '\"' ); i++) {\n // if(xmlData[i] === \" \") continue;\n // else \n entityName += xmlData[i];\n }\n entityName = entityName.trim();\n if(entityName.indexOf(\" \") !== -1) throw new Error(\"External entites are not supported\");\n\n //read Entity Value\n const startChar = xmlData[i++];\n let val = \"\"\n for (; i < xmlData.length && xmlData[i] !== startChar ; i++) {\n val += xmlData[i];\n }\n return [entityName, val, i];\n}\n\nfunction isComment(xmlData, i){\n if(xmlData[i+1] === '!' &&\n xmlData[i+2] === '-' &&\n xmlData[i+3] === '-') return true\n return false\n}\nfunction isEntity(xmlData, i){\n if(xmlData[i+1] === '!' &&\n xmlData[i+2] === 'E' &&\n xmlData[i+3] === 'N' &&\n xmlData[i+4] === 'T' &&\n xmlData[i+5] === 'I' &&\n xmlData[i+6] === 'T' &&\n xmlData[i+7] === 'Y') return true\n return false\n}\nfunction isElement(xmlData, i){\n if(xmlData[i+1] === '!' &&\n xmlData[i+2] === 'E' &&\n xmlData[i+3] === 'L' &&\n xmlData[i+4] === 'E' &&\n xmlData[i+5] === 'M' &&\n xmlData[i+6] === 'E' &&\n xmlData[i+7] === 'N' &&\n xmlData[i+8] === 'T') return true\n return false\n}\n\nfunction isAttlist(xmlData, i){\n if(xmlData[i+1] === '!' &&\n xmlData[i+2] === 'A' &&\n xmlData[i+3] === 'T' &&\n xmlData[i+4] === 'T' &&\n xmlData[i+5] === 'L' &&\n xmlData[i+6] === 'I' &&\n xmlData[i+7] === 'S' &&\n xmlData[i+8] === 'T') return true\n return false\n}\nfunction isNotation(xmlData, i){\n if(xmlData[i+1] === '!' &&\n xmlData[i+2] === 'N' &&\n xmlData[i+3] === 'O' &&\n xmlData[i+4] === 'T' &&\n xmlData[i+5] === 'A' &&\n xmlData[i+6] === 'T' &&\n xmlData[i+7] === 'I' &&\n xmlData[i+8] === 'O' &&\n xmlData[i+9] === 'N') return true\n return false\n}\n\nfunction validateEntityName(name){\n if (util.isName(name))\n\treturn name;\n else\n throw new Error(`Invalid entity name ${name}`);\n}\n\nmodule.exports = readDocType;\n","const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;\nconst numRegex = /^([\\-\\+])?(0*)(\\.[0-9]+([eE]\\-?[0-9]+)?|[0-9]+(\\.[0-9]+([eE]\\-?[0-9]+)?)?)$/;\n// const octRegex = /0x[a-z0-9]+/;\n// const binRegex = /0x[a-z0-9]+/;\n\n\n//polyfill\nif (!Number.parseInt && window.parseInt) {\n Number.parseInt = window.parseInt;\n}\nif (!Number.parseFloat && window.parseFloat) {\n Number.parseFloat = window.parseFloat;\n}\n\n \nconst consider = {\n hex : true,\n leadingZeros: true,\n decimalPoint: \"\\.\",\n eNotation: true\n //skipLike: /regex/\n};\n\nfunction toNumber(str, options = {}){\n // const options = Object.assign({}, consider);\n // if(opt.leadingZeros === false){\n // options.leadingZeros = false;\n // }else if(opt.hex === false){\n // options.hex = false;\n // }\n\n options = Object.assign({}, consider, options );\n if(!str || typeof str !== \"string\" ) return str;\n \n let trimmedStr = str.trim();\n // if(trimmedStr === \"0.0\") return 0;\n // else if(trimmedStr === \"+0.0\") return 0;\n // else if(trimmedStr === \"-0.0\") return -0;\n\n if(options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str;\n else if (options.hex && hexRegex.test(trimmedStr)) {\n return Number.parseInt(trimmedStr, 16);\n // } else if (options.parseOct && octRegex.test(str)) {\n // return Number.parseInt(val, 8);\n // }else if (options.parseBin && binRegex.test(str)) {\n // return Number.parseInt(val, 2);\n }else{\n //separate negative sign, leading zeros, and rest number\n const match = numRegex.exec(trimmedStr);\n if(match){\n const sign = match[1];\n const leadingZeros = match[2];\n let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros\n //trim ending zeros for floating number\n \n const eNotation = match[4] || match[6];\n if(!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== \".\") return str; //-0123\n else if(!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== \".\") return str; //0123\n else{//no leading zeros or leading zeros are allowed\n const num = Number(trimmedStr);\n const numStr = \"\" + num;\n if(numStr.search(/[eE]/) !== -1){ //given number is long and parsed to eNotation\n if(options.eNotation) return num;\n else return str;\n }else if(eNotation){ //given number has enotation\n if(options.eNotation) return num;\n else return str;\n }else if(trimmedStr.indexOf(\".\") !== -1){ //floating number\n // const decimalPart = match[5].substr(1);\n // const intPart = trimmedStr.substr(0,trimmedStr.indexOf(\".\"));\n\n \n // const p = numStr.indexOf(\".\");\n // const givenIntPart = numStr.substr(0,p);\n // const givenDecPart = numStr.substr(p+1);\n if(numStr === \"0\" && (numTrimmedByZeros === \"\") ) return num; //0.0\n else if(numStr === numTrimmedByZeros) return num; //0.456. 0.79000\n else if( sign && numStr === \"-\"+numTrimmedByZeros) return num;\n else return str;\n }\n \n if(leadingZeros){\n // if(numTrimmedByZeros === numStr){\n // if(options.leadingZeros) return num;\n // else return str;\n // }else return str;\n if(numTrimmedByZeros === numStr) return num;\n else if(sign+numTrimmedByZeros === numStr) return num;\n else return str;\n }\n\n if(trimmedStr === numStr) return num;\n else if(trimmedStr === sign+numStr) return num;\n // else{\n // //number with +/- sign\n // trimmedStr.test(/[-+][0-9]);\n\n // }\n return str;\n }\n // else if(!eNotation && trimmedStr && trimmedStr !== Number(trimmedStr) ) return str;\n \n }else{ //non-numeric string\n return str;\n }\n }\n}\n\n/**\n * \n * @param {string} numStr without leading zeros\n * @returns \n */\nfunction trimZeros(numStr){\n if(numStr && numStr.indexOf(\".\") !== -1){//float\n numStr = numStr.replace(/0+$/, \"\"); //remove ending zeros\n if(numStr === \".\") numStr = \"0\";\n else if(numStr[0] === \".\") numStr = \"0\"+numStr;\n else if(numStr[numStr.length-1] === \".\") numStr = numStr.substr(0,numStr.length-1);\n return numStr;\n }\n return numStr;\n}\nmodule.exports = toNumber\n","'use strict';\n///@ts-check\n\nconst util = require('../util');\nconst xmlNode = require('./xmlNode');\nconst readDocType = require(\"./DocTypeReader\");\nconst toNumber = require(\"strnum\");\n\n// const regx =\n// '<((!\\\\[CDATA\\\\[([\\\\s\\\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\\\/)(NAME)\\\\s*>))([^<]*)'\n// .replace(/NAME/g, util.nameRegexp);\n\n//const tagsRegx = new RegExp(\"<(\\\\/?[\\\\w:\\\\-\\._]+)([^>]*)>(\\\\s*\"+cdataRegx+\")*([^<]+)?\",\"g\");\n//const tagsRegx = new RegExp(\"<(\\\\/?)((\\\\w*:)?([\\\\w:\\\\-\\._]+))([^>]*)>([^<]*)(\"+cdataRegx+\"([^<]*))*([^<]+)?\",\"g\");\n\nclass OrderedObjParser{\n constructor(options){\n this.options = options;\n this.currentNode = null;\n this.tagsNodeStack = [];\n this.docTypeEntities = {};\n this.lastEntities = {\n \"apos\" : { regex: /&(apos|#39|#x27);/g, val : \"'\"},\n \"gt\" : { regex: /&(gt|#62|#x3E);/g, val : \">\"},\n \"lt\" : { regex: /&(lt|#60|#x3C);/g, val : \"<\"},\n \"quot\" : { regex: /&(quot|#34|#x22);/g, val : \"\\\"\"},\n };\n this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : \"&\"};\n this.htmlEntities = {\n \"space\": { regex: /&(nbsp|#160);/g, val: \" \" },\n // \"lt\" : { regex: /&(lt|#60);/g, val: \"<\" },\n // \"gt\" : { regex: /&(gt|#62);/g, val: \">\" },\n // \"amp\" : { regex: /&(amp|#38);/g, val: \"&\" },\n // \"quot\" : { regex: /&(quot|#34);/g, val: \"\\\"\" },\n // \"apos\" : { regex: /&(apos|#39);/g, val: \"'\" },\n \"cent\" : { regex: /&(cent|#162);/g, val: \"¢\" },\n \"pound\" : { regex: /&(pound|#163);/g, val: \"£\" },\n \"yen\" : { regex: /&(yen|#165);/g, val: \"¥\" },\n \"euro\" : { regex: /&(euro|#8364);/g, val: \"€\" },\n \"copyright\" : { regex: /&(copy|#169);/g, val: \"©\" },\n \"reg\" : { regex: /&(reg|#174);/g, val: \"®\" },\n \"inr\" : { regex: /&(inr|#8377);/g, val: \"₹\" },\n \"num_dec\": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) },\n \"num_hex\": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) },\n };\n this.addExternalEntities = addExternalEntities;\n this.parseXml = parseXml;\n this.parseTextData = parseTextData;\n this.resolveNameSpace = resolveNameSpace;\n this.buildAttributesMap = buildAttributesMap;\n this.isItStopNode = isItStopNode;\n this.replaceEntitiesValue = replaceEntitiesValue;\n this.readStopNodeData = readStopNodeData;\n this.saveTextToParentTag = saveTextToParentTag;\n this.addChild = addChild;\n }\n\n}\n\nfunction addExternalEntities(externalEntities){\n const entKeys = Object.keys(externalEntities);\n for (let i = 0; i < entKeys.length; i++) {\n const ent = entKeys[i];\n this.lastEntities[ent] = {\n regex: new RegExp(\"&\"+ent+\";\",\"g\"),\n val : externalEntities[ent]\n }\n }\n}\n\n/**\n * @param {string} val\n * @param {string} tagName\n * @param {string} jPath\n * @param {boolean} dontTrim\n * @param {boolean} hasAttributes\n * @param {boolean} isLeafNode\n * @param {boolean} escapeEntities\n */\nfunction parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {\n if (val !== undefined) {\n if (this.options.trimValues && !dontTrim) {\n val = val.trim();\n }\n if(val.length > 0){\n if(!escapeEntities) val = this.replaceEntitiesValue(val);\n \n const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode);\n if(newval === null || newval === undefined){\n //don't parse\n return val;\n }else if(typeof newval !== typeof val || newval !== val){\n //overwrite\n return newval;\n }else if(this.options.trimValues){\n return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);\n }else{\n const trimmedVal = val.trim();\n if(trimmedVal === val){\n return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);\n }else{\n return val;\n }\n }\n }\n }\n}\n\nfunction resolveNameSpace(tagname) {\n if (this.options.removeNSPrefix) {\n const tags = tagname.split(':');\n const prefix = tagname.charAt(0) === '/' ? '/' : '';\n if (tags[0] === 'xmlns') {\n return '';\n }\n if (tags.length === 2) {\n tagname = prefix + tags[1];\n }\n }\n return tagname;\n}\n\n//TODO: change regex to capture NS\n//const attrsRegx = new RegExp(\"([\\\\w\\\\-\\\\.\\\\:]+)\\\\s*=\\\\s*(['\\\"])((.|\\n)*?)\\\\2\",\"gm\");\nconst attrsRegx = new RegExp('([^\\\\s=]+)\\\\s*(=\\\\s*([\\'\"])([\\\\s\\\\S]*?)\\\\3)?', 'gm');\n\nfunction buildAttributesMap(attrStr, jPath, tagName) {\n if (!this.options.ignoreAttributes && typeof attrStr === 'string') {\n // attrStr = attrStr.replace(/\\r?\\n/g, ' ');\n //attrStr = attrStr || attrStr.trim();\n\n const matches = util.getAllMatches(attrStr, attrsRegx);\n const len = matches.length; //don't make it inline\n const attrs = {};\n for (let i = 0; i < len; i++) {\n const attrName = this.resolveNameSpace(matches[i][1]);\n let oldVal = matches[i][4];\n let aName = this.options.attributeNamePrefix + attrName;\n if (attrName.length) {\n if (this.options.transformAttributeName) {\n aName = this.options.transformAttributeName(aName);\n }\n if(aName === \"__proto__\") aName = \"#__proto__\";\n if (oldVal !== undefined) {\n if (this.options.trimValues) {\n oldVal = oldVal.trim();\n }\n oldVal = this.replaceEntitiesValue(oldVal);\n const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);\n if(newVal === null || newVal === undefined){\n //don't parse\n attrs[aName] = oldVal;\n }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){\n //overwrite\n attrs[aName] = newVal;\n }else{\n //parse\n attrs[aName] = parseValue(\n oldVal,\n this.options.parseAttributeValue,\n this.options.numberParseOptions\n );\n }\n } else if (this.options.allowBooleanAttributes) {\n attrs[aName] = true;\n }\n }\n }\n if (!Object.keys(attrs).length) {\n return;\n }\n if (this.options.attributesGroupName) {\n const attrCollection = {};\n attrCollection[this.options.attributesGroupName] = attrs;\n return attrCollection;\n }\n return attrs\n }\n}\n\nconst parseXml = function(xmlData) {\n xmlData = xmlData.replace(/\\r\\n?/g, \"\\n\"); //TODO: remove this line\n const xmlObj = new xmlNode('!xml');\n let currentNode = xmlObj;\n let textData = \"\";\n let jPath = \"\";\n for(let i=0; i< xmlData.length; i++){//for each char in XML data\n const ch = xmlData[i];\n if(ch === '<'){\n // const nextIndex = i+1;\n // const _2ndChar = xmlData[nextIndex];\n if( xmlData[i+1] === '/') {//Closing Tag\n const closeIndex = findClosingIndex(xmlData, \">\", i, \"Closing Tag is not closed.\")\n let tagName = xmlData.substring(i+2,closeIndex).trim();\n\n if(this.options.removeNSPrefix){\n const colonIndex = tagName.indexOf(\":\");\n if(colonIndex !== -1){\n tagName = tagName.substr(colonIndex+1);\n }\n }\n\n if(this.options.transformTagName) {\n tagName = this.options.transformTagName(tagName);\n }\n\n if(currentNode){\n textData = this.saveTextToParentTag(textData, currentNode, jPath);\n }\n\n //check if last tag of nested tag was unpaired tag\n const lastTagName = jPath.substring(jPath.lastIndexOf(\".\")+1);\n if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){\n throw new Error(`Unpaired tag can not be used as closing tag: `);\n }\n let propIndex = 0\n if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){\n propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1)\n this.tagsNodeStack.pop();\n }else{\n propIndex = jPath.lastIndexOf(\".\");\n }\n jPath = jPath.substring(0, propIndex);\n\n currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope\n textData = \"\";\n i = closeIndex;\n } else if( xmlData[i+1] === '?') {\n\n let tagData = readTagExp(xmlData,i, false, \"?>\");\n if(!tagData) throw new Error(\"Pi Tag is not closed.\");\n\n textData = this.saveTextToParentTag(textData, currentNode, jPath);\n if( (this.options.ignoreDeclaration && tagData.tagName === \"?xml\") || this.options.ignorePiTags){\n\n }else{\n \n const childNode = new xmlNode(tagData.tagName);\n childNode.add(this.options.textNodeName, \"\");\n \n if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){\n childNode[\":@\"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName);\n }\n this.addChild(currentNode, childNode, jPath)\n\n }\n\n\n i = tagData.closeIndex + 1;\n } else if(xmlData.substr(i + 1, 3) === '!--') {\n const endIndex = findClosingIndex(xmlData, \"-->\", i+4, \"Comment is not closed.\")\n if(this.options.commentPropName){\n const comment = xmlData.substring(i + 4, endIndex - 2);\n\n textData = this.saveTextToParentTag(textData, currentNode, jPath);\n\n currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]);\n }\n i = endIndex;\n } else if( xmlData.substr(i + 1, 2) === '!D') {\n const result = readDocType(xmlData, i);\n this.docTypeEntities = result.entities;\n i = result.i;\n }else if(xmlData.substr(i + 1, 2) === '![') {\n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"CDATA is not closed.\") - 2;\n const tagExp = xmlData.substring(i + 9,closeIndex);\n\n textData = this.saveTextToParentTag(textData, currentNode, jPath);\n\n let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);\n if(val == undefined) val = \"\";\n\n //cdata should be set even if it is 0 length string\n if(this.options.cdataPropName){\n currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]);\n }else{\n currentNode.add(this.options.textNodeName, val);\n }\n \n i = closeIndex + 2;\n }else {//Opening tag\n let result = readTagExp(xmlData,i, this.options.removeNSPrefix);\n let tagName= result.tagName;\n const rawTagName = result.rawTagName;\n let tagExp = result.tagExp;\n let attrExpPresent = result.attrExpPresent;\n let closeIndex = result.closeIndex;\n\n if (this.options.transformTagName) {\n tagName = this.options.transformTagName(tagName);\n }\n \n //save text as child node\n if (currentNode && textData) {\n if(currentNode.tagname !== '!xml'){\n //when nested tag is found\n textData = this.saveTextToParentTag(textData, currentNode, jPath, false);\n }\n }\n\n //check if last tag was unpaired tag\n const lastTag = currentNode;\n if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){\n currentNode = this.tagsNodeStack.pop();\n jPath = jPath.substring(0, jPath.lastIndexOf(\".\"));\n }\n if(tagName !== xmlObj.tagname){\n jPath += jPath ? \".\" + tagName : tagName;\n }\n if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) {\n let tagContent = \"\";\n //self-closing tag\n if(tagExp.length > 0 && tagExp.lastIndexOf(\"/\") === tagExp.length - 1){\n i = result.closeIndex;\n }\n //unpaired tag\n else if(this.options.unpairedTags.indexOf(tagName) !== -1){\n i = result.closeIndex;\n }\n //normal tag\n else{\n //read until closing tag is found\n const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);\n if(!result) throw new Error(`Unexpected end of ${rawTagName}`);\n i = result.i;\n tagContent = result.tagContent;\n }\n\n const childNode = new xmlNode(tagName);\n if(tagName !== tagExp && attrExpPresent){\n childNode[\":@\"] = this.buildAttributesMap(tagExp, jPath, tagName);\n }\n if(tagContent) {\n tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);\n }\n \n jPath = jPath.substr(0, jPath.lastIndexOf(\".\"));\n childNode.add(this.options.textNodeName, tagContent);\n \n this.addChild(currentNode, childNode, jPath)\n }else{\n //selfClosing tag\n if(tagExp.length > 0 && tagExp.lastIndexOf(\"/\") === tagExp.length - 1){\n if(tagName[tagName.length - 1] === \"/\"){ //remove trailing '/'\n tagName = tagName.substr(0, tagName.length - 1);\n jPath = jPath.substr(0, jPath.length - 1);\n tagExp = tagName;\n }else{\n tagExp = tagExp.substr(0, tagExp.length - 1);\n }\n \n if(this.options.transformTagName) {\n tagName = this.options.transformTagName(tagName);\n }\n\n const childNode = new xmlNode(tagName);\n if(tagName !== tagExp && attrExpPresent){\n childNode[\":@\"] = this.buildAttributesMap(tagExp, jPath, tagName);\n }\n this.addChild(currentNode, childNode, jPath)\n jPath = jPath.substr(0, jPath.lastIndexOf(\".\"));\n }\n //opening tag\n else{\n const childNode = new xmlNode( tagName);\n this.tagsNodeStack.push(currentNode);\n \n if(tagName !== tagExp && attrExpPresent){\n childNode[\":@\"] = this.buildAttributesMap(tagExp, jPath, tagName);\n }\n this.addChild(currentNode, childNode, jPath)\n currentNode = childNode;\n }\n textData = \"\";\n i = closeIndex;\n }\n }\n }else{\n textData += xmlData[i];\n }\n }\n return xmlObj.child;\n}\n\nfunction addChild(currentNode, childNode, jPath){\n const result = this.options.updateTag(childNode.tagname, jPath, childNode[\":@\"])\n if(result === false){\n }else if(typeof result === \"string\"){\n childNode.tagname = result\n currentNode.addChild(childNode);\n }else{\n currentNode.addChild(childNode);\n }\n}\n\nconst replaceEntitiesValue = function(val){\n\n if(this.options.processEntities){\n for(let entityName in this.docTypeEntities){\n const entity = this.docTypeEntities[entityName];\n val = val.replace( entity.regx, entity.val);\n }\n for(let entityName in this.lastEntities){\n const entity = this.lastEntities[entityName];\n val = val.replace( entity.regex, entity.val);\n }\n if(this.options.htmlEntities){\n for(let entityName in this.htmlEntities){\n const entity = this.htmlEntities[entityName];\n val = val.replace( entity.regex, entity.val);\n }\n }\n val = val.replace( this.ampEntity.regex, this.ampEntity.val);\n }\n return val;\n}\nfunction saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {\n if (textData) { //store previously collected data as textNode\n if(isLeafNode === undefined) isLeafNode = Object.keys(currentNode.child).length === 0\n \n textData = this.parseTextData(textData,\n currentNode.tagname,\n jPath,\n false,\n currentNode[\":@\"] ? Object.keys(currentNode[\":@\"]).length !== 0 : false,\n isLeafNode);\n\n if (textData !== undefined && textData !== \"\")\n currentNode.add(this.options.textNodeName, textData);\n textData = \"\";\n }\n return textData;\n}\n\n//TODO: use jPath to simplify the logic\n/**\n * \n * @param {string[]} stopNodes \n * @param {string} jPath\n * @param {string} currentTagName \n */\nfunction isItStopNode(stopNodes, jPath, currentTagName){\n const allNodesExp = \"*.\" + currentTagName;\n for (const stopNodePath in stopNodes) {\n const stopNodeExp = stopNodes[stopNodePath];\n if( allNodesExp === stopNodeExp || jPath === stopNodeExp ) return true;\n }\n return false;\n}\n\n/**\n * Returns the tag Expression and where it is ending handling single-double quotes situation\n * @param {string} xmlData \n * @param {number} i starting index\n * @returns \n */\nfunction tagExpWithClosingIndex(xmlData, i, closingChar = \">\"){\n let attrBoundary;\n let tagExp = \"\";\n for (let index = i; index < xmlData.length; index++) {\n let ch = xmlData[index];\n if (attrBoundary) {\n if (ch === attrBoundary) attrBoundary = \"\";//reset\n } else if (ch === '\"' || ch === \"'\") {\n attrBoundary = ch;\n } else if (ch === closingChar[0]) {\n if(closingChar[1]){\n if(xmlData[index + 1] === closingChar[1]){\n return {\n data: tagExp,\n index: index\n }\n }\n }else{\n return {\n data: tagExp,\n index: index\n }\n }\n } else if (ch === '\\t') {\n ch = \" \"\n }\n tagExp += ch;\n }\n}\n\nfunction findClosingIndex(xmlData, str, i, errMsg){\n const closingIndex = xmlData.indexOf(str, i);\n if(closingIndex === -1){\n throw new Error(errMsg)\n }else{\n return closingIndex + str.length - 1;\n }\n}\n\nfunction readTagExp(xmlData,i, removeNSPrefix, closingChar = \">\"){\n const result = tagExpWithClosingIndex(xmlData, i+1, closingChar);\n if(!result) return;\n let tagExp = result.data;\n const closeIndex = result.index;\n const separatorIndex = tagExp.search(/\\s/);\n let tagName = tagExp;\n let attrExpPresent = true;\n if(separatorIndex !== -1){//separate tag name and attributes expression\n tagName = tagExp.substring(0, separatorIndex);\n tagExp = tagExp.substring(separatorIndex + 1).trimStart();\n }\n\n const rawTagName = tagName;\n if(removeNSPrefix){\n const colonIndex = tagName.indexOf(\":\");\n if(colonIndex !== -1){\n tagName = tagName.substr(colonIndex+1);\n attrExpPresent = tagName !== result.data.substr(colonIndex + 1);\n }\n }\n\n return {\n tagName: tagName,\n tagExp: tagExp,\n closeIndex: closeIndex,\n attrExpPresent: attrExpPresent,\n rawTagName: rawTagName,\n }\n}\n/**\n * find paired tag for a stop node\n * @param {string} xmlData \n * @param {string} tagName \n * @param {number} i \n */\nfunction readStopNodeData(xmlData, tagName, i){\n const startIndex = i;\n // Starting at 1 since we already have an open tag\n let openTagCount = 1;\n\n for (; i < xmlData.length; i++) {\n if( xmlData[i] === \"<\"){ \n if (xmlData[i+1] === \"/\") {//close tag\n const closeIndex = findClosingIndex(xmlData, \">\", i, `${tagName} is not closed`);\n let closeTagName = xmlData.substring(i+2,closeIndex).trim();\n if(closeTagName === tagName){\n openTagCount--;\n if (openTagCount === 0) {\n return {\n tagContent: xmlData.substring(startIndex, i),\n i : closeIndex\n }\n }\n }\n i=closeIndex;\n } else if(xmlData[i+1] === '?') { \n const closeIndex = findClosingIndex(xmlData, \"?>\", i+1, \"StopNode is not closed.\")\n i=closeIndex;\n } else if(xmlData.substr(i + 1, 3) === '!--') { \n const closeIndex = findClosingIndex(xmlData, \"-->\", i+3, \"StopNode is not closed.\")\n i=closeIndex;\n } else if(xmlData.substr(i + 1, 2) === '![') { \n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"StopNode is not closed.\") - 2;\n i=closeIndex;\n } else {\n const tagData = readTagExp(xmlData, i, '>')\n\n if (tagData) {\n const openTagName = tagData && tagData.tagName;\n if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== \"/\") {\n openTagCount++;\n }\n i=tagData.closeIndex;\n }\n }\n }\n }//end for loop\n}\n\nfunction parseValue(val, shouldParse, options) {\n if (shouldParse && typeof val === 'string') {\n //console.log(options)\n const newval = val.trim();\n if(newval === 'true' ) return true;\n else if(newval === 'false' ) return false;\n else return toNumber(val, options);\n } else {\n if (util.isExist(val)) {\n return val;\n } else {\n return '';\n }\n }\n}\n\n\nmodule.exports = OrderedObjParser;\n","'use strict';\n\n/**\n * \n * @param {array} node \n * @param {any} options \n * @returns \n */\nfunction prettify(node, options){\n return compress( node, options);\n}\n\n/**\n * \n * @param {array} arr \n * @param {object} options \n * @param {string} jPath \n * @returns object\n */\nfunction compress(arr, options, jPath){\n let text;\n const compressedObj = {};\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const property = propName(tagObj);\n let newJpath = \"\";\n if(jPath === undefined) newJpath = property;\n else newJpath = jPath + \".\" + property;\n\n if(property === options.textNodeName){\n if(text === undefined) text = tagObj[property];\n else text += \"\" + tagObj[property];\n }else if(property === undefined){\n continue;\n }else if(tagObj[property]){\n \n let val = compress(tagObj[property], options, newJpath);\n const isLeaf = isLeafTag(val, options);\n\n if(tagObj[\":@\"]){\n assignAttributes( val, tagObj[\":@\"], newJpath, options);\n }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){\n val = val[options.textNodeName];\n }else if(Object.keys(val).length === 0){\n if(options.alwaysCreateTextNode) val[options.textNodeName] = \"\";\n else val = \"\";\n }\n\n if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) {\n if(!Array.isArray(compressedObj[property])) {\n compressedObj[property] = [ compressedObj[property] ];\n }\n compressedObj[property].push(val);\n }else{\n //TODO: if a node is not an array, then check if it should be an array\n //also determine if it is a leaf node\n if (options.isArray(property, newJpath, isLeaf )) {\n compressedObj[property] = [val];\n }else{\n compressedObj[property] = val;\n }\n }\n }\n \n }\n // if(text && text.length > 0) compressedObj[options.textNodeName] = text;\n if(typeof text === \"string\"){\n if(text.length > 0) compressedObj[options.textNodeName] = text;\n }else if(text !== undefined) compressedObj[options.textNodeName] = text;\n return compressedObj;\n}\n\nfunction propName(obj){\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if(key !== \":@\") return key;\n }\n}\n\nfunction assignAttributes(obj, attrMap, jpath, options){\n if (attrMap) {\n const keys = Object.keys(attrMap);\n const len = keys.length; //don't make it inline\n for (let i = 0; i < len; i++) {\n const atrrName = keys[i];\n if (options.isArray(atrrName, jpath + \".\" + atrrName, true, true)) {\n obj[atrrName] = [ attrMap[atrrName] ];\n } else {\n obj[atrrName] = attrMap[atrrName];\n }\n }\n }\n}\n\nfunction isLeafTag(obj, options){\n const { textNodeName } = options;\n const propCount = Object.keys(obj).length;\n \n if (propCount === 0) {\n return true;\n }\n\n if (\n propCount === 1 &&\n (obj[textNodeName] || typeof obj[textNodeName] === \"boolean\" || obj[textNodeName] === 0)\n ) {\n return true;\n }\n\n return false;\n}\nexports.prettify = prettify;\n","const { buildOptions} = require(\"./OptionsBuilder\");\nconst OrderedObjParser = require(\"./OrderedObjParser\");\nconst { prettify} = require(\"./node2json\");\nconst validator = require('../validator');\n\nclass XMLParser{\n \n constructor(options){\n this.externalEntities = {};\n this.options = buildOptions(options);\n \n }\n /**\n * Parse XML dats to JS object \n * @param {string|Buffer} xmlData \n * @param {boolean|Object} validationOption \n */\n parse(xmlData,validationOption){\n if(typeof xmlData === \"string\"){\n }else if( xmlData.toString){\n xmlData = xmlData.toString();\n }else{\n throw new Error(\"XML data is accepted in String or Bytes[] form.\")\n }\n if( validationOption){\n if(validationOption === true) validationOption = {}; //validate with default options\n \n const result = validator.validate(xmlData, validationOption);\n if (result !== true) {\n throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` )\n }\n }\n const orderedObjParser = new OrderedObjParser(this.options);\n orderedObjParser.addExternalEntities(this.externalEntities);\n const orderedResult = orderedObjParser.parseXml(xmlData);\n if(this.options.preserveOrder || orderedResult === undefined) return orderedResult;\n else return prettify(orderedResult, this.options);\n }\n\n /**\n * Add Entity which is not by default supported by this library\n * @param {string} key \n * @param {string} value \n */\n addEntity(key, value){\n if(value.indexOf(\"&\") !== -1){\n throw new Error(\"Entity value can't have '&'\")\n }else if(key.indexOf(\"&\") !== -1 || key.indexOf(\";\") !== -1){\n throw new Error(\"An entity must be set without '&' and ';'. Eg. use '#xD' for ' '\")\n }else if(value === \"&\"){\n throw new Error(\"An entity with value '&' is not permitted\");\n }else{\n this.externalEntities[key] = value;\n }\n }\n}\n\nmodule.exports = XMLParser;","const EOL = \"\\n\";\n\n/**\n * \n * @param {array} jArray \n * @param {any} options \n * @returns \n */\nfunction toXml(jArray, options) {\n let indentation = \"\";\n if (options.format && options.indentBy.length > 0) {\n indentation = EOL;\n }\n return arrToStr(jArray, options, \"\", indentation);\n}\n\nfunction arrToStr(arr, options, jPath, indentation) {\n let xmlStr = \"\";\n let isPreviousElementTag = false;\n\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const tagName = propName(tagObj);\n if(tagName === undefined) continue;\n\n let newJPath = \"\";\n if (jPath.length === 0) newJPath = tagName\n else newJPath = `${jPath}.${tagName}`;\n\n if (tagName === options.textNodeName) {\n let tagText = tagObj[tagName];\n if (!isStopNode(newJPath, options)) {\n tagText = options.tagValueProcessor(tagName, tagText);\n tagText = replaceEntitiesValue(tagText, options);\n }\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n xmlStr += tagText;\n isPreviousElementTag = false;\n continue;\n } else if (tagName === options.cdataPropName) {\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n xmlStr += ``;\n isPreviousElementTag = false;\n continue;\n } else if (tagName === options.commentPropName) {\n xmlStr += indentation + ``;\n isPreviousElementTag = true;\n continue;\n } else if (tagName[0] === \"?\") {\n const attStr = attr_to_str(tagObj[\":@\"], options);\n const tempInd = tagName === \"?xml\" ? \"\" : indentation;\n let piTextNodeName = tagObj[tagName][0][options.textNodeName];\n piTextNodeName = piTextNodeName.length !== 0 ? \" \" + piTextNodeName : \"\"; //remove extra spacing\n xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`;\n isPreviousElementTag = true;\n continue;\n }\n let newIdentation = indentation;\n if (newIdentation !== \"\") {\n newIdentation += options.indentBy;\n }\n const attStr = attr_to_str(tagObj[\":@\"], options);\n const tagStart = indentation + `<${tagName}${attStr}`;\n const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation);\n if (options.unpairedTags.indexOf(tagName) !== -1) {\n if (options.suppressUnpairedNode) xmlStr += tagStart + \">\";\n else xmlStr += tagStart + \"/>\";\n } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {\n xmlStr += tagStart + \"/>\";\n } else if (tagValue && tagValue.endsWith(\">\")) {\n xmlStr += tagStart + `>${tagValue}${indentation}`;\n } else {\n xmlStr += tagStart + \">\";\n if (tagValue && indentation !== \"\" && (tagValue.includes(\"/>\") || tagValue.includes(\"`;\n }\n isPreviousElementTag = true;\n }\n\n return xmlStr;\n}\n\nfunction propName(obj) {\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if(!obj.hasOwnProperty(key)) continue;\n if (key !== \":@\") return key;\n }\n}\n\nfunction attr_to_str(attrMap, options) {\n let attrStr = \"\";\n if (attrMap && !options.ignoreAttributes) {\n for (let attr in attrMap) {\n if(!attrMap.hasOwnProperty(attr)) continue;\n let attrVal = options.attributeValueProcessor(attr, attrMap[attr]);\n attrVal = replaceEntitiesValue(attrVal, options);\n if (attrVal === true && options.suppressBooleanAttributes) {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;\n } else {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}=\"${attrVal}\"`;\n }\n }\n }\n return attrStr;\n}\n\nfunction isStopNode(jPath, options) {\n jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1);\n let tagName = jPath.substr(jPath.lastIndexOf(\".\") + 1);\n for (let index in options.stopNodes) {\n if (options.stopNodes[index] === jPath || options.stopNodes[index] === \"*.\" + tagName) return true;\n }\n return false;\n}\n\nfunction replaceEntitiesValue(textValue, options) {\n if (textValue && textValue.length > 0 && options.processEntities) {\n for (let i = 0; i < options.entities.length; i++) {\n const entity = options.entities[i];\n textValue = textValue.replace(entity.regex, entity.val);\n }\n }\n return textValue;\n}\nmodule.exports = toXml;\n","'use strict';\n//parse Empty Node as self closing node\nconst buildFromOrderedJs = require('./orderedJs2Xml');\n\nconst defaultOptions = {\n attributeNamePrefix: '@_',\n attributesGroupName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n cdataPropName: false,\n format: false,\n indentBy: ' ',\n suppressEmptyNode: false,\n suppressUnpairedNode: true,\n suppressBooleanAttributes: true,\n tagValueProcessor: function(key, a) {\n return a;\n },\n attributeValueProcessor: function(attrName, a) {\n return a;\n },\n preserveOrder: false,\n commentPropName: false,\n unpairedTags: [],\n entities: [\n { regex: new RegExp(\"&\", \"g\"), val: \"&\" },//it must be on top\n { regex: new RegExp(\">\", \"g\"), val: \">\" },\n { regex: new RegExp(\"<\", \"g\"), val: \"<\" },\n { regex: new RegExp(\"\\'\", \"g\"), val: \"'\" },\n { regex: new RegExp(\"\\\"\", \"g\"), val: \""\" }\n ],\n processEntities: true,\n stopNodes: [],\n // transformTagName: false,\n // transformAttributeName: false,\n oneListGroup: false\n};\n\nfunction Builder(options) {\n this.options = Object.assign({}, defaultOptions, options);\n if (this.options.ignoreAttributes || this.options.attributesGroupName) {\n this.isAttribute = function(/*a*/) {\n return false;\n };\n } else {\n this.attrPrefixLen = this.options.attributeNamePrefix.length;\n this.isAttribute = isAttribute;\n }\n\n this.processTextOrObjNode = processTextOrObjNode\n\n if (this.options.format) {\n this.indentate = indentate;\n this.tagEndChar = '>\\n';\n this.newLine = '\\n';\n } else {\n this.indentate = function() {\n return '';\n };\n this.tagEndChar = '>';\n this.newLine = '';\n }\n}\n\nBuilder.prototype.build = function(jObj) {\n if(this.options.preserveOrder){\n return buildFromOrderedJs(jObj, this.options);\n }else {\n if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){\n jObj = {\n [this.options.arrayNodeName] : jObj\n }\n }\n return this.j2x(jObj, 0).val;\n }\n};\n\nBuilder.prototype.j2x = function(jObj, level) {\n let attrStr = '';\n let val = '';\n for (let key in jObj) {\n if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue;\n if (typeof jObj[key] === 'undefined') {\n // supress undefined node only if it is not an attribute\n if (this.isAttribute(key)) {\n val += '';\n }\n } else if (jObj[key] === null) {\n // null attribute should be ignored by the attribute list, but should not cause the tag closing\n if (this.isAttribute(key)) {\n val += '';\n } else if (key[0] === '?') {\n val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;\n } else {\n val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n }\n // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n } else if (jObj[key] instanceof Date) {\n val += this.buildTextValNode(jObj[key], key, '', level);\n } else if (typeof jObj[key] !== 'object') {\n //premitive type\n const attr = this.isAttribute(key);\n if (attr) {\n attrStr += this.buildAttrPairStr(attr, '' + jObj[key]);\n }else {\n //tag value\n if (key === this.options.textNodeName) {\n let newval = this.options.tagValueProcessor(key, '' + jObj[key]);\n val += this.replaceEntitiesValue(newval);\n } else {\n val += this.buildTextValNode(jObj[key], key, '', level);\n }\n }\n } else if (Array.isArray(jObj[key])) {\n //repeated nodes\n const arrLen = jObj[key].length;\n let listTagVal = \"\";\n for (let j = 0; j < arrLen; j++) {\n const item = jObj[key][j];\n if (typeof item === 'undefined') {\n // supress undefined node\n } else if (item === null) {\n if(key[0] === \"?\") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;\n else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n } else if (typeof item === 'object') {\n if(this.options.oneListGroup ){\n listTagVal += this.j2x(item, level + 1).val;\n }else{\n listTagVal += this.processTextOrObjNode(item, key, level)\n }\n } else {\n listTagVal += this.buildTextValNode(item, key, '', level);\n }\n }\n if(this.options.oneListGroup){\n listTagVal = this.buildObjectNode(listTagVal, key, '', level);\n }\n val += listTagVal;\n } else {\n //nested node\n if (this.options.attributesGroupName && key === this.options.attributesGroupName) {\n const Ks = Object.keys(jObj[key]);\n const L = Ks.length;\n for (let j = 0; j < L; j++) {\n attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]);\n }\n } else {\n val += this.processTextOrObjNode(jObj[key], key, level)\n }\n }\n }\n return {attrStr: attrStr, val: val};\n};\n\nBuilder.prototype.buildAttrPairStr = function(attrName, val){\n val = this.options.attributeValueProcessor(attrName, '' + val);\n val = this.replaceEntitiesValue(val);\n if (this.options.suppressBooleanAttributes && val === \"true\") {\n return ' ' + attrName;\n } else return ' ' + attrName + '=\"' + val + '\"';\n}\n\nfunction processTextOrObjNode (object, key, level) {\n const result = this.j2x(object, level + 1);\n if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) {\n return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level);\n } else {\n return this.buildObjectNode(result.val, key, result.attrStr, level);\n }\n}\n\nBuilder.prototype.buildObjectNode = function(val, key, attrStr, level) {\n if(val === \"\"){\n if(key[0] === \"?\") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;\n else {\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n }\n }else{\n\n let tagEndExp = '' + val + tagEndExp );\n } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {\n return this.indentate(level) + `` + this.newLine;\n }else {\n return (\n this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar +\n val +\n this.indentate(level) + tagEndExp );\n }\n }\n}\n\nBuilder.prototype.closeTag = function(key){\n let closeTag = \"\";\n if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired\n if(!this.options.suppressUnpairedNode) closeTag = \"/\"\n }else if(this.options.suppressEmptyNode){ //empty\n closeTag = \"/\";\n }else{\n closeTag = `>` + this.newLine;\n }else if (this.options.commentPropName !== false && key === this.options.commentPropName) {\n return this.indentate(level) + `` + this.newLine;\n }else if(key[0] === \"?\") {//PI tag\n return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; \n }else{\n let textValue = this.options.tagValueProcessor(key, val);\n textValue = this.replaceEntitiesValue(textValue);\n \n if( textValue === ''){\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n }else{\n return this.indentate(level) + '<' + key + attrStr + '>' +\n textValue +\n ' 0 && this.options.processEntities){\n for (let i=0; i {\n const finalOptions = {\n ...defaultOptions,\n ...options,\n };\n\n return [finalOptions.php, finalOptions.script, command]\n .concat([...inputs, '-v'])\n .map((part) => `'${part}'`)\n .join(' ');\n};\n\nconst execSymfonyCommand = async (finalCommand: string) => {\n return new Promise((resolve, reject) => {\n exec(finalCommand, (error, stdout, stderr) => {\n if (error) {\n reject(\n new Error(dedent`\n Symfony console failed with exit status ${error.code}:\n CMD: ${error.cmd}\n Output: ${stdout}\n Error output: ${stderr}\n `)\n );\n }\n\n resolve(stdout);\n });\n });\n};\n\n/**\n * Run a Symfony command.\n */\nexport const runSymfonyCommand = async (command: string, inputs: string[] = [], options: CommandOptions = {}) => {\n const finalCommand = prepareSymfonyCommand(command, inputs, options);\n\n return execSymfonyCommand(finalCommand);\n};\n\n/**\n * Run a Symfony command with JSON formatted output and get the result as a JS object.\n */\nexport const runSymfonyCommandJson = async (\n command: string,\n inputs: string[] = [],\n options: CommandOptions = {}\n): Promise => {\n const finalCommand = prepareSymfonyCommand(command, [...inputs, '--format=json'], options);\n const result = await execSymfonyCommand(finalCommand);\n\n try {\n return JSON.parse(result);\n } catch (err) {\n throw new Error(dedent`\n Failed to process JSON output for Symfony command.\n CMD: ${finalCommand}\n Raw output: ${result}\n `);\n }\n};\n\nexport const getKernelProjectDir = async () => {\n return (\n await runSymfonyCommandJson<{ [p: string]: string }>('debug:container', ['--parameter=kernel.project_dir'])\n )['kernel.project_dir'];\n};\n\ntype StorybookBundleConfig = {\n storybook: {\n runtime_dir: string;\n };\n};\n\nexport const getBundleConfig = async () => {\n return (await runSymfonyCommandJson('debug:config', ['storybook']))['storybook'];\n};\n\ntype SymfonyTwigComponentConfiguration = {\n twig_component: {\n anonymous_template_directory: string;\n defaults: {\n [p: string]: {\n name_prefix: string;\n template_directory: string;\n };\n };\n };\n};\n\nexport const getTwigComponentConfiguration = async () => {\n return (\n await runSymfonyCommandJson('debug:config', [\n 'twig_component',\n '--resolve-env',\n ])\n )['twig_component'];\n};\n\nexport type TwigComponentConfiguration = {\n anonymousTemplateDirectory: [string];\n namespaces: {\n [p: string]: [string];\n };\n};\n\ntype SymfonyTwigConfiguration = {\n twig: {\n paths: {\n [p: string]: string;\n };\n };\n};\n\nexport const getTwigConfiguration = async () => {\n return (await runSymfonyCommandJson('debug:config', ['twig', '--resolve-env']))['twig'];\n};\n\nexport type TwigConfiguration = {\n paths: string[];\n};\n","export function dedent(\n templ: TemplateStringsArray | string,\n ...values: unknown[]\n): string {\n let strings = Array.from(typeof templ === 'string' ? [templ] : templ);\n\n // 1. Remove trailing whitespace.\n strings[strings.length - 1] = strings[strings.length - 1].replace(\n /\\r?\\n([\\t ]*)$/,\n '',\n );\n\n // 2. Find all line breaks to determine the highest common indentation level.\n const indentLengths = strings.reduce((arr, str) => {\n const matches = str.match(/\\n([\\t ]+|(?!\\s).)/g);\n if (matches) {\n return arr.concat(\n matches.map((match) => match.match(/[\\t ]/g)?.length ?? 0),\n );\n }\n return arr;\n }, []);\n\n // 3. Remove the common indentation from all strings.\n if (indentLengths.length) {\n const pattern = new RegExp(`\\n[\\t ]{${Math.min(...indentLengths)}}`, 'g');\n\n strings = strings.map((str) => str.replace(pattern, '\\n'));\n }\n\n // 4. Remove leading whitespace.\n strings[0] = strings[0].replace(/^\\r?\\n/, '');\n\n // 5. Perform interpolation.\n let string = strings[0];\n\n values.forEach((value, i) => {\n // 5.1 Read current indentation level\n const endentations = string.match(/(?:^|\\n)( *)$/)\n const endentation = endentations ? endentations[1] : ''\n let indentedValue = value\n // 5.2 Add indentation to values with multiline strings\n if (typeof value === 'string' && value.includes('\\n')) {\n indentedValue = String(value)\n .split('\\n')\n .map((str, i) => {\n return i === 0 ? str : `${endentation}${str}`\n })\n .join('\\n');\n }\n\n string += indentedValue + strings[i + 1];\n });\n\n return string;\n}\n\nexport default dedent;\n","import {\n getBundleConfig,\n getKernelProjectDir,\n getTwigComponentConfiguration,\n getTwigConfiguration,\n TwigComponentConfiguration,\n TwigConfiguration,\n} from './lib/symfony';\nimport { StorybookConfig, SymfonyOptions } from '../types';\nimport { join } from 'path';\nimport { PreviewCompilerPlugin } from './lib/preview-compiler-plugin';\nimport { DevPreviewCompilerPlugin } from './lib/dev-preview-compiler-plugin';\nimport { TwigLoaderPlugin } from './lib/twig-loader-plugin';\nimport { PresetProperty } from '@storybook/types';\nimport dedent from 'ts-dedent';\n\ntype BuildOptions = {\n twigComponent: TwigComponentConfiguration;\n twig: TwigConfiguration;\n runtimeDir: string;\n projectDir: string;\n additionalWatchPaths: string[];\n};\n\nconst getBuildOptions = async (symfonyOptions: SymfonyOptions) => {\n const projectDir = await getKernelProjectDir();\n const twigComponentsConfig = await getTwigComponentConfiguration();\n const twigConfig = await getTwigConfiguration();\n\n const componentNamespaces: { [p: string]: string[] } = {};\n\n const twigPaths: string[] = Object.keys(twigConfig.paths).map((key) => `${projectDir}/${key}/`);\n\n if (twigPaths.length === 0) {\n twigPaths.push(`${projectDir}/templates`);\n }\n\n for (const { name_prefix: namePrefix, template_directory: templateDirectory } of Object.values(\n twigComponentsConfig.defaults\n )) {\n componentNamespaces[namePrefix] = twigPaths.map((twigPath) => join(twigPath, templateDirectory));\n }\n\n const anonymousNamespace: string[] = twigPaths.map((twigPath) =>\n join(twigPath, twigComponentsConfig['anonymous_template_directory'])\n );\n\n const runtimeDir = (await getBundleConfig()).runtime_dir;\n\n return {\n twigComponent: {\n anonymousTemplateDirectory: anonymousNamespace,\n namespaces: componentNamespaces,\n },\n twig: {\n paths: twigPaths,\n },\n runtimeDir,\n projectDir,\n additionalWatchPaths: symfonyOptions.additionalWatchPaths || [],\n } as BuildOptions;\n};\n\nexport const webpack: StorybookConfig['webpack'] = async (config, options) => {\n const framework = await options.presets.apply('framework');\n\n const frameworkOptions = typeof framework === 'string' ? {} : framework.options;\n\n // This options resolution should be done right before creating the build configuration (i.e. not in options presets).\n const symfonyOptions = await getBuildOptions(frameworkOptions.symfony);\n\n return {\n ...config,\n plugins: [\n ...(config.plugins || []),\n ...[\n options.configType === 'PRODUCTION'\n ? PreviewCompilerPlugin.webpack()\n : DevPreviewCompilerPlugin.webpack({\n projectDir: symfonyOptions.projectDir,\n additionalWatchPaths: symfonyOptions.additionalWatchPaths,\n }),\n TwigLoaderPlugin.webpack({\n twigComponentConfiguration: symfonyOptions.twigComponent,\n }),\n ],\n ],\n module: {\n ...config.module,\n rules: [...(config.module?.rules || [])],\n },\n };\n};\n\nexport const previewHead: PresetProperty<'previewHead'> = async (base: any) => dedent`\n ${base}\n \n `;\n\nexport const previewBody: PresetProperty<'previewBody'> = async (base: any) => dedent`\n ${base}\n \n `;\n","import { createUnplugin } from 'unplugin';\nimport { runSymfonyCommand } from './symfony';\nimport HtmlWebpackPlugin from 'html-webpack-plugin';\nimport { logger } from '@storybook/node-logger';\nimport dedent from 'ts-dedent';\nimport { injectPreviewHtml } from './injectPreviewHtml';\n\nconst PLUGIN_NAME = 'preview-plugin';\n\n/**\n * Compile preview HTML.\n */\nexport const PreviewCompilerPlugin = createUnplugin(() => {\n return {\n name: PLUGIN_NAME,\n webpack(compiler) {\n compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {\n // Inject previewHead and previewBody in the compiled iframe.html before it is output\n HtmlWebpackPlugin.getHooks(compilation).afterTemplateExecution.tapPromise(\n PLUGIN_NAME,\n async (params) => {\n try {\n const previewHtml = await runSymfonyCommand('storybook:generate-preview');\n params.html = injectPreviewHtml(previewHtml, params.html);\n\n return params;\n } catch (err) {\n logger.error(dedent`\n Failed to inject Symfony preview template in main iframe.html.\n ERR: ${err}\n `);\n return params;\n }\n }\n );\n });\n },\n };\n});\n","import { JSDOM } from 'jsdom';\n\nexport const injectPreviewHtml = (previewHtml: string, targetHtml: string) => {\n const previewDom = new JSDOM(previewHtml);\n\n const previewHead = previewDom.window.document.head;\n const previewBody = previewDom.window.document.body;\n\n return targetHtml\n .replace('', previewHead.innerHTML)\n .replace('', previewBody.innerHTML);\n};\n","import { createUnplugin } from 'unplugin';\nimport dedent from 'ts-dedent';\nimport VirtualModulesPlugin from 'webpack-virtual-modules';\nimport { runSymfonyCommand } from './symfony';\nimport { computeAdditionalWatchPaths } from './computeAdditionalWatchPaths';\nimport HtmlWebpackPlugin from 'html-webpack-plugin';\nimport { logger } from '@storybook/node-logger';\nimport { injectPreviewHtml } from './injectPreviewHtml';\n\nconst PLUGIN_NAME = 'dev-preview-plugin';\n\nexport type Options = {\n projectDir: string;\n additionalWatchPaths: string[];\n};\n\n/**\n * Compile preview HTML for dev with HMR .\n */\nexport const DevPreviewCompilerPlugin = createUnplugin((options) => {\n const { projectDir, additionalWatchPaths } = options;\n\n return {\n name: PLUGIN_NAME,\n enforce: 'post',\n transformInclude(id) {\n return /storybook-config-entry\\.js$/.test(id);\n },\n async transform(code) {\n return dedent`\n import { symfonyPreview } from './symfony-preview.js';\n \n ${code}\n\n window.__SYMFONY_PREVIEW__ = symfonyPreview;\n if (import.meta.webpackHot) {\n import.meta.webpackHot.accept('./symfony-preview.js', () => {\n const iframe = window.top.document.getElementById('storybook-preview-iframe');\n if (iframe) {\n iframe.src = iframe.src;\n }\n });\n }\n `;\n },\n webpack(compiler) {\n // Virtual plugin for preview module\n const v = new VirtualModulesPlugin();\n v.apply(compiler);\n\n let previewHtml = '';\n\n // Compile preview before each compilation in watch mode\n compiler.hooks.watchRun.tapPromise(PLUGIN_NAME, async () => {\n previewHtml = await runSymfonyCommand('storybook:generate-preview');\n\n // Write preview module\n v.writeModule(\n './symfony-preview.js',\n dedent`\n export const symfonyPreview = {\n html: \\`${previewHtml}\\`,\n };`\n );\n });\n\n compiler.hooks.afterCompile.tap(PLUGIN_NAME, (compilation) => {\n if ('HtmlWebpackCompiler' == compilation.name) {\n // Register additional watch paths for HMR\n const resolvedWatchPaths = computeAdditionalWatchPaths(additionalWatchPaths, projectDir);\n compilation.contextDependencies.addAll(resolvedWatchPaths.dirs);\n compilation.fileDependencies.addAll(resolvedWatchPaths.files);\n }\n });\n\n compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {\n // Inject previewHead and previewBody in the compiled iframe.html before it is output\n HtmlWebpackPlugin.getHooks(compilation).afterTemplateExecution.tapPromise(\n PLUGIN_NAME,\n async (params) => {\n try {\n params.html = injectPreviewHtml(previewHtml, params.html);\n return params;\n } catch (err) {\n logger.error(dedent`\n Failed to inject Symfony preview template in main iframe.html.\n ERR: ${err}\n `);\n return params;\n }\n }\n );\n });\n },\n };\n});\n","import { join } from 'path';\nimport isGlob from 'is-glob';\nimport { glob } from 'glob';\nimport fs from 'node:fs';\nimport { logger } from '@storybook/node-logger';\nimport dedent from 'ts-dedent';\n\ntype AdditionalWatchPaths = {\n dirs: string[];\n files: string[];\n};\n\nexport const computeAdditionalWatchPaths = (paths: string[], baseDir: string) => {\n const result: AdditionalWatchPaths = {\n dirs: [],\n files: [],\n };\n\n paths\n .map((v) => join(baseDir, v))\n .forEach((watchPath) => {\n if (isGlob(watchPath)) {\n result.files.push(\n ...glob.sync(watchPath, {\n dot: true,\n absolute: true,\n })\n );\n } else if (fs.existsSync(watchPath)) {\n const stats = fs.lstatSync(watchPath);\n (stats.isDirectory() ? result.dirs : result.files).push(watchPath);\n } else {\n logger.warn(dedent`\n Ignoring additional watch path '${watchPath}': path doesn't exists.\n `);\n }\n });\n\n return result;\n};\n","import expand from 'brace-expansion'\nimport { assertValidPattern } from './assert-valid-pattern.js'\nimport { AST, ExtglobType } from './ast.js'\nimport { escape } from './escape.js'\nimport { unescape } from './unescape.js'\n\ntype Platform =\n | 'aix'\n | 'android'\n | 'darwin'\n | 'freebsd'\n | 'haiku'\n | 'linux'\n | 'openbsd'\n | 'sunos'\n | 'win32'\n | 'cygwin'\n | 'netbsd'\n\nexport interface MinimatchOptions {\n nobrace?: boolean\n nocomment?: boolean\n nonegate?: boolean\n debug?: boolean\n noglobstar?: boolean\n noext?: boolean\n nonull?: boolean\n windowsPathsNoEscape?: boolean\n allowWindowsEscape?: boolean\n partial?: boolean\n dot?: boolean\n nocase?: boolean\n nocaseMagicOnly?: boolean\n magicalBraces?: boolean\n matchBase?: boolean\n flipNegate?: boolean\n preserveMultipleSlashes?: boolean\n optimizationLevel?: number\n platform?: Platform\n windowsNoMagicRoot?: boolean\n}\n\nexport const minimatch = (\n p: string,\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n assertValidPattern(pattern)\n\n // shortcut: comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n return false\n }\n\n return new Minimatch(pattern, options).match(p)\n}\n\n// Optimized checking for the most common glob patterns.\nconst starDotExtRE = /^\\*+([^+@!?\\*\\[\\(]*)$/\nconst starDotExtTest = (ext: string) => (f: string) =>\n !f.startsWith('.') && f.endsWith(ext)\nconst starDotExtTestDot = (ext: string) => (f: string) => f.endsWith(ext)\nconst starDotExtTestNocase = (ext: string) => {\n ext = ext.toLowerCase()\n return (f: string) => !f.startsWith('.') && f.toLowerCase().endsWith(ext)\n}\nconst starDotExtTestNocaseDot = (ext: string) => {\n ext = ext.toLowerCase()\n return (f: string) => f.toLowerCase().endsWith(ext)\n}\nconst starDotStarRE = /^\\*+\\.\\*+$/\nconst starDotStarTest = (f: string) => !f.startsWith('.') && f.includes('.')\nconst starDotStarTestDot = (f: string) =>\n f !== '.' && f !== '..' && f.includes('.')\nconst dotStarRE = /^\\.\\*+$/\nconst dotStarTest = (f: string) => f !== '.' && f !== '..' && f.startsWith('.')\nconst starRE = /^\\*+$/\nconst starTest = (f: string) => f.length !== 0 && !f.startsWith('.')\nconst starTestDot = (f: string) => f.length !== 0 && f !== '.' && f !== '..'\nconst qmarksRE = /^\\?+([^+@!?\\*\\[\\(]*)?$/\nconst qmarksTestNocase = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExt([$0])\n if (!ext) return noext\n ext = ext.toLowerCase()\n return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestNocaseDot = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExtDot([$0])\n if (!ext) return noext\n ext = ext.toLowerCase()\n return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestDot = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExtDot([$0])\n return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTest = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExt([$0])\n return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTestNoExt = ([$0]: RegExpMatchArray) => {\n const len = $0.length\n return (f: string) => f.length === len && !f.startsWith('.')\n}\nconst qmarksTestNoExtDot = ([$0]: RegExpMatchArray) => {\n const len = $0.length\n return (f: string) => f.length === len && f !== '.' && f !== '..'\n}\n\n/* c8 ignore start */\nconst defaultPlatform: Platform = (\n typeof process === 'object' && process\n ? (typeof process.env === 'object' &&\n process.env &&\n process.env.__MINIMATCH_TESTING_PLATFORM__) ||\n process.platform\n : 'posix'\n) as Platform\ntype Sep = '\\\\' | '/'\nconst path: { [k: string]: { sep: Sep } } = {\n win32: { sep: '\\\\' },\n posix: { sep: '/' },\n}\n/* c8 ignore stop */\n\nexport const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep\nminimatch.sep = sep\n\nexport const GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\n\n// any single thing other than /\n// don't need to escape / when using new RegExp()\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n\n// ** when dots are allowed. Anything goes, except .. and .\n// not (^ or / followed by one or two dots followed by $ or /),\n// followed by anything, any number of times.\nconst twoStarDot = '(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?'\n\n// not a ^ or / followed by a dot,\n// followed by anything, any number of times.\nconst twoStarNoDot = '(?:(?!(?:\\\\/|^)\\\\.).)*?'\n\nexport const filter =\n (pattern: string, options: MinimatchOptions = {}) =>\n (p: string) =>\n minimatch(p, pattern, options)\nminimatch.filter = filter\n\nconst ext = (a: MinimatchOptions, b: MinimatchOptions = {}) =>\n Object.assign({}, a, b)\n\nexport const defaults = (def: MinimatchOptions): typeof minimatch => {\n if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n return minimatch\n }\n\n const orig = minimatch\n\n const m = (p: string, pattern: string, options: MinimatchOptions = {}) =>\n orig(p, pattern, ext(def, options))\n\n return Object.assign(m, {\n Minimatch: class Minimatch extends orig.Minimatch {\n constructor(pattern: string, options: MinimatchOptions = {}) {\n super(pattern, ext(def, options))\n }\n static defaults(options: MinimatchOptions) {\n return orig.defaults(ext(def, options)).Minimatch\n }\n },\n\n AST: class AST extends orig.AST {\n /* c8 ignore start */\n constructor(\n type: ExtglobType | null,\n parent?: AST,\n options: MinimatchOptions = {}\n ) {\n super(type, parent, ext(def, options))\n }\n /* c8 ignore stop */\n\n static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n return orig.AST.fromGlob(pattern, ext(def, options))\n }\n },\n\n unescape: (\n s: string,\n options: Pick = {}\n ) => orig.unescape(s, ext(def, options)),\n\n escape: (\n s: string,\n options: Pick = {}\n ) => orig.escape(s, ext(def, options)),\n\n filter: (pattern: string, options: MinimatchOptions = {}) =>\n orig.filter(pattern, ext(def, options)),\n\n defaults: (options: MinimatchOptions) => orig.defaults(ext(def, options)),\n\n makeRe: (pattern: string, options: MinimatchOptions = {}) =>\n orig.makeRe(pattern, ext(def, options)),\n\n braceExpand: (pattern: string, options: MinimatchOptions = {}) =>\n orig.braceExpand(pattern, ext(def, options)),\n\n match: (list: string[], pattern: string, options: MinimatchOptions = {}) =>\n orig.match(list, pattern, ext(def, options)),\n\n sep: orig.sep,\n GLOBSTAR: GLOBSTAR as typeof GLOBSTAR,\n })\n}\nminimatch.defaults = defaults\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n assertValidPattern(pattern)\n\n // Thanks to Yeting Li for\n // improving this regexp to avoid a ReDOS vulnerability.\n if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n // shortcut. no need to expand.\n return [pattern]\n }\n\n return expand(pattern)\n}\nminimatch.braceExpand = braceExpand\n\n// parse a component of the expanded set.\n// At this point, no pattern may contain \"/\" in it\n// so we're going to return a 2d array, where each entry is the full\n// pattern, split on '/', and then turned into a regular expression.\n// A regexp is made at the end which joins each array with an\n// escaped /, and another full one which joins each regexp with |.\n//\n// Following the lead of Bash 4.1, note that \"**\" only has special meaning\n// when it is the *only* thing in a path portion. Otherwise, any series\n// of * is equivalent to a single *. Globstar behavior is enabled by\n// default, and can be disabled by setting options.noglobstar.\n\nexport const makeRe = (pattern: string, options: MinimatchOptions = {}) =>\n new Minimatch(pattern, options).makeRe()\nminimatch.makeRe = makeRe\n\nexport const match = (\n list: string[],\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n const mm = new Minimatch(pattern, options)\n list = list.filter(f => mm.match(f))\n if (mm.options.nonull && !list.length) {\n list.push(pattern)\n }\n return list\n}\nminimatch.match = match\n\n// replace stuff like \\* with *\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/\nconst regExpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\nexport type MMRegExp = RegExp & {\n _src?: string\n _glob?: string\n}\n\nexport type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR\nexport type ParseReturn = ParseReturnFiltered | false\n\nexport class Minimatch {\n options: MinimatchOptions\n set: ParseReturnFiltered[][]\n pattern: string\n\n windowsPathsNoEscape: boolean\n nonegate: boolean\n negate: boolean\n comment: boolean\n empty: boolean\n preserveMultipleSlashes: boolean\n partial: boolean\n globSet: string[]\n globParts: string[][]\n nocase: boolean\n\n isWindows: boolean\n platform: Platform\n windowsNoMagicRoot: boolean\n\n regexp: false | null | MMRegExp\n constructor(pattern: string, options: MinimatchOptions = {}) {\n assertValidPattern(pattern)\n\n options = options || {}\n this.options = options\n this.pattern = pattern\n this.platform = options.platform || defaultPlatform\n this.isWindows = this.platform === 'win32'\n this.windowsPathsNoEscape =\n !!options.windowsPathsNoEscape || options.allowWindowsEscape === false\n if (this.windowsPathsNoEscape) {\n this.pattern = this.pattern.replace(/\\\\/g, '/')\n }\n this.preserveMultipleSlashes = !!options.preserveMultipleSlashes\n this.regexp = null\n this.negate = false\n this.nonegate = !!options.nonegate\n this.comment = false\n this.empty = false\n this.partial = !!options.partial\n this.nocase = !!this.options.nocase\n this.windowsNoMagicRoot =\n options.windowsNoMagicRoot !== undefined\n ? options.windowsNoMagicRoot\n : !!(this.isWindows && this.nocase)\n\n this.globSet = []\n this.globParts = []\n this.set = []\n\n // make the set of regexps etc.\n this.make()\n }\n\n hasMagic(): boolean {\n if (this.options.magicalBraces && this.set.length > 1) {\n return true\n }\n for (const pattern of this.set) {\n for (const part of pattern) {\n if (typeof part !== 'string') return true\n }\n }\n return false\n }\n\n debug(..._: any[]) {}\n\n make() {\n const pattern = this.pattern\n const options = this.options\n\n // empty patterns and comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n this.comment = true\n return\n }\n\n if (!pattern) {\n this.empty = true\n return\n }\n\n // step 1: figure out negation, etc.\n this.parseNegate()\n\n // step 2: expand braces\n this.globSet = [...new Set(this.braceExpand())]\n\n if (options.debug) {\n this.debug = (...args: any[]) => console.error(...args)\n }\n\n this.debug(this.pattern, this.globSet)\n\n // step 3: now we have a set, so turn each one into a series of\n // path-portion matching patterns.\n // These will be regexps, except in the case of \"**\", which is\n // set to the GLOBSTAR object for globstar behavior,\n // and will not contain any / characters\n //\n // First, we preprocess to make the glob pattern sets a bit simpler\n // and deduped. There are some perf-killing patterns that can cause\n // problems with a glob walk, but we can simplify them down a bit.\n const rawGlobParts = this.globSet.map(s => this.slashSplit(s))\n this.globParts = this.preprocess(rawGlobParts)\n this.debug(this.pattern, this.globParts)\n\n // glob --> regexps\n let set = this.globParts.map((s, _, __) => {\n if (this.isWindows && this.windowsNoMagicRoot) {\n // check if it's a drive or unc path.\n const isUNC =\n s[0] === '' &&\n s[1] === '' &&\n (s[2] === '?' || !globMagic.test(s[2])) &&\n !globMagic.test(s[3])\n const isDrive = /^[a-z]:/i.test(s[0])\n if (isUNC) {\n return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))]\n } else if (isDrive) {\n return [s[0], ...s.slice(1).map(ss => this.parse(ss))]\n }\n }\n return s.map(ss => this.parse(ss))\n })\n\n this.debug(this.pattern, set)\n\n // filter out everything that didn't compile properly.\n this.set = set.filter(\n s => s.indexOf(false) === -1\n ) as ParseReturnFiltered[][]\n\n // do not treat the ? in UNC paths as magic\n if (this.isWindows) {\n for (let i = 0; i < this.set.length; i++) {\n const p = this.set[i]\n if (\n p[0] === '' &&\n p[1] === '' &&\n this.globParts[i][2] === '?' &&\n typeof p[3] === 'string' &&\n /^[a-z]:$/i.test(p[3])\n ) {\n p[2] = '?'\n }\n }\n }\n\n this.debug(this.pattern, this.set)\n }\n\n // various transforms to equivalent pattern sets that are\n // faster to process in a filesystem walk. The goal is to\n // eliminate what we can, and push all ** patterns as far\n // to the right as possible, even if it increases the number\n // of patterns that we have to process.\n preprocess(globParts: string[][]) {\n // if we're not in globstar mode, then turn all ** into *\n if (this.options.noglobstar) {\n for (let i = 0; i < globParts.length; i++) {\n for (let j = 0; j < globParts[i].length; j++) {\n if (globParts[i][j] === '**') {\n globParts[i][j] = '*'\n }\n }\n }\n }\n\n const { optimizationLevel = 1 } = this.options\n\n if (optimizationLevel >= 2) {\n // aggressive optimization for the purpose of fs walking\n globParts = this.firstPhasePreProcess(globParts)\n globParts = this.secondPhasePreProcess(globParts)\n } else if (optimizationLevel >= 1) {\n // just basic optimizations to remove some .. parts\n globParts = this.levelOneOptimize(globParts)\n } else {\n globParts = this.adjascentGlobstarOptimize(globParts)\n }\n\n return globParts\n }\n\n // just get rid of adjascent ** portions\n adjascentGlobstarOptimize(globParts: string[][]) {\n return globParts.map(parts => {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let i = gs\n while (parts[i + 1] === '**') {\n i++\n }\n if (i !== gs) {\n parts.splice(gs, i - gs)\n }\n }\n return parts\n })\n }\n\n // get rid of adjascent ** and resolve .. portions\n levelOneOptimize(globParts: string[][]) {\n return globParts.map(parts => {\n parts = parts.reduce((set: string[], part) => {\n const prev = set[set.length - 1]\n if (part === '**' && prev === '**') {\n return set\n }\n if (part === '..') {\n if (prev && prev !== '..' && prev !== '.' && prev !== '**') {\n set.pop()\n return set\n }\n }\n set.push(part)\n return set\n }, [])\n return parts.length === 0 ? [''] : parts\n })\n }\n\n levelTwoFileOptimize(parts: string | string[]) {\n if (!Array.isArray(parts)) {\n parts = this.slashSplit(parts)\n }\n let didSomething: boolean = false\n do {\n didSomething = false\n //
// -> 
/\n      if (!this.preserveMultipleSlashes) {\n        for (let i = 1; i < parts.length - 1; i++) {\n          const p = parts[i]\n          // don't squeeze out UNC patterns\n          if (i === 1 && p === '' && parts[0] === '') continue\n          if (p === '.' || p === '') {\n            didSomething = true\n            parts.splice(i, 1)\n            i--\n          }\n        }\n        if (\n          parts[0] === '.' &&\n          parts.length === 2 &&\n          (parts[1] === '.' || parts[1] === '')\n        ) {\n          didSomething = true\n          parts.pop()\n        }\n      }\n\n      // 
/

/../ ->

/\n      let dd: number = 0\n      while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n        const p = parts[dd - 1]\n        if (p && p !== '.' && p !== '..' && p !== '**') {\n          didSomething = true\n          parts.splice(dd - 1, 2)\n          dd -= 2\n        }\n      }\n    } while (didSomething)\n    return parts.length === 0 ? [''] : parts\n  }\n\n  // First phase: single-pattern processing\n  // 
 is 1 or more portions\n  //  is 1 or more portions\n  // 

is any portion other than ., .., '', or **\n // is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n //

// -> 
/\n  // 
/

/../ ->

/\n  // **/**/ -> **/\n  //\n  // **/*/ -> */**/ <== not valid because ** doesn't follow\n  // this WOULD be allowed if ** did follow symlinks, or * didn't\n  firstPhasePreProcess(globParts: string[][]) {\n    let didSomething = false\n    do {\n      didSomething = false\n      // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n for (let parts of globParts) {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss: number = gs\n while (parts[gss + 1] === '**') {\n //

/**/**/ -> 
/**/\n            gss++\n          }\n          // eg, if gs is 2 and gss is 4, that means we have 3 **\n          // parts, and can remove 2 of them.\n          if (gss > gs) {\n            parts.splice(gs + 1, gss - gs)\n          }\n\n          let next = parts[gs + 1]\n          const p = parts[gs + 2]\n          const p2 = parts[gs + 3]\n          if (next !== '..') continue\n          if (\n            !p ||\n            p === '.' ||\n            p === '..' ||\n            !p2 ||\n            p2 === '.' ||\n            p2 === '..'\n          ) {\n            continue\n          }\n          didSomething = true\n          // edit parts in place, and push the new one\n          parts.splice(gs, 1)\n          const other = parts.slice(0)\n          other[gs] = '**'\n          globParts.push(other)\n          gs--\n        }\n\n        // 
// -> 
/\n        if (!this.preserveMultipleSlashes) {\n          for (let i = 1; i < parts.length - 1; i++) {\n            const p = parts[i]\n            // don't squeeze out UNC patterns\n            if (i === 1 && p === '' && parts[0] === '') continue\n            if (p === '.' || p === '') {\n              didSomething = true\n              parts.splice(i, 1)\n              i--\n            }\n          }\n          if (\n            parts[0] === '.' &&\n            parts.length === 2 &&\n            (parts[1] === '.' || parts[1] === '')\n          ) {\n            didSomething = true\n            parts.pop()\n          }\n        }\n\n        // 
/

/../ ->

/\n        let dd: number = 0\n        while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n          const p = parts[dd - 1]\n          if (p && p !== '.' && p !== '..' && p !== '**') {\n            didSomething = true\n            const needDot = dd === 1 && parts[dd + 1] === '**'\n            const splin = needDot ? ['.'] : []\n            parts.splice(dd - 1, 2, ...splin)\n            if (parts.length === 0) parts.push('')\n            dd -= 2\n          }\n        }\n      }\n    } while (didSomething)\n\n    return globParts\n  }\n\n  // second phase: multi-pattern dedupes\n  // {
/*/,
/

/} ->

/*/\n  // {
/,
/} -> 
/\n  // {
/**/,
/} -> 
/**/\n  //\n  // {
/**/,
/**/

/} ->

/**/\n  // ^-- not valid because ** doens't follow symlinks\n  secondPhasePreProcess(globParts: string[][]): string[][] {\n    for (let i = 0; i < globParts.length - 1; i++) {\n      for (let j = i + 1; j < globParts.length; j++) {\n        const matched = this.partsMatch(\n          globParts[i],\n          globParts[j],\n          !this.preserveMultipleSlashes\n        )\n        if (!matched) continue\n        globParts[i] = matched\n        globParts[j] = []\n      }\n    }\n    return globParts.filter(gs => gs.length)\n  }\n\n  partsMatch(\n    a: string[],\n    b: string[],\n    emptyGSMatch: boolean = false\n  ): false | string[] {\n    let ai = 0\n    let bi = 0\n    let result: string[] = []\n    let which: string = ''\n    while (ai < a.length && bi < b.length) {\n      if (a[ai] === b[bi]) {\n        result.push(which === 'b' ? b[bi] : a[ai])\n        ai++\n        bi++\n      } else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {\n        result.push(a[ai])\n        ai++\n      } else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {\n        result.push(b[bi])\n        bi++\n      } else if (\n        a[ai] === '*' &&\n        b[bi] &&\n        (this.options.dot || !b[bi].startsWith('.')) &&\n        b[bi] !== '**'\n      ) {\n        if (which === 'b') return false\n        which = 'a'\n        result.push(a[ai])\n        ai++\n        bi++\n      } else if (\n        b[bi] === '*' &&\n        a[ai] &&\n        (this.options.dot || !a[ai].startsWith('.')) &&\n        a[ai] !== '**'\n      ) {\n        if (which === 'a') return false\n        which = 'b'\n        result.push(b[bi])\n        ai++\n        bi++\n      } else {\n        return false\n      }\n    }\n    // if we fall out of the loop, it means they two are identical\n    // as long as their lengths match\n    return a.length === b.length && result\n  }\n\n  parseNegate() {\n    if (this.nonegate) return\n\n    const pattern = this.pattern\n    let negate = false\n    let negateOffset = 0\n\n    for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n      negate = !negate\n      negateOffset++\n    }\n\n    if (negateOffset) this.pattern = pattern.slice(negateOffset)\n    this.negate = negate\n  }\n\n  // set partial to true to test if, for example,\n  // \"/a/b\" matches the start of \"/*/b/*/d\"\n  // Partial means, if you run out of file before you run\n  // out of pattern, then that's fine, as long as all\n  // the parts match.\n  matchOne(file: string[], pattern: ParseReturn[], partial: boolean = false) {\n    const options = this.options\n\n    // UNC paths like //?/X:/... can match X:/... and vice versa\n    // Drive letters in absolute drive or unc paths are always compared\n    // case-insensitively.\n    if (this.isWindows) {\n      const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0])\n      const fileUNC =\n        !fileDrive &&\n        file[0] === '' &&\n        file[1] === '' &&\n        file[2] === '?' &&\n        /^[a-z]:$/i.test(file[3])\n\n      const patternDrive =\n        typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0])\n      const patternUNC =\n        !patternDrive &&\n        pattern[0] === '' &&\n        pattern[1] === '' &&\n        pattern[2] === '?' &&\n        typeof pattern[3] === 'string' &&\n        /^[a-z]:$/i.test(pattern[3])\n\n      const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined\n      const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined\n      if (typeof fdi === 'number' && typeof pdi === 'number') {\n        const [fd, pd]: [string, string] = [file[fdi], pattern[pdi] as string]\n        if (fd.toLowerCase() === pd.toLowerCase()) {\n          pattern[pdi] = fd\n          if (pdi > fdi) {\n            pattern = pattern.slice( pdi)\n          } else if (fdi > pdi) {\n            file = file.slice(fdi)\n          }\n        }\n      }\n    }\n\n    // resolve and reduce . and .. portions in the file as well.\n    // dont' need to do the second phase, because it's only one string[]\n    const { optimizationLevel = 1 } = this.options\n    if (optimizationLevel >= 2) {\n      file = this.levelTwoFileOptimize(file)\n    }\n\n    this.debug('matchOne', this, { file, pattern })\n    this.debug('matchOne', file.length, pattern.length)\n\n    for (\n      var fi = 0, pi = 0, fl = file.length, pl = pattern.length;\n      fi < fl && pi < pl;\n      fi++, pi++\n    ) {\n      this.debug('matchOne loop')\n      var p = pattern[pi]\n      var f = file[fi]\n\n      this.debug(pattern, p, f)\n\n      // should be impossible.\n      // some invalid regexp stuff in the set.\n      /* c8 ignore start */\n      if (p === false) {\n        return false\n      }\n      /* c8 ignore stop */\n\n      if (p === GLOBSTAR) {\n        this.debug('GLOBSTAR', [pattern, p, f])\n\n        // \"**\"\n        // a/**/b/**/c would match the following:\n        // a/b/x/y/z/c\n        // a/x/y/z/b/c\n        // a/b/x/b/x/c\n        // a/b/c\n        // To do this, take the rest of the pattern after\n        // the **, and see if it would match the file remainder.\n        // If so, return success.\n        // If not, the ** \"swallows\" a segment, and try again.\n        // This is recursively awful.\n        //\n        // a/**/b/**/c matching a/b/x/y/z/c\n        // - a matches a\n        // - doublestar\n        //   - matchOne(b/x/y/z/c, b/**/c)\n        //     - b matches b\n        //     - doublestar\n        //       - matchOne(x/y/z/c, c) -> no\n        //       - matchOne(y/z/c, c) -> no\n        //       - matchOne(z/c, c) -> no\n        //       - matchOne(c, c) yes, hit\n        var fr = fi\n        var pr = pi + 1\n        if (pr === pl) {\n          this.debug('** at the end')\n          // a ** at the end will just swallow the rest.\n          // We have found a match.\n          // however, it will not swallow /.x, unless\n          // options.dot is set.\n          // . and .. are *never* matched by **, for explosively\n          // exponential reasons.\n          for (; fi < fl; fi++) {\n            if (\n              file[fi] === '.' ||\n              file[fi] === '..' ||\n              (!options.dot && file[fi].charAt(0) === '.')\n            )\n              return false\n          }\n          return true\n        }\n\n        // ok, let's see if we can swallow whatever we can.\n        while (fr < fl) {\n          var swallowee = file[fr]\n\n          this.debug('\\nglobstar while', file, fr, pattern, pr, swallowee)\n\n          // XXX remove this slice.  Just pass the start index.\n          if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {\n            this.debug('globstar found match!', fr, fl, swallowee)\n            // found a match.\n            return true\n          } else {\n            // can't swallow \".\" or \"..\" ever.\n            // can only swallow \".foo\" when explicitly asked.\n            if (\n              swallowee === '.' ||\n              swallowee === '..' ||\n              (!options.dot && swallowee.charAt(0) === '.')\n            ) {\n              this.debug('dot detected!', file, fr, pattern, pr)\n              break\n            }\n\n            // ** swallows a segment, and continue.\n            this.debug('globstar swallow a segment, and continue')\n            fr++\n          }\n        }\n\n        // no match was found.\n        // However, in partial mode, we can't say this is necessarily over.\n        /* c8 ignore start */\n        if (partial) {\n          // ran out of file\n          this.debug('\\n>>> no match, partial?', file, fr, pattern, pr)\n          if (fr === fl) {\n            return true\n          }\n        }\n        /* c8 ignore stop */\n        return false\n      }\n\n      // something other than **\n      // non-magic patterns just have to match exactly\n      // patterns with magic have been turned into regexps.\n      let hit: boolean\n      if (typeof p === 'string') {\n        hit = f === p\n        this.debug('string match', p, f, hit)\n      } else {\n        hit = p.test(f)\n        this.debug('pattern match', p, f, hit)\n      }\n\n      if (!hit) return false\n    }\n\n    // Note: ending in / means that we'll get a final \"\"\n    // at the end of the pattern.  This can only match a\n    // corresponding \"\" at the end of the file.\n    // If the file ends in /, then it can only match a\n    // a pattern that ends in /, unless the pattern just\n    // doesn't have any more for it. But, a/b/ should *not*\n    // match \"a/b/*\", even though \"\" matches against the\n    // [^/]*? pattern, except in partial mode, where it might\n    // simply not be reached yet.\n    // However, a/b/ should still satisfy a/*\n\n    // now either we fell off the end of the pattern, or we're done.\n    if (fi === fl && pi === pl) {\n      // ran out of pattern and filename at the same time.\n      // an exact hit!\n      return true\n    } else if (fi === fl) {\n      // ran out of file, but still had pattern left.\n      // this is ok if we're doing the match as part of\n      // a glob fs traversal.\n      return partial\n    } else if (pi === pl) {\n      // ran out of pattern, still have file left.\n      // this is only acceptable if we're on the very last\n      // empty segment of a file with a trailing slash.\n      // a/* should match a/b/\n      return fi === fl - 1 && file[fi] === ''\n\n      /* c8 ignore start */\n    } else {\n      // should be unreachable.\n      throw new Error('wtf?')\n    }\n    /* c8 ignore stop */\n  }\n\n  braceExpand() {\n    return braceExpand(this.pattern, this.options)\n  }\n\n  parse(pattern: string): ParseReturn {\n    assertValidPattern(pattern)\n\n    const options = this.options\n\n    // shortcuts\n    if (pattern === '**') return GLOBSTAR\n    if (pattern === '') return ''\n\n    // far and away, the most common glob pattern parts are\n    // *, *.*, and *.  Add a fast check method for those.\n    let m: RegExpMatchArray | null\n    let fastTest: null | ((f: string) => boolean) = null\n    if ((m = pattern.match(starRE))) {\n      fastTest = options.dot ? starTestDot : starTest\n    } else if ((m = pattern.match(starDotExtRE))) {\n      fastTest = (\n        options.nocase\n          ? options.dot\n            ? starDotExtTestNocaseDot\n            : starDotExtTestNocase\n          : options.dot\n          ? starDotExtTestDot\n          : starDotExtTest\n      )(m[1])\n    } else if ((m = pattern.match(qmarksRE))) {\n      fastTest = (\n        options.nocase\n          ? options.dot\n            ? qmarksTestNocaseDot\n            : qmarksTestNocase\n          : options.dot\n          ? qmarksTestDot\n          : qmarksTest\n      )(m)\n    } else if ((m = pattern.match(starDotStarRE))) {\n      fastTest = options.dot ? starDotStarTestDot : starDotStarTest\n    } else if ((m = pattern.match(dotStarRE))) {\n      fastTest = dotStarTest\n    }\n\n    const re = AST.fromGlob(pattern, this.options).toMMPattern()\n    return fastTest ? Object.assign(re, { test: fastTest }) : re\n  }\n\n  makeRe() {\n    if (this.regexp || this.regexp === false) return this.regexp\n\n    // at this point, this.set is a 2d array of partial\n    // pattern strings, or \"**\".\n    //\n    // It's better to use .match().  This function shouldn't\n    // be used, really, but it's pretty convenient sometimes,\n    // when you just want to work with a regex.\n    const set = this.set\n\n    if (!set.length) {\n      this.regexp = false\n      return this.regexp\n    }\n    const options = this.options\n\n    const twoStar = options.noglobstar\n      ? star\n      : options.dot\n      ? twoStarDot\n      : twoStarNoDot\n    const flags = new Set(options.nocase ? ['i'] : [])\n\n    // regexpify non-globstar patterns\n    // if ** is only item, then we just do one twoStar\n    // if ** is first, and there are more, prepend (\\/|twoStar\\/)? to next\n    // if ** is last, append (\\/twoStar|) to previous\n    // if ** is in the middle, append (\\/|\\/twoStar\\/) to previous\n    // then filter out GLOBSTAR symbols\n    let re = set\n      .map(pattern => {\n        const pp: (string | typeof GLOBSTAR)[] = pattern.map(p => {\n          if (p instanceof RegExp) {\n            for (const f of p.flags.split('')) flags.add(f)\n          }\n          return typeof p === 'string'\n            ? regExpEscape(p)\n            : p === GLOBSTAR\n            ? GLOBSTAR\n            : p._src\n        }) as (string | typeof GLOBSTAR)[]\n        pp.forEach((p, i) => {\n          const next = pp[i + 1]\n          const prev = pp[i - 1]\n          if (p !== GLOBSTAR || prev === GLOBSTAR) {\n            return\n          }\n          if (prev === undefined) {\n            if (next !== undefined && next !== GLOBSTAR) {\n              pp[i + 1] = '(?:\\\\/|' + twoStar + '\\\\/)?' + next\n            } else {\n              pp[i] = twoStar\n            }\n          } else if (next === undefined) {\n            pp[i - 1] = prev + '(?:\\\\/|' + twoStar + ')?'\n          } else if (next !== GLOBSTAR) {\n            pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + '\\\\/)' + next\n            pp[i + 1] = GLOBSTAR\n          }\n        })\n        return pp.filter(p => p !== GLOBSTAR).join('/')\n      })\n      .join('|')\n\n    // need to wrap in parens if we had more than one thing with |,\n    // otherwise only the first will be anchored to ^ and the last to $\n    const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', '']\n    // must match entire pattern\n    // ending in a * or ** will make it less strict.\n    re = '^' + open + re + close + '$'\n\n    // can match anything, as long as it's not this.\n    if (this.negate) re = '^(?!' + re + ').+$'\n\n    try {\n      this.regexp = new RegExp(re, [...flags].join(''))\n      /* c8 ignore start */\n    } catch (ex) {\n      // should be impossible\n      this.regexp = false\n    }\n    /* c8 ignore stop */\n    return this.regexp\n  }\n\n  slashSplit(p: string) {\n    // if p starts with // on windows, we preserve that\n    // so that UNC paths aren't broken.  Otherwise, any number of\n    // / characters are coalesced into one, unless\n    // preserveMultipleSlashes is set to true.\n    if (this.preserveMultipleSlashes) {\n      return p.split('/')\n    } else if (this.isWindows && /^\\/\\/[^\\/]+/.test(p)) {\n      // add an extra '' for the one we lose\n      return ['', ...p.split(/\\/+/)]\n    } else {\n      return p.split(/\\/+/)\n    }\n  }\n\n  match(f: string, partial = this.partial) {\n    this.debug('match', f, this.pattern)\n    // short-circuit in the case of busted things.\n    // comments, etc.\n    if (this.comment) {\n      return false\n    }\n    if (this.empty) {\n      return f === ''\n    }\n\n    if (f === '/' && partial) {\n      return true\n    }\n\n    const options = this.options\n\n    // windows: need to use /, not \\\n    if (this.isWindows) {\n      f = f.split('\\\\').join('/')\n    }\n\n    // treat the test path as a set of pathparts.\n    const ff = this.slashSplit(f)\n    this.debug(this.pattern, 'split', ff)\n\n    // just ONE of the pattern sets in this.set needs to match\n    // in order for it to be valid.  If negating, then just one\n    // match means that we have failed.\n    // Either way, return on the first hit.\n\n    const set = this.set\n    this.debug(this.pattern, 'set', set)\n\n    // Find the basename of the path by looking for the last non-empty segment\n    let filename: string = ff[ff.length - 1]\n    if (!filename) {\n      for (let i = ff.length - 2; !filename && i >= 0; i--) {\n        filename = ff[i]\n      }\n    }\n\n    for (let i = 0; i < set.length; i++) {\n      const pattern = set[i]\n      let file = ff\n      if (options.matchBase && pattern.length === 1) {\n        file = [filename]\n      }\n      const hit = this.matchOne(file, pattern, partial)\n      if (hit) {\n        if (options.flipNegate) {\n          return true\n        }\n        return !this.negate\n      }\n    }\n\n    // didn't get any hits.  this is success if it's a negative\n    // pattern, failure otherwise.\n    if (options.flipNegate) {\n      return false\n    }\n    return this.negate\n  }\n\n  static defaults(def: MinimatchOptions) {\n    return minimatch.defaults(def).Minimatch\n  }\n}\n/* c8 ignore start */\nexport { AST } from './ast.js'\nexport { escape } from './escape.js'\nexport { unescape } from './unescape.js'\n/* c8 ignore stop */\nminimatch.AST = AST\nminimatch.Minimatch = Minimatch\nminimatch.escape = escape\nminimatch.unescape = unescape\n","const MAX_PATTERN_LENGTH = 1024 * 64\nexport const assertValidPattern: (pattern: any) => void = (\n  pattern: any\n): asserts pattern is string => {\n  if (typeof pattern !== 'string') {\n    throw new TypeError('invalid pattern')\n  }\n\n  if (pattern.length > MAX_PATTERN_LENGTH) {\n    throw new TypeError('pattern is too long')\n  }\n}\n","// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { : [, /u flag required, negated]\nconst posixClasses: { [k: string]: [e: string, u: boolean, n?: boolean] } = {\n  '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}', true],\n  '[:alpha:]': ['\\\\p{L}\\\\p{Nl}', true],\n  '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f', false],\n  '[:blank:]': ['\\\\p{Zs}\\\\t', true],\n  '[:cntrl:]': ['\\\\p{Cc}', true],\n  '[:digit:]': ['\\\\p{Nd}', true],\n  '[:graph:]': ['\\\\p{Z}\\\\p{C}', true, true],\n  '[:lower:]': ['\\\\p{Ll}', true],\n  '[:print:]': ['\\\\p{C}', true],\n  '[:punct:]': ['\\\\p{P}', true],\n  '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f', true],\n  '[:upper:]': ['\\\\p{Lu}', true],\n  '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}', true],\n  '[:xdigit:]': ['A-Fa-f0-9', false],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n// escape all regexp magic characters\nconst regexpEscape = (s: string) =>\n  s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// everything has already been escaped, we just have to join\nconst rangesToString = (ranges: string[]): string => ranges.join('')\n\nexport type ParseClassResult = [\n  src: string,\n  uFlag: boolean,\n  consumed: number,\n  hasMagic: boolean\n]\n\n// takes a glob string at a posix brace expression, and returns\n// an equivalent regular expression source, and boolean indicating\n// whether the /u flag needs to be applied, and the number of chars\n// consumed to parse the character class.\n// This also removes out of order ranges, and returns ($.) if the\n// entire class just no good.\nexport const parseClass = (\n  glob: string,\n  position: number\n): ParseClassResult => {\n  const pos = position\n  /* c8 ignore start */\n  if (glob.charAt(pos) !== '[') {\n    throw new Error('not in a brace expression')\n  }\n  /* c8 ignore stop */\n  const ranges: string[] = []\n  const negs: string[] = []\n\n  let i = pos + 1\n  let sawStart = false\n  let uflag = false\n  let escaping = false\n  let negate = false\n  let endPos = pos\n  let rangeStart = ''\n  WHILE: while (i < glob.length) {\n    const c = glob.charAt(i)\n    if ((c === '!' || c === '^') && i === pos + 1) {\n      negate = true\n      i++\n      continue\n    }\n\n    if (c === ']' && sawStart && !escaping) {\n      endPos = i + 1\n      break\n    }\n\n    sawStart = true\n    if (c === '\\\\') {\n      if (!escaping) {\n        escaping = true\n        i++\n        continue\n      }\n      // escaped \\ char, fall through and treat like normal char\n    }\n    if (c === '[' && !escaping) {\n      // either a posix class, a collation equivalent, or just a [\n      for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {\n        if (glob.startsWith(cls, i)) {\n          // invalid, [a-[] is fine, but not [a-[:alpha]]\n          if (rangeStart) {\n            return ['$.', false, glob.length - pos, true]\n          }\n          i += cls.length\n          if (neg) negs.push(unip)\n          else ranges.push(unip)\n          uflag = uflag || u\n          continue WHILE\n        }\n      }\n    }\n\n    // now it's just a normal character, effectively\n    escaping = false\n    if (rangeStart) {\n      // throw this range away if it's not valid, but others\n      // can still match.\n      if (c > rangeStart) {\n        ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c))\n      } else if (c === rangeStart) {\n        ranges.push(braceEscape(c))\n      }\n      rangeStart = ''\n      i++\n      continue\n    }\n\n    // now might be the start of a range.\n    // can be either c-d or c-] or c] or c] at this point\n    if (glob.startsWith('-]', i + 1)) {\n      ranges.push(braceEscape(c + '-'))\n      i += 2\n      continue\n    }\n    if (glob.startsWith('-', i + 1)) {\n      rangeStart = c\n      i += 2\n      continue\n    }\n\n    // not the start of a range, just a single character\n    ranges.push(braceEscape(c))\n    i++\n  }\n\n  if (endPos < i) {\n    // didn't see the end of the class, not a valid class,\n    // but might still be valid as a literal match.\n    return ['', false, 0, false]\n  }\n\n  // if we got no ranges and no negates, then we have a range that\n  // cannot possibly match anything, and that poisons the whole glob\n  if (!ranges.length && !negs.length) {\n    return ['$.', false, glob.length - pos, true]\n  }\n\n  // if we got one positive range, and it's a single character, then that's\n  // not actually a magic pattern, it's just that one literal character.\n  // we should not treat that as \"magic\", we should just return the literal\n  // character. [_] is a perfectly valid way to escape glob magic chars.\n  if (\n    negs.length === 0 &&\n    ranges.length === 1 &&\n    /^\\\\?.$/.test(ranges[0]) &&\n    !negate\n  ) {\n    const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]\n    return [regexpEscape(r), false, endPos - pos, false]\n  }\n\n  const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'\n  const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'\n  const comb =\n    ranges.length && negs.length\n      ? '(' + sranges + '|' + snegs + ')'\n      : ranges.length\n      ? sranges\n      : snegs\n\n  return [comb, uflag, endPos - pos, true]\n}\n","import { MinimatchOptions } from './index.js'\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link windowsPathsNoEscape} option is used, then square-brace\n * escapes are removed, but not backslash escapes.  For example, it will turn\n * the string `'[*]'` into `*`, but it will not turn `'\\\\*'` into `'*'`,\n * becuase `\\` is a path separator in `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both brace escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n */\nexport const unescape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n  }: Pick = {}\n) => {\n  return windowsPathsNoEscape\n    ? s.replace(/\\[([^\\/\\\\])\\]/g, '$1')\n    : s.replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, '$1$2').replace(/\\\\([^\\/])/g, '$1')\n}\n","// parse a single path portion\n\nimport { parseClass } from './brace-expressions.js'\nimport { MinimatchOptions, MMRegExp } from './index.js'\nimport { unescape } from './unescape.js'\n\n// classes [] are handled by the parseClass method\n// for positive extglobs, we sub-parse the contents, and combine,\n// with the appropriate regexp close.\n// for negative extglobs, we sub-parse the contents, but then\n// have to include the rest of the pattern, then the parent, etc.,\n// as the thing that cannot be because RegExp negative lookaheads\n// are different from globs.\n//\n// So for example:\n// a@(i|w!(x|y)z|j)b => ^a(i|w((!?(x|y)zb).*)z|j)b$\n//   1   2 3   4 5 6      1   2    3   46      5 6\n//\n// Assembling the extglob requires not just the negated patterns themselves,\n// but also anything following the negative patterns up to the boundary\n// of the current pattern, plus anything following in the parent pattern.\n//\n//\n// So, first, we parse the string into an AST of extglobs, without turning\n// anything into regexps yet.\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y']}, 'z'], ['j']]}, 'b']\n//\n// Then, for all the negative extglobs, we append whatever comes after in\n// each parent as their tail\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y'], 'z', 'b'}, 'z'], ['j']]}, 'b']\n//\n// Lastly, we turn each of these pieces into a regexp, and join\n//\n//                                 v----- .* because there's more following,\n//                                 v    v  otherwise, .+ because it must be\n//                                 v    v  *something* there.\n// ['^a', {@ ['i', 'w(?:(!?(?:x|y).*zb$).*)z', 'j' ]}, 'b$']\n//   copy what follows into here--^^^^^\n// ['^a', '(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)', 'b$']\n// ['^a(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)b$']\n\nexport type ExtglobType = '!' | '?' | '+' | '*' | '@'\nconst types = new Set(['!', '?', '+', '*', '@'])\nconst isExtglobType = (c: string): c is ExtglobType =>\n  types.has(c as ExtglobType)\n\n// Patterns that get prepended to bind to the start of either the\n// entire string, or just a single path portion, to prevent dots\n// and/or traversal patterns, when needed.\n// Exts don't need the ^ or / bit, because the root binds that already.\nconst startNoTraversal = '(?!(?:^|/)\\\\.\\\\.?(?:$|/))'\nconst startNoDot = '(?!\\\\.)'\n\n// characters that indicate a start of pattern needs the \"no dots\" bit,\n// because a dot *might* be matched. ( is not in the list, because in\n// the case of a child extglob, it will handle the prevention itself.\nconst addPatternStart = new Set(['[', '.'])\n// cases where traversal is A-OK, no dot prevention needed\nconst justDots = new Set(['..', '.'])\nconst reSpecials = new Set('().*{}+?[]^$\\\\!')\nconst regExpEscape = (s: string) =>\n  s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// any single thing other than /\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n// use + when we need to ensure that *something* matches, because the * is\n// the only thing in the path portion.\nconst starNoEmpty = qmark + '+?'\n\n// remove the \\ chars that we added if we end up doing a nonmagic compare\n// const deslash = (s: string) => s.replace(/\\\\(.)/g, '$1')\n\nexport class AST {\n  type: ExtglobType | null\n  readonly #root: AST\n\n  #hasMagic?: boolean\n  #uflag: boolean = false\n  #parts: (string | AST)[] = []\n  readonly #parent?: AST\n  readonly #parentIndex: number\n  #negs: AST[]\n  #filledNegs: boolean = false\n  #options: MinimatchOptions\n  #toString?: string\n  // set to true if it's an extglob with no children\n  // (which really means one child of '')\n  #emptyExt: boolean = false\n\n  constructor(\n    type: ExtglobType | null,\n    parent?: AST,\n    options: MinimatchOptions = {}\n  ) {\n    this.type = type\n    // extglobs are inherently magical\n    if (type) this.#hasMagic = true\n    this.#parent = parent\n    this.#root = this.#parent ? this.#parent.#root : this\n    this.#options = this.#root === this ? options : this.#root.#options\n    this.#negs = this.#root === this ? [] : this.#root.#negs\n    if (type === '!' && !this.#root.#filledNegs) this.#negs.push(this)\n    this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0\n  }\n\n  get hasMagic(): boolean | undefined {\n    /* c8 ignore start */\n    if (this.#hasMagic !== undefined) return this.#hasMagic\n    /* c8 ignore stop */\n    for (const p of this.#parts) {\n      if (typeof p === 'string') continue\n      if (p.type || p.hasMagic) return (this.#hasMagic = true)\n    }\n    // note: will be undefined until we generate the regexp src and find out\n    return this.#hasMagic\n  }\n\n  // reconstructs the pattern\n  toString(): string {\n    if (this.#toString !== undefined) return this.#toString\n    if (!this.type) {\n      return (this.#toString = this.#parts.map(p => String(p)).join(''))\n    } else {\n      return (this.#toString =\n        this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')')\n    }\n  }\n\n  #fillNegs() {\n    /* c8 ignore start */\n    if (this !== this.#root) throw new Error('should only call on root')\n    if (this.#filledNegs) return this\n    /* c8 ignore stop */\n\n    // call toString() once to fill this out\n    this.toString()\n    this.#filledNegs = true\n    let n: AST | undefined\n    while ((n = this.#negs.pop())) {\n      if (n.type !== '!') continue\n      // walk up the tree, appending everthing that comes AFTER parentIndex\n      let p: AST | undefined = n\n      let pp = p.#parent\n      while (pp) {\n        for (\n          let i = p.#parentIndex + 1;\n          !pp.type && i < pp.#parts.length;\n          i++\n        ) {\n          for (const part of n.#parts) {\n            /* c8 ignore start */\n            if (typeof part === 'string') {\n              throw new Error('string part in extglob AST??')\n            }\n            /* c8 ignore stop */\n            part.copyIn(pp.#parts[i])\n          }\n        }\n        p = pp\n        pp = p.#parent\n      }\n    }\n    return this\n  }\n\n  push(...parts: (string | AST)[]) {\n    for (const p of parts) {\n      if (p === '') continue\n      /* c8 ignore start */\n      if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {\n        throw new Error('invalid part: ' + p)\n      }\n      /* c8 ignore stop */\n      this.#parts.push(p)\n    }\n  }\n\n  toJSON() {\n    const ret: any[] =\n      this.type === null\n        ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))\n        : [this.type, ...this.#parts.map(p => (p as AST).toJSON())]\n    if (this.isStart() && !this.type) ret.unshift([])\n    if (\n      this.isEnd() &&\n      (this === this.#root ||\n        (this.#root.#filledNegs && this.#parent?.type === '!'))\n    ) {\n      ret.push({})\n    }\n    return ret\n  }\n\n  isStart(): boolean {\n    if (this.#root === this) return true\n    // if (this.type) return !!this.#parent?.isStart()\n    if (!this.#parent?.isStart()) return false\n    if (this.#parentIndex === 0) return true\n    // if everything AHEAD of this is a negation, then it's still the \"start\"\n    const p = this.#parent\n    for (let i = 0; i < this.#parentIndex; i++) {\n      const pp = p.#parts[i]\n      if (!(pp instanceof AST && pp.type === '!')) {\n        return false\n      }\n    }\n    return true\n  }\n\n  isEnd(): boolean {\n    if (this.#root === this) return true\n    if (this.#parent?.type === '!') return true\n    if (!this.#parent?.isEnd()) return false\n    if (!this.type) return this.#parent?.isEnd()\n    // if not root, it'll always have a parent\n    /* c8 ignore start */\n    const pl = this.#parent ? this.#parent.#parts.length : 0\n    /* c8 ignore stop */\n    return this.#parentIndex === pl - 1\n  }\n\n  copyIn(part: AST | string) {\n    if (typeof part === 'string') this.push(part)\n    else this.push(part.clone(this))\n  }\n\n  clone(parent: AST) {\n    const c = new AST(this.type, parent)\n    for (const p of this.#parts) {\n      c.copyIn(p)\n    }\n    return c\n  }\n\n  static #parseAST(\n    str: string,\n    ast: AST,\n    pos: number,\n    opt: MinimatchOptions\n  ): number {\n    let escaping = false\n    let inBrace = false\n    let braceStart = -1\n    let braceNeg = false\n    if (ast.type === null) {\n      // outside of a extglob, append until we find a start\n      let i = pos\n      let acc = ''\n      while (i < str.length) {\n        const c = str.charAt(i++)\n        // still accumulate escapes at this point, but we do ignore\n        // starts that are escaped\n        if (escaping || c === '\\\\') {\n          escaping = !escaping\n          acc += c\n          continue\n        }\n\n        if (inBrace) {\n          if (i === braceStart + 1) {\n            if (c === '^' || c === '!') {\n              braceNeg = true\n            }\n          } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n            inBrace = false\n          }\n          acc += c\n          continue\n        } else if (c === '[') {\n          inBrace = true\n          braceStart = i\n          braceNeg = false\n          acc += c\n          continue\n        }\n\n        if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {\n          ast.push(acc)\n          acc = ''\n          const ext = new AST(c, ast)\n          i = AST.#parseAST(str, ext, i, opt)\n          ast.push(ext)\n          continue\n        }\n        acc += c\n      }\n      ast.push(acc)\n      return i\n    }\n\n    // some kind of extglob, pos is at the (\n    // find the next | or )\n    let i = pos + 1\n    let part = new AST(null, ast)\n    const parts: AST[] = []\n    let acc = ''\n    while (i < str.length) {\n      const c = str.charAt(i++)\n      // still accumulate escapes at this point, but we do ignore\n      // starts that are escaped\n      if (escaping || c === '\\\\') {\n        escaping = !escaping\n        acc += c\n        continue\n      }\n\n      if (inBrace) {\n        if (i === braceStart + 1) {\n          if (c === '^' || c === '!') {\n            braceNeg = true\n          }\n        } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n          inBrace = false\n        }\n        acc += c\n        continue\n      } else if (c === '[') {\n        inBrace = true\n        braceStart = i\n        braceNeg = false\n        acc += c\n        continue\n      }\n\n      if (isExtglobType(c) && str.charAt(i) === '(') {\n        part.push(acc)\n        acc = ''\n        const ext = new AST(c, part)\n        part.push(ext)\n        i = AST.#parseAST(str, ext, i, opt)\n        continue\n      }\n      if (c === '|') {\n        part.push(acc)\n        acc = ''\n        parts.push(part)\n        part = new AST(null, ast)\n        continue\n      }\n      if (c === ')') {\n        if (acc === '' && ast.#parts.length === 0) {\n          ast.#emptyExt = true\n        }\n        part.push(acc)\n        acc = ''\n        ast.push(...parts, part)\n        return i\n      }\n      acc += c\n    }\n\n    // unfinished extglob\n    // if we got here, it was a malformed extglob! not an extglob, but\n    // maybe something else in there.\n    ast.type = null\n    ast.#hasMagic = undefined\n    ast.#parts = [str.substring(pos - 1)]\n    return i\n  }\n\n  static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n    const ast = new AST(null, undefined, options)\n    AST.#parseAST(pattern, ast, 0, options)\n    return ast\n  }\n\n  // returns the regular expression if there's magic, or the unescaped\n  // string if not.\n  toMMPattern(): MMRegExp | string {\n    // should only be called on root\n    /* c8 ignore start */\n    if (this !== this.#root) return this.#root.toMMPattern()\n    /* c8 ignore stop */\n    const glob = this.toString()\n    const [re, body, hasMagic, uflag] = this.toRegExpSource()\n    // if we're in nocase mode, and not nocaseMagicOnly, then we do\n    // still need a regular expression if we have to case-insensitively\n    // match capital/lowercase characters.\n    const anyMagic =\n      hasMagic ||\n      this.#hasMagic ||\n      (this.#options.nocase &&\n        !this.#options.nocaseMagicOnly &&\n        glob.toUpperCase() !== glob.toLowerCase())\n    if (!anyMagic) {\n      return body\n    }\n\n    const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '')\n    return Object.assign(new RegExp(`^${re}$`, flags), {\n      _src: re,\n      _glob: glob,\n    })\n  }\n\n  // returns the string match, the regexp source, whether there's magic\n  // in the regexp (so a regular expression is required) and whether or\n  // not the uflag is needed for the regular expression (for posix classes)\n  // TODO: instead of injecting the start/end at this point, just return\n  // the BODY of the regexp, along with the start/end portions suitable\n  // for binding the start/end in either a joined full-path makeRe context\n  // (where we bind to (^|/), or a standalone matchPart context (where\n  // we bind to ^, and not /).  Otherwise slashes get duped!\n  //\n  // In part-matching mode, the start is:\n  // - if not isStart: nothing\n  // - if traversal possible, but not allowed: ^(?!\\.\\.?$)\n  // - if dots allowed or not possible: ^\n  // - if dots possible and not allowed: ^(?!\\.)\n  // end is:\n  // - if not isEnd(): nothing\n  // - else: $\n  //\n  // In full-path matching mode, we put the slash at the START of the\n  // pattern, so start is:\n  // - if first pattern: same as part-matching mode\n  // - if not isStart(): nothing\n  // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))\n  // - if dots allowed or not possible: /\n  // - if dots possible and not allowed: /(?!\\.)\n  // end is:\n  // - if last pattern, same as part-matching mode\n  // - else nothing\n  //\n  // Always put the (?:$|/) on negated tails, though, because that has to be\n  // there to bind the end of the negated pattern portion, and it's easier to\n  // just stick it in now rather than try to inject it later in the middle of\n  // the pattern.\n  //\n  // We can just always return the same end, and leave it up to the caller\n  // to know whether it's going to be used joined or in parts.\n  // And, if the start is adjusted slightly, can do the same there:\n  // - if not isStart: nothing\n  // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)\n  // - if dots allowed or not possible: (?:/|^)\n  // - if dots possible and not allowed: (?:/|^)(?!\\.)\n  //\n  // But it's better to have a simpler binding without a conditional, for\n  // performance, so probably better to return both start options.\n  //\n  // Then the caller just ignores the end if it's not the first pattern,\n  // and the start always gets applied.\n  //\n  // But that's always going to be $ if it's the ending pattern, or nothing,\n  // so the caller can just attach $ at the end of the pattern when building.\n  //\n  // So the todo is:\n  // - better detect what kind of start is needed\n  // - return both flavors of starting pattern\n  // - attach $ at the end of the pattern when creating the actual RegExp\n  //\n  // Ah, but wait, no, that all only applies to the root when the first pattern\n  // is not an extglob. If the first pattern IS an extglob, then we need all\n  // that dot prevention biz to live in the extglob portions, because eg\n  // +(*|.x*) can match .xy but not .yx.\n  //\n  // So, return the two flavors if it's #root and the first child is not an\n  // AST, otherwise leave it to the child AST to handle it, and there,\n  // use the (?:^|/) style of start binding.\n  //\n  // Even simplified further:\n  // - Since the start for a join is eg /(?!\\.) and the start for a part\n  // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root\n  // or start or whatever) and prepend ^ or / at the Regexp construction.\n  toRegExpSource(\n    allowDot?: boolean\n  ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n    const dot = allowDot ?? !!this.#options.dot\n    if (this.#root === this) this.#fillNegs()\n    if (!this.type) {\n      const noEmpty = this.isStart() && this.isEnd()\n      const src = this.#parts\n        .map(p => {\n          const [re, _, hasMagic, uflag] =\n            typeof p === 'string'\n              ? AST.#parseGlob(p, this.#hasMagic, noEmpty)\n              : p.toRegExpSource(allowDot)\n          this.#hasMagic = this.#hasMagic || hasMagic\n          this.#uflag = this.#uflag || uflag\n          return re\n        })\n        .join('')\n\n      let start = ''\n      if (this.isStart()) {\n        if (typeof this.#parts[0] === 'string') {\n          // this is the string that will match the start of the pattern,\n          // so we need to protect against dots and such.\n\n          // '.' and '..' cannot match unless the pattern is that exactly,\n          // even if it starts with . or dot:true is set.\n          const dotTravAllowed =\n            this.#parts.length === 1 && justDots.has(this.#parts[0])\n          if (!dotTravAllowed) {\n            const aps = addPatternStart\n            // check if we have a possibility of matching . or ..,\n            // and prevent that.\n            const needNoTrav =\n              // dots are allowed, and the pattern starts with [ or .\n              (dot && aps.has(src.charAt(0))) ||\n              // the pattern starts with \\., and then [ or .\n              (src.startsWith('\\\\.') && aps.has(src.charAt(2))) ||\n              // the pattern starts with \\.\\., and then [ or .\n              (src.startsWith('\\\\.\\\\.') && aps.has(src.charAt(4)))\n            // no need to prevent dots if it can't match a dot, or if a\n            // sub-pattern will be preventing it anyway.\n            const needNoDot = !dot && !allowDot && aps.has(src.charAt(0))\n\n            start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ''\n          }\n        }\n      }\n\n      // append the \"end of path portion\" pattern to negation tails\n      let end = ''\n      if (\n        this.isEnd() &&\n        this.#root.#filledNegs &&\n        this.#parent?.type === '!'\n      ) {\n        end = '(?:$|\\\\/)'\n      }\n      const final = start + src + end\n      return [\n        final,\n        unescape(src),\n        (this.#hasMagic = !!this.#hasMagic),\n        this.#uflag,\n      ]\n    }\n\n    // We need to calculate the body *twice* if it's a repeat pattern\n    // at the start, once in nodot mode, then again in dot mode, so a\n    // pattern like *(?) can match 'x.y'\n\n    const repeated = this.type === '*' || this.type === '+'\n    // some kind of extglob\n    const start = this.type === '!' ? '(?:(?!(?:' : '(?:'\n    let body = this.#partsToRegExp(dot)\n\n    if (this.isStart() && this.isEnd() && !body && this.type !== '!') {\n      // invalid extglob, has to at least be *something* present, if it's\n      // the entire path portion.\n      const s = this.toString()\n      this.#parts = [s]\n      this.type = null\n      this.#hasMagic = undefined\n      return [s, unescape(this.toString()), false, false]\n    }\n\n    // XXX abstract out this map method\n    let bodyDotAllowed =\n      !repeated || allowDot || dot || !startNoDot\n        ? ''\n        : this.#partsToRegExp(true)\n    if (bodyDotAllowed === body) {\n      bodyDotAllowed = ''\n    }\n    if (bodyDotAllowed) {\n      body = `(?:${body})(?:${bodyDotAllowed})*?`\n    }\n\n    // an empty !() is exactly equivalent to a starNoEmpty\n    let final = ''\n    if (this.type === '!' && this.#emptyExt) {\n      final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty\n    } else {\n      const close =\n        this.type === '!'\n          ? // !() must match something,but !(x) can match ''\n            '))' +\n            (this.isStart() && !dot && !allowDot ? startNoDot : '') +\n            star +\n            ')'\n          : this.type === '@'\n          ? ')'\n          : this.type === '?'\n          ? ')?'\n          : this.type === '+' && bodyDotAllowed\n          ? ')'\n          : this.type === '*' && bodyDotAllowed\n          ? `)?`\n          : `)${this.type}`\n      final = start + body + close\n    }\n    return [\n      final,\n      unescape(body),\n      (this.#hasMagic = !!this.#hasMagic),\n      this.#uflag,\n    ]\n  }\n\n  #partsToRegExp(dot: boolean) {\n    return this.#parts\n      .map(p => {\n        // extglob ASTs should only contain parent ASTs\n        /* c8 ignore start */\n        if (typeof p === 'string') {\n          throw new Error('string type in extglob ast??')\n        }\n        /* c8 ignore stop */\n        // can ignore hasMagic, because extglobs are already always magic\n        const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot)\n        this.#uflag = this.#uflag || uflag\n        return re\n      })\n      .filter(p => !(this.isStart() && this.isEnd()) || !!p)\n      .join('|')\n  }\n\n  static #parseGlob(\n    glob: string,\n    hasMagic: boolean | undefined,\n    noEmpty: boolean = false\n  ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n    let escaping = false\n    let re = ''\n    let uflag = false\n    for (let i = 0; i < glob.length; i++) {\n      const c = glob.charAt(i)\n      if (escaping) {\n        escaping = false\n        re += (reSpecials.has(c) ? '\\\\' : '') + c\n        continue\n      }\n      if (c === '\\\\') {\n        if (i === glob.length - 1) {\n          re += '\\\\\\\\'\n        } else {\n          escaping = true\n        }\n        continue\n      }\n      if (c === '[') {\n        const [src, needUflag, consumed, magic] = parseClass(glob, i)\n        if (consumed) {\n          re += src\n          uflag = uflag || needUflag\n          i += consumed - 1\n          hasMagic = hasMagic || magic\n          continue\n        }\n      }\n      if (c === '*') {\n        if (noEmpty && glob === '*') re += starNoEmpty\n        else re += star\n        hasMagic = true\n        continue\n      }\n      if (c === '?') {\n        re += qmark\n        hasMagic = true\n        continue\n      }\n      re += regExpEscape(c)\n    }\n    return [re, unescape(glob), !!hasMagic, uflag]\n  }\n}\n","import { MinimatchOptions } from './index.js'\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character.  In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n */\nexport const escape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n  }: Pick = {}\n) => {\n  // don't need to escape +@! because we escape the parens\n  // that make those magic, and escaping ! as [!] isn't valid,\n  // because [!]] is a valid glob class meaning not ']'.\n  return windowsPathsNoEscape\n    ? s.replace(/[?*()[\\]]/g, '[$&]')\n    : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n","/**\n * @module LRUCache\n */\n\n// module-private names and types\ntype Perf = { now: () => number }\nconst perf: Perf =\n  typeof performance === 'object' &&\n  performance &&\n  typeof performance.now === 'function'\n    ? performance\n    : Date\n\nconst warned = new Set()\n\n// either a function or a class\ntype ForC = ((...a: any[]) => any) | { new (...a: any[]): any }\n\n/* c8 ignore start */\nconst PROCESS = (\n  typeof process === 'object' && !!process ? process : {}\n) as { [k: string]: any }\n/* c8 ignore start */\n\nconst emitWarning = (\n  msg: string,\n  type: string,\n  code: string,\n  fn: ForC\n) => {\n  typeof PROCESS.emitWarning === 'function'\n    ? PROCESS.emitWarning(msg, type, code, fn)\n    : console.error(`[${code}] ${type}: ${msg}`)\n}\n\nlet AC = globalThis.AbortController\nlet AS = globalThis.AbortSignal\n\n/* c8 ignore start */\nif (typeof AC === 'undefined') {\n  //@ts-ignore\n  AS = class AbortSignal {\n    onabort?: (...a: any[]) => any\n    _onabort: ((...a: any[]) => any)[] = []\n    reason?: any\n    aborted: boolean = false\n    addEventListener(_: string, fn: (...a: any[]) => any) {\n      this._onabort.push(fn)\n    }\n  }\n  //@ts-ignore\n  AC = class AbortController {\n    constructor() {\n      warnACPolyfill()\n    }\n    signal = new AS()\n    abort(reason: any) {\n      if (this.signal.aborted) return\n      //@ts-ignore\n      this.signal.reason = reason\n      //@ts-ignore\n      this.signal.aborted = true\n      //@ts-ignore\n      for (const fn of this.signal._onabort) {\n        fn(reason)\n      }\n      this.signal.onabort?.(reason)\n    }\n  }\n  let printACPolyfillWarning =\n    PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'\n  const warnACPolyfill = () => {\n    if (!printACPolyfillWarning) return\n    printACPolyfillWarning = false\n    emitWarning(\n      'AbortController is not defined. If using lru-cache in ' +\n        'node 14, load an AbortController polyfill from the ' +\n        '`node-abort-controller` package. A minimal polyfill is ' +\n        'provided for use by LRUCache.fetch(), but it should not be ' +\n        'relied upon in other contexts (eg, passing it to other APIs that ' +\n        'use AbortController/AbortSignal might have undesirable effects). ' +\n        'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.',\n      'NO_ABORT_CONTROLLER',\n      'ENOTSUP',\n      warnACPolyfill\n    )\n  }\n}\n/* c8 ignore stop */\n\nconst shouldWarn = (code: string) => !warned.has(code)\n\nconst TYPE = Symbol('type')\nexport type PosInt = number & { [TYPE]: 'Positive Integer' }\nexport type Index = number & { [TYPE]: 'LRUCache Index' }\n\nconst isPosInt = (n: any): n is PosInt =>\n  n && n === Math.floor(n) && n > 0 && isFinite(n)\n\nexport type UintArray = Uint8Array | Uint16Array | Uint32Array\nexport type NumberArray = UintArray | number[]\n\n/* c8 ignore start */\n// This is a little bit ridiculous, tbh.\n// The maximum array length is 2^32-1 or thereabouts on most JS impls.\n// And well before that point, you're caching the entire world, I mean,\n// that's ~32GB of just integers for the next/prev links, plus whatever\n// else to hold that many keys and values.  Just filling the memory with\n// zeroes at init time is brutal when you get that big.\n// But why not be complete?\n// Maybe in the future, these limits will have expanded.\nconst getUintArray = (max: number) =>\n  !isPosInt(max)\n    ? null\n    : max <= Math.pow(2, 8)\n    ? Uint8Array\n    : max <= Math.pow(2, 16)\n    ? Uint16Array\n    : max <= Math.pow(2, 32)\n    ? Uint32Array\n    : max <= Number.MAX_SAFE_INTEGER\n    ? ZeroArray\n    : null\n/* c8 ignore stop */\n\nclass ZeroArray extends Array {\n  constructor(size: number) {\n    super(size)\n    this.fill(0)\n  }\n}\nexport type { ZeroArray }\nexport type { Stack }\n\nexport type StackLike = Stack | Index[]\nclass Stack {\n  heap: NumberArray\n  length: number\n  // private constructor\n  static #constructing: boolean = false\n  static create(max: number): StackLike {\n    const HeapCls = getUintArray(max)\n    if (!HeapCls) return []\n    Stack.#constructing = true\n    const s = new Stack(max, HeapCls)\n    Stack.#constructing = false\n    return s\n  }\n  constructor(\n    max: number,\n    HeapCls: { new (n: number): NumberArray }\n  ) {\n    /* c8 ignore start */\n    if (!Stack.#constructing) {\n      throw new TypeError('instantiate Stack using Stack.create(n)')\n    }\n    /* c8 ignore stop */\n    this.heap = new HeapCls(max)\n    this.length = 0\n  }\n  push(n: Index) {\n    this.heap[this.length++] = n\n  }\n  pop(): Index {\n    return this.heap[--this.length] as Index\n  }\n}\n\n/**\n * Promise representing an in-progress {@link LRUCache#fetch} call\n */\nexport type BackgroundFetch = Promise & {\n  __returned: BackgroundFetch | undefined\n  __abortController: AbortController\n  __staleWhileFetching: V | undefined\n}\n\nexport type DisposeTask = [\n  value: V,\n  key: K,\n  reason: LRUCache.DisposeReason\n]\n\nexport namespace LRUCache {\n  /**\n   * An integer greater than 0, reflecting the calculated size of items\n   */\n  export type Size = number\n\n  /**\n   * Integer greater than 0, representing some number of milliseconds, or the\n   * time at which a TTL started counting from.\n   */\n  export type Milliseconds = number\n\n  /**\n   * An integer greater than 0, reflecting a number of items\n   */\n  export type Count = number\n\n  /**\n   * The reason why an item was removed from the cache, passed\n   * to the {@link Disposer} methods.\n   */\n  export type DisposeReason = 'evict' | 'set' | 'delete'\n  /**\n   * A method called upon item removal, passed as the\n   * {@link OptionsBase.dispose} and/or\n   * {@link OptionsBase.disposeAfter} options.\n   */\n  export type Disposer = (\n    value: V,\n    key: K,\n    reason: DisposeReason\n  ) => void\n\n  /**\n   * A function that returns the effective calculated size\n   * of an entry in the cache.\n   */\n  export type SizeCalculator = (value: V, key: K) => Size\n\n  /**\n   * Options provided to the\n   * {@link OptionsBase.fetchMethod} function.\n   */\n  export interface FetcherOptions {\n    signal: AbortSignal\n    options: FetcherFetchOptions\n    /**\n     * Object provided in the {@link FetchOptions.context} option to\n     * {@link LRUCache#fetch}\n     */\n    context: FC\n  }\n\n  /**\n   * Status object that may be passed to {@link LRUCache#fetch},\n   * {@link LRUCache#get}, {@link LRUCache#set}, and {@link LRUCache#has}.\n   */\n  export interface Status {\n    /**\n     * The status of a set() operation.\n     *\n     * - add: the item was not found in the cache, and was added\n     * - update: the item was in the cache, with the same value provided\n     * - replace: the item was in the cache, and replaced\n     * - miss: the item was not added to the cache for some reason\n     */\n    set?: 'add' | 'update' | 'replace' | 'miss'\n\n    /**\n     * the ttl stored for the item, or undefined if ttls are not used.\n     */\n    ttl?: Milliseconds\n\n    /**\n     * the start time for the item, or undefined if ttls are not used.\n     */\n    start?: Milliseconds\n\n    /**\n     * The timestamp used for TTL calculation\n     */\n    now?: Milliseconds\n\n    /**\n     * the remaining ttl for the item, or undefined if ttls are not used.\n     */\n    remainingTTL?: Milliseconds\n\n    /**\n     * The calculated size for the item, if sizes are used.\n     */\n    entrySize?: Size\n\n    /**\n     * The total calculated size of the cache, if sizes are used.\n     */\n    totalCalculatedSize?: Size\n\n    /**\n     * A flag indicating that the item was not stored, due to exceeding the\n     * {@link OptionsBase.maxEntrySize}\n     */\n    maxEntrySizeExceeded?: true\n\n    /**\n     * The old value, specified in the case of `set:'update'` or\n     * `set:'replace'`\n     */\n    oldValue?: V\n\n    /**\n     * The results of a {@link LRUCache#has} operation\n     *\n     * - hit: the item was found in the cache\n     * - stale: the item was found in the cache, but is stale\n     * - miss: the item was not found in the cache\n     */\n    has?: 'hit' | 'stale' | 'miss'\n\n    /**\n     * The status of a {@link LRUCache#fetch} operation.\n     * Note that this can change as the underlying fetch() moves through\n     * various states.\n     *\n     * - inflight: there is another fetch() for this key which is in process\n     * - get: there is no fetchMethod, so {@link LRUCache#get} was called.\n     * - miss: the item is not in cache, and will be fetched.\n     * - hit: the item is in the cache, and was resolved immediately.\n     * - stale: the item is in the cache, but stale.\n     * - refresh: the item is in the cache, and not stale, but\n     *   {@link FetchOptions.forceRefresh} was specified.\n     */\n    fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'\n\n    /**\n     * The {@link OptionsBase.fetchMethod} was called\n     */\n    fetchDispatched?: true\n\n    /**\n     * The cached value was updated after a successful call to\n     * {@link OptionsBase.fetchMethod}\n     */\n    fetchUpdated?: true\n\n    /**\n     * The reason for a fetch() rejection.  Either the error raised by the\n     * {@link OptionsBase.fetchMethod}, or the reason for an\n     * AbortSignal.\n     */\n    fetchError?: Error\n\n    /**\n     * The fetch received an abort signal\n     */\n    fetchAborted?: true\n\n    /**\n     * The abort signal received was ignored, and the fetch was allowed to\n     * continue.\n     */\n    fetchAbortIgnored?: true\n\n    /**\n     * The fetchMethod promise resolved successfully\n     */\n    fetchResolved?: true\n\n    /**\n     * The fetchMethod promise was rejected\n     */\n    fetchRejected?: true\n\n    /**\n     * The status of a {@link LRUCache#get} operation.\n     *\n     * - fetching: The item is currently being fetched.  If a previous value\n     *   is present and allowed, that will be returned.\n     * - stale: The item is in the cache, and is stale.\n     * - hit: the item is in the cache\n     * - miss: the item is not in the cache\n     */\n    get?: 'stale' | 'hit' | 'miss'\n\n    /**\n     * A fetch or get operation returned a stale value.\n     */\n    returnedStale?: true\n  }\n\n  /**\n   * options which override the options set in the LRUCache constructor\n   * when calling {@link LRUCache#fetch}.\n   *\n   * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n   * {@link OptionsBase.noDeleteOnFetchRejection},\n   * {@link OptionsBase.allowStaleOnFetchRejection},\n   * {@link FetchOptions.forceRefresh}, and\n   * {@link FetcherOptions.context}\n   *\n   * Any of these may be modified in the {@link OptionsBase.fetchMethod}\n   * function, but the {@link GetOptions} fields will of course have no\n   * effect, as the {@link LRUCache#get} call already happened by the time\n   * the fetchMethod is called.\n   */\n  export interface FetcherFetchOptions\n    extends Pick<\n      OptionsBase,\n      | 'allowStale'\n      | 'updateAgeOnGet'\n      | 'noDeleteOnStaleGet'\n      | 'sizeCalculation'\n      | 'ttl'\n      | 'noDisposeOnSet'\n      | 'noUpdateTTL'\n      | 'noDeleteOnFetchRejection'\n      | 'allowStaleOnFetchRejection'\n      | 'ignoreFetchAbort'\n      | 'allowStaleOnFetchAbort'\n    > {\n    status?: Status\n    size?: Size\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#fetch} method.\n   */\n  export interface FetchOptions\n    extends FetcherFetchOptions {\n    /**\n     * Set to true to force a re-load of the existing data, even if it\n     * is not yet stale.\n     */\n    forceRefresh?: boolean\n    /**\n     * Context provided to the {@link OptionsBase.fetchMethod} as\n     * the {@link FetcherOptions.context} param.\n     *\n     * If the FC type is specified as unknown (the default),\n     * undefined or void, then this is optional.  Otherwise, it will\n     * be required.\n     */\n    context?: FC\n    signal?: AbortSignal\n    status?: Status\n  }\n  /**\n   * Options provided to {@link LRUCache#fetch} when the FC type is something\n   * other than `unknown`, `undefined`, or `void`\n   */\n  export interface FetchOptionsWithContext\n    extends FetchOptions {\n    context: FC\n  }\n  /**\n   * Options provided to {@link LRUCache#fetch} when the FC type is\n   * `undefined` or `void`\n   */\n  export interface FetchOptionsNoContext\n    extends FetchOptions {\n    context?: undefined\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#has} method.\n   */\n  export interface HasOptions\n    extends Pick, 'updateAgeOnHas'> {\n    status?: Status\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#get} method.\n   */\n  export interface GetOptions\n    extends Pick<\n      OptionsBase,\n      'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'\n    > {\n    status?: Status\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#peek} method.\n   */\n  export interface PeekOptions\n    extends Pick, 'allowStale'> {}\n\n  /**\n   * Options that may be passed to the {@link LRUCache#set} method.\n   */\n  export interface SetOptions\n    extends Pick<\n      OptionsBase,\n      'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'\n    > {\n    /**\n     * If size tracking is enabled, then setting an explicit size\n     * in the {@link LRUCache#set} call will prevent calling the\n     * {@link OptionsBase.sizeCalculation} function.\n     */\n    size?: Size\n    /**\n     * If TTL tracking is enabled, then setting an explicit start\n     * time in the {@link LRUCache#set} call will override the\n     * default time from `performance.now()` or `Date.now()`.\n     *\n     * Note that it must be a valid value for whichever time-tracking\n     * method is in use.\n     */\n    start?: Milliseconds\n    status?: Status\n  }\n\n  /**\n   * The type signature for the {@link OptionsBase.fetchMethod} option.\n   */\n  export type Fetcher = (\n    key: K,\n    staleValue: V | undefined,\n    options: FetcherOptions\n  ) => Promise | V | undefined | void\n\n  /**\n   * Options which may be passed to the {@link LRUCache} constructor.\n   *\n   * Most of these may be overridden in the various options that use\n   * them.\n   *\n   * Despite all being technically optional, the constructor requires that\n   * a cache is at minimum limited by one or more of {@link OptionsBase.max},\n   * {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}.\n   *\n   * If {@link OptionsBase.ttl} is used alone, then it is strongly advised\n   * (and in fact required by the type definitions here) that the cache\n   * also set {@link OptionsBase.ttlAutopurge}, to prevent potentially\n   * unbounded storage.\n   */\n  export interface OptionsBase {\n    /**\n     * The maximum number of items to store in the cache before evicting\n     * old entries. This is read-only on the {@link LRUCache} instance,\n     * and may not be overridden.\n     *\n     * If set, then storage space will be pre-allocated at construction\n     * time, and the cache will perform significantly faster.\n     *\n     * Note that significantly fewer items may be stored, if\n     * {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also\n     * set.\n     */\n    max?: Count\n\n    /**\n     * Max time in milliseconds for items to live in cache before they are\n     * considered stale.  Note that stale items are NOT preemptively removed\n     * by default, and MAY live in the cache long after they have expired.\n     *\n     * Also, as this cache is optimized for LRU/MRU operations, some of\n     * the staleness/TTL checks will reduce performance, as they will incur\n     * overhead by deleting items.\n     *\n     * Must be an integer number of ms. If set to 0, this indicates \"no TTL\"\n     *\n     * @default 0\n     */\n    ttl?: Milliseconds\n\n    /**\n     * Minimum amount of time in ms in which to check for staleness.\n     * Defaults to 1, which means that the current time is checked\n     * at most once per millisecond.\n     *\n     * Set to 0 to check the current time every time staleness is tested.\n     * (This reduces performance, and is theoretically unnecessary.)\n     *\n     * Setting this to a higher value will improve performance somewhat\n     * while using ttl tracking, albeit at the expense of keeping stale\n     * items around a bit longer than their TTLs would indicate.\n     *\n     * @default 1\n     */\n    ttlResolution?: Milliseconds\n\n    /**\n     * Preemptively remove stale items from the cache.\n     * Note that this may significantly degrade performance,\n     * especially if the cache is storing a large number of items.\n     * It is almost always best to just leave the stale items in\n     * the cache, and let them fall out as new items are added.\n     *\n     * Note that this means that {@link OptionsBase.allowStale} is a bit\n     * pointless, as stale items will be deleted almost as soon as they\n     * expire.\n     *\n     * @default false\n     */\n    ttlAutopurge?: boolean\n\n    /**\n     * Update the age of items on {@link LRUCache#get}, renewing their TTL\n     *\n     * Has no effect if {@link OptionsBase.ttl} is not set.\n     *\n     * @default false\n     */\n    updateAgeOnGet?: boolean\n\n    /**\n     * Update the age of items on {@link LRUCache#has}, renewing their TTL\n     *\n     * Has no effect if {@link OptionsBase.ttl} is not set.\n     *\n     * @default false\n     */\n    updateAgeOnHas?: boolean\n\n    /**\n     * Allow {@link LRUCache#get} and {@link LRUCache#fetch} calls to return\n     * stale data, if available.\n     */\n    allowStale?: boolean\n\n    /**\n     * Function that is called on items when they are dropped from the cache.\n     * This can be handy if you want to close file descriptors or do other\n     * cleanup tasks when items are no longer accessible. Called with `key,\n     * value`.  It's called before actually removing the item from the\n     * internal cache, so it is *NOT* safe to re-add them.\n     *\n     * Use {@link OptionsBase.disposeAfter} if you wish to dispose items after\n     * they have been full removed, when it is safe to add them back to the\n     * cache.\n     */\n    dispose?: Disposer\n\n    /**\n     * The same as {@link OptionsBase.dispose}, but called *after* the entry\n     * is completely removed and the cache is once again in a clean state.\n     * It is safe to add an item right back into the cache at this point.\n     * However, note that it is *very* easy to inadvertently create infinite\n     * recursion this way.\n     */\n    disposeAfter?: Disposer\n\n    /**\n     * Set to true to suppress calling the\n     * {@link OptionsBase.dispose} function if the entry key is\n     * still accessible within the cache.\n     * This may be overridden by passing an options object to\n     * {@link LRUCache#set}.\n     */\n    noDisposeOnSet?: boolean\n\n    /**\n     * Boolean flag to tell the cache to not update the TTL when\n     * setting a new value for an existing key (ie, when updating a value\n     * rather than inserting a new value).  Note that the TTL value is\n     * _always_ set (if provided) when adding a new entry into the cache.\n     *\n     * Has no effect if a {@link OptionsBase.ttl} is not set.\n     */\n    noUpdateTTL?: boolean\n\n    /**\n     * If you wish to track item size, you must provide a maxSize\n     * note that we still will only keep up to max *actual items*,\n     * if max is set, so size tracking may cause fewer than max items\n     * to be stored.  At the extreme, a single item of maxSize size\n     * will cause everything else in the cache to be dropped when it\n     * is added.  Use with caution!\n     *\n     * Note also that size tracking can negatively impact performance,\n     * though for most cases, only minimally.\n     */\n    maxSize?: Size\n\n    /**\n     * The maximum allowed size for any single item in the cache.\n     *\n     * If a larger item is passed to {@link LRUCache#set} or returned by a\n     * {@link OptionsBase.fetchMethod}, then it will not be stored in the\n     * cache.\n     */\n    maxEntrySize?: Size\n\n    /**\n     * A function that returns a number indicating the item's size.\n     *\n     * If not provided, and {@link OptionsBase.maxSize} or\n     * {@link OptionsBase.maxEntrySize} are set, then all\n     * {@link LRUCache#set} calls **must** provide an explicit\n     * {@link SetOptions.size} or sizeCalculation param.\n     */\n    sizeCalculation?: SizeCalculator\n\n    /**\n     * Method that provides the implementation for {@link LRUCache#fetch}\n     */\n    fetchMethod?: Fetcher\n\n    /**\n     * Set to true to suppress the deletion of stale data when a\n     * {@link OptionsBase.fetchMethod} returns a rejected promise.\n     */\n    noDeleteOnFetchRejection?: boolean\n\n    /**\n     * Do not delete stale items when they are retrieved with\n     * {@link LRUCache#get}.\n     *\n     * Note that the `get` return value will still be `undefined`\n     * unless {@link OptionsBase.allowStale} is true.\n     */\n    noDeleteOnStaleGet?: boolean\n\n    /**\n     * Set to true to allow returning stale data when a\n     * {@link OptionsBase.fetchMethod} throws an error or returns a rejected\n     * promise.\n     *\n     * This differs from using {@link OptionsBase.allowStale} in that stale\n     * data will ONLY be returned in the case that the\n     * {@link LRUCache#fetch} fails, not any other times.\n     */\n    allowStaleOnFetchRejection?: boolean\n\n    /**\n     * Set to true to return a stale value from the cache when the\n     * `AbortSignal` passed to the {@link OptionsBase.fetchMethod} dispatches an `'abort'`\n     * event, whether user-triggered, or due to internal cache behavior.\n     *\n     * Unless {@link OptionsBase.ignoreFetchAbort} is also set, the underlying\n     * {@link OptionsBase.fetchMethod} will still be considered canceled, and\n     * any value it returns will be ignored and not cached.\n     *\n     * Caveat: since fetches are aborted when a new value is explicitly\n     * set in the cache, this can lead to fetch returning a stale value,\n     * since that was the fallback value _at the moment the `fetch()` was\n     * initiated_, even though the new updated value is now present in\n     * the cache.\n     *\n     * For example:\n     *\n     * ```ts\n     * const cache = new LRUCache({\n     *   ttl: 100,\n     *   fetchMethod: async (url, oldValue, { signal }) =>  {\n     *     const res = await fetch(url, { signal })\n     *     return await res.json()\n     *   }\n     * })\n     * cache.set('https://example.com/', { some: 'data' })\n     * // 100ms go by...\n     * const result = cache.fetch('https://example.com/')\n     * cache.set('https://example.com/', { other: 'thing' })\n     * console.log(await result) // { some: 'data' }\n     * console.log(cache.get('https://example.com/')) // { other: 'thing' }\n     * ```\n     */\n    allowStaleOnFetchAbort?: boolean\n\n    /**\n     * Set to true to ignore the `abort` event emitted by the `AbortSignal`\n     * object passed to {@link OptionsBase.fetchMethod}, and still cache the\n     * resulting resolution value, as long as it is not `undefined`.\n     *\n     * When used on its own, this means aborted {@link LRUCache#fetch} calls are not\n     * immediately resolved or rejected when they are aborted, and instead\n     * take the full time to await.\n     *\n     * When used with {@link OptionsBase.allowStaleOnFetchAbort}, aborted\n     * {@link LRUCache#fetch} calls will resolve immediately to their stale\n     * cached value or `undefined`, and will continue to process and eventually\n     * update the cache when they resolve, as long as the resulting value is\n     * not `undefined`, thus supporting a \"return stale on timeout while\n     * refreshing\" mechanism by passing `AbortSignal.timeout(n)` as the signal.\n     *\n     * **Note**: regardless of this setting, an `abort` event _is still\n     * emitted on the `AbortSignal` object_, so may result in invalid results\n     * when passed to other underlying APIs that use AbortSignals.\n     *\n     * This may be overridden in the {@link OptionsBase.fetchMethod} or the\n     * call to {@link LRUCache#fetch}.\n     */\n    ignoreFetchAbort?: boolean\n  }\n\n  export interface OptionsMaxLimit\n    extends OptionsBase {\n    max: Count\n  }\n  export interface OptionsTTLLimit\n    extends OptionsBase {\n    ttl: Milliseconds\n    ttlAutopurge: boolean\n  }\n  export interface OptionsSizeLimit\n    extends OptionsBase {\n    maxSize: Size\n  }\n\n  /**\n   * The valid safe options for the {@link LRUCache} constructor\n   */\n  export type Options =\n    | OptionsMaxLimit\n    | OptionsSizeLimit\n    | OptionsTTLLimit\n\n  /**\n   * Entry objects used by {@link LRUCache#load} and {@link LRUCache#dump},\n   * and returned by {@link LRUCache#info}.\n   */\n  export interface Entry {\n    value: V\n    ttl?: Milliseconds\n    size?: Size\n    start?: Milliseconds\n  }\n}\n\n/**\n * Default export, the thing you're using this module to get.\n *\n * All properties from the options object (with the exception of\n * {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as\n * normal public members. (`max` and `maxBase` are read-only getters.)\n * Changing any of these will alter the defaults for subsequent method calls,\n * but is otherwise safe.\n */\nexport class LRUCache implements Map {\n  // properties coming in from the options of these, only max and maxSize\n  // really *need* to be protected. The rest can be modified, as they just\n  // set defaults for various methods.\n  readonly #max: LRUCache.Count\n  readonly #maxSize: LRUCache.Size\n  readonly #dispose?: LRUCache.Disposer\n  readonly #disposeAfter?: LRUCache.Disposer\n  readonly #fetchMethod?: LRUCache.Fetcher\n\n  /**\n   * {@link LRUCache.OptionsBase.ttl}\n   */\n  ttl: LRUCache.Milliseconds\n\n  /**\n   * {@link LRUCache.OptionsBase.ttlResolution}\n   */\n  ttlResolution: LRUCache.Milliseconds\n  /**\n   * {@link LRUCache.OptionsBase.ttlAutopurge}\n   */\n  ttlAutopurge: boolean\n  /**\n   * {@link LRUCache.OptionsBase.updateAgeOnGet}\n   */\n  updateAgeOnGet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.updateAgeOnHas}\n   */\n  updateAgeOnHas: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStale}\n   */\n  allowStale: boolean\n\n  /**\n   * {@link LRUCache.OptionsBase.noDisposeOnSet}\n   */\n  noDisposeOnSet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.noUpdateTTL}\n   */\n  noUpdateTTL: boolean\n  /**\n   * {@link LRUCache.OptionsBase.maxEntrySize}\n   */\n  maxEntrySize: LRUCache.Size\n  /**\n   * {@link LRUCache.OptionsBase.sizeCalculation}\n   */\n  sizeCalculation?: LRUCache.SizeCalculator\n  /**\n   * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}\n   */\n  noDeleteOnFetchRejection: boolean\n  /**\n   * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}\n   */\n  noDeleteOnStaleGet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}\n   */\n  allowStaleOnFetchAbort: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}\n   */\n  allowStaleOnFetchRejection: boolean\n  /**\n   * {@link LRUCache.OptionsBase.ignoreFetchAbort}\n   */\n  ignoreFetchAbort: boolean\n\n  // computed properties\n  #size: LRUCache.Count\n  #calculatedSize: LRUCache.Size\n  #keyMap: Map\n  #keyList: (K | undefined)[]\n  #valList: (V | BackgroundFetch | undefined)[]\n  #next: NumberArray\n  #prev: NumberArray\n  #head: Index\n  #tail: Index\n  #free: StackLike\n  #disposed?: DisposeTask[]\n  #sizes?: ZeroArray\n  #starts?: ZeroArray\n  #ttls?: ZeroArray\n\n  #hasDispose: boolean\n  #hasFetchMethod: boolean\n  #hasDisposeAfter: boolean\n\n  /**\n   * Do not call this method unless you need to inspect the\n   * inner workings of the cache.  If anything returned by this\n   * object is modified in any way, strange breakage may occur.\n   *\n   * These fields are private for a reason!\n   *\n   * @internal\n   */\n  static unsafeExposeInternals<\n    K extends {},\n    V extends {},\n    FC extends unknown = unknown\n  >(c: LRUCache) {\n    return {\n      // properties\n      starts: c.#starts,\n      ttls: c.#ttls,\n      sizes: c.#sizes,\n      keyMap: c.#keyMap as Map,\n      keyList: c.#keyList,\n      valList: c.#valList,\n      next: c.#next,\n      prev: c.#prev,\n      get head() {\n        return c.#head\n      },\n      get tail() {\n        return c.#tail\n      },\n      free: c.#free,\n      // methods\n      isBackgroundFetch: (p: any) => c.#isBackgroundFetch(p),\n      backgroundFetch: (\n        k: K,\n        index: number | undefined,\n        options: LRUCache.FetchOptions,\n        context: any\n      ): BackgroundFetch =>\n        c.#backgroundFetch(\n          k,\n          index as Index | undefined,\n          options,\n          context\n        ),\n      moveToTail: (index: number): void =>\n        c.#moveToTail(index as Index),\n      indexes: (options?: { allowStale: boolean }) =>\n        c.#indexes(options),\n      rindexes: (options?: { allowStale: boolean }) =>\n        c.#rindexes(options),\n      isStale: (index: number | undefined) =>\n        c.#isStale(index as Index),\n    }\n  }\n\n  // Protected read-only members\n\n  /**\n   * {@link LRUCache.OptionsBase.max} (read-only)\n   */\n  get max(): LRUCache.Count {\n    return this.#max\n  }\n  /**\n   * {@link LRUCache.OptionsBase.maxSize} (read-only)\n   */\n  get maxSize(): LRUCache.Count {\n    return this.#maxSize\n  }\n  /**\n   * The total computed size of items in the cache (read-only)\n   */\n  get calculatedSize(): LRUCache.Size {\n    return this.#calculatedSize\n  }\n  /**\n   * The number of items stored in the cache (read-only)\n   */\n  get size(): LRUCache.Count {\n    return this.#size\n  }\n  /**\n   * {@link LRUCache.OptionsBase.fetchMethod} (read-only)\n   */\n  get fetchMethod(): LRUCache.Fetcher | undefined {\n    return this.#fetchMethod\n  }\n  /**\n   * {@link LRUCache.OptionsBase.dispose} (read-only)\n   */\n  get dispose() {\n    return this.#dispose\n  }\n  /**\n   * {@link LRUCache.OptionsBase.disposeAfter} (read-only)\n   */\n  get disposeAfter() {\n    return this.#disposeAfter\n  }\n\n  constructor(\n    options: LRUCache.Options | LRUCache\n  ) {\n    const {\n      max = 0,\n      ttl,\n      ttlResolution = 1,\n      ttlAutopurge,\n      updateAgeOnGet,\n      updateAgeOnHas,\n      allowStale,\n      dispose,\n      disposeAfter,\n      noDisposeOnSet,\n      noUpdateTTL,\n      maxSize = 0,\n      maxEntrySize = 0,\n      sizeCalculation,\n      fetchMethod,\n      noDeleteOnFetchRejection,\n      noDeleteOnStaleGet,\n      allowStaleOnFetchRejection,\n      allowStaleOnFetchAbort,\n      ignoreFetchAbort,\n    } = options\n\n    if (max !== 0 && !isPosInt(max)) {\n      throw new TypeError('max option must be a nonnegative integer')\n    }\n\n    const UintArray = max ? getUintArray(max) : Array\n    if (!UintArray) {\n      throw new Error('invalid max value: ' + max)\n    }\n\n    this.#max = max\n    this.#maxSize = maxSize\n    this.maxEntrySize = maxEntrySize || this.#maxSize\n    this.sizeCalculation = sizeCalculation\n    if (this.sizeCalculation) {\n      if (!this.#maxSize && !this.maxEntrySize) {\n        throw new TypeError(\n          'cannot set sizeCalculation without setting maxSize or maxEntrySize'\n        )\n      }\n      if (typeof this.sizeCalculation !== 'function') {\n        throw new TypeError('sizeCalculation set to non-function')\n      }\n    }\n\n    if (\n      fetchMethod !== undefined &&\n      typeof fetchMethod !== 'function'\n    ) {\n      throw new TypeError(\n        'fetchMethod must be a function if specified'\n      )\n    }\n    this.#fetchMethod = fetchMethod\n    this.#hasFetchMethod = !!fetchMethod\n\n    this.#keyMap = new Map()\n    this.#keyList = new Array(max).fill(undefined)\n    this.#valList = new Array(max).fill(undefined)\n    this.#next = new UintArray(max)\n    this.#prev = new UintArray(max)\n    this.#head = 0 as Index\n    this.#tail = 0 as Index\n    this.#free = Stack.create(max)\n    this.#size = 0\n    this.#calculatedSize = 0\n\n    if (typeof dispose === 'function') {\n      this.#dispose = dispose\n    }\n    if (typeof disposeAfter === 'function') {\n      this.#disposeAfter = disposeAfter\n      this.#disposed = []\n    } else {\n      this.#disposeAfter = undefined\n      this.#disposed = undefined\n    }\n    this.#hasDispose = !!this.#dispose\n    this.#hasDisposeAfter = !!this.#disposeAfter\n\n    this.noDisposeOnSet = !!noDisposeOnSet\n    this.noUpdateTTL = !!noUpdateTTL\n    this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection\n    this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection\n    this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort\n    this.ignoreFetchAbort = !!ignoreFetchAbort\n\n    // NB: maxEntrySize is set to maxSize if it's set\n    if (this.maxEntrySize !== 0) {\n      if (this.#maxSize !== 0) {\n        if (!isPosInt(this.#maxSize)) {\n          throw new TypeError(\n            'maxSize must be a positive integer if specified'\n          )\n        }\n      }\n      if (!isPosInt(this.maxEntrySize)) {\n        throw new TypeError(\n          'maxEntrySize must be a positive integer if specified'\n        )\n      }\n      this.#initializeSizeTracking()\n    }\n\n    this.allowStale = !!allowStale\n    this.noDeleteOnStaleGet = !!noDeleteOnStaleGet\n    this.updateAgeOnGet = !!updateAgeOnGet\n    this.updateAgeOnHas = !!updateAgeOnHas\n    this.ttlResolution =\n      isPosInt(ttlResolution) || ttlResolution === 0\n        ? ttlResolution\n        : 1\n    this.ttlAutopurge = !!ttlAutopurge\n    this.ttl = ttl || 0\n    if (this.ttl) {\n      if (!isPosInt(this.ttl)) {\n        throw new TypeError(\n          'ttl must be a positive integer if specified'\n        )\n      }\n      this.#initializeTTLTracking()\n    }\n\n    // do not allow completely unbounded caches\n    if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {\n      throw new TypeError(\n        'At least one of max, maxSize, or ttl is required'\n      )\n    }\n    if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {\n      const code = 'LRU_CACHE_UNBOUNDED'\n      if (shouldWarn(code)) {\n        warned.add(code)\n        const msg =\n          'TTL caching without ttlAutopurge, max, or maxSize can ' +\n          'result in unbounded memory consumption.'\n        emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache)\n      }\n    }\n  }\n\n  /**\n   * Return the remaining TTL time for a given entry key\n   */\n  getRemainingTTL(key: K) {\n    return this.#keyMap.has(key) ? Infinity : 0\n  }\n\n  #initializeTTLTracking() {\n    const ttls = new ZeroArray(this.#max)\n    const starts = new ZeroArray(this.#max)\n    this.#ttls = ttls\n    this.#starts = starts\n\n    this.#setItemTTL = (index, ttl, start = perf.now()) => {\n      starts[index] = ttl !== 0 ? start : 0\n      ttls[index] = ttl\n      if (ttl !== 0 && this.ttlAutopurge) {\n        const t = setTimeout(() => {\n          if (this.#isStale(index)) {\n            this.delete(this.#keyList[index] as K)\n          }\n        }, ttl + 1)\n        // unref() not supported on all platforms\n        /* c8 ignore start */\n        if (t.unref) {\n          t.unref()\n        }\n        /* c8 ignore stop */\n      }\n    }\n\n    this.#updateItemAge = index => {\n      starts[index] = ttls[index] !== 0 ? perf.now() : 0\n    }\n\n    this.#statusTTL = (status, index) => {\n      if (ttls[index]) {\n        const ttl = ttls[index]\n        const start = starts[index]\n        /* c8 ignore next */\n        if (!ttl || !start) return\n        status.ttl = ttl\n        status.start = start\n        status.now = cachedNow || getNow()\n        const age = status.now - start\n        status.remainingTTL = ttl - age\n      }\n    }\n\n    // debounce calls to perf.now() to 1s so we're not hitting\n    // that costly call repeatedly.\n    let cachedNow = 0\n    const getNow = () => {\n      const n = perf.now()\n      if (this.ttlResolution > 0) {\n        cachedNow = n\n        const t = setTimeout(\n          () => (cachedNow = 0),\n          this.ttlResolution\n        )\n        // not available on all platforms\n        /* c8 ignore start */\n        if (t.unref) {\n          t.unref()\n        }\n        /* c8 ignore stop */\n      }\n      return n\n    }\n\n    this.getRemainingTTL = key => {\n      const index = this.#keyMap.get(key)\n      if (index === undefined) {\n        return 0\n      }\n      const ttl = ttls[index]\n      const start = starts[index]\n      if (!ttl || !start) {\n        return Infinity\n      }\n      const age = (cachedNow || getNow()) - start\n      return ttl - age\n    }\n\n    this.#isStale = index => {\n      const s = starts[index]\n      const t = ttls[index]\n      return !!t && !!s && (cachedNow || getNow()) - s > t\n    }\n  }\n\n  // conditionally set private methods related to TTL\n  #updateItemAge: (index: Index) => void = () => {}\n  #statusTTL: (status: LRUCache.Status, index: Index) => void =\n    () => {}\n  #setItemTTL: (\n    index: Index,\n    ttl: LRUCache.Milliseconds,\n    start?: LRUCache.Milliseconds\n    // ignore because we never call this if we're not already in TTL mode\n    /* c8 ignore start */\n  ) => void = () => {}\n  /* c8 ignore stop */\n\n  #isStale: (index: Index) => boolean = () => false\n\n  #initializeSizeTracking() {\n    const sizes = new ZeroArray(this.#max)\n    this.#calculatedSize = 0\n    this.#sizes = sizes\n    this.#removeItemSize = index => {\n      this.#calculatedSize -= sizes[index] as number\n      sizes[index] = 0\n    }\n    this.#requireSize = (k, v, size, sizeCalculation) => {\n      // provisionally accept background fetches.\n      // actual value size will be checked when they return.\n      if (this.#isBackgroundFetch(v)) {\n        return 0\n      }\n      if (!isPosInt(size)) {\n        if (sizeCalculation) {\n          if (typeof sizeCalculation !== 'function') {\n            throw new TypeError('sizeCalculation must be a function')\n          }\n          size = sizeCalculation(v, k)\n          if (!isPosInt(size)) {\n            throw new TypeError(\n              'sizeCalculation return invalid (expect positive integer)'\n            )\n          }\n        } else {\n          throw new TypeError(\n            'invalid size value (must be positive integer). ' +\n              'When maxSize or maxEntrySize is used, sizeCalculation ' +\n              'or size must be set.'\n          )\n        }\n      }\n      return size\n    }\n    this.#addItemSize = (\n      index: Index,\n      size: LRUCache.Size,\n      status?: LRUCache.Status\n    ) => {\n      sizes[index] = size\n      if (this.#maxSize) {\n        const maxSize = this.#maxSize - (sizes[index] as number)\n        while (this.#calculatedSize > maxSize) {\n          this.#evict(true)\n        }\n      }\n      this.#calculatedSize += sizes[index] as number\n      if (status) {\n        status.entrySize = size\n        status.totalCalculatedSize = this.#calculatedSize\n      }\n    }\n  }\n\n  #removeItemSize: (index: Index) => void = _i => {}\n  #addItemSize: (\n    index: Index,\n    size: LRUCache.Size,\n    status?: LRUCache.Status\n  ) => void = (_i, _s, _st) => {}\n  #requireSize: (\n    k: K,\n    v: V | BackgroundFetch,\n    size?: LRUCache.Size,\n    sizeCalculation?: LRUCache.SizeCalculator\n  ) => LRUCache.Size = (\n    _k: K,\n    _v: V | BackgroundFetch,\n    size?: LRUCache.Size,\n    sizeCalculation?: LRUCache.SizeCalculator\n  ) => {\n    if (size || sizeCalculation) {\n      throw new TypeError(\n        'cannot set size without setting maxSize or maxEntrySize on cache'\n      )\n    }\n    return 0\n  };\n\n  *#indexes({ allowStale = this.allowStale } = {}) {\n    if (this.#size) {\n      for (let i = this.#tail; true; ) {\n        if (!this.#isValidIndex(i)) {\n          break\n        }\n        if (allowStale || !this.#isStale(i)) {\n          yield i\n        }\n        if (i === this.#head) {\n          break\n        } else {\n          i = this.#prev[i] as Index\n        }\n      }\n    }\n  }\n\n  *#rindexes({ allowStale = this.allowStale } = {}) {\n    if (this.#size) {\n      for (let i = this.#head; true; ) {\n        if (!this.#isValidIndex(i)) {\n          break\n        }\n        if (allowStale || !this.#isStale(i)) {\n          yield i\n        }\n        if (i === this.#tail) {\n          break\n        } else {\n          i = this.#next[i] as Index\n        }\n      }\n    }\n  }\n\n  #isValidIndex(index: Index) {\n    return (\n      index !== undefined &&\n      this.#keyMap.get(this.#keyList[index] as K) === index\n    )\n  }\n\n  /**\n   * Return a generator yielding `[key, value]` pairs,\n   * in order from most recently used to least recently used.\n   */\n  *entries() {\n    for (const i of this.#indexes()) {\n      if (\n        this.#valList[i] !== undefined &&\n        this.#keyList[i] !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield [this.#keyList[i], this.#valList[i]] as [K, V]\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.entries}\n   *\n   * Return a generator yielding `[key, value]` pairs,\n   * in order from least recently used to most recently used.\n   */\n  *rentries() {\n    for (const i of this.#rindexes()) {\n      if (\n        this.#valList[i] !== undefined &&\n        this.#keyList[i] !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield [this.#keyList[i], this.#valList[i]]\n      }\n    }\n  }\n\n  /**\n   * Return a generator yielding the keys in the cache,\n   * in order from most recently used to least recently used.\n   */\n  *keys() {\n    for (const i of this.#indexes()) {\n      const k = this.#keyList[i]\n      if (\n        k !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield k\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.keys}\n   *\n   * Return a generator yielding the keys in the cache,\n   * in order from least recently used to most recently used.\n   */\n  *rkeys() {\n    for (const i of this.#rindexes()) {\n      const k = this.#keyList[i]\n      if (\n        k !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield k\n      }\n    }\n  }\n\n  /**\n   * Return a generator yielding the values in the cache,\n   * in order from most recently used to least recently used.\n   */\n  *values() {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      if (\n        v !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield this.#valList[i] as V\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.values}\n   *\n   * Return a generator yielding the values in the cache,\n   * in order from least recently used to most recently used.\n   */\n  *rvalues() {\n    for (const i of this.#rindexes()) {\n      const v = this.#valList[i]\n      if (\n        v !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield this.#valList[i]\n      }\n    }\n  }\n\n  /**\n   * Iterating over the cache itself yields the same results as\n   * {@link LRUCache.entries}\n   */\n  [Symbol.iterator]() {\n    return this.entries()\n  }\n\n  /**\n   * A String value that is used in the creation of the default string description of an object.\n   * Called by the built-in method Object.prototype.toString.\n   */\n  [Symbol.toStringTag] = 'LRUCache'\n\n  /**\n   * Find a value for which the supplied fn method returns a truthy value,\n   * similar to Array.find().  fn is called as fn(value, key, cache).\n   */\n  find(\n    fn: (v: V, k: K, self: LRUCache) => boolean,\n    getOptions: LRUCache.GetOptions = {}\n  ) {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v)\n        ? v.__staleWhileFetching\n        : v\n      if (value === undefined) continue\n      if (fn(value, this.#keyList[i] as K, this)) {\n        return this.get(this.#keyList[i] as K, getOptions)\n      }\n    }\n  }\n\n  /**\n   * Call the supplied function on each item in the cache, in order from\n   * most recently used to least recently used.  fn is called as\n   * fn(value, key, cache).  Does not update age or recenty of use.\n   * Does not iterate over stale values.\n   */\n  forEach(\n    fn: (v: V, k: K, self: LRUCache) => any,\n    thisp: any = this\n  ) {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v)\n        ? v.__staleWhileFetching\n        : v\n      if (value === undefined) continue\n      fn.call(thisp, value, this.#keyList[i] as K, this)\n    }\n  }\n\n  /**\n   * The same as {@link LRUCache.forEach} but items are iterated over in\n   * reverse order.  (ie, less recently used items are iterated over first.)\n   */\n  rforEach(\n    fn: (v: V, k: K, self: LRUCache) => any,\n    thisp: any = this\n  ) {\n    for (const i of this.#rindexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v)\n        ? v.__staleWhileFetching\n        : v\n      if (value === undefined) continue\n      fn.call(thisp, value, this.#keyList[i] as K, this)\n    }\n  }\n\n  /**\n   * Delete any stale entries. Returns true if anything was removed,\n   * false otherwise.\n   */\n  purgeStale() {\n    let deleted = false\n    for (const i of this.#rindexes({ allowStale: true })) {\n      if (this.#isStale(i)) {\n        this.delete(this.#keyList[i] as K)\n        deleted = true\n      }\n    }\n    return deleted\n  }\n\n  /**\n   * Get the extended info about a given entry, to get its value, size, and\n   * TTL info simultaneously. Like {@link LRUCache#dump}, but just for a\n   * single key. Always returns stale values, if their info is found in the\n   * cache, so be sure to check for expired TTLs if relevant.\n   */\n  info(key: K): LRUCache.Entry | undefined {\n    const i = this.#keyMap.get(key)\n    if (i === undefined) return undefined\n    const v = this.#valList[i]\n    const value: V | undefined = this.#isBackgroundFetch(v)\n      ? v.__staleWhileFetching\n      : v\n    if (value === undefined) return undefined\n    const entry: LRUCache.Entry = { value }\n    if (this.#ttls && this.#starts) {\n      const ttl = this.#ttls[i]\n      const start = this.#starts[i]\n      if (ttl && start) {\n        const remain = ttl - (perf.now() - start)\n        entry.ttl = remain\n        entry.start = Date.now()\n      }\n    }\n    if (this.#sizes) {\n      entry.size = this.#sizes[i]\n    }\n    return entry\n  }\n\n  /**\n   * Return an array of [key, {@link LRUCache.Entry}] tuples which can be\n   * passed to cache.load()\n   */\n  dump() {\n    const arr: [K, LRUCache.Entry][] = []\n    for (const i of this.#indexes({ allowStale: true })) {\n      const key = this.#keyList[i]\n      const v = this.#valList[i]\n      const value: V | undefined = this.#isBackgroundFetch(v)\n        ? v.__staleWhileFetching\n        : v\n      if (value === undefined || key === undefined) continue\n      const entry: LRUCache.Entry = { value }\n      if (this.#ttls && this.#starts) {\n        entry.ttl = this.#ttls[i]\n        // always dump the start relative to a portable timestamp\n        // it's ok for this to be a bit slow, it's a rare operation.\n        const age = perf.now() - (this.#starts[i] as number)\n        entry.start = Math.floor(Date.now() - age)\n      }\n      if (this.#sizes) {\n        entry.size = this.#sizes[i]\n      }\n      arr.unshift([key, entry])\n    }\n    return arr\n  }\n\n  /**\n   * Reset the cache and load in the items in entries in the order listed.\n   * Note that the shape of the resulting cache may be different if the\n   * same options are not used in both caches.\n   */\n  load(arr: [K, LRUCache.Entry][]) {\n    this.clear()\n    for (const [key, entry] of arr) {\n      if (entry.start) {\n        // entry.start is a portable timestamp, but we may be using\n        // node's performance.now(), so calculate the offset, so that\n        // we get the intended remaining TTL, no matter how long it's\n        // been on ice.\n        //\n        // it's ok for this to be a bit slow, it's a rare operation.\n        const age = Date.now() - entry.start\n        entry.start = perf.now() - age\n      }\n      this.set(key, entry.value, entry)\n    }\n  }\n\n  /**\n   * Add a value to the cache.\n   *\n   * Note: if `undefined` is specified as a value, this is an alias for\n   * {@link LRUCache#delete}\n   */\n  set(\n    k: K,\n    v: V | BackgroundFetch | undefined,\n    setOptions: LRUCache.SetOptions = {}\n  ) {\n    if (v === undefined) {\n      this.delete(k)\n      return this\n    }\n    const {\n      ttl = this.ttl,\n      start,\n      noDisposeOnSet = this.noDisposeOnSet,\n      sizeCalculation = this.sizeCalculation,\n      status,\n    } = setOptions\n    let { noUpdateTTL = this.noUpdateTTL } = setOptions\n\n    const size = this.#requireSize(\n      k,\n      v,\n      setOptions.size || 0,\n      sizeCalculation\n    )\n    // if the item doesn't fit, don't do anything\n    // NB: maxEntrySize set to maxSize by default\n    if (this.maxEntrySize && size > this.maxEntrySize) {\n      if (status) {\n        status.set = 'miss'\n        status.maxEntrySizeExceeded = true\n      }\n      // have to delete, in case something is there already.\n      this.delete(k)\n      return this\n    }\n    let index = this.#size === 0 ? undefined : this.#keyMap.get(k)\n    if (index === undefined) {\n      // addition\n      index = (\n        this.#size === 0\n          ? this.#tail\n          : this.#free.length !== 0\n          ? this.#free.pop()\n          : this.#size === this.#max\n          ? this.#evict(false)\n          : this.#size\n      ) as Index\n      this.#keyList[index] = k\n      this.#valList[index] = v\n      this.#keyMap.set(k, index)\n      this.#next[this.#tail] = index\n      this.#prev[index] = this.#tail\n      this.#tail = index\n      this.#size++\n      this.#addItemSize(index, size, status)\n      if (status) status.set = 'add'\n      noUpdateTTL = false\n    } else {\n      // update\n      this.#moveToTail(index)\n      const oldVal = this.#valList[index] as V | BackgroundFetch\n      if (v !== oldVal) {\n        if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {\n          oldVal.__abortController.abort(new Error('replaced'))\n          const { __staleWhileFetching: s } = oldVal\n          if (s !== undefined && !noDisposeOnSet) {\n            if (this.#hasDispose) {\n              this.#dispose?.(s as V, k, 'set')\n            }\n            if (this.#hasDisposeAfter) {\n              this.#disposed?.push([s as V, k, 'set'])\n            }\n          }\n        } else if (!noDisposeOnSet) {\n          if (this.#hasDispose) {\n            this.#dispose?.(oldVal as V, k, 'set')\n          }\n          if (this.#hasDisposeAfter) {\n            this.#disposed?.push([oldVal as V, k, 'set'])\n          }\n        }\n        this.#removeItemSize(index)\n        this.#addItemSize(index, size, status)\n        this.#valList[index] = v\n        if (status) {\n          status.set = 'replace'\n          const oldValue =\n            oldVal && this.#isBackgroundFetch(oldVal)\n              ? oldVal.__staleWhileFetching\n              : oldVal\n          if (oldValue !== undefined) status.oldValue = oldValue\n        }\n      } else if (status) {\n        status.set = 'update'\n      }\n    }\n    if (ttl !== 0 && !this.#ttls) {\n      this.#initializeTTLTracking()\n    }\n    if (this.#ttls) {\n      if (!noUpdateTTL) {\n        this.#setItemTTL(index, ttl, start)\n      }\n      if (status) this.#statusTTL(status, index)\n    }\n    if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n    return this\n  }\n\n  /**\n   * Evict the least recently used item, returning its value or\n   * `undefined` if cache is empty.\n   */\n  pop(): V | undefined {\n    try {\n      while (this.#size) {\n        const val = this.#valList[this.#head]\n        this.#evict(true)\n        if (this.#isBackgroundFetch(val)) {\n          if (val.__staleWhileFetching) {\n            return val.__staleWhileFetching\n          }\n        } else if (val !== undefined) {\n          return val\n        }\n      }\n    } finally {\n      if (this.#hasDisposeAfter && this.#disposed) {\n        const dt = this.#disposed\n        let task: DisposeTask | undefined\n        while ((task = dt?.shift())) {\n          this.#disposeAfter?.(...task)\n        }\n      }\n    }\n  }\n\n  #evict(free: boolean) {\n    const head = this.#head\n    const k = this.#keyList[head] as K\n    const v = this.#valList[head] as V\n    if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {\n      v.__abortController.abort(new Error('evicted'))\n    } else if (this.#hasDispose || this.#hasDisposeAfter) {\n      if (this.#hasDispose) {\n        this.#dispose?.(v, k, 'evict')\n      }\n      if (this.#hasDisposeAfter) {\n        this.#disposed?.push([v, k, 'evict'])\n      }\n    }\n    this.#removeItemSize(head)\n    // if we aren't about to use the index, then null these out\n    if (free) {\n      this.#keyList[head] = undefined\n      this.#valList[head] = undefined\n      this.#free.push(head)\n    }\n    if (this.#size === 1) {\n      this.#head = this.#tail = 0 as Index\n      this.#free.length = 0\n    } else {\n      this.#head = this.#next[head] as Index\n    }\n    this.#keyMap.delete(k)\n    this.#size--\n    return head\n  }\n\n  /**\n   * Check if a key is in the cache, without updating the recency of use.\n   * Will return false if the item is stale, even though it is technically\n   * in the cache.\n   *\n   * Will not update item age unless\n   * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.\n   */\n  has(k: K, hasOptions: LRUCache.HasOptions = {}) {\n    const { updateAgeOnHas = this.updateAgeOnHas, status } =\n      hasOptions\n    const index = this.#keyMap.get(k)\n    if (index !== undefined) {\n      const v = this.#valList[index]\n      if (\n        this.#isBackgroundFetch(v) &&\n        v.__staleWhileFetching === undefined\n      ) {\n        return false\n      }\n      if (!this.#isStale(index)) {\n        if (updateAgeOnHas) {\n          this.#updateItemAge(index)\n        }\n        if (status) {\n          status.has = 'hit'\n          this.#statusTTL(status, index)\n        }\n        return true\n      } else if (status) {\n        status.has = 'stale'\n        this.#statusTTL(status, index)\n      }\n    } else if (status) {\n      status.has = 'miss'\n    }\n    return false\n  }\n\n  /**\n   * Like {@link LRUCache#get} but doesn't update recency or delete stale\n   * items.\n   *\n   * Returns `undefined` if the item is stale, unless\n   * {@link LRUCache.OptionsBase.allowStale} is set.\n   */\n  peek(k: K, peekOptions: LRUCache.PeekOptions = {}) {\n    const { allowStale = this.allowStale } = peekOptions\n    const index = this.#keyMap.get(k)\n    if (\n      index === undefined ||\n      (!allowStale && this.#isStale(index))\n    ) {\n      return\n    }\n    const v = this.#valList[index]\n    // either stale and allowed, or forcing a refresh of non-stale value\n    return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n  }\n\n  #backgroundFetch(\n    k: K,\n    index: Index | undefined,\n    options: LRUCache.FetchOptions,\n    context: any\n  ): BackgroundFetch {\n    const v = index === undefined ? undefined : this.#valList[index]\n    if (this.#isBackgroundFetch(v)) {\n      return v\n    }\n\n    const ac = new AC()\n    const { signal } = options\n    // when/if our AC signals, then stop listening to theirs.\n    signal?.addEventListener('abort', () => ac.abort(signal.reason), {\n      signal: ac.signal,\n    })\n\n    const fetchOpts = {\n      signal: ac.signal,\n      options,\n      context,\n    }\n\n    const cb = (\n      v: V | undefined,\n      updateCache = false\n    ): V | undefined => {\n      const { aborted } = ac.signal\n      const ignoreAbort = options.ignoreFetchAbort && v !== undefined\n      if (options.status) {\n        if (aborted && !updateCache) {\n          options.status.fetchAborted = true\n          options.status.fetchError = ac.signal.reason\n          if (ignoreAbort) options.status.fetchAbortIgnored = true\n        } else {\n          options.status.fetchResolved = true\n        }\n      }\n      if (aborted && !ignoreAbort && !updateCache) {\n        return fetchFail(ac.signal.reason)\n      }\n      // either we didn't abort, and are still here, or we did, and ignored\n      const bf = p as BackgroundFetch\n      if (this.#valList[index as Index] === p) {\n        if (v === undefined) {\n          if (bf.__staleWhileFetching) {\n            this.#valList[index as Index] = bf.__staleWhileFetching\n          } else {\n            this.delete(k)\n          }\n        } else {\n          if (options.status) options.status.fetchUpdated = true\n          this.set(k, v, fetchOpts.options)\n        }\n      }\n      return v\n    }\n\n    const eb = (er: any) => {\n      if (options.status) {\n        options.status.fetchRejected = true\n        options.status.fetchError = er\n      }\n      return fetchFail(er)\n    }\n\n    const fetchFail = (er: any): V | undefined => {\n      const { aborted } = ac.signal\n      const allowStaleAborted =\n        aborted && options.allowStaleOnFetchAbort\n      const allowStale =\n        allowStaleAborted || options.allowStaleOnFetchRejection\n      const noDelete = allowStale || options.noDeleteOnFetchRejection\n      const bf = p as BackgroundFetch\n      if (this.#valList[index as Index] === p) {\n        // if we allow stale on fetch rejections, then we need to ensure that\n        // the stale value is not removed from the cache when the fetch fails.\n        const del = !noDelete || bf.__staleWhileFetching === undefined\n        if (del) {\n          this.delete(k)\n        } else if (!allowStaleAborted) {\n          // still replace the *promise* with the stale value,\n          // since we are done with the promise at this point.\n          // leave it untouched if we're still waiting for an\n          // aborted background fetch that hasn't yet returned.\n          this.#valList[index as Index] = bf.__staleWhileFetching\n        }\n      }\n      if (allowStale) {\n        if (options.status && bf.__staleWhileFetching !== undefined) {\n          options.status.returnedStale = true\n        }\n        return bf.__staleWhileFetching\n      } else if (bf.__returned === bf) {\n        throw er\n      }\n    }\n\n    const pcall = (\n      res: (v: V | undefined) => void,\n      rej: (e: any) => void\n    ) => {\n      const fmp = this.#fetchMethod?.(k, v, fetchOpts)\n      if (fmp && fmp instanceof Promise) {\n        fmp.then(v => res(v === undefined ? undefined : v), rej)\n      }\n      // ignored, we go until we finish, regardless.\n      // defer check until we are actually aborting,\n      // so fetchMethod can override.\n      ac.signal.addEventListener('abort', () => {\n        if (\n          !options.ignoreFetchAbort ||\n          options.allowStaleOnFetchAbort\n        ) {\n          res(undefined)\n          // when it eventually resolves, update the cache.\n          if (options.allowStaleOnFetchAbort) {\n            res = v => cb(v, true)\n          }\n        }\n      })\n    }\n\n    if (options.status) options.status.fetchDispatched = true\n    const p = new Promise(pcall).then(cb, eb)\n    const bf: BackgroundFetch = Object.assign(p, {\n      __abortController: ac,\n      __staleWhileFetching: v,\n      __returned: undefined,\n    })\n\n    if (index === undefined) {\n      // internal, don't expose status.\n      this.set(k, bf, { ...fetchOpts.options, status: undefined })\n      index = this.#keyMap.get(k)\n    } else {\n      this.#valList[index] = bf\n    }\n    return bf\n  }\n\n  #isBackgroundFetch(p: any): p is BackgroundFetch {\n    if (!this.#hasFetchMethod) return false\n    const b = p as BackgroundFetch\n    return (\n      !!b &&\n      b instanceof Promise &&\n      b.hasOwnProperty('__staleWhileFetching') &&\n      b.__abortController instanceof AC\n    )\n  }\n\n  /**\n   * Make an asynchronous cached fetch using the\n   * {@link LRUCache.OptionsBase.fetchMethod} function.\n   *\n   * If multiple fetches for the same key are issued, then they will all be\n   * coalesced into a single call to fetchMethod.\n   *\n   * Note that this means that handling options such as\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort},\n   * {@link LRUCache.FetchOptions.signal},\n   * and {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} will be\n   * determined by the FIRST fetch() call for a given key.\n   *\n   * This is a known (fixable) shortcoming which will be addresed on when\n   * someone complains about it, as the fix would involve added complexity and\n   * may not be worth the costs for this edge case.\n   */\n  fetch(\n    k: K,\n    fetchOptions: unknown extends FC\n      ? LRUCache.FetchOptions\n      : FC extends undefined | void\n      ? LRUCache.FetchOptionsNoContext\n      : LRUCache.FetchOptionsWithContext\n  ): Promise\n  // this overload not allowed if context is required\n  fetch(\n    k: unknown extends FC\n      ? K\n      : FC extends undefined | void\n      ? K\n      : never,\n    fetchOptions?: unknown extends FC\n      ? LRUCache.FetchOptions\n      : FC extends undefined | void\n      ? LRUCache.FetchOptionsNoContext\n      : never\n  ): Promise\n  async fetch(\n    k: K,\n    fetchOptions: LRUCache.FetchOptions = {}\n  ): Promise {\n    const {\n      // get options\n      allowStale = this.allowStale,\n      updateAgeOnGet = this.updateAgeOnGet,\n      noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n      // set options\n      ttl = this.ttl,\n      noDisposeOnSet = this.noDisposeOnSet,\n      size = 0,\n      sizeCalculation = this.sizeCalculation,\n      noUpdateTTL = this.noUpdateTTL,\n      // fetch exclusive options\n      noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,\n      allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,\n      ignoreFetchAbort = this.ignoreFetchAbort,\n      allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,\n      context,\n      forceRefresh = false,\n      status,\n      signal,\n    } = fetchOptions\n\n    if (!this.#hasFetchMethod) {\n      if (status) status.fetch = 'get'\n      return this.get(k, {\n        allowStale,\n        updateAgeOnGet,\n        noDeleteOnStaleGet,\n        status,\n      })\n    }\n\n    const options = {\n      allowStale,\n      updateAgeOnGet,\n      noDeleteOnStaleGet,\n      ttl,\n      noDisposeOnSet,\n      size,\n      sizeCalculation,\n      noUpdateTTL,\n      noDeleteOnFetchRejection,\n      allowStaleOnFetchRejection,\n      allowStaleOnFetchAbort,\n      ignoreFetchAbort,\n      status,\n      signal,\n    }\n\n    let index = this.#keyMap.get(k)\n    if (index === undefined) {\n      if (status) status.fetch = 'miss'\n      const p = this.#backgroundFetch(k, index, options, context)\n      return (p.__returned = p)\n    } else {\n      // in cache, maybe already fetching\n      const v = this.#valList[index]\n      if (this.#isBackgroundFetch(v)) {\n        const stale =\n          allowStale && v.__staleWhileFetching !== undefined\n        if (status) {\n          status.fetch = 'inflight'\n          if (stale) status.returnedStale = true\n        }\n        return stale ? v.__staleWhileFetching : (v.__returned = v)\n      }\n\n      // if we force a refresh, that means do NOT serve the cached value,\n      // unless we are already in the process of refreshing the cache.\n      const isStale = this.#isStale(index)\n      if (!forceRefresh && !isStale) {\n        if (status) status.fetch = 'hit'\n        this.#moveToTail(index)\n        if (updateAgeOnGet) {\n          this.#updateItemAge(index)\n        }\n        if (status) this.#statusTTL(status, index)\n        return v\n      }\n\n      // ok, it is stale or a forced refresh, and not already fetching.\n      // refresh the cache.\n      const p = this.#backgroundFetch(k, index, options, context)\n      const hasStale = p.__staleWhileFetching !== undefined\n      const staleVal = hasStale && allowStale\n      if (status) {\n        status.fetch = isStale ? 'stale' : 'refresh'\n        if (staleVal && isStale) status.returnedStale = true\n      }\n      return staleVal ? p.__staleWhileFetching : (p.__returned = p)\n    }\n  }\n\n  /**\n   * Return a value from the cache. Will update the recency of the cache\n   * entry found.\n   *\n   * If the key is not found, get() will return `undefined`.\n   */\n  get(k: K, getOptions: LRUCache.GetOptions = {}) {\n    const {\n      allowStale = this.allowStale,\n      updateAgeOnGet = this.updateAgeOnGet,\n      noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n      status,\n    } = getOptions\n    const index = this.#keyMap.get(k)\n    if (index !== undefined) {\n      const value = this.#valList[index]\n      const fetching = this.#isBackgroundFetch(value)\n      if (status) this.#statusTTL(status, index)\n      if (this.#isStale(index)) {\n        if (status) status.get = 'stale'\n        // delete only if not an in-flight background fetch\n        if (!fetching) {\n          if (!noDeleteOnStaleGet) {\n            this.delete(k)\n          }\n          if (status && allowStale) status.returnedStale = true\n          return allowStale ? value : undefined\n        } else {\n          if (\n            status &&\n            allowStale &&\n            value.__staleWhileFetching !== undefined\n          ) {\n            status.returnedStale = true\n          }\n          return allowStale ? value.__staleWhileFetching : undefined\n        }\n      } else {\n        if (status) status.get = 'hit'\n        // if we're currently fetching it, we don't actually have it yet\n        // it's not stale, which means this isn't a staleWhileRefetching.\n        // If it's not stale, and fetching, AND has a __staleWhileFetching\n        // value, then that means the user fetched with {forceRefresh:true},\n        // so it's safe to return that value.\n        if (fetching) {\n          return value.__staleWhileFetching\n        }\n        this.#moveToTail(index)\n        if (updateAgeOnGet) {\n          this.#updateItemAge(index)\n        }\n        return value\n      }\n    } else if (status) {\n      status.get = 'miss'\n    }\n  }\n\n  #connect(p: Index, n: Index) {\n    this.#prev[n] = p\n    this.#next[p] = n\n  }\n\n  #moveToTail(index: Index): void {\n    // if tail already, nothing to do\n    // if head, move head to next[index]\n    // else\n    //   move next[prev[index]] to next[index] (head has no prev)\n    //   move prev[next[index]] to prev[index]\n    // prev[index] = tail\n    // next[tail] = index\n    // tail = index\n    if (index !== this.#tail) {\n      if (index === this.#head) {\n        this.#head = this.#next[index] as Index\n      } else {\n        this.#connect(\n          this.#prev[index] as Index,\n          this.#next[index] as Index\n        )\n      }\n      this.#connect(this.#tail, index)\n      this.#tail = index\n    }\n  }\n\n  /**\n   * Deletes a key out of the cache.\n   * Returns true if the key was deleted, false otherwise.\n   */\n  delete(k: K) {\n    let deleted = false\n    if (this.#size !== 0) {\n      const index = this.#keyMap.get(k)\n      if (index !== undefined) {\n        deleted = true\n        if (this.#size === 1) {\n          this.clear()\n        } else {\n          this.#removeItemSize(index)\n          const v = this.#valList[index]\n          if (this.#isBackgroundFetch(v)) {\n            v.__abortController.abort(new Error('deleted'))\n          } else if (this.#hasDispose || this.#hasDisposeAfter) {\n            if (this.#hasDispose) {\n              this.#dispose?.(v as V, k, 'delete')\n            }\n            if (this.#hasDisposeAfter) {\n              this.#disposed?.push([v as V, k, 'delete'])\n            }\n          }\n          this.#keyMap.delete(k)\n          this.#keyList[index] = undefined\n          this.#valList[index] = undefined\n          if (index === this.#tail) {\n            this.#tail = this.#prev[index] as Index\n          } else if (index === this.#head) {\n            this.#head = this.#next[index] as Index\n          } else {\n            const pi = this.#prev[index] as number\n            this.#next[pi] = this.#next[index] as number\n            const ni = this.#next[index] as number\n            this.#prev[ni] = this.#prev[index] as number\n          }\n          this.#size--\n          this.#free.push(index)\n        }\n      }\n    }\n    if (this.#hasDisposeAfter && this.#disposed?.length) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n    return deleted\n  }\n\n  /**\n   * Clear the cache entirely, throwing away all values.\n   */\n  clear() {\n    for (const index of this.#rindexes({ allowStale: true })) {\n      const v = this.#valList[index]\n      if (this.#isBackgroundFetch(v)) {\n        v.__abortController.abort(new Error('deleted'))\n      } else {\n        const k = this.#keyList[index]\n        if (this.#hasDispose) {\n          this.#dispose?.(v as V, k as K, 'delete')\n        }\n        if (this.#hasDisposeAfter) {\n          this.#disposed?.push([v as V, k as K, 'delete'])\n        }\n      }\n    }\n\n    this.#keyMap.clear()\n    this.#valList.fill(undefined)\n    this.#keyList.fill(undefined)\n    if (this.#ttls && this.#starts) {\n      this.#ttls.fill(0)\n      this.#starts.fill(0)\n    }\n    if (this.#sizes) {\n      this.#sizes.fill(0)\n    }\n    this.#head = 0 as Index\n    this.#tail = 0 as Index\n    this.#free.length = 0\n    this.#calculatedSize = 0\n    this.#size = 0\n    if (this.#hasDisposeAfter && this.#disposed) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n  }\n}\n","import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'path'\n\nimport { fileURLToPath } from 'url'\n\nimport * as actualFS from 'fs'\nimport {\n  lstatSync,\n  readdir as readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync as rps,\n} from 'fs'\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\nimport { lstat, readdir, readlink, realpath } from 'fs/promises'\n\nimport type { Dirent, Stats } from 'fs'\nimport { Minipass } from 'minipass'\n\n/**\n * An object that will be used to override the default `fs`\n * methods.  Any methods that are not overridden will use Node's\n * built-in implementations.\n *\n * - lstatSync\n * - readdir (callback `withFileTypes` Dirent variant, used for\n *   readdirCB and most walks)\n * - readdirSync\n * - readlinkSync\n * - realpathSync\n * - promises: Object containing the following async methods:\n *   - lstat\n *   - readdir (Dirent variant only)\n *   - readlink\n *   - realpath\n */\nexport interface FSOption {\n  lstatSync?: (path: string) => Stats\n  readdir?: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any\n  ) => void\n  readdirSync?: (\n    path: string,\n    options: { withFileTypes: true }\n  ) => Dirent[]\n  readlinkSync?: (path: string) => string\n  realpathSync?: (path: string) => string\n  promises?: {\n    lstat?: (path: string) => Promise\n    readdir?: (\n      path: string,\n      options: { withFileTypes: true }\n    ) => Promise\n    readlink?: (path: string) => Promise\n    realpath?: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\ninterface FSValue {\n  lstatSync: (path: string) => Stats\n  readdir: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any\n  ) => void\n  readdirSync: (path: string, options: { withFileTypes: true }) => Dirent[]\n  readlinkSync: (path: string) => string\n  realpathSync: (path: string) => string\n  promises: {\n    lstat: (path: string) => Promise\n    readdir: (\n      path: string,\n      options: { withFileTypes: true }\n    ) => Promise\n    readlink: (path: string) => Promise\n    realpath: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\nconst defaultFS: FSValue = {\n  lstatSync,\n  readdir: readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync,\n  promises: {\n    lstat,\n    readdir,\n    readlink,\n    realpath,\n  },\n}\n\n// if they just gave us require('fs') then use our default\nconst fsFromOption = (fsOption?: FSOption): FSValue =>\n  !fsOption || fsOption === defaultFS || fsOption === actualFS\n    ? defaultFS\n    : {\n        ...defaultFS,\n        ...fsOption,\n        promises: {\n          ...defaultFS.promises,\n          ...(fsOption.promises || {}),\n        },\n      }\n\n// turn something like //?/c:/ into c:\\\nconst uncDriveRegexp = /^\\\\\\\\\\?\\\\([a-z]:)\\\\?$/i\nconst uncToDrive = (rootPath: string): string =>\n  rootPath.replace(/\\//g, '\\\\').replace(uncDriveRegexp, '$1\\\\')\n\n// windows paths are separated by either / or \\\nconst eitherSep = /[\\\\\\/]/\n\nconst UNKNOWN = 0 // may not even exist, for all we know\nconst IFIFO = 0b0001\nconst IFCHR = 0b0010\nconst IFDIR = 0b0100\nconst IFBLK = 0b0110\nconst IFREG = 0b1000\nconst IFLNK = 0b1010\nconst IFSOCK = 0b1100\nconst IFMT = 0b1111\n\nexport type Type =\n  | 'Unknown'\n  | 'FIFO'\n  | 'CharacterDevice'\n  | 'Directory'\n  | 'BlockDevice'\n  | 'File'\n  | 'SymbolicLink'\n  | 'Socket'\n\n// mask to unset low 4 bits\nconst IFMT_UNKNOWN = ~IFMT\n\n// set after successfully calling readdir() and getting entries.\nconst READDIR_CALLED = 0b0000_0001_0000\n// set after a successful lstat()\nconst LSTAT_CALLED = 0b0000_0010_0000\n// set if an entry (or one of its parents) is definitely not a dir\nconst ENOTDIR = 0b0000_0100_0000\n// set if an entry (or one of its parents) does not exist\n// (can also be set on lstat errors like EACCES or ENAMETOOLONG)\nconst ENOENT = 0b0000_1000_0000\n// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK\n// set if we fail to readlink\nconst ENOREADLINK = 0b0001_0000_0000\n// set if we know realpath() will fail\nconst ENOREALPATH = 0b0010_0000_0000\n\nconst ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH\nconst TYPEMASK = 0b0011_1111_1111\n\nconst entToType = (s: Dirent | Stats) =>\n  s.isFile()\n    ? IFREG\n    : s.isDirectory()\n    ? IFDIR\n    : s.isSymbolicLink()\n    ? IFLNK\n    : s.isCharacterDevice()\n    ? IFCHR\n    : s.isBlockDevice()\n    ? IFBLK\n    : s.isSocket()\n    ? IFSOCK\n    : s.isFIFO()\n    ? IFIFO\n    : UNKNOWN\n\n// normalize unicode path names\nconst normalizeCache = new Map()\nconst normalize = (s: string) => {\n  const c = normalizeCache.get(s)\n  if (c) return c\n  const n = s.normalize('NFKD')\n  normalizeCache.set(s, n)\n  return n\n}\n\nconst normalizeNocaseCache = new Map()\nconst normalizeNocase = (s: string) => {\n  const c = normalizeNocaseCache.get(s)\n  if (c) return c\n  const n = normalize(s.toLowerCase())\n  normalizeNocaseCache.set(s, n)\n  return n\n}\n\n/**\n * Options that may be provided to the Path constructor\n */\nexport interface PathOpts {\n  fullpath?: string\n  relative?: string\n  relativePosix?: string\n  parent?: PathBase\n  /**\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * An LRUCache for storing resolved path strings or Path objects.\n * @internal\n */\nexport class ResolveCache extends LRUCache {\n  constructor() {\n    super({ max: 256 })\n  }\n}\n\n// In order to prevent blowing out the js heap by allocating hundreds of\n// thousands of Path entries when walking extremely large trees, the \"children\"\n// in this tree are represented by storing an array of Path entries in an\n// LRUCache, indexed by the parent.  At any time, Path.children() may return an\n// empty array, indicating that it doesn't know about any of its children, and\n// thus has to rebuild that cache.  This is fine, it just means that we don't\n// benefit as much from having the cached entries, but huge directory walks\n// don't blow out the stack, and smaller ones are still as fast as possible.\n//\n//It does impose some complexity when building up the readdir data, because we\n//need to pass a reference to the children array that we started with.\n\n/**\n * an LRUCache for storing child entries.\n * @internal\n */\nexport class ChildrenCache extends LRUCache {\n  constructor(maxSize: number = 16 * 1024) {\n    super({\n      maxSize,\n      // parent + children\n      sizeCalculation: a => a.length + 1,\n    })\n  }\n}\n\n/**\n * Array of Path objects, plus a marker indicating the first provisional entry\n *\n * @internal\n */\nexport type Children = PathBase[] & { provisional: number }\n\nconst setAsCwd = Symbol('PathScurry setAsCwd')\n\n/**\n * Path objects are sort of like a super-powered\n * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}\n *\n * Each one represents a single filesystem entry on disk, which may or may not\n * exist. It includes methods for reading various types of information via\n * lstat, readlink, and readdir, and caches all information to the greatest\n * degree possible.\n *\n * Note that fs operations that would normally throw will instead return an\n * \"empty\" value. This is in order to prevent excessive overhead from error\n * stack traces.\n */\nexport abstract class PathBase implements Dirent {\n  /**\n   * the basename of this path\n   *\n   * **Important**: *always* test the path name against any test string\n   * usingthe {@link isNamed} method, and not by directly comparing this\n   * string. Otherwise, unicode path strings that the system sees as identical\n   * will not be properly treated as the same path, leading to incorrect\n   * behavior and possible security issues.\n   */\n  name: string\n  /**\n   * the Path entry corresponding to the path root.\n   *\n   * @internal\n   */\n  root: PathBase\n  /**\n   * All roots found within the current PathScurry family\n   *\n   * @internal\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * a reference to the parent path, or undefined in the case of root entries\n   *\n   * @internal\n   */\n  parent?: PathBase\n  /**\n   * boolean indicating whether paths are compared case-insensitively\n   * @internal\n   */\n  nocase: boolean\n\n  /**\n   * the string or regexp used to split paths. On posix, it is `'/'`, and on\n   * windows it is a RegExp matching either `'/'` or `'\\\\'`\n   */\n  abstract splitSep: string | RegExp\n  /**\n   * The path separator string to use when joining paths\n   */\n  abstract sep: string\n\n  // potential default fs override\n  #fs: FSValue\n\n  // Stats fields\n  #dev?: number\n  get dev() {\n    return this.#dev\n  }\n  #mode?: number\n  get mode() {\n    return this.#mode\n  }\n  #nlink?: number\n  get nlink() {\n    return this.#nlink\n  }\n  #uid?: number\n  get uid() {\n    return this.#uid\n  }\n  #gid?: number\n  get gid() {\n    return this.#gid\n  }\n  #rdev?: number\n  get rdev() {\n    return this.#rdev\n  }\n  #blksize?: number\n  get blksize() {\n    return this.#blksize\n  }\n  #ino?: number\n  get ino() {\n    return this.#ino\n  }\n  #size?: number\n  get size() {\n    return this.#size\n  }\n  #blocks?: number\n  get blocks() {\n    return this.#blocks\n  }\n  #atimeMs?: number\n  get atimeMs() {\n    return this.#atimeMs\n  }\n  #mtimeMs?: number\n  get mtimeMs() {\n    return this.#mtimeMs\n  }\n  #ctimeMs?: number\n  get ctimeMs() {\n    return this.#ctimeMs\n  }\n  #birthtimeMs?: number\n  get birthtimeMs() {\n    return this.#birthtimeMs\n  }\n  #atime?: Date\n  get atime() {\n    return this.#atime\n  }\n  #mtime?: Date\n  get mtime() {\n    return this.#mtime\n  }\n  #ctime?: Date\n  get ctime() {\n    return this.#ctime\n  }\n  #birthtime?: Date\n  get birthtime() {\n    return this.#birthtime\n  }\n\n  #matchName: string\n  #depth?: number\n  #fullpath?: string\n  #fullpathPosix?: string\n  #relative?: string\n  #relativePosix?: string\n  #type: number\n  #children: ChildrenCache\n  #linkTarget?: PathBase\n  #realpath?: PathBase\n\n  /**\n   * This property is for compatibility with the Dirent class as of\n   * Node v20, where Dirent['path'] refers to the path of the directory\n   * that was passed to readdir.  So, somewhat counterintuitively, this\n   * property refers to the *parent* path, not the path object itself.\n   * For root entries, it's the path to the entry itself.\n   */\n  get path(): string {\n    return (this.parent || this).fullpath()\n  }\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts\n  ) {\n    this.name = name\n    this.#matchName = nocase ? normalizeNocase(name) : normalize(name)\n    this.#type = type & TYPEMASK\n    this.nocase = nocase\n    this.roots = roots\n    this.root = root || this\n    this.#children = children\n    this.#fullpath = opts.fullpath\n    this.#relative = opts.relative\n    this.#relativePosix = opts.relativePosix\n    this.parent = opts.parent\n    if (this.parent) {\n      this.#fs = this.parent.#fs\n    } else {\n      this.#fs = fsFromOption(opts.fs)\n    }\n  }\n\n  /**\n   * Returns the depth of the Path object from its root.\n   *\n   * For example, a path at `/foo/bar` would have a depth of 2.\n   */\n  depth(): number {\n    if (this.#depth !== undefined) return this.#depth\n    if (!this.parent) return (this.#depth = 0)\n    return (this.#depth = this.parent.depth() + 1)\n  }\n\n  /**\n   * @internal\n   */\n  abstract getRootString(path: string): string\n  /**\n   * @internal\n   */\n  abstract getRoot(rootPath: string): PathBase\n  /**\n   * @internal\n   */\n  abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase\n\n  /**\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Get the Path object referenced by the string path, resolved from this Path\n   */\n  resolve(path?: string): PathBase {\n    if (!path) {\n      return this\n    }\n    const rootPath = this.getRootString(path)\n    const dir = path.substring(rootPath.length)\n    const dirParts = dir.split(this.splitSep)\n    const result: PathBase = rootPath\n      ? this.getRoot(rootPath).#resolveParts(dirParts)\n      : this.#resolveParts(dirParts)\n    return result\n  }\n\n  #resolveParts(dirParts: string[]) {\n    let p: PathBase = this\n    for (const part of dirParts) {\n      p = p.child(part)\n    }\n    return p\n  }\n\n  /**\n   * Returns the cached children Path objects, if still available.  If they\n   * have fallen out of the cache, then returns an empty array, and resets the\n   * READDIR_CALLED bit, so that future calls to readdir() will require an fs\n   * lookup.\n   *\n   * @internal\n   */\n  children(): Children {\n    const cached = this.#children.get(this)\n    if (cached) {\n      return cached\n    }\n    const children: Children = Object.assign([], { provisional: 0 })\n    this.#children.set(this, children)\n    this.#type &= ~READDIR_CALLED\n    return children\n  }\n\n  /**\n   * Resolves a path portion and returns or creates the child Path.\n   *\n   * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is\n   * `'..'`.\n   *\n   * This should not be called directly.  If `pathPart` contains any path\n   * separators, it will lead to unsafe undefined behavior.\n   *\n   * Use `Path.resolve()` instead.\n   *\n   * @internal\n   */\n  child(pathPart: string, opts?: PathOpts): PathBase {\n    if (pathPart === '' || pathPart === '.') {\n      return this\n    }\n    if (pathPart === '..') {\n      return this.parent || this\n    }\n\n    // find the child\n    const children = this.children()\n    const name = this.nocase\n      ? normalizeNocase(pathPart)\n      : normalize(pathPart)\n    for (const p of children) {\n      if (p.#matchName === name) {\n        return p\n      }\n    }\n\n    // didn't find it, create provisional child, since it might not\n    // actually exist.  If we know the parent isn't a dir, then\n    // in fact it CAN'T exist.\n    const s = this.parent ? this.sep : ''\n    const fullpath = this.#fullpath\n      ? this.#fullpath + s + pathPart\n      : undefined\n    const pchild = this.newChild(pathPart, UNKNOWN, {\n      ...opts,\n      parent: this,\n      fullpath,\n    })\n\n    if (!this.canReaddir()) {\n      pchild.#type |= ENOENT\n    }\n\n    // don't have to update provisional, because if we have real children,\n    // then provisional is set to children.length, otherwise a lower number\n    children.push(pchild)\n    return pchild\n  }\n\n  /**\n   * The relative path from the cwd. If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpath()\n   */\n  relative(): string {\n    if (this.#relative !== undefined) {\n      return this.#relative\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relative = this.name)\n    }\n    const pv = p.relative()\n    return pv + (!pv || !p.parent ? '' : this.sep) + name\n  }\n\n  /**\n   * The relative path from the cwd, using / as the path separator.\n   * If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpathPosix()\n   * On posix systems, this is identical to relative().\n   */\n  relativePosix(): string {\n    if (this.sep === '/') return this.relative()\n    if (this.#relativePosix !== undefined) return this.#relativePosix\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relativePosix = this.fullpathPosix())\n    }\n    const pv = p.relativePosix()\n    return pv + (!pv || !p.parent ? '' : '/') + name\n  }\n\n  /**\n   * The fully resolved path string for this Path entry\n   */\n  fullpath(): string {\n    if (this.#fullpath !== undefined) {\n      return this.#fullpath\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#fullpath = this.name)\n    }\n    const pv = p.fullpath()\n    const fp = pv + (!p.parent ? '' : this.sep) + name\n    return (this.#fullpath = fp)\n  }\n\n  /**\n   * On platforms other than windows, this is identical to fullpath.\n   *\n   * On windows, this is overridden to return the forward-slash form of the\n   * full UNC path.\n   */\n  fullpathPosix(): string {\n    if (this.#fullpathPosix !== undefined) return this.#fullpathPosix\n    if (this.sep === '/') return (this.#fullpathPosix = this.fullpath())\n    if (!this.parent) {\n      const p = this.fullpath().replace(/\\\\/g, '/')\n      if (/^[a-z]:\\//i.test(p)) {\n        return (this.#fullpathPosix = `//?/${p}`)\n      } else {\n        return (this.#fullpathPosix = p)\n      }\n    }\n    const p = this.parent\n    const pfpp = p.fullpathPosix()\n    const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name\n    return (this.#fullpathPosix = fpp)\n  }\n\n  /**\n   * Is the Path of an unknown type?\n   *\n   * Note that we might know *something* about it if there has been a previous\n   * filesystem operation, for example that it does not exist, or is not a\n   * link, or whether it has child entries.\n   */\n  isUnknown(): boolean {\n    return (this.#type & IFMT) === UNKNOWN\n  }\n\n  isType(type: Type): boolean {\n    return this[`is${type}`]()\n  }\n\n  getType(): Type {\n    return this.isUnknown()\n      ? 'Unknown'\n      : this.isDirectory()\n      ? 'Directory'\n      : this.isFile()\n      ? 'File'\n      : this.isSymbolicLink()\n      ? 'SymbolicLink'\n      : this.isFIFO()\n      ? 'FIFO'\n      : this.isCharacterDevice()\n      ? 'CharacterDevice'\n      : this.isBlockDevice()\n      ? 'BlockDevice'\n      : /* c8 ignore start */ this.isSocket()\n      ? 'Socket'\n      : 'Unknown'\n    /* c8 ignore stop */\n  }\n\n  /**\n   * Is the Path a regular file?\n   */\n  isFile(): boolean {\n    return (this.#type & IFMT) === IFREG\n  }\n\n  /**\n   * Is the Path a directory?\n   */\n  isDirectory(): boolean {\n    return (this.#type & IFMT) === IFDIR\n  }\n\n  /**\n   * Is the path a character device?\n   */\n  isCharacterDevice(): boolean {\n    return (this.#type & IFMT) === IFCHR\n  }\n\n  /**\n   * Is the path a block device?\n   */\n  isBlockDevice(): boolean {\n    return (this.#type & IFMT) === IFBLK\n  }\n\n  /**\n   * Is the path a FIFO pipe?\n   */\n  isFIFO(): boolean {\n    return (this.#type & IFMT) === IFIFO\n  }\n\n  /**\n   * Is the path a socket?\n   */\n  isSocket(): boolean {\n    return (this.#type & IFMT) === IFSOCK\n  }\n\n  /**\n   * Is the path a symbolic link?\n   */\n  isSymbolicLink(): boolean {\n    return (this.#type & IFLNK) === IFLNK\n  }\n\n  /**\n   * Return the entry if it has been subject of a successful lstat, or\n   * undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* simply\n   * mean that we haven't called lstat on it.\n   */\n  lstatCached(): PathBase | undefined {\n    return this.#type & LSTAT_CALLED ? this : undefined\n  }\n\n  /**\n   * Return the cached link target if the entry has been the subject of a\n   * successful readlink, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readlink() has been called at some point.\n   */\n  readlinkCached(): PathBase | undefined {\n    return this.#linkTarget\n  }\n\n  /**\n   * Returns the cached realpath target if the entry has been the subject\n   * of a successful realpath, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * realpath() has been called at some point.\n   */\n  realpathCached(): PathBase | undefined {\n    return this.#realpath\n  }\n\n  /**\n   * Returns the cached child Path entries array if the entry has been the\n   * subject of a successful readdir(), or [] otherwise.\n   *\n   * Does not read the filesystem, so an empty array *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readdir() has been called recently enough to still be valid.\n   */\n  readdirCached(): PathBase[] {\n    const children = this.children()\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * Return true if it's worth trying to readlink.  Ie, we don't (yet) have\n   * any indication that readlink will definitely fail.\n   *\n   * Returns false if the path is known to not be a symlink, if a previous\n   * readlink failed, or if the entry does not exist.\n   */\n  canReadlink(): boolean {\n    if (this.#linkTarget) return true\n    if (!this.parent) return false\n    // cases where it cannot possibly succeed\n    const ifmt = this.#type & IFMT\n    return !(\n      (ifmt !== UNKNOWN && ifmt !== IFLNK) ||\n      this.#type & ENOREADLINK ||\n      this.#type & ENOENT\n    )\n  }\n\n  /**\n   * Return true if readdir has previously been successfully called on this\n   * path, indicating that cachedReaddir() is likely valid.\n   */\n  calledReaddir(): boolean {\n    return !!(this.#type & READDIR_CALLED)\n  }\n\n  /**\n   * Returns true if the path is known to not exist. That is, a previous lstat\n   * or readdir failed to verify its existence when that would have been\n   * expected, or a parent entry was marked either enoent or enotdir.\n   */\n  isENOENT(): boolean {\n    return !!(this.#type & ENOENT)\n  }\n\n  /**\n   * Return true if the path is a match for the given path name.  This handles\n   * case sensitivity and unicode normalization.\n   *\n   * Note: even on case-sensitive systems, it is **not** safe to test the\n   * equality of the `.name` property to determine whether a given pathname\n   * matches, due to unicode normalization mismatches.\n   *\n   * Always use this method instead of testing the `path.name` property\n   * directly.\n   */\n  isNamed(n: string): boolean {\n    return !this.nocase\n      ? this.#matchName === normalize(n)\n      : this.#matchName === normalizeNocase(n)\n  }\n\n  /**\n   * Return the Path object corresponding to the target of a symbolic link.\n   *\n   * If the Path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   */\n  async readlink(): Promise {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = await this.#fs.promises.readlink(this.fullpath())\n      const linkTarget = this.parent.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  /**\n   * Synchronous {@link PathBase.readlink}\n   */\n  readlinkSync(): PathBase | undefined {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = this.#fs.readlinkSync(this.fullpath())\n      const linkTarget = this.parent.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  #readdirSuccess(children: Children) {\n    // succeeded, mark readdir called bit\n    this.#type |= READDIR_CALLED\n    // mark all remaining provisional children as ENOENT\n    for (let p = children.provisional; p < children.length; p++) {\n      children[p].#markENOENT()\n    }\n  }\n\n  #markENOENT() {\n    // mark as UNKNOWN and ENOENT\n    if (this.#type & ENOENT) return\n    this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN\n    this.#markChildrenENOENT()\n  }\n\n  #markChildrenENOENT() {\n    // all children are provisional and do not exist\n    const children = this.children()\n    children.provisional = 0\n    for (const p of children) {\n      p.#markENOENT()\n    }\n  }\n\n  #markENOREALPATH() {\n    this.#type |= ENOREALPATH\n    this.#markENOTDIR()\n  }\n\n  // save the information when we know the entry is not a dir\n  #markENOTDIR() {\n    // entry is not a directory, so any children can't exist.\n    // this *should* be impossible, since any children created\n    // after it's been marked ENOTDIR should be marked ENOENT,\n    // so it won't even get to this point.\n    /* c8 ignore start */\n    if (this.#type & ENOTDIR) return\n    /* c8 ignore stop */\n    let t = this.#type\n    // this could happen if we stat a dir, then delete it,\n    // then try to read it or one of its children.\n    if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN\n    this.#type = t | ENOTDIR\n    this.#markChildrenENOENT()\n  }\n\n  #readdirFail(code: string = '') {\n    // markENOTDIR and markENOENT also set provisional=0\n    if (code === 'ENOTDIR' || code === 'EPERM') {\n      this.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      this.#markENOENT()\n    } else {\n      this.children().provisional = 0\n    }\n  }\n\n  #lstatFail(code: string = '') {\n    // Windows just raises ENOENT in this case, disable for win CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR') {\n      // already know it has a parent by this point\n      const p = this.parent as PathBase\n      p.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      /* c8 ignore stop */\n      this.#markENOENT()\n    }\n  }\n\n  #readlinkFail(code: string = '') {\n    let ter = this.#type\n    ter |= ENOREADLINK\n    if (code === 'ENOENT') ter |= ENOENT\n    // windows gets a weird error when you try to readlink a file\n    if (code === 'EINVAL' || code === 'UNKNOWN') {\n      // exists, but not a symlink, we don't know WHAT it is, so remove\n      // all IFMT bits.\n      ter &= IFMT_UNKNOWN\n    }\n    this.#type = ter\n    // windows just gets ENOENT in this case.  We do cover the case,\n    // just disabled because it's impossible on Windows CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR' && this.parent) {\n      this.parent.#markENOTDIR()\n    }\n    /* c8 ignore stop */\n  }\n\n  #readdirAddChild(e: Dirent, c: Children) {\n    return (\n      this.#readdirMaybePromoteChild(e, c) ||\n      this.#readdirAddNewChild(e, c)\n    )\n  }\n\n  #readdirAddNewChild(e: Dirent, c: Children): PathBase {\n    // alloc new entry at head, so it's never provisional\n    const type = entToType(e)\n    const child = this.newChild(e.name, type, { parent: this })\n    const ifmt = child.#type & IFMT\n    if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {\n      child.#type |= ENOTDIR\n    }\n    c.unshift(child)\n    c.provisional++\n    return child\n  }\n\n  #readdirMaybePromoteChild(e: Dirent, c: Children): PathBase | undefined {\n    for (let p = c.provisional; p < c.length; p++) {\n      const pchild = c[p]\n      const name = this.nocase\n        ? normalizeNocase(e.name)\n        : normalize(e.name)\n      if (name !== pchild.#matchName) {\n        continue\n      }\n\n      return this.#readdirPromoteChild(e, pchild, p, c)\n    }\n  }\n\n  #readdirPromoteChild(\n    e: Dirent,\n    p: PathBase,\n    index: number,\n    c: Children\n  ): PathBase {\n    const v = p.name\n    // retain any other flags, but set ifmt from dirent\n    p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e)\n    // case sensitivity fixing when we learn the true name.\n    if (v !== e.name) p.name = e.name\n\n    // just advance provisional index (potentially off the list),\n    // otherwise we have to splice/pop it out and re-insert at head\n    if (index !== c.provisional) {\n      if (index === c.length - 1) c.pop()\n      else c.splice(index, 1)\n      c.unshift(p)\n    }\n    c.provisional++\n    return p\n  }\n\n  /**\n   * Call lstat() on this Path, and update all known information that can be\n   * determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(): Promise {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(await this.#fs.promises.lstat(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  /**\n   * synchronous {@link PathBase.lstat}\n   */\n  lstatSync(): PathBase | undefined {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(this.#fs.lstatSync(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  #applyStat(st: Stats) {\n    const {\n      atime,\n      atimeMs,\n      birthtime,\n      birthtimeMs,\n      blksize,\n      blocks,\n      ctime,\n      ctimeMs,\n      dev,\n      gid,\n      ino,\n      mode,\n      mtime,\n      mtimeMs,\n      nlink,\n      rdev,\n      size,\n      uid,\n    } = st\n    this.#atime = atime\n    this.#atimeMs = atimeMs\n    this.#birthtime = birthtime\n    this.#birthtimeMs = birthtimeMs\n    this.#blksize = blksize\n    this.#blocks = blocks\n    this.#ctime = ctime\n    this.#ctimeMs = ctimeMs\n    this.#dev = dev\n    this.#gid = gid\n    this.#ino = ino\n    this.#mode = mode\n    this.#mtime = mtime\n    this.#mtimeMs = mtimeMs\n    this.#nlink = nlink\n    this.#rdev = rdev\n    this.#size = size\n    this.#uid = uid\n    const ifmt = entToType(st)\n    // retain any other flags, but set the ifmt\n    this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED\n    if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {\n      this.#type |= ENOTDIR\n    }\n  }\n\n  #onReaddirCB: ((\n    er: NodeJS.ErrnoException | null,\n    entries: Path[]\n  ) => any)[] = []\n  #readdirCBInFlight: boolean = false\n  #callOnReaddirCB(children: Path[]) {\n    this.#readdirCBInFlight = false\n    const cbs = this.#onReaddirCB.slice()\n    this.#onReaddirCB.length = 0\n    cbs.forEach(cb => cb(null, children))\n  }\n\n  /**\n   * Standard node-style callback interface to get list of directory entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * @param cb The callback called with (er, entries).  Note that the `er`\n   * param is somewhat extraneous, as all readdir() errors are handled and\n   * simply result in an empty set of entries being returned.\n   * @param allowZalgo Boolean indicating that immediately known results should\n   * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release\n   * zalgo at your peril, the dark pony lord is devious and unforgiving.\n   */\n  readdirCB(\n    cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any,\n    allowZalgo: boolean = false\n  ): void {\n    if (!this.canReaddir()) {\n      if (allowZalgo) cb(null, [])\n      else queueMicrotask(() => cb(null, []))\n      return\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      const c = children.slice(0, children.provisional)\n      if (allowZalgo) cb(null, c)\n      else queueMicrotask(() => cb(null, c))\n      return\n    }\n\n    // don't have to worry about zalgo at this point.\n    this.#onReaddirCB.push(cb)\n    if (this.#readdirCBInFlight) {\n      return\n    }\n    this.#readdirCBInFlight = true\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {\n      if (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      } else {\n        // if we didn't get an error, we always get entries.\n        //@ts-ignore\n        for (const e of entries) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      }\n      this.#callOnReaddirCB(children.slice(0, children.provisional))\n      return\n    })\n  }\n\n  #asyncReaddirInFlight?: Promise\n\n  /**\n   * Return an array of known child entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async readdir(): Promise {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    if (this.#asyncReaddirInFlight) {\n      await this.#asyncReaddirInFlight\n    } else {\n      /* c8 ignore start */\n      let resolve: () => void = () => {}\n      /* c8 ignore stop */\n      this.#asyncReaddirInFlight = new Promise(\n        res => (resolve = res)\n      )\n      try {\n        for (const e of await this.#fs.promises.readdir(fullpath, {\n          withFileTypes: true,\n        })) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      } catch (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      }\n      this.#asyncReaddirInFlight = undefined\n      resolve()\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * synchronous {@link PathBase.readdir}\n   */\n  readdirSync(): PathBase[] {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    try {\n      for (const e of this.#fs.readdirSync(fullpath, {\n        withFileTypes: true,\n      })) {\n        this.#readdirAddChild(e, children)\n      }\n      this.#readdirSuccess(children)\n    } catch (er) {\n      this.#readdirFail((er as NodeJS.ErrnoException).code)\n      children.provisional = 0\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  canReaddir() {\n    if (this.#type & ENOCHILD) return false\n    const ifmt = IFMT & this.#type\n    // we always set ENOTDIR when setting IFMT, so should be impossible\n    /* c8 ignore start */\n    if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {\n      return false\n    }\n    /* c8 ignore stop */\n    return true\n  }\n\n  shouldWalk(\n    dirs: Set,\n    walkFilter?: (e: PathBase) => boolean\n  ): boolean {\n    return (\n      (this.#type & IFDIR) === IFDIR &&\n      !(this.#type & ENOCHILD) &&\n      !dirs.has(this) &&\n      (!walkFilter || walkFilter(this))\n    )\n  }\n\n  /**\n   * Return the Path object corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   * On success, returns a Path object.\n   */\n  async realpath(): Promise {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = await this.#fs.promises.realpath(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch (_) {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Synchronous {@link realpath}\n   */\n  realpathSync(): PathBase | undefined {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = this.#fs.realpathSync(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch (_) {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Internal method to mark this Path object as the scurry cwd,\n   * called by {@link PathScurry#chdir}\n   *\n   * @internal\n   */\n  [setAsCwd](oldCwd: PathBase): void {\n    if (oldCwd === this) return\n\n    const changed = new Set([])\n    let rp = []\n    let p: PathBase = this\n    while (p && p.parent) {\n      changed.add(p)\n      p.#relative = rp.join(this.sep)\n      p.#relativePosix = rp.join('/')\n      p = p.parent\n      rp.push('..')\n    }\n    // now un-memoize parents of old cwd\n    p = oldCwd\n    while (p && p.parent && !changed.has(p)) {\n      p.#relative = undefined\n      p.#relativePosix = undefined\n      p = p.parent\n    }\n  }\n}\n\n/**\n * Path class used on win32 systems\n *\n * Uses `'\\\\'` as the path separator for returned paths, either `'\\\\'` or `'/'`\n * as the path separator for parsing paths.\n */\nexport class PathWin32 extends PathBase {\n  /**\n   * Separator for generating path strings.\n   */\n  sep: '\\\\' = '\\\\'\n  /**\n   * Separator for parsing path strings.\n   */\n  splitSep: RegExp = eitherSep\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathWin32(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts\n    )\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return win32.parse(path).root\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(rootPath: string): PathBase {\n    rootPath = uncToDrive(rootPath.toUpperCase())\n    if (rootPath === this.root.name) {\n      return this.root\n    }\n    // ok, not that one, check if it matches another we know about\n    for (const [compare, root] of Object.entries(this.roots)) {\n      if (this.sameRoot(rootPath, compare)) {\n        return (this.roots[rootPath] = root)\n      }\n    }\n    // otherwise, have to create a new one.\n    return (this.roots[rootPath] = new PathScurryWin32(\n      rootPath,\n      this\n    ).root)\n  }\n\n  /**\n   * @internal\n   */\n  sameRoot(rootPath: string, compare: string = this.root.name): boolean {\n    // windows can (rarely) have case-sensitive filesystem, but\n    // UNC and drive letters are always case-insensitive, and canonically\n    // represented uppercase.\n    rootPath = rootPath\n      .toUpperCase()\n      .replace(/\\//g, '\\\\')\n      .replace(uncDriveRegexp, '$1\\\\')\n    return rootPath === compare\n  }\n}\n\n/**\n * Path class used on all posix systems.\n *\n * Uses `'/'` as the path separator.\n */\nexport class PathPosix extends PathBase {\n  /**\n   * separator for parsing path strings\n   */\n  splitSep: '/' = '/'\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return path.startsWith('/') ? '/' : ''\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(_rootPath: string): PathBase {\n    return this.root\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathPosix(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts\n    )\n  }\n}\n\n/**\n * Options that may be provided to the PathScurry constructor\n */\nexport interface PathScurryOpts {\n  /**\n   * perform case-insensitive path matching. Default based on platform\n   * subclass.\n   */\n  nocase?: boolean\n  /**\n   * Number of Path entries to keep in the cache of Path child references.\n   *\n   * Setting this higher than 65536 will dramatically increase the data\n   * consumption and construction time overhead of each PathScurry.\n   *\n   * Setting this value to 256 or lower will significantly reduce the data\n   * consumption and construction time overhead, but may also reduce resolve()\n   * and readdir() performance on large filesystems.\n   *\n   * Default `16384`.\n   */\n  childrenCacheSize?: number\n  /**\n   * An object that overrides the built-in functions from the fs and\n   * fs/promises modules.\n   *\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * The base class for all PathScurry classes, providing the interface for path\n * resolution and filesystem operations.\n *\n * Typically, you should *not* instantiate this class directly, but rather one\n * of the platform-specific classes, or the exported {@link PathScurry} which\n * defaults to the current platform.\n */\nexport abstract class PathScurryBase {\n  /**\n   * The root Path entry for the current working directory of this Scurry\n   */\n  root: PathBase\n  /**\n   * The string path for the root of this Scurry's current working directory\n   */\n  rootPath: string\n  /**\n   * A collection of all roots encountered, referenced by rootPath\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * The Path entry corresponding to this PathScurry's current working directory.\n   */\n  cwd: PathBase\n  #resolveCache: ResolveCache\n  #resolvePosixCache: ResolveCache\n  #children: ChildrenCache\n  /**\n   * Perform path comparisons case-insensitively.\n   *\n   * Defaults true on Darwin and Windows systems, false elsewhere.\n   */\n  nocase: boolean\n\n  /**\n   * The path separator used for parsing paths\n   *\n   * `'/'` on Posix systems, either `'/'` or `'\\\\'` on Windows\n   */\n  abstract sep: string | RegExp\n\n  #fs: FSValue\n\n  /**\n   * This class should not be instantiated directly.\n   *\n   * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry\n   *\n   * @internal\n   */\n  constructor(\n    cwd: URL | string = process.cwd(),\n    pathImpl: typeof win32 | typeof posix,\n    sep: string | RegExp,\n    {\n      nocase,\n      childrenCacheSize = 16 * 1024,\n      fs = defaultFS,\n    }: PathScurryOpts = {}\n  ) {\n    this.#fs = fsFromOption(fs)\n    if (cwd instanceof URL || cwd.startsWith('file://')) {\n      cwd = fileURLToPath(cwd)\n    }\n    // resolve and split root, and then add to the store.\n    // this is the only time we call path.resolve()\n    const cwdPath = pathImpl.resolve(cwd)\n    this.roots = Object.create(null)\n    this.rootPath = this.parseRootPath(cwdPath)\n    this.#resolveCache = new ResolveCache()\n    this.#resolvePosixCache = new ResolveCache()\n    this.#children = new ChildrenCache(childrenCacheSize)\n\n    const split = cwdPath.substring(this.rootPath.length).split(sep)\n    // resolve('/') leaves '', splits to [''], we don't want that.\n    if (split.length === 1 && !split[0]) {\n      split.pop()\n    }\n    /* c8 ignore start */\n    if (nocase === undefined) {\n      throw new TypeError(\n        'must provide nocase setting to PathScurryBase ctor'\n      )\n    }\n    /* c8 ignore stop */\n    this.nocase = nocase\n    this.root = this.newRoot(this.#fs)\n    this.roots[this.rootPath] = this.root\n    let prev: PathBase = this.root\n    let len = split.length - 1\n    const joinSep = pathImpl.sep\n    let abs = this.rootPath\n    let sawFirst = false\n    for (const part of split) {\n      const l = len--\n      prev = prev.child(part, {\n        relative: new Array(l).fill('..').join(joinSep),\n        relativePosix: new Array(l).fill('..').join('/'),\n        fullpath: (abs += (sawFirst ? '' : joinSep) + part),\n      })\n      sawFirst = true\n    }\n    this.cwd = prev\n  }\n\n  /**\n   * Get the depth of a provided path, string, or the cwd\n   */\n  depth(path: Path | string = this.cwd): number {\n    if (typeof path === 'string') {\n      path = this.cwd.resolve(path)\n    }\n    return path.depth()\n  }\n\n  /**\n   * Parse the root portion of a path string\n   *\n   * @internal\n   */\n  abstract parseRootPath(dir: string): string\n  /**\n   * create a new Path to use as root during construction.\n   *\n   * @internal\n   */\n  abstract newRoot(fs: FSValue): PathBase\n  /**\n   * Determine whether a given path string is absolute\n   */\n  abstract isAbsolute(p: string): boolean\n\n  /**\n   * Return the cache of child entries.  Exposed so subclasses can create\n   * child Path objects in a platform-specific way.\n   *\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolve(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolveCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpath()\n    this.#resolveCache.set(r, result)\n    return result\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string, returning\n   * the posix path.  Identical to .resolve() on posix systems, but on\n   * windows will return a forward-slash separated UNC path.\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolvePosix(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolvePosixCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpathPosix()\n    this.#resolvePosixCache.set(r, result)\n    return result\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or entry\n   */\n  relative(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relative()\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or\n   * entry, using / as the path delimiter, even on Windows.\n   */\n  relativePosix(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relativePosix()\n  }\n\n  /**\n   * Return the basename for the provided string or Path object\n   */\n  basename(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.name\n  }\n\n  /**\n   * Return the dirname for the provided string or Path object\n   */\n  dirname(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return (entry.parent || entry).fullpath()\n  }\n\n  /**\n   * Return an array of known child entries.\n   *\n   * First argument may be either a string, or a Path object.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set\n   * `{ withFileTypes: false }` to return strings.\n   */\n\n  readdir(): Promise\n  readdir(opts: { withFileTypes: true }): Promise\n  readdir(opts: { withFileTypes: false }): Promise\n  readdir(opts: { withFileTypes: boolean }): Promise\n  readdir(entry: PathBase | string): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: true }\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: false }\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean }\n  ): Promise\n  async readdir(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    }\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else {\n      const p = await entry.readdir()\n      return withFileTypes ? p : p.map(e => e.name)\n    }\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readdir}\n   */\n  readdirSync(): PathBase[]\n  readdirSync(opts: { withFileTypes: true }): PathBase[]\n  readdirSync(opts: { withFileTypes: false }): string[]\n  readdirSync(opts: { withFileTypes: boolean }): PathBase[] | string[]\n  readdirSync(entry: PathBase | string): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: true }\n  ): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: false }\n  ): string[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean }\n  ): PathBase[] | string[]\n  readdirSync(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    }\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes = true } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else if (withFileTypes) {\n      return entry.readdirSync()\n    } else {\n      return entry.readdirSync().map(e => e.name)\n    }\n  }\n\n  /**\n   * Call lstat() on the string or Path object, and update all known\n   * information that can be determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(\n    entry: string | PathBase = this.cwd\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstat()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.lstat}\n   */\n  lstatSync(entry: string | PathBase = this.cwd): PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstatSync()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to the target of a\n   * symbolic link.\n   *\n   * If the path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  readlink(): Promise\n  readlink(opt: { withFileTypes: false }): Promise\n  readlink(opt: { withFileTypes: true }): Promise\n  readlink(opt: {\n    withFileTypes: boolean\n  }): Promise\n  readlink(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false }\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: true }\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean }\n  ): Promise\n  async readlink(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    }\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.readlink()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readlink}\n   */\n  readlinkSync(): string | undefined\n  readlinkSync(opt: { withFileTypes: false }): string | undefined\n  readlinkSync(opt: { withFileTypes: true }): PathBase | undefined\n  readlinkSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false }\n  ): string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true }\n  ): PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean }\n  ): string | PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    }\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.readlinkSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  realpath(): Promise\n  realpath(opt: { withFileTypes: false }): Promise\n  realpath(opt: { withFileTypes: true }): Promise\n  realpath(opt: {\n    withFileTypes: boolean\n  }): Promise\n  realpath(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false }\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: true }\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean }\n  ): Promise\n  async realpath(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    }\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.realpath()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  realpathSync(): string | undefined\n  realpathSync(opt: { withFileTypes: false }): string | undefined\n  realpathSync(opt: { withFileTypes: true }): PathBase | undefined\n  realpathSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false }\n  ): string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true }\n  ): PathBase | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean }\n  ): string | PathBase | undefined\n  realpathSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    }\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.realpathSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Asynchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walk(): Promise\n  walk(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): Promise\n  walk(opts: WalkOptionsWithFileTypesFalse): Promise\n  walk(opts: WalkOptions): Promise\n  walk(entry: string | PathBase): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptions\n  ): Promise\n  async walk(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {}\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const walk = (\n      dir: PathBase,\n      cb: (er?: NodeJS.ErrnoException) => void\n    ) => {\n      dirs.add(dir)\n      dir.readdirCB((er, entries) => {\n        /* c8 ignore start */\n        if (er) {\n          return cb(er)\n        }\n        /* c8 ignore stop */\n        let len = entries.length\n        if (!len) return cb()\n        const next = () => {\n          if (--len === 0) {\n            cb()\n          }\n        }\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            results.push(withFileTypes ? e : e.fullpath())\n          }\n          if (follow && e.isSymbolicLink()) {\n            e.realpath()\n              .then(r => (r?.isUnknown() ? r.lstat() : r))\n              .then(r =>\n                r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next()\n              )\n          } else {\n            if (e.shouldWalk(dirs, walkFilter)) {\n              walk(e, next)\n            } else {\n              next()\n            }\n          }\n        }\n      }, true) // zalgooooooo\n    }\n\n    const start = entry\n    return new Promise((res, rej) => {\n      walk(start, er => {\n        /* c8 ignore start */\n        if (er) return rej(er)\n        /* c8 ignore stop */\n        res(results as PathBase[] | string[])\n      })\n    })\n  }\n\n  /**\n   * Synchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walkSync(): PathBase[]\n  walkSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): PathBase[]\n  walkSync(opts: WalkOptionsWithFileTypesFalse): string[]\n  walkSync(opts: WalkOptions): string[] | PathBase[]\n  walkSync(entry: string | PathBase): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue\n  ): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse\n  ): string[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptions\n  ): PathBase[] | string[]\n  walkSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {}\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          results.push(withFileTypes ? e : e.fullpath())\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n    return results as string[] | PathBase[]\n  }\n\n  /**\n   * Support for `for await`\n   *\n   * Alias for {@link PathScurryBase.iterate}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n\n  /**\n   * Async generator form of {@link PathScurryBase.walk}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking, especially if most/all of the directory tree has been previously\n   * walked.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  iterate(): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesFalse\n  ): AsyncGenerator\n  iterate(opts: WalkOptions): AsyncGenerator\n  iterate(entry: string | PathBase): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptions\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    options: WalkOptions = {}\n  ): AsyncGenerator {\n    // iterating async over the stream is significantly more performant,\n    // especially in the warm-cache scenario, because it buffers up directory\n    // entries in the background instead of waiting for a yield for each one.\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      options = entry\n      entry = this.cwd\n    }\n    return this.stream(entry, options)[Symbol.asyncIterator]()\n  }\n\n  /**\n   * Iterating over a PathScurry performs a synchronous walk.\n   *\n   * Alias for {@link PathScurryBase.iterateSync}\n   */\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  iterateSync(): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesFalse\n  ): Generator\n  iterateSync(opts: WalkOptions): Generator\n  iterateSync(entry: string | PathBase): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptions\n  ): Generator\n  *iterateSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {}\n  ): Generator {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    if (!filter || filter(entry)) {\n      yield withFileTypes ? entry : entry.fullpath()\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          yield withFileTypes ? e : e.fullpath()\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n  }\n\n  /**\n   * Stream form of {@link PathScurryBase.walk}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   */\n  stream(): Minipass\n  stream(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): Minipass\n  stream(opts: WalkOptionsWithFileTypesFalse): Minipass\n  stream(opts: WalkOptions): Minipass\n  stream(entry: string | PathBase): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptions\n  ): Minipass | Minipass\n  stream(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {}\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n\n        processing++\n        dirs.add(dir)\n\n        const onReaddir = (\n          er: null | NodeJS.ErrnoException,\n          entries: PathBase[],\n          didRealpaths: boolean = false\n        ) => {\n          /* c8 ignore start */\n          if (er) return results.emit('error', er)\n          /* c8 ignore stop */\n          if (follow && !didRealpaths) {\n            const promises: Promise[] = []\n            for (const e of entries) {\n              if (e.isSymbolicLink()) {\n                promises.push(\n                  e\n                    .realpath()\n                    .then((r: PathBase | undefined) =>\n                      r?.isUnknown() ? r.lstat() : r\n                    )\n                )\n              }\n            }\n            if (promises.length) {\n              Promise.all(promises).then(() =>\n                onReaddir(null, entries, true)\n              )\n              return\n            }\n          }\n\n          for (const e of entries) {\n            if (e && (!filter || filter(e))) {\n              if (!results.write(withFileTypes ? e : e.fullpath())) {\n                paused = true\n              }\n            }\n          }\n\n          processing--\n          for (const e of entries) {\n            const r = e.realpathCached() || e\n            if (r.shouldWalk(dirs, walkFilter)) {\n              queue.push(r)\n            }\n          }\n          if (paused && !results.flowing) {\n            results.once('drain', process)\n          } else if (!sync) {\n            process()\n          }\n        }\n\n        // zalgo containment\n        let sync = true\n        dir.readdirCB(onReaddir, true)\n        sync = false\n      }\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  /**\n   * Synchronous form of {@link PathScurryBase.stream}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   *\n   * Will complete the walk in a single tick if the stream is consumed fully.\n   * Otherwise, will pause as needed for stream backpressure.\n   */\n  streamSync(): Minipass\n  streamSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): Minipass\n  streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass\n  streamSync(opts: WalkOptions): Minipass\n  streamSync(entry: string | PathBase): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptions\n  ): Minipass | Minipass\n  streamSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {}\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    const dirs = new Set()\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n        processing++\n        dirs.add(dir)\n\n        const entries = dir.readdirSync()\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            if (!results.write(withFileTypes ? e : e.fullpath())) {\n              paused = true\n            }\n          }\n        }\n        processing--\n        for (const e of entries) {\n          let r: PathBase | undefined = e\n          if (e.isSymbolicLink()) {\n            if (!(follow && (r = e.realpathSync()))) continue\n            if (r.isUnknown()) r.lstatSync()\n          }\n          if (r.shouldWalk(dirs, walkFilter)) {\n            queue.push(r)\n          }\n        }\n      }\n      if (paused && !results.flowing) results.once('drain', process)\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  chdir(path: string | Path = this.cwd) {\n    const oldCwd = this.cwd\n    this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path\n    this.cwd[setAsCwd](oldCwd)\n  }\n}\n\n/**\n * Options provided to all walk methods.\n */\nexport interface WalkOptions {\n  /**\n   * Return results as {@link PathBase} objects rather than strings.\n   * When set to false, results are fully resolved paths, as returned by\n   * {@link PathBase.fullpath}.\n   * @default true\n   */\n  withFileTypes?: boolean\n\n  /**\n   *  Attempt to read directory entries from symbolic links. Otherwise, only\n   *  actual directories are traversed. Regardless of this setting, a given\n   *  target path will only ever be walked once, meaning that a symbolic link\n   *  to a previously traversed directory will never be followed.\n   *\n   *  Setting this imposes a slight performance penalty, because `readlink`\n   *  must be called on all symbolic links encountered, in order to avoid\n   *  infinite cycles.\n   * @default false\n   */\n  follow?: boolean\n\n  /**\n   * Only return entries where the provided function returns true.\n   *\n   * This will not prevent directories from being traversed, even if they do\n   * not pass the filter, though it will prevent directories themselves from\n   * being included in the result set.  See {@link walkFilter}\n   *\n   * Asynchronous functions are not supported here.\n   *\n   * By default, if no filter is provided, all entries and traversed\n   * directories are included.\n   */\n  filter?: (entry: PathBase) => boolean\n\n  /**\n   * Only traverse directories (and in the case of {@link follow} being set to\n   * true, symbolic links to directories) if the provided function returns\n   * true.\n   *\n   * This will not prevent directories from being included in the result set,\n   * even if they do not pass the supplied filter function.  See {@link filter}\n   * to do that.\n   *\n   * Asynchronous functions are not supported here.\n   */\n  walkFilter?: (entry: PathBase) => boolean\n}\n\nexport type WalkOptionsWithFileTypesUnset = WalkOptions & {\n  withFileTypes?: undefined\n}\nexport type WalkOptionsWithFileTypesTrue = WalkOptions & {\n  withFileTypes: true\n}\nexport type WalkOptionsWithFileTypesFalse = WalkOptions & {\n  withFileTypes: false\n}\n\n/**\n * Windows implementation of {@link PathScurryBase}\n *\n * Defaults to case insensitve, uses `'\\\\'` to generate path strings.  Uses\n * {@link PathWin32} for Path objects.\n */\nexport class PathScurryWin32 extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '\\\\' = '\\\\'\n\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {}\n  ) {\n    const { nocase = true } = opts\n    super(cwd, win32, '\\\\', { ...opts, nocase })\n    this.nocase = nocase\n    for (let p: PathBase | undefined = this.cwd; p; p = p.parent) {\n      p.nocase = this.nocase\n    }\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(dir: string): string {\n    // if the path starts with a single separator, it's not a UNC, and we'll\n    // just get separator as the root, and driveFromUNC will return \\\n    // In that case, mount \\ on the root from the cwd.\n    return win32.parse(dir).root.toUpperCase()\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathWin32(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs }\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return (\n      p.startsWith('/') || p.startsWith('\\\\') || /^[a-z]:(\\/|\\\\)/i.test(p)\n    )\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for all posix systems other than Darwin.\n *\n * Defaults to case-sensitive matching, uses `'/'` to generate path strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryPosix extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {}\n  ) {\n    const { nocase = false } = opts\n    super(cwd, posix, '/', { ...opts, nocase })\n    this.nocase = nocase\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(_dir: string): string {\n    return '/'\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathPosix(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs }\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return p.startsWith('/')\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for Darwin (macOS) systems.\n *\n * Defaults to case-insensitive matching, uses `'/'` for generating path\n * strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryDarwin extends PathScurryPosix {\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {}\n  ) {\n    const { nocase = true } = opts\n    super(cwd, { ...opts, nocase })\n  }\n}\n\n/**\n * Default {@link PathBase} implementation for the current platform.\n *\n * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.\n */\nexport const Path = process.platform === 'win32' ? PathWin32 : PathPosix\nexport type Path = PathBase | InstanceType\n\n/**\n * Default {@link PathScurryBase} implementation for the current platform.\n *\n * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on\n * Darwin (macOS) systems, {@link PathScurryPosix} on all others.\n */\nexport const PathScurry:\n  | typeof PathScurryWin32\n  | typeof PathScurryDarwin\n  | typeof PathScurryPosix =\n  process.platform === 'win32'\n    ? PathScurryWin32\n    : process.platform === 'darwin'\n    ? PathScurryDarwin\n    : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType\n","const proc =\n  typeof process === 'object' && process\n    ? process\n    : {\n        stdout: null,\n        stderr: null,\n      }\nimport { EventEmitter } from 'events'\nimport Stream from 'stream'\nimport { StringDecoder } from 'string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n  s: any\n): s is Minipass.Readable | Minipass.Writable =>\n  !!s &&\n  typeof s === 'object' &&\n  (s instanceof Minipass ||\n    s instanceof Stream ||\n    isReadable(s) ||\n    isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n  !!s &&\n  typeof s === 'object' &&\n  s instanceof EventEmitter &&\n  typeof (s as Minipass.Readable).pipe === 'function' &&\n  // node core Writable streams have a pipe() method, but it throws\n  (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n  !!s &&\n  typeof s === 'object' &&\n  s instanceof EventEmitter &&\n  typeof (s as Minipass.Writable).write === 'function' &&\n  typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n  ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n  b instanceof ArrayBuffer ||\n  (!!b &&\n    typeof b === 'object' &&\n    b.constructor &&\n    b.constructor.name === 'ArrayBuffer' &&\n    b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n  !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n  /**\n   * end the destination stream when the source stream ends\n   */\n  end?: boolean\n  /**\n   * proxy errors from the source stream to the destination stream\n   */\n  proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe {\n  src: Minipass\n  dest: Minipass\n  opts: PipeOptions\n  ondrain: () => any\n  constructor(\n    src: Minipass,\n    dest: Minipass.Writable,\n    opts: PipeOptions\n  ) {\n    this.src = src\n    this.dest = dest as Minipass\n    this.opts = opts\n    this.ondrain = () => src[RESUME]()\n    this.dest.on('drain', this.ondrain)\n  }\n  unpipe() {\n    this.dest.removeListener('drain', this.ondrain)\n  }\n  // only here for the prototype\n  /* c8 ignore start */\n  proxyErrors(_er: any) {}\n  /* c8 ignore stop */\n  end() {\n    this.unpipe()\n    if (this.opts.end) this.dest.end()\n  }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors extends Pipe {\n  unpipe() {\n    this.src.removeListener('error', this.proxyErrors)\n    super.unpipe()\n  }\n  constructor(\n    src: Minipass,\n    dest: Minipass.Writable,\n    opts: PipeOptions\n  ) {\n    super(src, dest, opts)\n    this.proxyErrors = er => dest.emit('error', er)\n    src.on('error', this.proxyErrors)\n  }\n}\n\nexport namespace Minipass {\n  /**\n   * Encoding used to create a stream that outputs strings rather than\n   * Buffer objects.\n   */\n  export type Encoding = BufferEncoding | 'buffer' | null\n\n  /**\n   * Any stream that Minipass can pipe into\n   */\n  export type Writable =\n    | Minipass\n    | NodeJS.WriteStream\n    | (NodeJS.WriteStream & { fd: number })\n    | (EventEmitter & {\n        end(): any\n        write(chunk: any, ...args: any[]): any\n      })\n\n  /**\n   * Any stream that can be read from\n   */\n  export type Readable =\n    | Minipass\n    | NodeJS.ReadStream\n    | (NodeJS.ReadStream & { fd: number })\n    | (EventEmitter & {\n        pause(): any\n        resume(): any\n        pipe(...destArgs: any[]): any\n      })\n\n  /**\n   * Utility type that can be iterated sync or async\n   */\n  export type DualIterable = Iterable & AsyncIterable\n\n  type EventArguments = Record\n\n  /**\n   * The listing of events that a Minipass class can emit.\n   * Extend this when extending the Minipass class, and pass as\n   * the third template argument.  The key is the name of the event,\n   * and the value is the argument list.\n   *\n   * Any undeclared events will still be allowed, but the handler will get\n   * arguments as `unknown[]`.\n   */\n  export interface Events\n    extends EventArguments {\n    readable: []\n    data: [chunk: RType]\n    error: [er: unknown]\n    abort: [reason: unknown]\n    drain: []\n    resume: []\n    end: []\n    finish: []\n    prefinish: []\n    close: []\n    [DESTROYED]: [er?: unknown]\n    [ERROR]: [er: unknown]\n  }\n\n  /**\n   * String or buffer-like data that can be joined and sliced\n   */\n  export type ContiguousData =\n    | Buffer\n    | ArrayBufferLike\n    | ArrayBufferView\n    | string\n  export type BufferOrString = Buffer | string\n\n  /**\n   * Options passed to the Minipass constructor.\n   */\n  export type SharedOptions = {\n    /**\n     * Defer all data emission and other events until the end of the\n     * current tick, similar to Node core streams\n     */\n    async?: boolean\n    /**\n     * A signal which will abort the stream\n     */\n    signal?: AbortSignal\n    /**\n     * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n     * emit Buffer objects rather than strings.\n     *\n     * Conflicts with `objectMode`\n     */\n    encoding?: BufferEncoding | null | 'buffer'\n    /**\n     * Output data exactly as it was written, supporting non-buffer/string\n     * data (such as arbitrary objects, falsey values, etc.)\n     *\n     * Conflicts with `encoding`\n     */\n    objectMode?: boolean\n  }\n\n  /**\n   * Options for a string encoded output\n   */\n  export type EncodingOptions = SharedOptions & {\n    encoding: BufferEncoding\n    objectMode?: false\n  }\n\n  /**\n   * Options for contiguous data buffer output\n   */\n  export type BufferOptions = SharedOptions & {\n    encoding?: null | 'buffer'\n    objectMode?: false\n  }\n\n  /**\n   * Options for objectMode arbitrary output\n   */\n  export type ObjectModeOptions = SharedOptions & {\n    objectMode: true\n    encoding?: null\n  }\n\n  /**\n   * Utility type to determine allowed options based on read type\n   */\n  export type Options = T extends string\n    ? EncodingOptions | ObjectModeOptions\n    : T extends Buffer\n    ? BufferOptions | ObjectModeOptions\n    : SharedOptions\n}\n\nconst isObjectModeOptions = (\n  o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n  o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n  !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n    RType extends unknown = Buffer,\n    WType extends unknown = RType extends Minipass.BufferOrString\n      ? Minipass.ContiguousData\n      : RType,\n    Events extends Minipass.Events = Minipass.Events\n  >\n  extends EventEmitter\n  implements Minipass.DualIterable\n{\n  [FLOWING]: boolean = false;\n  [PAUSED]: boolean = false;\n  [PIPES]: Pipe[] = [];\n  [BUFFER]: RType[] = [];\n  [OBJECTMODE]: boolean;\n  [ENCODING]: BufferEncoding | null;\n  [ASYNC]: boolean;\n  [DECODER]: SD | null;\n  [EOF]: boolean = false;\n  [EMITTED_END]: boolean = false;\n  [EMITTING_END]: boolean = false;\n  [CLOSED]: boolean = false;\n  [EMITTED_ERROR]: unknown = null;\n  [BUFFERLENGTH]: number = 0;\n  [DESTROYED]: boolean = false;\n  [SIGNAL]?: AbortSignal;\n  [ABORTED]: boolean = false;\n  [DATALISTENERS]: number = 0;\n  [DISCARDED]: boolean = false\n\n  /**\n   * true if the stream can be written\n   */\n  writable: boolean = true\n  /**\n   * true if the stream can be read\n   */\n  readable: boolean = true\n\n  /**\n   * If `RType` is Buffer, then options do not need to be provided.\n   * Otherwise, an options object must be provided to specify either\n   * {@link Minipass.SharedOptions.objectMode} or\n   * {@link Minipass.SharedOptions.encoding}, as appropriate.\n   */\n  constructor(\n    ...args: RType extends Buffer\n      ? [] | [Minipass.Options]\n      : [Minipass.Options]\n  ) {\n    const options: Minipass.Options = (args[0] ||\n      {}) as Minipass.Options\n    super()\n    if (options.objectMode && typeof options.encoding === 'string') {\n      throw new TypeError(\n        'Encoding and objectMode may not be used together'\n      )\n    }\n    if (isObjectModeOptions(options)) {\n      this[OBJECTMODE] = true\n      this[ENCODING] = null\n    } else if (isEncodingOptions(options)) {\n      this[ENCODING] = options.encoding\n      this[OBJECTMODE] = false\n    } else {\n      this[OBJECTMODE] = false\n      this[ENCODING] = null\n    }\n    this[ASYNC] = !!options.async\n    this[DECODER] = this[ENCODING]\n      ? (new StringDecoder(this[ENCODING]) as SD)\n      : null\n\n    //@ts-ignore - private option for debugging and testing\n    if (options && options.debugExposeBuffer === true) {\n      Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n    }\n    //@ts-ignore - private option for debugging and testing\n    if (options && options.debugExposePipes === true) {\n      Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n    }\n\n    const { signal } = options\n    if (signal) {\n      this[SIGNAL] = signal\n      if (signal.aborted) {\n        this[ABORT]()\n      } else {\n        signal.addEventListener('abort', () => this[ABORT]())\n      }\n    }\n  }\n\n  /**\n   * The amount of data stored in the buffer waiting to be read.\n   *\n   * For Buffer strings, this will be the total byte length.\n   * For string encoding streams, this will be the string character length,\n   * according to JavaScript's `string.length` logic.\n   * For objectMode streams, this is a count of the items waiting to be\n   * emitted.\n   */\n  get bufferLength() {\n    return this[BUFFERLENGTH]\n  }\n\n  /**\n   * The `BufferEncoding` currently in use, or `null`\n   */\n  get encoding() {\n    return this[ENCODING]\n  }\n\n  /**\n   * @deprecated - This is a read only property\n   */\n  set encoding(_enc) {\n    throw new Error('Encoding must be set at instantiation time')\n  }\n\n  /**\n   * @deprecated - Encoding may only be set at instantiation time\n   */\n  setEncoding(_enc: Minipass.Encoding) {\n    throw new Error('Encoding must be set at instantiation time')\n  }\n\n  /**\n   * True if this is an objectMode stream\n   */\n  get objectMode() {\n    return this[OBJECTMODE]\n  }\n\n  /**\n   * @deprecated - This is a read-only property\n   */\n  set objectMode(_om) {\n    throw new Error('objectMode must be set at instantiation time')\n  }\n\n  /**\n   * true if this is an async stream\n   */\n  get ['async'](): boolean {\n    return this[ASYNC]\n  }\n  /**\n   * Set to true to make this stream async.\n   *\n   * Once set, it cannot be unset, as this would potentially cause incorrect\n   * behavior.  Ie, a sync stream can be made async, but an async stream\n   * cannot be safely made sync.\n   */\n  set ['async'](a: boolean) {\n    this[ASYNC] = this[ASYNC] || !!a\n  }\n\n  // drop everything and get out of the flow completely\n  [ABORT]() {\n    this[ABORTED] = true\n    this.emit('abort', this[SIGNAL]?.reason)\n    this.destroy(this[SIGNAL]?.reason)\n  }\n\n  /**\n   * True if the stream has been aborted.\n   */\n  get aborted() {\n    return this[ABORTED]\n  }\n  /**\n   * No-op setter. Stream aborted status is set via the AbortSignal provided\n   * in the constructor options.\n   */\n  set aborted(_) {}\n\n  /**\n   * Write data into the stream\n   *\n   * If the chunk written is a string, and encoding is not specified, then\n   * `utf8` will be assumed. If the stream encoding matches the encoding of\n   * a written string, and the state of the string decoder allows it, then\n   * the string will be passed through to either the output or the internal\n   * buffer without any processing. Otherwise, it will be turned into a\n   * Buffer object for processing into the desired encoding.\n   *\n   * If provided, `cb` function is called immediately before return for\n   * sync streams, or on next tick for async streams, because for this\n   * base class, a chunk is considered \"processed\" once it is accepted\n   * and either emitted or buffered. That is, the callback does not indicate\n   * that the chunk has been eventually emitted, though of course child\n   * classes can override this function to do whatever processing is required\n   * and call `super.write(...)` only once processing is completed.\n   */\n  write(chunk: WType, cb?: () => void): boolean\n  write(\n    chunk: WType,\n    encoding?: Minipass.Encoding,\n    cb?: () => void\n  ): boolean\n  write(\n    chunk: WType,\n    encoding?: Minipass.Encoding | (() => void),\n    cb?: () => void\n  ): boolean {\n    if (this[ABORTED]) return false\n    if (this[EOF]) throw new Error('write after end')\n\n    if (this[DESTROYED]) {\n      this.emit(\n        'error',\n        Object.assign(\n          new Error('Cannot call write after a stream was destroyed'),\n          { code: 'ERR_STREAM_DESTROYED' }\n        )\n      )\n      return true\n    }\n\n    if (typeof encoding === 'function') {\n      cb = encoding\n      encoding = 'utf8'\n    }\n\n    if (!encoding) encoding = 'utf8'\n\n    const fn = this[ASYNC] ? defer : nodefer\n\n    // convert array buffers and typed array views into buffers\n    // at some point in the future, we may want to do the opposite!\n    // leave strings and buffers as-is\n    // anything is only allowed if in object mode, so throw\n    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n      if (isArrayBufferView(chunk)) {\n        //@ts-ignore - sinful unsafe type changing\n        chunk = Buffer.from(\n          chunk.buffer,\n          chunk.byteOffset,\n          chunk.byteLength\n        )\n      } else if (isArrayBufferLike(chunk)) {\n        //@ts-ignore - sinful unsafe type changing\n        chunk = Buffer.from(chunk)\n      } else if (typeof chunk !== 'string') {\n        throw new Error(\n          'Non-contiguous data written to non-objectMode stream'\n        )\n      }\n    }\n\n    // handle object mode up front, since it's simpler\n    // this yields better performance, fewer checks later.\n    if (this[OBJECTMODE]) {\n      // maybe impossible?\n      /* c8 ignore start */\n      if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n      /* c8 ignore stop */\n\n      if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n      else this[BUFFERPUSH](chunk as unknown as RType)\n\n      if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n      if (cb) fn(cb)\n\n      return this[FLOWING]\n    }\n\n    // at this point the chunk is a buffer or string\n    // don't buffer it up or send it to the decoder\n    if (!(chunk as Minipass.BufferOrString).length) {\n      if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n      if (cb) fn(cb)\n      return this[FLOWING]\n    }\n\n    // fast-path writing strings of same encoding to a stream with\n    // an empty buffer, skipping the buffer/decoder dance\n    if (\n      typeof chunk === 'string' &&\n      // unless it is a string already ready for us to use\n      !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n    ) {\n      //@ts-ignore - sinful unsafe type change\n      chunk = Buffer.from(chunk, encoding)\n    }\n\n    if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n      //@ts-ignore - sinful unsafe type change\n      chunk = this[DECODER].write(chunk)\n    }\n\n    // Note: flushing CAN potentially switch us into not-flowing mode\n    if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n    if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n    else this[BUFFERPUSH](chunk as unknown as RType)\n\n    if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n    if (cb) fn(cb)\n\n    return this[FLOWING]\n  }\n\n  /**\n   * Low-level explicit read method.\n   *\n   * In objectMode, the argument is ignored, and one item is returned if\n   * available.\n   *\n   * `n` is the number of bytes (or in the case of encoding streams,\n   * characters) to consume. If `n` is not provided, then the entire buffer\n   * is returned, or `null` is returned if no data is available.\n   *\n   * If `n` is greater that the amount of data in the internal buffer,\n   * then `null` is returned.\n   */\n  read(n?: number | null): RType | null {\n    if (this[DESTROYED]) return null\n    this[DISCARDED] = false\n\n    if (\n      this[BUFFERLENGTH] === 0 ||\n      n === 0 ||\n      (n && n > this[BUFFERLENGTH])\n    ) {\n      this[MAYBE_EMIT_END]()\n      return null\n    }\n\n    if (this[OBJECTMODE]) n = null\n\n    if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n      // not object mode, so if we have an encoding, then RType is string\n      // otherwise, must be Buffer\n      this[BUFFER] = [\n        (this[ENCODING]\n          ? this[BUFFER].join('')\n          : Buffer.concat(\n              this[BUFFER] as Buffer[],\n              this[BUFFERLENGTH]\n            )) as RType,\n      ]\n    }\n\n    const ret = this[READ](n || null, this[BUFFER][0] as RType)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [READ](n: number | null, chunk: RType) {\n    if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n    else {\n      const c = chunk as Minipass.BufferOrString\n      if (n === c.length || n === null) this[BUFFERSHIFT]()\n      else if (typeof c === 'string') {\n        this[BUFFER][0] = c.slice(n) as RType\n        chunk = c.slice(0, n) as RType\n        this[BUFFERLENGTH] -= n\n      } else {\n        this[BUFFER][0] = c.subarray(n) as RType\n        chunk = c.subarray(0, n) as RType\n        this[BUFFERLENGTH] -= n\n      }\n    }\n\n    this.emit('data', chunk)\n\n    if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n    return chunk\n  }\n\n  /**\n   * End the stream, optionally providing a final write.\n   *\n   * See {@link Minipass#write} for argument descriptions\n   */\n  end(cb?: () => void): this\n  end(chunk: WType, cb?: () => void): this\n  end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n  end(\n    chunk?: WType | (() => void),\n    encoding?: Minipass.Encoding | (() => void),\n    cb?: () => void\n  ) {\n    if (typeof chunk === 'function') {\n      cb = chunk as () => void\n      chunk = undefined\n    }\n    if (typeof encoding === 'function') {\n      cb = encoding\n      encoding = 'utf8'\n    }\n    if (chunk !== undefined) this.write(chunk, encoding)\n    if (cb) this.once('end', cb)\n    this[EOF] = true\n    this.writable = false\n\n    // if we haven't written anything, then go ahead and emit,\n    // even if we're not reading.\n    // we'll re-emit if a new 'end' listener is added anyway.\n    // This makes MP more suitable to write-only use cases.\n    if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n    return this\n  }\n\n  // don't let the internal resume be overwritten\n  [RESUME]() {\n    if (this[DESTROYED]) return\n\n    if (!this[DATALISTENERS] && !this[PIPES].length) {\n      this[DISCARDED] = true\n    }\n    this[PAUSED] = false\n    this[FLOWING] = true\n    this.emit('resume')\n    if (this[BUFFER].length) this[FLUSH]()\n    else if (this[EOF]) this[MAYBE_EMIT_END]()\n    else this.emit('drain')\n  }\n\n  /**\n   * Resume the stream if it is currently in a paused state\n   *\n   * If called when there are no pipe destinations or `data` event listeners,\n   * this will place the stream in a \"discarded\" state, where all data will\n   * be thrown away. The discarded state is removed if a pipe destination or\n   * data handler is added, if pause() is called, or if any synchronous or\n   * asynchronous iteration is started.\n   */\n  resume() {\n    return this[RESUME]()\n  }\n\n  /**\n   * Pause the stream\n   */\n  pause() {\n    this[FLOWING] = false\n    this[PAUSED] = true\n    this[DISCARDED] = false\n  }\n\n  /**\n   * true if the stream has been forcibly destroyed\n   */\n  get destroyed() {\n    return this[DESTROYED]\n  }\n\n  /**\n   * true if the stream is currently in a flowing state, meaning that\n   * any writes will be immediately emitted.\n   */\n  get flowing() {\n    return this[FLOWING]\n  }\n\n  /**\n   * true if the stream is currently in a paused state\n   */\n  get paused() {\n    return this[PAUSED]\n  }\n\n  [BUFFERPUSH](chunk: RType) {\n    if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n    else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n    this[BUFFER].push(chunk)\n  }\n\n  [BUFFERSHIFT](): RType {\n    if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n    else\n      this[BUFFERLENGTH] -= (\n        this[BUFFER][0] as Minipass.BufferOrString\n      ).length\n    return this[BUFFER].shift() as RType\n  }\n\n  [FLUSH](noDrain: boolean = false) {\n    do {} while (\n      this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n      this[BUFFER].length\n    )\n\n    if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n  }\n\n  [FLUSHCHUNK](chunk: RType) {\n    this.emit('data', chunk)\n    return this[FLOWING]\n  }\n\n  /**\n   * Pipe all data emitted by this stream into the destination provided.\n   *\n   * Triggers the flow of data.\n   */\n  pipe(dest: W, opts?: PipeOptions): W {\n    if (this[DESTROYED]) return dest\n    this[DISCARDED] = false\n\n    const ended = this[EMITTED_END]\n    opts = opts || {}\n    if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n    else opts.end = opts.end !== false\n    opts.proxyErrors = !!opts.proxyErrors\n\n    // piping an ended stream ends immediately\n    if (ended) {\n      if (opts.end) dest.end()\n    } else {\n      // \"as\" here just ignores the WType, which pipes don't care about,\n      // since they're only consuming from us, and writing to the dest\n      this[PIPES].push(\n        !opts.proxyErrors\n          ? new Pipe(this as Minipass, dest, opts)\n          : new PipeProxyErrors(this as Minipass, dest, opts)\n      )\n      if (this[ASYNC]) defer(() => this[RESUME]())\n      else this[RESUME]()\n    }\n\n    return dest\n  }\n\n  /**\n   * Fully unhook a piped destination stream.\n   *\n   * If the destination stream was the only consumer of this stream (ie,\n   * there are no other piped destinations or `'data'` event listeners)\n   * then the flow of data will stop until there is another consumer or\n   * {@link Minipass#resume} is explicitly called.\n   */\n  unpipe(dest: W) {\n    const p = this[PIPES].find(p => p.dest === dest)\n    if (p) {\n      if (this[PIPES].length === 1) {\n        if (this[FLOWING] && this[DATALISTENERS] === 0) {\n          this[FLOWING] = false\n        }\n        this[PIPES] = []\n      } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n      p.unpipe()\n    }\n  }\n\n  /**\n   * Alias for {@link Minipass#on}\n   */\n  addListener(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ): this {\n    return this.on(ev, handler)\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.on`, with the following\n   * behavior differences to prevent data loss and unnecessary hangs:\n   *\n   * - Adding a 'data' event handler will trigger the flow of data\n   *\n   * - Adding a 'readable' event handler when there is data waiting to be read\n   *   will cause 'readable' to be emitted immediately.\n   *\n   * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n   *   already passed will cause the event to be emitted immediately and all\n   *   handlers removed.\n   *\n   * - Adding an 'error' event handler after an error has been emitted will\n   *   cause the event to be re-emitted immediately with the error previously\n   *   raised.\n   */\n  on(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ): this {\n    const ret = super.on(\n      ev as string | symbol,\n      handler as (...a: any[]) => any\n    )\n    if (ev === 'data') {\n      this[DISCARDED] = false\n      this[DATALISTENERS]++\n      if (!this[PIPES].length && !this[FLOWING]) {\n        this[RESUME]()\n      }\n    } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n      super.emit('readable')\n    } else if (isEndish(ev) && this[EMITTED_END]) {\n      super.emit(ev)\n      this.removeAllListeners(ev)\n    } else if (ev === 'error' && this[EMITTED_ERROR]) {\n      const h = handler as (...a: Events['error']) => any\n      if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n      else h.call(this, this[EMITTED_ERROR])\n    }\n    return ret\n  }\n\n  /**\n   * Alias for {@link Minipass#off}\n   */\n  removeListener(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ) {\n    return this.off(ev, handler)\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.off`\n   *\n   * If a 'data' event handler is removed, and it was the last consumer\n   * (ie, there are no pipe destinations or other 'data' event listeners),\n   * then the flow of data will stop until there is another consumer or\n   * {@link Minipass#resume} is explicitly called.\n   */\n  off(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ) {\n    const ret = super.off(\n      ev as string | symbol,\n      handler as (...a: any[]) => any\n    )\n    // if we previously had listeners, and now we don't, and we don't\n    // have any pipes, then stop the flow, unless it's been explicitly\n    // put in a discarded flowing state via stream.resume().\n    if (ev === 'data') {\n      this[DATALISTENERS] = this.listeners('data').length\n      if (\n        this[DATALISTENERS] === 0 &&\n        !this[DISCARDED] &&\n        !this[PIPES].length\n      ) {\n        this[FLOWING] = false\n      }\n    }\n    return ret\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.removeAllListeners`\n   *\n   * If all 'data' event handlers are removed, and they were the last consumer\n   * (ie, there are no pipe destinations), then the flow of data will stop\n   * until there is another consumer or {@link Minipass#resume} is explicitly\n   * called.\n   */\n  removeAllListeners(ev?: Event) {\n    const ret = super.removeAllListeners(ev as string | symbol | undefined)\n    if (ev === 'data' || ev === undefined) {\n      this[DATALISTENERS] = 0\n      if (!this[DISCARDED] && !this[PIPES].length) {\n        this[FLOWING] = false\n      }\n    }\n    return ret\n  }\n\n  /**\n   * true if the 'end' event has been emitted\n   */\n  get emittedEnd() {\n    return this[EMITTED_END]\n  }\n\n  [MAYBE_EMIT_END]() {\n    if (\n      !this[EMITTING_END] &&\n      !this[EMITTED_END] &&\n      !this[DESTROYED] &&\n      this[BUFFER].length === 0 &&\n      this[EOF]\n    ) {\n      this[EMITTING_END] = true\n      this.emit('end')\n      this.emit('prefinish')\n      this.emit('finish')\n      if (this[CLOSED]) this.emit('close')\n      this[EMITTING_END] = false\n    }\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.emit`, with the following\n   * behavior differences to prevent data loss and unnecessary hangs:\n   *\n   * If the stream has been destroyed, and the event is something other\n   * than 'close' or 'error', then `false` is returned and no handlers\n   * are called.\n   *\n   * If the event is 'end', and has already been emitted, then the event\n   * is ignored. If the stream is in a paused or non-flowing state, then\n   * the event will be deferred until data flow resumes. If the stream is\n   * async, then handlers will be called on the next tick rather than\n   * immediately.\n   *\n   * If the event is 'close', and 'end' has not yet been emitted, then\n   * the event will be deferred until after 'end' is emitted.\n   *\n   * If the event is 'error', and an AbortSignal was provided for the stream,\n   * and there are no listeners, then the event is ignored, matching the\n   * behavior of node core streams in the presense of an AbortSignal.\n   *\n   * If the event is 'finish' or 'prefinish', then all listeners will be\n   * removed after emitting the event, to prevent double-firing.\n   */\n  emit(\n    ev: Event,\n    ...args: Events[Event]\n  ): boolean {\n    const data = args[0]\n    // error and close are only events allowed after calling destroy()\n    if (\n      ev !== 'error' &&\n      ev !== 'close' &&\n      ev !== DESTROYED &&\n      this[DESTROYED]\n    ) {\n      return false\n    } else if (ev === 'data') {\n      return !this[OBJECTMODE] && !data\n        ? false\n        : this[ASYNC]\n        ? (defer(() => this[EMITDATA](data as RType)), true)\n        : this[EMITDATA](data as RType)\n    } else if (ev === 'end') {\n      return this[EMITEND]()\n    } else if (ev === 'close') {\n      this[CLOSED] = true\n      // don't emit close before 'end' and 'finish'\n      if (!this[EMITTED_END] && !this[DESTROYED]) return false\n      const ret = super.emit('close')\n      this.removeAllListeners('close')\n      return ret\n    } else if (ev === 'error') {\n      this[EMITTED_ERROR] = data\n      super.emit(ERROR, data)\n      const ret =\n        !this[SIGNAL] || this.listeners('error').length\n          ? super.emit('error', data)\n          : false\n      this[MAYBE_EMIT_END]()\n      return ret\n    } else if (ev === 'resume') {\n      const ret = super.emit('resume')\n      this[MAYBE_EMIT_END]()\n      return ret\n    } else if (ev === 'finish' || ev === 'prefinish') {\n      const ret = super.emit(ev)\n      this.removeAllListeners(ev)\n      return ret\n    }\n\n    // Some other unknown event\n    const ret = super.emit(ev as string, ...args)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [EMITDATA](data: RType) {\n    for (const p of this[PIPES]) {\n      if (p.dest.write(data) === false) this.pause()\n    }\n    const ret = this[DISCARDED] ? false : super.emit('data', data)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [EMITEND]() {\n    if (this[EMITTED_END]) return false\n\n    this[EMITTED_END] = true\n    this.readable = false\n    return this[ASYNC]\n      ? (defer(() => this[EMITEND2]()), true)\n      : this[EMITEND2]()\n  }\n\n  [EMITEND2]() {\n    if (this[DECODER]) {\n      const data = this[DECODER].end()\n      if (data) {\n        for (const p of this[PIPES]) {\n          p.dest.write(data as RType)\n        }\n        if (!this[DISCARDED]) super.emit('data', data)\n      }\n    }\n\n    for (const p of this[PIPES]) {\n      p.end()\n    }\n    const ret = super.emit('end')\n    this.removeAllListeners('end')\n    return ret\n  }\n\n  /**\n   * Return a Promise that resolves to an array of all emitted data once\n   * the stream ends.\n   */\n  async collect(): Promise {\n    const buf: RType[] & { dataLength: number } = Object.assign([], {\n      dataLength: 0,\n    })\n    if (!this[OBJECTMODE]) buf.dataLength = 0\n    // set the promise first, in case an error is raised\n    // by triggering the flow here.\n    const p = this.promise()\n    this.on('data', c => {\n      buf.push(c)\n      if (!this[OBJECTMODE])\n        buf.dataLength += (c as Minipass.BufferOrString).length\n    })\n    await p\n    return buf\n  }\n\n  /**\n   * Return a Promise that resolves to the concatenation of all emitted data\n   * once the stream ends.\n   *\n   * Not allowed on objectMode streams.\n   */\n  async concat(): Promise {\n    if (this[OBJECTMODE]) {\n      throw new Error('cannot concat in objectMode')\n    }\n    const buf = await this.collect()\n    return (\n      this[ENCODING]\n        ? buf.join('')\n        : Buffer.concat(buf as Buffer[], buf.dataLength)\n    ) as RType\n  }\n\n  /**\n   * Return a void Promise that resolves once the stream ends.\n   */\n  async promise(): Promise {\n    return new Promise((resolve, reject) => {\n      this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n      this.on('error', er => reject(er))\n      this.on('end', () => resolve())\n    })\n  }\n\n  /**\n   * Asynchronous `for await of` iteration.\n   *\n   * This will continue emitting all chunks until the stream terminates.\n   */\n  [Symbol.asyncIterator](): AsyncGenerator {\n    // set this up front, in case the consumer doesn't call next()\n    // right away.\n    this[DISCARDED] = false\n    let stopped = false\n    const stop = async (): Promise> => {\n      this.pause()\n      stopped = true\n      return { value: undefined, done: true }\n    }\n    const next = (): Promise> => {\n      if (stopped) return stop()\n      const res = this.read()\n      if (res !== null) return Promise.resolve({ done: false, value: res })\n\n      if (this[EOF]) return stop()\n\n      let resolve!: (res: IteratorResult) => void\n      let reject!: (er: unknown) => void\n      const onerr = (er: unknown) => {\n        this.off('data', ondata)\n        this.off('end', onend)\n        this.off(DESTROYED, ondestroy)\n        stop()\n        reject(er)\n      }\n      const ondata = (value: RType) => {\n        this.off('error', onerr)\n        this.off('end', onend)\n        this.off(DESTROYED, ondestroy)\n        this.pause()\n        resolve({ value, done: !!this[EOF] })\n      }\n      const onend = () => {\n        this.off('error', onerr)\n        this.off('data', ondata)\n        this.off(DESTROYED, ondestroy)\n        stop()\n        resolve({ done: true, value: undefined })\n      }\n      const ondestroy = () => onerr(new Error('stream destroyed'))\n      return new Promise>((res, rej) => {\n        reject = rej\n        resolve = res\n        this.once(DESTROYED, ondestroy)\n        this.once('error', onerr)\n        this.once('end', onend)\n        this.once('data', ondata)\n      })\n    }\n\n    return {\n      next,\n      throw: stop,\n      return: stop,\n      [Symbol.asyncIterator]() {\n        return this\n      },\n    }\n  }\n\n  /**\n   * Synchronous `for of` iteration.\n   *\n   * The iteration will terminate when the internal buffer runs out, even\n   * if the stream has not yet terminated.\n   */\n  [Symbol.iterator](): Generator {\n    // set this up front, in case the consumer doesn't call next()\n    // right away.\n    this[DISCARDED] = false\n    let stopped = false\n    const stop = (): IteratorReturnResult => {\n      this.pause()\n      this.off(ERROR, stop)\n      this.off(DESTROYED, stop)\n      this.off('end', stop)\n      stopped = true\n      return { done: true, value: undefined }\n    }\n\n    const next = (): IteratorResult => {\n      if (stopped) return stop()\n      const value = this.read()\n      return value === null ? stop() : { done: false, value }\n    }\n\n    this.once('end', stop)\n    this.once(ERROR, stop)\n    this.once(DESTROYED, stop)\n\n    return {\n      next,\n      throw: stop,\n      return: stop,\n      [Symbol.iterator]() {\n        return this\n      },\n    }\n  }\n\n  /**\n   * Destroy a stream, preventing it from being used for any further purpose.\n   *\n   * If the stream has a `close()` method, then it will be called on\n   * destruction.\n   *\n   * After destruction, any attempt to write data, read data, or emit most\n   * events will be ignored.\n   *\n   * If an error argument is provided, then it will be emitted in an\n   * 'error' event.\n   */\n  destroy(er?: unknown) {\n    if (this[DESTROYED]) {\n      if (er) this.emit('error', er)\n      else this.emit(DESTROYED)\n      return this\n    }\n\n    this[DESTROYED] = true\n    this[DISCARDED] = true\n\n    // throw away all buffered data, it's never coming out\n    this[BUFFER].length = 0\n    this[BUFFERLENGTH] = 0\n\n    const wc = this as Minipass & {\n      close?: () => void\n    }\n    if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n    if (er) this.emit('error', er)\n    // if no error to emit, still reject pending promises\n    else this.emit(DESTROYED)\n\n    return this\n  }\n\n  /**\n   * Alias for {@link isStream}\n   *\n   * Former export location, maintained for backwards compatibility.\n   *\n   * @deprecated\n   */\n  static get isStream() {\n    return isStream\n  }\n}\n","import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport {\n  FSOption,\n  Path,\n  PathScurry,\n  PathScurryDarwin,\n  PathScurryPosix,\n  PathScurryWin32,\n} from 'path-scurry'\nimport { fileURLToPath } from 'url'\nimport { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n  typeof process === 'object' &&\n  process &&\n  typeof process.platform === 'string'\n    ? process.platform\n    : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n  /**\n   * Set to `true` to always receive absolute paths for\n   * matched files. Set to `false` to always return relative paths.\n   *\n   * When this option is not set, absolute paths are returned for patterns\n   * that are absolute, and otherwise paths are returned that are relative\n   * to the `cwd` setting.\n   *\n   * This does _not_ make an extra system call to get\n   * the realpath, it only does string path resolution.\n   *\n   * Conflicts with {@link withFileTypes}\n   */\n  absolute?: boolean\n\n  /**\n   * Set to false to enable {@link windowsPathsNoEscape}\n   *\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n\n  /**\n   * The current working directory in which to search. Defaults to\n   * `process.cwd()`.\n   *\n   * May be eiher a string path or a `file://` URL object or string.\n   */\n  cwd?: string | URL\n\n  /**\n   * Include `.dot` files in normal matches and `globstar`\n   * matches. Note that an explicit dot in a portion of the pattern\n   * will always match dot files.\n   */\n  dot?: boolean\n\n  /**\n   * Prepend all relative path strings with `./` (or `.\\` on Windows).\n   *\n   * Without this option, returned relative paths are \"bare\", so instead of\n   * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n   *\n   * Relative patterns starting with `'../'` are not prepended with `./`, even\n   * if this option is set.\n   */\n  dotRelative?: boolean\n\n  /**\n   * Follow symlinked directories when expanding `**`\n   * patterns. This can result in a lot of duplicate references in\n   * the presence of cyclic links, and make performance quite bad.\n   *\n   * By default, a `**` in a pattern will follow 1 symbolic link if\n   * it is not the first item in the pattern, or none if it is the\n   * first item in the pattern, following the same behavior as Bash.\n   */\n  follow?: boolean\n\n  /**\n   * string or string[], or an object with `ignore` and `ignoreChildren`\n   * methods.\n   *\n   * If a string or string[] is provided, then this is treated as a glob\n   * pattern or array of glob patterns to exclude from matches. To ignore all\n   * children within a directory, as well as the entry itself, append `'/**'`\n   * to the ignore pattern.\n   *\n   * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n   * any other settings.\n   *\n   * If an object is provided that has `ignored(path)` and/or\n   * `childrenIgnored(path)` methods, then these methods will be called to\n   * determine whether any Path is a match or if its children should be\n   * traversed, respectively.\n   */\n  ignore?: string | string[] | IgnoreLike\n\n  /**\n   * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n   * effect if {@link nobrace} is set.\n   *\n   * Only has effect on the {@link hasMagic} function.\n   */\n  magicalBraces?: boolean\n\n  /**\n   * Add a `/` character to directory matches. Note that this requires\n   * additional stat calls in some cases.\n   */\n  mark?: boolean\n\n  /**\n   * Perform a basename-only match if the pattern does not contain any slash\n   * characters. That is, `*.js` would be treated as equivalent to\n   * `**\\/*.js`, matching all js files in all directories.\n   */\n  matchBase?: boolean\n\n  /**\n   * Limit the directory traversal to a given depth below the cwd.\n   * Note that this does NOT prevent traversal to sibling folders,\n   * root patterns, and so on. It only limits the maximum folder depth\n   * that the walk will descend, relative to the cwd.\n   */\n  maxDepth?: number\n\n  /**\n   * Do not expand `{a,b}` and `{1..3}` brace sets.\n   */\n  nobrace?: boolean\n\n  /**\n   * Perform a case-insensitive match. This defaults to `true` on macOS and\n   * Windows systems, and `false` on all others.\n   *\n   * **Note** `nocase` should only be explicitly set when it is\n   * known that the filesystem's case sensitivity differs from the\n   * platform default. If set `true` on case-sensitive file\n   * systems, or `false` on case-insensitive file systems, then the\n   * walk may return more or less results than expected.\n   */\n  nocase?: boolean\n\n  /**\n   * Do not match directories, only files. (Note: to match\n   * _only_ directories, put a `/` at the end of the pattern.)\n   */\n  nodir?: boolean\n\n  /**\n   * Do not match \"extglob\" patterns such as `+(a|b)`.\n   */\n  noext?: boolean\n\n  /**\n   * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n   * `*` instead.)\n   *\n   * Conflicts with {@link matchBase}\n   */\n  noglobstar?: boolean\n\n  /**\n   * Defaults to value of `process.platform` if available, or `'linux'` if\n   * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n   * behavior.\n   */\n  platform?: NodeJS.Platform\n\n  /**\n   * Set to true to call `fs.realpath` on all of the\n   * results. In the case of an entry that cannot be resolved, the\n   * entry is omitted. This incurs a slight performance penalty, of\n   * course, because of the added system calls.\n   */\n  realpath?: boolean\n\n  /**\n   *\n   * A string path resolved against the `cwd` option, which\n   * is used as the starting point for absolute patterns that start\n   * with `/`, (but not drive letters or UNC paths on Windows).\n   *\n   * Note that this _doesn't_ necessarily limit the walk to the\n   * `root` directory, and doesn't affect the cwd starting point for\n   * non-absolute patterns. A pattern containing `..` will still be\n   * able to traverse out of the root directory, if it is not an\n   * actual root directory on the filesystem, and any non-absolute\n   * patterns will be matched in the `cwd`. For example, the\n   * pattern `/../*` with `{root:'/some/path'}` will return all\n   * files in `/some`, not all files in `/some/path`. The pattern\n   * `*` with `{root:'/some/path'}` will return all the entries in\n   * the cwd, not the entries in `/some/path`.\n   *\n   * To start absolute and non-absolute patterns in the same\n   * path, you can use `{root:''}`. However, be aware that on\n   * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n   * _always_ start in the `x:/` or `//host/share` directory,\n   * regardless of the `root` setting.\n   */\n  root?: string\n\n  /**\n   * A [PathScurry](http://npm.im/path-scurry) object used\n   * to traverse the file system. If the `nocase` option is set\n   * explicitly, then any provided `scurry` object must match this\n   * setting.\n   */\n  scurry?: PathScurry\n\n  /**\n   * Call `lstat()` on all entries, whether required or not to determine\n   * if it's a valid match. When used with {@link withFileTypes}, this means\n   * that matches will include data such as modified time, permissions, and\n   * so on.  Note that this will incur a performance cost due to the added\n   * system calls.\n   */\n  stat?: boolean\n\n  /**\n   * An AbortSignal which will cancel the Glob walk when\n   * triggered.\n   */\n  signal?: AbortSignal\n\n  /**\n   * Use `\\\\` as a path separator _only_, and\n   *  _never_ as an escape character. If set, all `\\\\` characters are\n   *  replaced with `/` in the pattern.\n   *\n   *  Note that this makes it **impossible** to match against paths\n   *  containing literal glob pattern characters, but allows matching\n   *  with patterns constructed using `path.join()` and\n   *  `path.resolve()` on Windows platforms, mimicking the (buggy!)\n   *  behavior of Glob v7 and before on Windows. Please use with\n   *  caution, and be mindful of [the caveat below about Windows\n   *  paths](#windows). (For legacy reasons, this is also set if\n   *  `allowWindowsEscape` is set to the exact value `false`.)\n   */\n  windowsPathsNoEscape?: boolean\n\n  /**\n   * Return [PathScurry](http://npm.im/path-scurry)\n   * `Path` objects instead of strings. These are similar to a\n   * NodeJS `Dirent` object, but with additional methods and\n   * properties.\n   *\n   * Conflicts with {@link absolute}\n   */\n  withFileTypes?: boolean\n\n  /**\n   * An fs implementation to override some or all of the defaults.  See\n   * http://npm.im/path-scurry for details about what can be overridden.\n   */\n  fs?: FSOption\n\n  /**\n   * Just passed along to Minimatch.  Note that this makes all pattern\n   * matching operations slower and *extremely* noisy.\n   */\n  debug?: boolean\n\n  /**\n   * Return `/` delimited paths, even on Windows.\n   *\n   * On posix systems, this has no effect.  But, on Windows, it means that\n   * paths will be `/` delimited, and absolute paths will be their full\n   * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n   * `'//?/C:/foo/bar'`\n   */\n  posix?: boolean\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n  withFileTypes: true\n  // string options not relevant if returning Path objects.\n  absolute?: undefined\n  mark?: undefined\n  posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n  withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n  withFileTypes?: undefined\n}\n\nexport type Result = Opts extends GlobOptionsWithFileTypesTrue\n  ? Path\n  : Opts extends GlobOptionsWithFileTypesFalse\n  ? string\n  : Opts extends GlobOptionsWithFileTypesUnset\n  ? string\n  : string | Path\nexport type Results = Result[]\n\nexport type FileTypes = Opts extends GlobOptionsWithFileTypesTrue\n  ? true\n  : Opts extends GlobOptionsWithFileTypesFalse\n  ? false\n  : Opts extends GlobOptionsWithFileTypesUnset\n  ? false\n  : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob implements GlobOptions {\n  absolute?: boolean\n  cwd: string\n  root?: string\n  dot: boolean\n  dotRelative: boolean\n  follow: boolean\n  ignore?: string | string[] | IgnoreLike\n  magicalBraces: boolean\n  mark?: boolean\n  matchBase: boolean\n  maxDepth: number\n  nobrace: boolean\n  nocase: boolean\n  nodir: boolean\n  noext: boolean\n  noglobstar: boolean\n  pattern: string[]\n  platform: NodeJS.Platform\n  realpath: boolean\n  scurry: PathScurry\n  stat: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape: boolean\n  withFileTypes: FileTypes\n\n  /**\n   * The options provided to the constructor.\n   */\n  opts: Opts\n\n  /**\n   * An array of parsed immutable {@link Pattern} objects.\n   */\n  patterns: Pattern[]\n\n  /**\n   * All options are stored as properties on the `Glob` object.\n   *\n   * See {@link GlobOptions} for full options descriptions.\n   *\n   * Note that a previous `Glob` object can be passed as the\n   * `GlobOptions` to another `Glob` instantiation to re-use settings\n   * and caches with a new pattern.\n   *\n   * Traversal functions can be called multiple times to run the walk\n   * again.\n   */\n  constructor(pattern: string | string[], opts: Opts) {\n    /* c8 ignore start */\n    if (!opts) throw new TypeError('glob options required')\n    /* c8 ignore stop */\n    this.withFileTypes = !!opts.withFileTypes as FileTypes\n    this.signal = opts.signal\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.dotRelative = !!opts.dotRelative\n    this.nodir = !!opts.nodir\n    this.mark = !!opts.mark\n    if (!opts.cwd) {\n      this.cwd = ''\n    } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n      opts.cwd = fileURLToPath(opts.cwd)\n    }\n    this.cwd = opts.cwd || ''\n    this.root = opts.root\n    this.magicalBraces = !!opts.magicalBraces\n    this.nobrace = !!opts.nobrace\n    this.noext = !!opts.noext\n    this.realpath = !!opts.realpath\n    this.absolute = opts.absolute\n\n    this.noglobstar = !!opts.noglobstar\n    this.matchBase = !!opts.matchBase\n    this.maxDepth =\n      typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n    this.stat = !!opts.stat\n    this.ignore = opts.ignore\n\n    if (this.withFileTypes && this.absolute !== undefined) {\n      throw new Error('cannot set absolute and withFileTypes:true')\n    }\n\n    if (typeof pattern === 'string') {\n      pattern = [pattern]\n    }\n\n    this.windowsPathsNoEscape =\n      !!opts.windowsPathsNoEscape ||\n      (opts as GlobOptions).allowWindowsEscape === false\n\n    if (this.windowsPathsNoEscape) {\n      pattern = pattern.map(p => p.replace(/\\\\/g, '/'))\n    }\n\n    if (this.matchBase) {\n      if (opts.noglobstar) {\n        throw new TypeError('base matching requires globstar')\n      }\n      pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`))\n    }\n\n    this.pattern = pattern\n\n    this.platform = opts.platform || defaultPlatform\n    this.opts = { ...opts, platform: this.platform }\n    if (opts.scurry) {\n      this.scurry = opts.scurry\n      if (\n        opts.nocase !== undefined &&\n        opts.nocase !== opts.scurry.nocase\n      ) {\n        throw new Error('nocase option contradicts provided scurry option')\n      }\n    } else {\n      const Scurry =\n        opts.platform === 'win32'\n          ? PathScurryWin32\n          : opts.platform === 'darwin'\n          ? PathScurryDarwin\n          : opts.platform\n          ? PathScurryPosix\n          : PathScurry\n      this.scurry = new Scurry(this.cwd, {\n        nocase: opts.nocase,\n        fs: opts.fs,\n      })\n    }\n    this.nocase = this.scurry.nocase\n\n    // If you do nocase:true on a case-sensitive file system, then\n    // we need to use regexps instead of strings for non-magic\n    // path portions, because statting `aBc` won't return results\n    // for the file `AbC` for example.\n    const nocaseMagicOnly =\n      this.platform === 'darwin' || this.platform === 'win32'\n\n    const mmo: MinimatchOptions = {\n      // default nocase based on platform\n      ...opts,\n      dot: this.dot,\n      matchBase: this.matchBase,\n      nobrace: this.nobrace,\n      nocase: this.nocase,\n      nocaseMagicOnly,\n      nocomment: true,\n      noext: this.noext,\n      nonegate: true,\n      optimizationLevel: 2,\n      platform: this.platform,\n      windowsPathsNoEscape: this.windowsPathsNoEscape,\n      debug: !!this.opts.debug,\n    }\n\n    const mms = this.pattern.map(p => new Minimatch(p, mmo))\n    const [matchSet, globParts] = mms.reduce(\n      (set: [MatchSet, GlobParts], m) => {\n        set[0].push(...m.set)\n        set[1].push(...m.globParts)\n        return set\n      },\n      [[], []]\n    )\n    this.patterns = matchSet.map((set, i) => {\n      const g = globParts[i]\n      /* c8 ignore start */\n      if (!g) throw new Error('invalid pattern object')\n      /* c8 ignore stop */\n      return new Pattern(set, g, 0, this.platform)\n    })\n  }\n\n  /**\n   * Returns a Promise that resolves to the results array.\n   */\n  async walk(): Promise>\n  async walk(): Promise<(string | Path)[]> {\n    // Walkers always return array of Path objects, so we just have to\n    // coerce them into the right shape.  It will have already called\n    // realpath() if the option was set to do so, so we know that's cached.\n    // start out knowing the cwd, at least\n    return [\n      ...(await new GlobWalker(this.patterns, this.scurry.cwd, {\n        ...this.opts,\n        maxDepth:\n          this.maxDepth !== Infinity\n            ? this.maxDepth + this.scurry.cwd.depth()\n            : Infinity,\n        platform: this.platform,\n        nocase: this.nocase,\n      }).walk()),\n    ]\n  }\n\n  /**\n   * synchronous {@link Glob.walk}\n   */\n  walkSync(): Results\n  walkSync(): (string | Path)[] {\n    return [\n      ...new GlobWalker(this.patterns, this.scurry.cwd, {\n        ...this.opts,\n        maxDepth:\n          this.maxDepth !== Infinity\n            ? this.maxDepth + this.scurry.cwd.depth()\n            : Infinity,\n        platform: this.platform,\n        nocase: this.nocase,\n      }).walkSync(),\n    ]\n  }\n\n  /**\n   * Stream results asynchronously.\n   */\n  stream(): Minipass, Result>\n  stream(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity\n          ? this.maxDepth + this.scurry.cwd.depth()\n          : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n    }).stream()\n  }\n\n  /**\n   * Stream results synchronously.\n   */\n  streamSync(): Minipass, Result>\n  streamSync(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity\n          ? this.maxDepth + this.scurry.cwd.depth()\n          : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n    }).streamSync()\n  }\n\n  /**\n   * Default sync iteration function. Returns a Generator that\n   * iterates over the results.\n   */\n  iterateSync(): Generator, void, void> {\n    return this.streamSync()[Symbol.iterator]()\n  }\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  /**\n   * Default async iteration function. Returns an AsyncGenerator that\n   * iterates over the results.\n   */\n  iterate(): AsyncGenerator, void, void> {\n    return this.stream()[Symbol.asyncIterator]()\n  }\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n}\n","// this is just a very light wrapper around 2 arrays with an offset index\n\nimport { GLOBSTAR } from 'minimatch'\nexport type MMPattern = string | RegExp | typeof GLOBSTAR\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n  p0: '',\n  p1: '',\n  p2: string,\n  p3: string,\n  ...rest: MMPattern[]\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n  pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n  readonly #patternList: PatternList\n  readonly #globList: GlobList\n  readonly #index: number\n  readonly length: number\n  readonly #platform: NodeJS.Platform\n  #rest?: Pattern | null\n  #globString?: string\n  #isDrive?: boolean\n  #isUNC?: boolean\n  #isAbsolute?: boolean\n  #followGlobstar: boolean = true\n\n  constructor(\n    patternList: MMPattern[],\n    globList: string[],\n    index: number,\n    platform: NodeJS.Platform\n  ) {\n    if (!isPatternList(patternList)) {\n      throw new TypeError('empty pattern list')\n    }\n    if (!isGlobList(globList)) {\n      throw new TypeError('empty glob list')\n    }\n    if (globList.length !== patternList.length) {\n      throw new TypeError('mismatched pattern list and glob list lengths')\n    }\n    this.length = patternList.length\n    if (index < 0 || index >= this.length) {\n      throw new TypeError('index out of range')\n    }\n    this.#patternList = patternList\n    this.#globList = globList\n    this.#index = index\n    this.#platform = platform\n\n    // normalize root entries of absolute patterns on initial creation.\n    if (this.#index === 0) {\n      // c: => ['c:/']\n      // C:/ => ['C:/']\n      // C:/x => ['C:/', 'x']\n      // //host/share => ['//host/share/']\n      // //host/share/ => ['//host/share/']\n      // //host/share/x => ['//host/share/', 'x']\n      // /etc => ['/', 'etc']\n      // / => ['/']\n      if (this.isUNC()) {\n        // '' / '' / 'host' / 'share'\n        const [p0, p1, p2, p3, ...prest] = this.#patternList\n        const [g0, g1, g2, g3, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = [p0, p1, p2, p3, ''].join('/')\n        const g = [g0, g1, g2, g3, ''].join('/')\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      } else if (this.isDrive() || this.isAbsolute()) {\n        const [p1, ...prest] = this.#patternList\n        const [g1, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = (p1 as string) + '/'\n        const g = g1 + '/'\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      }\n    }\n  }\n\n  /**\n   * The first entry in the parsed list of patterns\n   */\n  pattern(): MMPattern {\n    return this.#patternList[this.#index] as MMPattern\n  }\n\n  /**\n   * true of if pattern() returns a string\n   */\n  isString(): boolean {\n    return typeof this.#patternList[this.#index] === 'string'\n  }\n  /**\n   * true of if pattern() returns GLOBSTAR\n   */\n  isGlobstar(): boolean {\n    return this.#patternList[this.#index] === GLOBSTAR\n  }\n  /**\n   * true if pattern() returns a regexp\n   */\n  isRegExp(): boolean {\n    return this.#patternList[this.#index] instanceof RegExp\n  }\n\n  /**\n   * The /-joined set of glob parts that make up this pattern\n   */\n  globString(): string {\n    return (this.#globString =\n      this.#globString ||\n      (this.#index === 0\n        ? this.isAbsolute()\n          ? this.#globList[0] + this.#globList.slice(1).join('/')\n          : this.#globList.join('/')\n        : this.#globList.slice(this.#index).join('/')))\n  }\n\n  /**\n   * true if there are more pattern parts after this one\n   */\n  hasMore(): boolean {\n    return this.length > this.#index + 1\n  }\n\n  /**\n   * The rest of the pattern after this part, or null if this is the end\n   */\n  rest(): Pattern | null {\n    if (this.#rest !== undefined) return this.#rest\n    if (!this.hasMore()) return (this.#rest = null)\n    this.#rest = new Pattern(\n      this.#patternList,\n      this.#globList,\n      this.#index + 1,\n      this.#platform\n    )\n    this.#rest.#isAbsolute = this.#isAbsolute\n    this.#rest.#isUNC = this.#isUNC\n    this.#rest.#isDrive = this.#isDrive\n    return this.#rest\n  }\n\n  /**\n   * true if the pattern represents a //unc/path/ on windows\n   */\n  isUNC(): boolean {\n    const pl = this.#patternList\n    return this.#isUNC !== undefined\n      ? this.#isUNC\n      : (this.#isUNC =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          pl[0] === '' &&\n          pl[1] === '' &&\n          typeof pl[2] === 'string' &&\n          !!pl[2] &&\n          typeof pl[3] === 'string' &&\n          !!pl[3])\n  }\n\n  // pattern like C:/...\n  // split = ['C:', ...]\n  // XXX: would be nice to handle patterns like `c:*` to test the cwd\n  // in c: for *, but I don't know of a way to even figure out what that\n  // cwd is without actually chdir'ing into it?\n  /**\n   * True if the pattern starts with a drive letter on Windows\n   */\n  isDrive(): boolean {\n    const pl = this.#patternList\n    return this.#isDrive !== undefined\n      ? this.#isDrive\n      : (this.#isDrive =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          this.length > 1 &&\n          typeof pl[0] === 'string' &&\n          /^[a-z]:$/i.test(pl[0]))\n  }\n\n  // pattern = '/' or '/...' or '/x/...'\n  // split = ['', ''] or ['', ...] or ['', 'x', ...]\n  // Drive and UNC both considered absolute on windows\n  /**\n   * True if the pattern is rooted on an absolute path\n   */\n  isAbsolute(): boolean {\n    const pl = this.#patternList\n    return this.#isAbsolute !== undefined\n      ? this.#isAbsolute\n      : (this.#isAbsolute =\n          (pl[0] === '' && pl.length > 1) ||\n          this.isDrive() ||\n          this.isUNC())\n  }\n\n  /**\n   * consume the root of the pattern, and return it\n   */\n  root(): string {\n    const p = this.#patternList[0]\n    return typeof p === 'string' && this.isAbsolute() && this.#index === 0\n      ? p\n      : ''\n  }\n\n  /**\n   * Check to see if the current globstar pattern is allowed to follow\n   * a symbolic link.\n   */\n  checkFollowGlobstar(): boolean {\n    return !(\n      this.#index === 0 ||\n      !this.isGlobstar() ||\n      !this.#followGlobstar\n    )\n  }\n\n  /**\n   * Mark that the current globstar pattern is following a symbolic link\n   */\n  markFollowGlobstar(): boolean {\n    if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n      return false\n    this.#followGlobstar = false\n    return true\n  }\n}\n","// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport { Minimatch } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n  ignored?: (p: Path) => boolean\n  childrenIgnored?: (p: Path) => boolean\n}\n\nconst defaultPlatform: NodeJS.Platform =\n  typeof process === 'object' &&\n  process &&\n  typeof process.platform === 'string'\n    ? process.platform\n    : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n  relative: Minimatch[]\n  relativeChildren: Minimatch[]\n  absolute: Minimatch[]\n  absoluteChildren: Minimatch[]\n\n  constructor(\n    ignored: string[],\n    {\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      platform = defaultPlatform,\n    }: GlobWalkerOpts\n  ) {\n    this.relative = []\n    this.absolute = []\n    this.relativeChildren = []\n    this.absoluteChildren = []\n    const mmopts = {\n      dot: true,\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      optimizationLevel: 2,\n      platform,\n      nocomment: true,\n      nonegate: true,\n    }\n\n    // this is a little weird, but it gives us a clean set of optimized\n    // minimatch matchers, without getting tripped up if one of them\n    // ends in /** inside a brace section, and it's only inefficient at\n    // the start of the walk, not along it.\n    // It'd be nice if the Pattern class just had a .test() method, but\n    // handling globstars is a bit of a pita, and that code already lives\n    // in minimatch anyway.\n    // Another way would be if maybe Minimatch could take its set/globParts\n    // as an option, and then we could at least just use Pattern to test\n    // for absolute-ness.\n    // Yet another way, Minimatch could take an array of glob strings, and\n    // a cwd option, and do the right thing.\n    for (const ign of ignored) {\n      const mm = new Minimatch(ign, mmopts)\n      for (let i = 0; i < mm.set.length; i++) {\n        const parsed = mm.set[i]\n        const globParts = mm.globParts[i]\n        /* c8 ignore start */\n        if (!parsed || !globParts) {\n          throw new Error('invalid pattern object')\n        }\n        /* c8 ignore stop */\n        const p = new Pattern(parsed, globParts, 0, platform)\n        const m = new Minimatch(p.globString(), mmopts)\n        const children = globParts[globParts.length - 1] === '**'\n        const absolute = p.isAbsolute()\n        if (absolute) this.absolute.push(m)\n        else this.relative.push(m)\n        if (children) {\n          if (absolute) this.absoluteChildren.push(m)\n          else this.relativeChildren.push(m)\n        }\n      }\n    }\n  }\n\n  ignored(p: Path): boolean {\n    const fullpath = p.fullpath()\n    const fullpaths = `${fullpath}/`\n    const relative = p.relative() || '.'\n    const relatives = `${relative}/`\n    for (const m of this.relative) {\n      if (m.match(relative) || m.match(relatives)) return true\n    }\n    for (const m of this.absolute) {\n      if (m.match(fullpath) || m.match(fullpaths)) return true\n    }\n    return false\n  }\n\n  childrenIgnored(p: Path): boolean {\n    const fullpath = p.fullpath() + '/'\n    const relative = (p.relative() || '.') + '/'\n    for (const m of this.relativeChildren) {\n      if (m.match(relative)) return true\n    }\n    for (const m of this.absoluteChildren) {\n      if (m.match(fullpath)) return true\n    }\n    return false\n  }\n}\n","// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR, MMRegExp } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { MMPattern, Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path\n */\nexport class HasWalkedCache {\n  store: Map>\n  constructor(store: Map> = new Map()) {\n    this.store = store\n  }\n  copy() {\n    return new HasWalkedCache(new Map(this.store))\n  }\n  hasWalked(target: Path, pattern: Pattern) {\n    return this.store.get(target.fullpath())?.has(pattern.globString())\n  }\n  storeWalked(target: Path, pattern: Pattern) {\n    const fullpath = target.fullpath()\n    const cached = this.store.get(fullpath)\n    if (cached) cached.add(pattern.globString())\n    else this.store.set(fullpath, new Set([pattern.globString()]))\n  }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n */\nexport class MatchRecord {\n  store: Map = new Map()\n  add(target: Path, absolute: boolean, ifDir: boolean) {\n    const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0)\n    const current = this.store.get(target)\n    this.store.set(target, current === undefined ? n : n & current)\n  }\n  // match, absolute, ifdir\n  entries(): [Path, boolean, boolean][] {\n    return [...this.store.entries()].map(([path, n]) => [\n      path,\n      !!(n & 2),\n      !!(n & 1),\n    ])\n  }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n  store: Map = new Map()\n  add(target: Path, pattern: Pattern) {\n    if (!target.canReaddir()) {\n      return\n    }\n    const subs = this.store.get(target)\n    if (subs) {\n      if (!subs.find(p => p.globString() === pattern.globString())) {\n        subs.push(pattern)\n      }\n    } else this.store.set(target, [pattern])\n  }\n  get(target: Path): Pattern[] {\n    const subs = this.store.get(target)\n    /* c8 ignore start */\n    if (!subs) {\n      throw new Error('attempting to walk unknown path')\n    }\n    /* c8 ignore stop */\n    return subs\n  }\n  entries(): [Path, Pattern[]][] {\n    return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n  }\n  keys(): Path[] {\n    return [...this.store.keys()].filter(t => t.canReaddir())\n  }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n  hasWalkedCache: HasWalkedCache\n  matches = new MatchRecord()\n  subwalks = new SubWalks()\n  patterns?: Pattern[]\n  follow: boolean\n  dot: boolean\n  opts: GlobWalkerOpts\n\n  constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n    this.opts = opts\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.hasWalkedCache = hasWalkedCache\n      ? hasWalkedCache.copy()\n      : new HasWalkedCache()\n  }\n\n  processPatterns(target: Path, patterns: Pattern[]) {\n    this.patterns = patterns\n    const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n    // map of paths to the magic-starting subwalks they need to walk\n    // first item in patterns is the filter\n\n    for (let [t, pattern] of processingSet) {\n      this.hasWalkedCache.storeWalked(t, pattern)\n\n      const root = pattern.root()\n      const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n      // start absolute patterns at root\n      if (root) {\n        t = t.resolve(\n          root === '/' && this.opts.root !== undefined\n            ? this.opts.root\n            : root\n        )\n        const rest = pattern.rest()\n        if (!rest) {\n          this.matches.add(t, true, false)\n          continue\n        } else {\n          pattern = rest\n        }\n      }\n\n      if (t.isENOENT()) continue\n\n      let p: MMPattern\n      let rest: Pattern | null\n      let changed = false\n      while (\n        typeof (p = pattern.pattern()) === 'string' &&\n        (rest = pattern.rest())\n      ) {\n        const c = t.resolve(p)\n        t = c\n        pattern = rest\n        changed = true\n      }\n      p = pattern.pattern()\n      rest = pattern.rest()\n      if (changed) {\n        if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n        this.hasWalkedCache.storeWalked(t, pattern)\n      }\n\n      // now we have either a final string for a known entry,\n      // more strings for an unknown entry,\n      // or a pattern starting with magic, mounted on t.\n      if (typeof p === 'string') {\n        // must not be final entry, otherwise we would have\n        // concatenated it earlier.\n        const ifDir = p === '..' || p === '' || p === '.'\n        this.matches.add(t.resolve(p), absolute, ifDir)\n        continue\n      } else if (p === GLOBSTAR) {\n        // if no rest, match and subwalk pattern\n        // if rest, process rest and subwalk pattern\n        // if it's a symlink, but we didn't get here by way of a\n        // globstar match (meaning it's the first time THIS globstar\n        // has traversed a symlink), then we follow it. Otherwise, stop.\n        if (\n          !t.isSymbolicLink() ||\n          this.follow ||\n          pattern.checkFollowGlobstar()\n        ) {\n          this.subwalks.add(t, pattern)\n        }\n        const rp = rest?.pattern()\n        const rrest = rest?.rest()\n        if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n          // only HAS to be a dir if it ends in **/ or **/.\n          // but ending in ** will match files as well.\n          this.matches.add(t, absolute, rp === '' || rp === '.')\n        } else {\n          if (rp === '..') {\n            // this would mean you're matching **/.. at the fs root,\n            // and no thanks, I'm not gonna test that specific case.\n            /* c8 ignore start */\n            const tp = t.parent || t\n            /* c8 ignore stop */\n            if (!rrest) this.matches.add(tp, absolute, true)\n            else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n              this.subwalks.add(tp, rrest)\n            }\n          }\n        }\n      } else if (p instanceof RegExp) {\n        this.subwalks.add(t, pattern)\n      }\n    }\n\n    return this\n  }\n\n  subwalkTargets(): Path[] {\n    return this.subwalks.keys()\n  }\n\n  child() {\n    return new Processor(this.opts, this.hasWalkedCache)\n  }\n\n  // return a new Processor containing the subwalks for each\n  // child entry, and a set of matches, and\n  // a hasWalkedCache that's a copy of this one\n  // then we're going to call\n  filterEntries(parent: Path, entries: Path[]): Processor {\n    const patterns = this.subwalks.get(parent)\n    // put matches and entry walks into the results processor\n    const results = this.child()\n    for (const e of entries) {\n      for (const pattern of patterns) {\n        const absolute = pattern.isAbsolute()\n        const p = pattern.pattern()\n        const rest = pattern.rest()\n        if (p === GLOBSTAR) {\n          results.testGlobstar(e, pattern, rest, absolute)\n        } else if (p instanceof RegExp) {\n          results.testRegExp(e, p, rest, absolute)\n        } else {\n          results.testString(e, p, rest, absolute)\n        }\n      }\n    }\n    return results\n  }\n\n  testGlobstar(\n    e: Path,\n    pattern: Pattern,\n    rest: Pattern | null,\n    absolute: boolean\n  ) {\n    if (this.dot || !e.name.startsWith('.')) {\n      if (!pattern.hasMore()) {\n        this.matches.add(e, absolute, false)\n      }\n      if (e.canReaddir()) {\n        // if we're in follow mode or it's not a symlink, just keep\n        // testing the same pattern. If there's more after the globstar,\n        // then this symlink consumes the globstar. If not, then we can\n        // follow at most ONE symlink along the way, so we mark it, which\n        // also checks to ensure that it wasn't already marked.\n        if (this.follow || !e.isSymbolicLink()) {\n          this.subwalks.add(e, pattern)\n        } else if (e.isSymbolicLink()) {\n          if (rest && pattern.checkFollowGlobstar()) {\n            this.subwalks.add(e, rest)\n          } else if (pattern.markFollowGlobstar()) {\n            this.subwalks.add(e, pattern)\n          }\n        }\n      }\n    }\n    // if the NEXT thing matches this entry, then also add\n    // the rest.\n    if (rest) {\n      const rp = rest.pattern()\n      if (\n        typeof rp === 'string' &&\n        // dots and empty were handled already\n        rp !== '..' &&\n        rp !== '' &&\n        rp !== '.'\n      ) {\n        this.testString(e, rp, rest.rest(), absolute)\n      } else if (rp === '..') {\n        /* c8 ignore start */\n        const ep = e.parent || e\n        /* c8 ignore stop */\n        this.subwalks.add(ep, rest)\n      } else if (rp instanceof RegExp) {\n        this.testRegExp(e, rp, rest.rest(), absolute)\n      }\n    }\n  }\n\n  testRegExp(\n    e: Path,\n    p: MMRegExp,\n    rest: Pattern | null,\n    absolute: boolean\n  ) {\n    if (!p.test(e.name)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n\n  testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n    // should never happen?\n    if (!e.isNamed(p)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n}\n","/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport { Ignore, IgnoreLike } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed?  that'd speed\n// things up a lot.  Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport { Pattern } from './pattern.js'\nimport { Processor } from './processor.js'\n\nexport interface GlobWalkerOpts {\n  absolute?: boolean\n  allowWindowsEscape?: boolean\n  cwd?: string | URL\n  dot?: boolean\n  dotRelative?: boolean\n  follow?: boolean\n  ignore?: string | string[] | IgnoreLike\n  mark?: boolean\n  matchBase?: boolean\n  // Note: maxDepth here means \"maximum actual Path.depth()\",\n  // not \"maximum depth beyond cwd\"\n  maxDepth?: number\n  nobrace?: boolean\n  nocase?: boolean\n  nodir?: boolean\n  noext?: boolean\n  noglobstar?: boolean\n  platform?: NodeJS.Platform\n  posix?: boolean\n  realpath?: boolean\n  root?: string\n  stat?: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape?: boolean\n  withFileTypes?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n  withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n  withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n  withFileTypes?: undefined\n}\n\nexport type Result = O extends GWOFileTypesTrue\n  ? Path\n  : O extends GWOFileTypesFalse\n  ? string\n  : O extends GWOFileTypesUnset\n  ? string\n  : Path | string\n\nexport type Matches = O extends GWOFileTypesTrue\n  ? Set\n  : O extends GWOFileTypesFalse\n  ? Set\n  : O extends GWOFileTypesUnset\n  ? Set\n  : Set\n\nexport type MatchStream =\n  O extends GWOFileTypesTrue\n    ? Minipass\n    : O extends GWOFileTypesFalse\n    ? Minipass\n    : O extends GWOFileTypesUnset\n    ? Minipass\n    : Minipass\n\nconst makeIgnore = (\n  ignore: string | string[] | IgnoreLike,\n  opts: GlobWalkerOpts\n): IgnoreLike =>\n  typeof ignore === 'string'\n    ? new Ignore([ignore], opts)\n    : Array.isArray(ignore)\n    ? new Ignore(ignore, opts)\n    : ignore\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil {\n  path: Path\n  patterns: Pattern[]\n  opts: O\n  seen: Set = new Set()\n  paused: boolean = false\n  aborted: boolean = false\n  #onResume: (() => any)[] = []\n  #ignore?: IgnoreLike\n  #sep: '\\\\' | '/'\n  signal?: AbortSignal\n  maxDepth: number\n\n  constructor(patterns: Pattern[], path: Path, opts: O)\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    this.patterns = patterns\n    this.path = path\n    this.opts = opts\n    this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n    if (opts.ignore) {\n      this.#ignore = makeIgnore(opts.ignore, opts)\n    }\n    // ignore, always set with maxDepth, but it's optional on the\n    // GlobOptions type\n    /* c8 ignore start */\n    this.maxDepth = opts.maxDepth || Infinity\n    /* c8 ignore stop */\n    if (opts.signal) {\n      this.signal = opts.signal\n      this.signal.addEventListener('abort', () => {\n        this.#onResume.length = 0\n      })\n    }\n  }\n\n  #ignored(path: Path): boolean {\n    return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n  }\n  #childrenIgnored(path: Path): boolean {\n    return !!this.#ignore?.childrenIgnored?.(path)\n  }\n\n  // backpressure mechanism\n  pause() {\n    this.paused = true\n  }\n  resume() {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return\n    /* c8 ignore stop */\n    this.paused = false\n    let fn: (() => any) | undefined = undefined\n    while (!this.paused && (fn = this.#onResume.shift())) {\n      fn()\n    }\n  }\n  onResume(fn: () => any) {\n    if (this.signal?.aborted) return\n    /* c8 ignore start */\n    if (!this.paused) {\n      fn()\n    } else {\n      /* c8 ignore stop */\n      this.#onResume.push(fn)\n    }\n  }\n\n  // do the requisite realpath/stat checking, and return the path\n  // to add or undefined to filter it out.\n  async matchCheck(e: Path, ifDir: boolean): Promise {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || (await e.realpath())\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    return this.matchCheckTest(needStat ? await e.lstat() : e, ifDir)\n  }\n\n  matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n    return e &&\n      (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n      (!ifDir || e.canReaddir()) &&\n      (!this.opts.nodir || !e.isDirectory()) &&\n      !this.#ignored(e)\n      ? e\n      : undefined\n  }\n\n  matchCheckSync(e: Path, ifDir: boolean): Path | undefined {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || e.realpathSync()\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    return this.matchCheckTest(needStat ? e.lstatSync() : e, ifDir)\n  }\n\n  abstract matchEmit(p: Result): void\n  abstract matchEmit(p: string | Path): void\n\n  matchFinish(e: Path, absolute: boolean) {\n    if (this.#ignored(e)) return\n    const abs =\n      this.opts.absolute === undefined ? absolute : this.opts.absolute\n    this.seen.add(e)\n    const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n    // ok, we have what we need!\n    if (this.opts.withFileTypes) {\n      this.matchEmit(e)\n    } else if (abs) {\n      const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n      this.matchEmit(abs + mark)\n    } else {\n      const rel = this.opts.posix ? e.relativePosix() : e.relative()\n      const pre =\n        this.opts.dotRelative && !rel.startsWith('..' + this.#sep)\n          ? '.' + this.#sep\n          : ''\n      this.matchEmit(!rel ? '.' + mark : pre + rel + mark)\n    }\n  }\n\n  async match(e: Path, absolute: boolean, ifDir: boolean): Promise {\n    const p = await this.matchCheck(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n    const p = this.matchCheckSync(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  walkCB(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const childrenCached = t.readdirCached()\n      if (t.calledReaddir())\n        this.walkCB3(t, childrenCached, processor, next)\n      else {\n        t.readdirCB(\n          (_, entries) => this.walkCB3(t, entries, processor, next),\n          true\n        )\n      }\n    }\n\n    next()\n  }\n\n  walkCB3(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n\n  walkCBSync(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2Sync(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() =>\n        this.walkCB2Sync(target, patterns, processor, cb)\n      )\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const children = t.readdirSync()\n      this.walkCB3Sync(t, children, processor, next)\n    }\n\n    next()\n  }\n\n  walkCB3Sync(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2Sync(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n}\n\nexport class GlobWalker<\n  O extends GlobWalkerOpts = GlobWalkerOpts\n> extends GlobUtil {\n  matches: O extends GWOFileTypesTrue\n    ? Set\n    : O extends GWOFileTypesFalse\n    ? Set\n    : O extends GWOFileTypesUnset\n    ? Set\n    : Set\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n    this.matches = new Set() as Matches\n  }\n\n  matchEmit(e: Result): void\n  matchEmit(e: Path | string): void {\n    this.matches.add(e)\n  }\n\n  async walk(): Promise> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      await this.path.lstat()\n    }\n    await new Promise((res, rej) => {\n      this.walkCB(this.path, this.patterns, () => {\n        if (this.signal?.aborted) {\n          rej(this.signal.reason)\n        } else {\n          res(this.matches)\n        }\n      })\n    })\n    return this.matches\n  }\n\n  walkSync(): Matches {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    // nothing for the callback to do, because this never pauses\n    this.walkCBSync(this.path, this.patterns, () => {\n      if (this.signal?.aborted) throw this.signal.reason\n    })\n    return this.matches\n  }\n}\n\nexport class GlobStream<\n  O extends GlobWalkerOpts = GlobWalkerOpts\n> extends GlobUtil {\n  results: O extends GWOFileTypesTrue\n    ? Minipass\n    : O extends GWOFileTypesFalse\n    ? Minipass\n    : O extends GWOFileTypesUnset\n    ? Minipass\n    : Minipass\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n    this.results = new Minipass({\n      signal: this.signal,\n      objectMode: true,\n    }) as MatchStream\n    this.results.on('drain', () => this.resume())\n    this.results.on('resume', () => this.resume())\n  }\n\n  matchEmit(e: Result): void\n  matchEmit(e: Path | string): void {\n    this.results.write(e)\n    if (!this.results.flowing) this.pause()\n  }\n\n  stream(): MatchStream {\n    const target = this.path\n    if (target.isUnknown()) {\n      target.lstat().then(() => {\n        this.walkCB(target, this.patterns, () => this.results.end())\n      })\n    } else {\n      this.walkCB(target, this.patterns, () => this.results.end())\n    }\n    return this.results\n  }\n\n  streamSync(): MatchStream {\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    this.walkCBSync(this.path, this.patterns, () => this.results.end())\n    return this.results\n  }\n}\n","import { Minimatch } from 'minimatch'\nimport { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n  pattern: string | string[],\n  options: GlobOptions = {}\n): boolean => {\n  if (!Array.isArray(pattern)) {\n    pattern = [pattern]\n  }\n  for (const p of pattern) {\n    if (new Minimatch(p, options).hasMagic()) return true\n  }\n  return false\n}\n","import { escape, unescape } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesUnset\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions\n): Minipass | Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions = {}\n) {\n  return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions\n): Minipass | Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions = {}\n) {\n  return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue\n): Path[]\nexport function globSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions\n): Path[] | string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions = {}\n) {\n  return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions = {}\n) {\n  return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions\n): Generator | Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions = {}\n) {\n  return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions\n): AsyncGenerator | AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions = {}\n) {\n  return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n  sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n  stream: globStreamSync,\n  iterate: globIterateSync,\n})\n\n/* c8 ignore start */\nexport { escape, unescape } from 'minimatch'\nexport { Glob } from './glob.js'\nexport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\nexport type {\n  Path,\n  WalkOptionsWithFileTypesTrue,\n  WalkOptionsWithFileTypesUnset,\n  WalkOptions,\n  FSOption,\n} from 'path-scurry'\n\n/* c8 ignore stop */\n\nexport const glob = Object.assign(glob_, {\n  glob: glob_,\n  globSync,\n  sync,\n  globStream,\n  stream,\n  globStreamSync,\n  streamSync,\n  globIterate,\n  iterate,\n  globIterateSync,\n  iterateSync,\n  Glob,\n  hasMagic,\n  escape,\n  unescape,\n})\nglob.glob = glob\n","import { createUnplugin } from 'unplugin';\nimport dedent from 'ts-dedent';\nimport { logger } from '@storybook/node-logger';\nimport { extractComponentsFromTemplate } from './extractComponentsFromTemplate';\nimport { TwigComponentConfiguration } from './symfony';\nimport { TwigComponentResolver } from './TwigComponentResolver';\nimport crypto from 'crypto';\n\nconst PLUGIN_NAME = 'twig-loader';\n\nexport type Options = {\n    twigComponentConfiguration: TwigComponentConfiguration;\n};\n\n/**\n * Twig template source loader.\n *\n * Generates JS modules to export raw template source and imports required components.\n */\nexport const TwigLoaderPlugin = createUnplugin((options) => {\n    const { twigComponentConfiguration } = options;\n    const resolver = new TwigComponentResolver(twigComponentConfiguration);\n    return {\n        name: PLUGIN_NAME,\n        enforce: 'pre',\n        transformInclude: (id) => {\n            return /\\.html\\.twig$/.test(id);\n        },\n        transform: async (code, id) => {\n            const imports: string[] = [];\n\n            try {\n                const components = new Set(extractComponentsFromTemplate(code));\n\n                components.forEach((name) => {\n                    imports.push(resolver.resolveFileFromName(name));\n                });\n            } catch (err) {\n                logger.warn(dedent`\n                Failed to parse template in '${id}': ${err}\n                `);\n            }\n\n            const name = resolver.resolveNameFromFile(id);\n\n            return dedent`\n            ${imports.map((file) => `import '${file}';`).join('\\n')}\n            export default {\n                name: \\'${name}\\',\n                hash: \\`${crypto.createHash('sha1').update(code).digest('hex')}\\`,\n            };\n           `;\n        },\n    };\n});\n","import { XMLParser } from 'fast-xml-parser';\n\nexport const extractComponentsFromTemplate = (source: string) => {\n    const reservedNames = ['block'];\n    const tagRe = new RegExp(/twig:[A-Za-z]+(?::[A-Za-z]+)*/);\n    const functionRe = new RegExp(/component\\(\\s*'([A-Za-z]+(?::[A-Za-z]+)*)'\\s*(?:,.*)?\\)/, 'gs');\n\n    const lookupComponents = (obj: { [p: string]: any }): string[] => {\n        return Object.entries(obj).reduce((names, [key, value]) => {\n            if (value !== null && typeof value === 'object') {\n                names.push(...lookupComponents(value));\n            } else if (typeof value === 'string') {\n                for (const m of value.matchAll(functionRe)) {\n                    names.push([...m][1]);\n                }\n            }\n            if (tagRe.test(key)) {\n                names.push(key.replace('twig:', ''));\n            }\n            return names;\n        }, [] as string[]);\n    };\n\n    try {\n        // Dummy div tag to handle templates without any tag\n        const documentObj = new XMLParser().parse(`
${source}
`);\n\n return lookupComponents(documentObj).filter((name) => !reservedNames.includes(name));\n } catch (err) {\n throw new Error('Invalid XML.', {\n cause: {\n parserError: err,\n template: source,\n },\n });\n }\n};\n","import { TwigComponentConfiguration } from './symfony';\nimport path from 'path';\nimport dedent from 'ts-dedent';\n\nexport class TwigComponentResolver {\n constructor(private config: TwigComponentConfiguration) {}\n\n resolveNameFromFile(file: string) {\n const stripDirectory = (file: string, dir: string) => {\n return file.replace(dir, '').replace(/^\\//, '').replaceAll('/', ':').replace('.html.twig', '');\n };\n\n for (const [namespace, twigDirectories] of Object.entries(this.config.namespaces)) {\n const matchingDirectory = twigDirectories.find((dir) => file.startsWith(dir));\n if (matchingDirectory) {\n const trimmedPath = stripDirectory(file, matchingDirectory);\n return namespace ? `${namespace}:${trimmedPath}` : trimmedPath;\n }\n }\n\n for (const anonymousDir of this.config.anonymousTemplateDirectory) {\n if (file.startsWith(anonymousDir)) {\n return stripDirectory(file, anonymousDir);\n }\n }\n\n throw new Error(dedent`Unable to determine template name for file \"${file}\":`);\n }\n\n resolveFileFromName(name: string) {\n const nameParts = name.split(':');\n const namespace = nameParts.length > 1 ? nameParts[0] : '';\n const dirParts = nameParts.slice(0, -1);\n const filename = `${nameParts.slice(-1)}.html.twig`;\n\n const lookupPaths: string[] = [];\n\n if (namespace && this.config.namespaces[namespace]) {\n const namespacePaths = this.config.namespaces[namespace];\n if (namespacePaths.length > 0) {\n for (const namespacePath of this.config.namespaces[namespace]) {\n lookupPaths.push(path.join(namespacePath, dirParts.slice(1).join('/')));\n }\n }\n }\n\n if (this.config.namespaces[''] && this.config.namespaces[''].length > 0) {\n for (const namespacePath of this.config.namespaces['']) {\n lookupPaths.push(path.join(namespacePath, dirParts.join('/')));\n }\n }\n\n if (this.config.anonymousTemplateDirectory.length > 0) {\n for (const namespacePath of this.config.anonymousTemplateDirectory) {\n lookupPaths.push(path.join(namespacePath, dirParts.join('/')));\n }\n }\n\n try {\n return require.resolve(`./${filename}`, { paths: lookupPaths });\n } catch (err) {\n throw new Error(dedent`Unable to find template file for component \"${name}\": ${err}`);\n }\n }\n}\n"]} \ No newline at end of file +{"version":3,"sources":["../../node_modules/webpack-virtual-modules/src/virtual-stats.ts","../../node_modules/webpack-virtual-modules/src/index.ts","../../node_modules/is-extglob/index.js","../../node_modules/is-glob/index.js","../../node_modules/balanced-match/index.js","../../node_modules/brace-expansion/index.js","../../node_modules/fast-xml-parser/src/util.js","../../node_modules/fast-xml-parser/src/validator.js","../../node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js","../../node_modules/fast-xml-parser/src/xmlparser/xmlNode.js","../../node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js","../../node_modules/strnum/strnum.js","../../node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js","../../node_modules/fast-xml-parser/src/xmlparser/node2json.js","../../node_modules/fast-xml-parser/src/xmlparser/XMLParser.js","../../node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js","../../node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js","../../node_modules/fast-xml-parser/src/fxp.js","../../src/server/lib/symfony.ts","../../src/server/framework-preset.ts","../../src/server/lib/preview-compiler-plugin.ts","../../node_modules/ts-dedent/src/index.ts","../../src/server/lib/injectPreviewHtml.ts","../../src/server/lib/dev-preview-compiler-plugin.ts","../../src/server/lib/computeAdditionalWatchPaths.ts","../../node_modules/glob/node_modules/minimatch/src/index.ts","../../node_modules/glob/node_modules/minimatch/src/assert-valid-pattern.ts","../../node_modules/glob/node_modules/minimatch/src/brace-expressions.ts","../../node_modules/glob/node_modules/minimatch/src/unescape.ts","../../node_modules/glob/node_modules/minimatch/src/ast.ts","../../node_modules/glob/node_modules/minimatch/src/escape.ts","../../node_modules/lru-cache/src/index.ts","../../node_modules/path-scurry/src/index.ts","../../node_modules/minipass/src/index.ts","../../node_modules/glob/src/glob.ts","../../node_modules/glob/src/pattern.ts","../../node_modules/glob/src/ignore.ts","../../node_modules/glob/src/processor.ts","../../node_modules/glob/src/walker.ts","../../node_modules/glob/src/has-magic.ts","../../node_modules/glob/src/index.ts","../../src/server/lib/twig-loader-plugin.ts","../../src/server/lib/extractComponentsFromTemplate.ts","../../src/server/lib/TwigComponentResolver.ts"],"names":["constants_1","__importDefault","VirtualStats","config","key","property","exports","path_1","virtual_stats_1","inode","ALL","STATIC","DYNAMIC","checkActivation","instance","getModulePath","filePath","compiler","createWebpackData","result","backendOrStorage","curLevelIdx","curLevel","getData","storage","setData","valueFactory","value","getStatStorage","fileSystem","getFileStorage","getReadDirBackend","VirtualModulesPlugin","modules","filter","shouldGetStaticModules","shouldGetDynamicModules","finalInputFileSystem","_a","virtualFiles","_b","dynamicModules","contents","len","time","date","stats","modulePath","finalWatchFileSystem","fileWatchers","fileWatcher","afterEnvironmentHook","originalPurge","file","data","statStorage","fileStorage","readDirStorage","segments","count","minCount","dir","dirStats","dirData","filename","files","afterResolversHook","version","watchRunHook","watcher","callback","fts","mtime","module","require_is_extglob","__commonJSMin","str","match","require_is_glob","isExtglob","chars","strictCheck","index","pipeIndex","closeSquareIndex","closeCurlyIndex","closeParenIndex","backSlashIndex","open","close","n","relaxedCheck","options","check","require_balanced_match","balanced","a","b","maybeMatch","r","range","reg","m","begs","beg","left","right","ai","bi","i","require_brace_expansion","expandTop","escSlash","escOpen","escClose","escComma","escPeriod","numeric","escapeBraces","unescapeBraces","parseCommaParts","parts","pre","body","post","p","postParts","expand","embrace","isPadded","el","lte","y","gte","isTop","expansions","k","expansion","isNumericSequence","isAlphaSequence","isSequence","isOptions","N","x","width","incr","test","reverse","pad","c","need","z","j","require_util","nameStartChar","nameChar","nameRegexp","regexName","getAllMatches","string","regex","matches","allmatches","isName","v","obj","target","arrayMode","keys","require_validator","util","defaultOptions","xmlData","tags","tagFound","reachedRoot","readPI","tagStartPos","readCommentAndCDATA","closingTag","tagName","validateTagName","msg","getErrorObject","getLineNumberForPosition","readAttributeStr","attrStr","attrStrStart","isValid","validateAttributeString","otg","openPos","afterAmp","validateAmpersand","isWhiteSpace","t","char","start","tagname","angleBracketsCount","doubleQuote","singleQuote","startChar","tagClosed","validAttrStrRegxp","attrNames","getPositionFromMatch","attrName","validateAttrName","validateNumberAmpersand","re","code","message","lineNumber","lines","require_OptionsBuilder","val","jPath","attrs","buildOptions","require_xmlNode","XmlNode","node","require_DocTypeReader","readDocType","entities","hasBody","comment","exp","isEntity","readEntityExp","validateEntityName","isElement","isAttlist","isNotation","isComment","entityName","name","require_strnum","hexRegex","numRegex","consider","toNumber","trimmedStr","sign","leadingZeros","numTrimmedByZeros","trimZeros","eNotation","num","numStr","require_OrderedObjParser","xmlNode","OrderedObjParser","_","addExternalEntities","parseXml","parseTextData","resolveNameSpace","buildAttributesMap","isItStopNode","replaceEntitiesValue","readStopNodeData","saveTextToParentTag","addChild","externalEntities","entKeys","ent","dontTrim","hasAttributes","isLeafNode","escapeEntities","newval","parseValue","prefix","attrsRegx","oldVal","aName","newVal","attrCollection","xmlObj","currentNode","textData","closeIndex","findClosingIndex","colonIndex","lastTagName","propIndex","tagData","readTagExp","childNode","endIndex","tagExp","rawTagName","attrExpPresent","lastTag","tagContent","entity","stopNodes","currentTagName","allNodesExp","stopNodePath","stopNodeExp","tagExpWithClosingIndex","closingChar","attrBoundary","ch","errMsg","closingIndex","removeNSPrefix","separatorIndex","startIndex","openTagCount","shouldParse","require_node2json","prettify","compress","arr","text","compressedObj","tagObj","propName","newJpath","isLeaf","isLeafTag","assignAttributes","attrMap","jpath","atrrName","textNodeName","propCount","require_XMLParser","validator","XMLParser","validationOption","orderedObjParser","orderedResult","require_orderedJs2Xml","EOL","toXml","jArray","indentation","arrToStr","xmlStr","isPreviousElementTag","newJPath","tagText","isStopNode","attStr","attr_to_str","tempInd","piTextNodeName","newIdentation","tagStart","tagValue","attr","attrVal","textValue","require_json2xml","buildFromOrderedJs","Builder","isAttribute","processTextOrObjNode","indentate","jObj","level","arrLen","listTagVal","item","Ks","L","object","tagEndExp","piClosingChar","closeTag","require_fxp","XMLBuilder","fs","SymfonyPreviewRenderingError","errorPage","generateSymfonyPreview","server","fetchUrl","response","html","getSymfonyConfig","storybookCachePath","join","resolve","createUnplugin","HtmlWebpackPlugin","logger","dedent","templ","values","_i","strings","indentLengths","pattern_1","endentations","endentation","indentedValue","esm_default","JSDOM","injectPreviewHtml","previewHtml","targetHtml","previewDom","previewHead","previewBody","PLUGIN_NAME","PreviewCompilerPlugin","compilation","params","err","import_webpack_virtual_modules","import_is_glob","import_brace_expansion","assertValidPattern","pattern","posixClasses","braceEscape","regexpEscape","rangesToString","ranges","parseClass","glob","position","pos","negs","sawStart","uflag","escaping","negate","endPos","rangeStart","WHILE","cls","unip","u","neg","sranges","snegs","unescape","windowsPathsNoEscape","types","isExtglobType","startNoTraversal","startNoDot","addPatternStart","justDots","reSpecials","regExpEscape","qmark","star","starNoEmpty","AST","_AST","#root","#hasMagic","#uflag","#parts","#parent","#parentIndex","#negs","#filledNegs","#options","#toString","#emptyExt","type","parent","#fillNegs","pp","part","ret","pl","#parseAST","ast","opt","inBrace","braceStart","braceNeg","acc","ext","hasMagic","flags","allowDot","dot","noEmpty","src","#parseGlob","aps","needNoTrav","needNoDot","end","repeated","#partsToRegExp","s","bodyDotAllowed","final","_hasMagic","needUflag","consumed","magic","escape","minimatch","Minimatch","starDotExtRE","starDotExtTest","f","starDotExtTestDot","starDotExtTestNocase","starDotExtTestNocaseDot","starDotStarRE","starDotStarTest","starDotStarTestDot","dotStarRE","dotStarTest","starRE","starTest","starTestDot","qmarksRE","qmarksTestNocase","$0","noext","qmarksTestNoExt","qmarksTestNocaseDot","qmarksTestNoExtDot","qmarksTestDot","qmarksTest","defaultPlatform","path","sep","GLOBSTAR","twoStarDot","twoStarNoDot","defaults","def","orig","list","braceExpand","makeRe","mm","globMagic","args","rawGlobParts","set","__","isUNC","isDrive","ss","globParts","optimizationLevel","gs","prev","didSomething","dd","gss","next","p2","other","splin","matched","emptyGSMatch","which","negateOffset","partial","fileDrive","fileUNC","patternDrive","patternUNC","fdi","pdi","fd","pd","fi","pi","fl","fr","pr","swallowee","hit","fastTest","twoStar","ff","perf","warned","PROCESS","emitWarning","fn","AC","AS","warnACPolyfill","reason","printACPolyfillWarning","shouldWarn","TYPE","isPosInt","getUintArray","max","ZeroArray","size","Stack","_Stack","#constructing","HeapCls","LRUCache","_LRUCache","#max","#maxSize","#dispose","#disposeAfter","#fetchMethod","#size","#calculatedSize","#keyMap","#keyList","#valList","#next","#prev","#head","#tail","#free","#disposed","#sizes","#starts","#ttls","#hasDispose","#hasFetchMethod","#hasDisposeAfter","#isBackgroundFetch","context","#backgroundFetch","#moveToTail","#indexes","#rindexes","#isStale","ttl","ttlResolution","ttlAutopurge","updateAgeOnGet","updateAgeOnHas","allowStale","dispose","disposeAfter","noDisposeOnSet","noUpdateTTL","maxSize","maxEntrySize","sizeCalculation","fetchMethod","noDeleteOnFetchRejection","noDeleteOnStaleGet","allowStaleOnFetchRejection","allowStaleOnFetchAbort","ignoreFetchAbort","UintArray","#initializeSizeTracking","#initializeTTLTracking","ttls","starts","#setItemTTL","#updateItemAge","#statusTTL","status","cachedNow","getNow","age","sizes","#removeItemSize","#requireSize","#addItemSize","#evict","_s","_st","_k","_v","#isValidIndex","getOptions","thisp","deleted","entry","remain","setOptions","oldValue","dt","task","free","head","hasOptions","peekOptions","ac","signal","fetchOpts","cb","updateCache","aborted","ignoreAbort","fetchFail","bf","eb","er","allowStaleAborted","noDelete","pcall","res","rej","fmp","fetchOptions","forceRefresh","stale","isStale","staleVal","fetching","#connect","ni","posix","win32","fileURLToPath","actualFS","lstatSync","readdirCB","readdirSync","readlinkSync","rps","lstat","readdir","readlink","realpath","EventEmitter","Stream","StringDecoder","proc","isStream","Minipass","isReadable","isWritable","EOF","MAYBE_EMIT_END","EMITTED_END","EMITTING_END","EMITTED_ERROR","CLOSED","READ","FLUSH","FLUSHCHUNK","ENCODING","DECODER","FLOWING","PAUSED","RESUME","BUFFER","PIPES","BUFFERLENGTH","BUFFERPUSH","BUFFERSHIFT","OBJECTMODE","DESTROYED","ERROR","EMITDATA","EMITEND","EMITEND2","ASYNC","ABORT","ABORTED","SIGNAL","DATALISTENERS","DISCARDED","defer","nodefer","isEndish","ev","isArrayBufferLike","isArrayBufferView","Pipe","dest","opts","_er","PipeProxyErrors","isObjectModeOptions","o","isEncodingOptions","_enc","_om","chunk","encoding","noDrain","ended","handler","h","buf","reject","stopped","stop","onerr","ondata","onend","ondestroy","wc","realpathSync","defaultFS","fsFromOption","fsOption","uncDriveRegexp","uncToDrive","rootPath","eitherSep","UNKNOWN","IFIFO","IFCHR","IFDIR","IFBLK","IFREG","IFLNK","IFSOCK","IFMT","IFMT_UNKNOWN","READDIR_CALLED","LSTAT_CALLED","ENOTDIR","ENOENT","ENOREADLINK","ENOREALPATH","ENOCHILD","TYPEMASK","entToType","normalizeCache","normalize","normalizeNocaseCache","normalizeNocase","ResolveCache","ChildrenCache","setAsCwd","PathBase","#fs","#dev","#mode","#nlink","#uid","#gid","#rdev","#blksize","#ino","#blocks","#atimeMs","#mtimeMs","#ctimeMs","#birthtimeMs","#atime","#mtime","#ctime","#birthtime","#matchName","#depth","#fullpath","#fullpathPosix","#relative","#relativePosix","#type","#children","#linkTarget","#realpath","root","roots","nocase","children","dirParts","#resolveParts","cached","pathPart","fullpath","pchild","pv","fp","pfpp","fpp","ifmt","read","linkTarget","#readlinkFail","#readdirSuccess","#markENOENT","#markChildrenENOENT","#markENOREALPATH","#markENOTDIR","#readdirFail","#lstatFail","ter","#readdirAddChild","e","#readdirMaybePromoteChild","#readdirAddNewChild","child","#readdirPromoteChild","#applyStat","st","atime","atimeMs","birthtime","birthtimeMs","blksize","blocks","ctime","ctimeMs","dev","gid","ino","mode","mtimeMs","nlink","rdev","uid","#onReaddirCB","#readdirCBInFlight","#callOnReaddirCB","cbs","allowZalgo","entries","#asyncReaddirInFlight","dirs","walkFilter","rp","oldCwd","changed","PathWin32","_PathWin32","compare","PathScurryWin32","PathPosix","_PathPosix","_rootPath","PathScurryBase","#resolveCache","#resolvePosixCache","cwd","pathImpl","childrenCacheSize","cwdPath","split","joinSep","abs","sawFirst","l","paths","withFileTypes","follow","results","walk","queue","processing","process","paused","onReaddir","didRealpaths","promises","sync","PathScurryPosix","_dir","PathScurryDarwin","Path","PathScurry","isPatternList","isGlobList","gl","Pattern","_Pattern","#patternList","#globList","#index","#platform","#rest","#globString","#isDrive","#isUNC","#isAbsolute","#followGlobstar","patternList","globList","platform","p0","p1","p3","prest","g0","g1","g2","g3","grest","g","Ignore","ignored","nobrace","noglobstar","mmopts","ign","parsed","absolute","fullpaths","relative","relatives","HasWalkedCache","_HasWalkedCache","store","MatchRecord","ifDir","current","SubWalks","subs","Processor","_Processor","hasWalkedCache","patterns","processingSet","rest","rrest","tp","ep","makeIgnore","ignore","GlobUtil","#onResume","#ignore","#sep","#ignored","#childrenIgnored","rpc","needStat","mark","rel","processor","tasks","childrenCached","GlobWalker","GlobStream","Glob","Scurry","nocaseMagicOnly","mmo","mms","matchSet","globStreamSync","globStream","globSync","glob_","globIterateSync","globIterate","streamSync","stream","iterateSync","iterate","computeAdditionalWatchPaths","baseDir","watchPath","absoluteWatchPath","isGlob","DevPreviewCompilerPlugin","projectDir","additionalWatchPaths","id","resolvedWatchPaths","import_fast_xml_parser","extractComponentsFromTemplate","source","reservedNames","tagRe","functionRe","lookupComponents","names","documentObj","TwigComponentResolver","stripDirectory","resolvedFile","namespace","twigDirectories","matchingDirectory","trimmedPath","anonymousDir","nameParts","lookupPaths","namespacePath","__require","crypto","TwigLoaderPlugin","twigComponentConfiguration","resolver","imports","getBuildOptions","symfonyOptions","twig_config","twig_component_config","componentNamespaces","twigPaths","namePrefix","templateDirectory","alias","webpack","framework","frameworkOptions","base"],"mappings":"w8BASA,IAAAA,EAAAC,GAAA,GAAA,WAAA,CAAA,EAEaC,GAA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AAsC,MAAOpkC,EAAQyF,IAAY,CAC1E,IAAM4+B,EAAY,MAAM5+B,EAAQ,QAAQ,MAAM,WAAW,EAEnD6+B,EAAmB,OAAOD,GAAc,SAAW,CAAC,EAAIA,EAAU,QAGlET,EAAiB,MAAMD,GAAgBW,EAAiB,OAAO,EAErE,MAAO,CACH,GAAGtkC,EACH,QAAS,CACL,GAAIA,EAAO,SAAW,CAAC,EAEnByF,EAAQ,aAAe,aACjB+T,GAAsB,QAAQ,CAC1B,OAAQ8qB,EAAiB,QAAQ,MACrC,CAAC,EACD1C,GAAyB,QAAQ,CAC7B,WAAY3pB,GAAQ,EACpB,OAAQqsB,EAAiB,QAAQ,OACjC,qBAAsBV,EAAe,oBACzC,CAAC,EACPL,GAAiB,QAAQ,CACrB,WAAYtrB,GAAQ,EACpB,2BAA4B2rB,EAAe,aAC/C,CAAC,CAET,EACA,OAAQ,CACJ,GAAG5jC,EAAO,OACV,MAAO,CAAC,GAAIA,EAAO,QAAQ,OAAS,CAAC,CAAE,CAC3C,CACJ,CACJ,EAEaqZ,GAA6C,MAAOkrB,GAAcxrB;AAAA,MACzEwrB,CAAI;AAAA;AAAA,MAIGjrB,GAA6C,MAAOirB,GAAcxrB;AAAA,MACzEwrB,CAAI;AAAA","sourcesContent":["/**\n * Used to cache a stats object for the virtual file.\n * Extracted from the `mock-fs` package.\n *\n * @author Tim Schaub http://tschaub.net/\n * @author `webpack-virtual-modules` Contributors\n * @link https://github.com/tschaub/mock-fs/blob/master/lib/binding.js\n * @link https://github.com/tschaub/mock-fs/blob/master/license.md\n */\nimport constants from 'constants';\n\nexport class VirtualStats {\n /**\n * Create a new stats object.\n *\n * @param config Stats properties.\n */\n public constructor(config) {\n for (const key in config) {\n if (!Object.prototype.hasOwnProperty.call(config, key)) {\n continue;\n }\n this[key] = config[key];\n }\n }\n\n /**\n * Check if mode indicates property.\n */\n private _checkModeProperty(property): boolean {\n return ((this as any).mode & constants.S_IFMT) === property;\n }\n\n public isDirectory(): boolean {\n return this._checkModeProperty(constants.S_IFDIR);\n }\n\n public isFile(): boolean {\n return this._checkModeProperty(constants.S_IFREG);\n }\n\n public isBlockDevice(): boolean {\n return this._checkModeProperty(constants.S_IFBLK);\n }\n\n public isCharacterDevice(): boolean {\n return this._checkModeProperty(constants.S_IFCHR);\n }\n\n public isSymbolicLink(): boolean {\n return this._checkModeProperty(constants.S_IFLNK);\n }\n\n public isFIFO(): boolean {\n return this._checkModeProperty(constants.S_IFIFO);\n }\n\n public isSocket(): boolean {\n return this._checkModeProperty(constants.S_IFSOCK);\n }\n}\n","import path from 'path';\nimport { VirtualStats } from './virtual-stats';\nimport type { Compiler } from 'webpack';\n\nlet inode = 45000000;\nconst ALL = 'all';\nconst STATIC = 'static';\nconst DYNAMIC = 'dynamic';\n\ntype AvailableModules = typeof ALL | typeof STATIC | typeof DYNAMIC;\n\nfunction checkActivation(instance) {\n if (!instance._compiler) {\n throw new Error('You must use this plugin only after creating webpack instance!');\n }\n}\n\nfunction getModulePath(filePath, compiler) {\n return path.isAbsolute(filePath) ? filePath : path.join(compiler.context, filePath);\n}\n\nfunction createWebpackData(result) {\n return (backendOrStorage) => {\n // In Webpack v5, this variable is a \"Backend\", and has the data stored in a field\n // _data. In V4, the `_` prefix isn't present.\n if (backendOrStorage._data) {\n const curLevelIdx = backendOrStorage._currentLevel;\n const curLevel = backendOrStorage._levels[curLevelIdx];\n return {\n result,\n level: curLevel,\n };\n }\n // Webpack 4\n return [null, result];\n };\n}\n\nfunction getData(storage, key) {\n // Webpack 5\n if (storage._data instanceof Map) {\n return storage._data.get(key);\n } else if (storage._data) {\n return storage.data[key];\n } else if (storage.data instanceof Map) {\n // Webpack v4\n return storage.data.get(key);\n } else {\n return storage.data[key];\n }\n}\n\nfunction setData(backendOrStorage, key, valueFactory) {\n const value = valueFactory(backendOrStorage);\n\n // Webpack v5\n if (backendOrStorage._data instanceof Map) {\n backendOrStorage._data.set(key, value);\n } else if (backendOrStorage._data) {\n backendOrStorage.data[key] = value;\n } else if (backendOrStorage.data instanceof Map) {\n // Webpack 4\n backendOrStorage.data.set(key, value);\n } else {\n backendOrStorage.data[key] = value;\n }\n}\n\nfunction getStatStorage(fileSystem) {\n if (fileSystem._statStorage) {\n // Webpack v4\n return fileSystem._statStorage;\n } else if (fileSystem._statBackend) {\n // webpack v5\n return fileSystem._statBackend;\n } else {\n // Unknown version?\n throw new Error(\"Couldn't find a stat storage\");\n }\n}\n\nfunction getFileStorage(fileSystem) {\n if (fileSystem._readFileStorage) {\n // Webpack v4\n return fileSystem._readFileStorage;\n } else if (fileSystem._readFileBackend) {\n // Webpack v5\n return fileSystem._readFileBackend;\n } else {\n throw new Error(\"Couldn't find a readFileStorage\");\n }\n}\n\nfunction getReadDirBackend(fileSystem) {\n if (fileSystem._readdirBackend) {\n return fileSystem._readdirBackend;\n } else if (fileSystem._readdirStorage) {\n return fileSystem._readdirStorage;\n } else {\n throw new Error(\"Couldn't find a readDirStorage from Webpack Internals\");\n }\n}\n\nclass VirtualModulesPlugin {\n private _staticModules: Record | null;\n private _compiler: Compiler | null = null;\n private _watcher: any = null;\n\n public constructor(modules?: Record) {\n this._staticModules = modules || null;\n }\n\n public getModuleList(filter: AvailableModules = ALL) {\n let modules = {};\n const shouldGetStaticModules = filter === ALL || filter === STATIC;\n const shouldGetDynamicModules = filter === ALL || filter === DYNAMIC;\n\n if (shouldGetStaticModules) {\n // Get static modules\n modules = {\n ...modules,\n ...this._staticModules,\n };\n }\n\n if (shouldGetDynamicModules) {\n // Get dynamic modules\n const finalInputFileSystem: any = this._compiler?.inputFileSystem;\n const virtualFiles = finalInputFileSystem?._virtualFiles ?? {};\n\n const dynamicModules: Record = {};\n Object.keys(virtualFiles).forEach((key: string) => {\n dynamicModules[key] = virtualFiles[key].contents;\n });\n\n modules = {\n ...modules,\n ...dynamicModules,\n };\n }\n\n return modules;\n }\n\n public writeModule(filePath: string, contents: string): void {\n if (!this._compiler) {\n throw new Error(`Plugin has not been initialized`);\n }\n\n checkActivation(this);\n\n const len = contents ? contents.length : 0;\n const time = Date.now();\n const date = new Date(time);\n\n const stats = new VirtualStats({\n dev: 8675309,\n nlink: 0,\n uid: 1000,\n gid: 1000,\n rdev: 0,\n blksize: 4096,\n ino: inode++,\n mode: 33188,\n size: len,\n blocks: Math.floor(len / 4096),\n atime: date,\n mtime: date,\n ctime: date,\n birthtime: date,\n });\n const modulePath = getModulePath(filePath, this._compiler);\n\n if (process.env.WVM_DEBUG)\n // eslint-disable-next-line no-console\n console.log(this._compiler.name, 'Write virtual module:', modulePath, contents);\n\n // When using the WatchIgnorePlugin (https://github.com/webpack/webpack/blob/52184b897f40c75560b3630e43ca642fcac7e2cf/lib/WatchIgnorePlugin.js),\n // the original watchFileSystem is stored in `wfs`. The following \"unwraps\" the ignoring\n // wrappers, giving us access to the \"real\" watchFileSystem.\n let finalWatchFileSystem = this._watcher && this._watcher.watchFileSystem;\n\n while (finalWatchFileSystem && finalWatchFileSystem.wfs) {\n finalWatchFileSystem = finalWatchFileSystem.wfs;\n }\n\n let finalInputFileSystem: any = this._compiler.inputFileSystem;\n while (finalInputFileSystem && finalInputFileSystem._inputFileSystem) {\n finalInputFileSystem = finalInputFileSystem._inputFileSystem;\n }\n\n finalInputFileSystem._writeVirtualFile(modulePath, stats, contents);\n if (\n finalWatchFileSystem &&\n finalWatchFileSystem.watcher &&\n (finalWatchFileSystem.watcher.fileWatchers.size || finalWatchFileSystem.watcher.fileWatchers.length)\n ) {\n const fileWatchers =\n finalWatchFileSystem.watcher.fileWatchers instanceof Map\n ? Array.from(finalWatchFileSystem.watcher.fileWatchers.values())\n : finalWatchFileSystem.watcher.fileWatchers;\n for (let fileWatcher of fileWatchers) {\n if ('watcher' in fileWatcher) {\n fileWatcher = fileWatcher.watcher;\n }\n if (fileWatcher.path === modulePath) {\n if (process.env.DEBUG)\n // eslint-disable-next-line no-console\n console.log(this._compiler.name, 'Emit file change:', modulePath, time);\n delete fileWatcher.directoryWatcher._cachedTimeInfoEntries;\n fileWatcher.emit('change', time, null);\n }\n }\n }\n }\n\n public apply(compiler: Compiler) {\n this._compiler = compiler;\n\n const afterEnvironmentHook = () => {\n let finalInputFileSystem: any = compiler.inputFileSystem;\n while (finalInputFileSystem && finalInputFileSystem._inputFileSystem) {\n finalInputFileSystem = finalInputFileSystem._inputFileSystem;\n }\n\n if (!finalInputFileSystem._writeVirtualFile) {\n const originalPurge = finalInputFileSystem.purge;\n\n finalInputFileSystem.purge = () => {\n originalPurge.apply(finalInputFileSystem, []);\n if (finalInputFileSystem._virtualFiles) {\n Object.keys(finalInputFileSystem._virtualFiles).forEach((file) => {\n const data = finalInputFileSystem._virtualFiles[file];\n finalInputFileSystem._writeVirtualFile(file, data.stats, data.contents);\n });\n }\n };\n\n finalInputFileSystem._writeVirtualFile = (file, stats, contents) => {\n const statStorage = getStatStorage(finalInputFileSystem);\n const fileStorage = getFileStorage(finalInputFileSystem);\n const readDirStorage = getReadDirBackend(finalInputFileSystem);\n finalInputFileSystem._virtualFiles = finalInputFileSystem._virtualFiles || {};\n finalInputFileSystem._virtualFiles[file] = { stats: stats, contents: contents };\n setData(statStorage, file, createWebpackData(stats));\n setData(fileStorage, file, createWebpackData(contents));\n const segments = file.split(/[\\\\/]/);\n let count = segments.length - 1;\n const minCount = segments[0] ? 1 : 0;\n while (count > minCount) {\n const dir = segments.slice(0, count).join(path.sep) || path.sep;\n try {\n finalInputFileSystem.readdirSync(dir);\n } catch (e) {\n const time = Date.now();\n const dirStats = new VirtualStats({\n dev: 8675309,\n nlink: 0,\n uid: 1000,\n gid: 1000,\n rdev: 0,\n blksize: 4096,\n ino: inode++,\n mode: 16877,\n size: stats.size,\n blocks: Math.floor(stats.size / 4096),\n atime: time,\n mtime: time,\n ctime: time,\n birthtime: time,\n });\n\n setData(readDirStorage, dir, createWebpackData([]));\n setData(statStorage, dir, createWebpackData(dirStats));\n }\n let dirData = getData(getReadDirBackend(finalInputFileSystem), dir);\n // Webpack v4 returns an array, webpack v5 returns an object\n dirData = dirData[1] || dirData.result;\n const filename = segments[count];\n if (dirData.indexOf(filename) < 0) {\n const files = dirData.concat([filename]).sort();\n setData(getReadDirBackend(finalInputFileSystem), dir, createWebpackData(files));\n } else {\n break;\n }\n count--;\n }\n };\n }\n };\n const afterResolversHook = () => {\n if (this._staticModules) {\n for (const [filePath, contents] of Object.entries(this._staticModules)) {\n this.writeModule(filePath, contents);\n }\n this._staticModules = null;\n }\n };\n\n // The webpack property is not exposed in webpack v4\n const version = typeof (compiler as any).webpack === 'undefined' ? 4 : 5;\n\n const watchRunHook = (watcher, callback) => {\n this._watcher = watcher.compiler || watcher;\n const virtualFiles = (compiler as any).inputFileSystem._virtualFiles;\n const fts = compiler.fileTimestamps as any;\n\n if (virtualFiles && fts && typeof fts.set === 'function') {\n Object.keys(virtualFiles).forEach((file) => {\n const mtime = +virtualFiles[file].stats.mtime;\n // fts is\n // Map in webpack 4\n // Map in webpack 5\n fts.set(\n file,\n version === 4\n ? mtime\n : {\n safeTime: mtime,\n timestamp: mtime,\n }\n );\n });\n }\n callback();\n };\n\n if (compiler.hooks) {\n compiler.hooks.afterEnvironment.tap('VirtualModulesPlugin', afterEnvironmentHook);\n compiler.hooks.afterResolvers.tap('VirtualModulesPlugin', afterResolversHook);\n compiler.hooks.watchRun.tapAsync('VirtualModulesPlugin', watchRunHook);\n } else {\n (compiler as any).plugin('after-environment', afterEnvironmentHook);\n (compiler as any).plugin('after-resolvers', afterResolversHook);\n (compiler as any).plugin('watch-run', watchRunHook);\n }\n }\n}\n\nexport = VirtualModulesPlugin;\n","/*!\n * is-extglob \n *\n * Copyright (c) 2014-2016, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\nmodule.exports = function isExtglob(str) {\n if (typeof str !== 'string' || str === '') {\n return false;\n }\n\n var match;\n while ((match = /(\\\\).|([@?!+*]\\(.*\\))/g.exec(str))) {\n if (match[2]) return true;\n str = str.slice(match.index + match[0].length);\n }\n\n return false;\n};\n","/*!\n * is-glob \n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\nvar isExtglob = require('is-extglob');\nvar chars = { '{': '}', '(': ')', '[': ']'};\nvar strictCheck = function(str) {\n if (str[0] === '!') {\n return true;\n }\n var index = 0;\n var pipeIndex = -2;\n var closeSquareIndex = -2;\n var closeCurlyIndex = -2;\n var closeParenIndex = -2;\n var backSlashIndex = -2;\n while (index < str.length) {\n if (str[index] === '*') {\n return true;\n }\n\n if (str[index + 1] === '?' && /[\\].+)]/.test(str[index])) {\n return true;\n }\n\n if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {\n if (closeSquareIndex < index) {\n closeSquareIndex = str.indexOf(']', index);\n }\n if (closeSquareIndex > index) {\n if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {\n return true;\n }\n backSlashIndex = str.indexOf('\\\\', index);\n if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {\n return true;\n }\n }\n }\n\n if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {\n closeCurlyIndex = str.indexOf('}', index);\n if (closeCurlyIndex > index) {\n backSlashIndex = str.indexOf('\\\\', index);\n if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {\n return true;\n }\n }\n }\n\n if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {\n closeParenIndex = str.indexOf(')', index);\n if (closeParenIndex > index) {\n backSlashIndex = str.indexOf('\\\\', index);\n if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {\n return true;\n }\n }\n }\n\n if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {\n if (pipeIndex < index) {\n pipeIndex = str.indexOf('|', index);\n }\n if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {\n closeParenIndex = str.indexOf(')', pipeIndex);\n if (closeParenIndex > pipeIndex) {\n backSlashIndex = str.indexOf('\\\\', pipeIndex);\n if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {\n return true;\n }\n }\n }\n }\n\n if (str[index] === '\\\\') {\n var open = str[index + 1];\n index += 2;\n var close = chars[open];\n\n if (close) {\n var n = str.indexOf(close, index);\n if (n !== -1) {\n index = n + 1;\n }\n }\n\n if (str[index] === '!') {\n return true;\n }\n } else {\n index++;\n }\n }\n return false;\n};\n\nvar relaxedCheck = function(str) {\n if (str[0] === '!') {\n return true;\n }\n var index = 0;\n while (index < str.length) {\n if (/[*?{}()[\\]]/.test(str[index])) {\n return true;\n }\n\n if (str[index] === '\\\\') {\n var open = str[index + 1];\n index += 2;\n var close = chars[open];\n\n if (close) {\n var n = str.indexOf(close, index);\n if (n !== -1) {\n index = n + 1;\n }\n }\n\n if (str[index] === '!') {\n return true;\n }\n } else {\n index++;\n }\n }\n return false;\n};\n\nmodule.exports = function isGlob(str, options) {\n if (typeof str !== 'string' || str === '') {\n return false;\n }\n\n if (isExtglob(str)) {\n return true;\n }\n\n var check = strictCheck;\n\n // optionally relax check\n if (options && options.strict === false) {\n check = relaxedCheck;\n }\n\n return check(str);\n};\n","'use strict';\nmodule.exports = balanced;\nfunction balanced(a, b, str) {\n if (a instanceof RegExp) a = maybeMatch(a, str);\n if (b instanceof RegExp) b = maybeMatch(b, str);\n\n var r = range(a, b, str);\n\n return r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + a.length, r[1]),\n post: str.slice(r[1] + b.length)\n };\n}\n\nfunction maybeMatch(reg, str) {\n var m = str.match(reg);\n return m ? m[0] : null;\n}\n\nbalanced.range = range;\nfunction range(a, b, str) {\n var begs, beg, left, right, result;\n var ai = str.indexOf(a);\n var bi = str.indexOf(b, ai + 1);\n var i = ai;\n\n if (ai >= 0 && bi > 0) {\n if(a===b) {\n return [ai, bi];\n }\n begs = [];\n left = str.length;\n\n while (i >= 0 && !result) {\n if (i == ai) {\n begs.push(i);\n ai = str.indexOf(a, i + 1);\n } else if (begs.length == 1) {\n result = [ begs.pop(), bi ];\n } else {\n beg = begs.pop();\n if (beg < left) {\n left = beg;\n right = bi;\n }\n\n bi = str.indexOf(b, i + 1);\n }\n\n i = ai < bi && ai >= 0 ? ai : bi;\n }\n\n if (begs.length) {\n result = [ left, right ];\n }\n }\n\n return result;\n}\n","var balanced = require('balanced-match');\n\nmodule.exports = expandTop;\n\nvar escSlash = '\\0SLASH'+Math.random()+'\\0';\nvar escOpen = '\\0OPEN'+Math.random()+'\\0';\nvar escClose = '\\0CLOSE'+Math.random()+'\\0';\nvar escComma = '\\0COMMA'+Math.random()+'\\0';\nvar escPeriod = '\\0PERIOD'+Math.random()+'\\0';\n\nfunction numeric(str) {\n return parseInt(str, 10) == str\n ? parseInt(str, 10)\n : str.charCodeAt(0);\n}\n\nfunction escapeBraces(str) {\n return str.split('\\\\\\\\').join(escSlash)\n .split('\\\\{').join(escOpen)\n .split('\\\\}').join(escClose)\n .split('\\\\,').join(escComma)\n .split('\\\\.').join(escPeriod);\n}\n\nfunction unescapeBraces(str) {\n return str.split(escSlash).join('\\\\')\n .split(escOpen).join('{')\n .split(escClose).join('}')\n .split(escComma).join(',')\n .split(escPeriod).join('.');\n}\n\n\n// Basically just str.split(\",\"), but handling cases\n// where we have nested braced sections, which should be\n// treated as individual members, like {a,{b,c},d}\nfunction parseCommaParts(str) {\n if (!str)\n return [''];\n\n var parts = [];\n var m = balanced('{', '}', str);\n\n if (!m)\n return str.split(',');\n\n var pre = m.pre;\n var body = m.body;\n var post = m.post;\n var p = pre.split(',');\n\n p[p.length-1] += '{' + body + '}';\n var postParts = parseCommaParts(post);\n if (post.length) {\n p[p.length-1] += postParts.shift();\n p.push.apply(p, postParts);\n }\n\n parts.push.apply(parts, p);\n\n return parts;\n}\n\nfunction expandTop(str) {\n if (!str)\n return [];\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.substr(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.substr(2);\n }\n\n return expand(escapeBraces(str), true).map(unescapeBraces);\n}\n\nfunction embrace(str) {\n return '{' + str + '}';\n}\nfunction isPadded(el) {\n return /^-?0\\d/.test(el);\n}\n\nfunction lte(i, y) {\n return i <= y;\n}\nfunction gte(i, y) {\n return i >= y;\n}\n\nfunction expand(str, isTop) {\n var expansions = [];\n\n var m = balanced('{', '}', str);\n if (!m) return [str];\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n var pre = m.pre;\n var post = m.post.length\n ? expand(m.post, false)\n : [''];\n\n if (/\\$$/.test(m.pre)) { \n for (var k = 0; k < post.length; k++) {\n var expansion = pre+ '{' + m.body + '}' + post[k];\n expansions.push(expansion);\n }\n } else {\n var isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body);\n var isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body);\n var isSequence = isNumericSequence || isAlphaSequence;\n var isOptions = m.body.indexOf(',') >= 0;\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,.*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post;\n return expand(str);\n }\n return [str];\n }\n\n var n;\n if (isSequence) {\n n = m.body.split(/\\.\\./);\n } else {\n n = parseCommaParts(m.body);\n if (n.length === 1) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand(n[0], false).map(embrace);\n if (n.length === 1) {\n return post.map(function(p) {\n return m.pre + n[0] + p;\n });\n }\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n var N;\n\n if (isSequence) {\n var x = numeric(n[0]);\n var y = numeric(n[1]);\n var width = Math.max(n[0].length, n[1].length)\n var incr = n.length == 3\n ? Math.abs(numeric(n[2]))\n : 1;\n var test = lte;\n var reverse = y < x;\n if (reverse) {\n incr *= -1;\n test = gte;\n }\n var pad = n.some(isPadded);\n\n N = [];\n\n for (var i = x; test(i, y); i += incr) {\n var c;\n if (isAlphaSequence) {\n c = String.fromCharCode(i);\n if (c === '\\\\')\n c = '';\n } else {\n c = String(i);\n if (pad) {\n var need = width - c.length;\n if (need > 0) {\n var z = new Array(need + 1).join('0');\n if (i < 0)\n c = '-' + z + c.slice(1);\n else\n c = z + c;\n }\n }\n }\n N.push(c);\n }\n } else {\n N = [];\n\n for (var j = 0; j < n.length; j++) {\n N.push.apply(N, expand(n[j], false));\n }\n }\n\n for (var j = 0; j < N.length; j++) {\n for (var k = 0; k < post.length; k++) {\n var expansion = pre + N[j] + post[k];\n if (!isTop || isSequence || expansion)\n expansions.push(expansion);\n }\n }\n }\n\n return expansions;\n}\n\n","'use strict';\n\nconst nameStartChar = ':A-Za-z_\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD';\nconst nameChar = nameStartChar + '\\\\-.\\\\d\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040';\nconst nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*'\nconst regexName = new RegExp('^' + nameRegexp + '$');\n\nconst getAllMatches = function(string, regex) {\n const matches = [];\n let match = regex.exec(string);\n while (match) {\n const allmatches = [];\n allmatches.startIndex = regex.lastIndex - match[0].length;\n const len = match.length;\n for (let index = 0; index < len; index++) {\n allmatches.push(match[index]);\n }\n matches.push(allmatches);\n match = regex.exec(string);\n }\n return matches;\n};\n\nconst isName = function(string) {\n const match = regexName.exec(string);\n return !(match === null || typeof match === 'undefined');\n};\n\nexports.isExist = function(v) {\n return typeof v !== 'undefined';\n};\n\nexports.isEmptyObject = function(obj) {\n return Object.keys(obj).length === 0;\n};\n\n/**\n * Copy all the properties of a into b.\n * @param {*} target\n * @param {*} a\n */\nexports.merge = function(target, a, arrayMode) {\n if (a) {\n const keys = Object.keys(a); // will return an array of own properties\n const len = keys.length; //don't make it inline\n for (let i = 0; i < len; i++) {\n if (arrayMode === 'strict') {\n target[keys[i]] = [ a[keys[i]] ];\n } else {\n target[keys[i]] = a[keys[i]];\n }\n }\n }\n};\n/* exports.merge =function (b,a){\n return Object.assign(b,a);\n} */\n\nexports.getValue = function(v) {\n if (exports.isExist(v)) {\n return v;\n } else {\n return '';\n }\n};\n\n// const fakeCall = function(a) {return a;};\n// const fakeCallNoReturn = function() {};\n\nexports.isName = isName;\nexports.getAllMatches = getAllMatches;\nexports.nameRegexp = nameRegexp;\n","'use strict';\n\nconst util = require('./util');\n\nconst defaultOptions = {\n allowBooleanAttributes: false, //A tag can have attributes without any value\n unpairedTags: []\n};\n\n//const tagsPattern = new RegExp(\"<\\\\/?([\\\\w:\\\\-_\\.]+)\\\\s*\\/?>\",\"g\");\nexports.validate = function (xmlData, options) {\n options = Object.assign({}, defaultOptions, options);\n\n //xmlData = xmlData.replace(/(\\r\\n|\\n|\\r)/gm,\"\");//make it single line\n //xmlData = xmlData.replace(/(^\\s*<\\?xml.*?\\?>)/g,\"\");//Remove XML starting tag\n //xmlData = xmlData.replace(/()/g,\"\");//Remove DOCTYPE\n const tags = [];\n let tagFound = false;\n\n //indicates that the root tag has been closed (aka. depth 0 has been reached)\n let reachedRoot = false;\n\n if (xmlData[0] === '\\ufeff') {\n // check for byte order mark (BOM)\n xmlData = xmlData.substr(1);\n }\n \n for (let i = 0; i < xmlData.length; i++) {\n\n if (xmlData[i] === '<' && xmlData[i+1] === '?') {\n i+=2;\n i = readPI(xmlData,i);\n if (i.err) return i;\n }else if (xmlData[i] === '<') {\n //starting of tag\n //read until you reach to '>' avoiding any '>' in attribute value\n let tagStartPos = i;\n i++;\n \n if (xmlData[i] === '!') {\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else {\n let closingTag = false;\n if (xmlData[i] === '/') {\n //closing tag\n closingTag = true;\n i++;\n }\n //read tagname\n let tagName = '';\n for (; i < xmlData.length &&\n xmlData[i] !== '>' &&\n xmlData[i] !== ' ' &&\n xmlData[i] !== '\\t' &&\n xmlData[i] !== '\\n' &&\n xmlData[i] !== '\\r'; i++\n ) {\n tagName += xmlData[i];\n }\n tagName = tagName.trim();\n //console.log(tagName);\n\n if (tagName[tagName.length - 1] === '/') {\n //self closing tag without attributes\n tagName = tagName.substring(0, tagName.length - 1);\n //continue;\n i--;\n }\n if (!validateTagName(tagName)) {\n let msg;\n if (tagName.trim().length === 0) {\n msg = \"Invalid space after '<'.\";\n } else {\n msg = \"Tag '\"+tagName+\"' is an invalid name.\";\n }\n return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));\n }\n\n const result = readAttributeStr(xmlData, i);\n if (result === false) {\n return getErrorObject('InvalidAttr', \"Attributes for '\"+tagName+\"' have open quote.\", getLineNumberForPosition(xmlData, i));\n }\n let attrStr = result.value;\n i = result.index;\n\n if (attrStr[attrStr.length - 1] === '/') {\n //self closing tag\n const attrStrStart = i - attrStr.length;\n attrStr = attrStr.substring(0, attrStr.length - 1);\n const isValid = validateAttributeString(attrStr, options);\n if (isValid === true) {\n tagFound = true;\n //continue; //text may presents after self closing tag\n } else {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));\n }\n } else if (closingTag) {\n if (!result.tagClosed) {\n return getErrorObject('InvalidTag', \"Closing tag '\"+tagName+\"' doesn't have proper closing.\", getLineNumberForPosition(xmlData, i));\n } else if (attrStr.trim().length > 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\"+tagName+\"' can't have attributes or invalid starting.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else {\n const otg = tags.pop();\n if (tagName !== otg.tagName) {\n let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);\n return getErrorObject('InvalidTag',\n \"Expected closing tag '\"+otg.tagName+\"' (opened in line \"+openPos.line+\", col \"+openPos.col+\") instead of closing tag '\"+tagName+\"'.\",\n getLineNumberForPosition(xmlData, tagStartPos));\n }\n\n //when there are no more tags, we reached the root level.\n if (tags.length == 0) {\n reachedRoot = true;\n }\n }\n } else {\n const isValid = validateAttributeString(attrStr, options);\n if (isValid !== true) {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));\n }\n\n //if the root level has been reached before ...\n if (reachedRoot === true) {\n return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));\n } else if(options.unpairedTags.indexOf(tagName) !== -1){\n //don't push into stack\n } else {\n tags.push({tagName, tagStartPos});\n }\n tagFound = true;\n }\n\n //skip tag text value\n //It may include comments and CDATA value\n for (i++; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n if (xmlData[i + 1] === '!') {\n //comment or CADATA\n i++;\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else if (xmlData[i+1] === '?') {\n i = readPI(xmlData, ++i);\n if (i.err) return i;\n } else{\n break;\n }\n } else if (xmlData[i] === '&') {\n const afterAmp = validateAmpersand(xmlData, i);\n if (afterAmp == -1)\n return getErrorObject('InvalidChar', \"char '&' is not expected.\", getLineNumberForPosition(xmlData, i));\n i = afterAmp;\n }else{\n if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {\n return getErrorObject('InvalidXml', \"Extra text at the end\", getLineNumberForPosition(xmlData, i));\n }\n }\n } //end of reading tag text value\n if (xmlData[i] === '<') {\n i--;\n }\n }\n } else {\n if ( isWhiteSpace(xmlData[i])) {\n continue;\n }\n return getErrorObject('InvalidChar', \"char '\"+xmlData[i]+\"' is not expected.\", getLineNumberForPosition(xmlData, i));\n }\n }\n\n if (!tagFound) {\n return getErrorObject('InvalidXml', 'Start tag expected.', 1);\n }else if (tags.length == 1) {\n return getErrorObject('InvalidTag', \"Unclosed tag '\"+tags[0].tagName+\"'.\", getLineNumberForPosition(xmlData, tags[0].tagStartPos));\n }else if (tags.length > 0) {\n return getErrorObject('InvalidXml', \"Invalid '\"+\n JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\\r?\\n/g, '')+\n \"' found.\", {line: 1, col: 1});\n }\n\n return true;\n};\n\nfunction isWhiteSpace(char){\n return char === ' ' || char === '\\t' || char === '\\n' || char === '\\r';\n}\n/**\n * Read Processing insstructions and skip\n * @param {*} xmlData\n * @param {*} i\n */\nfunction readPI(xmlData, i) {\n const start = i;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] == '?' || xmlData[i] == ' ') {\n //tagname\n const tagname = xmlData.substr(start, i - start);\n if (i > 5 && tagname === 'xml') {\n return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));\n } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {\n //check if valid attribut string\n i++;\n break;\n } else {\n continue;\n }\n }\n }\n return i;\n}\n\nfunction readCommentAndCDATA(xmlData, i) {\n if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {\n //comment\n for (i += 3; i < xmlData.length; i++) {\n if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n } else if (\n xmlData.length > i + 8 &&\n xmlData[i + 1] === 'D' &&\n xmlData[i + 2] === 'O' &&\n xmlData[i + 3] === 'C' &&\n xmlData[i + 4] === 'T' &&\n xmlData[i + 5] === 'Y' &&\n xmlData[i + 6] === 'P' &&\n xmlData[i + 7] === 'E'\n ) {\n let angleBracketsCount = 1;\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n angleBracketsCount++;\n } else if (xmlData[i] === '>') {\n angleBracketsCount--;\n if (angleBracketsCount === 0) {\n break;\n }\n }\n }\n } else if (\n xmlData.length > i + 9 &&\n xmlData[i + 1] === '[' &&\n xmlData[i + 2] === 'C' &&\n xmlData[i + 3] === 'D' &&\n xmlData[i + 4] === 'A' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'A' &&\n xmlData[i + 7] === '['\n ) {\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n }\n\n return i;\n}\n\nconst doubleQuote = '\"';\nconst singleQuote = \"'\";\n\n/**\n * Keep reading xmlData until '<' is found outside the attribute value.\n * @param {string} xmlData\n * @param {number} i\n */\nfunction readAttributeStr(xmlData, i) {\n let attrStr = '';\n let startChar = '';\n let tagClosed = false;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {\n if (startChar === '') {\n startChar = xmlData[i];\n } else if (startChar !== xmlData[i]) {\n //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa\n } else {\n startChar = '';\n }\n } else if (xmlData[i] === '>') {\n if (startChar === '') {\n tagClosed = true;\n break;\n }\n }\n attrStr += xmlData[i];\n }\n if (startChar !== '') {\n return false;\n }\n\n return {\n value: attrStr,\n index: i,\n tagClosed: tagClosed\n };\n}\n\n/**\n * Select all the attributes whether valid or invalid.\n */\nconst validAttrStrRegxp = new RegExp('(\\\\s*)([^\\\\s=]+)(\\\\s*=)?(\\\\s*([\\'\"])(([\\\\s\\\\S])*?)\\\\5)?', 'g');\n\n//attr, =\"sd\", a=\"amit's\", a=\"sd\"b=\"saf\", ab cd=\"\"\n\nfunction validateAttributeString(attrStr, options) {\n //console.log(\"start:\"+attrStr+\":end\");\n\n //if(attrStr.trim().length === 0) return true; //empty string\n\n const matches = util.getAllMatches(attrStr, validAttrStrRegxp);\n const attrNames = {};\n\n for (let i = 0; i < matches.length; i++) {\n if (matches[i][1].length === 0) {\n //nospace before attribute name: a=\"sd\"b=\"saf\"\n return getErrorObject('InvalidAttr', \"Attribute '\"+matches[i][2]+\"' has no space in starting.\", getPositionFromMatch(matches[i]))\n } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {\n return getErrorObject('InvalidAttr', \"Attribute '\"+matches[i][2]+\"' is without value.\", getPositionFromMatch(matches[i]));\n } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {\n //independent attribute: ab\n return getErrorObject('InvalidAttr', \"boolean attribute '\"+matches[i][2]+\"' is not allowed.\", getPositionFromMatch(matches[i]));\n }\n /* else if(matches[i][6] === undefined){//attribute without value: ab=\n return { err: { code:\"InvalidAttr\",msg:\"attribute \" + matches[i][2] + \" has no value assigned.\"}};\n } */\n const attrName = matches[i][2];\n if (!validateAttrName(attrName)) {\n return getErrorObject('InvalidAttr', \"Attribute '\"+attrName+\"' is an invalid name.\", getPositionFromMatch(matches[i]));\n }\n if (!attrNames.hasOwnProperty(attrName)) {\n //check for duplicate attribute.\n attrNames[attrName] = 1;\n } else {\n return getErrorObject('InvalidAttr', \"Attribute '\"+attrName+\"' is repeated.\", getPositionFromMatch(matches[i]));\n }\n }\n\n return true;\n}\n\nfunction validateNumberAmpersand(xmlData, i) {\n let re = /\\d/;\n if (xmlData[i] === 'x') {\n i++;\n re = /[\\da-fA-F]/;\n }\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === ';')\n return i;\n if (!xmlData[i].match(re))\n break;\n }\n return -1;\n}\n\nfunction validateAmpersand(xmlData, i) {\n // https://www.w3.org/TR/xml/#dt-charref\n i++;\n if (xmlData[i] === ';')\n return -1;\n if (xmlData[i] === '#') {\n i++;\n return validateNumberAmpersand(xmlData, i);\n }\n let count = 0;\n for (; i < xmlData.length; i++, count++) {\n if (xmlData[i].match(/\\w/) && count < 20)\n continue;\n if (xmlData[i] === ';')\n break;\n return -1;\n }\n return i;\n}\n\nfunction getErrorObject(code, message, lineNumber) {\n return {\n err: {\n code: code,\n msg: message,\n line: lineNumber.line || lineNumber,\n col: lineNumber.col,\n },\n };\n}\n\nfunction validateAttrName(attrName) {\n return util.isName(attrName);\n}\n\n// const startsWithXML = /^xml/i;\n\nfunction validateTagName(tagname) {\n return util.isName(tagname) /* && !tagname.match(startsWithXML) */;\n}\n\n//this function returns the line number for the character at the given index\nfunction getLineNumberForPosition(xmlData, index) {\n const lines = xmlData.substring(0, index).split(/\\r?\\n/);\n return {\n line: lines.length,\n\n // column number is last line's length + 1, because column numbering starts at 1:\n col: lines[lines.length - 1].length + 1\n };\n}\n\n//this function returns the position of the first character of match within attrStr\nfunction getPositionFromMatch(match) {\n return match.startIndex + match[1].length;\n}\n","\nconst defaultOptions = {\n preserveOrder: false,\n attributeNamePrefix: '@_',\n attributesGroupName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n removeNSPrefix: false, // remove NS from tag name or attribute name if true\n allowBooleanAttributes: false, //a tag can have attributes without any value\n //ignoreRootElement : false,\n parseTagValue: true,\n parseAttributeValue: false,\n trimValues: true, //Trim string values of tag and attributes\n cdataPropName: false,\n numberParseOptions: {\n hex: true,\n leadingZeros: true,\n eNotation: true\n },\n tagValueProcessor: function(tagName, val) {\n return val;\n },\n attributeValueProcessor: function(attrName, val) {\n return val;\n },\n stopNodes: [], //nested tags will not be parsed even for errors\n alwaysCreateTextNode: false,\n isArray: () => false,\n commentPropName: false,\n unpairedTags: [],\n processEntities: true,\n htmlEntities: false,\n ignoreDeclaration: false,\n ignorePiTags: false,\n transformTagName: false,\n transformAttributeName: false,\n updateTag: function(tagName, jPath, attrs){\n return tagName\n },\n // skipEmptyListItem: false\n};\n \nconst buildOptions = function(options) {\n return Object.assign({}, defaultOptions, options);\n};\n\nexports.buildOptions = buildOptions;\nexports.defaultOptions = defaultOptions;","'use strict';\n\nclass XmlNode{\n constructor(tagname) {\n this.tagname = tagname;\n this.child = []; //nested tags, text, cdata, comments in order\n this[\":@\"] = {}; //attributes map\n }\n add(key,val){\n // this.child.push( {name : key, val: val, isCdata: isCdata });\n if(key === \"__proto__\") key = \"#__proto__\";\n this.child.push( {[key]: val });\n }\n addChild(node) {\n if(node.tagname === \"__proto__\") node.tagname = \"#__proto__\";\n if(node[\":@\"] && Object.keys(node[\":@\"]).length > 0){\n this.child.push( { [node.tagname]: node.child, [\":@\"]: node[\":@\"] });\n }else{\n this.child.push( { [node.tagname]: node.child });\n }\n };\n};\n\n\nmodule.exports = XmlNode;","const util = require('../util');\n\n//TODO: handle comments\nfunction readDocType(xmlData, i){\n \n const entities = {};\n if( xmlData[i + 3] === 'O' &&\n xmlData[i + 4] === 'C' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'Y' &&\n xmlData[i + 7] === 'P' &&\n xmlData[i + 8] === 'E')\n { \n i = i+9;\n let angleBracketsCount = 1;\n let hasBody = false, comment = false;\n let exp = \"\";\n for(;i') { //Read tag content\n if(comment){\n if( xmlData[i - 1] === \"-\" && xmlData[i - 2] === \"-\"){\n comment = false;\n angleBracketsCount--;\n }\n }else{\n angleBracketsCount--;\n }\n if (angleBracketsCount === 0) {\n break;\n }\n }else if( xmlData[i] === '['){\n hasBody = true;\n }else{\n exp += xmlData[i];\n }\n }\n if(angleBracketsCount !== 0){\n throw new Error(`Unclosed DOCTYPE`);\n }\n }else{\n throw new Error(`Invalid Tag instead of DOCTYPE`);\n }\n return {entities, i};\n}\n\nfunction readEntityExp(xmlData,i){\n //External entities are not supported\n // \n\n //Parameter entities are not supported\n // \n\n //Internal entities are supported\n // \n \n //read EntityName\n let entityName = \"\";\n for (; i < xmlData.length && (xmlData[i] !== \"'\" && xmlData[i] !== '\"' ); i++) {\n // if(xmlData[i] === \" \") continue;\n // else \n entityName += xmlData[i];\n }\n entityName = entityName.trim();\n if(entityName.indexOf(\" \") !== -1) throw new Error(\"External entites are not supported\");\n\n //read Entity Value\n const startChar = xmlData[i++];\n let val = \"\"\n for (; i < xmlData.length && xmlData[i] !== startChar ; i++) {\n val += xmlData[i];\n }\n return [entityName, val, i];\n}\n\nfunction isComment(xmlData, i){\n if(xmlData[i+1] === '!' &&\n xmlData[i+2] === '-' &&\n xmlData[i+3] === '-') return true\n return false\n}\nfunction isEntity(xmlData, i){\n if(xmlData[i+1] === '!' &&\n xmlData[i+2] === 'E' &&\n xmlData[i+3] === 'N' &&\n xmlData[i+4] === 'T' &&\n xmlData[i+5] === 'I' &&\n xmlData[i+6] === 'T' &&\n xmlData[i+7] === 'Y') return true\n return false\n}\nfunction isElement(xmlData, i){\n if(xmlData[i+1] === '!' &&\n xmlData[i+2] === 'E' &&\n xmlData[i+3] === 'L' &&\n xmlData[i+4] === 'E' &&\n xmlData[i+5] === 'M' &&\n xmlData[i+6] === 'E' &&\n xmlData[i+7] === 'N' &&\n xmlData[i+8] === 'T') return true\n return false\n}\n\nfunction isAttlist(xmlData, i){\n if(xmlData[i+1] === '!' &&\n xmlData[i+2] === 'A' &&\n xmlData[i+3] === 'T' &&\n xmlData[i+4] === 'T' &&\n xmlData[i+5] === 'L' &&\n xmlData[i+6] === 'I' &&\n xmlData[i+7] === 'S' &&\n xmlData[i+8] === 'T') return true\n return false\n}\nfunction isNotation(xmlData, i){\n if(xmlData[i+1] === '!' &&\n xmlData[i+2] === 'N' &&\n xmlData[i+3] === 'O' &&\n xmlData[i+4] === 'T' &&\n xmlData[i+5] === 'A' &&\n xmlData[i+6] === 'T' &&\n xmlData[i+7] === 'I' &&\n xmlData[i+8] === 'O' &&\n xmlData[i+9] === 'N') return true\n return false\n}\n\nfunction validateEntityName(name){\n if (util.isName(name))\n\treturn name;\n else\n throw new Error(`Invalid entity name ${name}`);\n}\n\nmodule.exports = readDocType;\n","const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;\nconst numRegex = /^([\\-\\+])?(0*)(\\.[0-9]+([eE]\\-?[0-9]+)?|[0-9]+(\\.[0-9]+([eE]\\-?[0-9]+)?)?)$/;\n// const octRegex = /0x[a-z0-9]+/;\n// const binRegex = /0x[a-z0-9]+/;\n\n\n//polyfill\nif (!Number.parseInt && window.parseInt) {\n Number.parseInt = window.parseInt;\n}\nif (!Number.parseFloat && window.parseFloat) {\n Number.parseFloat = window.parseFloat;\n}\n\n \nconst consider = {\n hex : true,\n leadingZeros: true,\n decimalPoint: \"\\.\",\n eNotation: true\n //skipLike: /regex/\n};\n\nfunction toNumber(str, options = {}){\n // const options = Object.assign({}, consider);\n // if(opt.leadingZeros === false){\n // options.leadingZeros = false;\n // }else if(opt.hex === false){\n // options.hex = false;\n // }\n\n options = Object.assign({}, consider, options );\n if(!str || typeof str !== \"string\" ) return str;\n \n let trimmedStr = str.trim();\n // if(trimmedStr === \"0.0\") return 0;\n // else if(trimmedStr === \"+0.0\") return 0;\n // else if(trimmedStr === \"-0.0\") return -0;\n\n if(options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str;\n else if (options.hex && hexRegex.test(trimmedStr)) {\n return Number.parseInt(trimmedStr, 16);\n // } else if (options.parseOct && octRegex.test(str)) {\n // return Number.parseInt(val, 8);\n // }else if (options.parseBin && binRegex.test(str)) {\n // return Number.parseInt(val, 2);\n }else{\n //separate negative sign, leading zeros, and rest number\n const match = numRegex.exec(trimmedStr);\n if(match){\n const sign = match[1];\n const leadingZeros = match[2];\n let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros\n //trim ending zeros for floating number\n \n const eNotation = match[4] || match[6];\n if(!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== \".\") return str; //-0123\n else if(!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== \".\") return str; //0123\n else{//no leading zeros or leading zeros are allowed\n const num = Number(trimmedStr);\n const numStr = \"\" + num;\n if(numStr.search(/[eE]/) !== -1){ //given number is long and parsed to eNotation\n if(options.eNotation) return num;\n else return str;\n }else if(eNotation){ //given number has enotation\n if(options.eNotation) return num;\n else return str;\n }else if(trimmedStr.indexOf(\".\") !== -1){ //floating number\n // const decimalPart = match[5].substr(1);\n // const intPart = trimmedStr.substr(0,trimmedStr.indexOf(\".\"));\n\n \n // const p = numStr.indexOf(\".\");\n // const givenIntPart = numStr.substr(0,p);\n // const givenDecPart = numStr.substr(p+1);\n if(numStr === \"0\" && (numTrimmedByZeros === \"\") ) return num; //0.0\n else if(numStr === numTrimmedByZeros) return num; //0.456. 0.79000\n else if( sign && numStr === \"-\"+numTrimmedByZeros) return num;\n else return str;\n }\n \n if(leadingZeros){\n // if(numTrimmedByZeros === numStr){\n // if(options.leadingZeros) return num;\n // else return str;\n // }else return str;\n if(numTrimmedByZeros === numStr) return num;\n else if(sign+numTrimmedByZeros === numStr) return num;\n else return str;\n }\n\n if(trimmedStr === numStr) return num;\n else if(trimmedStr === sign+numStr) return num;\n // else{\n // //number with +/- sign\n // trimmedStr.test(/[-+][0-9]);\n\n // }\n return str;\n }\n // else if(!eNotation && trimmedStr && trimmedStr !== Number(trimmedStr) ) return str;\n \n }else{ //non-numeric string\n return str;\n }\n }\n}\n\n/**\n * \n * @param {string} numStr without leading zeros\n * @returns \n */\nfunction trimZeros(numStr){\n if(numStr && numStr.indexOf(\".\") !== -1){//float\n numStr = numStr.replace(/0+$/, \"\"); //remove ending zeros\n if(numStr === \".\") numStr = \"0\";\n else if(numStr[0] === \".\") numStr = \"0\"+numStr;\n else if(numStr[numStr.length-1] === \".\") numStr = numStr.substr(0,numStr.length-1);\n return numStr;\n }\n return numStr;\n}\nmodule.exports = toNumber\n","'use strict';\n///@ts-check\n\nconst util = require('../util');\nconst xmlNode = require('./xmlNode');\nconst readDocType = require(\"./DocTypeReader\");\nconst toNumber = require(\"strnum\");\n\n// const regx =\n// '<((!\\\\[CDATA\\\\[([\\\\s\\\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\\\/)(NAME)\\\\s*>))([^<]*)'\n// .replace(/NAME/g, util.nameRegexp);\n\n//const tagsRegx = new RegExp(\"<(\\\\/?[\\\\w:\\\\-\\._]+)([^>]*)>(\\\\s*\"+cdataRegx+\")*([^<]+)?\",\"g\");\n//const tagsRegx = new RegExp(\"<(\\\\/?)((\\\\w*:)?([\\\\w:\\\\-\\._]+))([^>]*)>([^<]*)(\"+cdataRegx+\"([^<]*))*([^<]+)?\",\"g\");\n\nclass OrderedObjParser{\n constructor(options){\n this.options = options;\n this.currentNode = null;\n this.tagsNodeStack = [];\n this.docTypeEntities = {};\n this.lastEntities = {\n \"apos\" : { regex: /&(apos|#39|#x27);/g, val : \"'\"},\n \"gt\" : { regex: /&(gt|#62|#x3E);/g, val : \">\"},\n \"lt\" : { regex: /&(lt|#60|#x3C);/g, val : \"<\"},\n \"quot\" : { regex: /&(quot|#34|#x22);/g, val : \"\\\"\"},\n };\n this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : \"&\"};\n this.htmlEntities = {\n \"space\": { regex: /&(nbsp|#160);/g, val: \" \" },\n // \"lt\" : { regex: /&(lt|#60);/g, val: \"<\" },\n // \"gt\" : { regex: /&(gt|#62);/g, val: \">\" },\n // \"amp\" : { regex: /&(amp|#38);/g, val: \"&\" },\n // \"quot\" : { regex: /&(quot|#34);/g, val: \"\\\"\" },\n // \"apos\" : { regex: /&(apos|#39);/g, val: \"'\" },\n \"cent\" : { regex: /&(cent|#162);/g, val: \"¢\" },\n \"pound\" : { regex: /&(pound|#163);/g, val: \"£\" },\n \"yen\" : { regex: /&(yen|#165);/g, val: \"¥\" },\n \"euro\" : { regex: /&(euro|#8364);/g, val: \"€\" },\n \"copyright\" : { regex: /&(copy|#169);/g, val: \"©\" },\n \"reg\" : { regex: /&(reg|#174);/g, val: \"®\" },\n \"inr\" : { regex: /&(inr|#8377);/g, val: \"₹\" },\n \"num_dec\": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) },\n \"num_hex\": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) },\n };\n this.addExternalEntities = addExternalEntities;\n this.parseXml = parseXml;\n this.parseTextData = parseTextData;\n this.resolveNameSpace = resolveNameSpace;\n this.buildAttributesMap = buildAttributesMap;\n this.isItStopNode = isItStopNode;\n this.replaceEntitiesValue = replaceEntitiesValue;\n this.readStopNodeData = readStopNodeData;\n this.saveTextToParentTag = saveTextToParentTag;\n this.addChild = addChild;\n }\n\n}\n\nfunction addExternalEntities(externalEntities){\n const entKeys = Object.keys(externalEntities);\n for (let i = 0; i < entKeys.length; i++) {\n const ent = entKeys[i];\n this.lastEntities[ent] = {\n regex: new RegExp(\"&\"+ent+\";\",\"g\"),\n val : externalEntities[ent]\n }\n }\n}\n\n/**\n * @param {string} val\n * @param {string} tagName\n * @param {string} jPath\n * @param {boolean} dontTrim\n * @param {boolean} hasAttributes\n * @param {boolean} isLeafNode\n * @param {boolean} escapeEntities\n */\nfunction parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {\n if (val !== undefined) {\n if (this.options.trimValues && !dontTrim) {\n val = val.trim();\n }\n if(val.length > 0){\n if(!escapeEntities) val = this.replaceEntitiesValue(val);\n \n const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode);\n if(newval === null || newval === undefined){\n //don't parse\n return val;\n }else if(typeof newval !== typeof val || newval !== val){\n //overwrite\n return newval;\n }else if(this.options.trimValues){\n return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);\n }else{\n const trimmedVal = val.trim();\n if(trimmedVal === val){\n return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);\n }else{\n return val;\n }\n }\n }\n }\n}\n\nfunction resolveNameSpace(tagname) {\n if (this.options.removeNSPrefix) {\n const tags = tagname.split(':');\n const prefix = tagname.charAt(0) === '/' ? '/' : '';\n if (tags[0] === 'xmlns') {\n return '';\n }\n if (tags.length === 2) {\n tagname = prefix + tags[1];\n }\n }\n return tagname;\n}\n\n//TODO: change regex to capture NS\n//const attrsRegx = new RegExp(\"([\\\\w\\\\-\\\\.\\\\:]+)\\\\s*=\\\\s*(['\\\"])((.|\\n)*?)\\\\2\",\"gm\");\nconst attrsRegx = new RegExp('([^\\\\s=]+)\\\\s*(=\\\\s*([\\'\"])([\\\\s\\\\S]*?)\\\\3)?', 'gm');\n\nfunction buildAttributesMap(attrStr, jPath, tagName) {\n if (!this.options.ignoreAttributes && typeof attrStr === 'string') {\n // attrStr = attrStr.replace(/\\r?\\n/g, ' ');\n //attrStr = attrStr || attrStr.trim();\n\n const matches = util.getAllMatches(attrStr, attrsRegx);\n const len = matches.length; //don't make it inline\n const attrs = {};\n for (let i = 0; i < len; i++) {\n const attrName = this.resolveNameSpace(matches[i][1]);\n let oldVal = matches[i][4];\n let aName = this.options.attributeNamePrefix + attrName;\n if (attrName.length) {\n if (this.options.transformAttributeName) {\n aName = this.options.transformAttributeName(aName);\n }\n if(aName === \"__proto__\") aName = \"#__proto__\";\n if (oldVal !== undefined) {\n if (this.options.trimValues) {\n oldVal = oldVal.trim();\n }\n oldVal = this.replaceEntitiesValue(oldVal);\n const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);\n if(newVal === null || newVal === undefined){\n //don't parse\n attrs[aName] = oldVal;\n }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){\n //overwrite\n attrs[aName] = newVal;\n }else{\n //parse\n attrs[aName] = parseValue(\n oldVal,\n this.options.parseAttributeValue,\n this.options.numberParseOptions\n );\n }\n } else if (this.options.allowBooleanAttributes) {\n attrs[aName] = true;\n }\n }\n }\n if (!Object.keys(attrs).length) {\n return;\n }\n if (this.options.attributesGroupName) {\n const attrCollection = {};\n attrCollection[this.options.attributesGroupName] = attrs;\n return attrCollection;\n }\n return attrs\n }\n}\n\nconst parseXml = function(xmlData) {\n xmlData = xmlData.replace(/\\r\\n?/g, \"\\n\"); //TODO: remove this line\n const xmlObj = new xmlNode('!xml');\n let currentNode = xmlObj;\n let textData = \"\";\n let jPath = \"\";\n for(let i=0; i< xmlData.length; i++){//for each char in XML data\n const ch = xmlData[i];\n if(ch === '<'){\n // const nextIndex = i+1;\n // const _2ndChar = xmlData[nextIndex];\n if( xmlData[i+1] === '/') {//Closing Tag\n const closeIndex = findClosingIndex(xmlData, \">\", i, \"Closing Tag is not closed.\")\n let tagName = xmlData.substring(i+2,closeIndex).trim();\n\n if(this.options.removeNSPrefix){\n const colonIndex = tagName.indexOf(\":\");\n if(colonIndex !== -1){\n tagName = tagName.substr(colonIndex+1);\n }\n }\n\n if(this.options.transformTagName) {\n tagName = this.options.transformTagName(tagName);\n }\n\n if(currentNode){\n textData = this.saveTextToParentTag(textData, currentNode, jPath);\n }\n\n //check if last tag of nested tag was unpaired tag\n const lastTagName = jPath.substring(jPath.lastIndexOf(\".\")+1);\n if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){\n throw new Error(`Unpaired tag can not be used as closing tag: `);\n }\n let propIndex = 0\n if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){\n propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1)\n this.tagsNodeStack.pop();\n }else{\n propIndex = jPath.lastIndexOf(\".\");\n }\n jPath = jPath.substring(0, propIndex);\n\n currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope\n textData = \"\";\n i = closeIndex;\n } else if( xmlData[i+1] === '?') {\n\n let tagData = readTagExp(xmlData,i, false, \"?>\");\n if(!tagData) throw new Error(\"Pi Tag is not closed.\");\n\n textData = this.saveTextToParentTag(textData, currentNode, jPath);\n if( (this.options.ignoreDeclaration && tagData.tagName === \"?xml\") || this.options.ignorePiTags){\n\n }else{\n \n const childNode = new xmlNode(tagData.tagName);\n childNode.add(this.options.textNodeName, \"\");\n \n if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){\n childNode[\":@\"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName);\n }\n this.addChild(currentNode, childNode, jPath)\n\n }\n\n\n i = tagData.closeIndex + 1;\n } else if(xmlData.substr(i + 1, 3) === '!--') {\n const endIndex = findClosingIndex(xmlData, \"-->\", i+4, \"Comment is not closed.\")\n if(this.options.commentPropName){\n const comment = xmlData.substring(i + 4, endIndex - 2);\n\n textData = this.saveTextToParentTag(textData, currentNode, jPath);\n\n currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]);\n }\n i = endIndex;\n } else if( xmlData.substr(i + 1, 2) === '!D') {\n const result = readDocType(xmlData, i);\n this.docTypeEntities = result.entities;\n i = result.i;\n }else if(xmlData.substr(i + 1, 2) === '![') {\n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"CDATA is not closed.\") - 2;\n const tagExp = xmlData.substring(i + 9,closeIndex);\n\n textData = this.saveTextToParentTag(textData, currentNode, jPath);\n\n let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);\n if(val == undefined) val = \"\";\n\n //cdata should be set even if it is 0 length string\n if(this.options.cdataPropName){\n currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]);\n }else{\n currentNode.add(this.options.textNodeName, val);\n }\n \n i = closeIndex + 2;\n }else {//Opening tag\n let result = readTagExp(xmlData,i, this.options.removeNSPrefix);\n let tagName= result.tagName;\n const rawTagName = result.rawTagName;\n let tagExp = result.tagExp;\n let attrExpPresent = result.attrExpPresent;\n let closeIndex = result.closeIndex;\n\n if (this.options.transformTagName) {\n tagName = this.options.transformTagName(tagName);\n }\n \n //save text as child node\n if (currentNode && textData) {\n if(currentNode.tagname !== '!xml'){\n //when nested tag is found\n textData = this.saveTextToParentTag(textData, currentNode, jPath, false);\n }\n }\n\n //check if last tag was unpaired tag\n const lastTag = currentNode;\n if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){\n currentNode = this.tagsNodeStack.pop();\n jPath = jPath.substring(0, jPath.lastIndexOf(\".\"));\n }\n if(tagName !== xmlObj.tagname){\n jPath += jPath ? \".\" + tagName : tagName;\n }\n if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) {\n let tagContent = \"\";\n //self-closing tag\n if(tagExp.length > 0 && tagExp.lastIndexOf(\"/\") === tagExp.length - 1){\n i = result.closeIndex;\n }\n //unpaired tag\n else if(this.options.unpairedTags.indexOf(tagName) !== -1){\n i = result.closeIndex;\n }\n //normal tag\n else{\n //read until closing tag is found\n const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);\n if(!result) throw new Error(`Unexpected end of ${rawTagName}`);\n i = result.i;\n tagContent = result.tagContent;\n }\n\n const childNode = new xmlNode(tagName);\n if(tagName !== tagExp && attrExpPresent){\n childNode[\":@\"] = this.buildAttributesMap(tagExp, jPath, tagName);\n }\n if(tagContent) {\n tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);\n }\n \n jPath = jPath.substr(0, jPath.lastIndexOf(\".\"));\n childNode.add(this.options.textNodeName, tagContent);\n \n this.addChild(currentNode, childNode, jPath)\n }else{\n //selfClosing tag\n if(tagExp.length > 0 && tagExp.lastIndexOf(\"/\") === tagExp.length - 1){\n if(tagName[tagName.length - 1] === \"/\"){ //remove trailing '/'\n tagName = tagName.substr(0, tagName.length - 1);\n jPath = jPath.substr(0, jPath.length - 1);\n tagExp = tagName;\n }else{\n tagExp = tagExp.substr(0, tagExp.length - 1);\n }\n \n if(this.options.transformTagName) {\n tagName = this.options.transformTagName(tagName);\n }\n\n const childNode = new xmlNode(tagName);\n if(tagName !== tagExp && attrExpPresent){\n childNode[\":@\"] = this.buildAttributesMap(tagExp, jPath, tagName);\n }\n this.addChild(currentNode, childNode, jPath)\n jPath = jPath.substr(0, jPath.lastIndexOf(\".\"));\n }\n //opening tag\n else{\n const childNode = new xmlNode( tagName);\n this.tagsNodeStack.push(currentNode);\n \n if(tagName !== tagExp && attrExpPresent){\n childNode[\":@\"] = this.buildAttributesMap(tagExp, jPath, tagName);\n }\n this.addChild(currentNode, childNode, jPath)\n currentNode = childNode;\n }\n textData = \"\";\n i = closeIndex;\n }\n }\n }else{\n textData += xmlData[i];\n }\n }\n return xmlObj.child;\n}\n\nfunction addChild(currentNode, childNode, jPath){\n const result = this.options.updateTag(childNode.tagname, jPath, childNode[\":@\"])\n if(result === false){\n }else if(typeof result === \"string\"){\n childNode.tagname = result\n currentNode.addChild(childNode);\n }else{\n currentNode.addChild(childNode);\n }\n}\n\nconst replaceEntitiesValue = function(val){\n\n if(this.options.processEntities){\n for(let entityName in this.docTypeEntities){\n const entity = this.docTypeEntities[entityName];\n val = val.replace( entity.regx, entity.val);\n }\n for(let entityName in this.lastEntities){\n const entity = this.lastEntities[entityName];\n val = val.replace( entity.regex, entity.val);\n }\n if(this.options.htmlEntities){\n for(let entityName in this.htmlEntities){\n const entity = this.htmlEntities[entityName];\n val = val.replace( entity.regex, entity.val);\n }\n }\n val = val.replace( this.ampEntity.regex, this.ampEntity.val);\n }\n return val;\n}\nfunction saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {\n if (textData) { //store previously collected data as textNode\n if(isLeafNode === undefined) isLeafNode = Object.keys(currentNode.child).length === 0\n \n textData = this.parseTextData(textData,\n currentNode.tagname,\n jPath,\n false,\n currentNode[\":@\"] ? Object.keys(currentNode[\":@\"]).length !== 0 : false,\n isLeafNode);\n\n if (textData !== undefined && textData !== \"\")\n currentNode.add(this.options.textNodeName, textData);\n textData = \"\";\n }\n return textData;\n}\n\n//TODO: use jPath to simplify the logic\n/**\n * \n * @param {string[]} stopNodes \n * @param {string} jPath\n * @param {string} currentTagName \n */\nfunction isItStopNode(stopNodes, jPath, currentTagName){\n const allNodesExp = \"*.\" + currentTagName;\n for (const stopNodePath in stopNodes) {\n const stopNodeExp = stopNodes[stopNodePath];\n if( allNodesExp === stopNodeExp || jPath === stopNodeExp ) return true;\n }\n return false;\n}\n\n/**\n * Returns the tag Expression and where it is ending handling single-double quotes situation\n * @param {string} xmlData \n * @param {number} i starting index\n * @returns \n */\nfunction tagExpWithClosingIndex(xmlData, i, closingChar = \">\"){\n let attrBoundary;\n let tagExp = \"\";\n for (let index = i; index < xmlData.length; index++) {\n let ch = xmlData[index];\n if (attrBoundary) {\n if (ch === attrBoundary) attrBoundary = \"\";//reset\n } else if (ch === '\"' || ch === \"'\") {\n attrBoundary = ch;\n } else if (ch === closingChar[0]) {\n if(closingChar[1]){\n if(xmlData[index + 1] === closingChar[1]){\n return {\n data: tagExp,\n index: index\n }\n }\n }else{\n return {\n data: tagExp,\n index: index\n }\n }\n } else if (ch === '\\t') {\n ch = \" \"\n }\n tagExp += ch;\n }\n}\n\nfunction findClosingIndex(xmlData, str, i, errMsg){\n const closingIndex = xmlData.indexOf(str, i);\n if(closingIndex === -1){\n throw new Error(errMsg)\n }else{\n return closingIndex + str.length - 1;\n }\n}\n\nfunction readTagExp(xmlData,i, removeNSPrefix, closingChar = \">\"){\n const result = tagExpWithClosingIndex(xmlData, i+1, closingChar);\n if(!result) return;\n let tagExp = result.data;\n const closeIndex = result.index;\n const separatorIndex = tagExp.search(/\\s/);\n let tagName = tagExp;\n let attrExpPresent = true;\n if(separatorIndex !== -1){//separate tag name and attributes expression\n tagName = tagExp.substring(0, separatorIndex);\n tagExp = tagExp.substring(separatorIndex + 1).trimStart();\n }\n\n const rawTagName = tagName;\n if(removeNSPrefix){\n const colonIndex = tagName.indexOf(\":\");\n if(colonIndex !== -1){\n tagName = tagName.substr(colonIndex+1);\n attrExpPresent = tagName !== result.data.substr(colonIndex + 1);\n }\n }\n\n return {\n tagName: tagName,\n tagExp: tagExp,\n closeIndex: closeIndex,\n attrExpPresent: attrExpPresent,\n rawTagName: rawTagName,\n }\n}\n/**\n * find paired tag for a stop node\n * @param {string} xmlData \n * @param {string} tagName \n * @param {number} i \n */\nfunction readStopNodeData(xmlData, tagName, i){\n const startIndex = i;\n // Starting at 1 since we already have an open tag\n let openTagCount = 1;\n\n for (; i < xmlData.length; i++) {\n if( xmlData[i] === \"<\"){ \n if (xmlData[i+1] === \"/\") {//close tag\n const closeIndex = findClosingIndex(xmlData, \">\", i, `${tagName} is not closed`);\n let closeTagName = xmlData.substring(i+2,closeIndex).trim();\n if(closeTagName === tagName){\n openTagCount--;\n if (openTagCount === 0) {\n return {\n tagContent: xmlData.substring(startIndex, i),\n i : closeIndex\n }\n }\n }\n i=closeIndex;\n } else if(xmlData[i+1] === '?') { \n const closeIndex = findClosingIndex(xmlData, \"?>\", i+1, \"StopNode is not closed.\")\n i=closeIndex;\n } else if(xmlData.substr(i + 1, 3) === '!--') { \n const closeIndex = findClosingIndex(xmlData, \"-->\", i+3, \"StopNode is not closed.\")\n i=closeIndex;\n } else if(xmlData.substr(i + 1, 2) === '![') { \n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"StopNode is not closed.\") - 2;\n i=closeIndex;\n } else {\n const tagData = readTagExp(xmlData, i, '>')\n\n if (tagData) {\n const openTagName = tagData && tagData.tagName;\n if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== \"/\") {\n openTagCount++;\n }\n i=tagData.closeIndex;\n }\n }\n }\n }//end for loop\n}\n\nfunction parseValue(val, shouldParse, options) {\n if (shouldParse && typeof val === 'string') {\n //console.log(options)\n const newval = val.trim();\n if(newval === 'true' ) return true;\n else if(newval === 'false' ) return false;\n else return toNumber(val, options);\n } else {\n if (util.isExist(val)) {\n return val;\n } else {\n return '';\n }\n }\n}\n\n\nmodule.exports = OrderedObjParser;\n","'use strict';\n\n/**\n * \n * @param {array} node \n * @param {any} options \n * @returns \n */\nfunction prettify(node, options){\n return compress( node, options);\n}\n\n/**\n * \n * @param {array} arr \n * @param {object} options \n * @param {string} jPath \n * @returns object\n */\nfunction compress(arr, options, jPath){\n let text;\n const compressedObj = {};\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const property = propName(tagObj);\n let newJpath = \"\";\n if(jPath === undefined) newJpath = property;\n else newJpath = jPath + \".\" + property;\n\n if(property === options.textNodeName){\n if(text === undefined) text = tagObj[property];\n else text += \"\" + tagObj[property];\n }else if(property === undefined){\n continue;\n }else if(tagObj[property]){\n \n let val = compress(tagObj[property], options, newJpath);\n const isLeaf = isLeafTag(val, options);\n\n if(tagObj[\":@\"]){\n assignAttributes( val, tagObj[\":@\"], newJpath, options);\n }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){\n val = val[options.textNodeName];\n }else if(Object.keys(val).length === 0){\n if(options.alwaysCreateTextNode) val[options.textNodeName] = \"\";\n else val = \"\";\n }\n\n if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) {\n if(!Array.isArray(compressedObj[property])) {\n compressedObj[property] = [ compressedObj[property] ];\n }\n compressedObj[property].push(val);\n }else{\n //TODO: if a node is not an array, then check if it should be an array\n //also determine if it is a leaf node\n if (options.isArray(property, newJpath, isLeaf )) {\n compressedObj[property] = [val];\n }else{\n compressedObj[property] = val;\n }\n }\n }\n \n }\n // if(text && text.length > 0) compressedObj[options.textNodeName] = text;\n if(typeof text === \"string\"){\n if(text.length > 0) compressedObj[options.textNodeName] = text;\n }else if(text !== undefined) compressedObj[options.textNodeName] = text;\n return compressedObj;\n}\n\nfunction propName(obj){\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if(key !== \":@\") return key;\n }\n}\n\nfunction assignAttributes(obj, attrMap, jpath, options){\n if (attrMap) {\n const keys = Object.keys(attrMap);\n const len = keys.length; //don't make it inline\n for (let i = 0; i < len; i++) {\n const atrrName = keys[i];\n if (options.isArray(atrrName, jpath + \".\" + atrrName, true, true)) {\n obj[atrrName] = [ attrMap[atrrName] ];\n } else {\n obj[atrrName] = attrMap[atrrName];\n }\n }\n }\n}\n\nfunction isLeafTag(obj, options){\n const { textNodeName } = options;\n const propCount = Object.keys(obj).length;\n \n if (propCount === 0) {\n return true;\n }\n\n if (\n propCount === 1 &&\n (obj[textNodeName] || typeof obj[textNodeName] === \"boolean\" || obj[textNodeName] === 0)\n ) {\n return true;\n }\n\n return false;\n}\nexports.prettify = prettify;\n","const { buildOptions} = require(\"./OptionsBuilder\");\nconst OrderedObjParser = require(\"./OrderedObjParser\");\nconst { prettify} = require(\"./node2json\");\nconst validator = require('../validator');\n\nclass XMLParser{\n \n constructor(options){\n this.externalEntities = {};\n this.options = buildOptions(options);\n \n }\n /**\n * Parse XML dats to JS object \n * @param {string|Buffer} xmlData \n * @param {boolean|Object} validationOption \n */\n parse(xmlData,validationOption){\n if(typeof xmlData === \"string\"){\n }else if( xmlData.toString){\n xmlData = xmlData.toString();\n }else{\n throw new Error(\"XML data is accepted in String or Bytes[] form.\")\n }\n if( validationOption){\n if(validationOption === true) validationOption = {}; //validate with default options\n \n const result = validator.validate(xmlData, validationOption);\n if (result !== true) {\n throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` )\n }\n }\n const orderedObjParser = new OrderedObjParser(this.options);\n orderedObjParser.addExternalEntities(this.externalEntities);\n const orderedResult = orderedObjParser.parseXml(xmlData);\n if(this.options.preserveOrder || orderedResult === undefined) return orderedResult;\n else return prettify(orderedResult, this.options);\n }\n\n /**\n * Add Entity which is not by default supported by this library\n * @param {string} key \n * @param {string} value \n */\n addEntity(key, value){\n if(value.indexOf(\"&\") !== -1){\n throw new Error(\"Entity value can't have '&'\")\n }else if(key.indexOf(\"&\") !== -1 || key.indexOf(\";\") !== -1){\n throw new Error(\"An entity must be set without '&' and ';'. Eg. use '#xD' for ' '\")\n }else if(value === \"&\"){\n throw new Error(\"An entity with value '&' is not permitted\");\n }else{\n this.externalEntities[key] = value;\n }\n }\n}\n\nmodule.exports = XMLParser;","const EOL = \"\\n\";\n\n/**\n * \n * @param {array} jArray \n * @param {any} options \n * @returns \n */\nfunction toXml(jArray, options) {\n let indentation = \"\";\n if (options.format && options.indentBy.length > 0) {\n indentation = EOL;\n }\n return arrToStr(jArray, options, \"\", indentation);\n}\n\nfunction arrToStr(arr, options, jPath, indentation) {\n let xmlStr = \"\";\n let isPreviousElementTag = false;\n\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const tagName = propName(tagObj);\n if(tagName === undefined) continue;\n\n let newJPath = \"\";\n if (jPath.length === 0) newJPath = tagName\n else newJPath = `${jPath}.${tagName}`;\n\n if (tagName === options.textNodeName) {\n let tagText = tagObj[tagName];\n if (!isStopNode(newJPath, options)) {\n tagText = options.tagValueProcessor(tagName, tagText);\n tagText = replaceEntitiesValue(tagText, options);\n }\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n xmlStr += tagText;\n isPreviousElementTag = false;\n continue;\n } else if (tagName === options.cdataPropName) {\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n xmlStr += ``;\n isPreviousElementTag = false;\n continue;\n } else if (tagName === options.commentPropName) {\n xmlStr += indentation + ``;\n isPreviousElementTag = true;\n continue;\n } else if (tagName[0] === \"?\") {\n const attStr = attr_to_str(tagObj[\":@\"], options);\n const tempInd = tagName === \"?xml\" ? \"\" : indentation;\n let piTextNodeName = tagObj[tagName][0][options.textNodeName];\n piTextNodeName = piTextNodeName.length !== 0 ? \" \" + piTextNodeName : \"\"; //remove extra spacing\n xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`;\n isPreviousElementTag = true;\n continue;\n }\n let newIdentation = indentation;\n if (newIdentation !== \"\") {\n newIdentation += options.indentBy;\n }\n const attStr = attr_to_str(tagObj[\":@\"], options);\n const tagStart = indentation + `<${tagName}${attStr}`;\n const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation);\n if (options.unpairedTags.indexOf(tagName) !== -1) {\n if (options.suppressUnpairedNode) xmlStr += tagStart + \">\";\n else xmlStr += tagStart + \"/>\";\n } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {\n xmlStr += tagStart + \"/>\";\n } else if (tagValue && tagValue.endsWith(\">\")) {\n xmlStr += tagStart + `>${tagValue}${indentation}`;\n } else {\n xmlStr += tagStart + \">\";\n if (tagValue && indentation !== \"\" && (tagValue.includes(\"/>\") || tagValue.includes(\"`;\n }\n isPreviousElementTag = true;\n }\n\n return xmlStr;\n}\n\nfunction propName(obj) {\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if(!obj.hasOwnProperty(key)) continue;\n if (key !== \":@\") return key;\n }\n}\n\nfunction attr_to_str(attrMap, options) {\n let attrStr = \"\";\n if (attrMap && !options.ignoreAttributes) {\n for (let attr in attrMap) {\n if(!attrMap.hasOwnProperty(attr)) continue;\n let attrVal = options.attributeValueProcessor(attr, attrMap[attr]);\n attrVal = replaceEntitiesValue(attrVal, options);\n if (attrVal === true && options.suppressBooleanAttributes) {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;\n } else {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}=\"${attrVal}\"`;\n }\n }\n }\n return attrStr;\n}\n\nfunction isStopNode(jPath, options) {\n jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1);\n let tagName = jPath.substr(jPath.lastIndexOf(\".\") + 1);\n for (let index in options.stopNodes) {\n if (options.stopNodes[index] === jPath || options.stopNodes[index] === \"*.\" + tagName) return true;\n }\n return false;\n}\n\nfunction replaceEntitiesValue(textValue, options) {\n if (textValue && textValue.length > 0 && options.processEntities) {\n for (let i = 0; i < options.entities.length; i++) {\n const entity = options.entities[i];\n textValue = textValue.replace(entity.regex, entity.val);\n }\n }\n return textValue;\n}\nmodule.exports = toXml;\n","'use strict';\n//parse Empty Node as self closing node\nconst buildFromOrderedJs = require('./orderedJs2Xml');\n\nconst defaultOptions = {\n attributeNamePrefix: '@_',\n attributesGroupName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n cdataPropName: false,\n format: false,\n indentBy: ' ',\n suppressEmptyNode: false,\n suppressUnpairedNode: true,\n suppressBooleanAttributes: true,\n tagValueProcessor: function(key, a) {\n return a;\n },\n attributeValueProcessor: function(attrName, a) {\n return a;\n },\n preserveOrder: false,\n commentPropName: false,\n unpairedTags: [],\n entities: [\n { regex: new RegExp(\"&\", \"g\"), val: \"&\" },//it must be on top\n { regex: new RegExp(\">\", \"g\"), val: \">\" },\n { regex: new RegExp(\"<\", \"g\"), val: \"<\" },\n { regex: new RegExp(\"\\'\", \"g\"), val: \"'\" },\n { regex: new RegExp(\"\\\"\", \"g\"), val: \""\" }\n ],\n processEntities: true,\n stopNodes: [],\n // transformTagName: false,\n // transformAttributeName: false,\n oneListGroup: false\n};\n\nfunction Builder(options) {\n this.options = Object.assign({}, defaultOptions, options);\n if (this.options.ignoreAttributes || this.options.attributesGroupName) {\n this.isAttribute = function(/*a*/) {\n return false;\n };\n } else {\n this.attrPrefixLen = this.options.attributeNamePrefix.length;\n this.isAttribute = isAttribute;\n }\n\n this.processTextOrObjNode = processTextOrObjNode\n\n if (this.options.format) {\n this.indentate = indentate;\n this.tagEndChar = '>\\n';\n this.newLine = '\\n';\n } else {\n this.indentate = function() {\n return '';\n };\n this.tagEndChar = '>';\n this.newLine = '';\n }\n}\n\nBuilder.prototype.build = function(jObj) {\n if(this.options.preserveOrder){\n return buildFromOrderedJs(jObj, this.options);\n }else {\n if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){\n jObj = {\n [this.options.arrayNodeName] : jObj\n }\n }\n return this.j2x(jObj, 0).val;\n }\n};\n\nBuilder.prototype.j2x = function(jObj, level) {\n let attrStr = '';\n let val = '';\n for (let key in jObj) {\n if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue;\n if (typeof jObj[key] === 'undefined') {\n // supress undefined node only if it is not an attribute\n if (this.isAttribute(key)) {\n val += '';\n }\n } else if (jObj[key] === null) {\n // null attribute should be ignored by the attribute list, but should not cause the tag closing\n if (this.isAttribute(key)) {\n val += '';\n } else if (key[0] === '?') {\n val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;\n } else {\n val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n }\n // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n } else if (jObj[key] instanceof Date) {\n val += this.buildTextValNode(jObj[key], key, '', level);\n } else if (typeof jObj[key] !== 'object') {\n //premitive type\n const attr = this.isAttribute(key);\n if (attr) {\n attrStr += this.buildAttrPairStr(attr, '' + jObj[key]);\n }else {\n //tag value\n if (key === this.options.textNodeName) {\n let newval = this.options.tagValueProcessor(key, '' + jObj[key]);\n val += this.replaceEntitiesValue(newval);\n } else {\n val += this.buildTextValNode(jObj[key], key, '', level);\n }\n }\n } else if (Array.isArray(jObj[key])) {\n //repeated nodes\n const arrLen = jObj[key].length;\n let listTagVal = \"\";\n for (let j = 0; j < arrLen; j++) {\n const item = jObj[key][j];\n if (typeof item === 'undefined') {\n // supress undefined node\n } else if (item === null) {\n if(key[0] === \"?\") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;\n else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n } else if (typeof item === 'object') {\n if(this.options.oneListGroup ){\n listTagVal += this.j2x(item, level + 1).val;\n }else{\n listTagVal += this.processTextOrObjNode(item, key, level)\n }\n } else {\n listTagVal += this.buildTextValNode(item, key, '', level);\n }\n }\n if(this.options.oneListGroup){\n listTagVal = this.buildObjectNode(listTagVal, key, '', level);\n }\n val += listTagVal;\n } else {\n //nested node\n if (this.options.attributesGroupName && key === this.options.attributesGroupName) {\n const Ks = Object.keys(jObj[key]);\n const L = Ks.length;\n for (let j = 0; j < L; j++) {\n attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]);\n }\n } else {\n val += this.processTextOrObjNode(jObj[key], key, level)\n }\n }\n }\n return {attrStr: attrStr, val: val};\n};\n\nBuilder.prototype.buildAttrPairStr = function(attrName, val){\n val = this.options.attributeValueProcessor(attrName, '' + val);\n val = this.replaceEntitiesValue(val);\n if (this.options.suppressBooleanAttributes && val === \"true\") {\n return ' ' + attrName;\n } else return ' ' + attrName + '=\"' + val + '\"';\n}\n\nfunction processTextOrObjNode (object, key, level) {\n const result = this.j2x(object, level + 1);\n if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) {\n return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level);\n } else {\n return this.buildObjectNode(result.val, key, result.attrStr, level);\n }\n}\n\nBuilder.prototype.buildObjectNode = function(val, key, attrStr, level) {\n if(val === \"\"){\n if(key[0] === \"?\") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;\n else {\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n }\n }else{\n\n let tagEndExp = '' + val + tagEndExp );\n } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {\n return this.indentate(level) + `` + this.newLine;\n }else {\n return (\n this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar +\n val +\n this.indentate(level) + tagEndExp );\n }\n }\n}\n\nBuilder.prototype.closeTag = function(key){\n let closeTag = \"\";\n if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired\n if(!this.options.suppressUnpairedNode) closeTag = \"/\"\n }else if(this.options.suppressEmptyNode){ //empty\n closeTag = \"/\";\n }else{\n closeTag = `>` + this.newLine;\n }else if (this.options.commentPropName !== false && key === this.options.commentPropName) {\n return this.indentate(level) + `` + this.newLine;\n }else if(key[0] === \"?\") {//PI tag\n return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; \n }else{\n let textValue = this.options.tagValueProcessor(key, val);\n textValue = this.replaceEntitiesValue(textValue);\n \n if( textValue === ''){\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n }else{\n return this.indentate(level) + '<' + key + attrStr + '>' +\n textValue +\n ' 0 && this.options.processEntities){\n for (let i=0; i {\n const fetchUrl = new URL(`${server}/_storybook/preview`);\n\n const response = await fetch(fetchUrl, {\n method: 'GET',\n headers: {\n Accept: 'text/html',\n },\n });\n\n const html = await response.text();\n\n if (!response.ok) {\n throw new SymfonyPreviewRenderingError(html);\n }\n\n return html;\n};\n\ntype SymfonyConfiguration = {\n twig_config: SymfonyTwigConfiguration;\n twig_component_config: SymfonyTwigComponentConfiguration;\n};\n\nexport const getSymfonyConfig = async (storybookCachePath: string): Promise => {\n const filePath = `${storybookCachePath}/symfony_parameters.json`;\n\n return JSON.parse(fs.readFileSync(filePath, 'utf8'));\n};\n\ntype SymfonyTwigComponentConfiguration = {\n anonymous_template_directory: string;\n defaults: {\n [p: string]: {\n name_prefix: string;\n template_directory: string;\n };\n };\n};\n\nexport type TwigComponentConfiguration = {\n anonymousTemplateDirectory: string[];\n namespaces: {\n [p: string]: string[];\n };\n};\n\ntype SymfonyTwigConfiguration = {\n default_path: string;\n paths: {\n [p: string]: string;\n };\n};\n\nexport type TwigConfiguration = {\n paths: string[];\n};\n","import { getSymfonyConfig, TwigComponentConfiguration, TwigConfiguration } from './lib/symfony';\nimport { StorybookConfig, SymfonyOptions } from '../types';\nimport { join, resolve } from 'path';\nimport { PreviewCompilerPlugin } from './lib/preview-compiler-plugin';\nimport { DevPreviewCompilerPlugin } from './lib/dev-preview-compiler-plugin';\nimport { TwigLoaderPlugin } from './lib/twig-loader-plugin';\nimport { PresetProperty } from '@storybook/types';\nimport dedent from 'ts-dedent';\n\ntype BuildOptions = {\n twigComponent: TwigComponentConfiguration;\n twig: TwigConfiguration;\n additionalWatchPaths: string[];\n};\n\nconst getBuildOptions = async (symfonyOptions: SymfonyOptions) => {\n const { twig_config, twig_component_config } = await getSymfonyConfig(symfonyOptions.storybookCachePath);\n\n const componentNamespaces: { [p: string]: string[] } = {};\n\n const twigPaths: string[] = Object.keys(twig_config.paths);\n\n if (twigPaths.length === 0) {\n twigPaths.push('templates');\n }\n\n for (const { name_prefix: namePrefix, template_directory: templateDirectory } of Object.values(\n twig_component_config.defaults\n )) {\n componentNamespaces[namePrefix] = [join(twig_config.default_path, templateDirectory)];\n }\n\n Object.entries(twig_config.paths).forEach(([path, alias]) => {\n componentNamespaces[alias] = [join(path, twig_component_config.anonymous_template_directory)];\n });\n\n // TODO Should be a regular string ?\n const anonymousNamespace: string[] = [\n join(twig_config.default_path, twig_component_config.anonymous_template_directory),\n ];\n\n return {\n twigComponent: {\n anonymousTemplateDirectory: anonymousNamespace,\n namespaces: componentNamespaces,\n },\n twig: {\n paths: twigPaths,\n },\n additionalWatchPaths: symfonyOptions.additionalWatchPaths || [],\n } as BuildOptions;\n};\n\nexport const webpack: StorybookConfig['webpack'] = async (config, options) => {\n const framework = await options.presets.apply('framework');\n\n const frameworkOptions = typeof framework === 'string' ? {} : framework.options;\n\n // This options resolution should be done right before creating the build configuration (i.e. not in options presets).\n const symfonyOptions = await getBuildOptions(frameworkOptions.symfony);\n\n return {\n ...config,\n plugins: [\n ...(config.plugins || []),\n ...[\n options.configType === 'PRODUCTION'\n ? PreviewCompilerPlugin.webpack({\n server: frameworkOptions.symfony.server,\n })\n : DevPreviewCompilerPlugin.webpack({\n projectDir: resolve(),\n server: frameworkOptions.symfony.server,\n additionalWatchPaths: symfonyOptions.additionalWatchPaths,\n }),\n TwigLoaderPlugin.webpack({\n projectDir: resolve(),\n twigComponentConfiguration: symfonyOptions.twigComponent,\n }),\n ],\n ],\n module: {\n ...config.module,\n rules: [...(config.module?.rules || [])],\n },\n };\n};\n\nexport const previewHead: PresetProperty<'previewHead'> = async (base: any) => dedent`\n ${base}\n \n `;\n\nexport const previewBody: PresetProperty<'previewBody'> = async (base: any) => dedent`\n ${base}\n \n `;\n","import { createUnplugin } from 'unplugin';\nimport { generateSymfonyPreview } from './symfony';\nimport HtmlWebpackPlugin from 'html-webpack-plugin';\nimport { logger } from '@storybook/node-logger';\nimport dedent from 'ts-dedent';\nimport { injectPreviewHtml } from './injectPreviewHtml';\n\nconst PLUGIN_NAME = 'preview-plugin';\n\nexport type Options = {\n server: string;\n};\n\n/**\n * Compile preview HTML.\n */\nexport const PreviewCompilerPlugin = createUnplugin((options) => {\n const { server } = options;\n\n return {\n name: PLUGIN_NAME,\n webpack(compiler) {\n compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {\n // Inject previewHead and previewBody in the compiled iframe.html before it is output\n HtmlWebpackPlugin.getHooks(compilation).afterTemplateExecution.tapPromise(\n PLUGIN_NAME,\n async (params) => {\n try {\n const previewHtml = await generateSymfonyPreview(server);\n params.html = injectPreviewHtml(previewHtml, params.html);\n\n return params;\n } catch (err) {\n logger.error(dedent`\n Failed to inject Symfony preview template in main iframe.html.\n ERR: ${err}\n `);\n return params;\n }\n }\n );\n });\n },\n };\n});\n","export function dedent(\n templ: TemplateStringsArray | string,\n ...values: unknown[]\n): string {\n let strings = Array.from(typeof templ === 'string' ? [templ] : templ);\n\n // 1. Remove trailing whitespace.\n strings[strings.length - 1] = strings[strings.length - 1].replace(\n /\\r?\\n([\\t ]*)$/,\n '',\n );\n\n // 2. Find all line breaks to determine the highest common indentation level.\n const indentLengths = strings.reduce((arr, str) => {\n const matches = str.match(/\\n([\\t ]+|(?!\\s).)/g);\n if (matches) {\n return arr.concat(\n matches.map((match) => match.match(/[\\t ]/g)?.length ?? 0),\n );\n }\n return arr;\n }, []);\n\n // 3. Remove the common indentation from all strings.\n if (indentLengths.length) {\n const pattern = new RegExp(`\\n[\\t ]{${Math.min(...indentLengths)}}`, 'g');\n\n strings = strings.map((str) => str.replace(pattern, '\\n'));\n }\n\n // 4. Remove leading whitespace.\n strings[0] = strings[0].replace(/^\\r?\\n/, '');\n\n // 5. Perform interpolation.\n let string = strings[0];\n\n values.forEach((value, i) => {\n // 5.1 Read current indentation level\n const endentations = string.match(/(?:^|\\n)( *)$/)\n const endentation = endentations ? endentations[1] : ''\n let indentedValue = value\n // 5.2 Add indentation to values with multiline strings\n if (typeof value === 'string' && value.includes('\\n')) {\n indentedValue = String(value)\n .split('\\n')\n .map((str, i) => {\n return i === 0 ? str : `${endentation}${str}`\n })\n .join('\\n');\n }\n\n string += indentedValue + strings[i + 1];\n });\n\n return string;\n}\n\nexport default dedent;\n","import { JSDOM } from 'jsdom';\n\nexport const injectPreviewHtml = (previewHtml: string, targetHtml: string) => {\n const previewDom = new JSDOM(previewHtml);\n\n const previewHead = previewDom.window.document.head;\n const previewBody = previewDom.window.document.body;\n\n return targetHtml\n .replace('', previewHead.innerHTML)\n .replace('', previewBody.innerHTML);\n};\n","import { createUnplugin } from 'unplugin';\nimport dedent from 'ts-dedent';\nimport VirtualModulesPlugin from 'webpack-virtual-modules';\nimport { generateSymfonyPreview } from './symfony';\nimport { computeAdditionalWatchPaths } from './computeAdditionalWatchPaths';\nimport HtmlWebpackPlugin from 'html-webpack-plugin';\nimport { logger } from '@storybook/node-logger';\nimport { injectPreviewHtml } from './injectPreviewHtml';\n\nconst PLUGIN_NAME = 'dev-preview-plugin';\n\nexport type Options = {\n projectDir: string;\n server: string;\n additionalWatchPaths: string[];\n};\n\n/**\n * Compile preview HTML for dev with HMR .\n */\nexport const DevPreviewCompilerPlugin = createUnplugin((options) => {\n const { projectDir, server, additionalWatchPaths } = options;\n\n return {\n name: PLUGIN_NAME,\n enforce: 'post',\n transformInclude(id) {\n return /storybook-config-entry\\.js$/.test(id);\n },\n async transform(code) {\n return dedent`\n import { symfonyPreview } from './symfony-preview.js';\n \n ${code}\n\n window.__SYMFONY_PREVIEW__ = symfonyPreview;\n if (import.meta.webpackHot) {\n import.meta.webpackHot.accept('./symfony-preview.js', () => {\n const iframe = window.top.document.getElementById('storybook-preview-iframe');\n if (iframe) {\n iframe.src = iframe.src;\n }\n });\n }\n `;\n },\n webpack(compiler) {\n // Virtual plugin for preview module\n const v = new VirtualModulesPlugin();\n v.apply(compiler);\n\n let previewHtml = '';\n\n // Compile preview before each compilation in watch mode\n compiler.hooks.watchRun.tapPromise(PLUGIN_NAME, async () => {\n previewHtml = await generateSymfonyPreview(server);\n\n // Write preview module\n v.writeModule(\n './symfony-preview.js',\n dedent`\n export const symfonyPreview = {\n html: \\`${previewHtml}\\`,\n };`\n );\n });\n\n compiler.hooks.afterCompile.tap(PLUGIN_NAME, (compilation) => {\n if ('HtmlWebpackCompiler' == compilation.name) {\n // Register additional watch paths for HMR\n const resolvedWatchPaths = computeAdditionalWatchPaths(additionalWatchPaths, projectDir);\n compilation.contextDependencies.addAll(resolvedWatchPaths.dirs);\n compilation.fileDependencies.addAll(resolvedWatchPaths.files);\n }\n });\n\n compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {\n // Inject previewHead and previewBody in the compiled iframe.html before it is output\n HtmlWebpackPlugin.getHooks(compilation).afterTemplateExecution.tapPromise(\n PLUGIN_NAME,\n async (params) => {\n try {\n params.html = injectPreviewHtml(previewHtml, params.html);\n return params;\n } catch (err) {\n logger.error(dedent`\n Failed to inject Symfony preview template in main iframe.html.\n ERR: ${err}\n `);\n return params;\n }\n }\n );\n });\n },\n };\n});\n","import { join } from 'path';\nimport isGlob from 'is-glob';\nimport { glob } from 'glob';\nimport fs from 'node:fs';\nimport { logger } from '@storybook/node-logger';\nimport dedent from 'ts-dedent';\n\ntype AdditionalWatchPaths = {\n dirs: string[];\n files: string[];\n};\n\nexport const computeAdditionalWatchPaths = (paths: string[], baseDir: string) => {\n const result: AdditionalWatchPaths = {\n dirs: [],\n files: [],\n };\n\n paths.forEach((watchPath) => {\n const absoluteWatchPath = join(baseDir, watchPath);\n\n if (isGlob(absoluteWatchPath)) {\n result.files.push(\n ...glob.sync(absoluteWatchPath, {\n dot: true,\n absolute: true,\n })\n );\n } else if (fs.existsSync(watchPath)) {\n const stats = fs.lstatSync(watchPath);\n (stats.isDirectory() ? result.dirs : result.files).push(watchPath);\n } else if (fs.existsSync(absoluteWatchPath)) {\n const stats = fs.lstatSync(absoluteWatchPath);\n (stats.isDirectory() ? result.dirs : result.files).push(absoluteWatchPath);\n } else {\n logger.warn(dedent`\n Ignoring additional watch path '${watchPath}': path doesn't exists.\n `);\n }\n });\n\n return result;\n};\n","import expand from 'brace-expansion'\nimport { assertValidPattern } from './assert-valid-pattern.js'\nimport { AST, ExtglobType } from './ast.js'\nimport { escape } from './escape.js'\nimport { unescape } from './unescape.js'\n\ntype Platform =\n | 'aix'\n | 'android'\n | 'darwin'\n | 'freebsd'\n | 'haiku'\n | 'linux'\n | 'openbsd'\n | 'sunos'\n | 'win32'\n | 'cygwin'\n | 'netbsd'\n\nexport interface MinimatchOptions {\n nobrace?: boolean\n nocomment?: boolean\n nonegate?: boolean\n debug?: boolean\n noglobstar?: boolean\n noext?: boolean\n nonull?: boolean\n windowsPathsNoEscape?: boolean\n allowWindowsEscape?: boolean\n partial?: boolean\n dot?: boolean\n nocase?: boolean\n nocaseMagicOnly?: boolean\n magicalBraces?: boolean\n matchBase?: boolean\n flipNegate?: boolean\n preserveMultipleSlashes?: boolean\n optimizationLevel?: number\n platform?: Platform\n windowsNoMagicRoot?: boolean\n}\n\nexport const minimatch = (\n p: string,\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n assertValidPattern(pattern)\n\n // shortcut: comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n return false\n }\n\n return new Minimatch(pattern, options).match(p)\n}\n\n// Optimized checking for the most common glob patterns.\nconst starDotExtRE = /^\\*+([^+@!?\\*\\[\\(]*)$/\nconst starDotExtTest = (ext: string) => (f: string) =>\n !f.startsWith('.') && f.endsWith(ext)\nconst starDotExtTestDot = (ext: string) => (f: string) => f.endsWith(ext)\nconst starDotExtTestNocase = (ext: string) => {\n ext = ext.toLowerCase()\n return (f: string) => !f.startsWith('.') && f.toLowerCase().endsWith(ext)\n}\nconst starDotExtTestNocaseDot = (ext: string) => {\n ext = ext.toLowerCase()\n return (f: string) => f.toLowerCase().endsWith(ext)\n}\nconst starDotStarRE = /^\\*+\\.\\*+$/\nconst starDotStarTest = (f: string) => !f.startsWith('.') && f.includes('.')\nconst starDotStarTestDot = (f: string) =>\n f !== '.' && f !== '..' && f.includes('.')\nconst dotStarRE = /^\\.\\*+$/\nconst dotStarTest = (f: string) => f !== '.' && f !== '..' && f.startsWith('.')\nconst starRE = /^\\*+$/\nconst starTest = (f: string) => f.length !== 0 && !f.startsWith('.')\nconst starTestDot = (f: string) => f.length !== 0 && f !== '.' && f !== '..'\nconst qmarksRE = /^\\?+([^+@!?\\*\\[\\(]*)?$/\nconst qmarksTestNocase = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExt([$0])\n if (!ext) return noext\n ext = ext.toLowerCase()\n return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestNocaseDot = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExtDot([$0])\n if (!ext) return noext\n ext = ext.toLowerCase()\n return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestDot = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExtDot([$0])\n return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTest = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExt([$0])\n return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTestNoExt = ([$0]: RegExpMatchArray) => {\n const len = $0.length\n return (f: string) => f.length === len && !f.startsWith('.')\n}\nconst qmarksTestNoExtDot = ([$0]: RegExpMatchArray) => {\n const len = $0.length\n return (f: string) => f.length === len && f !== '.' && f !== '..'\n}\n\n/* c8 ignore start */\nconst defaultPlatform: Platform = (\n typeof process === 'object' && process\n ? (typeof process.env === 'object' &&\n process.env &&\n process.env.__MINIMATCH_TESTING_PLATFORM__) ||\n process.platform\n : 'posix'\n) as Platform\ntype Sep = '\\\\' | '/'\nconst path: { [k: string]: { sep: Sep } } = {\n win32: { sep: '\\\\' },\n posix: { sep: '/' },\n}\n/* c8 ignore stop */\n\nexport const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep\nminimatch.sep = sep\n\nexport const GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\n\n// any single thing other than /\n// don't need to escape / when using new RegExp()\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n\n// ** when dots are allowed. Anything goes, except .. and .\n// not (^ or / followed by one or two dots followed by $ or /),\n// followed by anything, any number of times.\nconst twoStarDot = '(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?'\n\n// not a ^ or / followed by a dot,\n// followed by anything, any number of times.\nconst twoStarNoDot = '(?:(?!(?:\\\\/|^)\\\\.).)*?'\n\nexport const filter =\n (pattern: string, options: MinimatchOptions = {}) =>\n (p: string) =>\n minimatch(p, pattern, options)\nminimatch.filter = filter\n\nconst ext = (a: MinimatchOptions, b: MinimatchOptions = {}) =>\n Object.assign({}, a, b)\n\nexport const defaults = (def: MinimatchOptions): typeof minimatch => {\n if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n return minimatch\n }\n\n const orig = minimatch\n\n const m = (p: string, pattern: string, options: MinimatchOptions = {}) =>\n orig(p, pattern, ext(def, options))\n\n return Object.assign(m, {\n Minimatch: class Minimatch extends orig.Minimatch {\n constructor(pattern: string, options: MinimatchOptions = {}) {\n super(pattern, ext(def, options))\n }\n static defaults(options: MinimatchOptions) {\n return orig.defaults(ext(def, options)).Minimatch\n }\n },\n\n AST: class AST extends orig.AST {\n /* c8 ignore start */\n constructor(\n type: ExtglobType | null,\n parent?: AST,\n options: MinimatchOptions = {}\n ) {\n super(type, parent, ext(def, options))\n }\n /* c8 ignore stop */\n\n static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n return orig.AST.fromGlob(pattern, ext(def, options))\n }\n },\n\n unescape: (\n s: string,\n options: Pick = {}\n ) => orig.unescape(s, ext(def, options)),\n\n escape: (\n s: string,\n options: Pick = {}\n ) => orig.escape(s, ext(def, options)),\n\n filter: (pattern: string, options: MinimatchOptions = {}) =>\n orig.filter(pattern, ext(def, options)),\n\n defaults: (options: MinimatchOptions) => orig.defaults(ext(def, options)),\n\n makeRe: (pattern: string, options: MinimatchOptions = {}) =>\n orig.makeRe(pattern, ext(def, options)),\n\n braceExpand: (pattern: string, options: MinimatchOptions = {}) =>\n orig.braceExpand(pattern, ext(def, options)),\n\n match: (list: string[], pattern: string, options: MinimatchOptions = {}) =>\n orig.match(list, pattern, ext(def, options)),\n\n sep: orig.sep,\n GLOBSTAR: GLOBSTAR as typeof GLOBSTAR,\n })\n}\nminimatch.defaults = defaults\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n assertValidPattern(pattern)\n\n // Thanks to Yeting Li for\n // improving this regexp to avoid a ReDOS vulnerability.\n if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n // shortcut. no need to expand.\n return [pattern]\n }\n\n return expand(pattern)\n}\nminimatch.braceExpand = braceExpand\n\n// parse a component of the expanded set.\n// At this point, no pattern may contain \"/\" in it\n// so we're going to return a 2d array, where each entry is the full\n// pattern, split on '/', and then turned into a regular expression.\n// A regexp is made at the end which joins each array with an\n// escaped /, and another full one which joins each regexp with |.\n//\n// Following the lead of Bash 4.1, note that \"**\" only has special meaning\n// when it is the *only* thing in a path portion. Otherwise, any series\n// of * is equivalent to a single *. Globstar behavior is enabled by\n// default, and can be disabled by setting options.noglobstar.\n\nexport const makeRe = (pattern: string, options: MinimatchOptions = {}) =>\n new Minimatch(pattern, options).makeRe()\nminimatch.makeRe = makeRe\n\nexport const match = (\n list: string[],\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n const mm = new Minimatch(pattern, options)\n list = list.filter(f => mm.match(f))\n if (mm.options.nonull && !list.length) {\n list.push(pattern)\n }\n return list\n}\nminimatch.match = match\n\n// replace stuff like \\* with *\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/\nconst regExpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\nexport type MMRegExp = RegExp & {\n _src?: string\n _glob?: string\n}\n\nexport type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR\nexport type ParseReturn = ParseReturnFiltered | false\n\nexport class Minimatch {\n options: MinimatchOptions\n set: ParseReturnFiltered[][]\n pattern: string\n\n windowsPathsNoEscape: boolean\n nonegate: boolean\n negate: boolean\n comment: boolean\n empty: boolean\n preserveMultipleSlashes: boolean\n partial: boolean\n globSet: string[]\n globParts: string[][]\n nocase: boolean\n\n isWindows: boolean\n platform: Platform\n windowsNoMagicRoot: boolean\n\n regexp: false | null | MMRegExp\n constructor(pattern: string, options: MinimatchOptions = {}) {\n assertValidPattern(pattern)\n\n options = options || {}\n this.options = options\n this.pattern = pattern\n this.platform = options.platform || defaultPlatform\n this.isWindows = this.platform === 'win32'\n this.windowsPathsNoEscape =\n !!options.windowsPathsNoEscape || options.allowWindowsEscape === false\n if (this.windowsPathsNoEscape) {\n this.pattern = this.pattern.replace(/\\\\/g, '/')\n }\n this.preserveMultipleSlashes = !!options.preserveMultipleSlashes\n this.regexp = null\n this.negate = false\n this.nonegate = !!options.nonegate\n this.comment = false\n this.empty = false\n this.partial = !!options.partial\n this.nocase = !!this.options.nocase\n this.windowsNoMagicRoot =\n options.windowsNoMagicRoot !== undefined\n ? options.windowsNoMagicRoot\n : !!(this.isWindows && this.nocase)\n\n this.globSet = []\n this.globParts = []\n this.set = []\n\n // make the set of regexps etc.\n this.make()\n }\n\n hasMagic(): boolean {\n if (this.options.magicalBraces && this.set.length > 1) {\n return true\n }\n for (const pattern of this.set) {\n for (const part of pattern) {\n if (typeof part !== 'string') return true\n }\n }\n return false\n }\n\n debug(..._: any[]) {}\n\n make() {\n const pattern = this.pattern\n const options = this.options\n\n // empty patterns and comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n this.comment = true\n return\n }\n\n if (!pattern) {\n this.empty = true\n return\n }\n\n // step 1: figure out negation, etc.\n this.parseNegate()\n\n // step 2: expand braces\n this.globSet = [...new Set(this.braceExpand())]\n\n if (options.debug) {\n this.debug = (...args: any[]) => console.error(...args)\n }\n\n this.debug(this.pattern, this.globSet)\n\n // step 3: now we have a set, so turn each one into a series of\n // path-portion matching patterns.\n // These will be regexps, except in the case of \"**\", which is\n // set to the GLOBSTAR object for globstar behavior,\n // and will not contain any / characters\n //\n // First, we preprocess to make the glob pattern sets a bit simpler\n // and deduped. There are some perf-killing patterns that can cause\n // problems with a glob walk, but we can simplify them down a bit.\n const rawGlobParts = this.globSet.map(s => this.slashSplit(s))\n this.globParts = this.preprocess(rawGlobParts)\n this.debug(this.pattern, this.globParts)\n\n // glob --> regexps\n let set = this.globParts.map((s, _, __) => {\n if (this.isWindows && this.windowsNoMagicRoot) {\n // check if it's a drive or unc path.\n const isUNC =\n s[0] === '' &&\n s[1] === '' &&\n (s[2] === '?' || !globMagic.test(s[2])) &&\n !globMagic.test(s[3])\n const isDrive = /^[a-z]:/i.test(s[0])\n if (isUNC) {\n return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))]\n } else if (isDrive) {\n return [s[0], ...s.slice(1).map(ss => this.parse(ss))]\n }\n }\n return s.map(ss => this.parse(ss))\n })\n\n this.debug(this.pattern, set)\n\n // filter out everything that didn't compile properly.\n this.set = set.filter(\n s => s.indexOf(false) === -1\n ) as ParseReturnFiltered[][]\n\n // do not treat the ? in UNC paths as magic\n if (this.isWindows) {\n for (let i = 0; i < this.set.length; i++) {\n const p = this.set[i]\n if (\n p[0] === '' &&\n p[1] === '' &&\n this.globParts[i][2] === '?' &&\n typeof p[3] === 'string' &&\n /^[a-z]:$/i.test(p[3])\n ) {\n p[2] = '?'\n }\n }\n }\n\n this.debug(this.pattern, this.set)\n }\n\n // various transforms to equivalent pattern sets that are\n // faster to process in a filesystem walk. The goal is to\n // eliminate what we can, and push all ** patterns as far\n // to the right as possible, even if it increases the number\n // of patterns that we have to process.\n preprocess(globParts: string[][]) {\n // if we're not in globstar mode, then turn all ** into *\n if (this.options.noglobstar) {\n for (let i = 0; i < globParts.length; i++) {\n for (let j = 0; j < globParts[i].length; j++) {\n if (globParts[i][j] === '**') {\n globParts[i][j] = '*'\n }\n }\n }\n }\n\n const { optimizationLevel = 1 } = this.options\n\n if (optimizationLevel >= 2) {\n // aggressive optimization for the purpose of fs walking\n globParts = this.firstPhasePreProcess(globParts)\n globParts = this.secondPhasePreProcess(globParts)\n } else if (optimizationLevel >= 1) {\n // just basic optimizations to remove some .. parts\n globParts = this.levelOneOptimize(globParts)\n } else {\n globParts = this.adjascentGlobstarOptimize(globParts)\n }\n\n return globParts\n }\n\n // just get rid of adjascent ** portions\n adjascentGlobstarOptimize(globParts: string[][]) {\n return globParts.map(parts => {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let i = gs\n while (parts[i + 1] === '**') {\n i++\n }\n if (i !== gs) {\n parts.splice(gs, i - gs)\n }\n }\n return parts\n })\n }\n\n // get rid of adjascent ** and resolve .. portions\n levelOneOptimize(globParts: string[][]) {\n return globParts.map(parts => {\n parts = parts.reduce((set: string[], part) => {\n const prev = set[set.length - 1]\n if (part === '**' && prev === '**') {\n return set\n }\n if (part === '..') {\n if (prev && prev !== '..' && prev !== '.' && prev !== '**') {\n set.pop()\n return set\n }\n }\n set.push(part)\n return set\n }, [])\n return parts.length === 0 ? [''] : parts\n })\n }\n\n levelTwoFileOptimize(parts: string | string[]) {\n if (!Array.isArray(parts)) {\n parts = this.slashSplit(parts)\n }\n let didSomething: boolean = false\n do {\n didSomething = false\n //
// -> 
/\n      if (!this.preserveMultipleSlashes) {\n        for (let i = 1; i < parts.length - 1; i++) {\n          const p = parts[i]\n          // don't squeeze out UNC patterns\n          if (i === 1 && p === '' && parts[0] === '') continue\n          if (p === '.' || p === '') {\n            didSomething = true\n            parts.splice(i, 1)\n            i--\n          }\n        }\n        if (\n          parts[0] === '.' &&\n          parts.length === 2 &&\n          (parts[1] === '.' || parts[1] === '')\n        ) {\n          didSomething = true\n          parts.pop()\n        }\n      }\n\n      // 
/

/../ ->

/\n      let dd: number = 0\n      while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n        const p = parts[dd - 1]\n        if (p && p !== '.' && p !== '..' && p !== '**') {\n          didSomething = true\n          parts.splice(dd - 1, 2)\n          dd -= 2\n        }\n      }\n    } while (didSomething)\n    return parts.length === 0 ? [''] : parts\n  }\n\n  // First phase: single-pattern processing\n  // 
 is 1 or more portions\n  //  is 1 or more portions\n  // 

is any portion other than ., .., '', or **\n // is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n //

// -> 
/\n  // 
/

/../ ->

/\n  // **/**/ -> **/\n  //\n  // **/*/ -> */**/ <== not valid because ** doesn't follow\n  // this WOULD be allowed if ** did follow symlinks, or * didn't\n  firstPhasePreProcess(globParts: string[][]) {\n    let didSomething = false\n    do {\n      didSomething = false\n      // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n for (let parts of globParts) {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss: number = gs\n while (parts[gss + 1] === '**') {\n //

/**/**/ -> 
/**/\n            gss++\n          }\n          // eg, if gs is 2 and gss is 4, that means we have 3 **\n          // parts, and can remove 2 of them.\n          if (gss > gs) {\n            parts.splice(gs + 1, gss - gs)\n          }\n\n          let next = parts[gs + 1]\n          const p = parts[gs + 2]\n          const p2 = parts[gs + 3]\n          if (next !== '..') continue\n          if (\n            !p ||\n            p === '.' ||\n            p === '..' ||\n            !p2 ||\n            p2 === '.' ||\n            p2 === '..'\n          ) {\n            continue\n          }\n          didSomething = true\n          // edit parts in place, and push the new one\n          parts.splice(gs, 1)\n          const other = parts.slice(0)\n          other[gs] = '**'\n          globParts.push(other)\n          gs--\n        }\n\n        // 
// -> 
/\n        if (!this.preserveMultipleSlashes) {\n          for (let i = 1; i < parts.length - 1; i++) {\n            const p = parts[i]\n            // don't squeeze out UNC patterns\n            if (i === 1 && p === '' && parts[0] === '') continue\n            if (p === '.' || p === '') {\n              didSomething = true\n              parts.splice(i, 1)\n              i--\n            }\n          }\n          if (\n            parts[0] === '.' &&\n            parts.length === 2 &&\n            (parts[1] === '.' || parts[1] === '')\n          ) {\n            didSomething = true\n            parts.pop()\n          }\n        }\n\n        // 
/

/../ ->

/\n        let dd: number = 0\n        while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n          const p = parts[dd - 1]\n          if (p && p !== '.' && p !== '..' && p !== '**') {\n            didSomething = true\n            const needDot = dd === 1 && parts[dd + 1] === '**'\n            const splin = needDot ? ['.'] : []\n            parts.splice(dd - 1, 2, ...splin)\n            if (parts.length === 0) parts.push('')\n            dd -= 2\n          }\n        }\n      }\n    } while (didSomething)\n\n    return globParts\n  }\n\n  // second phase: multi-pattern dedupes\n  // {
/*/,
/

/} ->

/*/\n  // {
/,
/} -> 
/\n  // {
/**/,
/} -> 
/**/\n  //\n  // {
/**/,
/**/

/} ->

/**/\n  // ^-- not valid because ** doens't follow symlinks\n  secondPhasePreProcess(globParts: string[][]): string[][] {\n    for (let i = 0; i < globParts.length - 1; i++) {\n      for (let j = i + 1; j < globParts.length; j++) {\n        const matched = this.partsMatch(\n          globParts[i],\n          globParts[j],\n          !this.preserveMultipleSlashes\n        )\n        if (!matched) continue\n        globParts[i] = matched\n        globParts[j] = []\n      }\n    }\n    return globParts.filter(gs => gs.length)\n  }\n\n  partsMatch(\n    a: string[],\n    b: string[],\n    emptyGSMatch: boolean = false\n  ): false | string[] {\n    let ai = 0\n    let bi = 0\n    let result: string[] = []\n    let which: string = ''\n    while (ai < a.length && bi < b.length) {\n      if (a[ai] === b[bi]) {\n        result.push(which === 'b' ? b[bi] : a[ai])\n        ai++\n        bi++\n      } else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {\n        result.push(a[ai])\n        ai++\n      } else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {\n        result.push(b[bi])\n        bi++\n      } else if (\n        a[ai] === '*' &&\n        b[bi] &&\n        (this.options.dot || !b[bi].startsWith('.')) &&\n        b[bi] !== '**'\n      ) {\n        if (which === 'b') return false\n        which = 'a'\n        result.push(a[ai])\n        ai++\n        bi++\n      } else if (\n        b[bi] === '*' &&\n        a[ai] &&\n        (this.options.dot || !a[ai].startsWith('.')) &&\n        a[ai] !== '**'\n      ) {\n        if (which === 'a') return false\n        which = 'b'\n        result.push(b[bi])\n        ai++\n        bi++\n      } else {\n        return false\n      }\n    }\n    // if we fall out of the loop, it means they two are identical\n    // as long as their lengths match\n    return a.length === b.length && result\n  }\n\n  parseNegate() {\n    if (this.nonegate) return\n\n    const pattern = this.pattern\n    let negate = false\n    let negateOffset = 0\n\n    for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n      negate = !negate\n      negateOffset++\n    }\n\n    if (negateOffset) this.pattern = pattern.slice(negateOffset)\n    this.negate = negate\n  }\n\n  // set partial to true to test if, for example,\n  // \"/a/b\" matches the start of \"/*/b/*/d\"\n  // Partial means, if you run out of file before you run\n  // out of pattern, then that's fine, as long as all\n  // the parts match.\n  matchOne(file: string[], pattern: ParseReturn[], partial: boolean = false) {\n    const options = this.options\n\n    // UNC paths like //?/X:/... can match X:/... and vice versa\n    // Drive letters in absolute drive or unc paths are always compared\n    // case-insensitively.\n    if (this.isWindows) {\n      const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0])\n      const fileUNC =\n        !fileDrive &&\n        file[0] === '' &&\n        file[1] === '' &&\n        file[2] === '?' &&\n        /^[a-z]:$/i.test(file[3])\n\n      const patternDrive =\n        typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0])\n      const patternUNC =\n        !patternDrive &&\n        pattern[0] === '' &&\n        pattern[1] === '' &&\n        pattern[2] === '?' &&\n        typeof pattern[3] === 'string' &&\n        /^[a-z]:$/i.test(pattern[3])\n\n      const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined\n      const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined\n      if (typeof fdi === 'number' && typeof pdi === 'number') {\n        const [fd, pd]: [string, string] = [file[fdi], pattern[pdi] as string]\n        if (fd.toLowerCase() === pd.toLowerCase()) {\n          pattern[pdi] = fd\n          if (pdi > fdi) {\n            pattern = pattern.slice( pdi)\n          } else if (fdi > pdi) {\n            file = file.slice(fdi)\n          }\n        }\n      }\n    }\n\n    // resolve and reduce . and .. portions in the file as well.\n    // dont' need to do the second phase, because it's only one string[]\n    const { optimizationLevel = 1 } = this.options\n    if (optimizationLevel >= 2) {\n      file = this.levelTwoFileOptimize(file)\n    }\n\n    this.debug('matchOne', this, { file, pattern })\n    this.debug('matchOne', file.length, pattern.length)\n\n    for (\n      var fi = 0, pi = 0, fl = file.length, pl = pattern.length;\n      fi < fl && pi < pl;\n      fi++, pi++\n    ) {\n      this.debug('matchOne loop')\n      var p = pattern[pi]\n      var f = file[fi]\n\n      this.debug(pattern, p, f)\n\n      // should be impossible.\n      // some invalid regexp stuff in the set.\n      /* c8 ignore start */\n      if (p === false) {\n        return false\n      }\n      /* c8 ignore stop */\n\n      if (p === GLOBSTAR) {\n        this.debug('GLOBSTAR', [pattern, p, f])\n\n        // \"**\"\n        // a/**/b/**/c would match the following:\n        // a/b/x/y/z/c\n        // a/x/y/z/b/c\n        // a/b/x/b/x/c\n        // a/b/c\n        // To do this, take the rest of the pattern after\n        // the **, and see if it would match the file remainder.\n        // If so, return success.\n        // If not, the ** \"swallows\" a segment, and try again.\n        // This is recursively awful.\n        //\n        // a/**/b/**/c matching a/b/x/y/z/c\n        // - a matches a\n        // - doublestar\n        //   - matchOne(b/x/y/z/c, b/**/c)\n        //     - b matches b\n        //     - doublestar\n        //       - matchOne(x/y/z/c, c) -> no\n        //       - matchOne(y/z/c, c) -> no\n        //       - matchOne(z/c, c) -> no\n        //       - matchOne(c, c) yes, hit\n        var fr = fi\n        var pr = pi + 1\n        if (pr === pl) {\n          this.debug('** at the end')\n          // a ** at the end will just swallow the rest.\n          // We have found a match.\n          // however, it will not swallow /.x, unless\n          // options.dot is set.\n          // . and .. are *never* matched by **, for explosively\n          // exponential reasons.\n          for (; fi < fl; fi++) {\n            if (\n              file[fi] === '.' ||\n              file[fi] === '..' ||\n              (!options.dot && file[fi].charAt(0) === '.')\n            )\n              return false\n          }\n          return true\n        }\n\n        // ok, let's see if we can swallow whatever we can.\n        while (fr < fl) {\n          var swallowee = file[fr]\n\n          this.debug('\\nglobstar while', file, fr, pattern, pr, swallowee)\n\n          // XXX remove this slice.  Just pass the start index.\n          if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {\n            this.debug('globstar found match!', fr, fl, swallowee)\n            // found a match.\n            return true\n          } else {\n            // can't swallow \".\" or \"..\" ever.\n            // can only swallow \".foo\" when explicitly asked.\n            if (\n              swallowee === '.' ||\n              swallowee === '..' ||\n              (!options.dot && swallowee.charAt(0) === '.')\n            ) {\n              this.debug('dot detected!', file, fr, pattern, pr)\n              break\n            }\n\n            // ** swallows a segment, and continue.\n            this.debug('globstar swallow a segment, and continue')\n            fr++\n          }\n        }\n\n        // no match was found.\n        // However, in partial mode, we can't say this is necessarily over.\n        /* c8 ignore start */\n        if (partial) {\n          // ran out of file\n          this.debug('\\n>>> no match, partial?', file, fr, pattern, pr)\n          if (fr === fl) {\n            return true\n          }\n        }\n        /* c8 ignore stop */\n        return false\n      }\n\n      // something other than **\n      // non-magic patterns just have to match exactly\n      // patterns with magic have been turned into regexps.\n      let hit: boolean\n      if (typeof p === 'string') {\n        hit = f === p\n        this.debug('string match', p, f, hit)\n      } else {\n        hit = p.test(f)\n        this.debug('pattern match', p, f, hit)\n      }\n\n      if (!hit) return false\n    }\n\n    // Note: ending in / means that we'll get a final \"\"\n    // at the end of the pattern.  This can only match a\n    // corresponding \"\" at the end of the file.\n    // If the file ends in /, then it can only match a\n    // a pattern that ends in /, unless the pattern just\n    // doesn't have any more for it. But, a/b/ should *not*\n    // match \"a/b/*\", even though \"\" matches against the\n    // [^/]*? pattern, except in partial mode, where it might\n    // simply not be reached yet.\n    // However, a/b/ should still satisfy a/*\n\n    // now either we fell off the end of the pattern, or we're done.\n    if (fi === fl && pi === pl) {\n      // ran out of pattern and filename at the same time.\n      // an exact hit!\n      return true\n    } else if (fi === fl) {\n      // ran out of file, but still had pattern left.\n      // this is ok if we're doing the match as part of\n      // a glob fs traversal.\n      return partial\n    } else if (pi === pl) {\n      // ran out of pattern, still have file left.\n      // this is only acceptable if we're on the very last\n      // empty segment of a file with a trailing slash.\n      // a/* should match a/b/\n      return fi === fl - 1 && file[fi] === ''\n\n      /* c8 ignore start */\n    } else {\n      // should be unreachable.\n      throw new Error('wtf?')\n    }\n    /* c8 ignore stop */\n  }\n\n  braceExpand() {\n    return braceExpand(this.pattern, this.options)\n  }\n\n  parse(pattern: string): ParseReturn {\n    assertValidPattern(pattern)\n\n    const options = this.options\n\n    // shortcuts\n    if (pattern === '**') return GLOBSTAR\n    if (pattern === '') return ''\n\n    // far and away, the most common glob pattern parts are\n    // *, *.*, and *.  Add a fast check method for those.\n    let m: RegExpMatchArray | null\n    let fastTest: null | ((f: string) => boolean) = null\n    if ((m = pattern.match(starRE))) {\n      fastTest = options.dot ? starTestDot : starTest\n    } else if ((m = pattern.match(starDotExtRE))) {\n      fastTest = (\n        options.nocase\n          ? options.dot\n            ? starDotExtTestNocaseDot\n            : starDotExtTestNocase\n          : options.dot\n          ? starDotExtTestDot\n          : starDotExtTest\n      )(m[1])\n    } else if ((m = pattern.match(qmarksRE))) {\n      fastTest = (\n        options.nocase\n          ? options.dot\n            ? qmarksTestNocaseDot\n            : qmarksTestNocase\n          : options.dot\n          ? qmarksTestDot\n          : qmarksTest\n      )(m)\n    } else if ((m = pattern.match(starDotStarRE))) {\n      fastTest = options.dot ? starDotStarTestDot : starDotStarTest\n    } else if ((m = pattern.match(dotStarRE))) {\n      fastTest = dotStarTest\n    }\n\n    const re = AST.fromGlob(pattern, this.options).toMMPattern()\n    return fastTest ? Object.assign(re, { test: fastTest }) : re\n  }\n\n  makeRe() {\n    if (this.regexp || this.regexp === false) return this.regexp\n\n    // at this point, this.set is a 2d array of partial\n    // pattern strings, or \"**\".\n    //\n    // It's better to use .match().  This function shouldn't\n    // be used, really, but it's pretty convenient sometimes,\n    // when you just want to work with a regex.\n    const set = this.set\n\n    if (!set.length) {\n      this.regexp = false\n      return this.regexp\n    }\n    const options = this.options\n\n    const twoStar = options.noglobstar\n      ? star\n      : options.dot\n      ? twoStarDot\n      : twoStarNoDot\n    const flags = new Set(options.nocase ? ['i'] : [])\n\n    // regexpify non-globstar patterns\n    // if ** is only item, then we just do one twoStar\n    // if ** is first, and there are more, prepend (\\/|twoStar\\/)? to next\n    // if ** is last, append (\\/twoStar|) to previous\n    // if ** is in the middle, append (\\/|\\/twoStar\\/) to previous\n    // then filter out GLOBSTAR symbols\n    let re = set\n      .map(pattern => {\n        const pp: (string | typeof GLOBSTAR)[] = pattern.map(p => {\n          if (p instanceof RegExp) {\n            for (const f of p.flags.split('')) flags.add(f)\n          }\n          return typeof p === 'string'\n            ? regExpEscape(p)\n            : p === GLOBSTAR\n            ? GLOBSTAR\n            : p._src\n        }) as (string | typeof GLOBSTAR)[]\n        pp.forEach((p, i) => {\n          const next = pp[i + 1]\n          const prev = pp[i - 1]\n          if (p !== GLOBSTAR || prev === GLOBSTAR) {\n            return\n          }\n          if (prev === undefined) {\n            if (next !== undefined && next !== GLOBSTAR) {\n              pp[i + 1] = '(?:\\\\/|' + twoStar + '\\\\/)?' + next\n            } else {\n              pp[i] = twoStar\n            }\n          } else if (next === undefined) {\n            pp[i - 1] = prev + '(?:\\\\/|' + twoStar + ')?'\n          } else if (next !== GLOBSTAR) {\n            pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + '\\\\/)' + next\n            pp[i + 1] = GLOBSTAR\n          }\n        })\n        return pp.filter(p => p !== GLOBSTAR).join('/')\n      })\n      .join('|')\n\n    // need to wrap in parens if we had more than one thing with |,\n    // otherwise only the first will be anchored to ^ and the last to $\n    const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', '']\n    // must match entire pattern\n    // ending in a * or ** will make it less strict.\n    re = '^' + open + re + close + '$'\n\n    // can match anything, as long as it's not this.\n    if (this.negate) re = '^(?!' + re + ').+$'\n\n    try {\n      this.regexp = new RegExp(re, [...flags].join(''))\n      /* c8 ignore start */\n    } catch (ex) {\n      // should be impossible\n      this.regexp = false\n    }\n    /* c8 ignore stop */\n    return this.regexp\n  }\n\n  slashSplit(p: string) {\n    // if p starts with // on windows, we preserve that\n    // so that UNC paths aren't broken.  Otherwise, any number of\n    // / characters are coalesced into one, unless\n    // preserveMultipleSlashes is set to true.\n    if (this.preserveMultipleSlashes) {\n      return p.split('/')\n    } else if (this.isWindows && /^\\/\\/[^\\/]+/.test(p)) {\n      // add an extra '' for the one we lose\n      return ['', ...p.split(/\\/+/)]\n    } else {\n      return p.split(/\\/+/)\n    }\n  }\n\n  match(f: string, partial = this.partial) {\n    this.debug('match', f, this.pattern)\n    // short-circuit in the case of busted things.\n    // comments, etc.\n    if (this.comment) {\n      return false\n    }\n    if (this.empty) {\n      return f === ''\n    }\n\n    if (f === '/' && partial) {\n      return true\n    }\n\n    const options = this.options\n\n    // windows: need to use /, not \\\n    if (this.isWindows) {\n      f = f.split('\\\\').join('/')\n    }\n\n    // treat the test path as a set of pathparts.\n    const ff = this.slashSplit(f)\n    this.debug(this.pattern, 'split', ff)\n\n    // just ONE of the pattern sets in this.set needs to match\n    // in order for it to be valid.  If negating, then just one\n    // match means that we have failed.\n    // Either way, return on the first hit.\n\n    const set = this.set\n    this.debug(this.pattern, 'set', set)\n\n    // Find the basename of the path by looking for the last non-empty segment\n    let filename: string = ff[ff.length - 1]\n    if (!filename) {\n      for (let i = ff.length - 2; !filename && i >= 0; i--) {\n        filename = ff[i]\n      }\n    }\n\n    for (let i = 0; i < set.length; i++) {\n      const pattern = set[i]\n      let file = ff\n      if (options.matchBase && pattern.length === 1) {\n        file = [filename]\n      }\n      const hit = this.matchOne(file, pattern, partial)\n      if (hit) {\n        if (options.flipNegate) {\n          return true\n        }\n        return !this.negate\n      }\n    }\n\n    // didn't get any hits.  this is success if it's a negative\n    // pattern, failure otherwise.\n    if (options.flipNegate) {\n      return false\n    }\n    return this.negate\n  }\n\n  static defaults(def: MinimatchOptions) {\n    return minimatch.defaults(def).Minimatch\n  }\n}\n/* c8 ignore start */\nexport { AST } from './ast.js'\nexport { escape } from './escape.js'\nexport { unescape } from './unescape.js'\n/* c8 ignore stop */\nminimatch.AST = AST\nminimatch.Minimatch = Minimatch\nminimatch.escape = escape\nminimatch.unescape = unescape\n","const MAX_PATTERN_LENGTH = 1024 * 64\nexport const assertValidPattern: (pattern: any) => void = (\n  pattern: any\n): asserts pattern is string => {\n  if (typeof pattern !== 'string') {\n    throw new TypeError('invalid pattern')\n  }\n\n  if (pattern.length > MAX_PATTERN_LENGTH) {\n    throw new TypeError('pattern is too long')\n  }\n}\n","// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { : [, /u flag required, negated]\nconst posixClasses: { [k: string]: [e: string, u: boolean, n?: boolean] } = {\n  '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}', true],\n  '[:alpha:]': ['\\\\p{L}\\\\p{Nl}', true],\n  '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f', false],\n  '[:blank:]': ['\\\\p{Zs}\\\\t', true],\n  '[:cntrl:]': ['\\\\p{Cc}', true],\n  '[:digit:]': ['\\\\p{Nd}', true],\n  '[:graph:]': ['\\\\p{Z}\\\\p{C}', true, true],\n  '[:lower:]': ['\\\\p{Ll}', true],\n  '[:print:]': ['\\\\p{C}', true],\n  '[:punct:]': ['\\\\p{P}', true],\n  '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f', true],\n  '[:upper:]': ['\\\\p{Lu}', true],\n  '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}', true],\n  '[:xdigit:]': ['A-Fa-f0-9', false],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n// escape all regexp magic characters\nconst regexpEscape = (s: string) =>\n  s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// everything has already been escaped, we just have to join\nconst rangesToString = (ranges: string[]): string => ranges.join('')\n\nexport type ParseClassResult = [\n  src: string,\n  uFlag: boolean,\n  consumed: number,\n  hasMagic: boolean\n]\n\n// takes a glob string at a posix brace expression, and returns\n// an equivalent regular expression source, and boolean indicating\n// whether the /u flag needs to be applied, and the number of chars\n// consumed to parse the character class.\n// This also removes out of order ranges, and returns ($.) if the\n// entire class just no good.\nexport const parseClass = (\n  glob: string,\n  position: number\n): ParseClassResult => {\n  const pos = position\n  /* c8 ignore start */\n  if (glob.charAt(pos) !== '[') {\n    throw new Error('not in a brace expression')\n  }\n  /* c8 ignore stop */\n  const ranges: string[] = []\n  const negs: string[] = []\n\n  let i = pos + 1\n  let sawStart = false\n  let uflag = false\n  let escaping = false\n  let negate = false\n  let endPos = pos\n  let rangeStart = ''\n  WHILE: while (i < glob.length) {\n    const c = glob.charAt(i)\n    if ((c === '!' || c === '^') && i === pos + 1) {\n      negate = true\n      i++\n      continue\n    }\n\n    if (c === ']' && sawStart && !escaping) {\n      endPos = i + 1\n      break\n    }\n\n    sawStart = true\n    if (c === '\\\\') {\n      if (!escaping) {\n        escaping = true\n        i++\n        continue\n      }\n      // escaped \\ char, fall through and treat like normal char\n    }\n    if (c === '[' && !escaping) {\n      // either a posix class, a collation equivalent, or just a [\n      for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {\n        if (glob.startsWith(cls, i)) {\n          // invalid, [a-[] is fine, but not [a-[:alpha]]\n          if (rangeStart) {\n            return ['$.', false, glob.length - pos, true]\n          }\n          i += cls.length\n          if (neg) negs.push(unip)\n          else ranges.push(unip)\n          uflag = uflag || u\n          continue WHILE\n        }\n      }\n    }\n\n    // now it's just a normal character, effectively\n    escaping = false\n    if (rangeStart) {\n      // throw this range away if it's not valid, but others\n      // can still match.\n      if (c > rangeStart) {\n        ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c))\n      } else if (c === rangeStart) {\n        ranges.push(braceEscape(c))\n      }\n      rangeStart = ''\n      i++\n      continue\n    }\n\n    // now might be the start of a range.\n    // can be either c-d or c-] or c] or c] at this point\n    if (glob.startsWith('-]', i + 1)) {\n      ranges.push(braceEscape(c + '-'))\n      i += 2\n      continue\n    }\n    if (glob.startsWith('-', i + 1)) {\n      rangeStart = c\n      i += 2\n      continue\n    }\n\n    // not the start of a range, just a single character\n    ranges.push(braceEscape(c))\n    i++\n  }\n\n  if (endPos < i) {\n    // didn't see the end of the class, not a valid class,\n    // but might still be valid as a literal match.\n    return ['', false, 0, false]\n  }\n\n  // if we got no ranges and no negates, then we have a range that\n  // cannot possibly match anything, and that poisons the whole glob\n  if (!ranges.length && !negs.length) {\n    return ['$.', false, glob.length - pos, true]\n  }\n\n  // if we got one positive range, and it's a single character, then that's\n  // not actually a magic pattern, it's just that one literal character.\n  // we should not treat that as \"magic\", we should just return the literal\n  // character. [_] is a perfectly valid way to escape glob magic chars.\n  if (\n    negs.length === 0 &&\n    ranges.length === 1 &&\n    /^\\\\?.$/.test(ranges[0]) &&\n    !negate\n  ) {\n    const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]\n    return [regexpEscape(r), false, endPos - pos, false]\n  }\n\n  const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'\n  const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'\n  const comb =\n    ranges.length && negs.length\n      ? '(' + sranges + '|' + snegs + ')'\n      : ranges.length\n      ? sranges\n      : snegs\n\n  return [comb, uflag, endPos - pos, true]\n}\n","import { MinimatchOptions } from './index.js'\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link windowsPathsNoEscape} option is used, then square-brace\n * escapes are removed, but not backslash escapes.  For example, it will turn\n * the string `'[*]'` into `*`, but it will not turn `'\\\\*'` into `'*'`,\n * becuase `\\` is a path separator in `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both brace escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n */\nexport const unescape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n  }: Pick = {}\n) => {\n  return windowsPathsNoEscape\n    ? s.replace(/\\[([^\\/\\\\])\\]/g, '$1')\n    : s.replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, '$1$2').replace(/\\\\([^\\/])/g, '$1')\n}\n","// parse a single path portion\n\nimport { parseClass } from './brace-expressions.js'\nimport { MinimatchOptions, MMRegExp } from './index.js'\nimport { unescape } from './unescape.js'\n\n// classes [] are handled by the parseClass method\n// for positive extglobs, we sub-parse the contents, and combine,\n// with the appropriate regexp close.\n// for negative extglobs, we sub-parse the contents, but then\n// have to include the rest of the pattern, then the parent, etc.,\n// as the thing that cannot be because RegExp negative lookaheads\n// are different from globs.\n//\n// So for example:\n// a@(i|w!(x|y)z|j)b => ^a(i|w((!?(x|y)zb).*)z|j)b$\n//   1   2 3   4 5 6      1   2    3   46      5 6\n//\n// Assembling the extglob requires not just the negated patterns themselves,\n// but also anything following the negative patterns up to the boundary\n// of the current pattern, plus anything following in the parent pattern.\n//\n//\n// So, first, we parse the string into an AST of extglobs, without turning\n// anything into regexps yet.\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y']}, 'z'], ['j']]}, 'b']\n//\n// Then, for all the negative extglobs, we append whatever comes after in\n// each parent as their tail\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y'], 'z', 'b'}, 'z'], ['j']]}, 'b']\n//\n// Lastly, we turn each of these pieces into a regexp, and join\n//\n//                                 v----- .* because there's more following,\n//                                 v    v  otherwise, .+ because it must be\n//                                 v    v  *something* there.\n// ['^a', {@ ['i', 'w(?:(!?(?:x|y).*zb$).*)z', 'j' ]}, 'b$']\n//   copy what follows into here--^^^^^\n// ['^a', '(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)', 'b$']\n// ['^a(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)b$']\n\nexport type ExtglobType = '!' | '?' | '+' | '*' | '@'\nconst types = new Set(['!', '?', '+', '*', '@'])\nconst isExtglobType = (c: string): c is ExtglobType =>\n  types.has(c as ExtglobType)\n\n// Patterns that get prepended to bind to the start of either the\n// entire string, or just a single path portion, to prevent dots\n// and/or traversal patterns, when needed.\n// Exts don't need the ^ or / bit, because the root binds that already.\nconst startNoTraversal = '(?!(?:^|/)\\\\.\\\\.?(?:$|/))'\nconst startNoDot = '(?!\\\\.)'\n\n// characters that indicate a start of pattern needs the \"no dots\" bit,\n// because a dot *might* be matched. ( is not in the list, because in\n// the case of a child extglob, it will handle the prevention itself.\nconst addPatternStart = new Set(['[', '.'])\n// cases where traversal is A-OK, no dot prevention needed\nconst justDots = new Set(['..', '.'])\nconst reSpecials = new Set('().*{}+?[]^$\\\\!')\nconst regExpEscape = (s: string) =>\n  s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// any single thing other than /\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n// use + when we need to ensure that *something* matches, because the * is\n// the only thing in the path portion.\nconst starNoEmpty = qmark + '+?'\n\n// remove the \\ chars that we added if we end up doing a nonmagic compare\n// const deslash = (s: string) => s.replace(/\\\\(.)/g, '$1')\n\nexport class AST {\n  type: ExtglobType | null\n  readonly #root: AST\n\n  #hasMagic?: boolean\n  #uflag: boolean = false\n  #parts: (string | AST)[] = []\n  readonly #parent?: AST\n  readonly #parentIndex: number\n  #negs: AST[]\n  #filledNegs: boolean = false\n  #options: MinimatchOptions\n  #toString?: string\n  // set to true if it's an extglob with no children\n  // (which really means one child of '')\n  #emptyExt: boolean = false\n\n  constructor(\n    type: ExtglobType | null,\n    parent?: AST,\n    options: MinimatchOptions = {}\n  ) {\n    this.type = type\n    // extglobs are inherently magical\n    if (type) this.#hasMagic = true\n    this.#parent = parent\n    this.#root = this.#parent ? this.#parent.#root : this\n    this.#options = this.#root === this ? options : this.#root.#options\n    this.#negs = this.#root === this ? [] : this.#root.#negs\n    if (type === '!' && !this.#root.#filledNegs) this.#negs.push(this)\n    this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0\n  }\n\n  get hasMagic(): boolean | undefined {\n    /* c8 ignore start */\n    if (this.#hasMagic !== undefined) return this.#hasMagic\n    /* c8 ignore stop */\n    for (const p of this.#parts) {\n      if (typeof p === 'string') continue\n      if (p.type || p.hasMagic) return (this.#hasMagic = true)\n    }\n    // note: will be undefined until we generate the regexp src and find out\n    return this.#hasMagic\n  }\n\n  // reconstructs the pattern\n  toString(): string {\n    if (this.#toString !== undefined) return this.#toString\n    if (!this.type) {\n      return (this.#toString = this.#parts.map(p => String(p)).join(''))\n    } else {\n      return (this.#toString =\n        this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')')\n    }\n  }\n\n  #fillNegs() {\n    /* c8 ignore start */\n    if (this !== this.#root) throw new Error('should only call on root')\n    if (this.#filledNegs) return this\n    /* c8 ignore stop */\n\n    // call toString() once to fill this out\n    this.toString()\n    this.#filledNegs = true\n    let n: AST | undefined\n    while ((n = this.#negs.pop())) {\n      if (n.type !== '!') continue\n      // walk up the tree, appending everthing that comes AFTER parentIndex\n      let p: AST | undefined = n\n      let pp = p.#parent\n      while (pp) {\n        for (\n          let i = p.#parentIndex + 1;\n          !pp.type && i < pp.#parts.length;\n          i++\n        ) {\n          for (const part of n.#parts) {\n            /* c8 ignore start */\n            if (typeof part === 'string') {\n              throw new Error('string part in extglob AST??')\n            }\n            /* c8 ignore stop */\n            part.copyIn(pp.#parts[i])\n          }\n        }\n        p = pp\n        pp = p.#parent\n      }\n    }\n    return this\n  }\n\n  push(...parts: (string | AST)[]) {\n    for (const p of parts) {\n      if (p === '') continue\n      /* c8 ignore start */\n      if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {\n        throw new Error('invalid part: ' + p)\n      }\n      /* c8 ignore stop */\n      this.#parts.push(p)\n    }\n  }\n\n  toJSON() {\n    const ret: any[] =\n      this.type === null\n        ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))\n        : [this.type, ...this.#parts.map(p => (p as AST).toJSON())]\n    if (this.isStart() && !this.type) ret.unshift([])\n    if (\n      this.isEnd() &&\n      (this === this.#root ||\n        (this.#root.#filledNegs && this.#parent?.type === '!'))\n    ) {\n      ret.push({})\n    }\n    return ret\n  }\n\n  isStart(): boolean {\n    if (this.#root === this) return true\n    // if (this.type) return !!this.#parent?.isStart()\n    if (!this.#parent?.isStart()) return false\n    if (this.#parentIndex === 0) return true\n    // if everything AHEAD of this is a negation, then it's still the \"start\"\n    const p = this.#parent\n    for (let i = 0; i < this.#parentIndex; i++) {\n      const pp = p.#parts[i]\n      if (!(pp instanceof AST && pp.type === '!')) {\n        return false\n      }\n    }\n    return true\n  }\n\n  isEnd(): boolean {\n    if (this.#root === this) return true\n    if (this.#parent?.type === '!') return true\n    if (!this.#parent?.isEnd()) return false\n    if (!this.type) return this.#parent?.isEnd()\n    // if not root, it'll always have a parent\n    /* c8 ignore start */\n    const pl = this.#parent ? this.#parent.#parts.length : 0\n    /* c8 ignore stop */\n    return this.#parentIndex === pl - 1\n  }\n\n  copyIn(part: AST | string) {\n    if (typeof part === 'string') this.push(part)\n    else this.push(part.clone(this))\n  }\n\n  clone(parent: AST) {\n    const c = new AST(this.type, parent)\n    for (const p of this.#parts) {\n      c.copyIn(p)\n    }\n    return c\n  }\n\n  static #parseAST(\n    str: string,\n    ast: AST,\n    pos: number,\n    opt: MinimatchOptions\n  ): number {\n    let escaping = false\n    let inBrace = false\n    let braceStart = -1\n    let braceNeg = false\n    if (ast.type === null) {\n      // outside of a extglob, append until we find a start\n      let i = pos\n      let acc = ''\n      while (i < str.length) {\n        const c = str.charAt(i++)\n        // still accumulate escapes at this point, but we do ignore\n        // starts that are escaped\n        if (escaping || c === '\\\\') {\n          escaping = !escaping\n          acc += c\n          continue\n        }\n\n        if (inBrace) {\n          if (i === braceStart + 1) {\n            if (c === '^' || c === '!') {\n              braceNeg = true\n            }\n          } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n            inBrace = false\n          }\n          acc += c\n          continue\n        } else if (c === '[') {\n          inBrace = true\n          braceStart = i\n          braceNeg = false\n          acc += c\n          continue\n        }\n\n        if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {\n          ast.push(acc)\n          acc = ''\n          const ext = new AST(c, ast)\n          i = AST.#parseAST(str, ext, i, opt)\n          ast.push(ext)\n          continue\n        }\n        acc += c\n      }\n      ast.push(acc)\n      return i\n    }\n\n    // some kind of extglob, pos is at the (\n    // find the next | or )\n    let i = pos + 1\n    let part = new AST(null, ast)\n    const parts: AST[] = []\n    let acc = ''\n    while (i < str.length) {\n      const c = str.charAt(i++)\n      // still accumulate escapes at this point, but we do ignore\n      // starts that are escaped\n      if (escaping || c === '\\\\') {\n        escaping = !escaping\n        acc += c\n        continue\n      }\n\n      if (inBrace) {\n        if (i === braceStart + 1) {\n          if (c === '^' || c === '!') {\n            braceNeg = true\n          }\n        } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n          inBrace = false\n        }\n        acc += c\n        continue\n      } else if (c === '[') {\n        inBrace = true\n        braceStart = i\n        braceNeg = false\n        acc += c\n        continue\n      }\n\n      if (isExtglobType(c) && str.charAt(i) === '(') {\n        part.push(acc)\n        acc = ''\n        const ext = new AST(c, part)\n        part.push(ext)\n        i = AST.#parseAST(str, ext, i, opt)\n        continue\n      }\n      if (c === '|') {\n        part.push(acc)\n        acc = ''\n        parts.push(part)\n        part = new AST(null, ast)\n        continue\n      }\n      if (c === ')') {\n        if (acc === '' && ast.#parts.length === 0) {\n          ast.#emptyExt = true\n        }\n        part.push(acc)\n        acc = ''\n        ast.push(...parts, part)\n        return i\n      }\n      acc += c\n    }\n\n    // unfinished extglob\n    // if we got here, it was a malformed extglob! not an extglob, but\n    // maybe something else in there.\n    ast.type = null\n    ast.#hasMagic = undefined\n    ast.#parts = [str.substring(pos - 1)]\n    return i\n  }\n\n  static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n    const ast = new AST(null, undefined, options)\n    AST.#parseAST(pattern, ast, 0, options)\n    return ast\n  }\n\n  // returns the regular expression if there's magic, or the unescaped\n  // string if not.\n  toMMPattern(): MMRegExp | string {\n    // should only be called on root\n    /* c8 ignore start */\n    if (this !== this.#root) return this.#root.toMMPattern()\n    /* c8 ignore stop */\n    const glob = this.toString()\n    const [re, body, hasMagic, uflag] = this.toRegExpSource()\n    // if we're in nocase mode, and not nocaseMagicOnly, then we do\n    // still need a regular expression if we have to case-insensitively\n    // match capital/lowercase characters.\n    const anyMagic =\n      hasMagic ||\n      this.#hasMagic ||\n      (this.#options.nocase &&\n        !this.#options.nocaseMagicOnly &&\n        glob.toUpperCase() !== glob.toLowerCase())\n    if (!anyMagic) {\n      return body\n    }\n\n    const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '')\n    return Object.assign(new RegExp(`^${re}$`, flags), {\n      _src: re,\n      _glob: glob,\n    })\n  }\n\n  // returns the string match, the regexp source, whether there's magic\n  // in the regexp (so a regular expression is required) and whether or\n  // not the uflag is needed for the regular expression (for posix classes)\n  // TODO: instead of injecting the start/end at this point, just return\n  // the BODY of the regexp, along with the start/end portions suitable\n  // for binding the start/end in either a joined full-path makeRe context\n  // (where we bind to (^|/), or a standalone matchPart context (where\n  // we bind to ^, and not /).  Otherwise slashes get duped!\n  //\n  // In part-matching mode, the start is:\n  // - if not isStart: nothing\n  // - if traversal possible, but not allowed: ^(?!\\.\\.?$)\n  // - if dots allowed or not possible: ^\n  // - if dots possible and not allowed: ^(?!\\.)\n  // end is:\n  // - if not isEnd(): nothing\n  // - else: $\n  //\n  // In full-path matching mode, we put the slash at the START of the\n  // pattern, so start is:\n  // - if first pattern: same as part-matching mode\n  // - if not isStart(): nothing\n  // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))\n  // - if dots allowed or not possible: /\n  // - if dots possible and not allowed: /(?!\\.)\n  // end is:\n  // - if last pattern, same as part-matching mode\n  // - else nothing\n  //\n  // Always put the (?:$|/) on negated tails, though, because that has to be\n  // there to bind the end of the negated pattern portion, and it's easier to\n  // just stick it in now rather than try to inject it later in the middle of\n  // the pattern.\n  //\n  // We can just always return the same end, and leave it up to the caller\n  // to know whether it's going to be used joined or in parts.\n  // And, if the start is adjusted slightly, can do the same there:\n  // - if not isStart: nothing\n  // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)\n  // - if dots allowed or not possible: (?:/|^)\n  // - if dots possible and not allowed: (?:/|^)(?!\\.)\n  //\n  // But it's better to have a simpler binding without a conditional, for\n  // performance, so probably better to return both start options.\n  //\n  // Then the caller just ignores the end if it's not the first pattern,\n  // and the start always gets applied.\n  //\n  // But that's always going to be $ if it's the ending pattern, or nothing,\n  // so the caller can just attach $ at the end of the pattern when building.\n  //\n  // So the todo is:\n  // - better detect what kind of start is needed\n  // - return both flavors of starting pattern\n  // - attach $ at the end of the pattern when creating the actual RegExp\n  //\n  // Ah, but wait, no, that all only applies to the root when the first pattern\n  // is not an extglob. If the first pattern IS an extglob, then we need all\n  // that dot prevention biz to live in the extglob portions, because eg\n  // +(*|.x*) can match .xy but not .yx.\n  //\n  // So, return the two flavors if it's #root and the first child is not an\n  // AST, otherwise leave it to the child AST to handle it, and there,\n  // use the (?:^|/) style of start binding.\n  //\n  // Even simplified further:\n  // - Since the start for a join is eg /(?!\\.) and the start for a part\n  // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root\n  // or start or whatever) and prepend ^ or / at the Regexp construction.\n  toRegExpSource(\n    allowDot?: boolean\n  ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n    const dot = allowDot ?? !!this.#options.dot\n    if (this.#root === this) this.#fillNegs()\n    if (!this.type) {\n      const noEmpty = this.isStart() && this.isEnd()\n      const src = this.#parts\n        .map(p => {\n          const [re, _, hasMagic, uflag] =\n            typeof p === 'string'\n              ? AST.#parseGlob(p, this.#hasMagic, noEmpty)\n              : p.toRegExpSource(allowDot)\n          this.#hasMagic = this.#hasMagic || hasMagic\n          this.#uflag = this.#uflag || uflag\n          return re\n        })\n        .join('')\n\n      let start = ''\n      if (this.isStart()) {\n        if (typeof this.#parts[0] === 'string') {\n          // this is the string that will match the start of the pattern,\n          // so we need to protect against dots and such.\n\n          // '.' and '..' cannot match unless the pattern is that exactly,\n          // even if it starts with . or dot:true is set.\n          const dotTravAllowed =\n            this.#parts.length === 1 && justDots.has(this.#parts[0])\n          if (!dotTravAllowed) {\n            const aps = addPatternStart\n            // check if we have a possibility of matching . or ..,\n            // and prevent that.\n            const needNoTrav =\n              // dots are allowed, and the pattern starts with [ or .\n              (dot && aps.has(src.charAt(0))) ||\n              // the pattern starts with \\., and then [ or .\n              (src.startsWith('\\\\.') && aps.has(src.charAt(2))) ||\n              // the pattern starts with \\.\\., and then [ or .\n              (src.startsWith('\\\\.\\\\.') && aps.has(src.charAt(4)))\n            // no need to prevent dots if it can't match a dot, or if a\n            // sub-pattern will be preventing it anyway.\n            const needNoDot = !dot && !allowDot && aps.has(src.charAt(0))\n\n            start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ''\n          }\n        }\n      }\n\n      // append the \"end of path portion\" pattern to negation tails\n      let end = ''\n      if (\n        this.isEnd() &&\n        this.#root.#filledNegs &&\n        this.#parent?.type === '!'\n      ) {\n        end = '(?:$|\\\\/)'\n      }\n      const final = start + src + end\n      return [\n        final,\n        unescape(src),\n        (this.#hasMagic = !!this.#hasMagic),\n        this.#uflag,\n      ]\n    }\n\n    // We need to calculate the body *twice* if it's a repeat pattern\n    // at the start, once in nodot mode, then again in dot mode, so a\n    // pattern like *(?) can match 'x.y'\n\n    const repeated = this.type === '*' || this.type === '+'\n    // some kind of extglob\n    const start = this.type === '!' ? '(?:(?!(?:' : '(?:'\n    let body = this.#partsToRegExp(dot)\n\n    if (this.isStart() && this.isEnd() && !body && this.type !== '!') {\n      // invalid extglob, has to at least be *something* present, if it's\n      // the entire path portion.\n      const s = this.toString()\n      this.#parts = [s]\n      this.type = null\n      this.#hasMagic = undefined\n      return [s, unescape(this.toString()), false, false]\n    }\n\n    // XXX abstract out this map method\n    let bodyDotAllowed =\n      !repeated || allowDot || dot || !startNoDot\n        ? ''\n        : this.#partsToRegExp(true)\n    if (bodyDotAllowed === body) {\n      bodyDotAllowed = ''\n    }\n    if (bodyDotAllowed) {\n      body = `(?:${body})(?:${bodyDotAllowed})*?`\n    }\n\n    // an empty !() is exactly equivalent to a starNoEmpty\n    let final = ''\n    if (this.type === '!' && this.#emptyExt) {\n      final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty\n    } else {\n      const close =\n        this.type === '!'\n          ? // !() must match something,but !(x) can match ''\n            '))' +\n            (this.isStart() && !dot && !allowDot ? startNoDot : '') +\n            star +\n            ')'\n          : this.type === '@'\n          ? ')'\n          : this.type === '?'\n          ? ')?'\n          : this.type === '+' && bodyDotAllowed\n          ? ')'\n          : this.type === '*' && bodyDotAllowed\n          ? `)?`\n          : `)${this.type}`\n      final = start + body + close\n    }\n    return [\n      final,\n      unescape(body),\n      (this.#hasMagic = !!this.#hasMagic),\n      this.#uflag,\n    ]\n  }\n\n  #partsToRegExp(dot: boolean) {\n    return this.#parts\n      .map(p => {\n        // extglob ASTs should only contain parent ASTs\n        /* c8 ignore start */\n        if (typeof p === 'string') {\n          throw new Error('string type in extglob ast??')\n        }\n        /* c8 ignore stop */\n        // can ignore hasMagic, because extglobs are already always magic\n        const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot)\n        this.#uflag = this.#uflag || uflag\n        return re\n      })\n      .filter(p => !(this.isStart() && this.isEnd()) || !!p)\n      .join('|')\n  }\n\n  static #parseGlob(\n    glob: string,\n    hasMagic: boolean | undefined,\n    noEmpty: boolean = false\n  ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n    let escaping = false\n    let re = ''\n    let uflag = false\n    for (let i = 0; i < glob.length; i++) {\n      const c = glob.charAt(i)\n      if (escaping) {\n        escaping = false\n        re += (reSpecials.has(c) ? '\\\\' : '') + c\n        continue\n      }\n      if (c === '\\\\') {\n        if (i === glob.length - 1) {\n          re += '\\\\\\\\'\n        } else {\n          escaping = true\n        }\n        continue\n      }\n      if (c === '[') {\n        const [src, needUflag, consumed, magic] = parseClass(glob, i)\n        if (consumed) {\n          re += src\n          uflag = uflag || needUflag\n          i += consumed - 1\n          hasMagic = hasMagic || magic\n          continue\n        }\n      }\n      if (c === '*') {\n        if (noEmpty && glob === '*') re += starNoEmpty\n        else re += star\n        hasMagic = true\n        continue\n      }\n      if (c === '?') {\n        re += qmark\n        hasMagic = true\n        continue\n      }\n      re += regExpEscape(c)\n    }\n    return [re, unescape(glob), !!hasMagic, uflag]\n  }\n}\n","import { MinimatchOptions } from './index.js'\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character.  In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n */\nexport const escape = (\n  s: string,\n  {\n    windowsPathsNoEscape = false,\n  }: Pick = {}\n) => {\n  // don't need to escape +@! because we escape the parens\n  // that make those magic, and escaping ! as [!] isn't valid,\n  // because [!]] is a valid glob class meaning not ']'.\n  return windowsPathsNoEscape\n    ? s.replace(/[?*()[\\]]/g, '[$&]')\n    : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n","/**\n * @module LRUCache\n */\n\n// module-private names and types\ntype Perf = { now: () => number }\nconst perf: Perf =\n  typeof performance === 'object' &&\n  performance &&\n  typeof performance.now === 'function'\n    ? performance\n    : Date\n\nconst warned = new Set()\n\n// either a function or a class\ntype ForC = ((...a: any[]) => any) | { new (...a: any[]): any }\n\n/* c8 ignore start */\nconst PROCESS = (\n  typeof process === 'object' && !!process ? process : {}\n) as { [k: string]: any }\n/* c8 ignore start */\n\nconst emitWarning = (\n  msg: string,\n  type: string,\n  code: string,\n  fn: ForC\n) => {\n  typeof PROCESS.emitWarning === 'function'\n    ? PROCESS.emitWarning(msg, type, code, fn)\n    : console.error(`[${code}] ${type}: ${msg}`)\n}\n\nlet AC = globalThis.AbortController\nlet AS = globalThis.AbortSignal\n\n/* c8 ignore start */\nif (typeof AC === 'undefined') {\n  //@ts-ignore\n  AS = class AbortSignal {\n    onabort?: (...a: any[]) => any\n    _onabort: ((...a: any[]) => any)[] = []\n    reason?: any\n    aborted: boolean = false\n    addEventListener(_: string, fn: (...a: any[]) => any) {\n      this._onabort.push(fn)\n    }\n  }\n  //@ts-ignore\n  AC = class AbortController {\n    constructor() {\n      warnACPolyfill()\n    }\n    signal = new AS()\n    abort(reason: any) {\n      if (this.signal.aborted) return\n      //@ts-ignore\n      this.signal.reason = reason\n      //@ts-ignore\n      this.signal.aborted = true\n      //@ts-ignore\n      for (const fn of this.signal._onabort) {\n        fn(reason)\n      }\n      this.signal.onabort?.(reason)\n    }\n  }\n  let printACPolyfillWarning =\n    PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'\n  const warnACPolyfill = () => {\n    if (!printACPolyfillWarning) return\n    printACPolyfillWarning = false\n    emitWarning(\n      'AbortController is not defined. If using lru-cache in ' +\n        'node 14, load an AbortController polyfill from the ' +\n        '`node-abort-controller` package. A minimal polyfill is ' +\n        'provided for use by LRUCache.fetch(), but it should not be ' +\n        'relied upon in other contexts (eg, passing it to other APIs that ' +\n        'use AbortController/AbortSignal might have undesirable effects). ' +\n        'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.',\n      'NO_ABORT_CONTROLLER',\n      'ENOTSUP',\n      warnACPolyfill\n    )\n  }\n}\n/* c8 ignore stop */\n\nconst shouldWarn = (code: string) => !warned.has(code)\n\nconst TYPE = Symbol('type')\nexport type PosInt = number & { [TYPE]: 'Positive Integer' }\nexport type Index = number & { [TYPE]: 'LRUCache Index' }\n\nconst isPosInt = (n: any): n is PosInt =>\n  n && n === Math.floor(n) && n > 0 && isFinite(n)\n\nexport type UintArray = Uint8Array | Uint16Array | Uint32Array\nexport type NumberArray = UintArray | number[]\n\n/* c8 ignore start */\n// This is a little bit ridiculous, tbh.\n// The maximum array length is 2^32-1 or thereabouts on most JS impls.\n// And well before that point, you're caching the entire world, I mean,\n// that's ~32GB of just integers for the next/prev links, plus whatever\n// else to hold that many keys and values.  Just filling the memory with\n// zeroes at init time is brutal when you get that big.\n// But why not be complete?\n// Maybe in the future, these limits will have expanded.\nconst getUintArray = (max: number) =>\n  !isPosInt(max)\n    ? null\n    : max <= Math.pow(2, 8)\n    ? Uint8Array\n    : max <= Math.pow(2, 16)\n    ? Uint16Array\n    : max <= Math.pow(2, 32)\n    ? Uint32Array\n    : max <= Number.MAX_SAFE_INTEGER\n    ? ZeroArray\n    : null\n/* c8 ignore stop */\n\nclass ZeroArray extends Array {\n  constructor(size: number) {\n    super(size)\n    this.fill(0)\n  }\n}\nexport type { ZeroArray }\nexport type { Stack }\n\nexport type StackLike = Stack | Index[]\nclass Stack {\n  heap: NumberArray\n  length: number\n  // private constructor\n  static #constructing: boolean = false\n  static create(max: number): StackLike {\n    const HeapCls = getUintArray(max)\n    if (!HeapCls) return []\n    Stack.#constructing = true\n    const s = new Stack(max, HeapCls)\n    Stack.#constructing = false\n    return s\n  }\n  constructor(\n    max: number,\n    HeapCls: { new (n: number): NumberArray }\n  ) {\n    /* c8 ignore start */\n    if (!Stack.#constructing) {\n      throw new TypeError('instantiate Stack using Stack.create(n)')\n    }\n    /* c8 ignore stop */\n    this.heap = new HeapCls(max)\n    this.length = 0\n  }\n  push(n: Index) {\n    this.heap[this.length++] = n\n  }\n  pop(): Index {\n    return this.heap[--this.length] as Index\n  }\n}\n\n/**\n * Promise representing an in-progress {@link LRUCache#fetch} call\n */\nexport type BackgroundFetch = Promise & {\n  __returned: BackgroundFetch | undefined\n  __abortController: AbortController\n  __staleWhileFetching: V | undefined\n}\n\nexport type DisposeTask = [\n  value: V,\n  key: K,\n  reason: LRUCache.DisposeReason\n]\n\nexport namespace LRUCache {\n  /**\n   * An integer greater than 0, reflecting the calculated size of items\n   */\n  export type Size = number\n\n  /**\n   * Integer greater than 0, representing some number of milliseconds, or the\n   * time at which a TTL started counting from.\n   */\n  export type Milliseconds = number\n\n  /**\n   * An integer greater than 0, reflecting a number of items\n   */\n  export type Count = number\n\n  /**\n   * The reason why an item was removed from the cache, passed\n   * to the {@link Disposer} methods.\n   */\n  export type DisposeReason = 'evict' | 'set' | 'delete'\n  /**\n   * A method called upon item removal, passed as the\n   * {@link OptionsBase.dispose} and/or\n   * {@link OptionsBase.disposeAfter} options.\n   */\n  export type Disposer = (\n    value: V,\n    key: K,\n    reason: DisposeReason\n  ) => void\n\n  /**\n   * A function that returns the effective calculated size\n   * of an entry in the cache.\n   */\n  export type SizeCalculator = (value: V, key: K) => Size\n\n  /**\n   * Options provided to the\n   * {@link OptionsBase.fetchMethod} function.\n   */\n  export interface FetcherOptions {\n    signal: AbortSignal\n    options: FetcherFetchOptions\n    /**\n     * Object provided in the {@link FetchOptions.context} option to\n     * {@link LRUCache#fetch}\n     */\n    context: FC\n  }\n\n  /**\n   * Status object that may be passed to {@link LRUCache#fetch},\n   * {@link LRUCache#get}, {@link LRUCache#set}, and {@link LRUCache#has}.\n   */\n  export interface Status {\n    /**\n     * The status of a set() operation.\n     *\n     * - add: the item was not found in the cache, and was added\n     * - update: the item was in the cache, with the same value provided\n     * - replace: the item was in the cache, and replaced\n     * - miss: the item was not added to the cache for some reason\n     */\n    set?: 'add' | 'update' | 'replace' | 'miss'\n\n    /**\n     * the ttl stored for the item, or undefined if ttls are not used.\n     */\n    ttl?: Milliseconds\n\n    /**\n     * the start time for the item, or undefined if ttls are not used.\n     */\n    start?: Milliseconds\n\n    /**\n     * The timestamp used for TTL calculation\n     */\n    now?: Milliseconds\n\n    /**\n     * the remaining ttl for the item, or undefined if ttls are not used.\n     */\n    remainingTTL?: Milliseconds\n\n    /**\n     * The calculated size for the item, if sizes are used.\n     */\n    entrySize?: Size\n\n    /**\n     * The total calculated size of the cache, if sizes are used.\n     */\n    totalCalculatedSize?: Size\n\n    /**\n     * A flag indicating that the item was not stored, due to exceeding the\n     * {@link OptionsBase.maxEntrySize}\n     */\n    maxEntrySizeExceeded?: true\n\n    /**\n     * The old value, specified in the case of `set:'update'` or\n     * `set:'replace'`\n     */\n    oldValue?: V\n\n    /**\n     * The results of a {@link LRUCache#has} operation\n     *\n     * - hit: the item was found in the cache\n     * - stale: the item was found in the cache, but is stale\n     * - miss: the item was not found in the cache\n     */\n    has?: 'hit' | 'stale' | 'miss'\n\n    /**\n     * The status of a {@link LRUCache#fetch} operation.\n     * Note that this can change as the underlying fetch() moves through\n     * various states.\n     *\n     * - inflight: there is another fetch() for this key which is in process\n     * - get: there is no fetchMethod, so {@link LRUCache#get} was called.\n     * - miss: the item is not in cache, and will be fetched.\n     * - hit: the item is in the cache, and was resolved immediately.\n     * - stale: the item is in the cache, but stale.\n     * - refresh: the item is in the cache, and not stale, but\n     *   {@link FetchOptions.forceRefresh} was specified.\n     */\n    fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'\n\n    /**\n     * The {@link OptionsBase.fetchMethod} was called\n     */\n    fetchDispatched?: true\n\n    /**\n     * The cached value was updated after a successful call to\n     * {@link OptionsBase.fetchMethod}\n     */\n    fetchUpdated?: true\n\n    /**\n     * The reason for a fetch() rejection.  Either the error raised by the\n     * {@link OptionsBase.fetchMethod}, or the reason for an\n     * AbortSignal.\n     */\n    fetchError?: Error\n\n    /**\n     * The fetch received an abort signal\n     */\n    fetchAborted?: true\n\n    /**\n     * The abort signal received was ignored, and the fetch was allowed to\n     * continue.\n     */\n    fetchAbortIgnored?: true\n\n    /**\n     * The fetchMethod promise resolved successfully\n     */\n    fetchResolved?: true\n\n    /**\n     * The fetchMethod promise was rejected\n     */\n    fetchRejected?: true\n\n    /**\n     * The status of a {@link LRUCache#get} operation.\n     *\n     * - fetching: The item is currently being fetched.  If a previous value\n     *   is present and allowed, that will be returned.\n     * - stale: The item is in the cache, and is stale.\n     * - hit: the item is in the cache\n     * - miss: the item is not in the cache\n     */\n    get?: 'stale' | 'hit' | 'miss'\n\n    /**\n     * A fetch or get operation returned a stale value.\n     */\n    returnedStale?: true\n  }\n\n  /**\n   * options which override the options set in the LRUCache constructor\n   * when calling {@link LRUCache#fetch}.\n   *\n   * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n   * {@link OptionsBase.noDeleteOnFetchRejection},\n   * {@link OptionsBase.allowStaleOnFetchRejection},\n   * {@link FetchOptions.forceRefresh}, and\n   * {@link FetcherOptions.context}\n   *\n   * Any of these may be modified in the {@link OptionsBase.fetchMethod}\n   * function, but the {@link GetOptions} fields will of course have no\n   * effect, as the {@link LRUCache#get} call already happened by the time\n   * the fetchMethod is called.\n   */\n  export interface FetcherFetchOptions\n    extends Pick<\n      OptionsBase,\n      | 'allowStale'\n      | 'updateAgeOnGet'\n      | 'noDeleteOnStaleGet'\n      | 'sizeCalculation'\n      | 'ttl'\n      | 'noDisposeOnSet'\n      | 'noUpdateTTL'\n      | 'noDeleteOnFetchRejection'\n      | 'allowStaleOnFetchRejection'\n      | 'ignoreFetchAbort'\n      | 'allowStaleOnFetchAbort'\n    > {\n    status?: Status\n    size?: Size\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#fetch} method.\n   */\n  export interface FetchOptions\n    extends FetcherFetchOptions {\n    /**\n     * Set to true to force a re-load of the existing data, even if it\n     * is not yet stale.\n     */\n    forceRefresh?: boolean\n    /**\n     * Context provided to the {@link OptionsBase.fetchMethod} as\n     * the {@link FetcherOptions.context} param.\n     *\n     * If the FC type is specified as unknown (the default),\n     * undefined or void, then this is optional.  Otherwise, it will\n     * be required.\n     */\n    context?: FC\n    signal?: AbortSignal\n    status?: Status\n  }\n  /**\n   * Options provided to {@link LRUCache#fetch} when the FC type is something\n   * other than `unknown`, `undefined`, or `void`\n   */\n  export interface FetchOptionsWithContext\n    extends FetchOptions {\n    context: FC\n  }\n  /**\n   * Options provided to {@link LRUCache#fetch} when the FC type is\n   * `undefined` or `void`\n   */\n  export interface FetchOptionsNoContext\n    extends FetchOptions {\n    context?: undefined\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#has} method.\n   */\n  export interface HasOptions\n    extends Pick, 'updateAgeOnHas'> {\n    status?: Status\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#get} method.\n   */\n  export interface GetOptions\n    extends Pick<\n      OptionsBase,\n      'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'\n    > {\n    status?: Status\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#peek} method.\n   */\n  export interface PeekOptions\n    extends Pick, 'allowStale'> {}\n\n  /**\n   * Options that may be passed to the {@link LRUCache#set} method.\n   */\n  export interface SetOptions\n    extends Pick<\n      OptionsBase,\n      'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'\n    > {\n    /**\n     * If size tracking is enabled, then setting an explicit size\n     * in the {@link LRUCache#set} call will prevent calling the\n     * {@link OptionsBase.sizeCalculation} function.\n     */\n    size?: Size\n    /**\n     * If TTL tracking is enabled, then setting an explicit start\n     * time in the {@link LRUCache#set} call will override the\n     * default time from `performance.now()` or `Date.now()`.\n     *\n     * Note that it must be a valid value for whichever time-tracking\n     * method is in use.\n     */\n    start?: Milliseconds\n    status?: Status\n  }\n\n  /**\n   * The type signature for the {@link OptionsBase.fetchMethod} option.\n   */\n  export type Fetcher = (\n    key: K,\n    staleValue: V | undefined,\n    options: FetcherOptions\n  ) => Promise | V | undefined | void\n\n  /**\n   * Options which may be passed to the {@link LRUCache} constructor.\n   *\n   * Most of these may be overridden in the various options that use\n   * them.\n   *\n   * Despite all being technically optional, the constructor requires that\n   * a cache is at minimum limited by one or more of {@link OptionsBase.max},\n   * {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}.\n   *\n   * If {@link OptionsBase.ttl} is used alone, then it is strongly advised\n   * (and in fact required by the type definitions here) that the cache\n   * also set {@link OptionsBase.ttlAutopurge}, to prevent potentially\n   * unbounded storage.\n   */\n  export interface OptionsBase {\n    /**\n     * The maximum number of items to store in the cache before evicting\n     * old entries. This is read-only on the {@link LRUCache} instance,\n     * and may not be overridden.\n     *\n     * If set, then storage space will be pre-allocated at construction\n     * time, and the cache will perform significantly faster.\n     *\n     * Note that significantly fewer items may be stored, if\n     * {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also\n     * set.\n     */\n    max?: Count\n\n    /**\n     * Max time in milliseconds for items to live in cache before they are\n     * considered stale.  Note that stale items are NOT preemptively removed\n     * by default, and MAY live in the cache long after they have expired.\n     *\n     * Also, as this cache is optimized for LRU/MRU operations, some of\n     * the staleness/TTL checks will reduce performance, as they will incur\n     * overhead by deleting items.\n     *\n     * Must be an integer number of ms. If set to 0, this indicates \"no TTL\"\n     *\n     * @default 0\n     */\n    ttl?: Milliseconds\n\n    /**\n     * Minimum amount of time in ms in which to check for staleness.\n     * Defaults to 1, which means that the current time is checked\n     * at most once per millisecond.\n     *\n     * Set to 0 to check the current time every time staleness is tested.\n     * (This reduces performance, and is theoretically unnecessary.)\n     *\n     * Setting this to a higher value will improve performance somewhat\n     * while using ttl tracking, albeit at the expense of keeping stale\n     * items around a bit longer than their TTLs would indicate.\n     *\n     * @default 1\n     */\n    ttlResolution?: Milliseconds\n\n    /**\n     * Preemptively remove stale items from the cache.\n     * Note that this may significantly degrade performance,\n     * especially if the cache is storing a large number of items.\n     * It is almost always best to just leave the stale items in\n     * the cache, and let them fall out as new items are added.\n     *\n     * Note that this means that {@link OptionsBase.allowStale} is a bit\n     * pointless, as stale items will be deleted almost as soon as they\n     * expire.\n     *\n     * @default false\n     */\n    ttlAutopurge?: boolean\n\n    /**\n     * Update the age of items on {@link LRUCache#get}, renewing their TTL\n     *\n     * Has no effect if {@link OptionsBase.ttl} is not set.\n     *\n     * @default false\n     */\n    updateAgeOnGet?: boolean\n\n    /**\n     * Update the age of items on {@link LRUCache#has}, renewing their TTL\n     *\n     * Has no effect if {@link OptionsBase.ttl} is not set.\n     *\n     * @default false\n     */\n    updateAgeOnHas?: boolean\n\n    /**\n     * Allow {@link LRUCache#get} and {@link LRUCache#fetch} calls to return\n     * stale data, if available.\n     */\n    allowStale?: boolean\n\n    /**\n     * Function that is called on items when they are dropped from the cache.\n     * This can be handy if you want to close file descriptors or do other\n     * cleanup tasks when items are no longer accessible. Called with `key,\n     * value`.  It's called before actually removing the item from the\n     * internal cache, so it is *NOT* safe to re-add them.\n     *\n     * Use {@link OptionsBase.disposeAfter} if you wish to dispose items after\n     * they have been full removed, when it is safe to add them back to the\n     * cache.\n     */\n    dispose?: Disposer\n\n    /**\n     * The same as {@link OptionsBase.dispose}, but called *after* the entry\n     * is completely removed and the cache is once again in a clean state.\n     * It is safe to add an item right back into the cache at this point.\n     * However, note that it is *very* easy to inadvertently create infinite\n     * recursion this way.\n     */\n    disposeAfter?: Disposer\n\n    /**\n     * Set to true to suppress calling the\n     * {@link OptionsBase.dispose} function if the entry key is\n     * still accessible within the cache.\n     * This may be overridden by passing an options object to\n     * {@link LRUCache#set}.\n     */\n    noDisposeOnSet?: boolean\n\n    /**\n     * Boolean flag to tell the cache to not update the TTL when\n     * setting a new value for an existing key (ie, when updating a value\n     * rather than inserting a new value).  Note that the TTL value is\n     * _always_ set (if provided) when adding a new entry into the cache.\n     *\n     * Has no effect if a {@link OptionsBase.ttl} is not set.\n     */\n    noUpdateTTL?: boolean\n\n    /**\n     * If you wish to track item size, you must provide a maxSize\n     * note that we still will only keep up to max *actual items*,\n     * if max is set, so size tracking may cause fewer than max items\n     * to be stored.  At the extreme, a single item of maxSize size\n     * will cause everything else in the cache to be dropped when it\n     * is added.  Use with caution!\n     *\n     * Note also that size tracking can negatively impact performance,\n     * though for most cases, only minimally.\n     */\n    maxSize?: Size\n\n    /**\n     * The maximum allowed size for any single item in the cache.\n     *\n     * If a larger item is passed to {@link LRUCache#set} or returned by a\n     * {@link OptionsBase.fetchMethod}, then it will not be stored in the\n     * cache.\n     */\n    maxEntrySize?: Size\n\n    /**\n     * A function that returns a number indicating the item's size.\n     *\n     * If not provided, and {@link OptionsBase.maxSize} or\n     * {@link OptionsBase.maxEntrySize} are set, then all\n     * {@link LRUCache#set} calls **must** provide an explicit\n     * {@link SetOptions.size} or sizeCalculation param.\n     */\n    sizeCalculation?: SizeCalculator\n\n    /**\n     * Method that provides the implementation for {@link LRUCache#fetch}\n     */\n    fetchMethod?: Fetcher\n\n    /**\n     * Set to true to suppress the deletion of stale data when a\n     * {@link OptionsBase.fetchMethod} returns a rejected promise.\n     */\n    noDeleteOnFetchRejection?: boolean\n\n    /**\n     * Do not delete stale items when they are retrieved with\n     * {@link LRUCache#get}.\n     *\n     * Note that the `get` return value will still be `undefined`\n     * unless {@link OptionsBase.allowStale} is true.\n     */\n    noDeleteOnStaleGet?: boolean\n\n    /**\n     * Set to true to allow returning stale data when a\n     * {@link OptionsBase.fetchMethod} throws an error or returns a rejected\n     * promise.\n     *\n     * This differs from using {@link OptionsBase.allowStale} in that stale\n     * data will ONLY be returned in the case that the\n     * {@link LRUCache#fetch} fails, not any other times.\n     */\n    allowStaleOnFetchRejection?: boolean\n\n    /**\n     * Set to true to return a stale value from the cache when the\n     * `AbortSignal` passed to the {@link OptionsBase.fetchMethod} dispatches an `'abort'`\n     * event, whether user-triggered, or due to internal cache behavior.\n     *\n     * Unless {@link OptionsBase.ignoreFetchAbort} is also set, the underlying\n     * {@link OptionsBase.fetchMethod} will still be considered canceled, and\n     * any value it returns will be ignored and not cached.\n     *\n     * Caveat: since fetches are aborted when a new value is explicitly\n     * set in the cache, this can lead to fetch returning a stale value,\n     * since that was the fallback value _at the moment the `fetch()` was\n     * initiated_, even though the new updated value is now present in\n     * the cache.\n     *\n     * For example:\n     *\n     * ```ts\n     * const cache = new LRUCache({\n     *   ttl: 100,\n     *   fetchMethod: async (url, oldValue, { signal }) =>  {\n     *     const res = await fetch(url, { signal })\n     *     return await res.json()\n     *   }\n     * })\n     * cache.set('https://example.com/', { some: 'data' })\n     * // 100ms go by...\n     * const result = cache.fetch('https://example.com/')\n     * cache.set('https://example.com/', { other: 'thing' })\n     * console.log(await result) // { some: 'data' }\n     * console.log(cache.get('https://example.com/')) // { other: 'thing' }\n     * ```\n     */\n    allowStaleOnFetchAbort?: boolean\n\n    /**\n     * Set to true to ignore the `abort` event emitted by the `AbortSignal`\n     * object passed to {@link OptionsBase.fetchMethod}, and still cache the\n     * resulting resolution value, as long as it is not `undefined`.\n     *\n     * When used on its own, this means aborted {@link LRUCache#fetch} calls are not\n     * immediately resolved or rejected when they are aborted, and instead\n     * take the full time to await.\n     *\n     * When used with {@link OptionsBase.allowStaleOnFetchAbort}, aborted\n     * {@link LRUCache#fetch} calls will resolve immediately to their stale\n     * cached value or `undefined`, and will continue to process and eventually\n     * update the cache when they resolve, as long as the resulting value is\n     * not `undefined`, thus supporting a \"return stale on timeout while\n     * refreshing\" mechanism by passing `AbortSignal.timeout(n)` as the signal.\n     *\n     * **Note**: regardless of this setting, an `abort` event _is still\n     * emitted on the `AbortSignal` object_, so may result in invalid results\n     * when passed to other underlying APIs that use AbortSignals.\n     *\n     * This may be overridden in the {@link OptionsBase.fetchMethod} or the\n     * call to {@link LRUCache#fetch}.\n     */\n    ignoreFetchAbort?: boolean\n  }\n\n  export interface OptionsMaxLimit\n    extends OptionsBase {\n    max: Count\n  }\n  export interface OptionsTTLLimit\n    extends OptionsBase {\n    ttl: Milliseconds\n    ttlAutopurge: boolean\n  }\n  export interface OptionsSizeLimit\n    extends OptionsBase {\n    maxSize: Size\n  }\n\n  /**\n   * The valid safe options for the {@link LRUCache} constructor\n   */\n  export type Options =\n    | OptionsMaxLimit\n    | OptionsSizeLimit\n    | OptionsTTLLimit\n\n  /**\n   * Entry objects used by {@link LRUCache#load} and {@link LRUCache#dump},\n   * and returned by {@link LRUCache#info}.\n   */\n  export interface Entry {\n    value: V\n    ttl?: Milliseconds\n    size?: Size\n    start?: Milliseconds\n  }\n}\n\n/**\n * Default export, the thing you're using this module to get.\n *\n * All properties from the options object (with the exception of\n * {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as\n * normal public members. (`max` and `maxBase` are read-only getters.)\n * Changing any of these will alter the defaults for subsequent method calls,\n * but is otherwise safe.\n */\nexport class LRUCache implements Map {\n  // properties coming in from the options of these, only max and maxSize\n  // really *need* to be protected. The rest can be modified, as they just\n  // set defaults for various methods.\n  readonly #max: LRUCache.Count\n  readonly #maxSize: LRUCache.Size\n  readonly #dispose?: LRUCache.Disposer\n  readonly #disposeAfter?: LRUCache.Disposer\n  readonly #fetchMethod?: LRUCache.Fetcher\n\n  /**\n   * {@link LRUCache.OptionsBase.ttl}\n   */\n  ttl: LRUCache.Milliseconds\n\n  /**\n   * {@link LRUCache.OptionsBase.ttlResolution}\n   */\n  ttlResolution: LRUCache.Milliseconds\n  /**\n   * {@link LRUCache.OptionsBase.ttlAutopurge}\n   */\n  ttlAutopurge: boolean\n  /**\n   * {@link LRUCache.OptionsBase.updateAgeOnGet}\n   */\n  updateAgeOnGet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.updateAgeOnHas}\n   */\n  updateAgeOnHas: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStale}\n   */\n  allowStale: boolean\n\n  /**\n   * {@link LRUCache.OptionsBase.noDisposeOnSet}\n   */\n  noDisposeOnSet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.noUpdateTTL}\n   */\n  noUpdateTTL: boolean\n  /**\n   * {@link LRUCache.OptionsBase.maxEntrySize}\n   */\n  maxEntrySize: LRUCache.Size\n  /**\n   * {@link LRUCache.OptionsBase.sizeCalculation}\n   */\n  sizeCalculation?: LRUCache.SizeCalculator\n  /**\n   * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}\n   */\n  noDeleteOnFetchRejection: boolean\n  /**\n   * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}\n   */\n  noDeleteOnStaleGet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}\n   */\n  allowStaleOnFetchAbort: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}\n   */\n  allowStaleOnFetchRejection: boolean\n  /**\n   * {@link LRUCache.OptionsBase.ignoreFetchAbort}\n   */\n  ignoreFetchAbort: boolean\n\n  // computed properties\n  #size: LRUCache.Count\n  #calculatedSize: LRUCache.Size\n  #keyMap: Map\n  #keyList: (K | undefined)[]\n  #valList: (V | BackgroundFetch | undefined)[]\n  #next: NumberArray\n  #prev: NumberArray\n  #head: Index\n  #tail: Index\n  #free: StackLike\n  #disposed?: DisposeTask[]\n  #sizes?: ZeroArray\n  #starts?: ZeroArray\n  #ttls?: ZeroArray\n\n  #hasDispose: boolean\n  #hasFetchMethod: boolean\n  #hasDisposeAfter: boolean\n\n  /**\n   * Do not call this method unless you need to inspect the\n   * inner workings of the cache.  If anything returned by this\n   * object is modified in any way, strange breakage may occur.\n   *\n   * These fields are private for a reason!\n   *\n   * @internal\n   */\n  static unsafeExposeInternals<\n    K extends {},\n    V extends {},\n    FC extends unknown = unknown\n  >(c: LRUCache) {\n    return {\n      // properties\n      starts: c.#starts,\n      ttls: c.#ttls,\n      sizes: c.#sizes,\n      keyMap: c.#keyMap as Map,\n      keyList: c.#keyList,\n      valList: c.#valList,\n      next: c.#next,\n      prev: c.#prev,\n      get head() {\n        return c.#head\n      },\n      get tail() {\n        return c.#tail\n      },\n      free: c.#free,\n      // methods\n      isBackgroundFetch: (p: any) => c.#isBackgroundFetch(p),\n      backgroundFetch: (\n        k: K,\n        index: number | undefined,\n        options: LRUCache.FetchOptions,\n        context: any\n      ): BackgroundFetch =>\n        c.#backgroundFetch(\n          k,\n          index as Index | undefined,\n          options,\n          context\n        ),\n      moveToTail: (index: number): void =>\n        c.#moveToTail(index as Index),\n      indexes: (options?: { allowStale: boolean }) =>\n        c.#indexes(options),\n      rindexes: (options?: { allowStale: boolean }) =>\n        c.#rindexes(options),\n      isStale: (index: number | undefined) =>\n        c.#isStale(index as Index),\n    }\n  }\n\n  // Protected read-only members\n\n  /**\n   * {@link LRUCache.OptionsBase.max} (read-only)\n   */\n  get max(): LRUCache.Count {\n    return this.#max\n  }\n  /**\n   * {@link LRUCache.OptionsBase.maxSize} (read-only)\n   */\n  get maxSize(): LRUCache.Count {\n    return this.#maxSize\n  }\n  /**\n   * The total computed size of items in the cache (read-only)\n   */\n  get calculatedSize(): LRUCache.Size {\n    return this.#calculatedSize\n  }\n  /**\n   * The number of items stored in the cache (read-only)\n   */\n  get size(): LRUCache.Count {\n    return this.#size\n  }\n  /**\n   * {@link LRUCache.OptionsBase.fetchMethod} (read-only)\n   */\n  get fetchMethod(): LRUCache.Fetcher | undefined {\n    return this.#fetchMethod\n  }\n  /**\n   * {@link LRUCache.OptionsBase.dispose} (read-only)\n   */\n  get dispose() {\n    return this.#dispose\n  }\n  /**\n   * {@link LRUCache.OptionsBase.disposeAfter} (read-only)\n   */\n  get disposeAfter() {\n    return this.#disposeAfter\n  }\n\n  constructor(\n    options: LRUCache.Options | LRUCache\n  ) {\n    const {\n      max = 0,\n      ttl,\n      ttlResolution = 1,\n      ttlAutopurge,\n      updateAgeOnGet,\n      updateAgeOnHas,\n      allowStale,\n      dispose,\n      disposeAfter,\n      noDisposeOnSet,\n      noUpdateTTL,\n      maxSize = 0,\n      maxEntrySize = 0,\n      sizeCalculation,\n      fetchMethod,\n      noDeleteOnFetchRejection,\n      noDeleteOnStaleGet,\n      allowStaleOnFetchRejection,\n      allowStaleOnFetchAbort,\n      ignoreFetchAbort,\n    } = options\n\n    if (max !== 0 && !isPosInt(max)) {\n      throw new TypeError('max option must be a nonnegative integer')\n    }\n\n    const UintArray = max ? getUintArray(max) : Array\n    if (!UintArray) {\n      throw new Error('invalid max value: ' + max)\n    }\n\n    this.#max = max\n    this.#maxSize = maxSize\n    this.maxEntrySize = maxEntrySize || this.#maxSize\n    this.sizeCalculation = sizeCalculation\n    if (this.sizeCalculation) {\n      if (!this.#maxSize && !this.maxEntrySize) {\n        throw new TypeError(\n          'cannot set sizeCalculation without setting maxSize or maxEntrySize'\n        )\n      }\n      if (typeof this.sizeCalculation !== 'function') {\n        throw new TypeError('sizeCalculation set to non-function')\n      }\n    }\n\n    if (\n      fetchMethod !== undefined &&\n      typeof fetchMethod !== 'function'\n    ) {\n      throw new TypeError(\n        'fetchMethod must be a function if specified'\n      )\n    }\n    this.#fetchMethod = fetchMethod\n    this.#hasFetchMethod = !!fetchMethod\n\n    this.#keyMap = new Map()\n    this.#keyList = new Array(max).fill(undefined)\n    this.#valList = new Array(max).fill(undefined)\n    this.#next = new UintArray(max)\n    this.#prev = new UintArray(max)\n    this.#head = 0 as Index\n    this.#tail = 0 as Index\n    this.#free = Stack.create(max)\n    this.#size = 0\n    this.#calculatedSize = 0\n\n    if (typeof dispose === 'function') {\n      this.#dispose = dispose\n    }\n    if (typeof disposeAfter === 'function') {\n      this.#disposeAfter = disposeAfter\n      this.#disposed = []\n    } else {\n      this.#disposeAfter = undefined\n      this.#disposed = undefined\n    }\n    this.#hasDispose = !!this.#dispose\n    this.#hasDisposeAfter = !!this.#disposeAfter\n\n    this.noDisposeOnSet = !!noDisposeOnSet\n    this.noUpdateTTL = !!noUpdateTTL\n    this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection\n    this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection\n    this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort\n    this.ignoreFetchAbort = !!ignoreFetchAbort\n\n    // NB: maxEntrySize is set to maxSize if it's set\n    if (this.maxEntrySize !== 0) {\n      if (this.#maxSize !== 0) {\n        if (!isPosInt(this.#maxSize)) {\n          throw new TypeError(\n            'maxSize must be a positive integer if specified'\n          )\n        }\n      }\n      if (!isPosInt(this.maxEntrySize)) {\n        throw new TypeError(\n          'maxEntrySize must be a positive integer if specified'\n        )\n      }\n      this.#initializeSizeTracking()\n    }\n\n    this.allowStale = !!allowStale\n    this.noDeleteOnStaleGet = !!noDeleteOnStaleGet\n    this.updateAgeOnGet = !!updateAgeOnGet\n    this.updateAgeOnHas = !!updateAgeOnHas\n    this.ttlResolution =\n      isPosInt(ttlResolution) || ttlResolution === 0\n        ? ttlResolution\n        : 1\n    this.ttlAutopurge = !!ttlAutopurge\n    this.ttl = ttl || 0\n    if (this.ttl) {\n      if (!isPosInt(this.ttl)) {\n        throw new TypeError(\n          'ttl must be a positive integer if specified'\n        )\n      }\n      this.#initializeTTLTracking()\n    }\n\n    // do not allow completely unbounded caches\n    if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {\n      throw new TypeError(\n        'At least one of max, maxSize, or ttl is required'\n      )\n    }\n    if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {\n      const code = 'LRU_CACHE_UNBOUNDED'\n      if (shouldWarn(code)) {\n        warned.add(code)\n        const msg =\n          'TTL caching without ttlAutopurge, max, or maxSize can ' +\n          'result in unbounded memory consumption.'\n        emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache)\n      }\n    }\n  }\n\n  /**\n   * Return the remaining TTL time for a given entry key\n   */\n  getRemainingTTL(key: K) {\n    return this.#keyMap.has(key) ? Infinity : 0\n  }\n\n  #initializeTTLTracking() {\n    const ttls = new ZeroArray(this.#max)\n    const starts = new ZeroArray(this.#max)\n    this.#ttls = ttls\n    this.#starts = starts\n\n    this.#setItemTTL = (index, ttl, start = perf.now()) => {\n      starts[index] = ttl !== 0 ? start : 0\n      ttls[index] = ttl\n      if (ttl !== 0 && this.ttlAutopurge) {\n        const t = setTimeout(() => {\n          if (this.#isStale(index)) {\n            this.delete(this.#keyList[index] as K)\n          }\n        }, ttl + 1)\n        // unref() not supported on all platforms\n        /* c8 ignore start */\n        if (t.unref) {\n          t.unref()\n        }\n        /* c8 ignore stop */\n      }\n    }\n\n    this.#updateItemAge = index => {\n      starts[index] = ttls[index] !== 0 ? perf.now() : 0\n    }\n\n    this.#statusTTL = (status, index) => {\n      if (ttls[index]) {\n        const ttl = ttls[index]\n        const start = starts[index]\n        /* c8 ignore next */\n        if (!ttl || !start) return\n        status.ttl = ttl\n        status.start = start\n        status.now = cachedNow || getNow()\n        const age = status.now - start\n        status.remainingTTL = ttl - age\n      }\n    }\n\n    // debounce calls to perf.now() to 1s so we're not hitting\n    // that costly call repeatedly.\n    let cachedNow = 0\n    const getNow = () => {\n      const n = perf.now()\n      if (this.ttlResolution > 0) {\n        cachedNow = n\n        const t = setTimeout(\n          () => (cachedNow = 0),\n          this.ttlResolution\n        )\n        // not available on all platforms\n        /* c8 ignore start */\n        if (t.unref) {\n          t.unref()\n        }\n        /* c8 ignore stop */\n      }\n      return n\n    }\n\n    this.getRemainingTTL = key => {\n      const index = this.#keyMap.get(key)\n      if (index === undefined) {\n        return 0\n      }\n      const ttl = ttls[index]\n      const start = starts[index]\n      if (!ttl || !start) {\n        return Infinity\n      }\n      const age = (cachedNow || getNow()) - start\n      return ttl - age\n    }\n\n    this.#isStale = index => {\n      const s = starts[index]\n      const t = ttls[index]\n      return !!t && !!s && (cachedNow || getNow()) - s > t\n    }\n  }\n\n  // conditionally set private methods related to TTL\n  #updateItemAge: (index: Index) => void = () => {}\n  #statusTTL: (status: LRUCache.Status, index: Index) => void =\n    () => {}\n  #setItemTTL: (\n    index: Index,\n    ttl: LRUCache.Milliseconds,\n    start?: LRUCache.Milliseconds\n    // ignore because we never call this if we're not already in TTL mode\n    /* c8 ignore start */\n  ) => void = () => {}\n  /* c8 ignore stop */\n\n  #isStale: (index: Index) => boolean = () => false\n\n  #initializeSizeTracking() {\n    const sizes = new ZeroArray(this.#max)\n    this.#calculatedSize = 0\n    this.#sizes = sizes\n    this.#removeItemSize = index => {\n      this.#calculatedSize -= sizes[index] as number\n      sizes[index] = 0\n    }\n    this.#requireSize = (k, v, size, sizeCalculation) => {\n      // provisionally accept background fetches.\n      // actual value size will be checked when they return.\n      if (this.#isBackgroundFetch(v)) {\n        return 0\n      }\n      if (!isPosInt(size)) {\n        if (sizeCalculation) {\n          if (typeof sizeCalculation !== 'function') {\n            throw new TypeError('sizeCalculation must be a function')\n          }\n          size = sizeCalculation(v, k)\n          if (!isPosInt(size)) {\n            throw new TypeError(\n              'sizeCalculation return invalid (expect positive integer)'\n            )\n          }\n        } else {\n          throw new TypeError(\n            'invalid size value (must be positive integer). ' +\n              'When maxSize or maxEntrySize is used, sizeCalculation ' +\n              'or size must be set.'\n          )\n        }\n      }\n      return size\n    }\n    this.#addItemSize = (\n      index: Index,\n      size: LRUCache.Size,\n      status?: LRUCache.Status\n    ) => {\n      sizes[index] = size\n      if (this.#maxSize) {\n        const maxSize = this.#maxSize - (sizes[index] as number)\n        while (this.#calculatedSize > maxSize) {\n          this.#evict(true)\n        }\n      }\n      this.#calculatedSize += sizes[index] as number\n      if (status) {\n        status.entrySize = size\n        status.totalCalculatedSize = this.#calculatedSize\n      }\n    }\n  }\n\n  #removeItemSize: (index: Index) => void = _i => {}\n  #addItemSize: (\n    index: Index,\n    size: LRUCache.Size,\n    status?: LRUCache.Status\n  ) => void = (_i, _s, _st) => {}\n  #requireSize: (\n    k: K,\n    v: V | BackgroundFetch,\n    size?: LRUCache.Size,\n    sizeCalculation?: LRUCache.SizeCalculator\n  ) => LRUCache.Size = (\n    _k: K,\n    _v: V | BackgroundFetch,\n    size?: LRUCache.Size,\n    sizeCalculation?: LRUCache.SizeCalculator\n  ) => {\n    if (size || sizeCalculation) {\n      throw new TypeError(\n        'cannot set size without setting maxSize or maxEntrySize on cache'\n      )\n    }\n    return 0\n  };\n\n  *#indexes({ allowStale = this.allowStale } = {}) {\n    if (this.#size) {\n      for (let i = this.#tail; true; ) {\n        if (!this.#isValidIndex(i)) {\n          break\n        }\n        if (allowStale || !this.#isStale(i)) {\n          yield i\n        }\n        if (i === this.#head) {\n          break\n        } else {\n          i = this.#prev[i] as Index\n        }\n      }\n    }\n  }\n\n  *#rindexes({ allowStale = this.allowStale } = {}) {\n    if (this.#size) {\n      for (let i = this.#head; true; ) {\n        if (!this.#isValidIndex(i)) {\n          break\n        }\n        if (allowStale || !this.#isStale(i)) {\n          yield i\n        }\n        if (i === this.#tail) {\n          break\n        } else {\n          i = this.#next[i] as Index\n        }\n      }\n    }\n  }\n\n  #isValidIndex(index: Index) {\n    return (\n      index !== undefined &&\n      this.#keyMap.get(this.#keyList[index] as K) === index\n    )\n  }\n\n  /**\n   * Return a generator yielding `[key, value]` pairs,\n   * in order from most recently used to least recently used.\n   */\n  *entries() {\n    for (const i of this.#indexes()) {\n      if (\n        this.#valList[i] !== undefined &&\n        this.#keyList[i] !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield [this.#keyList[i], this.#valList[i]] as [K, V]\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.entries}\n   *\n   * Return a generator yielding `[key, value]` pairs,\n   * in order from least recently used to most recently used.\n   */\n  *rentries() {\n    for (const i of this.#rindexes()) {\n      if (\n        this.#valList[i] !== undefined &&\n        this.#keyList[i] !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield [this.#keyList[i], this.#valList[i]]\n      }\n    }\n  }\n\n  /**\n   * Return a generator yielding the keys in the cache,\n   * in order from most recently used to least recently used.\n   */\n  *keys() {\n    for (const i of this.#indexes()) {\n      const k = this.#keyList[i]\n      if (\n        k !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield k\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.keys}\n   *\n   * Return a generator yielding the keys in the cache,\n   * in order from least recently used to most recently used.\n   */\n  *rkeys() {\n    for (const i of this.#rindexes()) {\n      const k = this.#keyList[i]\n      if (\n        k !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield k\n      }\n    }\n  }\n\n  /**\n   * Return a generator yielding the values in the cache,\n   * in order from most recently used to least recently used.\n   */\n  *values() {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      if (\n        v !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield this.#valList[i] as V\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.values}\n   *\n   * Return a generator yielding the values in the cache,\n   * in order from least recently used to most recently used.\n   */\n  *rvalues() {\n    for (const i of this.#rindexes()) {\n      const v = this.#valList[i]\n      if (\n        v !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield this.#valList[i]\n      }\n    }\n  }\n\n  /**\n   * Iterating over the cache itself yields the same results as\n   * {@link LRUCache.entries}\n   */\n  [Symbol.iterator]() {\n    return this.entries()\n  }\n\n  /**\n   * A String value that is used in the creation of the default string description of an object.\n   * Called by the built-in method Object.prototype.toString.\n   */\n  [Symbol.toStringTag] = 'LRUCache'\n\n  /**\n   * Find a value for which the supplied fn method returns a truthy value,\n   * similar to Array.find().  fn is called as fn(value, key, cache).\n   */\n  find(\n    fn: (v: V, k: K, self: LRUCache) => boolean,\n    getOptions: LRUCache.GetOptions = {}\n  ) {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v)\n        ? v.__staleWhileFetching\n        : v\n      if (value === undefined) continue\n      if (fn(value, this.#keyList[i] as K, this)) {\n        return this.get(this.#keyList[i] as K, getOptions)\n      }\n    }\n  }\n\n  /**\n   * Call the supplied function on each item in the cache, in order from\n   * most recently used to least recently used.  fn is called as\n   * fn(value, key, cache).  Does not update age or recenty of use.\n   * Does not iterate over stale values.\n   */\n  forEach(\n    fn: (v: V, k: K, self: LRUCache) => any,\n    thisp: any = this\n  ) {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v)\n        ? v.__staleWhileFetching\n        : v\n      if (value === undefined) continue\n      fn.call(thisp, value, this.#keyList[i] as K, this)\n    }\n  }\n\n  /**\n   * The same as {@link LRUCache.forEach} but items are iterated over in\n   * reverse order.  (ie, less recently used items are iterated over first.)\n   */\n  rforEach(\n    fn: (v: V, k: K, self: LRUCache) => any,\n    thisp: any = this\n  ) {\n    for (const i of this.#rindexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v)\n        ? v.__staleWhileFetching\n        : v\n      if (value === undefined) continue\n      fn.call(thisp, value, this.#keyList[i] as K, this)\n    }\n  }\n\n  /**\n   * Delete any stale entries. Returns true if anything was removed,\n   * false otherwise.\n   */\n  purgeStale() {\n    let deleted = false\n    for (const i of this.#rindexes({ allowStale: true })) {\n      if (this.#isStale(i)) {\n        this.delete(this.#keyList[i] as K)\n        deleted = true\n      }\n    }\n    return deleted\n  }\n\n  /**\n   * Get the extended info about a given entry, to get its value, size, and\n   * TTL info simultaneously. Like {@link LRUCache#dump}, but just for a\n   * single key. Always returns stale values, if their info is found in the\n   * cache, so be sure to check for expired TTLs if relevant.\n   */\n  info(key: K): LRUCache.Entry | undefined {\n    const i = this.#keyMap.get(key)\n    if (i === undefined) return undefined\n    const v = this.#valList[i]\n    const value: V | undefined = this.#isBackgroundFetch(v)\n      ? v.__staleWhileFetching\n      : v\n    if (value === undefined) return undefined\n    const entry: LRUCache.Entry = { value }\n    if (this.#ttls && this.#starts) {\n      const ttl = this.#ttls[i]\n      const start = this.#starts[i]\n      if (ttl && start) {\n        const remain = ttl - (perf.now() - start)\n        entry.ttl = remain\n        entry.start = Date.now()\n      }\n    }\n    if (this.#sizes) {\n      entry.size = this.#sizes[i]\n    }\n    return entry\n  }\n\n  /**\n   * Return an array of [key, {@link LRUCache.Entry}] tuples which can be\n   * passed to cache.load()\n   */\n  dump() {\n    const arr: [K, LRUCache.Entry][] = []\n    for (const i of this.#indexes({ allowStale: true })) {\n      const key = this.#keyList[i]\n      const v = this.#valList[i]\n      const value: V | undefined = this.#isBackgroundFetch(v)\n        ? v.__staleWhileFetching\n        : v\n      if (value === undefined || key === undefined) continue\n      const entry: LRUCache.Entry = { value }\n      if (this.#ttls && this.#starts) {\n        entry.ttl = this.#ttls[i]\n        // always dump the start relative to a portable timestamp\n        // it's ok for this to be a bit slow, it's a rare operation.\n        const age = perf.now() - (this.#starts[i] as number)\n        entry.start = Math.floor(Date.now() - age)\n      }\n      if (this.#sizes) {\n        entry.size = this.#sizes[i]\n      }\n      arr.unshift([key, entry])\n    }\n    return arr\n  }\n\n  /**\n   * Reset the cache and load in the items in entries in the order listed.\n   * Note that the shape of the resulting cache may be different if the\n   * same options are not used in both caches.\n   */\n  load(arr: [K, LRUCache.Entry][]) {\n    this.clear()\n    for (const [key, entry] of arr) {\n      if (entry.start) {\n        // entry.start is a portable timestamp, but we may be using\n        // node's performance.now(), so calculate the offset, so that\n        // we get the intended remaining TTL, no matter how long it's\n        // been on ice.\n        //\n        // it's ok for this to be a bit slow, it's a rare operation.\n        const age = Date.now() - entry.start\n        entry.start = perf.now() - age\n      }\n      this.set(key, entry.value, entry)\n    }\n  }\n\n  /**\n   * Add a value to the cache.\n   *\n   * Note: if `undefined` is specified as a value, this is an alias for\n   * {@link LRUCache#delete}\n   */\n  set(\n    k: K,\n    v: V | BackgroundFetch | undefined,\n    setOptions: LRUCache.SetOptions = {}\n  ) {\n    if (v === undefined) {\n      this.delete(k)\n      return this\n    }\n    const {\n      ttl = this.ttl,\n      start,\n      noDisposeOnSet = this.noDisposeOnSet,\n      sizeCalculation = this.sizeCalculation,\n      status,\n    } = setOptions\n    let { noUpdateTTL = this.noUpdateTTL } = setOptions\n\n    const size = this.#requireSize(\n      k,\n      v,\n      setOptions.size || 0,\n      sizeCalculation\n    )\n    // if the item doesn't fit, don't do anything\n    // NB: maxEntrySize set to maxSize by default\n    if (this.maxEntrySize && size > this.maxEntrySize) {\n      if (status) {\n        status.set = 'miss'\n        status.maxEntrySizeExceeded = true\n      }\n      // have to delete, in case something is there already.\n      this.delete(k)\n      return this\n    }\n    let index = this.#size === 0 ? undefined : this.#keyMap.get(k)\n    if (index === undefined) {\n      // addition\n      index = (\n        this.#size === 0\n          ? this.#tail\n          : this.#free.length !== 0\n          ? this.#free.pop()\n          : this.#size === this.#max\n          ? this.#evict(false)\n          : this.#size\n      ) as Index\n      this.#keyList[index] = k\n      this.#valList[index] = v\n      this.#keyMap.set(k, index)\n      this.#next[this.#tail] = index\n      this.#prev[index] = this.#tail\n      this.#tail = index\n      this.#size++\n      this.#addItemSize(index, size, status)\n      if (status) status.set = 'add'\n      noUpdateTTL = false\n    } else {\n      // update\n      this.#moveToTail(index)\n      const oldVal = this.#valList[index] as V | BackgroundFetch\n      if (v !== oldVal) {\n        if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {\n          oldVal.__abortController.abort(new Error('replaced'))\n          const { __staleWhileFetching: s } = oldVal\n          if (s !== undefined && !noDisposeOnSet) {\n            if (this.#hasDispose) {\n              this.#dispose?.(s as V, k, 'set')\n            }\n            if (this.#hasDisposeAfter) {\n              this.#disposed?.push([s as V, k, 'set'])\n            }\n          }\n        } else if (!noDisposeOnSet) {\n          if (this.#hasDispose) {\n            this.#dispose?.(oldVal as V, k, 'set')\n          }\n          if (this.#hasDisposeAfter) {\n            this.#disposed?.push([oldVal as V, k, 'set'])\n          }\n        }\n        this.#removeItemSize(index)\n        this.#addItemSize(index, size, status)\n        this.#valList[index] = v\n        if (status) {\n          status.set = 'replace'\n          const oldValue =\n            oldVal && this.#isBackgroundFetch(oldVal)\n              ? oldVal.__staleWhileFetching\n              : oldVal\n          if (oldValue !== undefined) status.oldValue = oldValue\n        }\n      } else if (status) {\n        status.set = 'update'\n      }\n    }\n    if (ttl !== 0 && !this.#ttls) {\n      this.#initializeTTLTracking()\n    }\n    if (this.#ttls) {\n      if (!noUpdateTTL) {\n        this.#setItemTTL(index, ttl, start)\n      }\n      if (status) this.#statusTTL(status, index)\n    }\n    if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n    return this\n  }\n\n  /**\n   * Evict the least recently used item, returning its value or\n   * `undefined` if cache is empty.\n   */\n  pop(): V | undefined {\n    try {\n      while (this.#size) {\n        const val = this.#valList[this.#head]\n        this.#evict(true)\n        if (this.#isBackgroundFetch(val)) {\n          if (val.__staleWhileFetching) {\n            return val.__staleWhileFetching\n          }\n        } else if (val !== undefined) {\n          return val\n        }\n      }\n    } finally {\n      if (this.#hasDisposeAfter && this.#disposed) {\n        const dt = this.#disposed\n        let task: DisposeTask | undefined\n        while ((task = dt?.shift())) {\n          this.#disposeAfter?.(...task)\n        }\n      }\n    }\n  }\n\n  #evict(free: boolean) {\n    const head = this.#head\n    const k = this.#keyList[head] as K\n    const v = this.#valList[head] as V\n    if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {\n      v.__abortController.abort(new Error('evicted'))\n    } else if (this.#hasDispose || this.#hasDisposeAfter) {\n      if (this.#hasDispose) {\n        this.#dispose?.(v, k, 'evict')\n      }\n      if (this.#hasDisposeAfter) {\n        this.#disposed?.push([v, k, 'evict'])\n      }\n    }\n    this.#removeItemSize(head)\n    // if we aren't about to use the index, then null these out\n    if (free) {\n      this.#keyList[head] = undefined\n      this.#valList[head] = undefined\n      this.#free.push(head)\n    }\n    if (this.#size === 1) {\n      this.#head = this.#tail = 0 as Index\n      this.#free.length = 0\n    } else {\n      this.#head = this.#next[head] as Index\n    }\n    this.#keyMap.delete(k)\n    this.#size--\n    return head\n  }\n\n  /**\n   * Check if a key is in the cache, without updating the recency of use.\n   * Will return false if the item is stale, even though it is technically\n   * in the cache.\n   *\n   * Will not update item age unless\n   * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.\n   */\n  has(k: K, hasOptions: LRUCache.HasOptions = {}) {\n    const { updateAgeOnHas = this.updateAgeOnHas, status } =\n      hasOptions\n    const index = this.#keyMap.get(k)\n    if (index !== undefined) {\n      const v = this.#valList[index]\n      if (\n        this.#isBackgroundFetch(v) &&\n        v.__staleWhileFetching === undefined\n      ) {\n        return false\n      }\n      if (!this.#isStale(index)) {\n        if (updateAgeOnHas) {\n          this.#updateItemAge(index)\n        }\n        if (status) {\n          status.has = 'hit'\n          this.#statusTTL(status, index)\n        }\n        return true\n      } else if (status) {\n        status.has = 'stale'\n        this.#statusTTL(status, index)\n      }\n    } else if (status) {\n      status.has = 'miss'\n    }\n    return false\n  }\n\n  /**\n   * Like {@link LRUCache#get} but doesn't update recency or delete stale\n   * items.\n   *\n   * Returns `undefined` if the item is stale, unless\n   * {@link LRUCache.OptionsBase.allowStale} is set.\n   */\n  peek(k: K, peekOptions: LRUCache.PeekOptions = {}) {\n    const { allowStale = this.allowStale } = peekOptions\n    const index = this.#keyMap.get(k)\n    if (\n      index === undefined ||\n      (!allowStale && this.#isStale(index))\n    ) {\n      return\n    }\n    const v = this.#valList[index]\n    // either stale and allowed, or forcing a refresh of non-stale value\n    return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n  }\n\n  #backgroundFetch(\n    k: K,\n    index: Index | undefined,\n    options: LRUCache.FetchOptions,\n    context: any\n  ): BackgroundFetch {\n    const v = index === undefined ? undefined : this.#valList[index]\n    if (this.#isBackgroundFetch(v)) {\n      return v\n    }\n\n    const ac = new AC()\n    const { signal } = options\n    // when/if our AC signals, then stop listening to theirs.\n    signal?.addEventListener('abort', () => ac.abort(signal.reason), {\n      signal: ac.signal,\n    })\n\n    const fetchOpts = {\n      signal: ac.signal,\n      options,\n      context,\n    }\n\n    const cb = (\n      v: V | undefined,\n      updateCache = false\n    ): V | undefined => {\n      const { aborted } = ac.signal\n      const ignoreAbort = options.ignoreFetchAbort && v !== undefined\n      if (options.status) {\n        if (aborted && !updateCache) {\n          options.status.fetchAborted = true\n          options.status.fetchError = ac.signal.reason\n          if (ignoreAbort) options.status.fetchAbortIgnored = true\n        } else {\n          options.status.fetchResolved = true\n        }\n      }\n      if (aborted && !ignoreAbort && !updateCache) {\n        return fetchFail(ac.signal.reason)\n      }\n      // either we didn't abort, and are still here, or we did, and ignored\n      const bf = p as BackgroundFetch\n      if (this.#valList[index as Index] === p) {\n        if (v === undefined) {\n          if (bf.__staleWhileFetching) {\n            this.#valList[index as Index] = bf.__staleWhileFetching\n          } else {\n            this.delete(k)\n          }\n        } else {\n          if (options.status) options.status.fetchUpdated = true\n          this.set(k, v, fetchOpts.options)\n        }\n      }\n      return v\n    }\n\n    const eb = (er: any) => {\n      if (options.status) {\n        options.status.fetchRejected = true\n        options.status.fetchError = er\n      }\n      return fetchFail(er)\n    }\n\n    const fetchFail = (er: any): V | undefined => {\n      const { aborted } = ac.signal\n      const allowStaleAborted =\n        aborted && options.allowStaleOnFetchAbort\n      const allowStale =\n        allowStaleAborted || options.allowStaleOnFetchRejection\n      const noDelete = allowStale || options.noDeleteOnFetchRejection\n      const bf = p as BackgroundFetch\n      if (this.#valList[index as Index] === p) {\n        // if we allow stale on fetch rejections, then we need to ensure that\n        // the stale value is not removed from the cache when the fetch fails.\n        const del = !noDelete || bf.__staleWhileFetching === undefined\n        if (del) {\n          this.delete(k)\n        } else if (!allowStaleAborted) {\n          // still replace the *promise* with the stale value,\n          // since we are done with the promise at this point.\n          // leave it untouched if we're still waiting for an\n          // aborted background fetch that hasn't yet returned.\n          this.#valList[index as Index] = bf.__staleWhileFetching\n        }\n      }\n      if (allowStale) {\n        if (options.status && bf.__staleWhileFetching !== undefined) {\n          options.status.returnedStale = true\n        }\n        return bf.__staleWhileFetching\n      } else if (bf.__returned === bf) {\n        throw er\n      }\n    }\n\n    const pcall = (\n      res: (v: V | undefined) => void,\n      rej: (e: any) => void\n    ) => {\n      const fmp = this.#fetchMethod?.(k, v, fetchOpts)\n      if (fmp && fmp instanceof Promise) {\n        fmp.then(v => res(v === undefined ? undefined : v), rej)\n      }\n      // ignored, we go until we finish, regardless.\n      // defer check until we are actually aborting,\n      // so fetchMethod can override.\n      ac.signal.addEventListener('abort', () => {\n        if (\n          !options.ignoreFetchAbort ||\n          options.allowStaleOnFetchAbort\n        ) {\n          res(undefined)\n          // when it eventually resolves, update the cache.\n          if (options.allowStaleOnFetchAbort) {\n            res = v => cb(v, true)\n          }\n        }\n      })\n    }\n\n    if (options.status) options.status.fetchDispatched = true\n    const p = new Promise(pcall).then(cb, eb)\n    const bf: BackgroundFetch = Object.assign(p, {\n      __abortController: ac,\n      __staleWhileFetching: v,\n      __returned: undefined,\n    })\n\n    if (index === undefined) {\n      // internal, don't expose status.\n      this.set(k, bf, { ...fetchOpts.options, status: undefined })\n      index = this.#keyMap.get(k)\n    } else {\n      this.#valList[index] = bf\n    }\n    return bf\n  }\n\n  #isBackgroundFetch(p: any): p is BackgroundFetch {\n    if (!this.#hasFetchMethod) return false\n    const b = p as BackgroundFetch\n    return (\n      !!b &&\n      b instanceof Promise &&\n      b.hasOwnProperty('__staleWhileFetching') &&\n      b.__abortController instanceof AC\n    )\n  }\n\n  /**\n   * Make an asynchronous cached fetch using the\n   * {@link LRUCache.OptionsBase.fetchMethod} function.\n   *\n   * If multiple fetches for the same key are issued, then they will all be\n   * coalesced into a single call to fetchMethod.\n   *\n   * Note that this means that handling options such as\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort},\n   * {@link LRUCache.FetchOptions.signal},\n   * and {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} will be\n   * determined by the FIRST fetch() call for a given key.\n   *\n   * This is a known (fixable) shortcoming which will be addresed on when\n   * someone complains about it, as the fix would involve added complexity and\n   * may not be worth the costs for this edge case.\n   */\n  fetch(\n    k: K,\n    fetchOptions: unknown extends FC\n      ? LRUCache.FetchOptions\n      : FC extends undefined | void\n      ? LRUCache.FetchOptionsNoContext\n      : LRUCache.FetchOptionsWithContext\n  ): Promise\n  // this overload not allowed if context is required\n  fetch(\n    k: unknown extends FC\n      ? K\n      : FC extends undefined | void\n      ? K\n      : never,\n    fetchOptions?: unknown extends FC\n      ? LRUCache.FetchOptions\n      : FC extends undefined | void\n      ? LRUCache.FetchOptionsNoContext\n      : never\n  ): Promise\n  async fetch(\n    k: K,\n    fetchOptions: LRUCache.FetchOptions = {}\n  ): Promise {\n    const {\n      // get options\n      allowStale = this.allowStale,\n      updateAgeOnGet = this.updateAgeOnGet,\n      noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n      // set options\n      ttl = this.ttl,\n      noDisposeOnSet = this.noDisposeOnSet,\n      size = 0,\n      sizeCalculation = this.sizeCalculation,\n      noUpdateTTL = this.noUpdateTTL,\n      // fetch exclusive options\n      noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,\n      allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,\n      ignoreFetchAbort = this.ignoreFetchAbort,\n      allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,\n      context,\n      forceRefresh = false,\n      status,\n      signal,\n    } = fetchOptions\n\n    if (!this.#hasFetchMethod) {\n      if (status) status.fetch = 'get'\n      return this.get(k, {\n        allowStale,\n        updateAgeOnGet,\n        noDeleteOnStaleGet,\n        status,\n      })\n    }\n\n    const options = {\n      allowStale,\n      updateAgeOnGet,\n      noDeleteOnStaleGet,\n      ttl,\n      noDisposeOnSet,\n      size,\n      sizeCalculation,\n      noUpdateTTL,\n      noDeleteOnFetchRejection,\n      allowStaleOnFetchRejection,\n      allowStaleOnFetchAbort,\n      ignoreFetchAbort,\n      status,\n      signal,\n    }\n\n    let index = this.#keyMap.get(k)\n    if (index === undefined) {\n      if (status) status.fetch = 'miss'\n      const p = this.#backgroundFetch(k, index, options, context)\n      return (p.__returned = p)\n    } else {\n      // in cache, maybe already fetching\n      const v = this.#valList[index]\n      if (this.#isBackgroundFetch(v)) {\n        const stale =\n          allowStale && v.__staleWhileFetching !== undefined\n        if (status) {\n          status.fetch = 'inflight'\n          if (stale) status.returnedStale = true\n        }\n        return stale ? v.__staleWhileFetching : (v.__returned = v)\n      }\n\n      // if we force a refresh, that means do NOT serve the cached value,\n      // unless we are already in the process of refreshing the cache.\n      const isStale = this.#isStale(index)\n      if (!forceRefresh && !isStale) {\n        if (status) status.fetch = 'hit'\n        this.#moveToTail(index)\n        if (updateAgeOnGet) {\n          this.#updateItemAge(index)\n        }\n        if (status) this.#statusTTL(status, index)\n        return v\n      }\n\n      // ok, it is stale or a forced refresh, and not already fetching.\n      // refresh the cache.\n      const p = this.#backgroundFetch(k, index, options, context)\n      const hasStale = p.__staleWhileFetching !== undefined\n      const staleVal = hasStale && allowStale\n      if (status) {\n        status.fetch = isStale ? 'stale' : 'refresh'\n        if (staleVal && isStale) status.returnedStale = true\n      }\n      return staleVal ? p.__staleWhileFetching : (p.__returned = p)\n    }\n  }\n\n  /**\n   * Return a value from the cache. Will update the recency of the cache\n   * entry found.\n   *\n   * If the key is not found, get() will return `undefined`.\n   */\n  get(k: K, getOptions: LRUCache.GetOptions = {}) {\n    const {\n      allowStale = this.allowStale,\n      updateAgeOnGet = this.updateAgeOnGet,\n      noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n      status,\n    } = getOptions\n    const index = this.#keyMap.get(k)\n    if (index !== undefined) {\n      const value = this.#valList[index]\n      const fetching = this.#isBackgroundFetch(value)\n      if (status) this.#statusTTL(status, index)\n      if (this.#isStale(index)) {\n        if (status) status.get = 'stale'\n        // delete only if not an in-flight background fetch\n        if (!fetching) {\n          if (!noDeleteOnStaleGet) {\n            this.delete(k)\n          }\n          if (status && allowStale) status.returnedStale = true\n          return allowStale ? value : undefined\n        } else {\n          if (\n            status &&\n            allowStale &&\n            value.__staleWhileFetching !== undefined\n          ) {\n            status.returnedStale = true\n          }\n          return allowStale ? value.__staleWhileFetching : undefined\n        }\n      } else {\n        if (status) status.get = 'hit'\n        // if we're currently fetching it, we don't actually have it yet\n        // it's not stale, which means this isn't a staleWhileRefetching.\n        // If it's not stale, and fetching, AND has a __staleWhileFetching\n        // value, then that means the user fetched with {forceRefresh:true},\n        // so it's safe to return that value.\n        if (fetching) {\n          return value.__staleWhileFetching\n        }\n        this.#moveToTail(index)\n        if (updateAgeOnGet) {\n          this.#updateItemAge(index)\n        }\n        return value\n      }\n    } else if (status) {\n      status.get = 'miss'\n    }\n  }\n\n  #connect(p: Index, n: Index) {\n    this.#prev[n] = p\n    this.#next[p] = n\n  }\n\n  #moveToTail(index: Index): void {\n    // if tail already, nothing to do\n    // if head, move head to next[index]\n    // else\n    //   move next[prev[index]] to next[index] (head has no prev)\n    //   move prev[next[index]] to prev[index]\n    // prev[index] = tail\n    // next[tail] = index\n    // tail = index\n    if (index !== this.#tail) {\n      if (index === this.#head) {\n        this.#head = this.#next[index] as Index\n      } else {\n        this.#connect(\n          this.#prev[index] as Index,\n          this.#next[index] as Index\n        )\n      }\n      this.#connect(this.#tail, index)\n      this.#tail = index\n    }\n  }\n\n  /**\n   * Deletes a key out of the cache.\n   * Returns true if the key was deleted, false otherwise.\n   */\n  delete(k: K) {\n    let deleted = false\n    if (this.#size !== 0) {\n      const index = this.#keyMap.get(k)\n      if (index !== undefined) {\n        deleted = true\n        if (this.#size === 1) {\n          this.clear()\n        } else {\n          this.#removeItemSize(index)\n          const v = this.#valList[index]\n          if (this.#isBackgroundFetch(v)) {\n            v.__abortController.abort(new Error('deleted'))\n          } else if (this.#hasDispose || this.#hasDisposeAfter) {\n            if (this.#hasDispose) {\n              this.#dispose?.(v as V, k, 'delete')\n            }\n            if (this.#hasDisposeAfter) {\n              this.#disposed?.push([v as V, k, 'delete'])\n            }\n          }\n          this.#keyMap.delete(k)\n          this.#keyList[index] = undefined\n          this.#valList[index] = undefined\n          if (index === this.#tail) {\n            this.#tail = this.#prev[index] as Index\n          } else if (index === this.#head) {\n            this.#head = this.#next[index] as Index\n          } else {\n            const pi = this.#prev[index] as number\n            this.#next[pi] = this.#next[index] as number\n            const ni = this.#next[index] as number\n            this.#prev[ni] = this.#prev[index] as number\n          }\n          this.#size--\n          this.#free.push(index)\n        }\n      }\n    }\n    if (this.#hasDisposeAfter && this.#disposed?.length) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n    return deleted\n  }\n\n  /**\n   * Clear the cache entirely, throwing away all values.\n   */\n  clear() {\n    for (const index of this.#rindexes({ allowStale: true })) {\n      const v = this.#valList[index]\n      if (this.#isBackgroundFetch(v)) {\n        v.__abortController.abort(new Error('deleted'))\n      } else {\n        const k = this.#keyList[index]\n        if (this.#hasDispose) {\n          this.#dispose?.(v as V, k as K, 'delete')\n        }\n        if (this.#hasDisposeAfter) {\n          this.#disposed?.push([v as V, k as K, 'delete'])\n        }\n      }\n    }\n\n    this.#keyMap.clear()\n    this.#valList.fill(undefined)\n    this.#keyList.fill(undefined)\n    if (this.#ttls && this.#starts) {\n      this.#ttls.fill(0)\n      this.#starts.fill(0)\n    }\n    if (this.#sizes) {\n      this.#sizes.fill(0)\n    }\n    this.#head = 0 as Index\n    this.#tail = 0 as Index\n    this.#free.length = 0\n    this.#calculatedSize = 0\n    this.#size = 0\n    if (this.#hasDisposeAfter && this.#disposed) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n  }\n}\n","import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'path'\n\nimport { fileURLToPath } from 'url'\n\nimport * as actualFS from 'fs'\nimport {\n  lstatSync,\n  readdir as readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync as rps,\n} from 'fs'\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\nimport { lstat, readdir, readlink, realpath } from 'fs/promises'\n\nimport type { Dirent, Stats } from 'fs'\nimport { Minipass } from 'minipass'\n\n/**\n * An object that will be used to override the default `fs`\n * methods.  Any methods that are not overridden will use Node's\n * built-in implementations.\n *\n * - lstatSync\n * - readdir (callback `withFileTypes` Dirent variant, used for\n *   readdirCB and most walks)\n * - readdirSync\n * - readlinkSync\n * - realpathSync\n * - promises: Object containing the following async methods:\n *   - lstat\n *   - readdir (Dirent variant only)\n *   - readlink\n *   - realpath\n */\nexport interface FSOption {\n  lstatSync?: (path: string) => Stats\n  readdir?: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any\n  ) => void\n  readdirSync?: (\n    path: string,\n    options: { withFileTypes: true }\n  ) => Dirent[]\n  readlinkSync?: (path: string) => string\n  realpathSync?: (path: string) => string\n  promises?: {\n    lstat?: (path: string) => Promise\n    readdir?: (\n      path: string,\n      options: { withFileTypes: true }\n    ) => Promise\n    readlink?: (path: string) => Promise\n    realpath?: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\ninterface FSValue {\n  lstatSync: (path: string) => Stats\n  readdir: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any\n  ) => void\n  readdirSync: (path: string, options: { withFileTypes: true }) => Dirent[]\n  readlinkSync: (path: string) => string\n  realpathSync: (path: string) => string\n  promises: {\n    lstat: (path: string) => Promise\n    readdir: (\n      path: string,\n      options: { withFileTypes: true }\n    ) => Promise\n    readlink: (path: string) => Promise\n    realpath: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\nconst defaultFS: FSValue = {\n  lstatSync,\n  readdir: readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync,\n  promises: {\n    lstat,\n    readdir,\n    readlink,\n    realpath,\n  },\n}\n\n// if they just gave us require('fs') then use our default\nconst fsFromOption = (fsOption?: FSOption): FSValue =>\n  !fsOption || fsOption === defaultFS || fsOption === actualFS\n    ? defaultFS\n    : {\n        ...defaultFS,\n        ...fsOption,\n        promises: {\n          ...defaultFS.promises,\n          ...(fsOption.promises || {}),\n        },\n      }\n\n// turn something like //?/c:/ into c:\\\nconst uncDriveRegexp = /^\\\\\\\\\\?\\\\([a-z]:)\\\\?$/i\nconst uncToDrive = (rootPath: string): string =>\n  rootPath.replace(/\\//g, '\\\\').replace(uncDriveRegexp, '$1\\\\')\n\n// windows paths are separated by either / or \\\nconst eitherSep = /[\\\\\\/]/\n\nconst UNKNOWN = 0 // may not even exist, for all we know\nconst IFIFO = 0b0001\nconst IFCHR = 0b0010\nconst IFDIR = 0b0100\nconst IFBLK = 0b0110\nconst IFREG = 0b1000\nconst IFLNK = 0b1010\nconst IFSOCK = 0b1100\nconst IFMT = 0b1111\n\nexport type Type =\n  | 'Unknown'\n  | 'FIFO'\n  | 'CharacterDevice'\n  | 'Directory'\n  | 'BlockDevice'\n  | 'File'\n  | 'SymbolicLink'\n  | 'Socket'\n\n// mask to unset low 4 bits\nconst IFMT_UNKNOWN = ~IFMT\n\n// set after successfully calling readdir() and getting entries.\nconst READDIR_CALLED = 0b0000_0001_0000\n// set after a successful lstat()\nconst LSTAT_CALLED = 0b0000_0010_0000\n// set if an entry (or one of its parents) is definitely not a dir\nconst ENOTDIR = 0b0000_0100_0000\n// set if an entry (or one of its parents) does not exist\n// (can also be set on lstat errors like EACCES or ENAMETOOLONG)\nconst ENOENT = 0b0000_1000_0000\n// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK\n// set if we fail to readlink\nconst ENOREADLINK = 0b0001_0000_0000\n// set if we know realpath() will fail\nconst ENOREALPATH = 0b0010_0000_0000\n\nconst ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH\nconst TYPEMASK = 0b0011_1111_1111\n\nconst entToType = (s: Dirent | Stats) =>\n  s.isFile()\n    ? IFREG\n    : s.isDirectory()\n    ? IFDIR\n    : s.isSymbolicLink()\n    ? IFLNK\n    : s.isCharacterDevice()\n    ? IFCHR\n    : s.isBlockDevice()\n    ? IFBLK\n    : s.isSocket()\n    ? IFSOCK\n    : s.isFIFO()\n    ? IFIFO\n    : UNKNOWN\n\n// normalize unicode path names\nconst normalizeCache = new Map()\nconst normalize = (s: string) => {\n  const c = normalizeCache.get(s)\n  if (c) return c\n  const n = s.normalize('NFKD')\n  normalizeCache.set(s, n)\n  return n\n}\n\nconst normalizeNocaseCache = new Map()\nconst normalizeNocase = (s: string) => {\n  const c = normalizeNocaseCache.get(s)\n  if (c) return c\n  const n = normalize(s.toLowerCase())\n  normalizeNocaseCache.set(s, n)\n  return n\n}\n\n/**\n * Options that may be provided to the Path constructor\n */\nexport interface PathOpts {\n  fullpath?: string\n  relative?: string\n  relativePosix?: string\n  parent?: PathBase\n  /**\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * An LRUCache for storing resolved path strings or Path objects.\n * @internal\n */\nexport class ResolveCache extends LRUCache {\n  constructor() {\n    super({ max: 256 })\n  }\n}\n\n// In order to prevent blowing out the js heap by allocating hundreds of\n// thousands of Path entries when walking extremely large trees, the \"children\"\n// in this tree are represented by storing an array of Path entries in an\n// LRUCache, indexed by the parent.  At any time, Path.children() may return an\n// empty array, indicating that it doesn't know about any of its children, and\n// thus has to rebuild that cache.  This is fine, it just means that we don't\n// benefit as much from having the cached entries, but huge directory walks\n// don't blow out the stack, and smaller ones are still as fast as possible.\n//\n//It does impose some complexity when building up the readdir data, because we\n//need to pass a reference to the children array that we started with.\n\n/**\n * an LRUCache for storing child entries.\n * @internal\n */\nexport class ChildrenCache extends LRUCache {\n  constructor(maxSize: number = 16 * 1024) {\n    super({\n      maxSize,\n      // parent + children\n      sizeCalculation: a => a.length + 1,\n    })\n  }\n}\n\n/**\n * Array of Path objects, plus a marker indicating the first provisional entry\n *\n * @internal\n */\nexport type Children = PathBase[] & { provisional: number }\n\nconst setAsCwd = Symbol('PathScurry setAsCwd')\n\n/**\n * Path objects are sort of like a super-powered\n * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}\n *\n * Each one represents a single filesystem entry on disk, which may or may not\n * exist. It includes methods for reading various types of information via\n * lstat, readlink, and readdir, and caches all information to the greatest\n * degree possible.\n *\n * Note that fs operations that would normally throw will instead return an\n * \"empty\" value. This is in order to prevent excessive overhead from error\n * stack traces.\n */\nexport abstract class PathBase implements Dirent {\n  /**\n   * the basename of this path\n   *\n   * **Important**: *always* test the path name against any test string\n   * usingthe {@link isNamed} method, and not by directly comparing this\n   * string. Otherwise, unicode path strings that the system sees as identical\n   * will not be properly treated as the same path, leading to incorrect\n   * behavior and possible security issues.\n   */\n  name: string\n  /**\n   * the Path entry corresponding to the path root.\n   *\n   * @internal\n   */\n  root: PathBase\n  /**\n   * All roots found within the current PathScurry family\n   *\n   * @internal\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * a reference to the parent path, or undefined in the case of root entries\n   *\n   * @internal\n   */\n  parent?: PathBase\n  /**\n   * boolean indicating whether paths are compared case-insensitively\n   * @internal\n   */\n  nocase: boolean\n\n  /**\n   * the string or regexp used to split paths. On posix, it is `'/'`, and on\n   * windows it is a RegExp matching either `'/'` or `'\\\\'`\n   */\n  abstract splitSep: string | RegExp\n  /**\n   * The path separator string to use when joining paths\n   */\n  abstract sep: string\n\n  // potential default fs override\n  #fs: FSValue\n\n  // Stats fields\n  #dev?: number\n  get dev() {\n    return this.#dev\n  }\n  #mode?: number\n  get mode() {\n    return this.#mode\n  }\n  #nlink?: number\n  get nlink() {\n    return this.#nlink\n  }\n  #uid?: number\n  get uid() {\n    return this.#uid\n  }\n  #gid?: number\n  get gid() {\n    return this.#gid\n  }\n  #rdev?: number\n  get rdev() {\n    return this.#rdev\n  }\n  #blksize?: number\n  get blksize() {\n    return this.#blksize\n  }\n  #ino?: number\n  get ino() {\n    return this.#ino\n  }\n  #size?: number\n  get size() {\n    return this.#size\n  }\n  #blocks?: number\n  get blocks() {\n    return this.#blocks\n  }\n  #atimeMs?: number\n  get atimeMs() {\n    return this.#atimeMs\n  }\n  #mtimeMs?: number\n  get mtimeMs() {\n    return this.#mtimeMs\n  }\n  #ctimeMs?: number\n  get ctimeMs() {\n    return this.#ctimeMs\n  }\n  #birthtimeMs?: number\n  get birthtimeMs() {\n    return this.#birthtimeMs\n  }\n  #atime?: Date\n  get atime() {\n    return this.#atime\n  }\n  #mtime?: Date\n  get mtime() {\n    return this.#mtime\n  }\n  #ctime?: Date\n  get ctime() {\n    return this.#ctime\n  }\n  #birthtime?: Date\n  get birthtime() {\n    return this.#birthtime\n  }\n\n  #matchName: string\n  #depth?: number\n  #fullpath?: string\n  #fullpathPosix?: string\n  #relative?: string\n  #relativePosix?: string\n  #type: number\n  #children: ChildrenCache\n  #linkTarget?: PathBase\n  #realpath?: PathBase\n\n  /**\n   * This property is for compatibility with the Dirent class as of\n   * Node v20, where Dirent['path'] refers to the path of the directory\n   * that was passed to readdir.  So, somewhat counterintuitively, this\n   * property refers to the *parent* path, not the path object itself.\n   * For root entries, it's the path to the entry itself.\n   */\n  get path(): string {\n    return (this.parent || this).fullpath()\n  }\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts\n  ) {\n    this.name = name\n    this.#matchName = nocase ? normalizeNocase(name) : normalize(name)\n    this.#type = type & TYPEMASK\n    this.nocase = nocase\n    this.roots = roots\n    this.root = root || this\n    this.#children = children\n    this.#fullpath = opts.fullpath\n    this.#relative = opts.relative\n    this.#relativePosix = opts.relativePosix\n    this.parent = opts.parent\n    if (this.parent) {\n      this.#fs = this.parent.#fs\n    } else {\n      this.#fs = fsFromOption(opts.fs)\n    }\n  }\n\n  /**\n   * Returns the depth of the Path object from its root.\n   *\n   * For example, a path at `/foo/bar` would have a depth of 2.\n   */\n  depth(): number {\n    if (this.#depth !== undefined) return this.#depth\n    if (!this.parent) return (this.#depth = 0)\n    return (this.#depth = this.parent.depth() + 1)\n  }\n\n  /**\n   * @internal\n   */\n  abstract getRootString(path: string): string\n  /**\n   * @internal\n   */\n  abstract getRoot(rootPath: string): PathBase\n  /**\n   * @internal\n   */\n  abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase\n\n  /**\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Get the Path object referenced by the string path, resolved from this Path\n   */\n  resolve(path?: string): PathBase {\n    if (!path) {\n      return this\n    }\n    const rootPath = this.getRootString(path)\n    const dir = path.substring(rootPath.length)\n    const dirParts = dir.split(this.splitSep)\n    const result: PathBase = rootPath\n      ? this.getRoot(rootPath).#resolveParts(dirParts)\n      : this.#resolveParts(dirParts)\n    return result\n  }\n\n  #resolveParts(dirParts: string[]) {\n    let p: PathBase = this\n    for (const part of dirParts) {\n      p = p.child(part)\n    }\n    return p\n  }\n\n  /**\n   * Returns the cached children Path objects, if still available.  If they\n   * have fallen out of the cache, then returns an empty array, and resets the\n   * READDIR_CALLED bit, so that future calls to readdir() will require an fs\n   * lookup.\n   *\n   * @internal\n   */\n  children(): Children {\n    const cached = this.#children.get(this)\n    if (cached) {\n      return cached\n    }\n    const children: Children = Object.assign([], { provisional: 0 })\n    this.#children.set(this, children)\n    this.#type &= ~READDIR_CALLED\n    return children\n  }\n\n  /**\n   * Resolves a path portion and returns or creates the child Path.\n   *\n   * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is\n   * `'..'`.\n   *\n   * This should not be called directly.  If `pathPart` contains any path\n   * separators, it will lead to unsafe undefined behavior.\n   *\n   * Use `Path.resolve()` instead.\n   *\n   * @internal\n   */\n  child(pathPart: string, opts?: PathOpts): PathBase {\n    if (pathPart === '' || pathPart === '.') {\n      return this\n    }\n    if (pathPart === '..') {\n      return this.parent || this\n    }\n\n    // find the child\n    const children = this.children()\n    const name = this.nocase\n      ? normalizeNocase(pathPart)\n      : normalize(pathPart)\n    for (const p of children) {\n      if (p.#matchName === name) {\n        return p\n      }\n    }\n\n    // didn't find it, create provisional child, since it might not\n    // actually exist.  If we know the parent isn't a dir, then\n    // in fact it CAN'T exist.\n    const s = this.parent ? this.sep : ''\n    const fullpath = this.#fullpath\n      ? this.#fullpath + s + pathPart\n      : undefined\n    const pchild = this.newChild(pathPart, UNKNOWN, {\n      ...opts,\n      parent: this,\n      fullpath,\n    })\n\n    if (!this.canReaddir()) {\n      pchild.#type |= ENOENT\n    }\n\n    // don't have to update provisional, because if we have real children,\n    // then provisional is set to children.length, otherwise a lower number\n    children.push(pchild)\n    return pchild\n  }\n\n  /**\n   * The relative path from the cwd. If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpath()\n   */\n  relative(): string {\n    if (this.#relative !== undefined) {\n      return this.#relative\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relative = this.name)\n    }\n    const pv = p.relative()\n    return pv + (!pv || !p.parent ? '' : this.sep) + name\n  }\n\n  /**\n   * The relative path from the cwd, using / as the path separator.\n   * If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpathPosix()\n   * On posix systems, this is identical to relative().\n   */\n  relativePosix(): string {\n    if (this.sep === '/') return this.relative()\n    if (this.#relativePosix !== undefined) return this.#relativePosix\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relativePosix = this.fullpathPosix())\n    }\n    const pv = p.relativePosix()\n    return pv + (!pv || !p.parent ? '' : '/') + name\n  }\n\n  /**\n   * The fully resolved path string for this Path entry\n   */\n  fullpath(): string {\n    if (this.#fullpath !== undefined) {\n      return this.#fullpath\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#fullpath = this.name)\n    }\n    const pv = p.fullpath()\n    const fp = pv + (!p.parent ? '' : this.sep) + name\n    return (this.#fullpath = fp)\n  }\n\n  /**\n   * On platforms other than windows, this is identical to fullpath.\n   *\n   * On windows, this is overridden to return the forward-slash form of the\n   * full UNC path.\n   */\n  fullpathPosix(): string {\n    if (this.#fullpathPosix !== undefined) return this.#fullpathPosix\n    if (this.sep === '/') return (this.#fullpathPosix = this.fullpath())\n    if (!this.parent) {\n      const p = this.fullpath().replace(/\\\\/g, '/')\n      if (/^[a-z]:\\//i.test(p)) {\n        return (this.#fullpathPosix = `//?/${p}`)\n      } else {\n        return (this.#fullpathPosix = p)\n      }\n    }\n    const p = this.parent\n    const pfpp = p.fullpathPosix()\n    const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name\n    return (this.#fullpathPosix = fpp)\n  }\n\n  /**\n   * Is the Path of an unknown type?\n   *\n   * Note that we might know *something* about it if there has been a previous\n   * filesystem operation, for example that it does not exist, or is not a\n   * link, or whether it has child entries.\n   */\n  isUnknown(): boolean {\n    return (this.#type & IFMT) === UNKNOWN\n  }\n\n  isType(type: Type): boolean {\n    return this[`is${type}`]()\n  }\n\n  getType(): Type {\n    return this.isUnknown()\n      ? 'Unknown'\n      : this.isDirectory()\n      ? 'Directory'\n      : this.isFile()\n      ? 'File'\n      : this.isSymbolicLink()\n      ? 'SymbolicLink'\n      : this.isFIFO()\n      ? 'FIFO'\n      : this.isCharacterDevice()\n      ? 'CharacterDevice'\n      : this.isBlockDevice()\n      ? 'BlockDevice'\n      : /* c8 ignore start */ this.isSocket()\n      ? 'Socket'\n      : 'Unknown'\n    /* c8 ignore stop */\n  }\n\n  /**\n   * Is the Path a regular file?\n   */\n  isFile(): boolean {\n    return (this.#type & IFMT) === IFREG\n  }\n\n  /**\n   * Is the Path a directory?\n   */\n  isDirectory(): boolean {\n    return (this.#type & IFMT) === IFDIR\n  }\n\n  /**\n   * Is the path a character device?\n   */\n  isCharacterDevice(): boolean {\n    return (this.#type & IFMT) === IFCHR\n  }\n\n  /**\n   * Is the path a block device?\n   */\n  isBlockDevice(): boolean {\n    return (this.#type & IFMT) === IFBLK\n  }\n\n  /**\n   * Is the path a FIFO pipe?\n   */\n  isFIFO(): boolean {\n    return (this.#type & IFMT) === IFIFO\n  }\n\n  /**\n   * Is the path a socket?\n   */\n  isSocket(): boolean {\n    return (this.#type & IFMT) === IFSOCK\n  }\n\n  /**\n   * Is the path a symbolic link?\n   */\n  isSymbolicLink(): boolean {\n    return (this.#type & IFLNK) === IFLNK\n  }\n\n  /**\n   * Return the entry if it has been subject of a successful lstat, or\n   * undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* simply\n   * mean that we haven't called lstat on it.\n   */\n  lstatCached(): PathBase | undefined {\n    return this.#type & LSTAT_CALLED ? this : undefined\n  }\n\n  /**\n   * Return the cached link target if the entry has been the subject of a\n   * successful readlink, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readlink() has been called at some point.\n   */\n  readlinkCached(): PathBase | undefined {\n    return this.#linkTarget\n  }\n\n  /**\n   * Returns the cached realpath target if the entry has been the subject\n   * of a successful realpath, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * realpath() has been called at some point.\n   */\n  realpathCached(): PathBase | undefined {\n    return this.#realpath\n  }\n\n  /**\n   * Returns the cached child Path entries array if the entry has been the\n   * subject of a successful readdir(), or [] otherwise.\n   *\n   * Does not read the filesystem, so an empty array *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readdir() has been called recently enough to still be valid.\n   */\n  readdirCached(): PathBase[] {\n    const children = this.children()\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * Return true if it's worth trying to readlink.  Ie, we don't (yet) have\n   * any indication that readlink will definitely fail.\n   *\n   * Returns false if the path is known to not be a symlink, if a previous\n   * readlink failed, or if the entry does not exist.\n   */\n  canReadlink(): boolean {\n    if (this.#linkTarget) return true\n    if (!this.parent) return false\n    // cases where it cannot possibly succeed\n    const ifmt = this.#type & IFMT\n    return !(\n      (ifmt !== UNKNOWN && ifmt !== IFLNK) ||\n      this.#type & ENOREADLINK ||\n      this.#type & ENOENT\n    )\n  }\n\n  /**\n   * Return true if readdir has previously been successfully called on this\n   * path, indicating that cachedReaddir() is likely valid.\n   */\n  calledReaddir(): boolean {\n    return !!(this.#type & READDIR_CALLED)\n  }\n\n  /**\n   * Returns true if the path is known to not exist. That is, a previous lstat\n   * or readdir failed to verify its existence when that would have been\n   * expected, or a parent entry was marked either enoent or enotdir.\n   */\n  isENOENT(): boolean {\n    return !!(this.#type & ENOENT)\n  }\n\n  /**\n   * Return true if the path is a match for the given path name.  This handles\n   * case sensitivity and unicode normalization.\n   *\n   * Note: even on case-sensitive systems, it is **not** safe to test the\n   * equality of the `.name` property to determine whether a given pathname\n   * matches, due to unicode normalization mismatches.\n   *\n   * Always use this method instead of testing the `path.name` property\n   * directly.\n   */\n  isNamed(n: string): boolean {\n    return !this.nocase\n      ? this.#matchName === normalize(n)\n      : this.#matchName === normalizeNocase(n)\n  }\n\n  /**\n   * Return the Path object corresponding to the target of a symbolic link.\n   *\n   * If the Path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   */\n  async readlink(): Promise {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = await this.#fs.promises.readlink(this.fullpath())\n      const linkTarget = this.parent.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  /**\n   * Synchronous {@link PathBase.readlink}\n   */\n  readlinkSync(): PathBase | undefined {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = this.#fs.readlinkSync(this.fullpath())\n      const linkTarget = this.parent.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  #readdirSuccess(children: Children) {\n    // succeeded, mark readdir called bit\n    this.#type |= READDIR_CALLED\n    // mark all remaining provisional children as ENOENT\n    for (let p = children.provisional; p < children.length; p++) {\n      children[p].#markENOENT()\n    }\n  }\n\n  #markENOENT() {\n    // mark as UNKNOWN and ENOENT\n    if (this.#type & ENOENT) return\n    this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN\n    this.#markChildrenENOENT()\n  }\n\n  #markChildrenENOENT() {\n    // all children are provisional and do not exist\n    const children = this.children()\n    children.provisional = 0\n    for (const p of children) {\n      p.#markENOENT()\n    }\n  }\n\n  #markENOREALPATH() {\n    this.#type |= ENOREALPATH\n    this.#markENOTDIR()\n  }\n\n  // save the information when we know the entry is not a dir\n  #markENOTDIR() {\n    // entry is not a directory, so any children can't exist.\n    // this *should* be impossible, since any children created\n    // after it's been marked ENOTDIR should be marked ENOENT,\n    // so it won't even get to this point.\n    /* c8 ignore start */\n    if (this.#type & ENOTDIR) return\n    /* c8 ignore stop */\n    let t = this.#type\n    // this could happen if we stat a dir, then delete it,\n    // then try to read it or one of its children.\n    if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN\n    this.#type = t | ENOTDIR\n    this.#markChildrenENOENT()\n  }\n\n  #readdirFail(code: string = '') {\n    // markENOTDIR and markENOENT also set provisional=0\n    if (code === 'ENOTDIR' || code === 'EPERM') {\n      this.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      this.#markENOENT()\n    } else {\n      this.children().provisional = 0\n    }\n  }\n\n  #lstatFail(code: string = '') {\n    // Windows just raises ENOENT in this case, disable for win CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR') {\n      // already know it has a parent by this point\n      const p = this.parent as PathBase\n      p.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      /* c8 ignore stop */\n      this.#markENOENT()\n    }\n  }\n\n  #readlinkFail(code: string = '') {\n    let ter = this.#type\n    ter |= ENOREADLINK\n    if (code === 'ENOENT') ter |= ENOENT\n    // windows gets a weird error when you try to readlink a file\n    if (code === 'EINVAL' || code === 'UNKNOWN') {\n      // exists, but not a symlink, we don't know WHAT it is, so remove\n      // all IFMT bits.\n      ter &= IFMT_UNKNOWN\n    }\n    this.#type = ter\n    // windows just gets ENOENT in this case.  We do cover the case,\n    // just disabled because it's impossible on Windows CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR' && this.parent) {\n      this.parent.#markENOTDIR()\n    }\n    /* c8 ignore stop */\n  }\n\n  #readdirAddChild(e: Dirent, c: Children) {\n    return (\n      this.#readdirMaybePromoteChild(e, c) ||\n      this.#readdirAddNewChild(e, c)\n    )\n  }\n\n  #readdirAddNewChild(e: Dirent, c: Children): PathBase {\n    // alloc new entry at head, so it's never provisional\n    const type = entToType(e)\n    const child = this.newChild(e.name, type, { parent: this })\n    const ifmt = child.#type & IFMT\n    if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {\n      child.#type |= ENOTDIR\n    }\n    c.unshift(child)\n    c.provisional++\n    return child\n  }\n\n  #readdirMaybePromoteChild(e: Dirent, c: Children): PathBase | undefined {\n    for (let p = c.provisional; p < c.length; p++) {\n      const pchild = c[p]\n      const name = this.nocase\n        ? normalizeNocase(e.name)\n        : normalize(e.name)\n      if (name !== pchild.#matchName) {\n        continue\n      }\n\n      return this.#readdirPromoteChild(e, pchild, p, c)\n    }\n  }\n\n  #readdirPromoteChild(\n    e: Dirent,\n    p: PathBase,\n    index: number,\n    c: Children\n  ): PathBase {\n    const v = p.name\n    // retain any other flags, but set ifmt from dirent\n    p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e)\n    // case sensitivity fixing when we learn the true name.\n    if (v !== e.name) p.name = e.name\n\n    // just advance provisional index (potentially off the list),\n    // otherwise we have to splice/pop it out and re-insert at head\n    if (index !== c.provisional) {\n      if (index === c.length - 1) c.pop()\n      else c.splice(index, 1)\n      c.unshift(p)\n    }\n    c.provisional++\n    return p\n  }\n\n  /**\n   * Call lstat() on this Path, and update all known information that can be\n   * determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(): Promise {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(await this.#fs.promises.lstat(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  /**\n   * synchronous {@link PathBase.lstat}\n   */\n  lstatSync(): PathBase | undefined {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(this.#fs.lstatSync(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  #applyStat(st: Stats) {\n    const {\n      atime,\n      atimeMs,\n      birthtime,\n      birthtimeMs,\n      blksize,\n      blocks,\n      ctime,\n      ctimeMs,\n      dev,\n      gid,\n      ino,\n      mode,\n      mtime,\n      mtimeMs,\n      nlink,\n      rdev,\n      size,\n      uid,\n    } = st\n    this.#atime = atime\n    this.#atimeMs = atimeMs\n    this.#birthtime = birthtime\n    this.#birthtimeMs = birthtimeMs\n    this.#blksize = blksize\n    this.#blocks = blocks\n    this.#ctime = ctime\n    this.#ctimeMs = ctimeMs\n    this.#dev = dev\n    this.#gid = gid\n    this.#ino = ino\n    this.#mode = mode\n    this.#mtime = mtime\n    this.#mtimeMs = mtimeMs\n    this.#nlink = nlink\n    this.#rdev = rdev\n    this.#size = size\n    this.#uid = uid\n    const ifmt = entToType(st)\n    // retain any other flags, but set the ifmt\n    this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED\n    if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {\n      this.#type |= ENOTDIR\n    }\n  }\n\n  #onReaddirCB: ((\n    er: NodeJS.ErrnoException | null,\n    entries: Path[]\n  ) => any)[] = []\n  #readdirCBInFlight: boolean = false\n  #callOnReaddirCB(children: Path[]) {\n    this.#readdirCBInFlight = false\n    const cbs = this.#onReaddirCB.slice()\n    this.#onReaddirCB.length = 0\n    cbs.forEach(cb => cb(null, children))\n  }\n\n  /**\n   * Standard node-style callback interface to get list of directory entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * @param cb The callback called with (er, entries).  Note that the `er`\n   * param is somewhat extraneous, as all readdir() errors are handled and\n   * simply result in an empty set of entries being returned.\n   * @param allowZalgo Boolean indicating that immediately known results should\n   * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release\n   * zalgo at your peril, the dark pony lord is devious and unforgiving.\n   */\n  readdirCB(\n    cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any,\n    allowZalgo: boolean = false\n  ): void {\n    if (!this.canReaddir()) {\n      if (allowZalgo) cb(null, [])\n      else queueMicrotask(() => cb(null, []))\n      return\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      const c = children.slice(0, children.provisional)\n      if (allowZalgo) cb(null, c)\n      else queueMicrotask(() => cb(null, c))\n      return\n    }\n\n    // don't have to worry about zalgo at this point.\n    this.#onReaddirCB.push(cb)\n    if (this.#readdirCBInFlight) {\n      return\n    }\n    this.#readdirCBInFlight = true\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {\n      if (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      } else {\n        // if we didn't get an error, we always get entries.\n        //@ts-ignore\n        for (const e of entries) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      }\n      this.#callOnReaddirCB(children.slice(0, children.provisional))\n      return\n    })\n  }\n\n  #asyncReaddirInFlight?: Promise\n\n  /**\n   * Return an array of known child entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async readdir(): Promise {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    if (this.#asyncReaddirInFlight) {\n      await this.#asyncReaddirInFlight\n    } else {\n      /* c8 ignore start */\n      let resolve: () => void = () => {}\n      /* c8 ignore stop */\n      this.#asyncReaddirInFlight = new Promise(\n        res => (resolve = res)\n      )\n      try {\n        for (const e of await this.#fs.promises.readdir(fullpath, {\n          withFileTypes: true,\n        })) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      } catch (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      }\n      this.#asyncReaddirInFlight = undefined\n      resolve()\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * synchronous {@link PathBase.readdir}\n   */\n  readdirSync(): PathBase[] {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    try {\n      for (const e of this.#fs.readdirSync(fullpath, {\n        withFileTypes: true,\n      })) {\n        this.#readdirAddChild(e, children)\n      }\n      this.#readdirSuccess(children)\n    } catch (er) {\n      this.#readdirFail((er as NodeJS.ErrnoException).code)\n      children.provisional = 0\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  canReaddir() {\n    if (this.#type & ENOCHILD) return false\n    const ifmt = IFMT & this.#type\n    // we always set ENOTDIR when setting IFMT, so should be impossible\n    /* c8 ignore start */\n    if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {\n      return false\n    }\n    /* c8 ignore stop */\n    return true\n  }\n\n  shouldWalk(\n    dirs: Set,\n    walkFilter?: (e: PathBase) => boolean\n  ): boolean {\n    return (\n      (this.#type & IFDIR) === IFDIR &&\n      !(this.#type & ENOCHILD) &&\n      !dirs.has(this) &&\n      (!walkFilter || walkFilter(this))\n    )\n  }\n\n  /**\n   * Return the Path object corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   * On success, returns a Path object.\n   */\n  async realpath(): Promise {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = await this.#fs.promises.realpath(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch (_) {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Synchronous {@link realpath}\n   */\n  realpathSync(): PathBase | undefined {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = this.#fs.realpathSync(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch (_) {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Internal method to mark this Path object as the scurry cwd,\n   * called by {@link PathScurry#chdir}\n   *\n   * @internal\n   */\n  [setAsCwd](oldCwd: PathBase): void {\n    if (oldCwd === this) return\n\n    const changed = new Set([])\n    let rp = []\n    let p: PathBase = this\n    while (p && p.parent) {\n      changed.add(p)\n      p.#relative = rp.join(this.sep)\n      p.#relativePosix = rp.join('/')\n      p = p.parent\n      rp.push('..')\n    }\n    // now un-memoize parents of old cwd\n    p = oldCwd\n    while (p && p.parent && !changed.has(p)) {\n      p.#relative = undefined\n      p.#relativePosix = undefined\n      p = p.parent\n    }\n  }\n}\n\n/**\n * Path class used on win32 systems\n *\n * Uses `'\\\\'` as the path separator for returned paths, either `'\\\\'` or `'/'`\n * as the path separator for parsing paths.\n */\nexport class PathWin32 extends PathBase {\n  /**\n   * Separator for generating path strings.\n   */\n  sep: '\\\\' = '\\\\'\n  /**\n   * Separator for parsing path strings.\n   */\n  splitSep: RegExp = eitherSep\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathWin32(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts\n    )\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return win32.parse(path).root\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(rootPath: string): PathBase {\n    rootPath = uncToDrive(rootPath.toUpperCase())\n    if (rootPath === this.root.name) {\n      return this.root\n    }\n    // ok, not that one, check if it matches another we know about\n    for (const [compare, root] of Object.entries(this.roots)) {\n      if (this.sameRoot(rootPath, compare)) {\n        return (this.roots[rootPath] = root)\n      }\n    }\n    // otherwise, have to create a new one.\n    return (this.roots[rootPath] = new PathScurryWin32(\n      rootPath,\n      this\n    ).root)\n  }\n\n  /**\n   * @internal\n   */\n  sameRoot(rootPath: string, compare: string = this.root.name): boolean {\n    // windows can (rarely) have case-sensitive filesystem, but\n    // UNC and drive letters are always case-insensitive, and canonically\n    // represented uppercase.\n    rootPath = rootPath\n      .toUpperCase()\n      .replace(/\\//g, '\\\\')\n      .replace(uncDriveRegexp, '$1\\\\')\n    return rootPath === compare\n  }\n}\n\n/**\n * Path class used on all posix systems.\n *\n * Uses `'/'` as the path separator.\n */\nexport class PathPosix extends PathBase {\n  /**\n   * separator for parsing path strings\n   */\n  splitSep: '/' = '/'\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return path.startsWith('/') ? '/' : ''\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(_rootPath: string): PathBase {\n    return this.root\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathPosix(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts\n    )\n  }\n}\n\n/**\n * Options that may be provided to the PathScurry constructor\n */\nexport interface PathScurryOpts {\n  /**\n   * perform case-insensitive path matching. Default based on platform\n   * subclass.\n   */\n  nocase?: boolean\n  /**\n   * Number of Path entries to keep in the cache of Path child references.\n   *\n   * Setting this higher than 65536 will dramatically increase the data\n   * consumption and construction time overhead of each PathScurry.\n   *\n   * Setting this value to 256 or lower will significantly reduce the data\n   * consumption and construction time overhead, but may also reduce resolve()\n   * and readdir() performance on large filesystems.\n   *\n   * Default `16384`.\n   */\n  childrenCacheSize?: number\n  /**\n   * An object that overrides the built-in functions from the fs and\n   * fs/promises modules.\n   *\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * The base class for all PathScurry classes, providing the interface for path\n * resolution and filesystem operations.\n *\n * Typically, you should *not* instantiate this class directly, but rather one\n * of the platform-specific classes, or the exported {@link PathScurry} which\n * defaults to the current platform.\n */\nexport abstract class PathScurryBase {\n  /**\n   * The root Path entry for the current working directory of this Scurry\n   */\n  root: PathBase\n  /**\n   * The string path for the root of this Scurry's current working directory\n   */\n  rootPath: string\n  /**\n   * A collection of all roots encountered, referenced by rootPath\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * The Path entry corresponding to this PathScurry's current working directory.\n   */\n  cwd: PathBase\n  #resolveCache: ResolveCache\n  #resolvePosixCache: ResolveCache\n  #children: ChildrenCache\n  /**\n   * Perform path comparisons case-insensitively.\n   *\n   * Defaults true on Darwin and Windows systems, false elsewhere.\n   */\n  nocase: boolean\n\n  /**\n   * The path separator used for parsing paths\n   *\n   * `'/'` on Posix systems, either `'/'` or `'\\\\'` on Windows\n   */\n  abstract sep: string | RegExp\n\n  #fs: FSValue\n\n  /**\n   * This class should not be instantiated directly.\n   *\n   * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry\n   *\n   * @internal\n   */\n  constructor(\n    cwd: URL | string = process.cwd(),\n    pathImpl: typeof win32 | typeof posix,\n    sep: string | RegExp,\n    {\n      nocase,\n      childrenCacheSize = 16 * 1024,\n      fs = defaultFS,\n    }: PathScurryOpts = {}\n  ) {\n    this.#fs = fsFromOption(fs)\n    if (cwd instanceof URL || cwd.startsWith('file://')) {\n      cwd = fileURLToPath(cwd)\n    }\n    // resolve and split root, and then add to the store.\n    // this is the only time we call path.resolve()\n    const cwdPath = pathImpl.resolve(cwd)\n    this.roots = Object.create(null)\n    this.rootPath = this.parseRootPath(cwdPath)\n    this.#resolveCache = new ResolveCache()\n    this.#resolvePosixCache = new ResolveCache()\n    this.#children = new ChildrenCache(childrenCacheSize)\n\n    const split = cwdPath.substring(this.rootPath.length).split(sep)\n    // resolve('/') leaves '', splits to [''], we don't want that.\n    if (split.length === 1 && !split[0]) {\n      split.pop()\n    }\n    /* c8 ignore start */\n    if (nocase === undefined) {\n      throw new TypeError(\n        'must provide nocase setting to PathScurryBase ctor'\n      )\n    }\n    /* c8 ignore stop */\n    this.nocase = nocase\n    this.root = this.newRoot(this.#fs)\n    this.roots[this.rootPath] = this.root\n    let prev: PathBase = this.root\n    let len = split.length - 1\n    const joinSep = pathImpl.sep\n    let abs = this.rootPath\n    let sawFirst = false\n    for (const part of split) {\n      const l = len--\n      prev = prev.child(part, {\n        relative: new Array(l).fill('..').join(joinSep),\n        relativePosix: new Array(l).fill('..').join('/'),\n        fullpath: (abs += (sawFirst ? '' : joinSep) + part),\n      })\n      sawFirst = true\n    }\n    this.cwd = prev\n  }\n\n  /**\n   * Get the depth of a provided path, string, or the cwd\n   */\n  depth(path: Path | string = this.cwd): number {\n    if (typeof path === 'string') {\n      path = this.cwd.resolve(path)\n    }\n    return path.depth()\n  }\n\n  /**\n   * Parse the root portion of a path string\n   *\n   * @internal\n   */\n  abstract parseRootPath(dir: string): string\n  /**\n   * create a new Path to use as root during construction.\n   *\n   * @internal\n   */\n  abstract newRoot(fs: FSValue): PathBase\n  /**\n   * Determine whether a given path string is absolute\n   */\n  abstract isAbsolute(p: string): boolean\n\n  /**\n   * Return the cache of child entries.  Exposed so subclasses can create\n   * child Path objects in a platform-specific way.\n   *\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolve(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolveCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpath()\n    this.#resolveCache.set(r, result)\n    return result\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string, returning\n   * the posix path.  Identical to .resolve() on posix systems, but on\n   * windows will return a forward-slash separated UNC path.\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolvePosix(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolvePosixCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpathPosix()\n    this.#resolvePosixCache.set(r, result)\n    return result\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or entry\n   */\n  relative(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relative()\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or\n   * entry, using / as the path delimiter, even on Windows.\n   */\n  relativePosix(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relativePosix()\n  }\n\n  /**\n   * Return the basename for the provided string or Path object\n   */\n  basename(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.name\n  }\n\n  /**\n   * Return the dirname for the provided string or Path object\n   */\n  dirname(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return (entry.parent || entry).fullpath()\n  }\n\n  /**\n   * Return an array of known child entries.\n   *\n   * First argument may be either a string, or a Path object.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set\n   * `{ withFileTypes: false }` to return strings.\n   */\n\n  readdir(): Promise\n  readdir(opts: { withFileTypes: true }): Promise\n  readdir(opts: { withFileTypes: false }): Promise\n  readdir(opts: { withFileTypes: boolean }): Promise\n  readdir(entry: PathBase | string): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: true }\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: false }\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean }\n  ): Promise\n  async readdir(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    }\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else {\n      const p = await entry.readdir()\n      return withFileTypes ? p : p.map(e => e.name)\n    }\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readdir}\n   */\n  readdirSync(): PathBase[]\n  readdirSync(opts: { withFileTypes: true }): PathBase[]\n  readdirSync(opts: { withFileTypes: false }): string[]\n  readdirSync(opts: { withFileTypes: boolean }): PathBase[] | string[]\n  readdirSync(entry: PathBase | string): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: true }\n  ): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: false }\n  ): string[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean }\n  ): PathBase[] | string[]\n  readdirSync(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    }\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes = true } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else if (withFileTypes) {\n      return entry.readdirSync()\n    } else {\n      return entry.readdirSync().map(e => e.name)\n    }\n  }\n\n  /**\n   * Call lstat() on the string or Path object, and update all known\n   * information that can be determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(\n    entry: string | PathBase = this.cwd\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstat()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.lstat}\n   */\n  lstatSync(entry: string | PathBase = this.cwd): PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstatSync()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to the target of a\n   * symbolic link.\n   *\n   * If the path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  readlink(): Promise\n  readlink(opt: { withFileTypes: false }): Promise\n  readlink(opt: { withFileTypes: true }): Promise\n  readlink(opt: {\n    withFileTypes: boolean\n  }): Promise\n  readlink(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false }\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: true }\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean }\n  ): Promise\n  async readlink(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    }\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.readlink()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readlink}\n   */\n  readlinkSync(): string | undefined\n  readlinkSync(opt: { withFileTypes: false }): string | undefined\n  readlinkSync(opt: { withFileTypes: true }): PathBase | undefined\n  readlinkSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false }\n  ): string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true }\n  ): PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean }\n  ): string | PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    }\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.readlinkSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  realpath(): Promise\n  realpath(opt: { withFileTypes: false }): Promise\n  realpath(opt: { withFileTypes: true }): Promise\n  realpath(opt: {\n    withFileTypes: boolean\n  }): Promise\n  realpath(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false }\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: true }\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean }\n  ): Promise\n  async realpath(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    }\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.realpath()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  realpathSync(): string | undefined\n  realpathSync(opt: { withFileTypes: false }): string | undefined\n  realpathSync(opt: { withFileTypes: true }): PathBase | undefined\n  realpathSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false }\n  ): string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true }\n  ): PathBase | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean }\n  ): string | PathBase | undefined\n  realpathSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    }\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.realpathSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Asynchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walk(): Promise\n  walk(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): Promise\n  walk(opts: WalkOptionsWithFileTypesFalse): Promise\n  walk(opts: WalkOptions): Promise\n  walk(entry: string | PathBase): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptions\n  ): Promise\n  async walk(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {}\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const walk = (\n      dir: PathBase,\n      cb: (er?: NodeJS.ErrnoException) => void\n    ) => {\n      dirs.add(dir)\n      dir.readdirCB((er, entries) => {\n        /* c8 ignore start */\n        if (er) {\n          return cb(er)\n        }\n        /* c8 ignore stop */\n        let len = entries.length\n        if (!len) return cb()\n        const next = () => {\n          if (--len === 0) {\n            cb()\n          }\n        }\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            results.push(withFileTypes ? e : e.fullpath())\n          }\n          if (follow && e.isSymbolicLink()) {\n            e.realpath()\n              .then(r => (r?.isUnknown() ? r.lstat() : r))\n              .then(r =>\n                r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next()\n              )\n          } else {\n            if (e.shouldWalk(dirs, walkFilter)) {\n              walk(e, next)\n            } else {\n              next()\n            }\n          }\n        }\n      }, true) // zalgooooooo\n    }\n\n    const start = entry\n    return new Promise((res, rej) => {\n      walk(start, er => {\n        /* c8 ignore start */\n        if (er) return rej(er)\n        /* c8 ignore stop */\n        res(results as PathBase[] | string[])\n      })\n    })\n  }\n\n  /**\n   * Synchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walkSync(): PathBase[]\n  walkSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): PathBase[]\n  walkSync(opts: WalkOptionsWithFileTypesFalse): string[]\n  walkSync(opts: WalkOptions): string[] | PathBase[]\n  walkSync(entry: string | PathBase): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue\n  ): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse\n  ): string[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptions\n  ): PathBase[] | string[]\n  walkSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {}\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          results.push(withFileTypes ? e : e.fullpath())\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n    return results as string[] | PathBase[]\n  }\n\n  /**\n   * Support for `for await`\n   *\n   * Alias for {@link PathScurryBase.iterate}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n\n  /**\n   * Async generator form of {@link PathScurryBase.walk}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking, especially if most/all of the directory tree has been previously\n   * walked.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  iterate(): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesFalse\n  ): AsyncGenerator\n  iterate(opts: WalkOptions): AsyncGenerator\n  iterate(entry: string | PathBase): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptions\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    options: WalkOptions = {}\n  ): AsyncGenerator {\n    // iterating async over the stream is significantly more performant,\n    // especially in the warm-cache scenario, because it buffers up directory\n    // entries in the background instead of waiting for a yield for each one.\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      options = entry\n      entry = this.cwd\n    }\n    return this.stream(entry, options)[Symbol.asyncIterator]()\n  }\n\n  /**\n   * Iterating over a PathScurry performs a synchronous walk.\n   *\n   * Alias for {@link PathScurryBase.iterateSync}\n   */\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  iterateSync(): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesFalse\n  ): Generator\n  iterateSync(opts: WalkOptions): Generator\n  iterateSync(entry: string | PathBase): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptions\n  ): Generator\n  *iterateSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {}\n  ): Generator {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    if (!filter || filter(entry)) {\n      yield withFileTypes ? entry : entry.fullpath()\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          yield withFileTypes ? e : e.fullpath()\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n  }\n\n  /**\n   * Stream form of {@link PathScurryBase.walk}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   */\n  stream(): Minipass\n  stream(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): Minipass\n  stream(opts: WalkOptionsWithFileTypesFalse): Minipass\n  stream(opts: WalkOptions): Minipass\n  stream(entry: string | PathBase): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptions\n  ): Minipass | Minipass\n  stream(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {}\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n\n        processing++\n        dirs.add(dir)\n\n        const onReaddir = (\n          er: null | NodeJS.ErrnoException,\n          entries: PathBase[],\n          didRealpaths: boolean = false\n        ) => {\n          /* c8 ignore start */\n          if (er) return results.emit('error', er)\n          /* c8 ignore stop */\n          if (follow && !didRealpaths) {\n            const promises: Promise[] = []\n            for (const e of entries) {\n              if (e.isSymbolicLink()) {\n                promises.push(\n                  e\n                    .realpath()\n                    .then((r: PathBase | undefined) =>\n                      r?.isUnknown() ? r.lstat() : r\n                    )\n                )\n              }\n            }\n            if (promises.length) {\n              Promise.all(promises).then(() =>\n                onReaddir(null, entries, true)\n              )\n              return\n            }\n          }\n\n          for (const e of entries) {\n            if (e && (!filter || filter(e))) {\n              if (!results.write(withFileTypes ? e : e.fullpath())) {\n                paused = true\n              }\n            }\n          }\n\n          processing--\n          for (const e of entries) {\n            const r = e.realpathCached() || e\n            if (r.shouldWalk(dirs, walkFilter)) {\n              queue.push(r)\n            }\n          }\n          if (paused && !results.flowing) {\n            results.once('drain', process)\n          } else if (!sync) {\n            process()\n          }\n        }\n\n        // zalgo containment\n        let sync = true\n        dir.readdirCB(onReaddir, true)\n        sync = false\n      }\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  /**\n   * Synchronous form of {@link PathScurryBase.stream}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   *\n   * Will complete the walk in a single tick if the stream is consumed fully.\n   * Otherwise, will pause as needed for stream backpressure.\n   */\n  streamSync(): Minipass\n  streamSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset\n  ): Minipass\n  streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass\n  streamSync(opts: WalkOptions): Minipass\n  streamSync(entry: string | PathBase): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptions\n  ): Minipass | Minipass\n  streamSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {}\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    const dirs = new Set()\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n        processing++\n        dirs.add(dir)\n\n        const entries = dir.readdirSync()\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            if (!results.write(withFileTypes ? e : e.fullpath())) {\n              paused = true\n            }\n          }\n        }\n        processing--\n        for (const e of entries) {\n          let r: PathBase | undefined = e\n          if (e.isSymbolicLink()) {\n            if (!(follow && (r = e.realpathSync()))) continue\n            if (r.isUnknown()) r.lstatSync()\n          }\n          if (r.shouldWalk(dirs, walkFilter)) {\n            queue.push(r)\n          }\n        }\n      }\n      if (paused && !results.flowing) results.once('drain', process)\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  chdir(path: string | Path = this.cwd) {\n    const oldCwd = this.cwd\n    this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path\n    this.cwd[setAsCwd](oldCwd)\n  }\n}\n\n/**\n * Options provided to all walk methods.\n */\nexport interface WalkOptions {\n  /**\n   * Return results as {@link PathBase} objects rather than strings.\n   * When set to false, results are fully resolved paths, as returned by\n   * {@link PathBase.fullpath}.\n   * @default true\n   */\n  withFileTypes?: boolean\n\n  /**\n   *  Attempt to read directory entries from symbolic links. Otherwise, only\n   *  actual directories are traversed. Regardless of this setting, a given\n   *  target path will only ever be walked once, meaning that a symbolic link\n   *  to a previously traversed directory will never be followed.\n   *\n   *  Setting this imposes a slight performance penalty, because `readlink`\n   *  must be called on all symbolic links encountered, in order to avoid\n   *  infinite cycles.\n   * @default false\n   */\n  follow?: boolean\n\n  /**\n   * Only return entries where the provided function returns true.\n   *\n   * This will not prevent directories from being traversed, even if they do\n   * not pass the filter, though it will prevent directories themselves from\n   * being included in the result set.  See {@link walkFilter}\n   *\n   * Asynchronous functions are not supported here.\n   *\n   * By default, if no filter is provided, all entries and traversed\n   * directories are included.\n   */\n  filter?: (entry: PathBase) => boolean\n\n  /**\n   * Only traverse directories (and in the case of {@link follow} being set to\n   * true, symbolic links to directories) if the provided function returns\n   * true.\n   *\n   * This will not prevent directories from being included in the result set,\n   * even if they do not pass the supplied filter function.  See {@link filter}\n   * to do that.\n   *\n   * Asynchronous functions are not supported here.\n   */\n  walkFilter?: (entry: PathBase) => boolean\n}\n\nexport type WalkOptionsWithFileTypesUnset = WalkOptions & {\n  withFileTypes?: undefined\n}\nexport type WalkOptionsWithFileTypesTrue = WalkOptions & {\n  withFileTypes: true\n}\nexport type WalkOptionsWithFileTypesFalse = WalkOptions & {\n  withFileTypes: false\n}\n\n/**\n * Windows implementation of {@link PathScurryBase}\n *\n * Defaults to case insensitve, uses `'\\\\'` to generate path strings.  Uses\n * {@link PathWin32} for Path objects.\n */\nexport class PathScurryWin32 extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '\\\\' = '\\\\'\n\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {}\n  ) {\n    const { nocase = true } = opts\n    super(cwd, win32, '\\\\', { ...opts, nocase })\n    this.nocase = nocase\n    for (let p: PathBase | undefined = this.cwd; p; p = p.parent) {\n      p.nocase = this.nocase\n    }\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(dir: string): string {\n    // if the path starts with a single separator, it's not a UNC, and we'll\n    // just get separator as the root, and driveFromUNC will return \\\n    // In that case, mount \\ on the root from the cwd.\n    return win32.parse(dir).root.toUpperCase()\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathWin32(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs }\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return (\n      p.startsWith('/') || p.startsWith('\\\\') || /^[a-z]:(\\/|\\\\)/i.test(p)\n    )\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for all posix systems other than Darwin.\n *\n * Defaults to case-sensitive matching, uses `'/'` to generate path strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryPosix extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {}\n  ) {\n    const { nocase = false } = opts\n    super(cwd, posix, '/', { ...opts, nocase })\n    this.nocase = nocase\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(_dir: string): string {\n    return '/'\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathPosix(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs }\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return p.startsWith('/')\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for Darwin (macOS) systems.\n *\n * Defaults to case-insensitive matching, uses `'/'` for generating path\n * strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryDarwin extends PathScurryPosix {\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {}\n  ) {\n    const { nocase = true } = opts\n    super(cwd, { ...opts, nocase })\n  }\n}\n\n/**\n * Default {@link PathBase} implementation for the current platform.\n *\n * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.\n */\nexport const Path = process.platform === 'win32' ? PathWin32 : PathPosix\nexport type Path = PathBase | InstanceType\n\n/**\n * Default {@link PathScurryBase} implementation for the current platform.\n *\n * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on\n * Darwin (macOS) systems, {@link PathScurryPosix} on all others.\n */\nexport const PathScurry:\n  | typeof PathScurryWin32\n  | typeof PathScurryDarwin\n  | typeof PathScurryPosix =\n  process.platform === 'win32'\n    ? PathScurryWin32\n    : process.platform === 'darwin'\n    ? PathScurryDarwin\n    : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType\n","const proc =\n  typeof process === 'object' && process\n    ? process\n    : {\n        stdout: null,\n        stderr: null,\n      }\nimport { EventEmitter } from 'events'\nimport Stream from 'stream'\nimport { StringDecoder } from 'string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n  s: any\n): s is Minipass.Readable | Minipass.Writable =>\n  !!s &&\n  typeof s === 'object' &&\n  (s instanceof Minipass ||\n    s instanceof Stream ||\n    isReadable(s) ||\n    isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n  !!s &&\n  typeof s === 'object' &&\n  s instanceof EventEmitter &&\n  typeof (s as Minipass.Readable).pipe === 'function' &&\n  // node core Writable streams have a pipe() method, but it throws\n  (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n  !!s &&\n  typeof s === 'object' &&\n  s instanceof EventEmitter &&\n  typeof (s as Minipass.Writable).write === 'function' &&\n  typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n  ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n  b instanceof ArrayBuffer ||\n  (!!b &&\n    typeof b === 'object' &&\n    b.constructor &&\n    b.constructor.name === 'ArrayBuffer' &&\n    b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n  !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n  /**\n   * end the destination stream when the source stream ends\n   */\n  end?: boolean\n  /**\n   * proxy errors from the source stream to the destination stream\n   */\n  proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe {\n  src: Minipass\n  dest: Minipass\n  opts: PipeOptions\n  ondrain: () => any\n  constructor(\n    src: Minipass,\n    dest: Minipass.Writable,\n    opts: PipeOptions\n  ) {\n    this.src = src\n    this.dest = dest as Minipass\n    this.opts = opts\n    this.ondrain = () => src[RESUME]()\n    this.dest.on('drain', this.ondrain)\n  }\n  unpipe() {\n    this.dest.removeListener('drain', this.ondrain)\n  }\n  // only here for the prototype\n  /* c8 ignore start */\n  proxyErrors(_er: any) {}\n  /* c8 ignore stop */\n  end() {\n    this.unpipe()\n    if (this.opts.end) this.dest.end()\n  }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors extends Pipe {\n  unpipe() {\n    this.src.removeListener('error', this.proxyErrors)\n    super.unpipe()\n  }\n  constructor(\n    src: Minipass,\n    dest: Minipass.Writable,\n    opts: PipeOptions\n  ) {\n    super(src, dest, opts)\n    this.proxyErrors = er => dest.emit('error', er)\n    src.on('error', this.proxyErrors)\n  }\n}\n\nexport namespace Minipass {\n  /**\n   * Encoding used to create a stream that outputs strings rather than\n   * Buffer objects.\n   */\n  export type Encoding = BufferEncoding | 'buffer' | null\n\n  /**\n   * Any stream that Minipass can pipe into\n   */\n  export type Writable =\n    | Minipass\n    | NodeJS.WriteStream\n    | (NodeJS.WriteStream & { fd: number })\n    | (EventEmitter & {\n        end(): any\n        write(chunk: any, ...args: any[]): any\n      })\n\n  /**\n   * Any stream that can be read from\n   */\n  export type Readable =\n    | Minipass\n    | NodeJS.ReadStream\n    | (NodeJS.ReadStream & { fd: number })\n    | (EventEmitter & {\n        pause(): any\n        resume(): any\n        pipe(...destArgs: any[]): any\n      })\n\n  /**\n   * Utility type that can be iterated sync or async\n   */\n  export type DualIterable = Iterable & AsyncIterable\n\n  type EventArguments = Record\n\n  /**\n   * The listing of events that a Minipass class can emit.\n   * Extend this when extending the Minipass class, and pass as\n   * the third template argument.  The key is the name of the event,\n   * and the value is the argument list.\n   *\n   * Any undeclared events will still be allowed, but the handler will get\n   * arguments as `unknown[]`.\n   */\n  export interface Events\n    extends EventArguments {\n    readable: []\n    data: [chunk: RType]\n    error: [er: unknown]\n    abort: [reason: unknown]\n    drain: []\n    resume: []\n    end: []\n    finish: []\n    prefinish: []\n    close: []\n    [DESTROYED]: [er?: unknown]\n    [ERROR]: [er: unknown]\n  }\n\n  /**\n   * String or buffer-like data that can be joined and sliced\n   */\n  export type ContiguousData =\n    | Buffer\n    | ArrayBufferLike\n    | ArrayBufferView\n    | string\n  export type BufferOrString = Buffer | string\n\n  /**\n   * Options passed to the Minipass constructor.\n   */\n  export type SharedOptions = {\n    /**\n     * Defer all data emission and other events until the end of the\n     * current tick, similar to Node core streams\n     */\n    async?: boolean\n    /**\n     * A signal which will abort the stream\n     */\n    signal?: AbortSignal\n    /**\n     * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n     * emit Buffer objects rather than strings.\n     *\n     * Conflicts with `objectMode`\n     */\n    encoding?: BufferEncoding | null | 'buffer'\n    /**\n     * Output data exactly as it was written, supporting non-buffer/string\n     * data (such as arbitrary objects, falsey values, etc.)\n     *\n     * Conflicts with `encoding`\n     */\n    objectMode?: boolean\n  }\n\n  /**\n   * Options for a string encoded output\n   */\n  export type EncodingOptions = SharedOptions & {\n    encoding: BufferEncoding\n    objectMode?: false\n  }\n\n  /**\n   * Options for contiguous data buffer output\n   */\n  export type BufferOptions = SharedOptions & {\n    encoding?: null | 'buffer'\n    objectMode?: false\n  }\n\n  /**\n   * Options for objectMode arbitrary output\n   */\n  export type ObjectModeOptions = SharedOptions & {\n    objectMode: true\n    encoding?: null\n  }\n\n  /**\n   * Utility type to determine allowed options based on read type\n   */\n  export type Options = T extends string\n    ? EncodingOptions | ObjectModeOptions\n    : T extends Buffer\n    ? BufferOptions | ObjectModeOptions\n    : SharedOptions\n}\n\nconst isObjectModeOptions = (\n  o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n  o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n  !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n    RType extends unknown = Buffer,\n    WType extends unknown = RType extends Minipass.BufferOrString\n      ? Minipass.ContiguousData\n      : RType,\n    Events extends Minipass.Events = Minipass.Events\n  >\n  extends EventEmitter\n  implements Minipass.DualIterable\n{\n  [FLOWING]: boolean = false;\n  [PAUSED]: boolean = false;\n  [PIPES]: Pipe[] = [];\n  [BUFFER]: RType[] = [];\n  [OBJECTMODE]: boolean;\n  [ENCODING]: BufferEncoding | null;\n  [ASYNC]: boolean;\n  [DECODER]: SD | null;\n  [EOF]: boolean = false;\n  [EMITTED_END]: boolean = false;\n  [EMITTING_END]: boolean = false;\n  [CLOSED]: boolean = false;\n  [EMITTED_ERROR]: unknown = null;\n  [BUFFERLENGTH]: number = 0;\n  [DESTROYED]: boolean = false;\n  [SIGNAL]?: AbortSignal;\n  [ABORTED]: boolean = false;\n  [DATALISTENERS]: number = 0;\n  [DISCARDED]: boolean = false\n\n  /**\n   * true if the stream can be written\n   */\n  writable: boolean = true\n  /**\n   * true if the stream can be read\n   */\n  readable: boolean = true\n\n  /**\n   * If `RType` is Buffer, then options do not need to be provided.\n   * Otherwise, an options object must be provided to specify either\n   * {@link Minipass.SharedOptions.objectMode} or\n   * {@link Minipass.SharedOptions.encoding}, as appropriate.\n   */\n  constructor(\n    ...args: RType extends Buffer\n      ? [] | [Minipass.Options]\n      : [Minipass.Options]\n  ) {\n    const options: Minipass.Options = (args[0] ||\n      {}) as Minipass.Options\n    super()\n    if (options.objectMode && typeof options.encoding === 'string') {\n      throw new TypeError(\n        'Encoding and objectMode may not be used together'\n      )\n    }\n    if (isObjectModeOptions(options)) {\n      this[OBJECTMODE] = true\n      this[ENCODING] = null\n    } else if (isEncodingOptions(options)) {\n      this[ENCODING] = options.encoding\n      this[OBJECTMODE] = false\n    } else {\n      this[OBJECTMODE] = false\n      this[ENCODING] = null\n    }\n    this[ASYNC] = !!options.async\n    this[DECODER] = this[ENCODING]\n      ? (new StringDecoder(this[ENCODING]) as SD)\n      : null\n\n    //@ts-ignore - private option for debugging and testing\n    if (options && options.debugExposeBuffer === true) {\n      Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n    }\n    //@ts-ignore - private option for debugging and testing\n    if (options && options.debugExposePipes === true) {\n      Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n    }\n\n    const { signal } = options\n    if (signal) {\n      this[SIGNAL] = signal\n      if (signal.aborted) {\n        this[ABORT]()\n      } else {\n        signal.addEventListener('abort', () => this[ABORT]())\n      }\n    }\n  }\n\n  /**\n   * The amount of data stored in the buffer waiting to be read.\n   *\n   * For Buffer strings, this will be the total byte length.\n   * For string encoding streams, this will be the string character length,\n   * according to JavaScript's `string.length` logic.\n   * For objectMode streams, this is a count of the items waiting to be\n   * emitted.\n   */\n  get bufferLength() {\n    return this[BUFFERLENGTH]\n  }\n\n  /**\n   * The `BufferEncoding` currently in use, or `null`\n   */\n  get encoding() {\n    return this[ENCODING]\n  }\n\n  /**\n   * @deprecated - This is a read only property\n   */\n  set encoding(_enc) {\n    throw new Error('Encoding must be set at instantiation time')\n  }\n\n  /**\n   * @deprecated - Encoding may only be set at instantiation time\n   */\n  setEncoding(_enc: Minipass.Encoding) {\n    throw new Error('Encoding must be set at instantiation time')\n  }\n\n  /**\n   * True if this is an objectMode stream\n   */\n  get objectMode() {\n    return this[OBJECTMODE]\n  }\n\n  /**\n   * @deprecated - This is a read-only property\n   */\n  set objectMode(_om) {\n    throw new Error('objectMode must be set at instantiation time')\n  }\n\n  /**\n   * true if this is an async stream\n   */\n  get ['async'](): boolean {\n    return this[ASYNC]\n  }\n  /**\n   * Set to true to make this stream async.\n   *\n   * Once set, it cannot be unset, as this would potentially cause incorrect\n   * behavior.  Ie, a sync stream can be made async, but an async stream\n   * cannot be safely made sync.\n   */\n  set ['async'](a: boolean) {\n    this[ASYNC] = this[ASYNC] || !!a\n  }\n\n  // drop everything and get out of the flow completely\n  [ABORT]() {\n    this[ABORTED] = true\n    this.emit('abort', this[SIGNAL]?.reason)\n    this.destroy(this[SIGNAL]?.reason)\n  }\n\n  /**\n   * True if the stream has been aborted.\n   */\n  get aborted() {\n    return this[ABORTED]\n  }\n  /**\n   * No-op setter. Stream aborted status is set via the AbortSignal provided\n   * in the constructor options.\n   */\n  set aborted(_) {}\n\n  /**\n   * Write data into the stream\n   *\n   * If the chunk written is a string, and encoding is not specified, then\n   * `utf8` will be assumed. If the stream encoding matches the encoding of\n   * a written string, and the state of the string decoder allows it, then\n   * the string will be passed through to either the output or the internal\n   * buffer without any processing. Otherwise, it will be turned into a\n   * Buffer object for processing into the desired encoding.\n   *\n   * If provided, `cb` function is called immediately before return for\n   * sync streams, or on next tick for async streams, because for this\n   * base class, a chunk is considered \"processed\" once it is accepted\n   * and either emitted or buffered. That is, the callback does not indicate\n   * that the chunk has been eventually emitted, though of course child\n   * classes can override this function to do whatever processing is required\n   * and call `super.write(...)` only once processing is completed.\n   */\n  write(chunk: WType, cb?: () => void): boolean\n  write(\n    chunk: WType,\n    encoding?: Minipass.Encoding,\n    cb?: () => void\n  ): boolean\n  write(\n    chunk: WType,\n    encoding?: Minipass.Encoding | (() => void),\n    cb?: () => void\n  ): boolean {\n    if (this[ABORTED]) return false\n    if (this[EOF]) throw new Error('write after end')\n\n    if (this[DESTROYED]) {\n      this.emit(\n        'error',\n        Object.assign(\n          new Error('Cannot call write after a stream was destroyed'),\n          { code: 'ERR_STREAM_DESTROYED' }\n        )\n      )\n      return true\n    }\n\n    if (typeof encoding === 'function') {\n      cb = encoding\n      encoding = 'utf8'\n    }\n\n    if (!encoding) encoding = 'utf8'\n\n    const fn = this[ASYNC] ? defer : nodefer\n\n    // convert array buffers and typed array views into buffers\n    // at some point in the future, we may want to do the opposite!\n    // leave strings and buffers as-is\n    // anything is only allowed if in object mode, so throw\n    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n      if (isArrayBufferView(chunk)) {\n        //@ts-ignore - sinful unsafe type changing\n        chunk = Buffer.from(\n          chunk.buffer,\n          chunk.byteOffset,\n          chunk.byteLength\n        )\n      } else if (isArrayBufferLike(chunk)) {\n        //@ts-ignore - sinful unsafe type changing\n        chunk = Buffer.from(chunk)\n      } else if (typeof chunk !== 'string') {\n        throw new Error(\n          'Non-contiguous data written to non-objectMode stream'\n        )\n      }\n    }\n\n    // handle object mode up front, since it's simpler\n    // this yields better performance, fewer checks later.\n    if (this[OBJECTMODE]) {\n      // maybe impossible?\n      /* c8 ignore start */\n      if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n      /* c8 ignore stop */\n\n      if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n      else this[BUFFERPUSH](chunk as unknown as RType)\n\n      if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n      if (cb) fn(cb)\n\n      return this[FLOWING]\n    }\n\n    // at this point the chunk is a buffer or string\n    // don't buffer it up or send it to the decoder\n    if (!(chunk as Minipass.BufferOrString).length) {\n      if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n      if (cb) fn(cb)\n      return this[FLOWING]\n    }\n\n    // fast-path writing strings of same encoding to a stream with\n    // an empty buffer, skipping the buffer/decoder dance\n    if (\n      typeof chunk === 'string' &&\n      // unless it is a string already ready for us to use\n      !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n    ) {\n      //@ts-ignore - sinful unsafe type change\n      chunk = Buffer.from(chunk, encoding)\n    }\n\n    if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n      //@ts-ignore - sinful unsafe type change\n      chunk = this[DECODER].write(chunk)\n    }\n\n    // Note: flushing CAN potentially switch us into not-flowing mode\n    if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n    if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n    else this[BUFFERPUSH](chunk as unknown as RType)\n\n    if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n    if (cb) fn(cb)\n\n    return this[FLOWING]\n  }\n\n  /**\n   * Low-level explicit read method.\n   *\n   * In objectMode, the argument is ignored, and one item is returned if\n   * available.\n   *\n   * `n` is the number of bytes (or in the case of encoding streams,\n   * characters) to consume. If `n` is not provided, then the entire buffer\n   * is returned, or `null` is returned if no data is available.\n   *\n   * If `n` is greater that the amount of data in the internal buffer,\n   * then `null` is returned.\n   */\n  read(n?: number | null): RType | null {\n    if (this[DESTROYED]) return null\n    this[DISCARDED] = false\n\n    if (\n      this[BUFFERLENGTH] === 0 ||\n      n === 0 ||\n      (n && n > this[BUFFERLENGTH])\n    ) {\n      this[MAYBE_EMIT_END]()\n      return null\n    }\n\n    if (this[OBJECTMODE]) n = null\n\n    if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n      // not object mode, so if we have an encoding, then RType is string\n      // otherwise, must be Buffer\n      this[BUFFER] = [\n        (this[ENCODING]\n          ? this[BUFFER].join('')\n          : Buffer.concat(\n              this[BUFFER] as Buffer[],\n              this[BUFFERLENGTH]\n            )) as RType,\n      ]\n    }\n\n    const ret = this[READ](n || null, this[BUFFER][0] as RType)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [READ](n: number | null, chunk: RType) {\n    if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n    else {\n      const c = chunk as Minipass.BufferOrString\n      if (n === c.length || n === null) this[BUFFERSHIFT]()\n      else if (typeof c === 'string') {\n        this[BUFFER][0] = c.slice(n) as RType\n        chunk = c.slice(0, n) as RType\n        this[BUFFERLENGTH] -= n\n      } else {\n        this[BUFFER][0] = c.subarray(n) as RType\n        chunk = c.subarray(0, n) as RType\n        this[BUFFERLENGTH] -= n\n      }\n    }\n\n    this.emit('data', chunk)\n\n    if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n    return chunk\n  }\n\n  /**\n   * End the stream, optionally providing a final write.\n   *\n   * See {@link Minipass#write} for argument descriptions\n   */\n  end(cb?: () => void): this\n  end(chunk: WType, cb?: () => void): this\n  end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n  end(\n    chunk?: WType | (() => void),\n    encoding?: Minipass.Encoding | (() => void),\n    cb?: () => void\n  ) {\n    if (typeof chunk === 'function') {\n      cb = chunk as () => void\n      chunk = undefined\n    }\n    if (typeof encoding === 'function') {\n      cb = encoding\n      encoding = 'utf8'\n    }\n    if (chunk !== undefined) this.write(chunk, encoding)\n    if (cb) this.once('end', cb)\n    this[EOF] = true\n    this.writable = false\n\n    // if we haven't written anything, then go ahead and emit,\n    // even if we're not reading.\n    // we'll re-emit if a new 'end' listener is added anyway.\n    // This makes MP more suitable to write-only use cases.\n    if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n    return this\n  }\n\n  // don't let the internal resume be overwritten\n  [RESUME]() {\n    if (this[DESTROYED]) return\n\n    if (!this[DATALISTENERS] && !this[PIPES].length) {\n      this[DISCARDED] = true\n    }\n    this[PAUSED] = false\n    this[FLOWING] = true\n    this.emit('resume')\n    if (this[BUFFER].length) this[FLUSH]()\n    else if (this[EOF]) this[MAYBE_EMIT_END]()\n    else this.emit('drain')\n  }\n\n  /**\n   * Resume the stream if it is currently in a paused state\n   *\n   * If called when there are no pipe destinations or `data` event listeners,\n   * this will place the stream in a \"discarded\" state, where all data will\n   * be thrown away. The discarded state is removed if a pipe destination or\n   * data handler is added, if pause() is called, or if any synchronous or\n   * asynchronous iteration is started.\n   */\n  resume() {\n    return this[RESUME]()\n  }\n\n  /**\n   * Pause the stream\n   */\n  pause() {\n    this[FLOWING] = false\n    this[PAUSED] = true\n    this[DISCARDED] = false\n  }\n\n  /**\n   * true if the stream has been forcibly destroyed\n   */\n  get destroyed() {\n    return this[DESTROYED]\n  }\n\n  /**\n   * true if the stream is currently in a flowing state, meaning that\n   * any writes will be immediately emitted.\n   */\n  get flowing() {\n    return this[FLOWING]\n  }\n\n  /**\n   * true if the stream is currently in a paused state\n   */\n  get paused() {\n    return this[PAUSED]\n  }\n\n  [BUFFERPUSH](chunk: RType) {\n    if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n    else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n    this[BUFFER].push(chunk)\n  }\n\n  [BUFFERSHIFT](): RType {\n    if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n    else\n      this[BUFFERLENGTH] -= (\n        this[BUFFER][0] as Minipass.BufferOrString\n      ).length\n    return this[BUFFER].shift() as RType\n  }\n\n  [FLUSH](noDrain: boolean = false) {\n    do {} while (\n      this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n      this[BUFFER].length\n    )\n\n    if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n  }\n\n  [FLUSHCHUNK](chunk: RType) {\n    this.emit('data', chunk)\n    return this[FLOWING]\n  }\n\n  /**\n   * Pipe all data emitted by this stream into the destination provided.\n   *\n   * Triggers the flow of data.\n   */\n  pipe(dest: W, opts?: PipeOptions): W {\n    if (this[DESTROYED]) return dest\n    this[DISCARDED] = false\n\n    const ended = this[EMITTED_END]\n    opts = opts || {}\n    if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n    else opts.end = opts.end !== false\n    opts.proxyErrors = !!opts.proxyErrors\n\n    // piping an ended stream ends immediately\n    if (ended) {\n      if (opts.end) dest.end()\n    } else {\n      // \"as\" here just ignores the WType, which pipes don't care about,\n      // since they're only consuming from us, and writing to the dest\n      this[PIPES].push(\n        !opts.proxyErrors\n          ? new Pipe(this as Minipass, dest, opts)\n          : new PipeProxyErrors(this as Minipass, dest, opts)\n      )\n      if (this[ASYNC]) defer(() => this[RESUME]())\n      else this[RESUME]()\n    }\n\n    return dest\n  }\n\n  /**\n   * Fully unhook a piped destination stream.\n   *\n   * If the destination stream was the only consumer of this stream (ie,\n   * there are no other piped destinations or `'data'` event listeners)\n   * then the flow of data will stop until there is another consumer or\n   * {@link Minipass#resume} is explicitly called.\n   */\n  unpipe(dest: W) {\n    const p = this[PIPES].find(p => p.dest === dest)\n    if (p) {\n      if (this[PIPES].length === 1) {\n        if (this[FLOWING] && this[DATALISTENERS] === 0) {\n          this[FLOWING] = false\n        }\n        this[PIPES] = []\n      } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n      p.unpipe()\n    }\n  }\n\n  /**\n   * Alias for {@link Minipass#on}\n   */\n  addListener(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ): this {\n    return this.on(ev, handler)\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.on`, with the following\n   * behavior differences to prevent data loss and unnecessary hangs:\n   *\n   * - Adding a 'data' event handler will trigger the flow of data\n   *\n   * - Adding a 'readable' event handler when there is data waiting to be read\n   *   will cause 'readable' to be emitted immediately.\n   *\n   * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n   *   already passed will cause the event to be emitted immediately and all\n   *   handlers removed.\n   *\n   * - Adding an 'error' event handler after an error has been emitted will\n   *   cause the event to be re-emitted immediately with the error previously\n   *   raised.\n   */\n  on(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ): this {\n    const ret = super.on(\n      ev as string | symbol,\n      handler as (...a: any[]) => any\n    )\n    if (ev === 'data') {\n      this[DISCARDED] = false\n      this[DATALISTENERS]++\n      if (!this[PIPES].length && !this[FLOWING]) {\n        this[RESUME]()\n      }\n    } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n      super.emit('readable')\n    } else if (isEndish(ev) && this[EMITTED_END]) {\n      super.emit(ev)\n      this.removeAllListeners(ev)\n    } else if (ev === 'error' && this[EMITTED_ERROR]) {\n      const h = handler as (...a: Events['error']) => any\n      if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n      else h.call(this, this[EMITTED_ERROR])\n    }\n    return ret\n  }\n\n  /**\n   * Alias for {@link Minipass#off}\n   */\n  removeListener(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ) {\n    return this.off(ev, handler)\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.off`\n   *\n   * If a 'data' event handler is removed, and it was the last consumer\n   * (ie, there are no pipe destinations or other 'data' event listeners),\n   * then the flow of data will stop until there is another consumer or\n   * {@link Minipass#resume} is explicitly called.\n   */\n  off(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ) {\n    const ret = super.off(\n      ev as string | symbol,\n      handler as (...a: any[]) => any\n    )\n    // if we previously had listeners, and now we don't, and we don't\n    // have any pipes, then stop the flow, unless it's been explicitly\n    // put in a discarded flowing state via stream.resume().\n    if (ev === 'data') {\n      this[DATALISTENERS] = this.listeners('data').length\n      if (\n        this[DATALISTENERS] === 0 &&\n        !this[DISCARDED] &&\n        !this[PIPES].length\n      ) {\n        this[FLOWING] = false\n      }\n    }\n    return ret\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.removeAllListeners`\n   *\n   * If all 'data' event handlers are removed, and they were the last consumer\n   * (ie, there are no pipe destinations), then the flow of data will stop\n   * until there is another consumer or {@link Minipass#resume} is explicitly\n   * called.\n   */\n  removeAllListeners(ev?: Event) {\n    const ret = super.removeAllListeners(ev as string | symbol | undefined)\n    if (ev === 'data' || ev === undefined) {\n      this[DATALISTENERS] = 0\n      if (!this[DISCARDED] && !this[PIPES].length) {\n        this[FLOWING] = false\n      }\n    }\n    return ret\n  }\n\n  /**\n   * true if the 'end' event has been emitted\n   */\n  get emittedEnd() {\n    return this[EMITTED_END]\n  }\n\n  [MAYBE_EMIT_END]() {\n    if (\n      !this[EMITTING_END] &&\n      !this[EMITTED_END] &&\n      !this[DESTROYED] &&\n      this[BUFFER].length === 0 &&\n      this[EOF]\n    ) {\n      this[EMITTING_END] = true\n      this.emit('end')\n      this.emit('prefinish')\n      this.emit('finish')\n      if (this[CLOSED]) this.emit('close')\n      this[EMITTING_END] = false\n    }\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.emit`, with the following\n   * behavior differences to prevent data loss and unnecessary hangs:\n   *\n   * If the stream has been destroyed, and the event is something other\n   * than 'close' or 'error', then `false` is returned and no handlers\n   * are called.\n   *\n   * If the event is 'end', and has already been emitted, then the event\n   * is ignored. If the stream is in a paused or non-flowing state, then\n   * the event will be deferred until data flow resumes. If the stream is\n   * async, then handlers will be called on the next tick rather than\n   * immediately.\n   *\n   * If the event is 'close', and 'end' has not yet been emitted, then\n   * the event will be deferred until after 'end' is emitted.\n   *\n   * If the event is 'error', and an AbortSignal was provided for the stream,\n   * and there are no listeners, then the event is ignored, matching the\n   * behavior of node core streams in the presense of an AbortSignal.\n   *\n   * If the event is 'finish' or 'prefinish', then all listeners will be\n   * removed after emitting the event, to prevent double-firing.\n   */\n  emit(\n    ev: Event,\n    ...args: Events[Event]\n  ): boolean {\n    const data = args[0]\n    // error and close are only events allowed after calling destroy()\n    if (\n      ev !== 'error' &&\n      ev !== 'close' &&\n      ev !== DESTROYED &&\n      this[DESTROYED]\n    ) {\n      return false\n    } else if (ev === 'data') {\n      return !this[OBJECTMODE] && !data\n        ? false\n        : this[ASYNC]\n        ? (defer(() => this[EMITDATA](data as RType)), true)\n        : this[EMITDATA](data as RType)\n    } else if (ev === 'end') {\n      return this[EMITEND]()\n    } else if (ev === 'close') {\n      this[CLOSED] = true\n      // don't emit close before 'end' and 'finish'\n      if (!this[EMITTED_END] && !this[DESTROYED]) return false\n      const ret = super.emit('close')\n      this.removeAllListeners('close')\n      return ret\n    } else if (ev === 'error') {\n      this[EMITTED_ERROR] = data\n      super.emit(ERROR, data)\n      const ret =\n        !this[SIGNAL] || this.listeners('error').length\n          ? super.emit('error', data)\n          : false\n      this[MAYBE_EMIT_END]()\n      return ret\n    } else if (ev === 'resume') {\n      const ret = super.emit('resume')\n      this[MAYBE_EMIT_END]()\n      return ret\n    } else if (ev === 'finish' || ev === 'prefinish') {\n      const ret = super.emit(ev)\n      this.removeAllListeners(ev)\n      return ret\n    }\n\n    // Some other unknown event\n    const ret = super.emit(ev as string, ...args)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [EMITDATA](data: RType) {\n    for (const p of this[PIPES]) {\n      if (p.dest.write(data) === false) this.pause()\n    }\n    const ret = this[DISCARDED] ? false : super.emit('data', data)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [EMITEND]() {\n    if (this[EMITTED_END]) return false\n\n    this[EMITTED_END] = true\n    this.readable = false\n    return this[ASYNC]\n      ? (defer(() => this[EMITEND2]()), true)\n      : this[EMITEND2]()\n  }\n\n  [EMITEND2]() {\n    if (this[DECODER]) {\n      const data = this[DECODER].end()\n      if (data) {\n        for (const p of this[PIPES]) {\n          p.dest.write(data as RType)\n        }\n        if (!this[DISCARDED]) super.emit('data', data)\n      }\n    }\n\n    for (const p of this[PIPES]) {\n      p.end()\n    }\n    const ret = super.emit('end')\n    this.removeAllListeners('end')\n    return ret\n  }\n\n  /**\n   * Return a Promise that resolves to an array of all emitted data once\n   * the stream ends.\n   */\n  async collect(): Promise {\n    const buf: RType[] & { dataLength: number } = Object.assign([], {\n      dataLength: 0,\n    })\n    if (!this[OBJECTMODE]) buf.dataLength = 0\n    // set the promise first, in case an error is raised\n    // by triggering the flow here.\n    const p = this.promise()\n    this.on('data', c => {\n      buf.push(c)\n      if (!this[OBJECTMODE])\n        buf.dataLength += (c as Minipass.BufferOrString).length\n    })\n    await p\n    return buf\n  }\n\n  /**\n   * Return a Promise that resolves to the concatenation of all emitted data\n   * once the stream ends.\n   *\n   * Not allowed on objectMode streams.\n   */\n  async concat(): Promise {\n    if (this[OBJECTMODE]) {\n      throw new Error('cannot concat in objectMode')\n    }\n    const buf = await this.collect()\n    return (\n      this[ENCODING]\n        ? buf.join('')\n        : Buffer.concat(buf as Buffer[], buf.dataLength)\n    ) as RType\n  }\n\n  /**\n   * Return a void Promise that resolves once the stream ends.\n   */\n  async promise(): Promise {\n    return new Promise((resolve, reject) => {\n      this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n      this.on('error', er => reject(er))\n      this.on('end', () => resolve())\n    })\n  }\n\n  /**\n   * Asynchronous `for await of` iteration.\n   *\n   * This will continue emitting all chunks until the stream terminates.\n   */\n  [Symbol.asyncIterator](): AsyncGenerator {\n    // set this up front, in case the consumer doesn't call next()\n    // right away.\n    this[DISCARDED] = false\n    let stopped = false\n    const stop = async (): Promise> => {\n      this.pause()\n      stopped = true\n      return { value: undefined, done: true }\n    }\n    const next = (): Promise> => {\n      if (stopped) return stop()\n      const res = this.read()\n      if (res !== null) return Promise.resolve({ done: false, value: res })\n\n      if (this[EOF]) return stop()\n\n      let resolve!: (res: IteratorResult) => void\n      let reject!: (er: unknown) => void\n      const onerr = (er: unknown) => {\n        this.off('data', ondata)\n        this.off('end', onend)\n        this.off(DESTROYED, ondestroy)\n        stop()\n        reject(er)\n      }\n      const ondata = (value: RType) => {\n        this.off('error', onerr)\n        this.off('end', onend)\n        this.off(DESTROYED, ondestroy)\n        this.pause()\n        resolve({ value, done: !!this[EOF] })\n      }\n      const onend = () => {\n        this.off('error', onerr)\n        this.off('data', ondata)\n        this.off(DESTROYED, ondestroy)\n        stop()\n        resolve({ done: true, value: undefined })\n      }\n      const ondestroy = () => onerr(new Error('stream destroyed'))\n      return new Promise>((res, rej) => {\n        reject = rej\n        resolve = res\n        this.once(DESTROYED, ondestroy)\n        this.once('error', onerr)\n        this.once('end', onend)\n        this.once('data', ondata)\n      })\n    }\n\n    return {\n      next,\n      throw: stop,\n      return: stop,\n      [Symbol.asyncIterator]() {\n        return this\n      },\n    }\n  }\n\n  /**\n   * Synchronous `for of` iteration.\n   *\n   * The iteration will terminate when the internal buffer runs out, even\n   * if the stream has not yet terminated.\n   */\n  [Symbol.iterator](): Generator {\n    // set this up front, in case the consumer doesn't call next()\n    // right away.\n    this[DISCARDED] = false\n    let stopped = false\n    const stop = (): IteratorReturnResult => {\n      this.pause()\n      this.off(ERROR, stop)\n      this.off(DESTROYED, stop)\n      this.off('end', stop)\n      stopped = true\n      return { done: true, value: undefined }\n    }\n\n    const next = (): IteratorResult => {\n      if (stopped) return stop()\n      const value = this.read()\n      return value === null ? stop() : { done: false, value }\n    }\n\n    this.once('end', stop)\n    this.once(ERROR, stop)\n    this.once(DESTROYED, stop)\n\n    return {\n      next,\n      throw: stop,\n      return: stop,\n      [Symbol.iterator]() {\n        return this\n      },\n    }\n  }\n\n  /**\n   * Destroy a stream, preventing it from being used for any further purpose.\n   *\n   * If the stream has a `close()` method, then it will be called on\n   * destruction.\n   *\n   * After destruction, any attempt to write data, read data, or emit most\n   * events will be ignored.\n   *\n   * If an error argument is provided, then it will be emitted in an\n   * 'error' event.\n   */\n  destroy(er?: unknown) {\n    if (this[DESTROYED]) {\n      if (er) this.emit('error', er)\n      else this.emit(DESTROYED)\n      return this\n    }\n\n    this[DESTROYED] = true\n    this[DISCARDED] = true\n\n    // throw away all buffered data, it's never coming out\n    this[BUFFER].length = 0\n    this[BUFFERLENGTH] = 0\n\n    const wc = this as Minipass & {\n      close?: () => void\n    }\n    if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n    if (er) this.emit('error', er)\n    // if no error to emit, still reject pending promises\n    else this.emit(DESTROYED)\n\n    return this\n  }\n\n  /**\n   * Alias for {@link isStream}\n   *\n   * Former export location, maintained for backwards compatibility.\n   *\n   * @deprecated\n   */\n  static get isStream() {\n    return isStream\n  }\n}\n","import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport {\n  FSOption,\n  Path,\n  PathScurry,\n  PathScurryDarwin,\n  PathScurryPosix,\n  PathScurryWin32,\n} from 'path-scurry'\nimport { fileURLToPath } from 'url'\nimport { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n  typeof process === 'object' &&\n  process &&\n  typeof process.platform === 'string'\n    ? process.platform\n    : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n  /**\n   * Set to `true` to always receive absolute paths for\n   * matched files. Set to `false` to always return relative paths.\n   *\n   * When this option is not set, absolute paths are returned for patterns\n   * that are absolute, and otherwise paths are returned that are relative\n   * to the `cwd` setting.\n   *\n   * This does _not_ make an extra system call to get\n   * the realpath, it only does string path resolution.\n   *\n   * Conflicts with {@link withFileTypes}\n   */\n  absolute?: boolean\n\n  /**\n   * Set to false to enable {@link windowsPathsNoEscape}\n   *\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n\n  /**\n   * The current working directory in which to search. Defaults to\n   * `process.cwd()`.\n   *\n   * May be eiher a string path or a `file://` URL object or string.\n   */\n  cwd?: string | URL\n\n  /**\n   * Include `.dot` files in normal matches and `globstar`\n   * matches. Note that an explicit dot in a portion of the pattern\n   * will always match dot files.\n   */\n  dot?: boolean\n\n  /**\n   * Prepend all relative path strings with `./` (or `.\\` on Windows).\n   *\n   * Without this option, returned relative paths are \"bare\", so instead of\n   * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n   *\n   * Relative patterns starting with `'../'` are not prepended with `./`, even\n   * if this option is set.\n   */\n  dotRelative?: boolean\n\n  /**\n   * Follow symlinked directories when expanding `**`\n   * patterns. This can result in a lot of duplicate references in\n   * the presence of cyclic links, and make performance quite bad.\n   *\n   * By default, a `**` in a pattern will follow 1 symbolic link if\n   * it is not the first item in the pattern, or none if it is the\n   * first item in the pattern, following the same behavior as Bash.\n   */\n  follow?: boolean\n\n  /**\n   * string or string[], or an object with `ignore` and `ignoreChildren`\n   * methods.\n   *\n   * If a string or string[] is provided, then this is treated as a glob\n   * pattern or array of glob patterns to exclude from matches. To ignore all\n   * children within a directory, as well as the entry itself, append `'/**'`\n   * to the ignore pattern.\n   *\n   * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n   * any other settings.\n   *\n   * If an object is provided that has `ignored(path)` and/or\n   * `childrenIgnored(path)` methods, then these methods will be called to\n   * determine whether any Path is a match or if its children should be\n   * traversed, respectively.\n   */\n  ignore?: string | string[] | IgnoreLike\n\n  /**\n   * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n   * effect if {@link nobrace} is set.\n   *\n   * Only has effect on the {@link hasMagic} function.\n   */\n  magicalBraces?: boolean\n\n  /**\n   * Add a `/` character to directory matches. Note that this requires\n   * additional stat calls in some cases.\n   */\n  mark?: boolean\n\n  /**\n   * Perform a basename-only match if the pattern does not contain any slash\n   * characters. That is, `*.js` would be treated as equivalent to\n   * `**\\/*.js`, matching all js files in all directories.\n   */\n  matchBase?: boolean\n\n  /**\n   * Limit the directory traversal to a given depth below the cwd.\n   * Note that this does NOT prevent traversal to sibling folders,\n   * root patterns, and so on. It only limits the maximum folder depth\n   * that the walk will descend, relative to the cwd.\n   */\n  maxDepth?: number\n\n  /**\n   * Do not expand `{a,b}` and `{1..3}` brace sets.\n   */\n  nobrace?: boolean\n\n  /**\n   * Perform a case-insensitive match. This defaults to `true` on macOS and\n   * Windows systems, and `false` on all others.\n   *\n   * **Note** `nocase` should only be explicitly set when it is\n   * known that the filesystem's case sensitivity differs from the\n   * platform default. If set `true` on case-sensitive file\n   * systems, or `false` on case-insensitive file systems, then the\n   * walk may return more or less results than expected.\n   */\n  nocase?: boolean\n\n  /**\n   * Do not match directories, only files. (Note: to match\n   * _only_ directories, put a `/` at the end of the pattern.)\n   */\n  nodir?: boolean\n\n  /**\n   * Do not match \"extglob\" patterns such as `+(a|b)`.\n   */\n  noext?: boolean\n\n  /**\n   * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n   * `*` instead.)\n   *\n   * Conflicts with {@link matchBase}\n   */\n  noglobstar?: boolean\n\n  /**\n   * Defaults to value of `process.platform` if available, or `'linux'` if\n   * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n   * behavior.\n   */\n  platform?: NodeJS.Platform\n\n  /**\n   * Set to true to call `fs.realpath` on all of the\n   * results. In the case of an entry that cannot be resolved, the\n   * entry is omitted. This incurs a slight performance penalty, of\n   * course, because of the added system calls.\n   */\n  realpath?: boolean\n\n  /**\n   *\n   * A string path resolved against the `cwd` option, which\n   * is used as the starting point for absolute patterns that start\n   * with `/`, (but not drive letters or UNC paths on Windows).\n   *\n   * Note that this _doesn't_ necessarily limit the walk to the\n   * `root` directory, and doesn't affect the cwd starting point for\n   * non-absolute patterns. A pattern containing `..` will still be\n   * able to traverse out of the root directory, if it is not an\n   * actual root directory on the filesystem, and any non-absolute\n   * patterns will be matched in the `cwd`. For example, the\n   * pattern `/../*` with `{root:'/some/path'}` will return all\n   * files in `/some`, not all files in `/some/path`. The pattern\n   * `*` with `{root:'/some/path'}` will return all the entries in\n   * the cwd, not the entries in `/some/path`.\n   *\n   * To start absolute and non-absolute patterns in the same\n   * path, you can use `{root:''}`. However, be aware that on\n   * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n   * _always_ start in the `x:/` or `//host/share` directory,\n   * regardless of the `root` setting.\n   */\n  root?: string\n\n  /**\n   * A [PathScurry](http://npm.im/path-scurry) object used\n   * to traverse the file system. If the `nocase` option is set\n   * explicitly, then any provided `scurry` object must match this\n   * setting.\n   */\n  scurry?: PathScurry\n\n  /**\n   * Call `lstat()` on all entries, whether required or not to determine\n   * if it's a valid match. When used with {@link withFileTypes}, this means\n   * that matches will include data such as modified time, permissions, and\n   * so on.  Note that this will incur a performance cost due to the added\n   * system calls.\n   */\n  stat?: boolean\n\n  /**\n   * An AbortSignal which will cancel the Glob walk when\n   * triggered.\n   */\n  signal?: AbortSignal\n\n  /**\n   * Use `\\\\` as a path separator _only_, and\n   *  _never_ as an escape character. If set, all `\\\\` characters are\n   *  replaced with `/` in the pattern.\n   *\n   *  Note that this makes it **impossible** to match against paths\n   *  containing literal glob pattern characters, but allows matching\n   *  with patterns constructed using `path.join()` and\n   *  `path.resolve()` on Windows platforms, mimicking the (buggy!)\n   *  behavior of Glob v7 and before on Windows. Please use with\n   *  caution, and be mindful of [the caveat below about Windows\n   *  paths](#windows). (For legacy reasons, this is also set if\n   *  `allowWindowsEscape` is set to the exact value `false`.)\n   */\n  windowsPathsNoEscape?: boolean\n\n  /**\n   * Return [PathScurry](http://npm.im/path-scurry)\n   * `Path` objects instead of strings. These are similar to a\n   * NodeJS `Dirent` object, but with additional methods and\n   * properties.\n   *\n   * Conflicts with {@link absolute}\n   */\n  withFileTypes?: boolean\n\n  /**\n   * An fs implementation to override some or all of the defaults.  See\n   * http://npm.im/path-scurry for details about what can be overridden.\n   */\n  fs?: FSOption\n\n  /**\n   * Just passed along to Minimatch.  Note that this makes all pattern\n   * matching operations slower and *extremely* noisy.\n   */\n  debug?: boolean\n\n  /**\n   * Return `/` delimited paths, even on Windows.\n   *\n   * On posix systems, this has no effect.  But, on Windows, it means that\n   * paths will be `/` delimited, and absolute paths will be their full\n   * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n   * `'//?/C:/foo/bar'`\n   */\n  posix?: boolean\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n  withFileTypes: true\n  // string options not relevant if returning Path objects.\n  absolute?: undefined\n  mark?: undefined\n  posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n  withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n  withFileTypes?: undefined\n}\n\nexport type Result = Opts extends GlobOptionsWithFileTypesTrue\n  ? Path\n  : Opts extends GlobOptionsWithFileTypesFalse\n  ? string\n  : Opts extends GlobOptionsWithFileTypesUnset\n  ? string\n  : string | Path\nexport type Results = Result[]\n\nexport type FileTypes = Opts extends GlobOptionsWithFileTypesTrue\n  ? true\n  : Opts extends GlobOptionsWithFileTypesFalse\n  ? false\n  : Opts extends GlobOptionsWithFileTypesUnset\n  ? false\n  : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob implements GlobOptions {\n  absolute?: boolean\n  cwd: string\n  root?: string\n  dot: boolean\n  dotRelative: boolean\n  follow: boolean\n  ignore?: string | string[] | IgnoreLike\n  magicalBraces: boolean\n  mark?: boolean\n  matchBase: boolean\n  maxDepth: number\n  nobrace: boolean\n  nocase: boolean\n  nodir: boolean\n  noext: boolean\n  noglobstar: boolean\n  pattern: string[]\n  platform: NodeJS.Platform\n  realpath: boolean\n  scurry: PathScurry\n  stat: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape: boolean\n  withFileTypes: FileTypes\n\n  /**\n   * The options provided to the constructor.\n   */\n  opts: Opts\n\n  /**\n   * An array of parsed immutable {@link Pattern} objects.\n   */\n  patterns: Pattern[]\n\n  /**\n   * All options are stored as properties on the `Glob` object.\n   *\n   * See {@link GlobOptions} for full options descriptions.\n   *\n   * Note that a previous `Glob` object can be passed as the\n   * `GlobOptions` to another `Glob` instantiation to re-use settings\n   * and caches with a new pattern.\n   *\n   * Traversal functions can be called multiple times to run the walk\n   * again.\n   */\n  constructor(pattern: string | string[], opts: Opts) {\n    /* c8 ignore start */\n    if (!opts) throw new TypeError('glob options required')\n    /* c8 ignore stop */\n    this.withFileTypes = !!opts.withFileTypes as FileTypes\n    this.signal = opts.signal\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.dotRelative = !!opts.dotRelative\n    this.nodir = !!opts.nodir\n    this.mark = !!opts.mark\n    if (!opts.cwd) {\n      this.cwd = ''\n    } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n      opts.cwd = fileURLToPath(opts.cwd)\n    }\n    this.cwd = opts.cwd || ''\n    this.root = opts.root\n    this.magicalBraces = !!opts.magicalBraces\n    this.nobrace = !!opts.nobrace\n    this.noext = !!opts.noext\n    this.realpath = !!opts.realpath\n    this.absolute = opts.absolute\n\n    this.noglobstar = !!opts.noglobstar\n    this.matchBase = !!opts.matchBase\n    this.maxDepth =\n      typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n    this.stat = !!opts.stat\n    this.ignore = opts.ignore\n\n    if (this.withFileTypes && this.absolute !== undefined) {\n      throw new Error('cannot set absolute and withFileTypes:true')\n    }\n\n    if (typeof pattern === 'string') {\n      pattern = [pattern]\n    }\n\n    this.windowsPathsNoEscape =\n      !!opts.windowsPathsNoEscape ||\n      (opts as GlobOptions).allowWindowsEscape === false\n\n    if (this.windowsPathsNoEscape) {\n      pattern = pattern.map(p => p.replace(/\\\\/g, '/'))\n    }\n\n    if (this.matchBase) {\n      if (opts.noglobstar) {\n        throw new TypeError('base matching requires globstar')\n      }\n      pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`))\n    }\n\n    this.pattern = pattern\n\n    this.platform = opts.platform || defaultPlatform\n    this.opts = { ...opts, platform: this.platform }\n    if (opts.scurry) {\n      this.scurry = opts.scurry\n      if (\n        opts.nocase !== undefined &&\n        opts.nocase !== opts.scurry.nocase\n      ) {\n        throw new Error('nocase option contradicts provided scurry option')\n      }\n    } else {\n      const Scurry =\n        opts.platform === 'win32'\n          ? PathScurryWin32\n          : opts.platform === 'darwin'\n          ? PathScurryDarwin\n          : opts.platform\n          ? PathScurryPosix\n          : PathScurry\n      this.scurry = new Scurry(this.cwd, {\n        nocase: opts.nocase,\n        fs: opts.fs,\n      })\n    }\n    this.nocase = this.scurry.nocase\n\n    // If you do nocase:true on a case-sensitive file system, then\n    // we need to use regexps instead of strings for non-magic\n    // path portions, because statting `aBc` won't return results\n    // for the file `AbC` for example.\n    const nocaseMagicOnly =\n      this.platform === 'darwin' || this.platform === 'win32'\n\n    const mmo: MinimatchOptions = {\n      // default nocase based on platform\n      ...opts,\n      dot: this.dot,\n      matchBase: this.matchBase,\n      nobrace: this.nobrace,\n      nocase: this.nocase,\n      nocaseMagicOnly,\n      nocomment: true,\n      noext: this.noext,\n      nonegate: true,\n      optimizationLevel: 2,\n      platform: this.platform,\n      windowsPathsNoEscape: this.windowsPathsNoEscape,\n      debug: !!this.opts.debug,\n    }\n\n    const mms = this.pattern.map(p => new Minimatch(p, mmo))\n    const [matchSet, globParts] = mms.reduce(\n      (set: [MatchSet, GlobParts], m) => {\n        set[0].push(...m.set)\n        set[1].push(...m.globParts)\n        return set\n      },\n      [[], []]\n    )\n    this.patterns = matchSet.map((set, i) => {\n      const g = globParts[i]\n      /* c8 ignore start */\n      if (!g) throw new Error('invalid pattern object')\n      /* c8 ignore stop */\n      return new Pattern(set, g, 0, this.platform)\n    })\n  }\n\n  /**\n   * Returns a Promise that resolves to the results array.\n   */\n  async walk(): Promise>\n  async walk(): Promise<(string | Path)[]> {\n    // Walkers always return array of Path objects, so we just have to\n    // coerce them into the right shape.  It will have already called\n    // realpath() if the option was set to do so, so we know that's cached.\n    // start out knowing the cwd, at least\n    return [\n      ...(await new GlobWalker(this.patterns, this.scurry.cwd, {\n        ...this.opts,\n        maxDepth:\n          this.maxDepth !== Infinity\n            ? this.maxDepth + this.scurry.cwd.depth()\n            : Infinity,\n        platform: this.platform,\n        nocase: this.nocase,\n      }).walk()),\n    ]\n  }\n\n  /**\n   * synchronous {@link Glob.walk}\n   */\n  walkSync(): Results\n  walkSync(): (string | Path)[] {\n    return [\n      ...new GlobWalker(this.patterns, this.scurry.cwd, {\n        ...this.opts,\n        maxDepth:\n          this.maxDepth !== Infinity\n            ? this.maxDepth + this.scurry.cwd.depth()\n            : Infinity,\n        platform: this.platform,\n        nocase: this.nocase,\n      }).walkSync(),\n    ]\n  }\n\n  /**\n   * Stream results asynchronously.\n   */\n  stream(): Minipass, Result>\n  stream(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity\n          ? this.maxDepth + this.scurry.cwd.depth()\n          : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n    }).stream()\n  }\n\n  /**\n   * Stream results synchronously.\n   */\n  streamSync(): Minipass, Result>\n  streamSync(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity\n          ? this.maxDepth + this.scurry.cwd.depth()\n          : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n    }).streamSync()\n  }\n\n  /**\n   * Default sync iteration function. Returns a Generator that\n   * iterates over the results.\n   */\n  iterateSync(): Generator, void, void> {\n    return this.streamSync()[Symbol.iterator]()\n  }\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  /**\n   * Default async iteration function. Returns an AsyncGenerator that\n   * iterates over the results.\n   */\n  iterate(): AsyncGenerator, void, void> {\n    return this.stream()[Symbol.asyncIterator]()\n  }\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n}\n","// this is just a very light wrapper around 2 arrays with an offset index\n\nimport { GLOBSTAR } from 'minimatch'\nexport type MMPattern = string | RegExp | typeof GLOBSTAR\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n  p0: '',\n  p1: '',\n  p2: string,\n  p3: string,\n  ...rest: MMPattern[]\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n  pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n  readonly #patternList: PatternList\n  readonly #globList: GlobList\n  readonly #index: number\n  readonly length: number\n  readonly #platform: NodeJS.Platform\n  #rest?: Pattern | null\n  #globString?: string\n  #isDrive?: boolean\n  #isUNC?: boolean\n  #isAbsolute?: boolean\n  #followGlobstar: boolean = true\n\n  constructor(\n    patternList: MMPattern[],\n    globList: string[],\n    index: number,\n    platform: NodeJS.Platform\n  ) {\n    if (!isPatternList(patternList)) {\n      throw new TypeError('empty pattern list')\n    }\n    if (!isGlobList(globList)) {\n      throw new TypeError('empty glob list')\n    }\n    if (globList.length !== patternList.length) {\n      throw new TypeError('mismatched pattern list and glob list lengths')\n    }\n    this.length = patternList.length\n    if (index < 0 || index >= this.length) {\n      throw new TypeError('index out of range')\n    }\n    this.#patternList = patternList\n    this.#globList = globList\n    this.#index = index\n    this.#platform = platform\n\n    // normalize root entries of absolute patterns on initial creation.\n    if (this.#index === 0) {\n      // c: => ['c:/']\n      // C:/ => ['C:/']\n      // C:/x => ['C:/', 'x']\n      // //host/share => ['//host/share/']\n      // //host/share/ => ['//host/share/']\n      // //host/share/x => ['//host/share/', 'x']\n      // /etc => ['/', 'etc']\n      // / => ['/']\n      if (this.isUNC()) {\n        // '' / '' / 'host' / 'share'\n        const [p0, p1, p2, p3, ...prest] = this.#patternList\n        const [g0, g1, g2, g3, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = [p0, p1, p2, p3, ''].join('/')\n        const g = [g0, g1, g2, g3, ''].join('/')\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      } else if (this.isDrive() || this.isAbsolute()) {\n        const [p1, ...prest] = this.#patternList\n        const [g1, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = (p1 as string) + '/'\n        const g = g1 + '/'\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      }\n    }\n  }\n\n  /**\n   * The first entry in the parsed list of patterns\n   */\n  pattern(): MMPattern {\n    return this.#patternList[this.#index] as MMPattern\n  }\n\n  /**\n   * true of if pattern() returns a string\n   */\n  isString(): boolean {\n    return typeof this.#patternList[this.#index] === 'string'\n  }\n  /**\n   * true of if pattern() returns GLOBSTAR\n   */\n  isGlobstar(): boolean {\n    return this.#patternList[this.#index] === GLOBSTAR\n  }\n  /**\n   * true if pattern() returns a regexp\n   */\n  isRegExp(): boolean {\n    return this.#patternList[this.#index] instanceof RegExp\n  }\n\n  /**\n   * The /-joined set of glob parts that make up this pattern\n   */\n  globString(): string {\n    return (this.#globString =\n      this.#globString ||\n      (this.#index === 0\n        ? this.isAbsolute()\n          ? this.#globList[0] + this.#globList.slice(1).join('/')\n          : this.#globList.join('/')\n        : this.#globList.slice(this.#index).join('/')))\n  }\n\n  /**\n   * true if there are more pattern parts after this one\n   */\n  hasMore(): boolean {\n    return this.length > this.#index + 1\n  }\n\n  /**\n   * The rest of the pattern after this part, or null if this is the end\n   */\n  rest(): Pattern | null {\n    if (this.#rest !== undefined) return this.#rest\n    if (!this.hasMore()) return (this.#rest = null)\n    this.#rest = new Pattern(\n      this.#patternList,\n      this.#globList,\n      this.#index + 1,\n      this.#platform\n    )\n    this.#rest.#isAbsolute = this.#isAbsolute\n    this.#rest.#isUNC = this.#isUNC\n    this.#rest.#isDrive = this.#isDrive\n    return this.#rest\n  }\n\n  /**\n   * true if the pattern represents a //unc/path/ on windows\n   */\n  isUNC(): boolean {\n    const pl = this.#patternList\n    return this.#isUNC !== undefined\n      ? this.#isUNC\n      : (this.#isUNC =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          pl[0] === '' &&\n          pl[1] === '' &&\n          typeof pl[2] === 'string' &&\n          !!pl[2] &&\n          typeof pl[3] === 'string' &&\n          !!pl[3])\n  }\n\n  // pattern like C:/...\n  // split = ['C:', ...]\n  // XXX: would be nice to handle patterns like `c:*` to test the cwd\n  // in c: for *, but I don't know of a way to even figure out what that\n  // cwd is without actually chdir'ing into it?\n  /**\n   * True if the pattern starts with a drive letter on Windows\n   */\n  isDrive(): boolean {\n    const pl = this.#patternList\n    return this.#isDrive !== undefined\n      ? this.#isDrive\n      : (this.#isDrive =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          this.length > 1 &&\n          typeof pl[0] === 'string' &&\n          /^[a-z]:$/i.test(pl[0]))\n  }\n\n  // pattern = '/' or '/...' or '/x/...'\n  // split = ['', ''] or ['', ...] or ['', 'x', ...]\n  // Drive and UNC both considered absolute on windows\n  /**\n   * True if the pattern is rooted on an absolute path\n   */\n  isAbsolute(): boolean {\n    const pl = this.#patternList\n    return this.#isAbsolute !== undefined\n      ? this.#isAbsolute\n      : (this.#isAbsolute =\n          (pl[0] === '' && pl.length > 1) ||\n          this.isDrive() ||\n          this.isUNC())\n  }\n\n  /**\n   * consume the root of the pattern, and return it\n   */\n  root(): string {\n    const p = this.#patternList[0]\n    return typeof p === 'string' && this.isAbsolute() && this.#index === 0\n      ? p\n      : ''\n  }\n\n  /**\n   * Check to see if the current globstar pattern is allowed to follow\n   * a symbolic link.\n   */\n  checkFollowGlobstar(): boolean {\n    return !(\n      this.#index === 0 ||\n      !this.isGlobstar() ||\n      !this.#followGlobstar\n    )\n  }\n\n  /**\n   * Mark that the current globstar pattern is following a symbolic link\n   */\n  markFollowGlobstar(): boolean {\n    if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n      return false\n    this.#followGlobstar = false\n    return true\n  }\n}\n","// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport { Minimatch } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n  ignored?: (p: Path) => boolean\n  childrenIgnored?: (p: Path) => boolean\n}\n\nconst defaultPlatform: NodeJS.Platform =\n  typeof process === 'object' &&\n  process &&\n  typeof process.platform === 'string'\n    ? process.platform\n    : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n  relative: Minimatch[]\n  relativeChildren: Minimatch[]\n  absolute: Minimatch[]\n  absoluteChildren: Minimatch[]\n\n  constructor(\n    ignored: string[],\n    {\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      platform = defaultPlatform,\n    }: GlobWalkerOpts\n  ) {\n    this.relative = []\n    this.absolute = []\n    this.relativeChildren = []\n    this.absoluteChildren = []\n    const mmopts = {\n      dot: true,\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      optimizationLevel: 2,\n      platform,\n      nocomment: true,\n      nonegate: true,\n    }\n\n    // this is a little weird, but it gives us a clean set of optimized\n    // minimatch matchers, without getting tripped up if one of them\n    // ends in /** inside a brace section, and it's only inefficient at\n    // the start of the walk, not along it.\n    // It'd be nice if the Pattern class just had a .test() method, but\n    // handling globstars is a bit of a pita, and that code already lives\n    // in minimatch anyway.\n    // Another way would be if maybe Minimatch could take its set/globParts\n    // as an option, and then we could at least just use Pattern to test\n    // for absolute-ness.\n    // Yet another way, Minimatch could take an array of glob strings, and\n    // a cwd option, and do the right thing.\n    for (const ign of ignored) {\n      const mm = new Minimatch(ign, mmopts)\n      for (let i = 0; i < mm.set.length; i++) {\n        const parsed = mm.set[i]\n        const globParts = mm.globParts[i]\n        /* c8 ignore start */\n        if (!parsed || !globParts) {\n          throw new Error('invalid pattern object')\n        }\n        /* c8 ignore stop */\n        const p = new Pattern(parsed, globParts, 0, platform)\n        const m = new Minimatch(p.globString(), mmopts)\n        const children = globParts[globParts.length - 1] === '**'\n        const absolute = p.isAbsolute()\n        if (absolute) this.absolute.push(m)\n        else this.relative.push(m)\n        if (children) {\n          if (absolute) this.absoluteChildren.push(m)\n          else this.relativeChildren.push(m)\n        }\n      }\n    }\n  }\n\n  ignored(p: Path): boolean {\n    const fullpath = p.fullpath()\n    const fullpaths = `${fullpath}/`\n    const relative = p.relative() || '.'\n    const relatives = `${relative}/`\n    for (const m of this.relative) {\n      if (m.match(relative) || m.match(relatives)) return true\n    }\n    for (const m of this.absolute) {\n      if (m.match(fullpath) || m.match(fullpaths)) return true\n    }\n    return false\n  }\n\n  childrenIgnored(p: Path): boolean {\n    const fullpath = p.fullpath() + '/'\n    const relative = (p.relative() || '.') + '/'\n    for (const m of this.relativeChildren) {\n      if (m.match(relative)) return true\n    }\n    for (const m of this.absoluteChildren) {\n      if (m.match(fullpath)) return true\n    }\n    return false\n  }\n}\n","// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR, MMRegExp } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { MMPattern, Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path\n */\nexport class HasWalkedCache {\n  store: Map>\n  constructor(store: Map> = new Map()) {\n    this.store = store\n  }\n  copy() {\n    return new HasWalkedCache(new Map(this.store))\n  }\n  hasWalked(target: Path, pattern: Pattern) {\n    return this.store.get(target.fullpath())?.has(pattern.globString())\n  }\n  storeWalked(target: Path, pattern: Pattern) {\n    const fullpath = target.fullpath()\n    const cached = this.store.get(fullpath)\n    if (cached) cached.add(pattern.globString())\n    else this.store.set(fullpath, new Set([pattern.globString()]))\n  }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n */\nexport class MatchRecord {\n  store: Map = new Map()\n  add(target: Path, absolute: boolean, ifDir: boolean) {\n    const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0)\n    const current = this.store.get(target)\n    this.store.set(target, current === undefined ? n : n & current)\n  }\n  // match, absolute, ifdir\n  entries(): [Path, boolean, boolean][] {\n    return [...this.store.entries()].map(([path, n]) => [\n      path,\n      !!(n & 2),\n      !!(n & 1),\n    ])\n  }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n  store: Map = new Map()\n  add(target: Path, pattern: Pattern) {\n    if (!target.canReaddir()) {\n      return\n    }\n    const subs = this.store.get(target)\n    if (subs) {\n      if (!subs.find(p => p.globString() === pattern.globString())) {\n        subs.push(pattern)\n      }\n    } else this.store.set(target, [pattern])\n  }\n  get(target: Path): Pattern[] {\n    const subs = this.store.get(target)\n    /* c8 ignore start */\n    if (!subs) {\n      throw new Error('attempting to walk unknown path')\n    }\n    /* c8 ignore stop */\n    return subs\n  }\n  entries(): [Path, Pattern[]][] {\n    return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n  }\n  keys(): Path[] {\n    return [...this.store.keys()].filter(t => t.canReaddir())\n  }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n  hasWalkedCache: HasWalkedCache\n  matches = new MatchRecord()\n  subwalks = new SubWalks()\n  patterns?: Pattern[]\n  follow: boolean\n  dot: boolean\n  opts: GlobWalkerOpts\n\n  constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n    this.opts = opts\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.hasWalkedCache = hasWalkedCache\n      ? hasWalkedCache.copy()\n      : new HasWalkedCache()\n  }\n\n  processPatterns(target: Path, patterns: Pattern[]) {\n    this.patterns = patterns\n    const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n    // map of paths to the magic-starting subwalks they need to walk\n    // first item in patterns is the filter\n\n    for (let [t, pattern] of processingSet) {\n      this.hasWalkedCache.storeWalked(t, pattern)\n\n      const root = pattern.root()\n      const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n      // start absolute patterns at root\n      if (root) {\n        t = t.resolve(\n          root === '/' && this.opts.root !== undefined\n            ? this.opts.root\n            : root\n        )\n        const rest = pattern.rest()\n        if (!rest) {\n          this.matches.add(t, true, false)\n          continue\n        } else {\n          pattern = rest\n        }\n      }\n\n      if (t.isENOENT()) continue\n\n      let p: MMPattern\n      let rest: Pattern | null\n      let changed = false\n      while (\n        typeof (p = pattern.pattern()) === 'string' &&\n        (rest = pattern.rest())\n      ) {\n        const c = t.resolve(p)\n        t = c\n        pattern = rest\n        changed = true\n      }\n      p = pattern.pattern()\n      rest = pattern.rest()\n      if (changed) {\n        if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n        this.hasWalkedCache.storeWalked(t, pattern)\n      }\n\n      // now we have either a final string for a known entry,\n      // more strings for an unknown entry,\n      // or a pattern starting with magic, mounted on t.\n      if (typeof p === 'string') {\n        // must not be final entry, otherwise we would have\n        // concatenated it earlier.\n        const ifDir = p === '..' || p === '' || p === '.'\n        this.matches.add(t.resolve(p), absolute, ifDir)\n        continue\n      } else if (p === GLOBSTAR) {\n        // if no rest, match and subwalk pattern\n        // if rest, process rest and subwalk pattern\n        // if it's a symlink, but we didn't get here by way of a\n        // globstar match (meaning it's the first time THIS globstar\n        // has traversed a symlink), then we follow it. Otherwise, stop.\n        if (\n          !t.isSymbolicLink() ||\n          this.follow ||\n          pattern.checkFollowGlobstar()\n        ) {\n          this.subwalks.add(t, pattern)\n        }\n        const rp = rest?.pattern()\n        const rrest = rest?.rest()\n        if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n          // only HAS to be a dir if it ends in **/ or **/.\n          // but ending in ** will match files as well.\n          this.matches.add(t, absolute, rp === '' || rp === '.')\n        } else {\n          if (rp === '..') {\n            // this would mean you're matching **/.. at the fs root,\n            // and no thanks, I'm not gonna test that specific case.\n            /* c8 ignore start */\n            const tp = t.parent || t\n            /* c8 ignore stop */\n            if (!rrest) this.matches.add(tp, absolute, true)\n            else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n              this.subwalks.add(tp, rrest)\n            }\n          }\n        }\n      } else if (p instanceof RegExp) {\n        this.subwalks.add(t, pattern)\n      }\n    }\n\n    return this\n  }\n\n  subwalkTargets(): Path[] {\n    return this.subwalks.keys()\n  }\n\n  child() {\n    return new Processor(this.opts, this.hasWalkedCache)\n  }\n\n  // return a new Processor containing the subwalks for each\n  // child entry, and a set of matches, and\n  // a hasWalkedCache that's a copy of this one\n  // then we're going to call\n  filterEntries(parent: Path, entries: Path[]): Processor {\n    const patterns = this.subwalks.get(parent)\n    // put matches and entry walks into the results processor\n    const results = this.child()\n    for (const e of entries) {\n      for (const pattern of patterns) {\n        const absolute = pattern.isAbsolute()\n        const p = pattern.pattern()\n        const rest = pattern.rest()\n        if (p === GLOBSTAR) {\n          results.testGlobstar(e, pattern, rest, absolute)\n        } else if (p instanceof RegExp) {\n          results.testRegExp(e, p, rest, absolute)\n        } else {\n          results.testString(e, p, rest, absolute)\n        }\n      }\n    }\n    return results\n  }\n\n  testGlobstar(\n    e: Path,\n    pattern: Pattern,\n    rest: Pattern | null,\n    absolute: boolean\n  ) {\n    if (this.dot || !e.name.startsWith('.')) {\n      if (!pattern.hasMore()) {\n        this.matches.add(e, absolute, false)\n      }\n      if (e.canReaddir()) {\n        // if we're in follow mode or it's not a symlink, just keep\n        // testing the same pattern. If there's more after the globstar,\n        // then this symlink consumes the globstar. If not, then we can\n        // follow at most ONE symlink along the way, so we mark it, which\n        // also checks to ensure that it wasn't already marked.\n        if (this.follow || !e.isSymbolicLink()) {\n          this.subwalks.add(e, pattern)\n        } else if (e.isSymbolicLink()) {\n          if (rest && pattern.checkFollowGlobstar()) {\n            this.subwalks.add(e, rest)\n          } else if (pattern.markFollowGlobstar()) {\n            this.subwalks.add(e, pattern)\n          }\n        }\n      }\n    }\n    // if the NEXT thing matches this entry, then also add\n    // the rest.\n    if (rest) {\n      const rp = rest.pattern()\n      if (\n        typeof rp === 'string' &&\n        // dots and empty were handled already\n        rp !== '..' &&\n        rp !== '' &&\n        rp !== '.'\n      ) {\n        this.testString(e, rp, rest.rest(), absolute)\n      } else if (rp === '..') {\n        /* c8 ignore start */\n        const ep = e.parent || e\n        /* c8 ignore stop */\n        this.subwalks.add(ep, rest)\n      } else if (rp instanceof RegExp) {\n        this.testRegExp(e, rp, rest.rest(), absolute)\n      }\n    }\n  }\n\n  testRegExp(\n    e: Path,\n    p: MMRegExp,\n    rest: Pattern | null,\n    absolute: boolean\n  ) {\n    if (!p.test(e.name)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n\n  testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n    // should never happen?\n    if (!e.isNamed(p)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n}\n","/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport { Ignore, IgnoreLike } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed?  that'd speed\n// things up a lot.  Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport { Pattern } from './pattern.js'\nimport { Processor } from './processor.js'\n\nexport interface GlobWalkerOpts {\n  absolute?: boolean\n  allowWindowsEscape?: boolean\n  cwd?: string | URL\n  dot?: boolean\n  dotRelative?: boolean\n  follow?: boolean\n  ignore?: string | string[] | IgnoreLike\n  mark?: boolean\n  matchBase?: boolean\n  // Note: maxDepth here means \"maximum actual Path.depth()\",\n  // not \"maximum depth beyond cwd\"\n  maxDepth?: number\n  nobrace?: boolean\n  nocase?: boolean\n  nodir?: boolean\n  noext?: boolean\n  noglobstar?: boolean\n  platform?: NodeJS.Platform\n  posix?: boolean\n  realpath?: boolean\n  root?: string\n  stat?: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape?: boolean\n  withFileTypes?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n  withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n  withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n  withFileTypes?: undefined\n}\n\nexport type Result = O extends GWOFileTypesTrue\n  ? Path\n  : O extends GWOFileTypesFalse\n  ? string\n  : O extends GWOFileTypesUnset\n  ? string\n  : Path | string\n\nexport type Matches = O extends GWOFileTypesTrue\n  ? Set\n  : O extends GWOFileTypesFalse\n  ? Set\n  : O extends GWOFileTypesUnset\n  ? Set\n  : Set\n\nexport type MatchStream =\n  O extends GWOFileTypesTrue\n    ? Minipass\n    : O extends GWOFileTypesFalse\n    ? Minipass\n    : O extends GWOFileTypesUnset\n    ? Minipass\n    : Minipass\n\nconst makeIgnore = (\n  ignore: string | string[] | IgnoreLike,\n  opts: GlobWalkerOpts\n): IgnoreLike =>\n  typeof ignore === 'string'\n    ? new Ignore([ignore], opts)\n    : Array.isArray(ignore)\n    ? new Ignore(ignore, opts)\n    : ignore\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil {\n  path: Path\n  patterns: Pattern[]\n  opts: O\n  seen: Set = new Set()\n  paused: boolean = false\n  aborted: boolean = false\n  #onResume: (() => any)[] = []\n  #ignore?: IgnoreLike\n  #sep: '\\\\' | '/'\n  signal?: AbortSignal\n  maxDepth: number\n\n  constructor(patterns: Pattern[], path: Path, opts: O)\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    this.patterns = patterns\n    this.path = path\n    this.opts = opts\n    this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n    if (opts.ignore) {\n      this.#ignore = makeIgnore(opts.ignore, opts)\n    }\n    // ignore, always set with maxDepth, but it's optional on the\n    // GlobOptions type\n    /* c8 ignore start */\n    this.maxDepth = opts.maxDepth || Infinity\n    /* c8 ignore stop */\n    if (opts.signal) {\n      this.signal = opts.signal\n      this.signal.addEventListener('abort', () => {\n        this.#onResume.length = 0\n      })\n    }\n  }\n\n  #ignored(path: Path): boolean {\n    return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n  }\n  #childrenIgnored(path: Path): boolean {\n    return !!this.#ignore?.childrenIgnored?.(path)\n  }\n\n  // backpressure mechanism\n  pause() {\n    this.paused = true\n  }\n  resume() {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return\n    /* c8 ignore stop */\n    this.paused = false\n    let fn: (() => any) | undefined = undefined\n    while (!this.paused && (fn = this.#onResume.shift())) {\n      fn()\n    }\n  }\n  onResume(fn: () => any) {\n    if (this.signal?.aborted) return\n    /* c8 ignore start */\n    if (!this.paused) {\n      fn()\n    } else {\n      /* c8 ignore stop */\n      this.#onResume.push(fn)\n    }\n  }\n\n  // do the requisite realpath/stat checking, and return the path\n  // to add or undefined to filter it out.\n  async matchCheck(e: Path, ifDir: boolean): Promise {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || (await e.realpath())\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    return this.matchCheckTest(needStat ? await e.lstat() : e, ifDir)\n  }\n\n  matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n    return e &&\n      (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n      (!ifDir || e.canReaddir()) &&\n      (!this.opts.nodir || !e.isDirectory()) &&\n      !this.#ignored(e)\n      ? e\n      : undefined\n  }\n\n  matchCheckSync(e: Path, ifDir: boolean): Path | undefined {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || e.realpathSync()\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    return this.matchCheckTest(needStat ? e.lstatSync() : e, ifDir)\n  }\n\n  abstract matchEmit(p: Result): void\n  abstract matchEmit(p: string | Path): void\n\n  matchFinish(e: Path, absolute: boolean) {\n    if (this.#ignored(e)) return\n    const abs =\n      this.opts.absolute === undefined ? absolute : this.opts.absolute\n    this.seen.add(e)\n    const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n    // ok, we have what we need!\n    if (this.opts.withFileTypes) {\n      this.matchEmit(e)\n    } else if (abs) {\n      const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n      this.matchEmit(abs + mark)\n    } else {\n      const rel = this.opts.posix ? e.relativePosix() : e.relative()\n      const pre =\n        this.opts.dotRelative && !rel.startsWith('..' + this.#sep)\n          ? '.' + this.#sep\n          : ''\n      this.matchEmit(!rel ? '.' + mark : pre + rel + mark)\n    }\n  }\n\n  async match(e: Path, absolute: boolean, ifDir: boolean): Promise {\n    const p = await this.matchCheck(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n    const p = this.matchCheckSync(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  walkCB(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const childrenCached = t.readdirCached()\n      if (t.calledReaddir())\n        this.walkCB3(t, childrenCached, processor, next)\n      else {\n        t.readdirCB(\n          (_, entries) => this.walkCB3(t, entries, processor, next),\n          true\n        )\n      }\n    }\n\n    next()\n  }\n\n  walkCB3(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n\n  walkCBSync(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2Sync(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() =>\n        this.walkCB2Sync(target, patterns, processor, cb)\n      )\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const children = t.readdirSync()\n      this.walkCB3Sync(t, children, processor, next)\n    }\n\n    next()\n  }\n\n  walkCB3Sync(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2Sync(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n}\n\nexport class GlobWalker<\n  O extends GlobWalkerOpts = GlobWalkerOpts\n> extends GlobUtil {\n  matches: O extends GWOFileTypesTrue\n    ? Set\n    : O extends GWOFileTypesFalse\n    ? Set\n    : O extends GWOFileTypesUnset\n    ? Set\n    : Set\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n    this.matches = new Set() as Matches\n  }\n\n  matchEmit(e: Result): void\n  matchEmit(e: Path | string): void {\n    this.matches.add(e)\n  }\n\n  async walk(): Promise> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      await this.path.lstat()\n    }\n    await new Promise((res, rej) => {\n      this.walkCB(this.path, this.patterns, () => {\n        if (this.signal?.aborted) {\n          rej(this.signal.reason)\n        } else {\n          res(this.matches)\n        }\n      })\n    })\n    return this.matches\n  }\n\n  walkSync(): Matches {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    // nothing for the callback to do, because this never pauses\n    this.walkCBSync(this.path, this.patterns, () => {\n      if (this.signal?.aborted) throw this.signal.reason\n    })\n    return this.matches\n  }\n}\n\nexport class GlobStream<\n  O extends GlobWalkerOpts = GlobWalkerOpts\n> extends GlobUtil {\n  results: O extends GWOFileTypesTrue\n    ? Minipass\n    : O extends GWOFileTypesFalse\n    ? Minipass\n    : O extends GWOFileTypesUnset\n    ? Minipass\n    : Minipass\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n    this.results = new Minipass({\n      signal: this.signal,\n      objectMode: true,\n    }) as MatchStream\n    this.results.on('drain', () => this.resume())\n    this.results.on('resume', () => this.resume())\n  }\n\n  matchEmit(e: Result): void\n  matchEmit(e: Path | string): void {\n    this.results.write(e)\n    if (!this.results.flowing) this.pause()\n  }\n\n  stream(): MatchStream {\n    const target = this.path\n    if (target.isUnknown()) {\n      target.lstat().then(() => {\n        this.walkCB(target, this.patterns, () => this.results.end())\n      })\n    } else {\n      this.walkCB(target, this.patterns, () => this.results.end())\n    }\n    return this.results\n  }\n\n  streamSync(): MatchStream {\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    this.walkCBSync(this.path, this.patterns, () => this.results.end())\n    return this.results\n  }\n}\n","import { Minimatch } from 'minimatch'\nimport { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n  pattern: string | string[],\n  options: GlobOptions = {}\n): boolean => {\n  if (!Array.isArray(pattern)) {\n    pattern = [pattern]\n  }\n  for (const p of pattern) {\n    if (new Minimatch(p, options).hasMagic()) return true\n  }\n  return false\n}\n","import { escape, unescape } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesUnset\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions\n): Minipass | Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions = {}\n) {\n  return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions\n): Minipass | Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions = {}\n) {\n  return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue\n): Path[]\nexport function globSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions\n): Path[] | string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions = {}\n) {\n  return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions = {}\n) {\n  return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions\n): Generator | Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions = {}\n) {\n  return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions\n): AsyncGenerator | AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions = {}\n) {\n  return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n  sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n  stream: globStreamSync,\n  iterate: globIterateSync,\n})\n\n/* c8 ignore start */\nexport { escape, unescape } from 'minimatch'\nexport { Glob } from './glob.js'\nexport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\nexport type {\n  Path,\n  WalkOptionsWithFileTypesTrue,\n  WalkOptionsWithFileTypesUnset,\n  WalkOptions,\n  FSOption,\n} from 'path-scurry'\n\n/* c8 ignore stop */\n\nexport const glob = Object.assign(glob_, {\n  glob: glob_,\n  globSync,\n  sync,\n  globStream,\n  stream,\n  globStreamSync,\n  streamSync,\n  globIterate,\n  iterate,\n  globIterateSync,\n  iterateSync,\n  Glob,\n  hasMagic,\n  escape,\n  unescape,\n})\nglob.glob = glob\n","import { createUnplugin } from 'unplugin';\nimport dedent from 'ts-dedent';\nimport { logger } from '@storybook/node-logger';\nimport { extractComponentsFromTemplate } from './extractComponentsFromTemplate';\nimport { TwigComponentConfiguration } from './symfony';\nimport { TwigComponentResolver } from './TwigComponentResolver';\nimport crypto from 'crypto';\n\nconst PLUGIN_NAME = 'twig-loader';\n\nexport type Options = {\n    twigComponentConfiguration: TwigComponentConfiguration;\n    projectDir: string;\n};\n\n/**\n * Twig template source loader.\n *\n * Generates JS modules to export raw template source and imports required components.\n */\nexport const TwigLoaderPlugin = createUnplugin((options) => {\n    const { twigComponentConfiguration, projectDir } = options;\n    const resolver = new TwigComponentResolver(twigComponentConfiguration, projectDir);\n\n    return {\n        name: PLUGIN_NAME,\n        enforce: 'pre',\n        transformInclude: (id) => {\n            return /\\.html\\.twig$/.test(id);\n        },\n        transform: async (code, id) => {\n            const imports: string[] = [];\n\n            try {\n                const components = new Set(extractComponentsFromTemplate(code));\n\n                components.forEach((name) => {\n                    imports.push(resolver.resolveFileFromName(name));\n                });\n            } catch (err) {\n                logger.warn(dedent`\n                Failed to parse template in '${id}': ${err}\n                `);\n            }\n\n            const name = resolver.resolveNameFromFile(id);\n\n            return dedent`\n            ${imports.map((file) => `import '${file}';`).join('\\n')}\n            export default {\n                name: \\'${name}\\',\n                hash: \\`${crypto.createHash('sha1').update(code).digest('hex')}\\`,\n            };\n           `;\n        },\n    };\n});\n","import { XMLParser } from 'fast-xml-parser';\n\nexport const extractComponentsFromTemplate = (source: string) => {\n    const reservedNames = ['block'];\n    const tagRe = new RegExp(/twig:[A-Za-z]+(?::[A-Za-z]+)*/);\n    const functionRe = new RegExp(/component\\(\\s*'([A-Za-z]+(?::[A-Za-z]+)*)'\\s*(?:,.*)?\\)/, 'gs');\n\n    const lookupComponents = (obj: { [p: string]: any }): string[] => {\n        return Object.entries(obj).reduce((names, [key, value]) => {\n            if (value !== null && typeof value === 'object') {\n                names.push(...lookupComponents(value));\n            } else if (typeof value === 'string') {\n                for (const m of value.matchAll(functionRe)) {\n                    names.push([...m][1]);\n                }\n            }\n            if (tagRe.test(key)) {\n                names.push(key.replace('twig:', ''));\n            }\n            return names;\n        }, [] as string[]);\n    };\n\n    try {\n        // Dummy div tag to handle templates without any tag\n        const documentObj = new XMLParser().parse(`
${source}
`);\n\n return lookupComponents(documentObj).filter((name) => !reservedNames.includes(name));\n } catch (err) {\n throw new Error('Invalid XML.', {\n cause: {\n parserError: err,\n template: source,\n },\n });\n }\n};\n","import { TwigComponentConfiguration } from './symfony';\nimport path from 'path';\nimport dedent from 'ts-dedent';\n\nexport class TwigComponentResolver {\n constructor(\n private config: TwigComponentConfiguration,\n private projectDir: string\n ) {}\n\n resolveNameFromFile(file: string) {\n const stripDirectory = (file: string, dir: string) => {\n return file.replace(dir, '').replace(/^\\//, '').replaceAll('/', ':').replace('.html.twig', '');\n };\n\n const resolvedFile = this.resolveRelativePath(file);\n\n for (const [namespace, twigDirectories] of Object.entries(this.config.namespaces)) {\n const matchingDirectory = twigDirectories.find((dir) => resolvedFile.startsWith(dir));\n if (matchingDirectory) {\n const trimmedPath = stripDirectory(resolvedFile, matchingDirectory);\n return namespace ? `${namespace}:${trimmedPath}` : trimmedPath;\n }\n }\n\n for (const anonymousDir of this.config.anonymousTemplateDirectory) {\n if (resolvedFile.startsWith(anonymousDir)) {\n return stripDirectory(resolvedFile, anonymousDir);\n }\n }\n\n throw new Error(dedent`Unable to determine template name for file \"${file}\":`);\n }\n\n resolveFileFromName(name: string) {\n const nameParts = name.split(':');\n const namespace = nameParts.length > 1 ? nameParts[0] : '';\n const dirParts = nameParts.slice(0, -1);\n const filename = `${nameParts.slice(-1)}.html.twig`;\n\n const lookupPaths: string[] = [];\n\n if (namespace && this.config.namespaces[namespace]) {\n const namespacePaths = this.config.namespaces[namespace];\n if (namespacePaths.length > 0) {\n for (const namespacePath of this.config.namespaces[namespace]) {\n lookupPaths.push(path.join(this.resolveRelativePath(namespacePath), dirParts.slice(1).join('/')));\n }\n }\n }\n\n if (this.config.namespaces[''] && this.config.namespaces[''].length > 0) {\n for (const namespacePath of this.config.namespaces['']) {\n lookupPaths.push(path.join(this.resolveRelativePath(namespacePath), dirParts.join('/')));\n }\n }\n\n if (this.config.anonymousTemplateDirectory.length > 0) {\n for (const namespacePath of this.config.anonymousTemplateDirectory) {\n lookupPaths.push(path.join(this.resolveRelativePath(namespacePath), dirParts.join('/')));\n }\n }\n\n try {\n return require.resolve(`./${filename}`, { paths: lookupPaths });\n } catch (err) {\n throw new Error(dedent`Unable to find template file for component \"${name}\": ${err}`);\n }\n }\n\n /**\n * Remove the project path from the file path.\n * This is useful to have relative paths and not depend on host paths.\n */\n private resolveRelativePath(file: string) {\n return file.replace(this.projectDir, '');\n }\n}\n"]} \ No newline at end of file diff --git a/storybook/src/builders/webpack-builder.ts b/storybook/src/builders/webpack-builder.ts index 0fb3bd9..20689d3 100644 --- a/storybook/src/builders/webpack-builder.ts +++ b/storybook/src/builders/webpack-builder.ts @@ -4,6 +4,7 @@ import * as baseBuilder from '@storybook/builder-webpack5'; import dedent from 'ts-dedent'; export type BuilderOptions = { + storybookCachePath?: string; server?: string; proxyPaths?: string | string[]; }; @@ -28,7 +29,7 @@ export const start: typeof baseBuilder.start = async (options) => { `); } - const proxyPaths = ['/_storybook/render']; + const proxyPaths = ['/_storybook/render', '/_storybook/preview']; if (symfony.proxyPaths) { const paths = !Array.isArray(symfony.proxyPaths) ? [symfony.proxyPaths] : symfony.proxyPaths; diff --git a/storybook/src/server/framework-preset.ts b/storybook/src/server/framework-preset.ts index 1aced43..1132cb3 100644 --- a/storybook/src/server/framework-preset.ts +++ b/storybook/src/server/framework-preset.ts @@ -1,13 +1,6 @@ -import { - getBundleConfig, - getKernelProjectDir, - getTwigComponentConfiguration, - getTwigConfiguration, - TwigComponentConfiguration, - TwigConfiguration, -} from './lib/symfony'; +import { getSymfonyConfig, TwigComponentConfiguration, TwigConfiguration } from './lib/symfony'; import { StorybookConfig, SymfonyOptions } from '../types'; -import { join } from 'path'; +import { join, resolve } from 'path'; import { PreviewCompilerPlugin } from './lib/preview-compiler-plugin'; import { DevPreviewCompilerPlugin } from './lib/dev-preview-compiler-plugin'; import { TwigLoaderPlugin } from './lib/twig-loader-plugin'; @@ -17,35 +10,34 @@ import dedent from 'ts-dedent'; type BuildOptions = { twigComponent: TwigComponentConfiguration; twig: TwigConfiguration; - runtimeDir: string; - projectDir: string; additionalWatchPaths: string[]; }; const getBuildOptions = async (symfonyOptions: SymfonyOptions) => { - const projectDir = await getKernelProjectDir(); - const twigComponentsConfig = await getTwigComponentConfiguration(); - const twigConfig = await getTwigConfiguration(); + const { twig_config, twig_component_config } = await getSymfonyConfig(symfonyOptions.storybookCachePath); const componentNamespaces: { [p: string]: string[] } = {}; - const twigPaths: string[] = Object.keys(twigConfig.paths).map((key) => `${projectDir}/${key}/`); + const twigPaths: string[] = Object.keys(twig_config.paths); if (twigPaths.length === 0) { - twigPaths.push(`${projectDir}/templates`); + twigPaths.push('templates'); } for (const { name_prefix: namePrefix, template_directory: templateDirectory } of Object.values( - twigComponentsConfig.defaults + twig_component_config.defaults )) { - componentNamespaces[namePrefix] = twigPaths.map((twigPath) => join(twigPath, templateDirectory)); + componentNamespaces[namePrefix] = [join(twig_config.default_path, templateDirectory)]; } - const anonymousNamespace: string[] = twigPaths.map((twigPath) => - join(twigPath, twigComponentsConfig['anonymous_template_directory']) - ); + Object.entries(twig_config.paths).forEach(([path, alias]) => { + componentNamespaces[alias] = [join(path, twig_component_config.anonymous_template_directory)]; + }); - const runtimeDir = (await getBundleConfig()).runtime_dir; + // TODO Should be a regular string ? + const anonymousNamespace: string[] = [ + join(twig_config.default_path, twig_component_config.anonymous_template_directory), + ]; return { twigComponent: { @@ -55,8 +47,6 @@ const getBuildOptions = async (symfonyOptions: SymfonyOptions) => { twig: { paths: twigPaths, }, - runtimeDir, - projectDir, additionalWatchPaths: symfonyOptions.additionalWatchPaths || [], } as BuildOptions; }; @@ -75,12 +65,16 @@ export const webpack: StorybookConfig['webpack'] = async (config, options) => { ...(config.plugins || []), ...[ options.configType === 'PRODUCTION' - ? PreviewCompilerPlugin.webpack() + ? PreviewCompilerPlugin.webpack({ + server: frameworkOptions.symfony.server, + }) : DevPreviewCompilerPlugin.webpack({ - projectDir: symfonyOptions.projectDir, + projectDir: resolve(), + server: frameworkOptions.symfony.server, additionalWatchPaths: symfonyOptions.additionalWatchPaths, }), TwigLoaderPlugin.webpack({ + projectDir: resolve(), twigComponentConfiguration: symfonyOptions.twigComponent, }), ], diff --git a/storybook/src/server/lib/TwigComponentResolver.test.ts b/storybook/src/server/lib/TwigComponentResolver.test.ts index 6ffcd3a..ea3fc32 100644 --- a/storybook/src/server/lib/TwigComponentResolver.test.ts +++ b/storybook/src/server/lib/TwigComponentResolver.test.ts @@ -1,15 +1,19 @@ import { TwigComponentResolver } from './TwigComponentResolver'; +import path from 'path'; +const projectDir = path.resolve(); const fixturesDir = `${__dirname}/__fixtures__/templates`; +const relativeFixturesDir = path.relative(projectDir, fixturesDir); const twigComponentConfig = { - anonymousTemplateDirectory: [`${fixturesDir}/anonymous`, `${fixturesDir}/twig_path/anonymous`], + anonymousTemplateDirectory: [`${relativeFixturesDir}/anonymous`, `${relativeFixturesDir}/twig_path/anonymous`], namespaces: { - '': [`${fixturesDir}/components`, `${fixturesDir}/twig_path`], - Custom: [`${fixturesDir}/custom`], + '': [`${relativeFixturesDir}/components`, `${relativeFixturesDir}/twig_path`], + Custom: [`${relativeFixturesDir}/custom`], }, }; -const resolver = new TwigComponentResolver(twigComponentConfig); + +const resolver = new TwigComponentResolver(twigComponentConfig, projectDir); describe('resolveFileFromName', () => { it('resolves component path without namespace', () => { @@ -56,44 +60,46 @@ describe('resolveFileFromName', () => { describe('resolveNameFromFile', () => { it('resolves in default namespace', () => { - const resolved = resolver.resolveNameFromFile(`${fixturesDir}/components/Component.html.twig`); + const resolved = resolver.resolveNameFromFile(`${relativeFixturesDir}/components/Component.html.twig`); expect(resolved).toEqual('Component'); }); it('resolves in anonymous namespace', () => { - const resolved = resolver.resolveNameFromFile(`${fixturesDir}/anonymous/Anonymous.html.twig`); + const resolved = resolver.resolveNameFromFile(`${relativeFixturesDir}/anonymous/Anonymous.html.twig`); expect(resolved).toEqual('Anonymous'); }); it('resolves in custom namespace', () => { - const resolved = resolver.resolveNameFromFile(`${fixturesDir}/custom/CustomNamespace.html.twig`); + const resolved = resolver.resolveNameFromFile(`${relativeFixturesDir}/custom/CustomNamespace.html.twig`); expect(resolved).toEqual('Custom:CustomNamespace'); }); it('resolves in auto namespace', () => { - const resolved = resolver.resolveNameFromFile(`${fixturesDir}/components/Namespace/AutoNamespace.html.twig`); + const resolved = resolver.resolveNameFromFile( + `${relativeFixturesDir}/components/Namespace/AutoNamespace.html.twig` + ); expect(resolved).toEqual('Namespace:AutoNamespace'); }); it('fallbacks to default namespace', () => { const resolved = resolver.resolveNameFromFile( - `${fixturesDir}/components/Custom/NotInCustomNamespace.html.twig` + `${relativeFixturesDir}/components/Custom/NotInCustomNamespace.html.twig` ); expect(resolved).toEqual('Custom:NotInCustomNamespace'); }); it('handle multiple nested levels of namespaces', () => { - const resolved = resolver.resolveNameFromFile(`${fixturesDir}/anonymous/Foo/Bar/Baz.html.twig`); + const resolved = resolver.resolveNameFromFile(`${relativeFixturesDir}/anonymous/Foo/Bar/Baz.html.twig`); expect(resolved).toEqual('Foo:Bar:Baz'); }); it('fallbacks to next twig path', () => { - const resolved = resolver.resolveNameFromFile(`${fixturesDir}/twig_path/TwigPath.html.twig`); + const resolved = resolver.resolveNameFromFile(`${relativeFixturesDir}/twig_path/TwigPath.html.twig`); expect(resolved).toEqual('TwigPath'); }); it('handle multiple nested levels when fallbacks to next twig path', () => { - const resolved = resolver.resolveNameFromFile(`${fixturesDir}/twig_path/Foo/Bar.html.twig`); + const resolved = resolver.resolveNameFromFile(`${relativeFixturesDir}/twig_path/Foo/Bar.html.twig`); expect(resolved).toEqual('Foo:Bar'); }); diff --git a/storybook/src/server/lib/TwigComponentResolver.ts b/storybook/src/server/lib/TwigComponentResolver.ts index 92bcdce..df33b04 100644 --- a/storybook/src/server/lib/TwigComponentResolver.ts +++ b/storybook/src/server/lib/TwigComponentResolver.ts @@ -3,24 +3,29 @@ import path from 'path'; import dedent from 'ts-dedent'; export class TwigComponentResolver { - constructor(private config: TwigComponentConfiguration) {} + constructor( + private config: TwigComponentConfiguration, + private projectDir: string + ) {} resolveNameFromFile(file: string) { const stripDirectory = (file: string, dir: string) => { return file.replace(dir, '').replace(/^\//, '').replaceAll('/', ':').replace('.html.twig', ''); }; + const resolvedFile = this.resolveRelativePath(file); + for (const [namespace, twigDirectories] of Object.entries(this.config.namespaces)) { - const matchingDirectory = twigDirectories.find((dir) => file.startsWith(dir)); + const matchingDirectory = twigDirectories.find((dir) => resolvedFile.startsWith(dir)); if (matchingDirectory) { - const trimmedPath = stripDirectory(file, matchingDirectory); + const trimmedPath = stripDirectory(resolvedFile, matchingDirectory); return namespace ? `${namespace}:${trimmedPath}` : trimmedPath; } } for (const anonymousDir of this.config.anonymousTemplateDirectory) { - if (file.startsWith(anonymousDir)) { - return stripDirectory(file, anonymousDir); + if (resolvedFile.startsWith(anonymousDir)) { + return stripDirectory(resolvedFile, anonymousDir); } } @@ -39,20 +44,20 @@ export class TwigComponentResolver { const namespacePaths = this.config.namespaces[namespace]; if (namespacePaths.length > 0) { for (const namespacePath of this.config.namespaces[namespace]) { - lookupPaths.push(path.join(namespacePath, dirParts.slice(1).join('/'))); + lookupPaths.push(path.join(this.resolveRelativePath(namespacePath), dirParts.slice(1).join('/'))); } } } if (this.config.namespaces[''] && this.config.namespaces[''].length > 0) { for (const namespacePath of this.config.namespaces['']) { - lookupPaths.push(path.join(namespacePath, dirParts.join('/'))); + lookupPaths.push(path.join(this.resolveRelativePath(namespacePath), dirParts.join('/'))); } } if (this.config.anonymousTemplateDirectory.length > 0) { for (const namespacePath of this.config.anonymousTemplateDirectory) { - lookupPaths.push(path.join(namespacePath, dirParts.join('/'))); + lookupPaths.push(path.join(this.resolveRelativePath(namespacePath), dirParts.join('/'))); } } @@ -62,4 +67,12 @@ export class TwigComponentResolver { throw new Error(dedent`Unable to find template file for component "${name}": ${err}`); } } + + /** + * Remove the project path from the file path. + * This is useful to have relative paths and not depend on host paths. + */ + private resolveRelativePath(file: string) { + return file.replace(this.projectDir, ''); + } } diff --git a/storybook/src/server/lib/__fixtures__/templates/alias/Source/Aliased.html.twig b/storybook/src/server/lib/__fixtures__/templates/alias/Source/Aliased.html.twig new file mode 100644 index 0000000..e69de29 diff --git a/storybook/src/server/lib/__fixtures__/templates/alias/Target/Aliased.html.twig b/storybook/src/server/lib/__fixtures__/templates/alias/Target/Aliased.html.twig new file mode 100644 index 0000000..e69de29 diff --git a/storybook/src/server/lib/__fixtures__/var/cache/dev/storybook/symfony_parameters.json b/storybook/src/server/lib/__fixtures__/var/cache/dev/storybook/symfony_parameters.json new file mode 100644 index 0000000..cbeb0cf --- /dev/null +++ b/storybook/src/server/lib/__fixtures__/var/cache/dev/storybook/symfony_parameters.json @@ -0,0 +1,25 @@ +{ + "twig_config": { + "paths": { + "\/var\/www\/templates": "Shared", + "\/var\/www\/apps\/foo\/templates": "Foo" + } + }, + "twig_component_config": { + "defaults": { + "Front\\Twig\\Components\\": { + "template_directory": "components\/", + "name_prefix": "Shared" + }, + "Front\\Foo\\Twig\\Components\\Bar\\Baz\\": { + "template_directory": "bar\/baz\/components\/", + "name_prefix": "Bar:Baz" + }, + "Front\\Foo\\Twig\\Components\\": { + "template_directory": "components", + "name_prefix": "" + } + }, + "anonymous_template_directory": "components\/" + } +} diff --git a/storybook/src/server/lib/computeAdditionalWatchPaths.test.ts b/storybook/src/server/lib/computeAdditionalWatchPaths.test.ts index 5e78f94..d6e378b 100644 --- a/storybook/src/server/lib/computeAdditionalWatchPaths.test.ts +++ b/storybook/src/server/lib/computeAdditionalWatchPaths.test.ts @@ -4,19 +4,19 @@ const fixturesDir = `${__dirname}/__fixtures__/assets`; describe('computeAdditionalWatchPaths', () => { it('resolves single files', () => { - const watchPaths = computeAdditionalWatchPaths(['foo.js', 'bar/bar.js'], fixturesDir); + const watchPaths = computeAdditionalWatchPaths(['foo.js', `${fixturesDir}/foo.css`, 'bar/bar.js'], fixturesDir); expect(watchPaths).toEqual({ dirs: [], - files: [`${fixturesDir}/foo.js`, `${fixturesDir}/bar/bar.js`], + files: [`${fixturesDir}/foo.js`, `${fixturesDir}/foo.css`, `${fixturesDir}/bar/bar.js`], }); }); it('resolves directory', () => { - const watchPaths = computeAdditionalWatchPaths(['bar'], fixturesDir); + const watchPaths = computeAdditionalWatchPaths(['bar', `${fixturesDir}/bar/baz`], fixturesDir); expect(watchPaths).toEqual({ - dirs: [`${fixturesDir}/bar`], + dirs: [`${fixturesDir}/bar`, `${fixturesDir}/bar/baz`], files: [], }); }); diff --git a/storybook/src/server/lib/computeAdditionalWatchPaths.ts b/storybook/src/server/lib/computeAdditionalWatchPaths.ts index f47e242..e7b8480 100644 --- a/storybook/src/server/lib/computeAdditionalWatchPaths.ts +++ b/storybook/src/server/lib/computeAdditionalWatchPaths.ts @@ -16,25 +16,28 @@ export const computeAdditionalWatchPaths = (paths: string[], baseDir: string) => files: [], }; - paths - .map((v) => join(baseDir, v)) - .forEach((watchPath) => { - if (isGlob(watchPath)) { - result.files.push( - ...glob.sync(watchPath, { - dot: true, - absolute: true, - }) - ); - } else if (fs.existsSync(watchPath)) { - const stats = fs.lstatSync(watchPath); - (stats.isDirectory() ? result.dirs : result.files).push(watchPath); - } else { - logger.warn(dedent` + paths.forEach((watchPath) => { + const absoluteWatchPath = join(baseDir, watchPath); + + if (isGlob(absoluteWatchPath)) { + result.files.push( + ...glob.sync(absoluteWatchPath, { + dot: true, + absolute: true, + }) + ); + } else if (fs.existsSync(watchPath)) { + const stats = fs.lstatSync(watchPath); + (stats.isDirectory() ? result.dirs : result.files).push(watchPath); + } else if (fs.existsSync(absoluteWatchPath)) { + const stats = fs.lstatSync(absoluteWatchPath); + (stats.isDirectory() ? result.dirs : result.files).push(absoluteWatchPath); + } else { + logger.warn(dedent` Ignoring additional watch path '${watchPath}': path doesn't exists. `); - } - }); + } + }); return result; }; diff --git a/storybook/src/server/lib/dev-preview-compiler-plugin.ts b/storybook/src/server/lib/dev-preview-compiler-plugin.ts index 22d9735..1d78a4e 100644 --- a/storybook/src/server/lib/dev-preview-compiler-plugin.ts +++ b/storybook/src/server/lib/dev-preview-compiler-plugin.ts @@ -1,7 +1,7 @@ import { createUnplugin } from 'unplugin'; import dedent from 'ts-dedent'; import VirtualModulesPlugin from 'webpack-virtual-modules'; -import { runSymfonyCommand } from './symfony'; +import { generateSymfonyPreview } from './symfony'; import { computeAdditionalWatchPaths } from './computeAdditionalWatchPaths'; import HtmlWebpackPlugin from 'html-webpack-plugin'; import { logger } from '@storybook/node-logger'; @@ -11,6 +11,7 @@ const PLUGIN_NAME = 'dev-preview-plugin'; export type Options = { projectDir: string; + server: string; additionalWatchPaths: string[]; }; @@ -18,7 +19,7 @@ export type Options = { * Compile preview HTML for dev with HMR . */ export const DevPreviewCompilerPlugin = createUnplugin((options) => { - const { projectDir, additionalWatchPaths } = options; + const { projectDir, server, additionalWatchPaths } = options; return { name: PLUGIN_NAME, @@ -52,7 +53,7 @@ export const DevPreviewCompilerPlugin = createUnplugin((options) => { // Compile preview before each compilation in watch mode compiler.hooks.watchRun.tapPromise(PLUGIN_NAME, async () => { - previewHtml = await runSymfonyCommand('storybook:generate-preview'); + previewHtml = await generateSymfonyPreview(server); // Write preview module v.writeModule( diff --git a/storybook/src/server/lib/preview-compiler-plugin.ts b/storybook/src/server/lib/preview-compiler-plugin.ts index 19605b9..ec13a93 100644 --- a/storybook/src/server/lib/preview-compiler-plugin.ts +++ b/storybook/src/server/lib/preview-compiler-plugin.ts @@ -1,5 +1,5 @@ import { createUnplugin } from 'unplugin'; -import { runSymfonyCommand } from './symfony'; +import { generateSymfonyPreview } from './symfony'; import HtmlWebpackPlugin from 'html-webpack-plugin'; import { logger } from '@storybook/node-logger'; import dedent from 'ts-dedent'; @@ -7,10 +7,16 @@ import { injectPreviewHtml } from './injectPreviewHtml'; const PLUGIN_NAME = 'preview-plugin'; +export type Options = { + server: string; +}; + /** * Compile preview HTML. */ -export const PreviewCompilerPlugin = createUnplugin(() => { +export const PreviewCompilerPlugin = createUnplugin((options) => { + const { server } = options; + return { name: PLUGIN_NAME, webpack(compiler) { @@ -20,7 +26,7 @@ export const PreviewCompilerPlugin = createUnplugin(() => { PLUGIN_NAME, async (params) => { try { - const previewHtml = await runSymfonyCommand('storybook:generate-preview'); + const previewHtml = await generateSymfonyPreview(server); params.html = injectPreviewHtml(previewHtml, params.html); return params; diff --git a/storybook/src/server/lib/symfony.test.ts b/storybook/src/server/lib/symfony.test.ts index fb91e18..e8af41f 100644 --- a/storybook/src/server/lib/symfony.test.ts +++ b/storybook/src/server/lib/symfony.test.ts @@ -1,78 +1,61 @@ 'use strict'; -import { exec, ChildProcess, ExecException } from 'child_process'; -import { runSymfonyCommand, runSymfonyCommandJson } from './symfony'; +import { generateSymfonyPreview, getSymfonyConfig } from './symfony'; import { vi } from 'vitest'; - -vi.mock('child_process'); - -function mockExec(error: ExecException | null = null, stdout = '', stderr = '') { - // Vitest mock types don't support signature overload? - // @ts-ignore - vi.mocked(exec).mockImplementation((command: string, callback: (...args) => void) => { - callback(error, stdout, stderr); - return new ChildProcess(); - }); -} +import fs from 'node:fs'; +import dedent from 'ts-dedent'; describe('Symfony utils', () => { beforeEach(() => { - vi.mocked(exec).mockReset(); + vi.clearAllMocks(); }); - describe('runSymfonyCommand', () => { - it('uses default options', async () => { - mockExec(); - - await runSymfonyCommand('command'); - - expect(exec).toHaveBeenCalledWith("'php' 'bin/console' 'command' '-v'", expect.any(Function)); - }); - - it('with custom options', async () => { - mockExec(); - - const options = { - php: '/usr/bin/php', - script: 'custom/bin/console', - }; - await expect(runSymfonyCommand('command', [], options)).resolves.toBe(''); - - expect(exec).toHaveBeenCalledWith( - "'/usr/bin/php' 'custom/bin/console' 'command' '-v'", - expect.any(Function) - ); - }); - - it('rejects on exec failure', async () => { - mockExec({ code: 1, cmd: "'php' 'bin/console' 'command'" } as ExecException, ''); - - await expect(runSymfonyCommand('command')).rejects.toThrow(); - - expect(exec).toHaveBeenCalledWith("'php' 'bin/console' 'command' '-v'", expect.any(Function)); + describe('generateSymfonyPreview', () => { + it('returns a HTML page for preview', async () => { + const html = dedent` + + + Storybook Preview + + + `; + + global.fetch = vi.fn(() => Promise.resolve(new Response(html))); + + const preview = await generateSymfonyPreview('http://localhost:8000'); + + expect(preview).toEqual(html); + expect(fetch).toHaveBeenCalledWith(new URL('http://localhost:8000/_storybook/preview'), { + method: 'GET', + headers: { + Accept: 'text/html', + }, + }); }); - it('accepts input arguments and options', async () => { - mockExec(); + it('throws on fetch failure', async () => { + global.fetch = vi.fn(() => Promise.resolve(new Response('', { status: 500 }))); - await runSymfonyCommand('command', ['arg1', '-o', '--option=foo']); + await expect(generateSymfonyPreview('http://localhost:8000')).rejects.toThrow('Unable to render preview.'); - expect(exec).toHaveBeenCalledWith( - "'php' 'bin/console' 'command' 'arg1' '-o' '--option=foo' '-v'", - expect.any(Function) - ); + expect(fetch).toHaveBeenCalledWith(new URL('http://localhost:8000/_storybook/preview'), { + method: 'GET', + headers: { + Accept: 'text/html', + }, + }); }); }); - describe('runSymfonyCommandJSON', () => { + describe('getSymfonyConfig', () => { it('returns a JS object', async () => { - mockExec(null, '{ "prop": "value" }'); + const storybookCachePath = `${__dirname}/__fixtures__/var/cache/dev/storybook`; - const expected = { - prop: 'value', - }; + const symfonyParameters = JSON.parse( + fs.readFileSync(`${storybookCachePath}/symfony_parameters.json`, 'utf8') + ); - await expect(runSymfonyCommandJson('command')).resolves.toEqual(expected); + await expect(getSymfonyConfig(storybookCachePath)).resolves.toEqual(symfonyParameters); }); }); }); diff --git a/storybook/src/server/lib/symfony.ts b/storybook/src/server/lib/symfony.ts index 16d5281..87a4256 100644 --- a/storybook/src/server/lib/symfony.ts +++ b/storybook/src/server/lib/symfony.ts @@ -1,141 +1,65 @@ -import { exec } from 'child_process'; -import dedent from 'ts-dedent'; +import fs from 'node:fs'; -type CommandOptions = { - /** - * Path to the PHP binary used to execute the command. - */ - php?: string; - - /** - * Path to the Symfony Console entrypoint. - */ - script?: string; -}; - -const defaultOptions: CommandOptions = { - php: 'php', - script: 'bin/console', -}; - -const prepareSymfonyCommand = (command: string, inputs: string[] = [], options: CommandOptions = {}) => { - const finalOptions = { - ...defaultOptions, - ...options, - }; - - return [finalOptions.php, finalOptions.script, command] - .concat([...inputs, '-v']) - .map((part) => `'${part}'`) - .join(' '); -}; +class SymfonyPreviewRenderingError extends Error { + constructor(public readonly errorPage: string) { + super('Unable to render preview.'); + } +} -const execSymfonyCommand = async (finalCommand: string) => { - return new Promise((resolve, reject) => { - exec(finalCommand, (error, stdout, stderr) => { - if (error) { - reject( - new Error(dedent` - Symfony console failed with exit status ${error.code}: - CMD: ${error.cmd} - Output: ${stdout} - Error output: ${stderr} - `) - ); - } +export const generateSymfonyPreview = async (server: string) => { + const fetchUrl = new URL(`${server}/_storybook/preview`); - resolve(stdout); - }); + const response = await fetch(fetchUrl, { + method: 'GET', + headers: { + Accept: 'text/html', + }, }); -}; -/** - * Run a Symfony command. - */ -export const runSymfonyCommand = async (command: string, inputs: string[] = [], options: CommandOptions = {}) => { - const finalCommand = prepareSymfonyCommand(command, inputs, options); + const html = await response.text(); - return execSymfonyCommand(finalCommand); -}; - -/** - * Run a Symfony command with JSON formatted output and get the result as a JS object. - */ -export const runSymfonyCommandJson = async ( - command: string, - inputs: string[] = [], - options: CommandOptions = {} -): Promise => { - const finalCommand = prepareSymfonyCommand(command, [...inputs, '--format=json'], options); - const result = await execSymfonyCommand(finalCommand); - - try { - return JSON.parse(result); - } catch (err) { - throw new Error(dedent` - Failed to process JSON output for Symfony command. - CMD: ${finalCommand} - Raw output: ${result} - `); + if (!response.ok) { + throw new SymfonyPreviewRenderingError(html); } -}; -export const getKernelProjectDir = async () => { - return ( - await runSymfonyCommandJson<{ [p: string]: string }>('debug:container', ['--parameter=kernel.project_dir']) - )['kernel.project_dir']; + return html; }; -type StorybookBundleConfig = { - storybook: { - runtime_dir: string; - }; +type SymfonyConfiguration = { + twig_config: SymfonyTwigConfiguration; + twig_component_config: SymfonyTwigComponentConfiguration; }; -export const getBundleConfig = async () => { - return (await runSymfonyCommandJson('debug:config', ['storybook']))['storybook']; +export const getSymfonyConfig = async (storybookCachePath: string): Promise => { + const filePath = `${storybookCachePath}/symfony_parameters.json`; + + return JSON.parse(fs.readFileSync(filePath, 'utf8')); }; type SymfonyTwigComponentConfiguration = { - twig_component: { - anonymous_template_directory: string; - defaults: { - [p: string]: { - name_prefix: string; - template_directory: string; - }; + anonymous_template_directory: string; + defaults: { + [p: string]: { + name_prefix: string; + template_directory: string; }; }; }; -export const getTwigComponentConfiguration = async () => { - return ( - await runSymfonyCommandJson('debug:config', [ - 'twig_component', - '--resolve-env', - ]) - )['twig_component']; -}; - export type TwigComponentConfiguration = { - anonymousTemplateDirectory: [string]; + anonymousTemplateDirectory: string[]; namespaces: { - [p: string]: [string]; + [p: string]: string[]; }; }; type SymfonyTwigConfiguration = { - twig: { - paths: { - [p: string]: string; - }; + default_path: string; + paths: { + [p: string]: string; }; }; -export const getTwigConfiguration = async () => { - return (await runSymfonyCommandJson('debug:config', ['twig', '--resolve-env']))['twig']; -}; - export type TwigConfiguration = { paths: string[]; }; diff --git a/storybook/src/server/lib/twig-loader-plugin.ts b/storybook/src/server/lib/twig-loader-plugin.ts index c2df15d..41a2ce7 100644 --- a/storybook/src/server/lib/twig-loader-plugin.ts +++ b/storybook/src/server/lib/twig-loader-plugin.ts @@ -10,6 +10,7 @@ const PLUGIN_NAME = 'twig-loader'; export type Options = { twigComponentConfiguration: TwigComponentConfiguration; + projectDir: string; }; /** @@ -18,8 +19,9 @@ export type Options = { * Generates JS modules to export raw template source and imports required components. */ export const TwigLoaderPlugin = createUnplugin((options) => { - const { twigComponentConfiguration } = options; - const resolver = new TwigComponentResolver(twigComponentConfiguration); + const { twigComponentConfiguration, projectDir } = options; + const resolver = new TwigComponentResolver(twigComponentConfiguration, projectDir); + return { name: PLUGIN_NAME, enforce: 'pre', diff --git a/storybook/src/types.ts b/storybook/src/types.ts index ad396b7..b462479 100644 --- a/storybook/src/types.ts +++ b/storybook/src/types.ts @@ -17,6 +17,11 @@ type BuilderName = '@storybook/builder-webpack5'; type ProxyPaths = string[] | string; export type SymfonyOptions = { + /** + * Storybook cache directory. + */ + storybookCachePath: string; + /** * Symfony server URL. */ diff --git a/tests/Functional/Command/GeneratePreviewCommandTest.php b/tests/Functional/Command/GeneratePreviewCommandTest.php deleted file mode 100644 index 62f5858..0000000 --- a/tests/Functional/Command/GeneratePreviewCommandTest.php +++ /dev/null @@ -1,25 +0,0 @@ -find('storybook:generate-preview'); - $commandTester = new CommandTester($command); - $commandTester->execute([]); - - $commandTester->assertCommandIsSuccessful(); - - $this->assertNotEmpty($commandTester->getDisplay()); - } -} diff --git a/tests/Functional/Controller/StorybookPreviewControllerTest.php b/tests/Functional/Controller/StorybookPreviewControllerTest.php new file mode 100644 index 0000000..b874136 --- /dev/null +++ b/tests/Functional/Controller/StorybookPreviewControllerTest.php @@ -0,0 +1,26 @@ +request('GET', '_storybook/preview'); + + $this->assertResponseIsSuccessful(); + + // Check that the preview contains the basic HTML structure + $this->assertSelectorExists('html'); + $this->assertSelectorExists('head'); + $this->assertSelectorExists('body'); + } +} diff --git a/tests/Unit/Command/GeneratePreviewCommandTest.php b/tests/Unit/Command/GeneratePreviewCommandTest.php deleted file mode 100644 index 12a7845..0000000 --- a/tests/Unit/Command/GeneratePreviewCommandTest.php +++ /dev/null @@ -1,30 +0,0 @@ -createMock(Environment::class); - $eventDispatcher = $this->createMock(EventDispatcherInterface::class); - - $command = new GeneratePreviewCommand($twig, $eventDispatcher); - - $twig->method('render')->willReturn(''); - $eventDispatcher - ->expects($this->once()) - ->method('dispatch') - ->with($this->isInstanceOf(GeneratePreviewEvent::class)); - - $command->run($this->createMock(InputInterface::class), $this->createMock(OutputInterface::class)); - } -} diff --git a/tests/Unit/Controller/StorybookPreviewControllerTest.php b/tests/Unit/Controller/StorybookPreviewControllerTest.php new file mode 100644 index 0000000..eeb7529 --- /dev/null +++ b/tests/Unit/Controller/StorybookPreviewControllerTest.php @@ -0,0 +1,33 @@ +createMock(Environment::class); + $eventDispatcher = $this->createMock(EventDispatcherInterface::class); + + $controller = new StorybookPreviewController($twig, $eventDispatcher); + + $twig->expects($this->once()) + ->method('render') + ->with('@Storybook/preview.html.twig') + ->willReturn(''); + + $eventDispatcher + ->expects($this->once()) + ->method('dispatch') + ->with($this->isInstanceOf(GeneratePreviewEvent::class)); + + $this->assertInstanceOf(Response::class, $controller()); + } +}