diff --git a/README.md b/README.md index d581581..e949ef2 100644 --- a/README.md +++ b/README.md @@ -593,6 +593,96 @@ SecureBit.chat: --- +## 🔧 Development Workflow + +### Making Changes and Recompiling + +When you make changes to the source code, you need to recompile the assets. Here's the proper workflow: + +#### 1. **CSS Changes** (Tailwind classes, styles) +```bash +# Rebuild only CSS +npm run build:css + +# Or watch for changes during development +npm run watch +``` + +#### 2. **JavaScript/JSX Changes** (React components, logic) +```bash +# Rebuild only JavaScript +npm run build:js + +# Or rebuild everything +npm run build +``` + +#### 3. **Full Rebuild** (recommended after major changes) +```bash +# Complete rebuild of all assets +npm run build +``` + +#### 4. **Development with Live Server** +```bash +# Build and start development server +npm run dev + +# Or use custom server +npm run serve +``` + +### File Structure After Build + +``` +├── assets/ +│ ├── tailwind.css # ← Generated from src/styles/tw-input.css +│ ├── fontawesome/ # ← Local Font Awesome assets +│ └── fonts/ # ← Local Google Fonts +├── dist/ +│ ├── app.js # ← Generated from src/app.jsx +│ ├── app-boot.js # ← Generated from src/scripts/app-boot.js +│ └── qr-local.js # ← Generated from src/scripts/qr-local.js +└── src/ # ← Source files (edit these) + ├── app.jsx + ├── scripts/ + ├── styles/ + └── components/ +``` + +### Important Notes + +- **Always rebuild after changes** to see them in the browser +- **CSS changes** require `npm run build:css` +- **JS/JSX changes** require `npm run build:js` +- **Source files** are in `src/` directory +- **Generated files** are in `assets/` and `dist/` directories +- **Never edit** files in `assets/` or `dist/` directly + +### Troubleshooting Build Issues + +#### CSS not updating? +```bash +# Clear cache and rebuild +rm assets/tailwind.css +npm run build:css +``` + +#### JavaScript errors? +```bash +# Check for syntax errors in source files +npm run build:js +``` + +#### All changes not showing? +```bash +# Hard refresh browser (Ctrl+F5) or clear browser cache +# Then rebuild everything +npm run build +``` + +--- +
**SecureBit.chat Security Team** diff --git a/assets/tailwind.css b/assets/tailwind.css index a135c34..87bc4f0 100644 --- a/assets/tailwind.css +++ b/assets/tailwind.css @@ -1 +1 @@ -/*! tailwindcss v3.4.10 | MIT License | https://tailwindcss.com*/*,:after,:before{border:0 solid #e5e7eb;box-sizing:border-box}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-tap-highlight-color:transparent}body{line-height:inherit;margin:0}hr{border-top-width:1px;color:inherit;height:0}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-size:1em;font-variation-settings:normal}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{border-collapse:collapse;border-color:inherit;text-indent:0}button,input,optgroup,select,textarea{color:inherit;font-family:inherit;font-feature-settings:inherit;font-size:100%;font-variation-settings:inherit;font-weight:inherit;letter-spacing:inherit;line-height:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{color:#9ca3af;opacity:1}input::placeholder,textarea::placeholder{color:#9ca3af;opacity:1}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{height:auto;max-width:100%}[hidden]{display:none}*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }.container{width:100%}@media (min-width:640px){.container{max-width:640px}}@media (min-width:768px){.container{max-width:768px}}@media (min-width:1024px){.container{max-width:1024px}}@media (min-width:1280px){.container{max-width:1280px}}@media (min-width:1536px){.container{max-width:1536px}}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{inset:0}.-left-2{left:-.5rem}.-right-1{right:-.25rem}.-top-1{top:-.25rem}.-top-10{top:-2.5rem}.-top-2{top:-.5rem}.bottom-0{bottom:0}.bottom-2{bottom:.5rem}.bottom-4{bottom:1rem}.bottom-6{bottom:1.5rem}.left-0{left:0}.left-1\/2{left:50%}.left-2{left:.5rem}.left-4{left:1rem}.right-0{right:0}.right-2{right:.5rem}.right-3{right:.75rem}.right-4{right:1rem}.right-6{right:1.5rem}.right-\[-100px\]{right:-100px}.top-0{top:0}.top-1\/2{top:50%}.top-4{top:1rem}.z-10{z-index:10}.z-40{z-index:40}.z-50{z-index:50}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-2{margin-left:.5rem}.ml-3{margin-left:.75rem}.ml-4{margin-left:1rem}.ml-6{margin-left:1.5rem}.ml-auto{margin-left:auto}.mr-1{margin-right:.25rem}.mr-2{margin-right:.5rem}.mr-3{margin-right:.75rem}.mr-4{margin-right:1rem}.mr-auto{margin-right:auto}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-10{margin-top:2.5rem}.mt-12{margin-top:3rem}.mt-16{margin-top:4rem}.mt-2{margin-top:.5rem}.mt-20{margin-top:5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-1{height:.25rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-16{height:4rem}.h-2{height:.5rem}.h-28{height:7rem}.h-3{height:.75rem}.h-4{height:1rem}.h-48{height:12rem}.h-6{height:1.5rem}.h-8{height:2rem}.h-full{height:100%}.max-h-\[80vh\]{max-height:80vh}.max-h-\[90vh\]{max-height:90vh}.min-h-\[300px\]{min-height:300px}.min-h-\[72px\]{min-height:72px}.min-h-\[calc\(100vh-104px\)\]{min-height:calc(100vh - 104px)}.min-h-screen{min-height:100vh}.w-10{width:2.5rem}.w-12{width:3rem}.w-16{width:4rem}.w-2{width:.5rem}.w-28{width:7rem}.w-3{width:.75rem}.w-4{width:1rem}.w-48{width:12rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-full{width:100%}.min-w-\[160px\]{min-width:160px}.min-w-\[240px\]{min-width:240px}.max-w-2xl{max-width:42rem}.max-w-32{max-width:8rem}.max-w-3xl{max-width:48rem}.max-w-4xl{max-width:56rem}.max-w-5xl{max-width:64rem}.max-w-6xl{max-width:72rem}.max-w-7xl{max-width:80rem}.max-w-lg{max-width:32rem}.max-w-md{max-width:28rem}.max-w-sm{max-width:24rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.border-collapse{border-collapse:collapse}.-translate-x-1\/2{--tw-translate-x:-50%}.-translate-x-1\/2,.-translate-y-1\/2{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y:-50%}.translate-x-full{--tw-translate-x:100%}.translate-x-full,.translate-y-full{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-full{--tw-translate-y:100%}.rotate-180{--tw-rotate:180deg}.rotate-180,.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(1turn)}}.animate-spin{animation:spin 1s linear infinite}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.resize-none{resize:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-center{align-items:center}.items-stretch{align-items:stretch}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-x-1>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(.25rem*(1 - var(--tw-space-x-reverse)));margin-right:calc(.25rem*var(--tw-space-x-reverse))}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(.5rem*(1 - var(--tw-space-x-reverse)));margin-right:calc(.5rem*var(--tw-space-x-reverse))}.space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(.75rem*(1 - var(--tw-space-x-reverse)));margin-right:calc(.75rem*var(--tw-space-x-reverse))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(1rem*(1 - var(--tw-space-x-reverse)));margin-right:calc(1rem*var(--tw-space-x-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.25rem*var(--tw-space-y-reverse));margin-top:calc(.25rem*(1 - var(--tw-space-y-reverse)))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.5rem*var(--tw-space-y-reverse));margin-top:calc(.5rem*(1 - var(--tw-space-y-reverse)))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.75rem*var(--tw-space-y-reverse));margin-top:calc(.75rem*(1 - var(--tw-space-y-reverse)))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(1rem*var(--tw-space-y-reverse));margin-top:calc(1rem*(1 - var(--tw-space-y-reverse)))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(1.5rem*var(--tw-space-y-reverse));margin-top:calc(1.5rem*(1 - var(--tw-space-y-reverse)))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(2rem*var(--tw-space-y-reverse));margin-top:calc(2rem*(1 - var(--tw-space-y-reverse)))}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.scroll-smooth{scroll-behavior:smooth}.whitespace-nowrap{white-space:nowrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-t{border-top-width:1px}.border-blue-200{--tw-border-opacity:1;border-color:rgb(191 219 254/var(--tw-border-opacity))}.border-blue-500{--tw-border-opacity:1;border-color:rgb(59 130 246/var(--tw-border-opacity))}.border-blue-500\/20{border-color:rgba(59,130,246,.2)}.border-blue-500\/30{border-color:rgba(59,130,246,.3)}.border-blue-700\/30{border-color:rgba(29,78,216,.3)}.border-blue-700\/50{border-color:rgba(29,78,216,.5)}.border-cyan-500\/20{border-color:rgba(6,182,212,.2)}.border-gray-200{--tw-border-opacity:1;border-color:rgb(229 231 235/var(--tw-border-opacity))}.border-gray-500\/10{border-color:hsla(220,9%,46%,.1)}.border-gray-500\/20{border-color:hsla(220,9%,46%,.2)}.border-gray-500\/30{border-color:hsla(220,9%,46%,.3)}.border-gray-600{--tw-border-opacity:1;border-color:rgb(75 85 99/var(--tw-border-opacity))}.border-gray-600\/30{border-color:rgba(75,85,99,.3)}.border-gray-700\/30{border-color:rgba(55,65,81,.3)}.border-green-200{--tw-border-opacity:1;border-color:rgb(187 247 208/var(--tw-border-opacity))}.border-green-300{--tw-border-opacity:1;border-color:rgb(134 239 172/var(--tw-border-opacity))}.border-green-500\/20{border-color:rgba(34,197,94,.2)}.border-green-500\/30{border-color:rgba(34,197,94,.3)}.border-orange-500{--tw-border-opacity:1;border-color:rgb(249 115 22/var(--tw-border-opacity))}.border-orange-500\/10{border-color:rgba(249,115,22,.1)}.border-orange-500\/20{border-color:rgba(249,115,22,.2)}.border-orange-500\/30{border-color:rgba(249,115,22,.3)}.border-purple-500\/20{border-color:rgba(168,85,247,.2)}.border-red-300{--tw-border-opacity:1;border-color:rgb(252 165 165/var(--tw-border-opacity))}.border-red-500\/20{border-color:rgba(239,68,68,.2)}.border-yellow-200{--tw-border-opacity:1;border-color:rgb(254 240 138/var(--tw-border-opacity))}.border-yellow-500\/20{border-color:rgba(234,179,8,.2)}.bg-black{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity))}.bg-black\/30{background-color:rgba(0,0,0,.3)}.bg-black\/50{background-color:rgba(0,0,0,.5)}.bg-black\/80{background-color:rgba(0,0,0,.8)}.bg-blue-100{--tw-bg-opacity:1;background-color:rgb(219 234 254/var(--tw-bg-opacity))}.bg-blue-400{--tw-bg-opacity:1;background-color:rgb(96 165 250/var(--tw-bg-opacity))}.bg-blue-50{--tw-bg-opacity:1;background-color:rgb(239 246 255/var(--tw-bg-opacity))}.bg-blue-500{--tw-bg-opacity:1;background-color:rgb(59 130 246/var(--tw-bg-opacity))}.bg-blue-500\/10{background-color:rgba(59,130,246,.1)}.bg-blue-500\/20{background-color:rgba(59,130,246,.2)}.bg-blue-500\/90{background-color:rgba(59,130,246,.9)}.bg-blue-600{--tw-bg-opacity:1;background-color:rgb(37 99 235/var(--tw-bg-opacity))}.bg-blue-900\/20{background-color:rgba(30,58,138,.2)}.bg-cyan-500\/10{background-color:rgba(6,182,212,.1)}.bg-emerald-500{--tw-bg-opacity:1;background-color:rgb(16 185 129/var(--tw-bg-opacity))}.bg-gray-100{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity))}.bg-gray-50{--tw-bg-opacity:1;background-color:rgb(249 250 251/var(--tw-bg-opacity))}.bg-gray-500{--tw-bg-opacity:1;background-color:rgb(107 114 128/var(--tw-bg-opacity))}.bg-gray-500\/10{background-color:hsla(220,9%,46%,.1)}.bg-gray-500\/20{background-color:hsla(220,9%,46%,.2)}.bg-gray-600{--tw-bg-opacity:1;background-color:rgb(75 85 99/var(--tw-bg-opacity))}.bg-gray-600\/80{background-color:rgba(75,85,99,.8)}.bg-gray-700{--tw-bg-opacity:1;background-color:rgb(55 65 81/var(--tw-bg-opacity))}.bg-gray-700\/50{background-color:rgba(55,65,81,.5)}.bg-gray-800{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity))}.bg-gray-800\/50{background-color:rgba(31,41,55,.5)}.bg-gray-800\/95{background-color:rgba(31,41,55,.95)}.bg-gray-900\/30{background-color:rgba(17,24,39,.3)}.bg-green-100{--tw-bg-opacity:1;background-color:rgb(220 252 231/var(--tw-bg-opacity))}.bg-green-200{--tw-bg-opacity:1;background-color:rgb(187 247 208/var(--tw-bg-opacity))}.bg-green-400{--tw-bg-opacity:1;background-color:rgb(74 222 128/var(--tw-bg-opacity))}.bg-green-400\/20{background-color:rgba(74,222,128,.2)}.bg-green-50{--tw-bg-opacity:1;background-color:rgb(240 253 244/var(--tw-bg-opacity))}.bg-green-500{--tw-bg-opacity:1;background-color:rgb(34 197 94/var(--tw-bg-opacity))}.bg-green-500\/10{background-color:rgba(34,197,94,.1)}.bg-green-500\/20{background-color:rgba(34,197,94,.2)}.bg-green-500\/90{background-color:rgba(34,197,94,.9)}.bg-green-600{--tw-bg-opacity:1;background-color:rgb(22 163 74/var(--tw-bg-opacity))}.bg-orange-400{--tw-bg-opacity:1;background-color:rgb(251 146 60/var(--tw-bg-opacity))}.bg-orange-500{--tw-bg-opacity:1;background-color:rgb(249 115 22/var(--tw-bg-opacity))}.bg-orange-500\/10{background-color:rgba(249,115,22,.1)}.bg-orange-500\/15{background-color:rgba(249,115,22,.15)}.bg-orange-500\/20{background-color:rgba(249,115,22,.2)}.bg-orange-500\/5{background-color:rgba(249,115,22,.05)}.bg-orange-600{--tw-bg-opacity:1;background-color:rgb(234 88 12/var(--tw-bg-opacity))}.bg-purple-500\/10{background-color:rgba(168,85,247,.1)}.bg-red-100{--tw-bg-opacity:1;background-color:rgb(254 226 226/var(--tw-bg-opacity))}.bg-red-200{--tw-bg-opacity:1;background-color:rgb(254 202 202/var(--tw-bg-opacity))}.bg-red-400{--tw-bg-opacity:1;background-color:rgb(248 113 113/var(--tw-bg-opacity))}.bg-red-500{--tw-bg-opacity:1;background-color:rgb(239 68 68/var(--tw-bg-opacity))}.bg-red-500\/10{background-color:rgba(239,68,68,.1)}.bg-red-500\/20{background-color:rgba(239,68,68,.2)}.bg-red-500\/90{background-color:rgba(239,68,68,.9)}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity))}.bg-white\/20{background-color:hsla(0,0%,100%,.2)}.bg-yellow-400{--tw-bg-opacity:1;background-color:rgb(250 204 21/var(--tw-bg-opacity))}.bg-yellow-50{--tw-bg-opacity:1;background-color:rgb(254 252 232/var(--tw-bg-opacity))}.bg-yellow-500{--tw-bg-opacity:1;background-color:rgb(234 179 8/var(--tw-bg-opacity))}.bg-yellow-500\/10{background-color:rgba(234,179,8,.1)}.bg-yellow-500\/20{background-color:rgba(234,179,8,.2)}.bg-yellow-500\/90{background-color:rgba(234,179,8,.9)}.bg-opacity-50{--tw-bg-opacity:0.5}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-blue-900\/20{--tw-gradient-from:rgba(30,58,138,.2) var(--tw-gradient-from-position);--tw-gradient-to:rgba(30,58,138,0) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.from-gray-800\/20{--tw-gradient-from:rgba(31,41,55,.2) var(--tw-gradient-from-position);--tw-gradient-to:rgba(31,41,55,0) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.from-orange-500{--tw-gradient-from:#f97316 var(--tw-gradient-from-position);--tw-gradient-to:rgba(249,115,22,0) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.from-orange-500\/10{--tw-gradient-from:rgba(249,115,22,.1) var(--tw-gradient-from-position);--tw-gradient-to:rgba(249,115,22,0) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.to-gray-900\/20{--tw-gradient-to:rgba(17,24,39,.2) var(--tw-gradient-to-position)}.to-orange-600{--tw-gradient-to:#ea580c var(--tw-gradient-to-position)}.to-purple-900\/20{--tw-gradient-to:rgba(88,28,135,.2) var(--tw-gradient-to-position)}.to-yellow-500\/10{--tw-gradient-to:rgba(234,179,8,.1) var(--tw-gradient-to-position)}.fill-blue-500{fill:#3b82f6}.fill-white{fill:#fff}.p-1\.5{padding:.375rem}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-1{padding-bottom:.25rem;padding-top:.25rem}.py-1\.5{padding-bottom:.375rem;padding-top:.375rem}.py-2{padding-bottom:.5rem;padding-top:.5rem}.py-3{padding-bottom:.75rem;padding-top:.75rem}.py-4{padding-bottom:1rem;padding-top:1rem}.pr-2{padding-right:.5rem}.pt-4{padding-top:1rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-6xl{font-size:3.75rem;line-height:1}.text-\[300px\]{font-size:300px}.text-\[3rem\]{font-size:3rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.lowercase{text-transform:lowercase}.leading-relaxed{line-height:1.625}.leading-tight{line-height:1.25}.text-black{--tw-text-opacity:1;color:rgb(0 0 0/var(--tw-text-opacity))}.text-blue-200{--tw-text-opacity:1;color:rgb(191 219 254/var(--tw-text-opacity))}.text-blue-300{--tw-text-opacity:1;color:rgb(147 197 253/var(--tw-text-opacity))}.text-blue-400{--tw-text-opacity:1;color:rgb(96 165 250/var(--tw-text-opacity))}.text-blue-500{--tw-text-opacity:1;color:rgb(59 130 246/var(--tw-text-opacity))}.text-blue-600{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity))}.text-blue-700{--tw-text-opacity:1;color:rgb(29 78 216/var(--tw-text-opacity))}.text-blue-800{--tw-text-opacity:1;color:rgb(30 64 175/var(--tw-text-opacity))}.text-cyan-300{--tw-text-opacity:1;color:rgb(103 232 249/var(--tw-text-opacity))}.text-cyan-400{--tw-text-opacity:1;color:rgb(34 211 238/var(--tw-text-opacity))}.text-cyan-500{--tw-text-opacity:1;color:rgb(6 182 212/var(--tw-text-opacity))}.text-emerald-500{--tw-text-opacity:1;color:rgb(16 185 129/var(--tw-text-opacity))}.text-gray-300{--tw-text-opacity:1;color:rgb(209 213 219/var(--tw-text-opacity))}.text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175/var(--tw-text-opacity))}.text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity))}.text-gray-600{--tw-text-opacity:1;color:rgb(75 85 99/var(--tw-text-opacity))}.text-gray-800{--tw-text-opacity:1;color:rgb(31 41 55/var(--tw-text-opacity))}.text-green-300{--tw-text-opacity:1;color:rgb(134 239 172/var(--tw-text-opacity))}.text-green-400{--tw-text-opacity:1;color:rgb(74 222 128/var(--tw-text-opacity))}.text-green-500{--tw-text-opacity:1;color:rgb(34 197 94/var(--tw-text-opacity))}.text-green-600{--tw-text-opacity:1;color:rgb(22 163 74/var(--tw-text-opacity))}.text-green-700{--tw-text-opacity:1;color:rgb(21 128 61/var(--tw-text-opacity))}.text-green-800{--tw-text-opacity:1;color:rgb(22 101 52/var(--tw-text-opacity))}.text-orange-200{--tw-text-opacity:1;color:rgb(254 215 170/var(--tw-text-opacity))}.text-orange-300{--tw-text-opacity:1;color:rgb(253 186 116/var(--tw-text-opacity))}.text-orange-400{--tw-text-opacity:1;color:rgb(251 146 60/var(--tw-text-opacity))}.text-orange-500{--tw-text-opacity:1;color:rgb(249 115 22/var(--tw-text-opacity))}.text-purple-400{--tw-text-opacity:1;color:rgb(192 132 252/var(--tw-text-opacity))}.text-purple-500{--tw-text-opacity:1;color:rgb(168 85 247/var(--tw-text-opacity))}.text-red-200{--tw-text-opacity:1;color:rgb(254 202 202/var(--tw-text-opacity))}.text-red-300{--tw-text-opacity:1;color:rgb(252 165 165/var(--tw-text-opacity))}.text-red-400{--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity))}.text-red-500{--tw-text-opacity:1;color:rgb(239 68 68/var(--tw-text-opacity))}.text-red-700{--tw-text-opacity:1;color:rgb(185 28 28/var(--tw-text-opacity))}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.text-white\/10{color:hsla(0,0%,100%,.1)}.text-yellow-200{--tw-text-opacity:1;color:rgb(254 240 138/var(--tw-text-opacity))}.text-yellow-300{--tw-text-opacity:1;color:rgb(253 224 71/var(--tw-text-opacity))}.text-yellow-400{--tw-text-opacity:1;color:rgb(250 204 21/var(--tw-text-opacity))}.text-yellow-500{--tw-text-opacity:1;color:rgb(234 179 8/var(--tw-text-opacity))}.text-yellow-600{--tw-text-opacity:1;color:rgb(202 138 4/var(--tw-text-opacity))}.text-yellow-700{--tw-text-opacity:1;color:rgb(161 98 7/var(--tw-text-opacity))}.text-yellow-800{--tw-text-opacity:1;color:rgb(133 77 14/var(--tw-text-opacity))}.underline{text-decoration-line:underline}.placeholder-gray-400::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(156 163 175/var(--tw-placeholder-opacity))}.placeholder-gray-400::placeholder{--tw-placeholder-opacity:1;color:rgb(156 163 175/var(--tw-placeholder-opacity))}.placeholder-gray-500::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(107 114 128/var(--tw-placeholder-opacity))}.placeholder-gray-500::placeholder{--tw-placeholder-opacity:1;color:rgb(107 114 128/var(--tw-placeholder-opacity))}.opacity-0{opacity:0}.opacity-10{opacity:.1}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-90{opacity:.9}.shadow-2xl{--tw-shadow:0 25px 50px -12px rgba(0,0,0,.25);--tw-shadow-colored:0 25px 50px -12px var(--tw-shadow-color)}.shadow-2xl,.shadow-lg{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px rgba(0,0,0,.1),0 4px 6px -4px rgba(0,0,0,.1);--tw-shadow-colored:0 10px 15px -3px var(--tw-shadow-color),0 4px 6px -4px var(--tw-shadow-color)}.shadow-xl{--tw-shadow:0 20px 25px -5px rgba(0,0,0,.1),0 8px 10px -6px rgba(0,0,0,.1);--tw-shadow-colored:0 20px 25px -5px var(--tw-shadow-color),0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.ring-2{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.ring-orange-500\/30{--tw-ring-color:rgba(249,115,22,.3)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur:blur(12px)}.backdrop-blur-md,.backdrop-blur-sm{-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur:blur(4px)}.transition-all{transition-duration:.15s;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1)}.transition-colors{transition-duration:.15s;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1)}.transition-opacity{transition-duration:.15s;transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1)}.transition-transform{transition-duration:.15s;transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1)}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.\[checksum\:4\]{checksum:4}.\[data\:variable\]{data:variable}.\[name\:4\]{name:4}.\[size\:4\]{size:4}.hover\:scale-125:hover{--tw-scale-x:1.25;--tw-scale-y:1.25;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:border-gray-300:hover{--tw-border-opacity:1;border-color:rgb(209 213 219/var(--tw-border-opacity))}.hover\:border-orange-400:hover{--tw-border-opacity:1;border-color:rgb(251 146 60/var(--tw-border-opacity))}.hover\:bg-blue-200:hover{--tw-bg-opacity:1;background-color:rgb(191 219 254/var(--tw-bg-opacity))}.hover\:bg-blue-500:hover{--tw-bg-opacity:1;background-color:rgb(59 130 246/var(--tw-bg-opacity))}.hover\:bg-blue-600:hover{--tw-bg-opacity:1;background-color:rgb(37 99 235/var(--tw-bg-opacity))}.hover\:bg-blue-700:hover{--tw-bg-opacity:1;background-color:rgb(29 78 216/var(--tw-bg-opacity))}.hover\:bg-emerald-600:hover{--tw-bg-opacity:1;background-color:rgb(5 150 105/var(--tw-bg-opacity))}.hover\:bg-gray-500:hover{--tw-bg-opacity:1;background-color:rgb(107 114 128/var(--tw-bg-opacity))}.hover\:bg-gray-500\/80:hover{background-color:hsla(220,9%,46%,.8)}.hover\:bg-gray-600:hover{--tw-bg-opacity:1;background-color:rgb(75 85 99/var(--tw-bg-opacity))}.hover\:bg-gray-700:hover{--tw-bg-opacity:1;background-color:rgb(55 65 81/var(--tw-bg-opacity))}.hover\:bg-gray-700\/50:hover{background-color:rgba(55,65,81,.5)}.hover\:bg-gray-800\/30:hover{background-color:rgba(31,41,55,.3)}.hover\:bg-green-500:hover{--tw-bg-opacity:1;background-color:rgb(34 197 94/var(--tw-bg-opacity))}.hover\:bg-green-500\/20:hover{background-color:rgba(34,197,94,.2)}.hover\:bg-green-500\/30:hover{background-color:rgba(34,197,94,.3)}.hover\:bg-green-600:hover{--tw-bg-opacity:1;background-color:rgb(22 163 74/var(--tw-bg-opacity))}.hover\:bg-orange-500:hover{--tw-bg-opacity:1;background-color:rgb(249 115 22/var(--tw-bg-opacity))}.hover\:bg-orange-500\/20:hover{background-color:rgba(249,115,22,.2)}.hover\:bg-orange-600:hover{--tw-bg-opacity:1;background-color:rgb(234 88 12/var(--tw-bg-opacity))}.hover\:bg-red-200:hover{--tw-bg-opacity:1;background-color:rgb(254 202 202/var(--tw-bg-opacity))}.hover\:bg-red-500\/20:hover{background-color:rgba(239,68,68,.2)}.hover\:bg-red-600:hover{--tw-bg-opacity:1;background-color:rgb(220 38 38/var(--tw-bg-opacity))}.hover\:bg-white\/30:hover{background-color:hsla(0,0%,100%,.3)}.hover\:bg-yellow-500\/20:hover{background-color:rgba(234,179,8,.2)}.hover\:from-orange-600:hover{--tw-gradient-from:#ea580c var(--tw-gradient-from-position);--tw-gradient-to:rgba(234,88,12,0) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.hover\:to-orange-700:hover{--tw-gradient-to:#c2410c var(--tw-gradient-to-position)}.hover\:text-blue-300:hover{--tw-text-opacity:1;color:rgb(147 197 253/var(--tw-text-opacity))}.hover\:text-gray-300:hover{--tw-text-opacity:1;color:rgb(209 213 219/var(--tw-text-opacity))}.hover\:text-gray-600:hover{--tw-text-opacity:1;color:rgb(75 85 99/var(--tw-text-opacity))}.hover\:text-gray-700:hover{--tw-text-opacity:1;color:rgb(55 65 81/var(--tw-text-opacity))}.hover\:text-gray-800:hover{--tw-text-opacity:1;color:rgb(31 41 55/var(--tw-text-opacity))}.hover\:text-green-300:hover{--tw-text-opacity:1;color:rgb(134 239 172/var(--tw-text-opacity))}.hover\:text-orange-300:hover{--tw-text-opacity:1;color:rgb(253 186 116/var(--tw-text-opacity))}.hover\:text-red-300:hover{--tw-text-opacity:1;color:rgb(252 165 165/var(--tw-text-opacity))}.hover\:text-white:hover{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.hover\:opacity-100:hover{opacity:1}.hover\:opacity-80:hover{opacity:.8}.focus\:border-green-500\/40:focus{border-color:rgba(34,197,94,.4)}.focus\:border-orange-500\/40:focus{border-color:rgba(249,115,22,.4)}.focus\:border-purple-500\/40:focus{border-color:rgba(168,85,247,.4)}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:bg-gray-400:disabled{--tw-bg-opacity:1;background-color:rgb(156 163 175/var(--tw-bg-opacity))}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:scale-105{--tw-scale-x:1.05;--tw-scale-y:1.05}.group:hover .group-hover\:scale-105,.group:hover .group-hover\:scale-110{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-110{--tw-scale-x:1.1;--tw-scale-y:1.1}.group:hover .group-hover\:opacity-100{opacity:1}@media (min-width:640px){.sm\:mb-0{margin-bottom:0}.sm\:mb-3{margin-bottom:.75rem}.sm\:mr-2{margin-right:.5rem}.sm\:block{display:block}.sm\:inline{display:inline}.sm\:flex{display:flex}.sm\:h-10{height:2.5rem}.sm\:h-12{height:3rem}.sm\:w-10{width:2.5rem}.sm\:w-12{width:3rem}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-4{gap:1rem}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(.5rem*(1 - var(--tw-space-x-reverse)));margin-right:calc(.5rem*var(--tw-space-x-reverse))}.sm\:space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(.75rem*(1 - var(--tw-space-x-reverse)));margin-right:calc(.75rem*var(--tw-space-x-reverse))}.sm\:space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(1rem*(1 - var(--tw-space-x-reverse)));margin-right:calc(1rem*var(--tw-space-x-reverse))}.sm\:space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(0px*var(--tw-space-y-reverse));margin-top:calc(0px*(1 - var(--tw-space-y-reverse)))}.sm\:p-4{padding:1rem}.sm\:px-0{padding-left:0;padding-right:0}.sm\:px-3{padding-left:.75rem;padding-right:.75rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:py-1\.5{padding-bottom:.375rem;padding-top:.375rem}.sm\:text-base{font-size:1rem;line-height:1.5rem}.sm\:text-sm{font-size:.875rem;line-height:1.25rem}.sm\:text-xl{font-size:1.25rem;line-height:1.75rem}}@media (min-width:768px){.md\:flex{display:flex}.md\:hidden{display:none}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}@media (min-width:1024px){.lg\:block{display:block}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:px-8{padding-left:2rem;padding-right:2rem}} \ No newline at end of file +*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.17 | MIT License | https://tailwindcss.com*/*,:after,:before{box-sizing:border-box;border:0 solid #e5e7eb}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.container{width:100%}@media (min-width:640px){.container{max-width:640px}}@media (min-width:768px){.container{max-width:768px}}@media (min-width:1024px){.container{max-width:1024px}}@media (min-width:1280px){.container{max-width:1280px}}@media (min-width:1536px){.container{max-width:1536px}}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{inset:0}.-left-2{left:-.5rem}.-right-1{right:-.25rem}.-top-1{top:-.25rem}.-top-10{top:-2.5rem}.-top-2{top:-.5rem}.bottom-0{bottom:0}.bottom-2{bottom:.5rem}.bottom-4{bottom:1rem}.bottom-6{bottom:1.5rem}.left-0{left:0}.left-1\/2{left:50%}.left-2{left:.5rem}.left-4{left:1rem}.right-0{right:0}.right-2{right:.5rem}.right-3{right:.75rem}.right-4{right:1rem}.right-6{right:1.5rem}.right-\[-100px\]{right:-100px}.top-0{top:0}.top-1\/2{top:50%}.top-4{top:1rem}.z-10{z-index:10}.z-40{z-index:40}.z-50{z-index:50}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-2{margin-left:.5rem}.ml-3{margin-left:.75rem}.ml-4{margin-left:1rem}.ml-6{margin-left:1.5rem}.ml-auto{margin-left:auto}.mr-1{margin-right:.25rem}.mr-2{margin-right:.5rem}.mr-3{margin-right:.75rem}.mr-4{margin-right:1rem}.mr-auto{margin-right:auto}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-10{margin-top:2.5rem}.mt-12{margin-top:3rem}.mt-16{margin-top:4rem}.mt-2{margin-top:.5rem}.mt-20{margin-top:5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-1{height:.25rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-16{height:4rem}.h-2{height:.5rem}.h-28{height:7rem}.h-3{height:.75rem}.h-4{height:1rem}.h-48{height:12rem}.h-6{height:1.5rem}.h-8{height:2rem}.h-full{height:100%}.max-h-\[80vh\]{max-height:80vh}.max-h-\[90vh\]{max-height:90vh}.min-h-\[300px\]{min-height:300px}.min-h-\[72px\]{min-height:72px}.min-h-\[calc\(100vh-104px\)\]{min-height:calc(100vh - 104px)}.min-h-screen{min-height:100vh}.w-10{width:2.5rem}.w-12{width:3rem}.w-16{width:4rem}.w-2{width:.5rem}.w-28{width:7rem}.w-3{width:.75rem}.w-4{width:1rem}.w-48{width:12rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-full{width:100%}.min-w-\[160px\]{min-width:160px}.min-w-\[240px\]{min-width:240px}.max-w-2xl{max-width:42rem}.max-w-32{max-width:8rem}.max-w-3xl{max-width:48rem}.max-w-4xl{max-width:56rem}.max-w-5xl{max-width:64rem}.max-w-6xl{max-width:72rem}.max-w-7xl{max-width:80rem}.max-w-lg{max-width:32rem}.max-w-md{max-width:28rem}.max-w-sm{max-width:24rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.border-collapse{border-collapse:collapse}.-translate-x-1\/2{--tw-translate-x:-50%}.-translate-x-1\/2,.-translate-y-1\/2{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y:-50%}.translate-x-full{--tw-translate-x:100%}.translate-x-full,.translate-y-full{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-full{--tw-translate-y:100%}.rotate-180{--tw-rotate:180deg}.rotate-180,.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(1turn)}}.animate-spin{animation:spin 1s linear infinite}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.resize-none{resize:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-center{align-items:center}.items-stretch{align-items:stretch}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-x-1>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-right:calc(.25rem*var(--tw-space-x-reverse));margin-left:calc(.25rem*(1 - var(--tw-space-x-reverse)))}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-right:calc(.5rem*var(--tw-space-x-reverse));margin-left:calc(.5rem*(1 - var(--tw-space-x-reverse)))}.space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-right:calc(.75rem*var(--tw-space-x-reverse));margin-left:calc(.75rem*(1 - var(--tw-space-x-reverse)))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-right:calc(1rem*var(--tw-space-x-reverse));margin-left:calc(1rem*(1 - var(--tw-space-x-reverse)))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(.25rem*(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem*var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(.5rem*(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem*var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(.75rem*(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem*var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(1rem*(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem*var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(1.5rem*(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem*var(--tw-space-y-reverse))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(2rem*(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem*var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.scroll-smooth{scroll-behavior:smooth}.whitespace-nowrap{white-space:nowrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-t{border-top-width:1px}.border-blue-200{--tw-border-opacity:1;border-color:rgb(191 219 254/var(--tw-border-opacity,1))}.border-blue-500{--tw-border-opacity:1;border-color:rgb(59 130 246/var(--tw-border-opacity,1))}.border-blue-500\/20{border-color:rgba(59,130,246,.2)}.border-blue-500\/30{border-color:rgba(59,130,246,.3)}.border-blue-700\/30{border-color:rgba(29,78,216,.3)}.border-blue-700\/50{border-color:rgba(29,78,216,.5)}.border-cyan-500\/20{border-color:rgba(6,182,212,.2)}.border-gray-200{--tw-border-opacity:1;border-color:rgb(229 231 235/var(--tw-border-opacity,1))}.border-gray-500\/10{border-color:hsla(220,9%,46%,.1)}.border-gray-500\/20{border-color:hsla(220,9%,46%,.2)}.border-gray-500\/30{border-color:hsla(220,9%,46%,.3)}.border-gray-600{--tw-border-opacity:1;border-color:rgb(75 85 99/var(--tw-border-opacity,1))}.border-gray-600\/30{border-color:rgba(75,85,99,.3)}.border-gray-700\/30{border-color:rgba(55,65,81,.3)}.border-green-200{--tw-border-opacity:1;border-color:rgb(187 247 208/var(--tw-border-opacity,1))}.border-green-300{--tw-border-opacity:1;border-color:rgb(134 239 172/var(--tw-border-opacity,1))}.border-green-500\/20{border-color:rgba(34,197,94,.2)}.border-green-500\/30{border-color:rgba(34,197,94,.3)}.border-orange-500{--tw-border-opacity:1;border-color:rgb(249 115 22/var(--tw-border-opacity,1))}.border-orange-500\/10{border-color:rgba(249,115,22,.1)}.border-orange-500\/20{border-color:rgba(249,115,22,.2)}.border-orange-500\/30{border-color:rgba(249,115,22,.3)}.border-purple-500\/20{border-color:rgba(168,85,247,.2)}.border-red-300{--tw-border-opacity:1;border-color:rgb(252 165 165/var(--tw-border-opacity,1))}.border-red-500\/20{border-color:rgba(239,68,68,.2)}.border-yellow-200{--tw-border-opacity:1;border-color:rgb(254 240 138/var(--tw-border-opacity,1))}.border-yellow-500\/20{border-color:rgba(234,179,8,.2)}.bg-black{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity,1))}.bg-black\/30{background-color:rgba(0,0,0,.3)}.bg-black\/50{background-color:rgba(0,0,0,.5)}.bg-black\/80{background-color:rgba(0,0,0,.8)}.bg-blue-100{--tw-bg-opacity:1;background-color:rgb(219 234 254/var(--tw-bg-opacity,1))}.bg-blue-400{--tw-bg-opacity:1;background-color:rgb(96 165 250/var(--tw-bg-opacity,1))}.bg-blue-50{--tw-bg-opacity:1;background-color:rgb(239 246 255/var(--tw-bg-opacity,1))}.bg-blue-500{--tw-bg-opacity:1;background-color:rgb(59 130 246/var(--tw-bg-opacity,1))}.bg-blue-500\/10{background-color:rgba(59,130,246,.1)}.bg-blue-500\/20{background-color:rgba(59,130,246,.2)}.bg-blue-500\/90{background-color:rgba(59,130,246,.9)}.bg-blue-600{--tw-bg-opacity:1;background-color:rgb(37 99 235/var(--tw-bg-opacity,1))}.bg-blue-900\/20{background-color:rgba(30,58,138,.2)}.bg-cyan-500\/10{background-color:rgba(6,182,212,.1)}.bg-emerald-500{--tw-bg-opacity:1;background-color:rgb(16 185 129/var(--tw-bg-opacity,1))}.bg-gray-100{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity,1))}.bg-gray-50{--tw-bg-opacity:1;background-color:rgb(249 250 251/var(--tw-bg-opacity,1))}.bg-gray-500{--tw-bg-opacity:1;background-color:rgb(107 114 128/var(--tw-bg-opacity,1))}.bg-gray-500\/10{background-color:hsla(220,9%,46%,.1)}.bg-gray-500\/20{background-color:hsla(220,9%,46%,.2)}.bg-gray-600{--tw-bg-opacity:1;background-color:rgb(75 85 99/var(--tw-bg-opacity,1))}.bg-gray-600\/80{background-color:rgba(75,85,99,.8)}.bg-gray-700{--tw-bg-opacity:1;background-color:rgb(55 65 81/var(--tw-bg-opacity,1))}.bg-gray-700\/50{background-color:rgba(55,65,81,.5)}.bg-gray-800{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity,1))}.bg-gray-800\/50{background-color:rgba(31,41,55,.5)}.bg-gray-800\/95{background-color:rgba(31,41,55,.95)}.bg-gray-900\/30{background-color:rgba(17,24,39,.3)}.bg-green-100{--tw-bg-opacity:1;background-color:rgb(220 252 231/var(--tw-bg-opacity,1))}.bg-green-200{--tw-bg-opacity:1;background-color:rgb(187 247 208/var(--tw-bg-opacity,1))}.bg-green-400{--tw-bg-opacity:1;background-color:rgb(74 222 128/var(--tw-bg-opacity,1))}.bg-green-400\/20{background-color:rgba(74,222,128,.2)}.bg-green-50{--tw-bg-opacity:1;background-color:rgb(240 253 244/var(--tw-bg-opacity,1))}.bg-green-500{--tw-bg-opacity:1;background-color:rgb(34 197 94/var(--tw-bg-opacity,1))}.bg-green-500\/10{background-color:rgba(34,197,94,.1)}.bg-green-500\/20{background-color:rgba(34,197,94,.2)}.bg-green-500\/90{background-color:rgba(34,197,94,.9)}.bg-green-600{--tw-bg-opacity:1;background-color:rgb(22 163 74/var(--tw-bg-opacity,1))}.bg-orange-400{--tw-bg-opacity:1;background-color:rgb(251 146 60/var(--tw-bg-opacity,1))}.bg-orange-500{--tw-bg-opacity:1;background-color:rgb(249 115 22/var(--tw-bg-opacity,1))}.bg-orange-500\/10{background-color:rgba(249,115,22,.1)}.bg-orange-500\/15{background-color:rgba(249,115,22,.15)}.bg-orange-500\/20{background-color:rgba(249,115,22,.2)}.bg-orange-500\/5{background-color:rgba(249,115,22,.05)}.bg-orange-600{--tw-bg-opacity:1;background-color:rgb(234 88 12/var(--tw-bg-opacity,1))}.bg-purple-500\/10{background-color:rgba(168,85,247,.1)}.bg-red-100{--tw-bg-opacity:1;background-color:rgb(254 226 226/var(--tw-bg-opacity,1))}.bg-red-200{--tw-bg-opacity:1;background-color:rgb(254 202 202/var(--tw-bg-opacity,1))}.bg-red-400{--tw-bg-opacity:1;background-color:rgb(248 113 113/var(--tw-bg-opacity,1))}.bg-red-500{--tw-bg-opacity:1;background-color:rgb(239 68 68/var(--tw-bg-opacity,1))}.bg-red-500\/10{background-color:rgba(239,68,68,.1)}.bg-red-500\/20{background-color:rgba(239,68,68,.2)}.bg-red-500\/90{background-color:rgba(239,68,68,.9)}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity,1))}.bg-white\/20{background-color:hsla(0,0%,100%,.2)}.bg-yellow-400{--tw-bg-opacity:1;background-color:rgb(250 204 21/var(--tw-bg-opacity,1))}.bg-yellow-50{--tw-bg-opacity:1;background-color:rgb(254 252 232/var(--tw-bg-opacity,1))}.bg-yellow-500{--tw-bg-opacity:1;background-color:rgb(234 179 8/var(--tw-bg-opacity,1))}.bg-yellow-500\/10{background-color:rgba(234,179,8,.1)}.bg-yellow-500\/20{background-color:rgba(234,179,8,.2)}.bg-yellow-500\/90{background-color:rgba(234,179,8,.9)}.bg-opacity-50{--tw-bg-opacity:0.5}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-blue-900\/20{--tw-gradient-from:rgba(30,58,138,.2) var(--tw-gradient-from-position);--tw-gradient-to:rgba(30,58,138,0) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.from-gray-800\/20{--tw-gradient-from:rgba(31,41,55,.2) var(--tw-gradient-from-position);--tw-gradient-to:rgba(31,41,55,0) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.from-orange-500{--tw-gradient-from:#f97316 var(--tw-gradient-from-position);--tw-gradient-to:rgba(249,115,22,0) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.from-orange-500\/10{--tw-gradient-from:rgba(249,115,22,.1) var(--tw-gradient-from-position);--tw-gradient-to:rgba(249,115,22,0) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.to-gray-900\/20{--tw-gradient-to:rgba(17,24,39,.2) var(--tw-gradient-to-position)}.to-orange-600{--tw-gradient-to:#ea580c var(--tw-gradient-to-position)}.to-purple-900\/20{--tw-gradient-to:rgba(88,28,135,.2) var(--tw-gradient-to-position)}.to-yellow-500\/10{--tw-gradient-to:rgba(234,179,8,.1) var(--tw-gradient-to-position)}.fill-blue-500{fill:#3b82f6}.fill-white{fill:#fff}.p-1\.5{padding:.375rem}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.pr-2{padding-right:.5rem}.pt-4{padding-top:1rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-6xl{font-size:3.75rem;line-height:1}.text-\[300px\]{font-size:300px}.text-\[3rem\]{font-size:3rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.lowercase{text-transform:lowercase}.leading-relaxed{line-height:1.625}.leading-tight{line-height:1.25}.text-black{--tw-text-opacity:1;color:rgb(0 0 0/var(--tw-text-opacity,1))}.text-blue-200{--tw-text-opacity:1;color:rgb(191 219 254/var(--tw-text-opacity,1))}.text-blue-300{--tw-text-opacity:1;color:rgb(147 197 253/var(--tw-text-opacity,1))}.text-blue-400{--tw-text-opacity:1;color:rgb(96 165 250/var(--tw-text-opacity,1))}.text-blue-500{--tw-text-opacity:1;color:rgb(59 130 246/var(--tw-text-opacity,1))}.text-blue-600{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.text-blue-700{--tw-text-opacity:1;color:rgb(29 78 216/var(--tw-text-opacity,1))}.text-blue-800{--tw-text-opacity:1;color:rgb(30 64 175/var(--tw-text-opacity,1))}.text-cyan-300{--tw-text-opacity:1;color:rgb(103 232 249/var(--tw-text-opacity,1))}.text-cyan-400{--tw-text-opacity:1;color:rgb(34 211 238/var(--tw-text-opacity,1))}.text-cyan-500{--tw-text-opacity:1;color:rgb(6 182 212/var(--tw-text-opacity,1))}.text-emerald-500{--tw-text-opacity:1;color:rgb(16 185 129/var(--tw-text-opacity,1))}.text-gray-300{--tw-text-opacity:1;color:rgb(209 213 219/var(--tw-text-opacity,1))}.text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175/var(--tw-text-opacity,1))}.text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity,1))}.text-gray-600{--tw-text-opacity:1;color:rgb(75 85 99/var(--tw-text-opacity,1))}.text-gray-800{--tw-text-opacity:1;color:rgb(31 41 55/var(--tw-text-opacity,1))}.text-green-300{--tw-text-opacity:1;color:rgb(134 239 172/var(--tw-text-opacity,1))}.text-green-400{--tw-text-opacity:1;color:rgb(74 222 128/var(--tw-text-opacity,1))}.text-green-500{--tw-text-opacity:1;color:rgb(34 197 94/var(--tw-text-opacity,1))}.text-green-600{--tw-text-opacity:1;color:rgb(22 163 74/var(--tw-text-opacity,1))}.text-green-700{--tw-text-opacity:1;color:rgb(21 128 61/var(--tw-text-opacity,1))}.text-green-800{--tw-text-opacity:1;color:rgb(22 101 52/var(--tw-text-opacity,1))}.text-orange-200{--tw-text-opacity:1;color:rgb(254 215 170/var(--tw-text-opacity,1))}.text-orange-300{--tw-text-opacity:1;color:rgb(253 186 116/var(--tw-text-opacity,1))}.text-orange-400{--tw-text-opacity:1;color:rgb(251 146 60/var(--tw-text-opacity,1))}.text-orange-500{--tw-text-opacity:1;color:rgb(249 115 22/var(--tw-text-opacity,1))}.text-purple-400{--tw-text-opacity:1;color:rgb(192 132 252/var(--tw-text-opacity,1))}.text-purple-500{--tw-text-opacity:1;color:rgb(168 85 247/var(--tw-text-opacity,1))}.text-red-200{--tw-text-opacity:1;color:rgb(254 202 202/var(--tw-text-opacity,1))}.text-red-300{--tw-text-opacity:1;color:rgb(252 165 165/var(--tw-text-opacity,1))}.text-red-400{--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity,1))}.text-red-500{--tw-text-opacity:1;color:rgb(239 68 68/var(--tw-text-opacity,1))}.text-red-700{--tw-text-opacity:1;color:rgb(185 28 28/var(--tw-text-opacity,1))}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.text-white\/10{color:hsla(0,0%,100%,.1)}.text-yellow-200{--tw-text-opacity:1;color:rgb(254 240 138/var(--tw-text-opacity,1))}.text-yellow-300{--tw-text-opacity:1;color:rgb(253 224 71/var(--tw-text-opacity,1))}.text-yellow-400{--tw-text-opacity:1;color:rgb(250 204 21/var(--tw-text-opacity,1))}.text-yellow-500{--tw-text-opacity:1;color:rgb(234 179 8/var(--tw-text-opacity,1))}.text-yellow-600{--tw-text-opacity:1;color:rgb(202 138 4/var(--tw-text-opacity,1))}.text-yellow-700{--tw-text-opacity:1;color:rgb(161 98 7/var(--tw-text-opacity,1))}.text-yellow-800{--tw-text-opacity:1;color:rgb(133 77 14/var(--tw-text-opacity,1))}.underline{text-decoration-line:underline}.placeholder-gray-400::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(156 163 175/var(--tw-placeholder-opacity,1))}.placeholder-gray-400::placeholder{--tw-placeholder-opacity:1;color:rgb(156 163 175/var(--tw-placeholder-opacity,1))}.placeholder-gray-500::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(107 114 128/var(--tw-placeholder-opacity,1))}.placeholder-gray-500::placeholder{--tw-placeholder-opacity:1;color:rgb(107 114 128/var(--tw-placeholder-opacity,1))}.opacity-0{opacity:0}.opacity-10{opacity:.1}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-90{opacity:.9}.shadow-2xl{--tw-shadow:0 25px 50px -12px rgba(0,0,0,.25);--tw-shadow-colored:0 25px 50px -12px var(--tw-shadow-color)}.shadow-2xl,.shadow-lg{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px rgba(0,0,0,.1),0 4px 6px -4px rgba(0,0,0,.1);--tw-shadow-colored:0 10px 15px -3px var(--tw-shadow-color),0 4px 6px -4px var(--tw-shadow-color)}.shadow-xl{--tw-shadow:0 20px 25px -5px rgba(0,0,0,.1),0 8px 10px -6px rgba(0,0,0,.1);--tw-shadow-colored:0 20px 25px -5px var(--tw-shadow-color),0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.ring-2{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.ring-orange-400{--tw-ring-opacity:1;--tw-ring-color:rgb(251 146 60/var(--tw-ring-opacity,1))}.ring-orange-500\/30{--tw-ring-color:rgba(249,115,22,.3)}.ring-offset-2{--tw-ring-offset-width:2px}.ring-offset-black\/30{--tw-ring-offset-color:rgba(0,0,0,.3)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur:blur(12px)}.backdrop-blur-md,.backdrop-blur-sm{-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur:blur(4px)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.\[checksum\:4\]{checksum:4}.\[data\:variable\]{data:variable}.\[name\:4\]{name:4}.\[size\:4\]{size:4}.hover\:scale-125:hover{--tw-scale-x:1.25;--tw-scale-y:1.25;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:border-gray-300:hover{--tw-border-opacity:1;border-color:rgb(209 213 219/var(--tw-border-opacity,1))}.hover\:border-orange-400:hover{--tw-border-opacity:1;border-color:rgb(251 146 60/var(--tw-border-opacity,1))}.hover\:bg-blue-200:hover{--tw-bg-opacity:1;background-color:rgb(191 219 254/var(--tw-bg-opacity,1))}.hover\:bg-blue-500:hover{--tw-bg-opacity:1;background-color:rgb(59 130 246/var(--tw-bg-opacity,1))}.hover\:bg-blue-600:hover{--tw-bg-opacity:1;background-color:rgb(37 99 235/var(--tw-bg-opacity,1))}.hover\:bg-blue-700:hover{--tw-bg-opacity:1;background-color:rgb(29 78 216/var(--tw-bg-opacity,1))}.hover\:bg-emerald-600:hover{--tw-bg-opacity:1;background-color:rgb(5 150 105/var(--tw-bg-opacity,1))}.hover\:bg-gray-500:hover{--tw-bg-opacity:1;background-color:rgb(107 114 128/var(--tw-bg-opacity,1))}.hover\:bg-gray-500\/80:hover{background-color:hsla(220,9%,46%,.8)}.hover\:bg-gray-600:hover{--tw-bg-opacity:1;background-color:rgb(75 85 99/var(--tw-bg-opacity,1))}.hover\:bg-gray-700:hover{--tw-bg-opacity:1;background-color:rgb(55 65 81/var(--tw-bg-opacity,1))}.hover\:bg-gray-700\/50:hover{background-color:rgba(55,65,81,.5)}.hover\:bg-gray-800\/30:hover{background-color:rgba(31,41,55,.3)}.hover\:bg-green-500:hover{--tw-bg-opacity:1;background-color:rgb(34 197 94/var(--tw-bg-opacity,1))}.hover\:bg-green-500\/20:hover{background-color:rgba(34,197,94,.2)}.hover\:bg-green-500\/30:hover{background-color:rgba(34,197,94,.3)}.hover\:bg-green-600:hover{--tw-bg-opacity:1;background-color:rgb(22 163 74/var(--tw-bg-opacity,1))}.hover\:bg-orange-500:hover{--tw-bg-opacity:1;background-color:rgb(249 115 22/var(--tw-bg-opacity,1))}.hover\:bg-orange-500\/20:hover{background-color:rgba(249,115,22,.2)}.hover\:bg-orange-600:hover{--tw-bg-opacity:1;background-color:rgb(234 88 12/var(--tw-bg-opacity,1))}.hover\:bg-red-200:hover{--tw-bg-opacity:1;background-color:rgb(254 202 202/var(--tw-bg-opacity,1))}.hover\:bg-red-500\/20:hover{background-color:rgba(239,68,68,.2)}.hover\:bg-red-600:hover{--tw-bg-opacity:1;background-color:rgb(220 38 38/var(--tw-bg-opacity,1))}.hover\:bg-white\/30:hover{background-color:hsla(0,0%,100%,.3)}.hover\:bg-yellow-500\/20:hover{background-color:rgba(234,179,8,.2)}.hover\:from-orange-600:hover{--tw-gradient-from:#ea580c var(--tw-gradient-from-position);--tw-gradient-to:rgba(234,88,12,0) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.hover\:to-orange-700:hover{--tw-gradient-to:#c2410c var(--tw-gradient-to-position)}.hover\:text-blue-300:hover{--tw-text-opacity:1;color:rgb(147 197 253/var(--tw-text-opacity,1))}.hover\:text-gray-300:hover{--tw-text-opacity:1;color:rgb(209 213 219/var(--tw-text-opacity,1))}.hover\:text-gray-600:hover{--tw-text-opacity:1;color:rgb(75 85 99/var(--tw-text-opacity,1))}.hover\:text-gray-700:hover{--tw-text-opacity:1;color:rgb(55 65 81/var(--tw-text-opacity,1))}.hover\:text-gray-800:hover{--tw-text-opacity:1;color:rgb(31 41 55/var(--tw-text-opacity,1))}.hover\:text-green-300:hover{--tw-text-opacity:1;color:rgb(134 239 172/var(--tw-text-opacity,1))}.hover\:text-orange-300:hover{--tw-text-opacity:1;color:rgb(253 186 116/var(--tw-text-opacity,1))}.hover\:text-red-300:hover{--tw-text-opacity:1;color:rgb(252 165 165/var(--tw-text-opacity,1))}.hover\:text-white:hover{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.hover\:opacity-100:hover{opacity:1}.hover\:opacity-80:hover{opacity:.8}.focus\:border-green-500\/40:focus{border-color:rgba(34,197,94,.4)}.focus\:border-orange-500\/40:focus{border-color:rgba(249,115,22,.4)}.focus\:border-purple-500\/40:focus{border-color:rgba(168,85,247,.4)}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:bg-gray-400:disabled{--tw-bg-opacity:1;background-color:rgb(156 163 175/var(--tw-bg-opacity,1))}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:scale-105{--tw-scale-x:1.05;--tw-scale-y:1.05}.group:hover .group-hover\:scale-105,.group:hover .group-hover\:scale-110{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-110{--tw-scale-x:1.1;--tw-scale-y:1.1}.group:hover .group-hover\:opacity-100{opacity:1}@media (min-width:640px){.sm\:mb-0{margin-bottom:0}.sm\:mb-3{margin-bottom:.75rem}.sm\:mr-2{margin-right:.5rem}.sm\:block{display:block}.sm\:inline{display:inline}.sm\:flex{display:flex}.sm\:h-10{height:2.5rem}.sm\:h-12{height:3rem}.sm\:w-10{width:2.5rem}.sm\:w-12{width:3rem}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-4{gap:1rem}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-right:calc(.5rem*var(--tw-space-x-reverse));margin-left:calc(.5rem*(1 - var(--tw-space-x-reverse)))}.sm\:space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-right:calc(.75rem*var(--tw-space-x-reverse));margin-left:calc(.75rem*(1 - var(--tw-space-x-reverse)))}.sm\:space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-right:calc(1rem*var(--tw-space-x-reverse));margin-left:calc(1rem*(1 - var(--tw-space-x-reverse)))}.sm\:space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(0px*(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px*var(--tw-space-y-reverse))}.sm\:p-4{padding:1rem}.sm\:px-0{padding-left:0;padding-right:0}.sm\:px-3{padding-left:.75rem;padding-right:.75rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.sm\:text-base{font-size:1rem;line-height:1.5rem}.sm\:text-sm{font-size:.875rem;line-height:1.25rem}.sm\:text-xl{font-size:1.25rem;line-height:1.75rem}}@media (min-width:768px){.md\:flex{display:flex}.md\:hidden{display:none}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}@media (min-width:1024px){.lg\:block{display:block}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:px-8{padding-left:2rem;padding-right:2rem}} \ No newline at end of file diff --git a/build.ps1 b/build.ps1 new file mode 100644 index 0000000..9c6390e --- /dev/null +++ b/build.ps1 @@ -0,0 +1,83 @@ +# SecureBit.chat Build Script +# PowerShell script for building the application + +Write-Host "🔨 Building SecureBit.chat..." -ForegroundColor Green + +# Check if Node.js is installed +if (!(Get-Command node -ErrorAction SilentlyContinue)) { + Write-Host "❌ Node.js is not installed. Please install Node.js first." -ForegroundColor Red + exit 1 +} + +# Check if npm is installed +if (!(Get-Command npm -ErrorAction SilentlyContinue)) { + Write-Host "❌ npm is not installed. Please install npm first." -ForegroundColor Red + exit 1 +} + +# Install dependencies if needed +if (!(Test-Path "node_modules")) { + Write-Host "📦 Installing dependencies..." -ForegroundColor Yellow + npm install +} + +# Install build tools if needed +Write-Host "🛠️ Installing build tools..." -ForegroundColor Yellow +npm install -D tailwindcss esbuild +npm install qrcode + +# Create directories if they don't exist +if (!(Test-Path "dist")) { New-Item -ItemType Directory -Path "dist" } +if (!(Test-Path "assets")) { New-Item -ItemType Directory -Path "assets" } + +# Build CSS +Write-Host "🎨 Building Tailwind CSS..." -ForegroundColor Cyan +try { + npx tailwindcss -i src/styles/tw-input.css -o assets/tailwind.css --minify --content "./index.html,./src/**/*.jsx,./src/**/*.js" + Write-Host "✅ CSS build completed" -ForegroundColor Green +} catch { + Write-Host "❌ CSS build failed: $_" -ForegroundColor Red + exit 1 +} + +# Build JavaScript files +Write-Host "⚡ Building JavaScript files..." -ForegroundColor Cyan + +# Build main app +try { + npx esbuild src/app.jsx --bundle --format=esm --outfile=dist/app.js --sourcemap + Write-Host "✅ Main app build completed" -ForegroundColor Green +} catch { + Write-Host "❌ Main app build failed: $_" -ForegroundColor Red + exit 1 +} + +# Build app bootstrap +try { + npx esbuild src/scripts/app-boot.js --bundle --format=esm --outfile=dist/app-boot.js --sourcemap + Write-Host "✅ App bootstrap build completed" -ForegroundColor Green +} catch { + Write-Host "❌ App bootstrap build failed: $_" -ForegroundColor Red + exit 1 +} + +# Build QR generator +try { + npx esbuild src/scripts/qr-local.js --bundle --format=esm --outfile=dist/qr-local.js --sourcemap + Write-Host "✅ QR generator build completed" -ForegroundColor Green +} catch { + Write-Host "❌ QR generator build failed: $_" -ForegroundColor Red + exit 1 +} + +Write-Host "🎉 Build completed successfully!" -ForegroundColor Green +Write-Host "📁 Output files:" -ForegroundColor Yellow +Write-Host " - assets/tailwind.css" -ForegroundColor White +Write-Host " - dist/app.js" -ForegroundColor White +Write-Host " - dist/app-boot.js" -ForegroundColor White +Write-Host " - dist/qr-local.js" -ForegroundColor White + +Write-Host "`n🚀 You can now serve the application with:" -ForegroundColor Cyan +Write-Host " python -m http.server 8000" -ForegroundColor White +Write-Host " or" -ForegroundColor White +Write-Host " npx http-server" -ForegroundColor White diff --git a/dist/app-boot.js b/dist/app-boot.js index 90fe11a..7d72c22 100644 --- a/dist/app-boot.js +++ b/dist/app-boot.js @@ -5009,10 +5009,6 @@ var EnhancedSecureWebRTCManager = class _EnhancedSecureWebRTCManager { this._originalConsole?.error?.("\u{1F6A8} CRITICAL: Logging system disabled due to security violations"); } } - /** - * Shim to redirect arbitrary console.log calls to _secureLog('info', ...) - * Fixed syntax errors and improved error handling - */ _secureLogShim(...args) { try { if (!Array.isArray(args) || args.length === 0) { @@ -5041,10 +5037,6 @@ var EnhancedSecureWebRTCManager = class _EnhancedSecureWebRTCManager { } } } - /** - * Redirects global console.log to this instance's secure logger - * Improved error handling and validation - */ /** * Setup own logger without touching global console */ diff --git a/dist/app-boot.js.map b/dist/app-boot.js.map index 5871ae8..e990dc6 100644 --- a/dist/app-boot.js.map +++ b/dist/app-boot.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["../src/crypto/EnhancedSecureCryptoUtils.js", "../src/transfer/EnhancedSecureFileTransfer.js", "../src/network/EnhancedSecureWebRTCManager.js", "../src/session/PayPerSessionManager.js", "../src/components/ui/SessionTimer.jsx", "../src/components/ui/Header.jsx", "../src/components/ui/SessionTypeSelector.jsx", "../src/components/ui/LightningPayment.jsx", "../src/components/ui/PaymentModal.jsx", "../src/components/ui/DownloadApps.jsx", "../src/components/ui/FileTransfer.jsx", "../src/scripts/app-boot.js"], - "sourcesContent": ["class EnhancedSecureCryptoUtils {\n\n static _keyMetadata = new WeakMap();\n \n // Initialize secure logging system after class definition\n\n // Utility to sort object keys for deterministic serialization\n static sortObjectKeys(obj) {\n if (typeof obj !== 'object' || obj === null) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(EnhancedSecureCryptoUtils.sortObjectKeys);\n }\n\n const sortedObj = {};\n Object.keys(obj).sort().forEach(key => {\n sortedObj[key] = EnhancedSecureCryptoUtils.sortObjectKeys(obj[key]);\n });\n return sortedObj;\n }\n\n // Utility to assert CryptoKey type and properties\n static assertCryptoKey(key, expectedName = null, expectedUsages = []) {\n if (!(key instanceof CryptoKey)) throw new Error('Expected CryptoKey');\n if (expectedName && key.algorithm?.name !== expectedName) {\n throw new Error(`Expected algorithm ${expectedName}, got ${key.algorithm?.name}`);\n }\n for (const u of expectedUsages) {\n if (!key.usages || !key.usages.includes(u)) {\n throw new Error(`Missing required key usage: ${u}`);\n }\n }\n }\n // Helper function to convert ArrayBuffer to Base64\n static arrayBufferToBase64(buffer) {\n let binary = '';\n const bytes = new Uint8Array(buffer);\n const len = bytes.byteLength;\n for (let i = 0; i < len; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n }\n\n // Helper function to convert Base64 to ArrayBuffer\n static base64ToArrayBuffer(base64) {\n try {\n // Validate input\n if (typeof base64 !== 'string' || !base64) {\n throw new Error('Invalid base64 input: must be a non-empty string');\n }\n\n // Remove any whitespace and validate base64 format\n const cleanBase64 = base64.trim();\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(cleanBase64)) {\n throw new Error('Invalid base64 format');\n }\n\n // Handle empty string case\n if (cleanBase64 === '') {\n return new ArrayBuffer(0);\n }\n\n const binaryString = atob(cleanBase64);\n const len = binaryString.length;\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes.buffer;\n } catch (error) {\n console.error('Base64 to ArrayBuffer conversion failed:', error.message);\n throw new Error(`Base64 conversion error: ${error.message}`);\n }\n }\n\n // Helper function to convert hex string to Uint8Array\n static hexToUint8Array(hexString) {\n try {\n if (!hexString || typeof hexString !== 'string') {\n throw new Error('Invalid hex string input: must be a non-empty string');\n }\n\n // Remove colons and spaces from hex string (e.g., \"aa:bb:cc\" -> \"aabbcc\")\n const cleanHex = hexString.replace(/:/g, '').replace(/\\s/g, '');\n \n // Validate hex format\n if (!/^[0-9a-fA-F]*$/.test(cleanHex)) {\n throw new Error('Invalid hex format: contains non-hex characters');\n }\n \n // Ensure even length\n if (cleanHex.length % 2 !== 0) {\n throw new Error('Invalid hex format: odd length');\n }\n\n // Convert hex string to bytes\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = parseInt(cleanHex.substr(i, 2), 16);\n }\n \n return bytes;\n } catch (error) {\n console.error('Hex to Uint8Array conversion failed:', error.message);\n throw new Error(`Hex conversion error: ${error.message}`);\n }\n }\n\n static async encryptData(data, password) {\n try {\n const dataString = typeof data === 'string' ? data : JSON.stringify(data);\n const salt = crypto.getRandomValues(new Uint8Array(16));\n const encoder = new TextEncoder();\n const passwordBuffer = encoder.encode(password);\n\n const keyMaterial = await crypto.subtle.importKey(\n 'raw',\n passwordBuffer,\n { name: 'PBKDF2' },\n false,\n ['deriveKey']\n );\n\n const key = await crypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt: salt,\n iterations: 100000,\n hash: 'SHA-256',\n },\n keyMaterial,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt']\n );\n\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const dataBuffer = encoder.encode(dataString);\n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: iv },\n key,\n dataBuffer\n );\n\n const encryptedPackage = {\n version: '1.0',\n salt: Array.from(salt),\n iv: Array.from(iv),\n data: Array.from(new Uint8Array(encrypted)),\n timestamp: Date.now(),\n };\n\n const packageString = JSON.stringify(encryptedPackage);\n return EnhancedSecureCryptoUtils.arrayBufferToBase64(new TextEncoder().encode(packageString).buffer);\n\n } catch (error) {\n console.error('Encryption failed:', error.message);\n throw new Error(`Encryption error: ${error.message}`);\n }\n }\n\n static async decryptData(encryptedData, password) {\n try {\n const packageBuffer = EnhancedSecureCryptoUtils.base64ToArrayBuffer(encryptedData);\n const packageString = new TextDecoder().decode(packageBuffer);\n const encryptedPackage = JSON.parse(packageString);\n\n if (!encryptedPackage.version || !encryptedPackage.salt || !encryptedPackage.iv || !encryptedPackage.data) {\n throw new Error('Invalid encrypted data format');\n }\n\n const salt = new Uint8Array(encryptedPackage.salt);\n const iv = new Uint8Array(encryptedPackage.iv);\n const encrypted = new Uint8Array(encryptedPackage.data);\n\n const encoder = new TextEncoder();\n const passwordBuffer = encoder.encode(password);\n\n const keyMaterial = await crypto.subtle.importKey(\n 'raw',\n passwordBuffer,\n { name: 'PBKDF2' },\n false,\n ['deriveKey']\n );\n\n const key = await crypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt: salt,\n iterations: 100000,\n hash: 'SHA-256'\n },\n keyMaterial,\n { name: 'AES-GCM', length: 256 },\n false,\n ['decrypt']\n );\n\n const decrypted = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv },\n key,\n encrypted\n );\n\n const decryptedString = new TextDecoder().decode(decrypted);\n\n try {\n return JSON.parse(decryptedString);\n } catch {\n return decryptedString;\n }\n\n } catch (error) {\n console.error('Decryption failed:', error.message);\n throw new Error(`Decryption error: ${error.message}`);\n }\n }\n\n \n // Generate secure password for data exchange\n static generateSecurePassword() {\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;:,.<>?';\n const length = 32; \n const randomValues = new Uint32Array(length);\n crypto.getRandomValues(randomValues);\n \n let password = '';\n for (let i = 0; i < length; i++) {\n password += chars[randomValues[i] % chars.length];\n }\n return password;\n }\n\n // Real security level calculation with actual verification\n static async calculateSecurityLevel(securityManager) {\n let score = 0;\n const maxScore = 100; // Fixed: Changed from 110 to 100 for cleaner percentage\n const verificationResults = {};\n \n try {\n // Fallback to basic calculation if securityManager is not fully initialized\n if (!securityManager || !securityManager.securityFeatures) {\n console.warn('Security manager not fully initialized, using fallback calculation');\n return {\n level: 'INITIALIZING',\n score: 0,\n color: 'gray',\n verificationResults: {},\n timestamp: Date.now(),\n details: 'Security system initializing...',\n isRealData: false\n };\n }\n\n // Check session type to determine available features\n const sessionType = securityManager.currentSessionType || 'demo';\n const isDemoSession = sessionType === 'demo';\n \n // 1. Base encryption verification (20 points) - Available in demo\n try {\n if (await EnhancedSecureCryptoUtils.verifyEncryption(securityManager)) {\n score += 20;\n verificationResults.encryption = { passed: true, details: 'AES-GCM encryption verified', points: 20 };\n } else {\n verificationResults.encryption = { passed: false, details: 'Encryption not working', points: 0 };\n }\n } catch (error) {\n verificationResults.encryption = { passed: false, details: `Encryption check failed: ${error.message}`, points: 0 };\n }\n \n // 2. Simple key exchange verification (15 points) - Available in demo\n try {\n if (await EnhancedSecureCryptoUtils.verifyECDHKeyExchange(securityManager)) {\n score += 15;\n verificationResults.keyExchange = { passed: true, details: 'Simple key exchange verified', points: 15 };\n } else {\n verificationResults.keyExchange = { passed: false, details: 'Key exchange failed', points: 0 };\n }\n } catch (error) {\n verificationResults.keyExchange = { passed: false, details: `Key exchange check failed: ${error.message}`, points: 0 };\n }\n \n // 3. Message integrity verification (10 points) - Available in demo\n if (await EnhancedSecureCryptoUtils.verifyMessageIntegrity(securityManager)) {\n score += 10;\n verificationResults.messageIntegrity = { passed: true, details: 'Message integrity verified', points: 10 };\n } else {\n verificationResults.messageIntegrity = { passed: false, details: 'Message integrity failed', points: 0 };\n }\n \n // 4. Rate limiting verification (5 points) - Available in demo\n if (await EnhancedSecureCryptoUtils.verifyRateLimiting(securityManager)) {\n score += 5;\n verificationResults.rateLimiting = { passed: true, details: 'Rate limiting active', points: 5 };\n } else {\n verificationResults.rateLimiting = { passed: false, details: 'Rate limiting not working', points: 0 };\n }\n \n // 5. ECDSA signatures verification (15 points) - Only for enhanced sessions\n if (!isDemoSession && await EnhancedSecureCryptoUtils.verifyECDSASignatures(securityManager)) {\n score += 15;\n verificationResults.ecdsa = { passed: true, details: 'ECDSA signatures verified', points: 15 };\n } else {\n const reason = isDemoSession ? 'Enhanced session required - feature not available' : 'ECDSA signatures failed';\n verificationResults.ecdsa = { passed: false, details: reason, points: 0 };\n }\n \n // 6. Metadata protection verification (10 points) - Only for enhanced sessions\n if (!isDemoSession && await EnhancedSecureCryptoUtils.verifyMetadataProtection(securityManager)) {\n score += 10;\n verificationResults.metadataProtection = { passed: true, details: 'Metadata protection verified', points: 10 };\n } else {\n const reason = isDemoSession ? 'Enhanced session required - feature not available' : 'Metadata protection failed';\n verificationResults.metadataProtection = { passed: false, details: reason, points: 0 };\n }\n \n // 7. Perfect Forward Secrecy verification (10 points) - Only for enhanced sessions\n if (!isDemoSession && await EnhancedSecureCryptoUtils.verifyPFS(securityManager)) {\n score += 10;\n verificationResults.pfs = { passed: true, details: 'Perfect Forward Secrecy active', points: 10 };\n } else {\n const reason = isDemoSession ? 'Enhanced session required - feature not available' : 'PFS not active';\n verificationResults.pfs = { passed: false, details: reason, points: 0 };\n }\n \n // 8. Nested encryption verification (5 points) - Only for enhanced sessions\n if (!isDemoSession && await EnhancedSecureCryptoUtils.verifyNestedEncryption(securityManager)) {\n score += 5;\n verificationResults.nestedEncryption = { passed: true, details: 'Nested encryption active', points: 5 };\n } else {\n const reason = isDemoSession ? 'Enhanced session required - feature not available' : 'Nested encryption failed';\n verificationResults.nestedEncryption = { passed: false, details: reason, points: 0 };\n }\n \n // 9. Packet padding verification (5 points) - Only for enhanced sessions\n if (!isDemoSession && await EnhancedSecureCryptoUtils.verifyPacketPadding(securityManager)) {\n score += 5;\n verificationResults.packetPadding = { passed: true, details: 'Packet padding active', points: 5 };\n } else {\n const reason = isDemoSession ? 'Enhanced session required - feature not available' : 'Packet padding failed';\n verificationResults.packetPadding = { passed: false, details: reason, points: 0 };\n }\n \n // 10. Advanced features verification (10 points) - Only for premium sessions\n if (sessionType === 'premium' && await EnhancedSecureCryptoUtils.verifyAdvancedFeatures(securityManager)) {\n score += 10;\n verificationResults.advancedFeatures = { passed: true, details: 'Advanced features active', points: 10 };\n } else {\n const reason = sessionType === 'demo' ? 'Premium session required - feature not available' : \n sessionType === 'basic' ? 'Premium session required - feature not available' : 'Advanced features failed';\n verificationResults.advancedFeatures = { passed: false, details: reason, points: 0 };\n }\n \n const percentage = Math.round((score / maxScore) * 100);\n \n // Calculate available checks based on session type\n const availableChecks = isDemoSession ? 4 : 10; // Demo: encryption(20) + key exchange(15) + message integrity(10) + rate limiting(5) = 50 points\n const passedChecks = Object.values(verificationResults).filter(r => r.passed).length;\n \n const result = {\n level: percentage >= 85 ? 'HIGH' : percentage >= 65 ? 'MEDIUM' : percentage >= 35 ? 'LOW' : 'CRITICAL',\n score: percentage,\n color: percentage >= 85 ? 'green' : percentage >= 65 ? 'orange' : percentage >= 35 ? 'yellow' : 'red',\n verificationResults,\n timestamp: Date.now(),\n details: `Real verification: ${score}/${maxScore} security checks passed (${passedChecks}/${availableChecks} available)`,\n isRealData: true,\n passedChecks: passedChecks,\n totalChecks: availableChecks,\n sessionType: sessionType,\n maxPossibleScore: isDemoSession ? 50 : 100 // Demo sessions can only get max 50 points (4 checks)\n };\n \n console.log('Real security level calculated:', {\n score: percentage,\n level: result.level,\n passedChecks: passedChecks,\n totalChecks: availableChecks,\n sessionType: sessionType,\n maxPossibleScore: result.maxPossibleScore\n });\n \n return result;\n } catch (error) {\n console.error('Security level calculation failed:', error.message);\n return {\n level: 'UNKNOWN',\n score: 0,\n color: 'red',\n verificationResults: {},\n timestamp: Date.now(),\n details: `Verification failed: ${error.message}`,\n isRealData: false\n };\n }\n }\n\n // Real verification functions\n static async verifyEncryption(securityManager) {\n try {\n if (!securityManager.encryptionKey) return false;\n \n // Test actual encryption/decryption\n const testData = 'Test encryption verification';\n const encoder = new TextEncoder();\n const testBuffer = encoder.encode(testData);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n \n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n securityManager.encryptionKey,\n testBuffer\n );\n \n const decrypted = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv },\n securityManager.encryptionKey,\n encrypted\n );\n \n const decryptedText = new TextDecoder().decode(decrypted);\n return decryptedText === testData;\n } catch (error) {\n console.error('Encryption verification failed:', error.message);\n return false;\n }\n }\n \n static async verifyECDHKeyExchange(securityManager) {\n try {\n if (!securityManager.ecdhKeyPair || !securityManager.ecdhKeyPair.privateKey || !securityManager.ecdhKeyPair.publicKey) {\n return false;\n }\n \n // Test that keys are actually ECDH keys\n const keyType = securityManager.ecdhKeyPair.privateKey.algorithm.name;\n const curve = securityManager.ecdhKeyPair.privateKey.algorithm.namedCurve;\n \n return keyType === 'ECDH' && (curve === 'P-384' || curve === 'P-256');\n } catch (error) {\n console.error('ECDH verification failed:', error.message);\n return false;\n }\n }\n \n static async verifyECDSASignatures(securityManager) {\n try {\n if (!securityManager.ecdsaKeyPair || !securityManager.ecdsaKeyPair.privateKey || !securityManager.ecdsaKeyPair.publicKey) {\n return false;\n }\n \n // Test actual signing and verification\n const testData = 'Test ECDSA signature verification';\n const encoder = new TextEncoder();\n const testBuffer = encoder.encode(testData);\n \n const signature = await crypto.subtle.sign(\n { name: 'ECDSA', hash: 'SHA-256' },\n securityManager.ecdsaKeyPair.privateKey,\n testBuffer\n );\n \n const isValid = await crypto.subtle.verify(\n { name: 'ECDSA', hash: 'SHA-256' },\n securityManager.ecdsaKeyPair.publicKey,\n signature,\n testBuffer\n );\n \n return isValid;\n } catch (error) {\n console.error('ECDSA verification failed:', error.message);\n return false;\n }\n }\n \n static async verifyMessageIntegrity(securityManager) {\n try {\n // Check if macKey exists and is a valid CryptoKey\n if (!securityManager.macKey || !(securityManager.macKey instanceof CryptoKey)) {\n console.warn('MAC key not available or invalid for message integrity verification');\n return false;\n }\n \n // Test message integrity with HMAC\n const testData = 'Test message integrity verification';\n const encoder = new TextEncoder();\n const testBuffer = encoder.encode(testData);\n \n const hmac = await crypto.subtle.sign(\n { name: 'HMAC', hash: 'SHA-256' },\n securityManager.macKey,\n testBuffer\n );\n \n const isValid = await crypto.subtle.verify(\n { name: 'HMAC', hash: 'SHA-256' },\n securityManager.macKey,\n hmac,\n testBuffer\n );\n \n return isValid;\n } catch (error) {\n console.error('Message integrity verification failed:', error.message);\n return false;\n }\n }\n \n static async verifyNestedEncryption(securityManager) {\n try {\n // Check if nestedEncryptionKey exists and is a valid CryptoKey\n if (!securityManager.nestedEncryptionKey || !(securityManager.nestedEncryptionKey instanceof CryptoKey)) {\n console.warn('Nested encryption key not available or invalid');\n return false;\n }\n \n // Test nested encryption\n const testData = 'Test nested encryption verification';\n const encoder = new TextEncoder();\n const testBuffer = encoder.encode(testData);\n \n // Simulate nested encryption\n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: crypto.getRandomValues(new Uint8Array(12)) },\n securityManager.nestedEncryptionKey,\n testBuffer\n );\n \n return encrypted && encrypted.byteLength > 0;\n } catch (error) {\n console.error('Nested encryption verification failed:', error.message);\n return false;\n }\n }\n \n static async verifyPacketPadding(securityManager) {\n try {\n if (!securityManager.paddingConfig || !securityManager.paddingConfig.enabled) return false;\n \n // Test packet padding functionality\n const testData = 'Test packet padding verification';\n const encoder = new TextEncoder();\n const testBuffer = encoder.encode(testData);\n \n // Simulate packet padding\n const paddingSize = Math.floor(Math.random() * (securityManager.paddingConfig.maxPadding - securityManager.paddingConfig.minPadding)) + securityManager.paddingConfig.minPadding;\n const paddedData = new Uint8Array(testBuffer.byteLength + paddingSize);\n paddedData.set(new Uint8Array(testBuffer), 0);\n \n return paddedData.byteLength >= testBuffer.byteLength + securityManager.paddingConfig.minPadding;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Packet padding verification failed', { error: error.message });\n return false;\n }\n }\n \n static async verifyAdvancedFeatures(securityManager) {\n try {\n // Test advanced features like traffic obfuscation, fake traffic, etc.\n const hasFakeTraffic = securityManager.fakeTrafficConfig && securityManager.fakeTrafficConfig.enabled;\n const hasDecoyChannels = securityManager.decoyChannelsConfig && securityManager.decoyChannelsConfig.enabled;\n const hasAntiFingerprinting = securityManager.antiFingerprintingConfig && securityManager.antiFingerprintingConfig.enabled;\n \n return hasFakeTraffic || hasDecoyChannels || hasAntiFingerprinting;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Advanced features verification failed', { error: error.message });\n return false;\n }\n }\n \n static async verifyMutualAuth(securityManager) {\n try {\n if (!securityManager.isVerified || !securityManager.verificationCode) return false;\n \n // Test mutual authentication\n return securityManager.isVerified && securityManager.verificationCode.length > 0;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Mutual auth verification failed', { error: error.message });\n return false;\n }\n }\n \n static async verifyMetadataProtection(securityManager) {\n try {\n if (!securityManager.metadataKey) return false;\n \n // Test metadata protection\n const testData = 'Test metadata protection verification';\n const encoder = new TextEncoder();\n const testBuffer = encoder.encode(testData);\n \n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: crypto.getRandomValues(new Uint8Array(12)) },\n securityManager.metadataKey,\n testBuffer\n );\n \n return encrypted && encrypted.byteLength > 0;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Metadata protection verification failed', { error: error.message });\n return false;\n }\n }\n \n static async verifyReplayProtection(securityManager) {\n try {\n if (!securityManager.processedMessageIds || !securityManager.sequenceNumber) return false;\n \n // Test replay protection\n const testId = Date.now().toString();\n if (securityManager.processedMessageIds.has(testId)) return false;\n \n securityManager.processedMessageIds.add(testId);\n return true;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Replay protection verification failed', { error: error.message });\n return false;\n }\n }\n \n static async verifyNonExtractableKeys(securityManager) {\n try {\n if (!securityManager.encryptionKey) return false;\n \n // Test if keys are non-extractable\n const keyData = await crypto.subtle.exportKey('raw', securityManager.encryptionKey);\n return keyData && keyData.byteLength > 0;\n } catch (error) {\n // If export fails, keys are non-extractable (which is good)\n return true;\n }\n }\n \n static async verifyEnhancedValidation(securityManager) {\n try {\n if (!securityManager.securityFeatures) return false;\n \n // Test enhanced validation features\n const hasValidation = securityManager.securityFeatures.hasEnhancedValidation || \n securityManager.securityFeatures.hasEnhancedReplayProtection;\n \n return hasValidation;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Enhanced validation verification failed', { error: error.message });\n return false;\n }\n }\n \n static async verifyRateLimiting(securityManager) {\n try {\n const testId = 'test_' + Date.now();\n const canProceed = await EnhancedSecureCryptoUtils.rateLimiter.checkMessageRate(testId, 1, 60000);\n \n return securityManager.rateLimiterId && \n EnhancedSecureCryptoUtils.rateLimiter &&\n typeof EnhancedSecureCryptoUtils.rateLimiter.checkMessageRate === 'function' &&\n canProceed === true;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Rate limiting verification failed', { error: error.message });\n return false;\n }\n }\n \n static async verifyPFS(securityManager) {\n try {\n // Check if PFS is active\n return securityManager.securityFeatures &&\n securityManager.securityFeatures.hasPFS === true &&\n securityManager.keyRotationInterval &&\n securityManager.currentKeyVersion !== undefined &&\n securityManager.keyVersions &&\n securityManager.keyVersions instanceof Map;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'PFS verification failed', { error: error.message });\n return false;\n }\n }\n\n // Rate limiting implementation\n static rateLimiter = {\n messages: new Map(),\n connections: new Map(),\n locks: new Map(),\n \n async checkMessageRate(identifier, limit = 60, windowMs = 60000) {\n if (typeof identifier !== 'string' || identifier.length > 256) {\n return false;\n }\n \n const key = `msg_${identifier}`;\n\n if (this.locks.has(key)) {\n\n await new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * 10) + 5));\n return this.checkMessageRate(identifier, limit, windowMs);\n }\n \n this.locks.set(key, true);\n \n try {\n const now = Date.now();\n \n if (!this.messages.has(key)) {\n this.messages.set(key, []);\n }\n \n const timestamps = this.messages.get(key);\n \n const validTimestamps = timestamps.filter(ts => now - ts < windowMs);\n \n if (validTimestamps.length >= limit) {\n return false; \n }\n \n validTimestamps.push(now);\n this.messages.set(key, validTimestamps);\n return true;\n } finally {\n this.locks.delete(key);\n }\n },\n \n async checkConnectionRate(identifier, limit = 5, windowMs = 300000) {\n if (typeof identifier !== 'string' || identifier.length > 256) {\n return false;\n }\n \n const key = `conn_${identifier}`;\n \n if (this.locks.has(key)) {\n await new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * 10) + 5));\n return this.checkConnectionRate(identifier, limit, windowMs);\n }\n \n this.locks.set(key, true);\n \n try {\n const now = Date.now();\n \n if (!this.connections.has(key)) {\n this.connections.set(key, []);\n }\n \n const timestamps = this.connections.get(key);\n const validTimestamps = timestamps.filter(ts => now - ts < windowMs);\n \n if (validTimestamps.length >= limit) {\n return false;\n }\n \n validTimestamps.push(now);\n this.connections.set(key, validTimestamps);\n return true;\n } finally {\n this.locks.delete(key);\n }\n },\n \n cleanup() {\n const now = Date.now();\n const maxAge = 3600000; \n \n for (const [key, timestamps] of this.messages.entries()) {\n if (this.locks.has(key)) continue;\n \n const valid = timestamps.filter(ts => now - ts < maxAge);\n if (valid.length === 0) {\n this.messages.delete(key);\n } else {\n this.messages.set(key, valid);\n }\n }\n \n for (const [key, timestamps] of this.connections.entries()) {\n if (this.locks.has(key)) continue;\n \n const valid = timestamps.filter(ts => now - ts < maxAge);\n if (valid.length === 0) {\n this.connections.delete(key);\n } else {\n this.connections.set(key, valid);\n }\n }\n\n for (const lockKey of this.locks.keys()) {\n const keyTimestamp = parseInt(lockKey.split('_').pop()) || 0;\n if (now - keyTimestamp > 30000) {\n this.locks.delete(lockKey);\n }\n }\n }\n};\n\n static validateSalt(salt) {\n if (!salt || salt.length !== 64) {\n throw new Error('Salt must be exactly 64 bytes');\n }\n \n const uniqueBytes = new Set(salt);\n if (uniqueBytes.size < 16) {\n throw new Error('Salt has insufficient entropy');\n }\n \n return true;\n }\n\n // Secure logging without data leaks\n static secureLog = {\n logs: [],\n maxLogs: 100,\n isProductionMode: false,\n \n // Initialize production mode detection\n init() {\n this.isProductionMode = this._detectProductionMode();\n if (this.isProductionMode) {\n console.log('[SecureChat] Production mode detected - sensitive logging disabled');\n }\n },\n \n _detectProductionMode() {\n return (\n (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production') ||\n (!window.DEBUG_MODE && !window.DEVELOPMENT_MODE) ||\n (window.location.hostname && !window.location.hostname.includes('localhost') && \n !window.location.hostname.includes('127.0.0.1') && \n !window.location.hostname.includes('.local')) ||\n (typeof window.webpackHotUpdate === 'undefined' && !window.location.search.includes('debug'))\n );\n },\n \n log(level, message, context = {}) {\n const sanitizedContext = this.sanitizeContext(context);\n const logEntry = {\n timestamp: Date.now(),\n level,\n message,\n context: sanitizedContext,\n id: crypto.getRandomValues(new Uint32Array(1))[0]\n };\n \n this.logs.push(logEntry);\n \n // Keep only recent logs\n if (this.logs.length > this.maxLogs) {\n this.logs = this.logs.slice(-this.maxLogs);\n }\n \n // Production-safe console output\n if (this.isProductionMode) {\n if (level === 'error') {\n // \u0412 production \u043F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u043C \u0442\u043E\u043B\u044C\u043A\u043E \u043A\u043E\u0434 \u043E\u0448\u0438\u0431\u043A\u0438 \u0431\u0435\u0437 \u0434\u0435\u0442\u0430\u043B\u0435\u0439\n console.error(`\u274C [SecureChat] ${message} [ERROR_CODE: ${this._generateErrorCode(message)}]`);\n } else if (level === 'warn') {\n // \u0412 production \u043F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u043C \u0442\u043E\u043B\u044C\u043A\u043E \u043F\u0440\u0435\u0434\u0443\u043F\u0440\u0435\u0436\u0434\u0435\u043D\u0438\u0435 \u0431\u0435\u0437 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430\n console.warn(`\u26A0\uFE0F [SecureChat] ${message}`);\n } else {\n // \u0412 production \u043D\u0435 \u043F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u043C info/debug \u043B\u043E\u0433\u0438\n return;\n }\n } else {\n // Development mode - \u043F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u043C \u0432\u0441\u0435\n if (level === 'error') {\n console.error(`\u274C [SecureChat] ${message}`, { errorType: sanitizedContext?.constructor?.name || 'Unknown' });\n } else if (level === 'warn') {\n console.warn(`\u26A0\uFE0F [SecureChat] ${message}`, { details: sanitizedContext });\n } else {\n console.log(`[SecureChat] ${message}`, sanitizedContext);\n }\n }\n },\n \n // \u0413\u0435\u043D\u0435\u0440\u0438\u0440\u0443\u0435\u0442 \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u044B\u0439 \u043A\u043E\u0434 \u043E\u0448\u0438\u0431\u043A\u0438 \u0434\u043B\u044F production\n _generateErrorCode(message) {\n const hash = message.split('').reduce((a, b) => {\n a = ((a << 5) - a) + b.charCodeAt(0);\n return a & a;\n }, 0);\n return Math.abs(hash).toString(36).substring(0, 6).toUpperCase();\n },\n \n sanitizeContext(context) {\n if (!context || typeof context !== 'object') {\n return context;\n }\n \n const sensitivePatterns = [\n /key/i, /secret/i, /password/i, /token/i, /signature/i,\n /challenge/i, /proof/i, /salt/i, /iv/i, /nonce/i, /hash/i,\n /fingerprint/i, /mac/i, /private/i, /encryption/i, /decryption/i\n ];\n \n const sanitized = {};\n for (const [key, value] of Object.entries(context)) {\n const isSensitive = sensitivePatterns.some(pattern => \n pattern.test(key) || (typeof value === 'string' && pattern.test(value))\n );\n \n if (isSensitive) {\n sanitized[key] = '[REDACTED]';\n } else if (typeof value === 'string' && value.length > 100) {\n sanitized[key] = value.substring(0, 100) + '...[TRUNCATED]';\n } else if (value instanceof ArrayBuffer || value instanceof Uint8Array) {\n sanitized[key] = `[${value.constructor.name}(${value.byteLength || value.length} bytes)]`;\n } else if (value && typeof value === 'object' && !Array.isArray(value)) {\n // \u0420\u0435\u043A\u0443\u0440\u0441\u0438\u0432\u043D\u0430\u044F \u0441\u0430\u043D\u0438\u0442\u0438\u0437\u0430\u0446\u0438\u044F \u0434\u043B\u044F \u043E\u0431\u044A\u0435\u043A\u0442\u043E\u0432\n sanitized[key] = this.sanitizeContext(value);\n } else {\n sanitized[key] = value;\n }\n }\n return sanitized;\n },\n \n getLogs(level = null) {\n if (level) {\n return this.logs.filter(log => log.level === level);\n }\n return [...this.logs];\n },\n \n clearLogs() {\n this.logs = [];\n },\n \n // \u041C\u0435\u0442\u043E\u0434 \u0434\u043B\u044F \u043E\u0442\u043F\u0440\u0430\u0432\u043A\u0438 \u043E\u0448\u0438\u0431\u043E\u043A \u043D\u0430 \u0441\u0435\u0440\u0432\u0435\u0440 \u0432 production\n async sendErrorToServer(errorCode, message, context = {}) {\n if (!this.isProductionMode) {\n return; // \u0412 development \u043D\u0435 \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C\n }\n \n try {\n // \u041E\u0442\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C \u0442\u043E\u043B\u044C\u043A\u043E \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u0443\u044E \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044E\n const safeErrorData = {\n errorCode,\n timestamp: Date.now(),\n userAgent: navigator.userAgent.substring(0, 100),\n url: window.location.href.substring(0, 100)\n };\n \n // \u0417\u0434\u0435\u0441\u044C \u043C\u043E\u0436\u043D\u043E \u0434\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u043E\u0442\u043F\u0440\u0430\u0432\u043A\u0443 \u043D\u0430 \u0441\u0435\u0440\u0432\u0435\u0440\n // await fetch('/api/error-log', { method: 'POST', body: JSON.stringify(safeErrorData) });\n \n if (window.DEBUG_MODE) {\n console.log('[SecureChat] Error logged to server:', safeErrorData);\n }\n } catch (e) {\n // \u041D\u0435 \u043B\u043E\u0433\u0438\u0440\u0443\u0435\u043C \u043E\u0448\u0438\u0431\u043A\u0438 \u043B\u043E\u0433\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F\n }\n }\n };\n\n // Generate ECDH key pair for secure key exchange (non-extractable) with fallback\n static async generateECDHKeyPair() {\n try {\n // Try P-384 first\n try {\n const keyPair = await crypto.subtle.generateKey(\n {\n name: 'ECDH',\n namedCurve: 'P-384'\n },\n false, // Non-extractable for enhanced security\n ['deriveKey']\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'ECDH key pair generated successfully (P-384)', {\n curve: 'P-384',\n extractable: false\n });\n \n return keyPair;\n } catch (p384Error) {\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'P-384 generation failed, trying P-256', { error: p384Error.message });\n \n // Fallback to P-256\n const keyPair = await crypto.subtle.generateKey(\n {\n name: 'ECDH',\n namedCurve: 'P-256'\n },\n false, // Non-extractable for enhanced security\n ['deriveKey']\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'ECDH key pair generated successfully (P-256 fallback)', {\n curve: 'P-256',\n extractable: false\n });\n \n return keyPair;\n }\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'ECDH key generation failed', { error: error.message });\n throw new Error('Failed to create keys for secure exchange');\n }\n }\n\n // Generate ECDSA key pair for digital signatures with fallback\n static async generateECDSAKeyPair() {\n try {\n // Try P-384 first\n try {\n const keyPair = await crypto.subtle.generateKey(\n {\n name: 'ECDSA',\n namedCurve: 'P-384'\n },\n false, // Non-extractable for enhanced security\n ['sign', 'verify']\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'ECDSA key pair generated successfully (P-384)', {\n curve: 'P-384',\n extractable: false\n });\n \n return keyPair;\n } catch (p384Error) {\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'P-384 generation failed, trying P-256', { error: p384Error.message });\n \n // Fallback to P-256\n const keyPair = await crypto.subtle.generateKey(\n {\n name: 'ECDSA',\n namedCurve: 'P-256'\n },\n false, // Non-extractable for enhanced security\n ['sign', 'verify']\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'ECDSA key pair generated successfully (P-256 fallback)', {\n curve: 'P-256',\n extractable: false\n });\n \n return keyPair;\n }\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'ECDSA key generation failed', { error: error.message });\n throw new Error('Failed to generate keys for digital signatures');\n }\n }\n\n // Sign data with ECDSA (P-384 or P-256)\n static async signData(privateKey, data) {\n try {\n const encoder = new TextEncoder();\n const dataBuffer = typeof data === 'string' ? encoder.encode(data) : data;\n \n // Try SHA-384 first, fallback to SHA-256\n try {\n const signature = await crypto.subtle.sign(\n {\n name: 'ECDSA',\n hash: 'SHA-384'\n },\n privateKey,\n dataBuffer\n );\n \n return Array.from(new Uint8Array(signature));\n } catch (sha384Error) {\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'SHA-384 signing failed, trying SHA-256', { error: sha384Error.message });\n \n const signature = await crypto.subtle.sign(\n {\n name: 'ECDSA',\n hash: 'SHA-256'\n },\n privateKey,\n dataBuffer\n );\n \n return Array.from(new Uint8Array(signature));\n }\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Data signing failed', { error: error.message });\n throw new Error('Failed to sign data');\n }\n }\n\n // Verify ECDSA signature (P-384 or P-256)\n static async verifySignature(publicKey, signature, data) {\n try {\n const encoder = new TextEncoder();\n const dataBuffer = typeof data === 'string' ? encoder.encode(data) : data;\n const signatureBuffer = new Uint8Array(signature);\n \n // Try SHA-384 first, fallback to SHA-256\n try {\n const isValid = await crypto.subtle.verify(\n {\n name: 'ECDSA',\n hash: 'SHA-384'\n },\n publicKey,\n signatureBuffer,\n dataBuffer\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Signature verification completed (SHA-384)', {\n isValid,\n dataSize: dataBuffer.length\n });\n \n return isValid;\n } catch (sha384Error) {\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'SHA-384 verification failed, trying SHA-256', { error: sha384Error.message });\n \n const isValid = await crypto.subtle.verify(\n {\n name: 'ECDSA',\n hash: 'SHA-256'\n },\n publicKey,\n signatureBuffer,\n dataBuffer\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Signature verification completed (SHA-256 fallback)', {\n isValid,\n dataSize: dataBuffer.length\n });\n \n return isValid;\n }\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Signature verification failed', { error: error.message });\n throw new Error('Failed to verify digital signature');\n }\n }\n\n // Enhanced DER/SPKI validation with full ASN.1 parsing\n static async validateKeyStructure(keyData, expectedAlgorithm = 'ECDH') {\n try {\n if (!Array.isArray(keyData) || keyData.length === 0) {\n throw new Error('Invalid key data format');\n }\n\n const keyBytes = new Uint8Array(keyData);\n\n // Size limits to prevent DoS\n if (keyBytes.length < 50) {\n throw new Error('Key data too short - invalid SPKI structure');\n }\n if (keyBytes.length > 2000) {\n throw new Error('Key data too long - possible attack');\n }\n\n // Parse ASN.1 DER structure\n const asn1 = EnhancedSecureCryptoUtils.parseASN1(keyBytes);\n \n // Validate SPKI structure\n if (!asn1 || asn1.tag !== 0x30) {\n throw new Error('Invalid SPKI structure - missing SEQUENCE tag');\n }\n\n // SPKI should have exactly 2 elements: AlgorithmIdentifier and BIT STRING\n if (asn1.children.length !== 2) {\n throw new Error(`Invalid SPKI structure - expected 2 elements, got ${asn1.children.length}`);\n }\n\n // Validate AlgorithmIdentifier\n const algIdentifier = asn1.children[0];\n if (algIdentifier.tag !== 0x30) {\n throw new Error('Invalid AlgorithmIdentifier - not a SEQUENCE');\n }\n\n // Parse algorithm OID\n const algOid = algIdentifier.children[0];\n if (algOid.tag !== 0x06) {\n throw new Error('Invalid algorithm OID - not an OBJECT IDENTIFIER');\n }\n\n // Validate algorithm OID based on expected algorithm\n const oidBytes = algOid.value;\n const oidString = EnhancedSecureCryptoUtils.oidToString(oidBytes);\n \n // Check for expected algorithms\n const validAlgorithms = {\n 'ECDH': ['1.2.840.10045.2.1'], // id-ecPublicKey\n 'ECDSA': ['1.2.840.10045.2.1'], // id-ecPublicKey (same as ECDH)\n 'RSA': ['1.2.840.113549.1.1.1'], // rsaEncryption\n 'AES-GCM': ['2.16.840.1.101.3.4.1.6', '2.16.840.1.101.3.4.1.46'] // AES-128-GCM, AES-256-GCM\n };\n\n const expectedOids = validAlgorithms[expectedAlgorithm];\n if (!expectedOids) {\n throw new Error(`Unknown algorithm: ${expectedAlgorithm}`);\n }\n\n if (!expectedOids.includes(oidString)) {\n throw new Error(`Invalid algorithm OID: expected ${expectedOids.join(' or ')}, got ${oidString}`);\n }\n\n // For EC algorithms, validate curve parameters\n if (expectedAlgorithm === 'ECDH' || expectedAlgorithm === 'ECDSA') {\n if (algIdentifier.children.length < 2) {\n throw new Error('Missing curve parameters for EC key');\n }\n\n const curveOid = algIdentifier.children[1];\n if (curveOid.tag !== 0x06) {\n throw new Error('Invalid curve OID - not an OBJECT IDENTIFIER');\n }\n\n const curveOidString = EnhancedSecureCryptoUtils.oidToString(curveOid.value);\n \n // Only allow P-256 and P-384 curves\n const validCurves = {\n '1.2.840.10045.3.1.7': 'P-256', // secp256r1\n '1.3.132.0.34': 'P-384' // secp384r1\n };\n\n if (!validCurves[curveOidString]) {\n throw new Error(`Invalid or unsupported curve OID: ${curveOidString}`);\n }\n\n EnhancedSecureCryptoUtils.secureLog.log('info', 'EC key curve validated', {\n curve: validCurves[curveOidString],\n oid: curveOidString\n });\n }\n\n // Validate public key BIT STRING\n const publicKeyBitString = asn1.children[1];\n if (publicKeyBitString.tag !== 0x03) {\n throw new Error('Invalid public key - not a BIT STRING');\n }\n\n // Check for unused bits (should be 0 for public keys)\n if (publicKeyBitString.value[0] !== 0x00) {\n throw new Error(`Invalid BIT STRING - unexpected unused bits: ${publicKeyBitString.value[0]}`);\n }\n\n // For EC keys, validate point format\n if (expectedAlgorithm === 'ECDH' || expectedAlgorithm === 'ECDSA') {\n const pointData = publicKeyBitString.value.slice(1); // Skip unused bits byte\n \n // Check for uncompressed point format (0x04)\n if (pointData[0] !== 0x04) {\n throw new Error(`Invalid EC point format: expected uncompressed (0x04), got 0x${pointData[0].toString(16)}`);\n }\n\n // Validate point size based on curve\n const expectedSizes = {\n 'P-256': 65, // 1 + 32 + 32\n 'P-384': 97 // 1 + 48 + 48\n };\n\n // We already validated the curve above, so we can determine expected size\n const curveOidString = EnhancedSecureCryptoUtils.oidToString(algIdentifier.children[1].value);\n const curveName = curveOidString === '1.2.840.10045.3.1.7' ? 'P-256' : 'P-384';\n const expectedSize = expectedSizes[curveName];\n\n if (pointData.length !== expectedSize) {\n throw new Error(`Invalid EC point size for ${curveName}: expected ${expectedSize}, got ${pointData.length}`);\n }\n }\n\n // Additional validation: try to import the key\n try {\n const algorithm = expectedAlgorithm === 'ECDSA' || expectedAlgorithm === 'ECDH'\n ? { name: expectedAlgorithm, namedCurve: 'P-384' }\n : { name: expectedAlgorithm };\n\n const usages = expectedAlgorithm === 'ECDSA' ? ['verify'] : [];\n \n await crypto.subtle.importKey('spki', keyBytes.buffer, algorithm, false, usages);\n } catch (importError) {\n // Try P-256 as fallback for EC keys\n if (expectedAlgorithm === 'ECDSA' || expectedAlgorithm === 'ECDH') {\n try {\n const algorithm = { name: expectedAlgorithm, namedCurve: 'P-256' };\n const usages = expectedAlgorithm === 'ECDSA' ? ['verify'] : [];\n await crypto.subtle.importKey('spki', keyBytes.buffer, algorithm, false, usages);\n } catch (fallbackError) {\n throw new Error(`Key import validation failed: ${fallbackError.message}`);\n }\n } else {\n throw new Error(`Key import validation failed: ${importError.message}`);\n }\n }\n\n EnhancedSecureCryptoUtils.secureLog.log('info', 'Key structure validation passed', {\n keyLen: keyBytes.length,\n algorithm: expectedAlgorithm,\n asn1Valid: true,\n oidValid: true,\n importValid: true\n });\n\n return true;\n } catch (err) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Key structure validation failed', {\n error: err.message,\n algorithm: expectedAlgorithm\n });\n throw new Error(`Invalid key structure: ${err.message}`);\n }\n }\n\n // ASN.1 DER parser helper\n static parseASN1(bytes, offset = 0) {\n if (offset >= bytes.length) {\n return null;\n }\n\n const tag = bytes[offset];\n let lengthOffset = offset + 1;\n \n if (lengthOffset >= bytes.length) {\n throw new Error('Truncated ASN.1 structure');\n }\n\n let length = bytes[lengthOffset];\n let valueOffset = lengthOffset + 1;\n\n // Handle long form length\n if (length & 0x80) {\n const numLengthBytes = length & 0x7f;\n if (numLengthBytes > 4) {\n throw new Error('ASN.1 length too large');\n }\n \n length = 0;\n for (let i = 0; i < numLengthBytes; i++) {\n if (valueOffset + i >= bytes.length) {\n throw new Error('Truncated ASN.1 length');\n }\n length = (length << 8) | bytes[valueOffset + i];\n }\n valueOffset += numLengthBytes;\n }\n\n if (valueOffset + length > bytes.length) {\n throw new Error('ASN.1 structure extends beyond data');\n }\n\n const value = bytes.slice(valueOffset, valueOffset + length);\n const node = {\n tag: tag,\n length: length,\n value: value,\n children: []\n };\n\n // Parse children for SEQUENCE and SET\n if (tag === 0x30 || tag === 0x31) {\n let childOffset = 0;\n while (childOffset < value.length) {\n const child = EnhancedSecureCryptoUtils.parseASN1(value, childOffset);\n if (!child) break;\n node.children.push(child);\n childOffset = childOffset + 1 + child.lengthBytes + child.length;\n }\n }\n\n // Calculate how many bytes were used for length encoding\n node.lengthBytes = valueOffset - lengthOffset;\n \n return node;\n }\n\n // OID decoder helper\n static oidToString(bytes) {\n if (!bytes || bytes.length === 0) {\n throw new Error('Empty OID');\n }\n\n const parts = [];\n \n // First byte encodes first two components\n const first = Math.floor(bytes[0] / 40);\n const second = bytes[0] % 40;\n parts.push(first);\n parts.push(second);\n\n // Decode remaining components\n let value = 0;\n for (let i = 1; i < bytes.length; i++) {\n value = (value << 7) | (bytes[i] & 0x7f);\n if (!(bytes[i] & 0x80)) {\n parts.push(value);\n value = 0;\n }\n }\n\n return parts.join('.');\n }\n\n // Helper to validate and sanitize OID string\n static validateOidString(oidString) {\n // OID format: digits separated by dots\n const oidRegex = /^[0-9]+(\\.[0-9]+)*$/;\n if (!oidRegex.test(oidString)) {\n throw new Error(`Invalid OID format: ${oidString}`);\n }\n\n const parts = oidString.split('.').map(Number);\n \n // First component must be 0, 1, or 2\n if (parts[0] > 2) {\n throw new Error(`Invalid OID first component: ${parts[0]}`);\n }\n\n // If first component is 0 or 1, second must be <= 39\n if ((parts[0] === 0 || parts[0] === 1) && parts[1] > 39) {\n throw new Error(`Invalid OID second component: ${parts[1]} (must be <= 39 for first component ${parts[0]})`);\n }\n\n return true;\n }\n\n // Export public key for transmission with signature \n static async exportPublicKeyWithSignature(publicKey, signingKey, keyType = 'ECDH') {\n try {\n // Validate key type\n if (!['ECDH', 'ECDSA'].includes(keyType)) {\n throw new Error('Invalid key type');\n }\n \n const exported = await crypto.subtle.exportKey('spki', publicKey);\n const keyData = Array.from(new Uint8Array(exported));\n \n await EnhancedSecureCryptoUtils.validateKeyStructure(keyData, keyType);\n \n // Create signed key package\n const keyPackage = {\n keyType,\n keyData,\n timestamp: Date.now(),\n version: '4.0'\n };\n \n // Sign the key package\n const packageString = JSON.stringify(keyPackage);\n const signature = await EnhancedSecureCryptoUtils.signData(signingKey, packageString);\n \n const signedPackage = {\n ...keyPackage,\n signature\n };\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Public key exported with signature', {\n keyType,\n keySize: keyData.length,\n signed: true\n });\n \n return signedPackage;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Public key export failed', {\n error: error.message,\n keyType\n });\n throw new Error(`Failed to export ${keyType} key: ${error.message}`);\n }\n }\n\n // Import and verify signed public key\n static async importSignedPublicKey(signedPackage, verifyingKey, expectedKeyType = 'ECDH') {\n try {\n // Validate package structure\n if (!signedPackage || typeof signedPackage !== 'object') {\n throw new Error('Invalid signed package format');\n }\n \n const { keyType, keyData, timestamp, version, signature } = signedPackage;\n \n if (!keyType || !keyData || !timestamp || !signature) {\n throw new Error('Missing required fields in signed package');\n }\n \n if (!EnhancedSecureCryptoUtils.constantTimeCompare(keyType, expectedKeyType)) {\n throw new Error(`Key type mismatch: expected ${expectedKeyType}, got ${keyType}`);\n }\n \n // Check timestamp (reject keys older than 1 hour)\n const keyAge = Date.now() - timestamp;\n if (keyAge > 3600000) {\n throw new Error('Signed key package is too old');\n }\n \n await EnhancedSecureCryptoUtils.validateKeyStructure(keyData, keyType);\n \n // Verify signature\n const packageCopy = { keyType, keyData, timestamp, version };\n const packageString = JSON.stringify(packageCopy);\n const isValidSignature = await EnhancedSecureCryptoUtils.verifySignature(verifyingKey, signature, packageString);\n \n if (!isValidSignature) {\n throw new Error('Invalid signature on key package - possible MITM attack');\n }\n \n // Import the key with fallback support\n const keyBytes = new Uint8Array(keyData);\n \n // Try P-384 first\n try {\n const algorithm = keyType === 'ECDH' ?\n { name: 'ECDH', namedCurve: 'P-384' }\n : { name: 'ECDSA', namedCurve: 'P-384' };\n \n const keyUsages = keyType === 'ECDH' ? [] : ['verify'];\n \n const publicKey = await crypto.subtle.importKey(\n 'spki',\n keyBytes,\n algorithm,\n false, // Non-extractable\n keyUsages\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Signed public key imported successfully (P-384)', {\n keyType,\n signatureValid: true,\n keyAge: Math.round(keyAge / 1000) + 's'\n });\n \n return publicKey;\n } catch (p384Error) {\n // Fallback to P-256\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'P-384 import failed, trying P-256', {\n error: p384Error.message\n });\n \n const algorithm = keyType === 'ECDH' ?\n { name: 'ECDH', namedCurve: 'P-256' }\n : { name: 'ECDSA', namedCurve: 'P-256' };\n \n const keyUsages = keyType === 'ECDH' ? [] : ['verify'];\n \n const publicKey = await crypto.subtle.importKey(\n 'spki',\n keyBytes,\n algorithm,\n false, // Non-extractable\n keyUsages\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Signed public key imported successfully (P-256 fallback)', {\n keyType,\n signatureValid: true,\n keyAge: Math.round(keyAge / 1000) + 's'\n });\n \n return publicKey;\n }\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Signed public key import failed', {\n error: error.message,\n expectedKeyType\n });\n throw new Error(`Failed to import the signed key: ${error.message}`);\n }\n }\n\n // Legacy export for backward compatibility\n static async exportPublicKey(publicKey) {\n try {\n const exported = await crypto.subtle.exportKey('spki', publicKey);\n const keyData = Array.from(new Uint8Array(exported));\n \n await EnhancedSecureCryptoUtils.validateKeyStructure(keyData, 'ECDH');\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Legacy public key exported', { keySize: keyData.length });\n return keyData;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Legacy public key export failed', { error: error.message });\n throw new Error('Failed to export the public key');\n }\n }\n\n // Legacy import for backward compatibility with fallback\n static async importPublicKey(keyData) {\n try {\n await EnhancedSecureCryptoUtils.validateKeyStructure(keyData, 'ECDH');\n \n const keyBytes = new Uint8Array(keyData);\n \n // Try P-384 first\n try {\n const publicKey = await crypto.subtle.importKey(\n 'spki',\n keyBytes,\n {\n name: 'ECDH',\n namedCurve: 'P-384'\n },\n false, // Non-extractable\n []\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Legacy public key imported (P-384)', { keySize: keyData.length });\n return publicKey;\n } catch (p384Error) {\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'P-384 import failed, trying P-256', { error: p384Error.message });\n \n // Fallback to P-256\n const publicKey = await crypto.subtle.importKey(\n 'spki',\n keyBytes,\n {\n name: 'ECDH',\n namedCurve: 'P-256'\n },\n false, // Non-extractable\n []\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Legacy public key imported (P-256 fallback)', { keySize: keyData.length });\n return publicKey;\n }\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Legacy public key import failed', { error: error.message });\n throw new Error('Failed to import the public key');\n }\n }\n\n\n // Method to check if a key is trusted\n static isKeyTrusted(keyOrFingerprint) {\n if (keyOrFingerprint instanceof CryptoKey) {\n const meta = EnhancedSecureCryptoUtils._keyMetadata.get(keyOrFingerprint);\n return meta ? meta.trusted === true : false;\n } else if (keyOrFingerprint && keyOrFingerprint._securityMetadata) {\n // Check by key metadata\n return keyOrFingerprint._securityMetadata.trusted === true;\n }\n\n return false;\n }\n\n static async importPublicKeyFromSignedPackage(signedPackage, verifyingKey = null, options = {}) {\n try {\n if (!signedPackage || !signedPackage.keyData || !signedPackage.signature) {\n throw new Error('Invalid signed key package format');\n }\n\n // Validate all required fields are present\n const requiredFields = ['keyData', 'signature', 'keyType', 'timestamp', 'version'];\n const missingFields = requiredFields.filter(field => !signedPackage[field]);\n\n if (missingFields.length > 0) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Missing required fields in signed package', {\n missingFields: missingFields,\n availableFields: Object.keys(signedPackage)\n });\n throw new Error(`Required fields are missing in the signed package: ${missingFields.join(', ')}`);\n }\n\n // SECURITY ENHANCEMENT: MANDATORY signature verification for signed packages\n if (!verifyingKey) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'SECURITY VIOLATION: Signed package received without verifying key', {\n keyType: signedPackage.keyType,\n keySize: signedPackage.keyData.length,\n timestamp: signedPackage.timestamp,\n version: signedPackage.version,\n securityRisk: 'HIGH - Potential MITM attack vector'\n });\n\n // REJECT the signed package if no verifying key provided\n throw new Error('CRITICAL SECURITY ERROR: Signed key package received without a verification key. ' +\n 'This may indicate a possible MITM attack attempt. Import rejected for security reasons.');\n }\n\n // \u041E\u0411\u041D\u041E\u0412\u041B\u0415\u041D\u041E: \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u043C \u0443\u043B\u0443\u0447\u0448\u0435\u043D\u043D\u0443\u044E \u0432\u0430\u043B\u0438\u0434\u0430\u0446\u0438\u044E\n await EnhancedSecureCryptoUtils.validateKeyStructure(signedPackage.keyData, signedPackage.keyType || 'ECDH');\n\n // MANDATORY signature verification when verifyingKey is provided\n const packageCopy = { ...signedPackage };\n delete packageCopy.signature;\n const packageString = JSON.stringify(packageCopy);\n const isValidSignature = await EnhancedSecureCryptoUtils.verifySignature(verifyingKey, signedPackage.signature, packageString);\n\n if (!isValidSignature) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'SECURITY BREACH: Invalid signature detected - MITM attack prevented', {\n keyType: signedPackage.keyType,\n keySize: signedPackage.keyData.length,\n timestamp: signedPackage.timestamp,\n version: signedPackage.version,\n attackPrevented: true\n });\n throw new Error('CRITICAL SECURITY ERROR: Invalid key signature detected. ' +\n 'This indicates a possible MITM attack attempt. Key import rejected.');\n }\n\n // Additional MITM protection: Check for key reuse and suspicious patterns\n const keyFingerprint = await EnhancedSecureCryptoUtils.calculateKeyFingerprint(signedPackage.keyData);\n\n // Log successful verification with security details\n EnhancedSecureCryptoUtils.secureLog.log('info', 'SECURE: Signature verification passed for signed package', {\n keyType: signedPackage.keyType,\n keySize: signedPackage.keyData.length,\n timestamp: signedPackage.timestamp,\n version: signedPackage.version,\n signatureVerified: true,\n securityLevel: 'HIGH',\n keyFingerprint: keyFingerprint.substring(0, 8) // Only log first 8 chars for security\n });\n\n // Import the public key with fallback\n const keyBytes = new Uint8Array(signedPackage.keyData);\n const keyType = signedPackage.keyType || 'ECDH';\n\n // Try P-384 first\n try {\n const publicKey = await crypto.subtle.importKey(\n 'spki',\n keyBytes,\n {\n name: keyType,\n namedCurve: 'P-384'\n },\n false, // Non-extractable\n keyType === 'ECDSA' ? ['verify'] : []\n );\n\n // Use WeakMap to store metadata\n EnhancedSecureCryptoUtils._keyMetadata.set(publicKey, {\n trusted: true,\n verificationStatus: 'VERIFIED_SECURE',\n verificationTimestamp: Date.now()\n });\n\n return publicKey;\n } catch (p384Error) {\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'P-384 import failed, trying P-256', { error: p384Error.message });\n\n // Fallback to P-256\n const publicKey = await crypto.subtle.importKey(\n 'spki',\n keyBytes,\n {\n name: keyType,\n namedCurve: 'P-256'\n },\n false, // Non-extractable\n keyType === 'ECDSA' ? ['verify'] : []\n );\n\n // Use WeakMap to store metadata\n EnhancedSecureCryptoUtils._keyMetadata.set(publicKey, {\n trusted: true,\n verificationStatus: 'VERIFIED_SECURE',\n verificationTimestamp: Date.now()\n });\n\n return publicKey;\n }\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Signed package key import failed', {\n error: error.message,\n securityImplications: 'Potential security breach prevented'\n });\n throw new Error(`Failed to import the public key from the signed package: ${error.message}`);\n }\n }\n\n // Enhanced key derivation with metadata protection and 64-byte salt\n static async deriveSharedKeys(privateKey, publicKey, salt) {\n try {\n // Validate input parameters are CryptoKey instances\n if (!(privateKey instanceof CryptoKey)) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Private key is not a CryptoKey', {\n privateKeyType: typeof privateKey,\n privateKeyAlgorithm: privateKey?.algorithm?.name\n });\n throw new Error('The private key is not a valid CryptoKey.');\n }\n \n if (!(publicKey instanceof CryptoKey)) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Public key is not a CryptoKey', {\n publicKeyType: typeof publicKey,\n publicKeyAlgorithm: publicKey?.algorithm?.name\n });\n throw new Error('The private key is not a valid CryptoKey.');\n }\n \n // Validate salt size (should be 64 bytes for enhanced security)\n if (!salt || salt.length !== 64) {\n throw new Error('Salt must be exactly 64 bytes for enhanced security');\n }\n \n const saltBytes = new Uint8Array(salt);\n const encoder = new TextEncoder();\n \n // Enhanced context info with version and additional entropy\n const contextInfo = encoder.encode('SecureBit.chat v4.0 Enhanced Security Edition');\n \n // Derive master shared secret with enhanced parameters\n // Try SHA-384 first, fallback to SHA-256\n let sharedSecret;\n try {\n sharedSecret = await crypto.subtle.deriveKey(\n {\n name: 'ECDH',\n public: publicKey\n },\n privateKey,\n {\n name: 'HKDF',\n hash: 'SHA-384',\n salt: saltBytes,\n info: contextInfo\n },\n false, // Non-extractable\n ['deriveKey']\n );\n } catch (sha384Error) {\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'SHA-384 key derivation failed, trying SHA-256', { \n error: sha384Error.message,\n privateKeyType: typeof privateKey,\n publicKeyType: typeof publicKey,\n privateKeyAlgorithm: privateKey?.algorithm?.name,\n publicKeyAlgorithm: publicKey?.algorithm?.name\n });\n \n sharedSecret = await crypto.subtle.deriveKey(\n {\n name: 'ECDH',\n public: publicKey\n },\n privateKey,\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: saltBytes,\n info: contextInfo\n },\n false, // Non-extractable\n ['deriveKey']\n );\n }\n\n // Derive message encryption key with fallback\n let encryptionKey;\n try {\n encryptionKey = await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-384',\n salt: saltBytes,\n info: encoder.encode('message-encryption-v4')\n },\n sharedSecret,\n {\n name: 'AES-GCM',\n length: 256\n },\n false, // Non-extractable for enhanced security\n ['encrypt', 'decrypt']\n );\n } catch (sha384Error) {\n encryptionKey = await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: saltBytes,\n info: encoder.encode('message-encryption-v4')\n },\n sharedSecret,\n {\n name: 'AES-GCM',\n length: 256\n },\n false, // Non-extractable for enhanced security\n ['encrypt', 'decrypt']\n );\n }\n\n // Derive MAC key for message authentication with fallback\n let macKey;\n try {\n macKey = await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-384',\n salt: saltBytes,\n info: encoder.encode('message-authentication-v4')\n },\n sharedSecret,\n {\n name: 'HMAC',\n hash: 'SHA-384'\n },\n false, // Non-extractable\n ['sign', 'verify']\n );\n } catch (sha384Error) {\n macKey = await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: saltBytes,\n info: encoder.encode('message-authentication-v4')\n },\n sharedSecret,\n {\n name: 'HMAC',\n hash: 'SHA-256'\n },\n false, // Non-extractable\n ['sign', 'verify']\n );\n }\n\n // Derive separate metadata encryption key with fallback\n let metadataKey;\n try {\n metadataKey = await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-384',\n salt: saltBytes,\n info: encoder.encode('metadata-protection-v4')\n },\n sharedSecret,\n {\n name: 'AES-GCM',\n length: 256\n },\n false, // Non-extractable\n ['encrypt', 'decrypt']\n );\n } catch (sha384Error) {\n metadataKey = await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: saltBytes,\n info: encoder.encode('metadata-protection-v4')\n },\n sharedSecret,\n {\n name: 'AES-GCM',\n length: 256\n },\n false, // Non-extractable\n ['encrypt', 'decrypt']\n );\n }\n\n // Generate temporary extractable key for fingerprint calculation with fallback\n let fingerprintKey;\n try {\n fingerprintKey = await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-384',\n salt: saltBytes,\n info: encoder.encode('fingerprint-generation-v4')\n },\n sharedSecret,\n {\n name: 'AES-GCM',\n length: 256\n },\n true, // Extractable only for fingerprint\n ['encrypt', 'decrypt']\n );\n } catch (sha384Error) {\n fingerprintKey = await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: saltBytes,\n info: encoder.encode('fingerprint-generation-v4')\n },\n sharedSecret,\n {\n name: 'AES-GCM',\n length: 256\n },\n true, // Extractable only for fingerprint\n ['encrypt', 'decrypt']\n );\n }\n\n // Generate key fingerprint for verification\n const fingerprintKeyData = await crypto.subtle.exportKey('raw', fingerprintKey);\n const fingerprint = await EnhancedSecureCryptoUtils.generateKeyFingerprint(Array.from(new Uint8Array(fingerprintKeyData)));\n\n // Validate that all derived keys are CryptoKey instances\n if (!(encryptionKey instanceof CryptoKey)) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Derived encryption key is not a CryptoKey', {\n encryptionKeyType: typeof encryptionKey,\n encryptionKeyAlgorithm: encryptionKey?.algorithm?.name\n });\n throw new Error('The derived encryption key is not a valid CryptoKey.');\n }\n \n if (!(macKey instanceof CryptoKey)) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Derived MAC key is not a CryptoKey', {\n macKeyType: typeof macKey,\n macKeyAlgorithm: macKey?.algorithm?.name\n });\n throw new Error('The derived MAC key is not a valid CryptoKey.');\n }\n \n if (!(metadataKey instanceof CryptoKey)) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Derived metadata key is not a CryptoKey', {\n metadataKeyType: typeof metadataKey,\n metadataKeyAlgorithm: metadataKey?.algorithm?.name\n });\n throw new Error('The derived metadata key is not a valid CryptoKey.');\n }\n\n EnhancedSecureCryptoUtils.secureLog.log('info', 'Enhanced shared keys derived successfully', {\n saltSize: salt.length,\n hasMetadataKey: true,\n nonExtractable: true,\n version: '4.0',\n allKeysValid: true\n });\n\n return {\n encryptionKey,\n macKey,\n metadataKey,\n fingerprint,\n timestamp: Date.now(),\n version: '4.0'\n };\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Enhanced key derivation failed', { error: error.message });\n throw new Error(`Failed to create shared encryption keys: ${error.message}`);\n }\n }\n\n static async generateKeyFingerprint(keyData) {\n const keyBuffer = new Uint8Array(keyData);\n const hashBuffer = await crypto.subtle.digest('SHA-384', keyBuffer);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.slice(0, 12).map(b => b.toString(16).padStart(2, '0')).join(':');\n }\n\n // Generate mutual authentication challenge\n static generateMutualAuthChallenge() {\n const challenge = crypto.getRandomValues(new Uint8Array(48)); // Increased to 48 bytes\n const timestamp = Date.now();\n const nonce = crypto.getRandomValues(new Uint8Array(16));\n \n return {\n challenge: Array.from(challenge),\n timestamp,\n nonce: Array.from(nonce),\n version: '4.0'\n };\n }\n\n // Create cryptographic proof for mutual authentication\n static async createAuthProof(challenge, privateKey, publicKey) {\n try {\n if (!challenge || !challenge.challenge || !challenge.timestamp || !challenge.nonce) {\n throw new Error('Invalid challenge structure');\n }\n \n // Check challenge age (max 2 minutes)\n const challengeAge = Date.now() - challenge.timestamp;\n if (challengeAge > 120000) {\n throw new Error('Challenge expired');\n }\n \n // Create proof data\n const proofData = {\n challenge: challenge.challenge,\n timestamp: challenge.timestamp,\n nonce: challenge.nonce,\n responseTimestamp: Date.now(),\n publicKeyHash: await EnhancedSecureCryptoUtils.hashPublicKey(publicKey)\n };\n \n // Sign the proof\n const proofString = JSON.stringify(proofData);\n const signature = await EnhancedSecureCryptoUtils.signData(privateKey, proofString);\n \n const proof = {\n ...proofData,\n signature,\n version: '4.0'\n };\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Authentication proof created', {\n challengeAge: Math.round(challengeAge / 1000) + 's'\n });\n \n return proof;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Authentication proof creation failed', { error: error.message });\n throw new Error(`Failed to create cryptographic proof: ${error.message}`);\n }\n }\n\n // Verify mutual authentication proof\n static async verifyAuthProof(proof, challenge, publicKey) {\n try {\n await new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * 20) + 5));\n // Assert the public key is valid and has the correct usage\n EnhancedSecureCryptoUtils.assertCryptoKey(publicKey, 'ECDSA', ['verify']);\n\n if (!proof || !challenge || !publicKey) {\n throw new Error('Missing required parameters for proof verification');\n }\n\n // Validate proof structure\n const requiredFields = ['challenge', 'timestamp', 'nonce', 'responseTimestamp', 'publicKeyHash', 'signature'];\n for (const field of requiredFields) {\n if (!proof[field]) {\n throw new Error(`Missing required field: ${field}`);\n }\n }\n\n // Verify challenge matches\n if (!EnhancedSecureCryptoUtils.constantTimeCompareArrays(proof.challenge, challenge.challenge) ||\n proof.timestamp !== challenge.timestamp ||\n !EnhancedSecureCryptoUtils.constantTimeCompareArrays(proof.nonce, challenge.nonce)) {\n throw new Error('Challenge mismatch - possible replay attack');\n }\n\n // Check response time (max 5 minutes)\n const responseAge = Date.now() - proof.responseTimestamp;\n if (responseAge > 300000) {\n throw new Error('Proof response expired');\n }\n\n // Verify public key hash\n const expectedHash = await EnhancedSecureCryptoUtils.hashPublicKey(publicKey);\n if (!EnhancedSecureCryptoUtils.constantTimeCompare(proof.publicKeyHash, expectedHash)) {\n throw new Error('Public key hash mismatch');\n }\n\n // Verify signature\n const proofCopy = { ...proof };\n delete proofCopy.signature;\n const proofString = JSON.stringify(proofCopy);\n const isValidSignature = await EnhancedSecureCryptoUtils.verifySignature(publicKey, proof.signature, proofString);\n\n if (!isValidSignature) {\n throw new Error('Invalid proof signature');\n }\n\n EnhancedSecureCryptoUtils.secureLog.log('info', 'Authentication proof verified successfully', {\n responseAge: Math.round(responseAge / 1000) + 's'\n });\n\n return true;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Authentication proof verification failed', { error: error.message });\n throw new Error(`Failed to verify cryptographic proof: ${error.message}`);\n }\n }\n\n // Hash public key for verification\n static async hashPublicKey(publicKey) {\n try {\n const exported = await crypto.subtle.exportKey('spki', publicKey);\n const hash = await crypto.subtle.digest('SHA-384', exported);\n const hashArray = Array.from(new Uint8Array(hash));\n return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Public key hashing failed', { error: error.message });\n throw new Error('Failed to create hash of the public key');\n }\n }\n\n // Legacy authentication challenge for backward compatibility\n static generateAuthChallenge() {\n const challenge = crypto.getRandomValues(new Uint8Array(32));\n return Array.from(challenge);\n }\n\n // Generate verification code for out-of-band authentication\n static generateVerificationCode() {\n const chars = '0123456789ABCDEF';\n let result = '';\n const values = crypto.getRandomValues(new Uint8Array(6));\n for (let i = 0; i < 6; i++) {\n result += chars[values[i] % chars.length];\n }\n return result.match(/.{1,2}/g).join('-');\n }\n\n // Enhanced message encryption with metadata protection and sequence numbers\n static async encryptMessage(message, encryptionKey, macKey, metadataKey, messageId, sequenceNumber = 0) {\n try {\n if (!message || typeof message !== 'string') {\n throw new Error('Invalid message format');\n }\n\n EnhancedSecureCryptoUtils.assertCryptoKey(encryptionKey, 'AES-GCM', ['encrypt']);\n EnhancedSecureCryptoUtils.assertCryptoKey(macKey, 'HMAC', ['sign']);\n EnhancedSecureCryptoUtils.assertCryptoKey(metadataKey, 'AES-GCM', ['encrypt']);\n\n const encoder = new TextEncoder();\n const messageData = encoder.encode(message);\n const messageIv = crypto.getRandomValues(new Uint8Array(12));\n const metadataIv = crypto.getRandomValues(new Uint8Array(12));\n const timestamp = Date.now();\n\n const paddingSize = 16 - (messageData.length % 16);\n const paddedMessage = new Uint8Array(messageData.length + paddingSize);\n paddedMessage.set(messageData);\n const padding = crypto.getRandomValues(new Uint8Array(paddingSize));\n paddedMessage.set(padding, messageData.length);\n\n const encryptedMessage = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: messageIv },\n encryptionKey,\n paddedMessage\n );\n\n const metadata = {\n id: messageId,\n timestamp: timestamp,\n sequenceNumber: sequenceNumber,\n originalLength: messageData.length,\n version: '4.0'\n };\n\n const metadataStr = JSON.stringify(EnhancedSecureCryptoUtils.sortObjectKeys(metadata));\n const encryptedMetadata = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: metadataIv },\n metadataKey,\n encoder.encode(metadataStr)\n );\n\n const payload = {\n messageIv: Array.from(messageIv),\n messageData: Array.from(new Uint8Array(encryptedMessage)),\n metadataIv: Array.from(metadataIv),\n metadataData: Array.from(new Uint8Array(encryptedMetadata)),\n version: '4.0'\n };\n\n const sortedPayload = EnhancedSecureCryptoUtils.sortObjectKeys(payload);\n const payloadStr = JSON.stringify(sortedPayload);\n\n const mac = await crypto.subtle.sign(\n 'HMAC',\n macKey,\n encoder.encode(payloadStr)\n );\n\n payload.mac = Array.from(new Uint8Array(mac));\n\n EnhancedSecureCryptoUtils.secureLog.log('info', 'Message encrypted with metadata protection', {\n messageId,\n sequenceNumber,\n hasMetadataProtection: true,\n hasPadding: true\n });\n\n return payload;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Message encryption failed', {\n error: error.message,\n messageId\n });\n throw new Error(`Failed to encrypt the message: ${error.message}`);\n }\n }\n\n // Enhanced message decryption with metadata protection and sequence validation\n static async decryptMessage(encryptedPayload, encryptionKey, macKey, metadataKey, expectedSequenceNumber = null) {\n try {\n EnhancedSecureCryptoUtils.assertCryptoKey(encryptionKey, 'AES-GCM', ['decrypt']);\n EnhancedSecureCryptoUtils.assertCryptoKey(macKey, 'HMAC', ['verify']);\n EnhancedSecureCryptoUtils.assertCryptoKey(metadataKey, 'AES-GCM', ['decrypt']);\n\n const requiredFields = ['messageIv', 'messageData', 'metadataIv', 'metadataData', 'mac', 'version'];\n for (const field of requiredFields) {\n if (!encryptedPayload[field]) {\n throw new Error(`Missing required field: ${field}`);\n }\n }\n\n const payloadCopy = { ...encryptedPayload };\n delete payloadCopy.mac;\n const sortedPayloadCopy = EnhancedSecureCryptoUtils.sortObjectKeys(payloadCopy);\n const payloadStr = JSON.stringify(sortedPayloadCopy);\n\n const macValid = await crypto.subtle.verify(\n 'HMAC',\n macKey,\n new Uint8Array(encryptedPayload.mac),\n new TextEncoder().encode(payloadStr)\n );\n\n if (!macValid) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'MAC verification failed', {\n payloadFields: Object.keys(encryptedPayload),\n macLength: encryptedPayload.mac?.length\n });\n throw new Error('Message authentication failed - possible tampering');\n }\n\n const metadataIv = new Uint8Array(encryptedPayload.metadataIv);\n const metadataData = new Uint8Array(encryptedPayload.metadataData);\n\n const decryptedMetadataBuffer = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: metadataIv },\n metadataKey,\n metadataData\n );\n\n const metadataStr = new TextDecoder().decode(decryptedMetadataBuffer);\n const metadata = JSON.parse(metadataStr);\n\n if (!metadata.id || !metadata.timestamp || metadata.sequenceNumber === undefined || !metadata.originalLength) {\n throw new Error('Invalid metadata structure');\n }\n\n const messageAge = Date.now() - metadata.timestamp;\n if (messageAge > 300000) {\n throw new Error('Message expired (older than 5 minutes)');\n }\n\n if (expectedSequenceNumber !== null) {\n if (metadata.sequenceNumber < expectedSequenceNumber) {\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'Received message with lower sequence number, possible queued message', {\n expected: expectedSequenceNumber,\n received: metadata.sequenceNumber,\n messageId: metadata.id\n });\n } else if (metadata.sequenceNumber > expectedSequenceNumber + 10) {\n throw new Error(`Sequence number gap too large: expected around ${expectedSequenceNumber}, got ${metadata.sequenceNumber}`);\n }\n }\n\n const messageIv = new Uint8Array(encryptedPayload.messageIv);\n const messageData = new Uint8Array(encryptedPayload.messageData);\n\n const decryptedMessageBuffer = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: messageIv },\n encryptionKey,\n messageData\n );\n\n const paddedMessage = new Uint8Array(decryptedMessageBuffer);\n const originalMessage = paddedMessage.slice(0, metadata.originalLength);\n\n const decoder = new TextDecoder();\n const message = decoder.decode(originalMessage);\n\n EnhancedSecureCryptoUtils.secureLog.log('info', 'Message decrypted successfully', {\n messageId: metadata.id,\n sequenceNumber: metadata.sequenceNumber,\n messageAge: Math.round(messageAge / 1000) + 's'\n });\n\n return {\n message: message,\n messageId: metadata.id,\n timestamp: metadata.timestamp,\n sequenceNumber: metadata.sequenceNumber\n };\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Message decryption failed', { error: error.message });\n throw new Error(`Failed to decrypt the message: ${error.message}`);\n }\n }\n\n // Enhanced input sanitization\n static sanitizeMessage(message) {\n if (typeof message !== 'string') {\n throw new Error('Message must be a string');\n }\n \n return message\n .replace(/)<[^<]*)*<\\/script>/gi, '')\n .replace(/javascript:/gi, '')\n .replace(/data:/gi, '')\n .replace(/vbscript:/gi, '')\n .replace(/onload\\s*=/gi, '')\n .replace(/onerror\\s*=/gi, '')\n .replace(/onclick\\s*=/gi, '')\n .trim()\n .substring(0, 2000); // Increased limit\n }\n\n // Generate cryptographically secure salt (64 bytes for enhanced security)\n static generateSalt() {\n return Array.from(crypto.getRandomValues(new Uint8Array(64)));\n }\n\n // Calculate key fingerprint for MITM protection\n static async calculateKeyFingerprint(keyData) {\n try {\n const encoder = new TextEncoder();\n const keyBytes = new Uint8Array(keyData);\n \n // Create a hash of the key data for fingerprinting\n const hashBuffer = await crypto.subtle.digest('SHA-256', keyBytes);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n \n // Convert to hexadecimal string\n const fingerprint = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Key fingerprint calculated', {\n keySize: keyData.length,\n fingerprintLength: fingerprint.length\n });\n \n return fingerprint;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Key fingerprint calculation failed', { error: error.message });\n throw new Error('Failed to compute the key fingerprint');\n }\n }\n\n static constantTimeCompare(a, b) {\n const strA = typeof a === 'string' ? a : JSON.stringify(a);\n const strB = typeof b === 'string' ? b : JSON.stringify(b);\n \n if (strA.length !== strB.length) {\n let dummy = 0;\n for (let i = 0; i < Math.max(strA.length, strB.length); i++) {\n dummy |= (strA.charCodeAt(i % strA.length) || 0) ^ (strB.charCodeAt(i % strB.length) || 0);\n }\n return false;\n }\n \n let result = 0;\n for (let i = 0; i < strA.length; i++) {\n result |= strA.charCodeAt(i) ^ strB.charCodeAt(i);\n }\n \n return result === 0;\n }\n\n static constantTimeCompareArrays(arr1, arr2) {\n if (!Array.isArray(arr1) || !Array.isArray(arr2)) {\n return false;\n }\n \n if (arr1.length !== arr2.length) {\n let dummy = 0;\n const maxLen = Math.max(arr1.length, arr2.length);\n for (let i = 0; i < maxLen; i++) {\n dummy |= (arr1[i % arr1.length] || 0) ^ (arr2[i % arr2.length] || 0);\n }\n return false;\n }\n \n let result = 0;\n for (let i = 0; i < arr1.length; i++) {\n result |= arr1[i] ^ arr2[i];\n }\n \n return result === 0;\n }\n \n /**\n * CRITICAL SECURITY: Encrypt data with AAD (Additional Authenticated Data)\n * This method provides authenticated encryption with additional data binding\n */\n static async encryptDataWithAAD(data, key, aad) {\n try {\n const dataString = typeof data === 'string' ? data : JSON.stringify(data);\n const encoder = new TextEncoder();\n const dataBuffer = encoder.encode(dataString);\n const aadBuffer = encoder.encode(aad);\n\n // Generate random IV\n const iv = crypto.getRandomValues(new Uint8Array(12));\n\n // Encrypt with AAD\n const encrypted = await crypto.subtle.encrypt(\n { \n name: 'AES-GCM', \n iv: iv,\n additionalData: aadBuffer\n },\n key,\n dataBuffer\n );\n\n // Package encrypted data\n const encryptedPackage = {\n version: '1.0',\n iv: Array.from(iv),\n data: Array.from(new Uint8Array(encrypted)),\n aad: aad,\n timestamp: Date.now()\n };\n\n const packageString = JSON.stringify(encryptedPackage);\n const packageBuffer = encoder.encode(packageString);\n \n return EnhancedSecureCryptoUtils.arrayBufferToBase64(packageBuffer);\n } catch (error) {\n throw new Error(`AAD encryption failed: ${error.message}`);\n }\n }\n\n /**\n * CRITICAL SECURITY: Decrypt data with AAD validation\n * This method provides authenticated decryption with additional data validation\n */\n static async decryptDataWithAAD(encryptedData, key, expectedAad) {\n try {\n const packageBuffer = EnhancedSecureCryptoUtils.base64ToArrayBuffer(encryptedData);\n const packageString = new TextDecoder().decode(packageBuffer);\n const encryptedPackage = JSON.parse(packageString);\n\n if (!encryptedPackage.version || !encryptedPackage.iv || !encryptedPackage.data || !encryptedPackage.aad) {\n throw new Error('Invalid encrypted data format');\n }\n\n // Validate AAD matches expected\n if (encryptedPackage.aad !== expectedAad) {\n throw new Error('AAD mismatch - possible tampering or replay attack');\n }\n\n const iv = new Uint8Array(encryptedPackage.iv);\n const encrypted = new Uint8Array(encryptedPackage.data);\n const aadBuffer = new TextEncoder().encode(encryptedPackage.aad);\n\n // Decrypt with AAD validation\n const decrypted = await crypto.subtle.decrypt(\n { \n name: 'AES-GCM', \n iv: iv,\n additionalData: aadBuffer\n },\n key,\n encrypted\n );\n\n const decryptedString = new TextDecoder().decode(decrypted);\n\n try {\n return JSON.parse(decryptedString);\n } catch {\n return decryptedString;\n }\n } catch (error) {\n throw new Error(`AAD decryption failed: ${error.message}`);\n }\n }\n\n // Initialize secure logging system after class definition\n static {\n if (EnhancedSecureCryptoUtils.secureLog && typeof EnhancedSecureCryptoUtils.secureLog.init === 'function') {\n EnhancedSecureCryptoUtils.secureLog.init();\n }\n }\n}\n\nexport { EnhancedSecureCryptoUtils };", "// ============================================\n// SECURE FILE TRANSFER CONTEXT\n// ============================================\nclass SecureFileTransferContext {\n static #instance = null;\n static #contextKey = Symbol('SecureFileTransferContext');\n \n static getInstance() {\n if (!this.#instance) {\n this.#instance = new SecureFileTransferContext();\n }\n return this.#instance;\n }\n \n #fileTransferSystem = null;\n #active = false;\n #securityLevel = 'high';\n \n setFileTransferSystem(system) {\n if (!(system instanceof EnhancedSecureFileTransfer)) {\n throw new Error('Invalid file transfer system instance');\n }\n this.#fileTransferSystem = system;\n this.#active = true;\n console.log('\uD83D\uDD12 Secure file transfer context initialized');\n }\n \n getFileTransferSystem() {\n return this.#fileTransferSystem;\n }\n \n isActive() {\n return this.#active && this.#fileTransferSystem !== null;\n }\n \n deactivate() {\n this.#active = false;\n this.#fileTransferSystem = null;\n console.log('\uD83D\uDD12 Secure file transfer context deactivated');\n }\n \n getSecurityLevel() {\n return this.#securityLevel;\n }\n \n setSecurityLevel(level) {\n if (['low', 'medium', 'high'].includes(level)) {\n this.#securityLevel = level;\n }\n }\n}\n\n// ============================================\n// SECURITY ERROR HANDLER\n// ============================================\n\nclass SecurityErrorHandler {\n static #allowedErrors = new Set([\n 'File size exceeds maximum limit',\n 'Unsupported file type',\n 'Transfer timeout',\n 'Connection lost',\n 'Invalid file data',\n 'File transfer failed',\n 'Transfer cancelled',\n 'Network error',\n 'File not found',\n 'Permission denied'\n ]);\n \n static sanitizeError(error) {\n const message = error.message || error;\n\n for (const allowed of this.#allowedErrors) {\n if (message.includes(allowed)) {\n return allowed;\n }\n }\n\n console.error('\uD83D\uDD12 Internal file transfer error:', {\n message: error.message,\n stack: error.stack,\n timestamp: new Date().toISOString()\n });\n\n return 'File transfer failed';\n }\n \n static logSecurityEvent(event, details = {}) {\n console.warn('\uD83D\uDD12 Security event:', {\n event,\n timestamp: new Date().toISOString(),\n ...details\n });\n }\n}\n\n// ============================================\n// FILE METADATA SIGNATURE SYSTEM\n// ============================================\n\nclass FileMetadataSigner {\n static async signFileMetadata(metadata, privateKey) {\n try {\n const encoder = new TextEncoder();\n const data = encoder.encode(JSON.stringify({\n fileId: metadata.fileId,\n fileName: metadata.fileName,\n fileSize: metadata.fileSize,\n fileHash: metadata.fileHash,\n timestamp: metadata.timestamp,\n version: metadata.version || '2.0'\n }));\n \n const signature = await crypto.subtle.sign(\n 'RSASSA-PKCS1-v1_5',\n privateKey,\n data\n );\n \n return Array.from(new Uint8Array(signature));\n } catch (error) {\n SecurityErrorHandler.logSecurityEvent('signature_failed', { error: error.message });\n throw new Error('Failed to sign file metadata');\n }\n }\n \n static async verifyFileMetadata(metadata, signature, publicKey) {\n try {\n const encoder = new TextEncoder();\n const data = encoder.encode(JSON.stringify({\n fileId: metadata.fileId,\n fileName: metadata.fileName,\n fileSize: metadata.fileSize,\n fileHash: metadata.fileHash,\n timestamp: metadata.timestamp,\n version: metadata.version || '2.0'\n }));\n \n const signatureBuffer = new Uint8Array(signature);\n \n const isValid = await crypto.subtle.verify(\n 'RSASSA-PKCS1-v1_5',\n publicKey,\n signatureBuffer,\n data\n );\n \n if (!isValid) {\n SecurityErrorHandler.logSecurityEvent('invalid_signature', { fileId: metadata.fileId });\n }\n \n return isValid;\n } catch (error) {\n SecurityErrorHandler.logSecurityEvent('verification_failed', { error: error.message });\n return false;\n }\n }\n}\n\n// ============================================\n// \u0422\u041E\u0427\u041D\u042B\u0415 \u0418\u0421\u041F\u0420\u0410\u0412\u041B\u0415\u041D\u0418\u042F \u0411\u0415\u0417\u041E\u041F\u0410\u0421\u041D\u041E\u0421\u0422\u0418\n// ============================================\n\nclass MessageSizeValidator {\n static MAX_MESSAGE_SIZE = 1024 * 1024; // 1MB\n \n static isMessageSizeValid(message) {\n const messageString = JSON.stringify(message);\n const sizeInBytes = new Blob([messageString]).size;\n \n if (sizeInBytes > this.MAX_MESSAGE_SIZE) {\n SecurityErrorHandler.logSecurityEvent('message_too_large', {\n size: sizeInBytes,\n limit: this.MAX_MESSAGE_SIZE\n });\n throw new Error('Message too large');\n }\n \n return true;\n }\n}\n\nclass AtomicOperations {\n constructor() {\n this.locks = new Map();\n }\n \n async withLock(key, operation) {\n if (this.locks.has(key)) {\n await this.locks.get(key);\n }\n \n const lockPromise = (async () => {\n try {\n return await operation();\n } finally {\n this.locks.delete(key);\n }\n })();\n \n this.locks.set(key, lockPromise);\n return lockPromise;\n }\n}\n\n// Rate limiting \u0434\u043B\u044F \u0437\u0430\u0449\u0438\u0442\u044B \u043E\u0442 \u0441\u043F\u0430\u043C\u0430\nclass RateLimiter {\n constructor(maxRequests, windowMs) {\n this.maxRequests = maxRequests;\n this.windowMs = windowMs;\n this.requests = new Map();\n }\n \n isAllowed(identifier) {\n const now = Date.now();\n const windowStart = now - this.windowMs;\n \n if (!this.requests.has(identifier)) {\n this.requests.set(identifier, []);\n }\n \n const userRequests = this.requests.get(identifier);\n \n const validRequests = userRequests.filter(time => time > windowStart);\n this.requests.set(identifier, validRequests);\n \n if (validRequests.length >= this.maxRequests) {\n SecurityErrorHandler.logSecurityEvent('rate_limit_exceeded', {\n identifier,\n requestCount: validRequests.length,\n limit: this.maxRequests\n });\n return false;\n }\n \n validRequests.push(now);\n return true;\n }\n}\n\nclass SecureMemoryManager {\n static secureWipe(buffer) {\n if (buffer instanceof ArrayBuffer) {\n const view = new Uint8Array(buffer);\n crypto.getRandomValues(view);\n } else if (buffer instanceof Uint8Array) {\n crypto.getRandomValues(buffer);\n }\n }\n \n static secureDelete(obj, prop) {\n if (obj[prop]) {\n this.secureWipe(obj[prop]);\n delete obj[prop];\n }\n }\n}\n\nclass EnhancedSecureFileTransfer {\n constructor(webrtcManager, onProgress, onComplete, onError, onFileReceived) {\n this.webrtcManager = webrtcManager;\n this.onProgress = onProgress;\n this.onComplete = onComplete;\n this.onError = onError;\n this.onFileReceived = onFileReceived;\n \n // Validate webrtcManager\n if (!webrtcManager) {\n throw new Error('webrtcManager is required for EnhancedSecureFileTransfer');\n }\n \n SecureFileTransferContext.getInstance().setFileTransferSystem(this);\n \n this.atomicOps = new AtomicOperations();\n this.rateLimiter = new RateLimiter(10, 60000);\n\n this.signingKey = null;\n this.verificationKey = null;\n \n // Transfer settings\n this.CHUNK_SIZE = 64 * 1024; // 64 KB\n this.MAX_FILE_SIZE = 100 * 1024 * 1024; // 100 MB limit\n this.MAX_CONCURRENT_TRANSFERS = 3;\n this.CHUNK_TIMEOUT = 30000; // 30 seconds per chunk\n this.RETRY_ATTEMPTS = 3;\n\n this.FILE_TYPE_RESTRICTIONS = {\n documents: {\n extensions: ['.pdf', '.doc', '.docx', '.txt', '.md', '.rtf', '.odt'],\n mimeTypes: [\n 'application/pdf',\n 'application/msword',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'text/plain',\n 'text/markdown',\n 'application/rtf',\n 'application/vnd.oasis.opendocument.text'\n ],\n maxSize: 50 * 1024 * 1024, // 50 MB\n category: 'Documents',\n description: 'PDF, DOC, TXT, MD, RTF, ODT'\n },\n \n images: {\n extensions: ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.ico'],\n mimeTypes: [\n 'image/jpeg',\n 'image/png',\n 'image/gif',\n 'image/webp',\n 'image/bmp',\n 'image/svg+xml',\n 'image/x-icon'\n ],\n maxSize: 25 * 1024 * 1024, // 25 MB\n category: 'Images',\n description: 'JPG, PNG, GIF, WEBP, BMP, SVG, ICO'\n },\n \n archives: {\n extensions: ['.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.xz'],\n mimeTypes: [\n 'application/zip',\n 'application/x-rar-compressed',\n 'application/x-7z-compressed',\n 'application/x-tar',\n 'application/gzip',\n 'application/x-bzip2',\n 'application/x-xz'\n ],\n maxSize: 100 * 1024 * 1024, // 100 MB\n category: 'Archives',\n description: 'ZIP, RAR, 7Z, TAR, GZ, BZ2, XZ'\n },\n \n media: {\n extensions: ['.mp3', '.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.ogg', '.wav'],\n mimeTypes: [\n 'audio/mpeg',\n 'video/mp4',\n 'video/x-msvideo',\n 'video/x-matroska',\n 'video/quicktime',\n 'video/x-ms-wmv',\n 'video/x-flv',\n 'video/webm',\n 'audio/ogg',\n 'audio/wav'\n ],\n maxSize: 100 * 1024 * 1024, // 100 MB\n category: 'Media',\n description: 'MP3, MP4, AVI, MKV, MOV, WMV, FLV, WEBM, OGG, WAV'\n },\n \n general: {\n extensions: [], \n mimeTypes: [], \n maxSize: 50 * 1024 * 1024, // 50 MB\n category: 'General',\n description: 'Any file type up to size limits'\n }\n };\n \n // Active transfers tracking\n this.activeTransfers = new Map(); // fileId -> transfer state\n this.receivingTransfers = new Map(); // fileId -> receiving state\n this.transferQueue = []; // Queue for pending transfers\n this.pendingChunks = new Map();\n \n // Session key derivation\n this.sessionKeys = new Map(); // fileId -> derived session key\n \n // Security\n this.processedChunks = new Set(); // Prevent replay attacks\n this.transferNonces = new Map(); // fileId -> current nonce counter\n this.receivedFileBuffers = new Map(); // fileId -> { buffer:ArrayBuffer, type:string, name:string, size:number }\n\n this.setupFileMessageHandlers();\n\n if (this.webrtcManager) {\n this.webrtcManager.fileTransferSystem = this;\n }\n }\n\n // ============================================\n // FILE TYPE VALIDATION SYSTEM\n // ============================================\n\n getFileType(file) {\n const fileName = file.name.toLowerCase();\n const fileExtension = fileName.substring(fileName.lastIndexOf('.'));\n const mimeType = file.type.toLowerCase();\n\n for (const [typeKey, typeConfig] of Object.entries(this.FILE_TYPE_RESTRICTIONS)) {\n if (typeKey === 'general') continue; // \u041F\u0440\u043E\u043F\u0443\u0441\u043A\u0430\u0435\u043C \u043E\u0431\u0449\u0438\u0439 \u0442\u0438\u043F\n\n if (typeConfig.extensions.includes(fileExtension)) {\n return {\n type: typeKey,\n category: typeConfig.category,\n description: typeConfig.description,\n maxSize: typeConfig.maxSize,\n allowed: true\n };\n }\n\n if (typeConfig.mimeTypes.includes(mimeType)) {\n return {\n type: typeKey,\n category: typeConfig.category,\n description: typeConfig.description,\n maxSize: typeConfig.maxSize,\n allowed: true\n };\n }\n }\n\n const generalConfig = this.FILE_TYPE_RESTRICTIONS.general;\n return {\n type: 'general',\n category: generalConfig.category,\n description: generalConfig.description,\n maxSize: generalConfig.maxSize,\n allowed: true\n };\n }\n\n validateFile(file) {\n const fileType = this.getFileType(file);\n const errors = [];\n\n if (file.size > fileType.maxSize) {\n errors.push(`File size (${this.formatFileSize(file.size)}) exceeds maximum allowed for ${fileType.category} (${this.formatFileSize(fileType.maxSize)})`);\n }\n\n if (!fileType.allowed) {\n errors.push(`File type not allowed. Supported types: ${fileType.description}`);\n }\n\n if (file.size > this.MAX_FILE_SIZE) {\n errors.push(`File size (${this.formatFileSize(file.size)}) exceeds general limit (${this.formatFileSize(this.MAX_FILE_SIZE)})`);\n }\n \n return {\n isValid: errors.length === 0,\n errors: errors,\n fileType: fileType,\n fileSize: file.size,\n formattedSize: this.formatFileSize(file.size)\n };\n }\n\n formatFileSize(bytes) {\n if (bytes === 0) return '0 B';\n const k = 1024;\n const sizes = ['B', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n }\n\n getSupportedFileTypes() {\n const supportedTypes = {};\n \n for (const [typeKey, typeConfig] of Object.entries(this.FILE_TYPE_RESTRICTIONS)) {\n if (typeKey === 'general') continue;\n \n supportedTypes[typeKey] = {\n category: typeConfig.category,\n description: typeConfig.description,\n extensions: typeConfig.extensions,\n maxSize: this.formatFileSize(typeConfig.maxSize),\n maxSizeBytes: typeConfig.maxSize\n };\n }\n \n return supportedTypes;\n }\n\n getFileTypeInfo() {\n return {\n supportedTypes: this.getSupportedFileTypes(),\n generalMaxSize: this.formatFileSize(this.MAX_FILE_SIZE),\n generalMaxSizeBytes: this.MAX_FILE_SIZE,\n restrictions: this.FILE_TYPE_RESTRICTIONS\n };\n }\n\n // ============================================\n // ENCODING HELPERS (Base64 for efficient transport)\n // ============================================\n arrayBufferToBase64(buffer) {\n const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n let binary = '';\n const len = bytes.byteLength;\n for (let i = 0; i < len; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n }\n\n base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const len = binaryString.length;\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n }\n\n // ============================================\n // PUBLIC ACCESSORS FOR RECEIVED FILES\n // ============================================\n getReceivedFileMeta(fileId) {\n const entry = this.receivedFileBuffers.get(fileId);\n if (!entry) return null;\n return { fileId, fileName: entry.name, fileSize: entry.size, mimeType: entry.type };\n }\n\n async getBlob(fileId) {\n const entry = this.receivedFileBuffers.get(fileId);\n if (!entry) return null;\n return new Blob([entry.buffer], { type: entry.type });\n }\n\n async getObjectURL(fileId) {\n const blob = await this.getBlob(fileId);\n if (!blob) return null;\n return URL.createObjectURL(blob);\n }\n\n revokeObjectURL(url) {\n try { URL.revokeObjectURL(url); } catch (_) {}\n }\n\n setupFileMessageHandlers() {\n if (!this.webrtcManager.dataChannel) {\n const setupRetry = setInterval(() => {\n if (this.webrtcManager.dataChannel) {\n clearInterval(setupRetry);\n this.setupMessageInterception();\n }\n }, 100);\n\n setTimeout(() => {\n clearInterval(setupRetry);\n }, 5000);\n \n return;\n }\n \n // \u0415\u0441\u043B\u0438 dataChannel \u0443\u0436\u0435 \u0433\u043E\u0442\u043E\u0432, \u0441\u0440\u0430\u0437\u0443 \u043D\u0430\u0441\u0442\u0440\u0430\u0438\u0432\u0430\u0435\u043C\n this.setupMessageInterception();\n }\n\n setupMessageInterception() {\n try {\n if (!this.webrtcManager.dataChannel) {\n return;\n }\n\n if (this.webrtcManager) {\n this.webrtcManager.fileTransferSystem = this;\n }\n\n if (this.webrtcManager.dataChannel.onmessage) {\n this.originalOnMessage = this.webrtcManager.dataChannel.onmessage;\n }\n\n this.webrtcManager.dataChannel.onmessage = async (event) => {\n try {\n if (event.data.length > MessageSizeValidator.MAX_MESSAGE_SIZE) {\n console.warn('\uD83D\uDD12 Message too large, ignoring');\n SecurityErrorHandler.logSecurityEvent('oversized_message_blocked');\n return;\n }\n \n if (typeof event.data === 'string') {\n try {\n const parsed = JSON.parse(event.data);\n \n MessageSizeValidator.isMessageSizeValid(parsed);\n \n if (this.isFileTransferMessage(parsed)) {\n await this.handleFileMessage(parsed);\n return; \n }\n } catch (parseError) {\n if (parseError.message === 'Message too large') {\n return; \n }\n }\n }\n\n if (this.originalOnMessage) {\n return this.originalOnMessage.call(this.webrtcManager.dataChannel, event);\n }\n } catch (error) {\n console.error('\u274C Error in file system message interception:', error);\n if (this.originalOnMessage) {\n return this.originalOnMessage.call(this.webrtcManager.dataChannel, event);\n }\n }\n };\n } catch (error) {\n console.error('\u274C Failed to set up message interception:', error);\n }\n }\n\n isFileTransferMessage(message) {\n if (!message || typeof message !== 'object' || !message.type) {\n return false;\n }\n \n const fileMessageTypes = [\n 'file_transfer_start',\n 'file_transfer_response', \n 'file_chunk',\n 'chunk_confirmation',\n 'file_transfer_complete',\n 'file_transfer_error'\n ];\n \n return fileMessageTypes.includes(message.type);\n }\n\n async handleFileMessage(message) {\n try {\n if (!this.webrtcManager.fileTransferSystem) {\n try {\n if (typeof this.webrtcManager.initializeFileTransfer === 'function') {\n this.webrtcManager.initializeFileTransfer();\n \n let attempts = 0;\n const maxAttempts = 50; \n while (!this.webrtcManager.fileTransferSystem && attempts < maxAttempts) {\n await new Promise(resolve => setTimeout(resolve, 100));\n attempts++;\n }\n \n if (!this.webrtcManager.fileTransferSystem) {\n throw new Error('File transfer system initialization timeout');\n }\n } else {\n throw new Error('initializeFileTransfer method not available');\n }\n } catch (initError) {\n console.error('\u274C Failed to initialize file transfer system:', initError);\n if (message.fileId) {\n const errorMessage = {\n type: 'file_transfer_error',\n fileId: message.fileId,\n error: 'File transfer system not available',\n timestamp: Date.now()\n };\n await this.sendSecureMessage(errorMessage);\n }\n return;\n }\n }\n \n switch (message.type) {\n case 'file_transfer_start':\n await this.handleFileTransferStart(message);\n break;\n \n case 'file_transfer_response':\n this.handleTransferResponse(message);\n break;\n \n case 'file_chunk':\n await this.handleFileChunk(message);\n break;\n \n case 'chunk_confirmation':\n this.handleChunkConfirmation(message);\n break;\n \n case 'file_transfer_complete':\n this.handleTransferComplete(message);\n break;\n \n case 'file_transfer_error':\n this.handleTransferError(message);\n break;\n \n default:\n console.warn('\u26A0\uFE0F Unknown file message type:', message.type);\n }\n \n } catch (error) {\n console.error('\u274C Error handling file message:', error);\n\n if (message.fileId) {\n const errorMessage = {\n type: 'file_transfer_error',\n fileId: message.fileId,\n error: error.message,\n timestamp: Date.now()\n };\n await this.sendSecureMessage(errorMessage);\n }\n }\n }\n\n // ============================================\n // SIMPLIFIED KEY DERIVATION - USE SHARED DATA\n // ============================================\n\n async deriveFileSessionKey(fileId) {\n try {\n \n if (!this.webrtcManager.keyFingerprint || !this.webrtcManager.sessionSalt) {\n throw new Error('WebRTC session data not available');\n }\n\n const fileSalt = crypto.getRandomValues(new Uint8Array(32));\n\n const encoder = new TextEncoder();\n const fingerprintData = encoder.encode(this.webrtcManager.keyFingerprint);\n const fileIdData = encoder.encode(fileId);\n\n const sessionSaltArray = new Uint8Array(this.webrtcManager.sessionSalt);\n const combinedSeed = new Uint8Array(\n fingerprintData.length + \n sessionSaltArray.length + \n fileSalt.length + \n fileIdData.length\n );\n \n let offset = 0;\n combinedSeed.set(fingerprintData, offset);\n offset += fingerprintData.length;\n combinedSeed.set(sessionSaltArray, offset);\n offset += sessionSaltArray.length;\n combinedSeed.set(fileSalt, offset);\n offset += fileSalt.length;\n combinedSeed.set(fileIdData, offset);\n\n const keyMaterial = await crypto.subtle.digest('SHA-256', combinedSeed);\n\n const fileSessionKey = await crypto.subtle.importKey(\n 'raw',\n keyMaterial,\n { name: 'AES-GCM' },\n false,\n ['encrypt', 'decrypt']\n );\n\n this.sessionKeys.set(fileId, {\n key: fileSessionKey,\n salt: Array.from(fileSalt),\n created: Date.now()\n });\n\n return { key: fileSessionKey, salt: Array.from(fileSalt) };\n\n } catch (error) {\n console.error('\u274C Failed to derive file session key:', error);\n throw error;\n }\n }\n\n async deriveFileSessionKeyFromSalt(fileId, saltArray) {\n try {\n if (!saltArray || !Array.isArray(saltArray) || saltArray.length !== 32) {\n throw new Error(`Invalid salt: ${saltArray?.length || 0} bytes`);\n }\n \n if (!this.webrtcManager.keyFingerprint || !this.webrtcManager.sessionSalt) {\n throw new Error('WebRTC session data not available');\n }\n\n const encoder = new TextEncoder();\n const fingerprintData = encoder.encode(this.webrtcManager.keyFingerprint);\n const fileIdData = encoder.encode(fileId);\n\n const fileSalt = new Uint8Array(saltArray);\n const sessionSaltArray = new Uint8Array(this.webrtcManager.sessionSalt);\n\n const combinedSeed = new Uint8Array(\n fingerprintData.length + \n sessionSaltArray.length + \n fileSalt.length + \n fileIdData.length\n );\n \n let offset = 0;\n combinedSeed.set(fingerprintData, offset);\n offset += fingerprintData.length;\n combinedSeed.set(sessionSaltArray, offset);\n offset += sessionSaltArray.length;\n combinedSeed.set(fileSalt, offset);\n offset += fileSalt.length;\n combinedSeed.set(fileIdData, offset);\n\n const keyMaterial = await crypto.subtle.digest('SHA-256', combinedSeed);\n\n const fileSessionKey = await crypto.subtle.importKey(\n 'raw',\n keyMaterial,\n { name: 'AES-GCM' },\n false,\n ['encrypt', 'decrypt']\n );\n\n this.sessionKeys.set(fileId, {\n key: fileSessionKey,\n salt: saltArray,\n created: Date.now()\n });\n\n return fileSessionKey;\n\n } catch (error) {\n console.error('\u274C Failed to derive session key from salt:', error);\n throw error;\n }\n }\n\n // ============================================\n // FILE TRANSFER IMPLEMENTATION\n // ============================================\n\n async sendFile(file) {\n try {\n // Validate webrtcManager\n if (!this.webrtcManager) {\n throw new Error('WebRTC Manager not initialized');\n }\n\n const clientId = this.getClientIdentifier();\n if (!this.rateLimiter.isAllowed(clientId)) {\n SecurityErrorHandler.logSecurityEvent('rate_limit_exceeded', { clientId });\n throw new Error('Rate limit exceeded. Please wait before sending another file.');\n }\n\n if (!file || !file.size) {\n throw new Error('Invalid file object');\n }\n\n const validation = this.validateFile(file);\n if (!validation.isValid) {\n const errorMessage = validation.errors.join('. ');\n throw new Error(errorMessage);\n }\n\n if (this.activeTransfers.size >= this.MAX_CONCURRENT_TRANSFERS) {\n throw new Error('Maximum concurrent transfers reached');\n }\n\n // Generate unique file ID\n const fileId = `file_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n \n // Calculate file hash for integrity verification\n const fileHash = await this.calculateFileHash(file);\n \n // Derive session key for this file\n const keyResult = await this.deriveFileSessionKey(fileId);\n const sessionKey = keyResult.key;\n const salt = keyResult.salt;\n \n // Create transfer state\n const transferState = {\n fileId: fileId,\n file: file,\n fileHash: fileHash,\n sessionKey: sessionKey,\n salt: salt, \n totalChunks: Math.ceil(file.size / this.CHUNK_SIZE),\n sentChunks: 0,\n confirmedChunks: 0,\n startTime: Date.now(),\n status: 'preparing',\n retryCount: 0,\n lastChunkTime: Date.now()\n };\n\n this.activeTransfers.set(fileId, transferState);\n this.transferNonces.set(fileId, 0);\n\n // Send file metadata first\n await this.sendFileMetadata(transferState);\n \n // Start chunk transmission\n await this.startChunkTransmission(transferState);\n \n return fileId;\n\n } catch (error) {\n const safeError = SecurityErrorHandler.sanitizeError(error);\n console.error('\u274C File sending failed:', safeError);\n if (this.onError) this.onError(safeError);\n throw new Error(safeError);\n }\n }\n\n async sendFileMetadata(transferState) {\n try {\n const metadata = {\n type: 'file_transfer_start',\n fileId: transferState.fileId,\n fileName: transferState.file.name,\n fileSize: transferState.file.size,\n fileType: transferState.file.type || 'application/octet-stream',\n fileHash: transferState.fileHash,\n totalChunks: transferState.totalChunks,\n chunkSize: this.CHUNK_SIZE,\n salt: transferState.salt, \n timestamp: Date.now(),\n version: '2.0'\n };\n\n if (this.signingKey) {\n try {\n metadata.signature = await FileMetadataSigner.signFileMetadata(metadata, this.signingKey);\n console.log('\uD83D\uDD12 File metadata signed successfully');\n } catch (signError) {\n SecurityErrorHandler.logSecurityEvent('signature_failed', { \n fileId: transferState.fileId, \n error: signError.message \n });\n }\n }\n\n // Send metadata through secure channel\n await this.sendSecureMessage(metadata);\n \n transferState.status = 'metadata_sent';\n\n } catch (error) {\n const safeError = SecurityErrorHandler.sanitizeError(error);\n console.error('\u274C Failed to send file metadata:', safeError);\n transferState.status = 'failed';\n throw new Error(safeError);\n }\n }\n\n async startChunkTransmission(transferState) {\n try {\n transferState.status = 'transmitting';\n \n const file = transferState.file;\n const totalChunks = transferState.totalChunks;\n \n for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {\n const start = chunkIndex * this.CHUNK_SIZE;\n const end = Math.min(start + this.CHUNK_SIZE, file.size);\n \n // Read chunk from file\n const chunkData = await this.readFileChunk(file, start, end);\n \n // Send chunk (\u0441 \u0443\u0447\u0451\u0442\u043E\u043C backpressure)\n await this.sendFileChunk(transferState, chunkIndex, chunkData);\n \n // Update progress\n transferState.sentChunks++;\n const progress = Math.round((transferState.sentChunks / totalChunks) * 95) + 5; // 5-100%\n\n await this.waitForBackpressure();\n }\n \n transferState.status = 'waiting_confirmation';\n \n // Timeout for completion confirmation\n setTimeout(() => {\n if (this.activeTransfers.has(transferState.fileId)) {\n const state = this.activeTransfers.get(transferState.fileId);\n if (state.status === 'waiting_confirmation') {\n this.cleanupTransfer(transferState.fileId);\n }\n }\n }, 30000);\n \n } catch (error) {\n const safeError = SecurityErrorHandler.sanitizeError(error);\n console.error('\u274C Chunk transmission failed:', safeError);\n transferState.status = 'failed';\n throw new Error(safeError);\n }\n }\n\n async readFileChunk(file, start, end) {\n try {\n const blob = file.slice(start, end);\n return await blob.arrayBuffer();\n } catch (error) {\n const safeError = SecurityErrorHandler.sanitizeError(error);\n console.error('\u274C Failed to read file chunk:', safeError);\n throw new Error(safeError);\n }\n }\n\n async sendFileChunk(transferState, chunkIndex, chunkData) {\n try {\n const sessionKey = transferState.sessionKey;\n const nonce = crypto.getRandomValues(new Uint8Array(12));\n \n // Encrypt chunk data\n const encryptedChunk = await crypto.subtle.encrypt(\n {\n name: 'AES-GCM',\n iv: nonce\n },\n sessionKey,\n chunkData\n );\n \n // Use Base64 to drastically reduce JSON overhead\n const encryptedB64 = this.arrayBufferToBase64(new Uint8Array(encryptedChunk));\n const chunkMessage = {\n type: 'file_chunk',\n fileId: transferState.fileId,\n chunkIndex: chunkIndex,\n totalChunks: transferState.totalChunks,\n nonce: Array.from(nonce),\n encryptedDataB64: encryptedB64,\n chunkSize: chunkData.byteLength,\n timestamp: Date.now()\n };\n\n await this.waitForBackpressure();\n // Send chunk through secure channel\n await this.sendSecureMessage(chunkMessage);\n \n } catch (error) {\n const safeError = SecurityErrorHandler.sanitizeError(error);\n console.error('\u274C Failed to send file chunk:', safeError);\n throw new Error(safeError);\n }\n }\n\n async sendSecureMessage(message) {\n\n const messageString = JSON.stringify(message);\n const dc = this.webrtcManager?.dataChannel;\n const maxRetries = 10;\n let attempt = 0;\n const wait = (ms) => new Promise(r => setTimeout(r, ms));\n\n while (true) {\n try {\n if (!dc || dc.readyState !== 'open') {\n throw new Error('Data channel not ready');\n }\n await this.waitForBackpressure();\n dc.send(messageString);\n return; // success\n } catch (error) {\n const msg = String(error?.message || '');\n const queueFull = msg.includes('send queue is full') || msg.includes('bufferedAmount');\n const opErr = error?.name === 'OperationError';\n if ((queueFull || opErr) && attempt < maxRetries) {\n attempt++;\n await this.waitForBackpressure();\n await wait(Math.min(50 * attempt, 500));\n continue;\n }\n console.error('\u274C Failed to send secure message:', error);\n throw error;\n }\n }\n }\n\n async waitForBackpressure() {\n try {\n const dc = this.webrtcManager?.dataChannel;\n if (!dc) return;\n\n if (typeof dc.bufferedAmountLowThreshold === 'number') {\n if (dc.bufferedAmount > dc.bufferedAmountLowThreshold) {\n await new Promise(resolve => {\n const handler = () => {\n dc.removeEventListener('bufferedamountlow', handler);\n resolve();\n };\n dc.addEventListener('bufferedamountlow', handler, { once: true });\n });\n }\n return;\n }\n\n const softLimit = 4 * 1024 * 1024;\n while (dc.bufferedAmount > softLimit) {\n await new Promise(r => setTimeout(r, 20));\n }\n } catch (_) {\n // ignore\n }\n }\n\n async calculateFileHash(file) {\n try {\n const arrayBuffer = await file.arrayBuffer();\n const hashBuffer = await crypto.subtle.digest('SHA-256', arrayBuffer);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n } catch (error) {\n console.error('\u274C File hash calculation failed:', error);\n throw error;\n }\n }\n\n // ============================================\n // MESSAGE HANDLERS\n // ============================================\n\n async handleFileTransferStart(metadata) {\n try {\n // Validate metadata\n if (!metadata.fileId || !metadata.fileName || !metadata.fileSize) {\n throw new Error('Invalid file transfer metadata');\n }\n\n if (metadata.signature && this.verificationKey) {\n try {\n const isValid = await FileMetadataSigner.verifyFileMetadata(\n metadata, \n metadata.signature, \n this.verificationKey\n );\n \n if (!isValid) {\n SecurityErrorHandler.logSecurityEvent('invalid_metadata_signature', { \n fileId: metadata.fileId \n });\n throw new Error('Invalid file metadata signature');\n }\n \n console.log('\uD83D\uDD12 File metadata signature verified successfully');\n } catch (verifyError) {\n SecurityErrorHandler.logSecurityEvent('verification_failed', { \n fileId: metadata.fileId, \n error: verifyError.message \n });\n throw new Error('File metadata verification failed');\n }\n }\n \n // Check if we already have this transfer\n if (this.receivingTransfers.has(metadata.fileId)) {\n return;\n }\n \n // Derive session key from salt\n const sessionKey = await this.deriveFileSessionKeyFromSalt(\n metadata.fileId,\n metadata.salt\n );\n \n // Create receiving transfer state\n const receivingState = {\n fileId: metadata.fileId,\n fileName: metadata.fileName,\n fileSize: metadata.fileSize,\n fileType: metadata.fileType || 'application/octet-stream',\n fileHash: metadata.fileHash,\n totalChunks: metadata.totalChunks,\n chunkSize: metadata.chunkSize || this.CHUNK_SIZE,\n sessionKey: sessionKey,\n salt: metadata.salt,\n receivedChunks: new Map(),\n receivedCount: 0,\n startTime: Date.now(),\n lastChunkTime: Date.now(),\n status: 'receiving'\n };\n \n this.receivingTransfers.set(metadata.fileId, receivingState);\n \n // Send acceptance response\n const response = {\n type: 'file_transfer_response',\n fileId: metadata.fileId,\n accepted: true,\n timestamp: Date.now()\n };\n \n await this.sendSecureMessage(response);\n\n // Process buffered chunks if any\n if (this.pendingChunks.has(metadata.fileId)) {\n const bufferedChunks = this.pendingChunks.get(metadata.fileId);\n \n for (const [chunkIndex, chunkMessage] of bufferedChunks.entries()) {\n await this.handleFileChunk(chunkMessage);\n }\n \n this.pendingChunks.delete(metadata.fileId);\n }\n \n } catch (error) {\n const safeError = SecurityErrorHandler.sanitizeError(error);\n console.error('\u274C Failed to handle file transfer start:', safeError);\n \n // Send error response\n const errorResponse = {\n type: 'file_transfer_response',\n fileId: metadata.fileId,\n accepted: false,\n error: safeError, \n timestamp: Date.now()\n };\n await this.sendSecureMessage(errorResponse);\n }\n }\n\n async handleFileChunk(chunkMessage) {\n return this.atomicOps.withLock(\n `chunk-${chunkMessage.fileId}`, \n async () => {\n try {\n let receivingState = this.receivingTransfers.get(chunkMessage.fileId);\n \n // Buffer early chunks if transfer not yet initialized\n if (!receivingState) {\n if (!this.pendingChunks.has(chunkMessage.fileId)) {\n this.pendingChunks.set(chunkMessage.fileId, new Map());\n }\n \n this.pendingChunks.get(chunkMessage.fileId).set(chunkMessage.chunkIndex, chunkMessage);\n return;\n }\n \n // Update last chunk time\n receivingState.lastChunkTime = Date.now();\n \n // Check if chunk already received\n if (receivingState.receivedChunks.has(chunkMessage.chunkIndex)) {\n return;\n }\n \n // Validate chunk\n if (chunkMessage.chunkIndex < 0 || chunkMessage.chunkIndex >= receivingState.totalChunks) {\n throw new Error(`Invalid chunk index: ${chunkMessage.chunkIndex}`);\n }\n \n // Decrypt chunk\n const nonce = new Uint8Array(chunkMessage.nonce);\n // Backward compatible: prefer Base64, fallback to numeric array\n let encryptedData;\n if (chunkMessage.encryptedDataB64) {\n encryptedData = this.base64ToUint8Array(chunkMessage.encryptedDataB64);\n } else if (chunkMessage.encryptedData) {\n encryptedData = new Uint8Array(chunkMessage.encryptedData);\n } else {\n throw new Error('Missing encrypted data');\n }\n \n const decryptedChunk = await crypto.subtle.decrypt(\n {\n name: 'AES-GCM',\n iv: nonce\n },\n receivingState.sessionKey,\n encryptedData\n );\n \n // Verify chunk size\n if (decryptedChunk.byteLength !== chunkMessage.chunkSize) {\n throw new Error(`Chunk size mismatch: expected ${chunkMessage.chunkSize}, got ${decryptedChunk.byteLength}`);\n }\n \n // Store chunk\n receivingState.receivedChunks.set(chunkMessage.chunkIndex, decryptedChunk);\n receivingState.receivedCount++;\n \n // Send chunk confirmation\n const confirmation = {\n type: 'chunk_confirmation',\n fileId: chunkMessage.fileId,\n chunkIndex: chunkMessage.chunkIndex,\n timestamp: Date.now()\n };\n await this.sendSecureMessage(confirmation);\n \n // Check if all chunks received\n if (receivingState.receivedCount === receivingState.totalChunks) {\n await this.assembleFile(receivingState);\n }\n \n } catch (error) {\n const safeError = SecurityErrorHandler.sanitizeError(error);\n console.error('\u274C Failed to handle file chunk:', safeError);\n \n // Send error notification\n const errorMessage = {\n type: 'file_transfer_error',\n fileId: chunkMessage.fileId,\n error: safeError, \n chunkIndex: chunkMessage.chunkIndex,\n timestamp: Date.now()\n };\n await this.sendSecureMessage(errorMessage);\n \n // Mark transfer as failed\n const receivingState = this.receivingTransfers.get(chunkMessage.fileId);\n if (receivingState) {\n receivingState.status = 'failed';\n }\n \n if (this.onError) {\n this.onError(`Chunk processing failed: ${safeError}`);\n }\n }\n }\n );\n }\n\n async assembleFile(receivingState) {\n try {\n receivingState.status = 'assembling';\n \n // Verify we have all chunks\n for (let i = 0; i < receivingState.totalChunks; i++) {\n if (!receivingState.receivedChunks.has(i)) {\n throw new Error(`Missing chunk ${i}`);\n }\n }\n \n // Combine all chunks in order\n const chunks = [];\n for (let i = 0; i < receivingState.totalChunks; i++) {\n const chunk = receivingState.receivedChunks.get(i);\n chunks.push(new Uint8Array(chunk));\n }\n \n // Calculate total size\n const totalSize = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n \n // Verify total size matches expected\n if (totalSize !== receivingState.fileSize) {\n throw new Error(`File size mismatch: expected ${receivingState.fileSize}, got ${totalSize}`);\n }\n \n // Combine into single array\n const fileData = new Uint8Array(totalSize);\n let offset = 0;\n for (const chunk of chunks) {\n fileData.set(chunk, offset);\n offset += chunk.length;\n }\n \n // Verify file integrity\n const receivedHash = await this.calculateFileHashFromData(fileData);\n if (receivedHash !== receivingState.fileHash) {\n throw new Error('File integrity check failed - hash mismatch');\n }\n\n const fileBuffer = fileData.buffer;\n const fileBlob = new Blob([fileBuffer], { type: receivingState.fileType });\n \n receivingState.endTime = Date.now();\n receivingState.status = 'completed';\n\n this.receivedFileBuffers.set(receivingState.fileId, {\n buffer: fileBuffer,\n type: receivingState.fileType,\n name: receivingState.fileName,\n size: receivingState.fileSize\n });\n\n if (this.onFileReceived) {\n const getBlob = async () => new Blob([this.receivedFileBuffers.get(receivingState.fileId).buffer], { type: receivingState.fileType });\n const getObjectURL = async () => {\n const blob = await getBlob();\n return URL.createObjectURL(blob);\n };\n const revokeObjectURL = (url) => {\n try { URL.revokeObjectURL(url); } catch (_) {}\n };\n\n this.onFileReceived({\n fileId: receivingState.fileId,\n fileName: receivingState.fileName,\n fileSize: receivingState.fileSize,\n mimeType: receivingState.fileType,\n transferTime: receivingState.endTime - receivingState.startTime,\n // backward-compatibility for existing UIs\n fileBlob,\n getBlob,\n getObjectURL,\n revokeObjectURL\n });\n }\n \n // Send completion confirmation\n const completionMessage = {\n type: 'file_transfer_complete',\n fileId: receivingState.fileId,\n success: true,\n timestamp: Date.now()\n };\n await this.sendSecureMessage(completionMessage);\n \n // Cleanup\n if (this.receivingTransfers.has(receivingState.fileId)) {\n const rs = this.receivingTransfers.get(receivingState.fileId);\n if (rs && rs.receivedChunks) rs.receivedChunks.clear();\n }\n this.receivingTransfers.delete(receivingState.fileId);\n \n } catch (error) {\n console.error('\u274C File assembly failed:', error);\n receivingState.status = 'failed';\n \n if (this.onError) {\n this.onError(`File assembly failed: ${error.message}`);\n }\n \n // Send error notification\n const errorMessage = {\n type: 'file_transfer_complete',\n fileId: receivingState.fileId,\n success: false,\n error: error.message,\n timestamp: Date.now()\n };\n await this.sendSecureMessage(errorMessage);\n \n // Cleanup failed transfer\n this.cleanupReceivingTransfer(receivingState.fileId);\n }\n }\n\n async calculateFileHashFromData(data) {\n try {\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n } catch (error) {\n console.error('\u274C Hash calculation failed:', error);\n throw error;\n }\n }\n\n handleTransferResponse(response) {\n try {\n const transferState = this.activeTransfers.get(response.fileId);\n \n if (!transferState) {\n return;\n }\n \n if (response.accepted) {\n transferState.status = 'accepted';\n } else {\n transferState.status = 'rejected';\n \n if (this.onError) {\n this.onError(`Transfer rejected: ${response.error || 'Unknown reason'}`);\n }\n \n this.cleanupTransfer(response.fileId);\n }\n } catch (error) {\n console.error('\u274C Failed to handle transfer response:', error);\n }\n }\n\n handleChunkConfirmation(confirmation) {\n try {\n const transferState = this.activeTransfers.get(confirmation.fileId);\n if (!transferState) {\n return;\n }\n \n transferState.confirmedChunks++;\n transferState.lastChunkTime = Date.now();\n } catch (error) {\n console.error('\u274C Failed to handle chunk confirmation:', error);\n }\n }\n\n handleTransferComplete(completion) {\n try {\n const transferState = this.activeTransfers.get(completion.fileId);\n if (!transferState) {\n return;\n }\n \n if (completion.success) {\n transferState.status = 'completed';\n transferState.endTime = Date.now();\n \n if (this.onComplete) {\n this.onComplete({\n fileId: transferState.fileId,\n fileName: transferState.file.name,\n fileSize: transferState.file.size,\n transferTime: transferState.endTime - transferState.startTime,\n status: 'completed'\n });\n }\n } else {\n transferState.status = 'failed';\n \n if (this.onError) {\n this.onError(`Transfer failed: ${completion.error || 'Unknown error'}`);\n }\n }\n \n this.cleanupTransfer(completion.fileId);\n \n } catch (error) {\n console.error('\u274C Failed to handle transfer completion:', error);\n }\n }\n\n handleTransferError(errorMessage) {\n try {\n const transferState = this.activeTransfers.get(errorMessage.fileId);\n if (transferState) {\n transferState.status = 'failed';\n this.cleanupTransfer(errorMessage.fileId);\n }\n \n const receivingState = this.receivingTransfers.get(errorMessage.fileId);\n if (receivingState) {\n receivingState.status = 'failed';\n this.cleanupReceivingTransfer(errorMessage.fileId);\n }\n \n if (this.onError) {\n this.onError(`Transfer error: ${errorMessage.error || 'Unknown error'}`);\n }\n \n } catch (error) {\n console.error('\u274C Failed to handle transfer error:', error);\n }\n }\n\n // ============================================\n // UTILITY METHODS\n // ============================================\n\n getActiveTransfers() {\n return Array.from(this.activeTransfers.values()).map(transfer => ({\n fileId: transfer.fileId,\n fileName: transfer.file?.name || 'Unknown',\n fileSize: transfer.file?.size || 0,\n progress: Math.round((transfer.sentChunks / transfer.totalChunks) * 100),\n status: transfer.status,\n startTime: transfer.startTime\n }));\n }\n\n getReceivingTransfers() {\n return Array.from(this.receivingTransfers.values()).map(transfer => ({\n fileId: transfer.fileId,\n fileName: transfer.fileName || 'Unknown',\n fileSize: transfer.fileSize || 0,\n progress: Math.round((transfer.receivedCount / transfer.totalChunks) * 100),\n status: transfer.status,\n startTime: transfer.startTime\n }));\n }\n\n cancelTransfer(fileId) {\n try {\n if (this.activeTransfers.has(fileId)) {\n this.cleanupTransfer(fileId);\n return true;\n }\n if (this.receivingTransfers.has(fileId)) {\n this.cleanupReceivingTransfer(fileId);\n return true;\n }\n return false;\n } catch (error) {\n console.error('\u274C Failed to cancel transfer:', error);\n return false;\n }\n }\n\n cleanupTransfer(fileId) {\n this.activeTransfers.delete(fileId);\n this.sessionKeys.delete(fileId);\n this.transferNonces.delete(fileId);\n \n // Remove processed chunk IDs for this transfer\n for (const chunkId of this.processedChunks) {\n if (chunkId.startsWith(fileId)) {\n this.processedChunks.delete(chunkId);\n }\n }\n }\n\n // \u2705 \u0423\u041B\u0423\u0427\u0428\u0415\u041D\u041D\u0410\u042F \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u0430\u044F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 \u043F\u0430\u043C\u044F\u0442\u0438 \u0434\u043B\u044F \u043F\u0440\u0435\u0434\u043E\u0442\u0432\u0440\u0430\u0449\u0435\u043D\u0438\u044F use-after-free\n cleanupReceivingTransfer(fileId) {\n try {\n // \u0411\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E \u043E\u0447\u0438\u0449\u0430\u0435\u043C pending chunks\n this.pendingChunks.delete(fileId);\n \n const receivingState = this.receivingTransfers.get(fileId);\n if (receivingState) {\n // \u2705 \u0411\u0415\u0417\u041E\u041F\u0410\u0421\u041D\u0410\u042F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 receivedChunks \u0441 \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0439 \u0437\u0430\u0449\u0438\u0442\u043E\u0439\n if (receivingState.receivedChunks && receivingState.receivedChunks.size > 0) {\n for (const [index, chunk] of receivingState.receivedChunks) {\n try {\n // \u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u0430\u044F \u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0430 \u043D\u0430 \u0432\u0430\u043B\u0438\u0434\u043D\u043E\u0441\u0442\u044C chunk\n if (chunk && (chunk instanceof ArrayBuffer || chunk instanceof Uint8Array)) {\n SecureMemoryManager.secureWipe(chunk);\n \n // \u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u0430\u044F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 - \u0437\u0430\u043F\u043E\u043B\u043D\u044F\u0435\u043C \u043D\u0443\u043B\u044F\u043C\u0438 \u043F\u0435\u0440\u0435\u0434 \u0443\u0434\u0430\u043B\u0435\u043D\u0438\u0435\u043C\n if (chunk instanceof ArrayBuffer) {\n const view = new Uint8Array(chunk);\n view.fill(0);\n } else if (chunk instanceof Uint8Array) {\n chunk.fill(0);\n }\n }\n } catch (chunkError) {\n console.warn('\u26A0\uFE0F Failed to securely wipe chunk:', chunkError);\n }\n }\n receivingState.receivedChunks.clear();\n }\n \n // \u2705 \u0411\u0415\u0417\u041E\u041F\u0410\u0421\u041D\u0410\u042F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 session key\n if (receivingState.sessionKey) {\n try {\n // \u0414\u043B\u044F CryptoKey \u043D\u0435\u043B\u044C\u0437\u044F \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E \u043E\u0447\u0438\u0441\u0442\u0438\u0442\u044C, \u043D\u043E \u043C\u043E\u0436\u0435\u043C \u0443\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u0441\u044B\u043B\u043A\u0443\n receivingState.sessionKey = null;\n } catch (keyError) {\n console.warn('\u26A0\uFE0F Failed to clear session key:', keyError);\n }\n }\n \n // \u2705 \u0411\u0415\u0417\u041E\u041F\u0410\u0421\u041D\u0410\u042F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 \u0434\u0440\u0443\u0433\u0438\u0445 \u0447\u0443\u0432\u0441\u0442\u0432\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0445 \u0434\u0430\u043D\u043D\u044B\u0445\n if (receivingState.salt) {\n try {\n if (Array.isArray(receivingState.salt)) {\n receivingState.salt.fill(0);\n }\n receivingState.salt = null;\n } catch (saltError) {\n console.warn('\u26A0\uFE0F Failed to clear salt:', saltError);\n }\n }\n \n // \u041E\u0447\u0438\u0449\u0430\u0435\u043C \u0432\u0441\u0435 \u0441\u0432\u043E\u0439\u0441\u0442\u0432\u0430 receivingState\n for (const [key, value] of Object.entries(receivingState)) {\n if (value && typeof value === 'object') {\n if (value instanceof ArrayBuffer || value instanceof Uint8Array) {\n SecureMemoryManager.secureWipe(value);\n } else if (Array.isArray(value)) {\n value.fill(0);\n }\n receivingState[key] = null;\n }\n }\n }\n \n // \u0423\u0434\u0430\u043B\u044F\u0435\u043C \u0438\u0437 \u043E\u0441\u043D\u043E\u0432\u043D\u044B\u0445 \u043A\u043E\u043B\u043B\u0435\u043A\u0446\u0438\u0439\n this.receivingTransfers.delete(fileId);\n this.sessionKeys.delete(fileId);\n \n // \u2705 \u0411\u0415\u0417\u041E\u041F\u0410\u0421\u041D\u0410\u042F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 \u0444\u0438\u043D\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u0431\u0443\u0444\u0435\u0440\u0430 \u0444\u0430\u0439\u043B\u0430\n const fileBuffer = this.receivedFileBuffers.get(fileId);\n if (fileBuffer) {\n try {\n if (fileBuffer.buffer) {\n SecureMemoryManager.secureWipe(fileBuffer.buffer);\n \n // \u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u0430\u044F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 - \u0437\u0430\u043F\u043E\u043B\u043D\u044F\u0435\u043C \u043D\u0443\u043B\u044F\u043C\u0438\n const view = new Uint8Array(fileBuffer.buffer);\n view.fill(0);\n }\n \n // \u041E\u0447\u0438\u0449\u0430\u0435\u043C \u0432\u0441\u0435 \u0441\u0432\u043E\u0439\u0441\u0442\u0432\u0430 fileBuffer\n for (const [key, value] of Object.entries(fileBuffer)) {\n if (value && typeof value === 'object') {\n if (value instanceof ArrayBuffer || value instanceof Uint8Array) {\n SecureMemoryManager.secureWipe(value);\n }\n fileBuffer[key] = null;\n }\n }\n \n this.receivedFileBuffers.delete(fileId);\n } catch (bufferError) {\n console.warn('\u26A0\uFE0F Failed to securely clear file buffer:', bufferError);\n // \u041F\u0440\u0438\u043D\u0443\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u043E \u0443\u0434\u0430\u043B\u044F\u0435\u043C \u0434\u0430\u0436\u0435 \u043F\u0440\u0438 \u043E\u0448\u0438\u0431\u043A\u0435\n this.receivedFileBuffers.delete(fileId);\n }\n }\n \n // \u2705 \u0411\u0415\u0417\u041E\u041F\u0410\u0421\u041D\u0410\u042F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 processed chunks\n const chunksToRemove = [];\n for (const chunkId of this.processedChunks) {\n if (chunkId.startsWith(fileId)) {\n chunksToRemove.push(chunkId);\n }\n }\n \n // \u0423\u0434\u0430\u043B\u044F\u0435\u043C \u0432 \u043E\u0442\u0434\u0435\u043B\u044C\u043D\u043E\u043C \u0446\u0438\u043A\u043B\u0435 \u0434\u043B\u044F \u0438\u0437\u0431\u0435\u0436\u0430\u043D\u0438\u044F \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F \u043A\u043E\u043B\u043B\u0435\u043A\u0446\u0438\u0438 \u0432\u043E \u0432\u0440\u0435\u043C\u044F \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0438\n for (const chunkId of chunksToRemove) {\n this.processedChunks.delete(chunkId);\n }\n \n // \u041F\u0440\u0438\u043D\u0443\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u0430\u044F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 \u043F\u0430\u043C\u044F\u0442\u0438\n if (typeof global !== 'undefined' && global.gc) {\n try {\n global.gc();\n } catch (gcError) {\n // \u0418\u0433\u043D\u043E\u0440\u0438\u0440\u0443\u0435\u043C \u043E\u0448\u0438\u0431\u043A\u0438 GC\n }\n }\n \n console.log(`\uD83D\uDD12 Memory safely cleaned for file transfer: ${fileId}`);\n \n } catch (error) {\n console.error('\u274C Error during secure memory cleanup:', error);\n \n // \u041F\u0440\u0438\u043D\u0443\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u0430\u044F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 \u0434\u0430\u0436\u0435 \u043F\u0440\u0438 \u043E\u0448\u0438\u0431\u043A\u0435\n this.receivingTransfers.delete(fileId);\n this.sessionKeys.delete(fileId);\n this.receivedFileBuffers.delete(fileId);\n this.pendingChunks.delete(fileId);\n \n throw new Error(`Memory cleanup failed: ${error.message}`);\n }\n }\n\n getTransferStatus(fileId) {\n if (this.activeTransfers.has(fileId)) {\n const transfer = this.activeTransfers.get(fileId);\n return {\n type: 'sending',\n fileId: transfer.fileId,\n fileName: transfer.file.name,\n progress: Math.round((transfer.sentChunks / transfer.totalChunks) * 100),\n status: transfer.status,\n startTime: transfer.startTime\n };\n }\n \n if (this.receivingTransfers.has(fileId)) {\n const transfer = this.receivingTransfers.get(fileId);\n return {\n type: 'receiving',\n fileId: transfer.fileId,\n fileName: transfer.fileName,\n progress: Math.round((transfer.receivedCount / transfer.totalChunks) * 100),\n status: transfer.status,\n startTime: transfer.startTime\n };\n }\n \n return null;\n }\n\n getSystemStatus() {\n return {\n initialized: true,\n activeTransfers: this.activeTransfers.size,\n receivingTransfers: this.receivingTransfers.size,\n totalTransfers: this.activeTransfers.size + this.receivingTransfers.size,\n maxConcurrentTransfers: this.MAX_CONCURRENT_TRANSFERS,\n maxFileSize: this.MAX_FILE_SIZE,\n chunkSize: this.CHUNK_SIZE,\n hasWebrtcManager: !!this.webrtcManager,\n isConnected: this.webrtcManager?.isConnected?.() || false,\n hasDataChannel: !!this.webrtcManager?.dataChannel,\n dataChannelState: this.webrtcManager?.dataChannel?.readyState,\n isVerified: this.webrtcManager?.isVerified,\n hasEncryptionKey: !!this.webrtcManager?.encryptionKey,\n hasMacKey: !!this.webrtcManager?.macKey,\n linkedToWebRTCManager: this.webrtcManager?.fileTransferSystem === this,\n supportedFileTypes: this.getSupportedFileTypes(),\n fileTypeInfo: this.getFileTypeInfo()\n };\n }\n\n cleanup() {\n SecureFileTransferContext.getInstance().deactivate();\n\n if (this.webrtcManager && this.webrtcManager.dataChannel && this.originalOnMessage) {\n this.webrtcManager.dataChannel.onmessage = this.originalOnMessage;\n this.originalOnMessage = null;\n }\n \n if (this.webrtcManager && this.originalProcessMessage) {\n this.webrtcManager.processMessage = this.originalProcessMessage;\n this.originalProcessMessage = null;\n }\n \n if (this.webrtcManager && this.originalRemoveSecurityLayers) {\n this.webrtcManager.removeSecurityLayers = this.originalRemoveSecurityLayers;\n this.originalRemoveSecurityLayers = null;\n }\n \n // Cleanup all active transfers with secure memory wiping\n for (const fileId of this.activeTransfers.keys()) {\n this.cleanupTransfer(fileId);\n }\n \n for (const fileId of this.receivingTransfers.keys()) {\n this.cleanupReceivingTransfer(fileId);\n }\n\n if (this.atomicOps) {\n this.atomicOps.locks.clear();\n }\n \n if (this.rateLimiter) {\n this.rateLimiter.requests.clear();\n }\n \n // Clear all state\n this.pendingChunks.clear();\n this.activeTransfers.clear();\n this.receivingTransfers.clear();\n this.transferQueue.length = 0;\n this.sessionKeys.clear();\n this.transferNonces.clear();\n this.processedChunks.clear();\n\n this.clearKeys();\n }\n\n // ============================================\n // SESSION UPDATE HANDLER - FIXED\n // ============================================\n \n onSessionUpdate(sessionData) {\n // Clear session keys cache for resync\n this.sessionKeys.clear();\n }\n\n // ============================================\n // DEBUGGING AND DIAGNOSTICS\n // ============================================\n\n diagnoseFileTransferIssue() {\n const diagnosis = {\n timestamp: new Date().toISOString(),\n fileTransferSystem: {\n initialized: !!this,\n hasWebrtcManager: !!this.webrtcManager,\n webrtcManagerType: this.webrtcManager?.constructor?.name,\n linkedToWebRTCManager: this.webrtcManager?.fileTransferSystem === this\n },\n webrtcManager: {\n hasDataChannel: !!this.webrtcManager?.dataChannel,\n dataChannelState: this.webrtcManager?.dataChannel?.readyState,\n isConnected: this.webrtcManager?.isConnected?.() || false,\n isVerified: this.webrtcManager?.isVerified,\n hasEncryptionKey: !!this.webrtcManager?.encryptionKey,\n hasMacKey: !!this.webrtcManager?.macKey,\n hasKeyFingerprint: !!this.webrtcManager?.keyFingerprint,\n hasSessionSalt: !!this.webrtcManager?.sessionSalt\n },\n securityContext: {\n contextActive: SecureFileTransferContext.getInstance().isActive(),\n securityLevel: SecureFileTransferContext.getInstance().getSecurityLevel(),\n hasAtomicOps: !!this.atomicOps,\n hasRateLimiter: !!this.rateLimiter\n },\n transfers: {\n activeTransfers: this.activeTransfers.size,\n receivingTransfers: this.receivingTransfers.size,\n pendingChunks: this.pendingChunks.size,\n sessionKeys: this.sessionKeys.size\n },\n fileTypeSupport: {\n supportedTypes: this.getSupportedFileTypes(),\n generalMaxSize: this.formatFileSize(this.MAX_FILE_SIZE),\n restrictions: Object.keys(this.FILE_TYPE_RESTRICTIONS)\n }\n };\n \n return diagnosis;\n }\n\n async debugKeyDerivation(fileId) {\n try {\n if (!this.webrtcManager.keyFingerprint || !this.webrtcManager.sessionSalt) {\n throw new Error('Session data not available');\n }\n \n // Test sender derivation\n const senderResult = await this.deriveFileSessionKey(fileId);\n \n // Test receiver derivation with same salt\n const receiverKey = await this.deriveFileSessionKeyFromSalt(fileId, senderResult.salt);\n \n // Test encryption/decryption\n const testData = new TextEncoder().encode('test data');\n const nonce = crypto.getRandomValues(new Uint8Array(12));\n \n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: nonce },\n senderResult.key,\n testData\n );\n \n const decrypted = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: nonce },\n receiverKey,\n encrypted\n );\n \n const decryptedText = new TextDecoder().decode(decrypted);\n \n if (decryptedText === 'test data') {\n return { success: true, message: 'All tests passed' };\n } else {\n throw new Error('Decryption verification failed');\n }\n \n } catch (error) {\n console.error('\u274C Key derivation test failed:', error);\n return { success: false, error: error.message };\n }\n }\n\n // ============================================\n // ALTERNATIVE METHOD OF INITIALIZING HANDLERS\n // ============================================\n\n registerWithWebRTCManager() {\n if (!this.webrtcManager) {\n throw new Error('WebRTC manager not available');\n }\n\n this.webrtcManager.fileTransferSystem = this;\n\n this.webrtcManager.setFileMessageHandler = (handler) => {\n this.webrtcManager._fileMessageHandler = handler;\n };\n\n this.webrtcManager.setFileMessageHandler((message) => {\n return this.handleFileMessage(message);\n });\n }\n\n static createFileMessageFilter(fileTransferSystem) {\n return async (event) => {\n try {\n if (typeof event.data === 'string') {\n const parsed = JSON.parse(event.data);\n \n if (fileTransferSystem.isFileTransferMessage(parsed)) {\n await fileTransferSystem.handleFileMessage(parsed);\n return true; \n }\n }\n } catch (error) {\n }\n \n return false; \n };\n }\n\n // ============================================\n // SECURITY KEY MANAGEMENT\n // ============================================\n\n setSigningKey(privateKey) {\n if (!privateKey || !(privateKey instanceof CryptoKey)) {\n throw new Error('Invalid private key for signing');\n }\n this.signingKey = privateKey;\n console.log('\uD83D\uDD12 Signing key set successfully');\n }\n\n setVerificationKey(publicKey) {\n if (!publicKey || !(publicKey instanceof CryptoKey)) {\n throw new Error('Invalid public key for verification');\n }\n this.verificationKey = publicKey;\n console.log('\uD83D\uDD12 Verification key set successfully');\n }\n\n async generateSigningKeyPair() {\n try {\n const keyPair = await crypto.subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: 2048,\n publicExponent: new Uint8Array([1, 0, 1]),\n hash: 'SHA-256'\n },\n true, // extractable\n ['sign', 'verify']\n );\n \n this.signingKey = keyPair.privateKey;\n this.verificationKey = keyPair.publicKey;\n \n console.log('\uD83D\uDD12 RSA key pair generated successfully');\n return keyPair;\n } catch (error) {\n const safeError = SecurityErrorHandler.sanitizeError(error);\n console.error('\u274C Failed to generate signing key pair:', safeError);\n throw new Error(safeError);\n }\n }\n\n clearKeys() {\n this.signingKey = null;\n this.verificationKey = null;\n console.log('\uD83D\uDD12 Security keys cleared');\n }\n\n getSecurityStatus() {\n return {\n signingEnabled: this.signingKey !== null,\n verificationEnabled: this.verificationKey !== null,\n contextActive: SecureFileTransferContext.getInstance().isActive(),\n securityLevel: SecureFileTransferContext.getInstance().getSecurityLevel()\n };\n }\n\n getClientIdentifier() {\n return this.webrtcManager?.connectionId || \n this.webrtcManager?.keyFingerprint?.substring(0, 16) || \n 'default-client';\n }\n \n destroy() {\n SecureFileTransferContext.getInstance().deactivate();\n this.clearKeys();\n console.log('\uD83D\uDD12 File transfer system destroyed safely');\n }\n}\n\nexport { EnhancedSecureFileTransfer };", "// Import EnhancedSecureFileTransfer\nimport { EnhancedSecureFileTransfer } from '../transfer/EnhancedSecureFileTransfer.js';\n\n// MUTEX SYSTEM FIXES - RESOLVING MESSAGE DELIVERY ISSUES\n// ============================================\n// Issue: After introducing the Mutex system, messages stopped being delivered between users\n// Fix: Simplified locking logic \u2014 mutex is used ONLY for critical operations\n// - Regular messages are processed WITHOUT mutex\n// - File messages are processed WITHOUT mutex \n// - Mutex is used ONLY for cryptographic operations\n// ============================================\n\nclass EnhancedSecureWebRTCManager {\n // ============================================\n // CONSTANTS\n // ============================================\n \n static TIMEOUTS = {\n KEY_ROTATION_INTERVAL: 300000, // 5 minutes\n CONNECTION_TIMEOUT: 10000, // 10 seconds \n HEARTBEAT_INTERVAL: 30000, // 30 seconds\n SECURITY_CALC_DELAY: 1000, // 1 second\n SECURITY_CALC_RETRY_DELAY: 3000, // 3 seconds\n CLEANUP_INTERVAL: 300000, // 5 minutes (periodic cleanup)\n CLEANUP_CHECK_INTERVAL: 60000, // 1 minute (cleanup check)\n ICE_GATHERING_TIMEOUT: 10000, // 10 seconds\n DISCONNECT_CLEANUP_DELAY: 500, // 500ms\n PEER_DISCONNECT_CLEANUP: 2000, // 2 seconds\n STAGE2_ACTIVATION_DELAY: 10000, // 10 seconds\n STAGE3_ACTIVATION_DELAY: 15000, // 15 seconds \n STAGE4_ACTIVATION_DELAY: 20000, // 20 seconds\n FILE_TRANSFER_INIT_DELAY: 1000, // 1 second\n FAKE_TRAFFIC_MIN_INTERVAL: 15000, // 15 seconds\n FAKE_TRAFFIC_MAX_INTERVAL: 30000, // 30 seconds\n DECOY_INITIAL_DELAY: 5000, // 5 seconds\n DECOY_TRAFFIC_MIN: 10000, // 10 seconds\n DECOY_TRAFFIC_MAX: 25000, // 25 seconds\n REORDER_TIMEOUT: 3000, // 3 seconds\n RETRY_CONNECTION_DELAY: 2000 // 2 seconds\n };\n\n static LIMITS = {\n MAX_CONNECTION_ATTEMPTS: 3,\n MAX_OLD_KEYS: 3,\n MAX_PROCESSED_MESSAGE_IDS: 1000,\n MAX_OUT_OF_ORDER_PACKETS: 5,\n MAX_DECOY_CHANNELS: 1,\n MESSAGE_RATE_LIMIT: 60, // messages per minute\n MAX_KEY_AGE: 900000, // 15 minutes\n OFFER_MAX_AGE: 3600000, // 1 hour\n SALT_SIZE_V3: 32, // bytes\n SALT_SIZE_V4: 64 // bytes\n };\n\n static SIZES = {\n VERIFICATION_CODE_MIN_LENGTH: 6,\n FAKE_TRAFFIC_MIN_SIZE: 32,\n FAKE_TRAFFIC_MAX_SIZE: 128,\n PACKET_PADDING_MIN: 64,\n PACKET_PADDING_MAX: 512,\n CHUNK_SIZE_MAX: 2048,\n CHUNK_DELAY_MIN: 100,\n CHUNK_DELAY_MAX: 500,\n FINGERPRINT_DISPLAY_LENGTH: 8,\n SESSION_ID_LENGTH: 16,\n NESTED_ENCRYPTION_IV_SIZE: 12\n };\n\n static MESSAGE_TYPES = {\n // Regular messages\n MESSAGE: 'message',\n ENHANCED_MESSAGE: 'enhanced_message',\n \n // System messages\n HEARTBEAT: 'heartbeat',\n VERIFICATION: 'verification',\n VERIFICATION_RESPONSE: 'verification_response',\n VERIFICATION_CONFIRMED: 'verification_confirmed',\n VERIFICATION_BOTH_CONFIRMED: 'verification_both_confirmed',\n PEER_DISCONNECT: 'peer_disconnect',\n SECURITY_UPGRADE: 'security_upgrade',\n KEY_ROTATION_SIGNAL: 'key_rotation_signal',\n KEY_ROTATION_READY: 'key_rotation_ready',\n \n // File transfer messages\n FILE_TRANSFER_START: 'file_transfer_start',\n FILE_TRANSFER_RESPONSE: 'file_transfer_response',\n FILE_CHUNK: 'file_chunk',\n CHUNK_CONFIRMATION: 'chunk_confirmation',\n FILE_TRANSFER_COMPLETE: 'file_transfer_complete',\n FILE_TRANSFER_ERROR: 'file_transfer_error',\n \n // Fake traffic\n FAKE: 'fake'\n };\n\n static FILTERED_RESULTS = {\n FAKE_MESSAGE: 'FAKE_MESSAGE_FILTERED',\n FILE_MESSAGE: 'FILE_MESSAGE_FILTERED', \n SYSTEM_MESSAGE: 'SYSTEM_MESSAGE_FILTERED'\n };\n\n // Static debug flag instead of this._debugMode\n static DEBUG_MODE = false; // Set to true during development, false in production\n\n\n constructor(onMessage, onStatusChange, onKeyExchange, onVerificationRequired, onAnswerError = null, onVerificationStateChange = null, config = {}) {\n // Determine runtime mode\n this._isProductionMode = this._detectProductionMode();\n // Use static flag instead of this._debugMode\n this._debugMode = !this._isProductionMode && EnhancedSecureWebRTCManager.DEBUG_MODE;\n \n // Configuration from constructor parameters instead of global flags\n this._config = {\n fakeTraffic: {\n enabled: config.fakeTraffic?.enabled ?? true,\n minInterval: config.fakeTraffic?.minInterval ?? EnhancedSecureWebRTCManager.TIMEOUTS.FAKE_TRAFFIC_MIN_INTERVAL,\n maxInterval: config.fakeTraffic?.maxInterval ?? EnhancedSecureWebRTCManager.TIMEOUTS.FAKE_TRAFFIC_MAX_INTERVAL,\n minSize: config.fakeTraffic?.minSize ?? EnhancedSecureWebRTCManager.SIZES.FAKE_TRAFFIC_MIN_SIZE,\n maxSize: config.fakeTraffic?.maxSize ?? EnhancedSecureWebRTCManager.SIZES.FAKE_TRAFFIC_MAX_SIZE,\n patterns: config.fakeTraffic?.patterns ?? ['heartbeat', 'status', 'sync']\n },\n decoyChannels: {\n enabled: config.decoyChannels?.enabled ?? true,\n maxDecoyChannels: config.decoyChannels?.maxDecoyChannels ?? EnhancedSecureWebRTCManager.LIMITS.MAX_DECOY_CHANNELS,\n decoyChannelNames: config.decoyChannels?.decoyChannelNames ?? ['heartbeat'],\n sendDecoyData: config.decoyChannels?.sendDecoyData ?? true,\n randomDecoyIntervals: config.decoyChannels?.randomDecoyIntervals ?? true\n },\n packetPadding: {\n enabled: config.packetPadding?.enabled ?? true,\n minPadding: config.packetPadding?.minPadding ?? EnhancedSecureWebRTCManager.SIZES.PACKET_PADDING_MIN,\n maxPadding: config.packetPadding?.maxPadding ?? EnhancedSecureWebRTCManager.SIZES.PACKET_PADDING_MAX,\n useRandomPadding: config.packetPadding?.useRandomPadding ?? true,\n preserveMessageSize: config.packetPadding?.preserveMessageSize ?? false\n },\n antiFingerprinting: {\n enabled: config.antiFingerprinting?.enabled ?? false,\n randomizeTiming: config.antiFingerprinting?.randomizeTiming ?? true,\n randomizeSizes: config.antiFingerprinting?.randomizeSizes ?? false,\n addNoise: config.antiFingerprinting?.addNoise ?? true,\n maskPatterns: config.antiFingerprinting?.maskPatterns ?? false,\n useRandomHeaders: config.antiFingerprinting?.useRandomHeaders ?? false\n }\n };\n\n // Initialize own logging system\n this._initializeSecureLogging();\n this._setupOwnLogger();\n this._setupProductionLogging();\n \n // Store important methods first\n this._storeImportantMethods();\n \n // Setup global API after storing methods\n this._setupSecureGlobalAPI();\n if (!window.EnhancedSecureCryptoUtils) {\n throw new Error('EnhancedSecureCryptoUtils is not loaded. Please ensure the module is loaded first.');\n }\n this.getSecurityData = () => {\n // Return only public information\n return this.lastSecurityCalculation ? {\n level: this.lastSecurityCalculation.level,\n score: this.lastSecurityCalculation.score,\n timestamp: this.lastSecurityCalculation.timestamp,\n // Do NOT return check details or sensitive data\n } : null;\n };\n this._secureLog('info', '\uD83D\uDD12 Enhanced WebRTC Manager initialized with secure API');\n this.currentSessionType = null;\n this.currentSecurityLevel = 'basic';\n this.sessionConstraints = null;\n this.peerConnection = null;\n this.dataChannel = null;\n\n\n this.onMessage = onMessage;\n this.onStatusChange = onStatusChange;\n this.onKeyExchange = onKeyExchange;\n this.onVerificationStateChange = onVerificationStateChange;\n\n this.onVerificationRequired = onVerificationRequired;\n this.onAnswerError = onAnswerError; // Callback for response processing errors\n this.isInitiator = false;\n this.connectionAttempts = 0;\n this.maxConnectionAttempts = EnhancedSecureWebRTCManager.LIMITS.MAX_CONNECTION_ATTEMPTS;\n try {\n this._initializeMutexSystem();\n} catch (error) {\n this._secureLog('error', '\u274C Failed to initialize mutex system', {\n errorType: error.constructor.name\n });\n throw new Error('Critical: Mutex system initialization failed');\n}\n\n// Post-initialization validation of the mutex system\nif (!this._validateMutexSystem()) {\n this._secureLog('error', '\u274C Mutex system validation failed after initialization');\n throw new Error('Critical: Mutex system validation failed');\n}\n\nif (typeof window !== 'undefined') {\n this._secureLog('info', '\uD83D\uDD12 Emergency mutex handlers will be available through secure API');\n}\n\nthis._secureLog('info', '\uD83D\uDD12 Enhanced Mutex system fully initialized and validated');\n this.heartbeatInterval = null;\n this.messageQueue = [];\n this.ecdhKeyPair = null;\n this.ecdsaKeyPair = null;\n if (this.fileTransferSystem) {\n this.fileTransferSystem.cleanup();\n this.fileTransferSystem = null;\n }\n this.verificationCode = null;\n this.pendingSASCode = null;\n this.isVerified = false;\n this.processedMessageIds = new Set();\n \n // Mutual verification states\n this.localVerificationConfirmed = false;\n this.remoteVerificationConfirmed = false;\n this.bothVerificationsConfirmed = false;\n \n // Store expected DTLS fingerprint for validation\n this.expectedDTLSFingerprint = null;\n this.strictDTLSValidation = true; // Can be disabled for debugging\n \n // Real Perfect Forward Secrecy implementation\n this.ephemeralKeyPairs = new Map(); // Store ephemeral keys for current session only\n this.sessionStartTime = Date.now(); // Track session lifetime for PFS\n this.messageCounter = 0;\n this.sequenceNumber = 0;\n this.expectedSequenceNumber = 0;\n this.sessionSalt = null;\n \n // Anti-Replay and Message Ordering Protection\n this.replayWindowSize = 64; // Sliding window for replay protection\n this.replayWindow = new Set(); // Track recent sequence numbers\n this.maxSequenceGap = 100; // Maximum allowed sequence gap\n this.replayProtectionEnabled = true; // Enable/disable replay protection\n this.sessionId = null; // MITM protection: Session identifier\n this.connectionId = Array.from(crypto.getRandomValues(new Uint8Array(8)))\n .map(b => b.toString(16).padStart(2, '0')).join(''); // Connection identifier for AAD\n this.peerPublicKey = null; // Store peer's public key for PFS\n this.rateLimiterId = null;\n this.intentionalDisconnect = false;\n this.lastCleanupTime = Date.now();\n \n // Reset notification flags for new connection\n this._resetNotificationFlags();\n \n \n\n this.verificationInitiationSent = false;\n this.disconnectNotificationSent = false;\n this.reconnectionFailedNotificationSent = false;\n this.peerDisconnectNotificationSent = false;\n this.connectionClosedNotificationSent = false;\n this.fakeTrafficDisabledNotificationSent = false;\n this.advancedFeaturesDisabledNotificationSent = false;\n this.securityUpgradeNotificationSent = false;\n this.lastSecurityUpgradeStage = null;\n this.securityCalculationNotificationSent = false;\n this.lastSecurityCalculationLevel = null;\n \n // File transfer integration\n this.fileTransferSystem = null;\n this.onFileProgress = null;\n \n // ============================================\n // IV REUSE PREVENTION SYSTEM\n // ============================================\n // IV REUSE PREVENTION SYSTEM WITH LIMITS\n // ============================================\n this._ivTrackingSystem = {\n usedIVs: new Set(), // Track all used IVs to prevent reuse\n ivHistory: new Map(), // Track IV usage with timestamps (max 10k entries)\n collisionCount: 0, // Track potential collisions\n maxIVHistorySize: 10000, // Maximum IV history size\n maxSessionIVs: 1000, // Maximum IVs per session\n entropyValidation: {\n minEntropy: 3.0, // Minimum entropy threshold\n entropyTests: 0,\n entropyFailures: 0\n },\n rngValidation: {\n testsPerformed: 0,\n weakRngDetected: false,\n lastValidation: 0\n },\n sessionIVs: new Map(), // Track IVs per session\n emergencyMode: false // Emergency mode if IV reuse detected\n };\n \n // IV cleanup tracking\n this._lastIVCleanupTime = null;\n \n // ============================================\n // SECURE ERROR HANDLING SYSTEM\n // ============================================\n this._secureErrorHandler = {\n errorCategories: {\n CRYPTOGRAPHIC: 'cryptographic',\n NETWORK: 'network',\n VALIDATION: 'validation',\n SYSTEM: 'system',\n UNKNOWN: 'unknown'\n },\n errorMappings: new Map(), // Map internal errors to safe messages\n errorCounts: new Map(), // Track error frequencies\n lastErrorTime: 0,\n errorThreshold: 10, // Max errors per minute\n isInErrorMode: false\n };\n \n // ============================================\n // SECURE MEMORY MANAGEMENT SYSTEM\n // ============================================\n this._secureMemoryManager = {\n sensitiveData: new WeakMap(), // Track sensitive data for secure cleanup\n cleanupQueue: [], // Queue for deferred cleanup operations\n isCleaning: false, // Prevent concurrent cleanup operations\n cleanupInterval: null, // Periodic cleanup timer\n memoryStats: {\n totalCleanups: 0,\n failedCleanups: 0,\n lastCleanup: 0\n }\n };\n this.onFileReceived = null;\n this.onFileError = null;\n \n // PFS (Perfect Forward Secrecy) Implementation\n this.keyRotationInterval = EnhancedSecureWebRTCManager.TIMEOUTS.KEY_ROTATION_INTERVAL;\n this.lastKeyRotation = Date.now();\n this.currentKeyVersion = 0;\n this.keyVersions = new Map(); // Store key versions for PFS\n this.oldKeys = new Map(); // Store old keys temporarily for decryption\n this.maxOldKeys = EnhancedSecureWebRTCManager.LIMITS.MAX_OLD_KEYS; // Keep last 3 key versions for decryption\n this.peerConnection = null;\n this.dataChannel = null;\n \n\n this.securityFeatures = {\n\n hasEncryption: true, \n hasECDH: true, \n hasECDSA: false, \n hasMutualAuth: false, \n hasMetadataProtection: false, \n hasEnhancedReplayProtection: false, \n hasNonExtractableKeys: false, \n hasRateLimiting: true, \n hasEnhancedValidation: false, \n hasPFS: true, // Real Perfect Forward Secrecy enabled \n \n // Advanced Features (Session Managed) \n hasNestedEncryption: false, \n hasPacketPadding: false, \n hasPacketReordering: false, \n hasAntiFingerprinting: false, \n hasFakeTraffic: false, \n hasDecoyChannels: false, \n hasMessageChunking: false \n };\n this._secureLog('info', '\uD83D\uDD12 Enhanced WebRTC Manager initialized with tiered security');\n \n // Log configuration for debugging\n this._secureLog('info', '\uD83D\uDD12 Configuration loaded from constructor parameters', {\n fakeTraffic: this._config.fakeTraffic.enabled,\n decoyChannels: this._config.decoyChannels.enabled,\n packetPadding: this._config.packetPadding.enabled,\n antiFingerprinting: this._config.antiFingerprinting.enabled\n });\n \n // XSS Hardening - replace all window.DEBUG_MODE references\n this._hardenDebugModeReferences();\n \n // Initialize unified scheduler for all maintenance tasks\n this._initializeUnifiedScheduler();\n \n this._syncSecurityFeaturesWithTariff();\n \n if (!this._validateCryptographicSecurity()) {\n this._secureLog('error', '\uD83D\uDEA8 CRITICAL: Cryptographic security validation failed after tariff sync');\n throw new Error('Critical cryptographic features are missing after tariff synchronization');\n }\n // ============================================\n // ENHANCED SECURITY FEATURES\n // ============================================\n \n // 1. Nested Encryption Layer\n this.nestedEncryptionKey = null;\n // Removed nestedEncryptionIV and nestedEncryptionCounter\n // Each nested encryption now generates fresh random IV for maximum security\n \n // 2. Packet Padding\n this.paddingConfig = {\n enabled: this._config.packetPadding.enabled,\n minPadding: this._config.packetPadding.minPadding,\n maxPadding: this._config.packetPadding.maxPadding,\n useRandomPadding: this._config.packetPadding.useRandomPadding,\n preserveMessageSize: this._config.packetPadding.preserveMessageSize\n };\n \n // 3. Fake Traffic Generation\n this.fakeTrafficConfig = {\n enabled: this._config.fakeTraffic.enabled,\n minInterval: this._config.fakeTraffic.minInterval,\n maxInterval: this._config.fakeTraffic.maxInterval,\n minSize: this._config.fakeTraffic.minSize,\n maxSize: this._config.fakeTraffic.maxSize,\n patterns: this._config.fakeTraffic.patterns\n };\n this.fakeTrafficTimer = null;\n this.lastFakeTraffic = 0;\n \n // 4. Message Chunking\n this.chunkingConfig = {\n enabled: false,\n maxChunkSize: EnhancedSecureWebRTCManager.SIZES.CHUNK_SIZE_MAX, \n minDelay: EnhancedSecureWebRTCManager.SIZES.CHUNK_DELAY_MIN,\n maxDelay: EnhancedSecureWebRTCManager.SIZES.CHUNK_DELAY_MAX,\n useRandomDelays: true,\n addChunkHeaders: true\n };\n this.chunkQueue = [];\n this.chunkingInProgress = false;\n \n // 5. Decoy Channels\n this.decoyChannels = new Map();\n this.decoyChannelConfig = {\n enabled: this._config.decoyChannels.enabled,\n maxDecoyChannels: this._config.decoyChannels.maxDecoyChannels,\n decoyChannelNames: this._config.decoyChannels.decoyChannelNames,\n sendDecoyData: this._config.decoyChannels.sendDecoyData,\n randomDecoyIntervals: this._config.decoyChannels.randomDecoyIntervals\n };\n this.decoyTimers = new Map();\n \n // 6. Packet Reordering Protection\n this.reorderingConfig = {\n enabled: false, \n maxOutOfOrder: EnhancedSecureWebRTCManager.LIMITS.MAX_OUT_OF_ORDER_PACKETS, \n reorderTimeout: EnhancedSecureWebRTCManager.TIMEOUTS.REORDER_TIMEOUT, \n useSequenceNumbers: true,\n useTimestamps: true\n };\n this.packetBuffer = new Map(); // sequence -> {data, timestamp}\n this.lastProcessedSequence = -1;\n \n // 7. Anti-Fingerprinting\n this.antiFingerprintingConfig = {\n enabled: this._config.antiFingerprinting.enabled,\n randomizeTiming: this._config.antiFingerprinting.randomizeTiming,\n randomizeSizes: this._config.antiFingerprinting.randomizeSizes,\n addNoise: this._config.antiFingerprinting.addNoise,\n maskPatterns: this._config.antiFingerprinting.maskPatterns,\n useRandomHeaders: this._config.antiFingerprinting.useRandomHeaders\n };\n this.fingerprintMask = this.generateFingerprintMask();\n \n // Initialize rate limiter ID\n this.rateLimiterId = `webrtc_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n \n // Start periodic cleanup\n this.startPeriodicCleanup();\n \n this.initializeEnhancedSecurity(); \n \n // ============================================\n // MUTEX SYSTEM TO PREVENT RACE CONDITIONS\n // ============================================\n\n // Mutex for key operations\n this._keyOperationMutex = {\n locked: false,\n queue: [],\n lockId: null,\n lockTimeout: null\n };\n\n // Mutex for encryption/decryption operations\n this._cryptoOperationMutex = {\n locked: false,\n queue: [],\n lockId: null,\n lockTimeout: null\n };\n\n // Mutex for connection initialization\n this._connectionOperationMutex = {\n locked: false,\n queue: [],\n lockId: null,\n lockTimeout: null\n };\n\n // Key system state\n this._keySystemState = {\n isInitializing: false,\n isRotating: false,\n isDestroying: false,\n lastOperation: null,\n lastOperationTime: Date.now()\n };\n\n // Operation counters\n this._operationCounters = {\n keyOperations: 0,\n cryptoOperations: 0,\n connectionOperations: 0\n };\n\n }\n \n /**\n * Create AAD with sequence number for anti-replay protection\n * This binds each message to its sequence number and prevents replay attacks\n */\n _createMessageAAD(messageType, messageData = null, isFileMessage = false) {\n try {\n const aad = {\n sessionId: this.currentSession?.sessionId || this.sessionId || 'unknown',\n keyFingerprint: this.keyFingerprint || 'unknown',\n sequenceNumber: this._generateNextSequenceNumber(),\n messageType: messageType,\n timestamp: Date.now(),\n connectionId: this.connectionId || 'unknown',\n isFileMessage: isFileMessage\n };\n\n // Add message-specific data if available\n if (messageData && typeof messageData === 'object') {\n if (messageData.fileId) aad.fileId = messageData.fileId;\n if (messageData.chunkIndex !== undefined) aad.chunkIndex = messageData.chunkIndex;\n if (messageData.totalChunks !== undefined) aad.totalChunks = messageData.totalChunks;\n }\n\n return JSON.stringify(aad);\n } catch (error) {\n this._secureLog('error', '\u274C Failed to create message AAD', {\n errorType: error.constructor.name,\n message: error.message,\n messageType: messageType\n });\n // Fallback to basic AAD\n return JSON.stringify({\n sessionId: 'unknown',\n keyFingerprint: 'unknown',\n sequenceNumber: Date.now(),\n messageType: messageType,\n timestamp: Date.now(),\n connectionId: 'unknown',\n isFileMessage: isFileMessage\n });\n }\n }\n \n /**\n * Generate next sequence number for outgoing messages\n * This ensures unique ordering and prevents replay attacks\n */\n _generateNextSequenceNumber() {\n const nextSeq = this.sequenceNumber++;\n \n // Reset sequence number if it gets too large\n if (this.sequenceNumber > Number.MAX_SAFE_INTEGER - 1000) {\n this.sequenceNumber = 0;\n this.expectedSequenceNumber = 0;\n this.replayWindow.clear();\n this._secureLog('warn', '\u26A0\uFE0F Sequence number reset due to overflow', {\n timestamp: Date.now()\n });\n }\n \n return nextSeq;\n }\n \n /**\n * Enhanced mutex system initialization with atomic protection\n */\n _initializeMutexSystem() {\n // Initialize standard mutexes with enhanced state tracking\n this._keyOperationMutex = {\n locked: false,\n queue: [],\n lockId: null,\n lockTimeout: null,\n lockTime: null,\n operationCount: 0\n };\n\n this._cryptoOperationMutex = {\n locked: false,\n queue: [],\n lockId: null,\n lockTimeout: null,\n lockTime: null,\n operationCount: 0\n };\n\n this._connectionOperationMutex = {\n locked: false,\n queue: [],\n lockId: null,\n lockTimeout: null,\n lockTime: null,\n operationCount: 0\n };\n\n // Enhanced key system state with atomic operation tracking\n this._keySystemState = {\n isInitializing: false,\n isRotating: false,\n isDestroying: false,\n lastOperation: null,\n lastOperationTime: Date.now(),\n operationId: null,\n concurrentOperations: 0,\n maxConcurrentOperations: 1\n };\n\n // Operation counters with atomic increments\n this._operationCounters = {\n keyOperations: 0,\n cryptoOperations: 0,\n connectionOperations: 0,\n totalOperations: 0,\n failedOperations: 0\n };\n\n this._secureLog('info', '\uD83D\uDD12 Enhanced mutex system initialized with atomic protection', {\n mutexes: ['keyOperation', 'cryptoOperation', 'connectionOperation'],\n timestamp: Date.now(),\n features: ['atomic_operations', 'race_condition_protection', 'enhanced_state_tracking']\n });\n }\n\n /**\n * XSS Hardening - Debug mode references validation\n * This method is called during initialization to ensure XSS hardening\n */\n _hardenDebugModeReferences() {\n // Log that we're hardening debug mode references\n this._secureLog('info', '\uD83D\uDD12 XSS Hardening: Debug mode references already replaced');\n }\n\n /**\n * Unified scheduler for all maintenance tasks\n * Replaces multiple setInterval calls with a single, controlled scheduler\n */\n _initializeUnifiedScheduler() {\n // Single scheduler interval for all maintenance tasks\n this._maintenanceScheduler = setInterval(() => {\n this._executeMaintenanceCycle();\n }, 300000); // Every 5 minutes\n \n // Log scheduler initialization\n this._secureLog('info', '\uD83D\uDD27 Unified maintenance scheduler initialized (5-minute cycle)');\n \n // Store scheduler reference for cleanup\n this._activeTimers = new Set([this._maintenanceScheduler]);\n }\n\n /**\n * Execute all maintenance tasks in a single cycle\n */\n _executeMaintenanceCycle() {\n try {\n this._secureLog('info', '\uD83D\uDD27 Starting maintenance cycle');\n \n // 1. Log cleanup and security audit\n this._cleanupLogs();\n this._auditLoggingSystemSecurity();\n \n // 2. Security monitoring\n this._verifyAPIIntegrity();\n this._validateCryptographicSecurity();\n this._syncSecurityFeaturesWithTariff();\n \n // 3. Resource cleanup\n this._cleanupResources();\n this._enforceResourceLimits();\n \n // 4. Key monitoring (if connected)\n if (this.isConnected && this.isVerified) {\n this._monitorKeySecurity();\n }\n \n // 5. Global exposure monitoring (debug mode only)\n if (this._debugMode) {\n this._monitorGlobalExposure();\n }\n \n // 6. Heartbeat (if enabled and connected)\n if (this._heartbeatConfig && this._heartbeatConfig.enabled && this.isConnected()) {\n this._sendHeartbeat();\n }\n \n this._secureLog('info', '\uD83D\uDD27 Maintenance cycle completed successfully');\n \n } catch (error) {\n this._secureLog('error', '\u274C Maintenance cycle failed', {\n errorType: error?.constructor?.name || 'Unknown',\n message: error?.message || 'Unknown error'\n });\n \n // Emergency cleanup on failure\n this._emergencyCleanup();\n }\n }\n\n /**\n * Enforce hard resource limits with emergency cleanup\n */\n _enforceResourceLimits() {\n const violations = [];\n \n // Check log entries\n if (this._logCounts.size > this._resourceLimits.maxLogEntries) {\n violations.push('log_entries');\n }\n \n // Check message queue\n if (this.messageQueue.length > this._resourceLimits.maxMessageQueue) {\n violations.push('message_queue');\n }\n \n // Check IV history\n if (this._ivTrackingSystem && this._ivTrackingSystem.ivHistory.size > this._resourceLimits.maxIVHistory) {\n violations.push('iv_history');\n }\n \n // Check processed message IDs\n if (this.processedMessageIds.size > this._resourceLimits.maxProcessedMessageIds) {\n violations.push('processed_message_ids');\n }\n \n // Check decoy channels\n if (this.decoyChannels.size > this._resourceLimits.maxDecoyChannels) {\n violations.push('decoy_channels');\n }\n \n // Check fake traffic messages\n if (this._fakeTrafficMessages && this._fakeTrafficMessages.length > this._resourceLimits.maxFakeTrafficMessages) {\n violations.push('fake_traffic_messages');\n }\n \n // Check chunk queue\n if (this.chunkQueue.length > this._resourceLimits.maxChunkQueue) {\n violations.push('chunk_queue');\n }\n \n // Check packet buffer\n if (this.packetBuffer && this.packetBuffer.size > this._resourceLimits.maxPacketBuffer) {\n violations.push('packet_buffer');\n }\n \n // If violations detected, trigger emergency cleanup\n if (violations.length > 0) {\n this._secureLog('warn', '\u26A0\uFE0F Resource limit violations detected', { violations });\n this._emergencyCleanup();\n }\n }\n\n /**\n * Emergency cleanup when resource limits are exceeded\n */\n _emergencyCleanup() {\n this._secureLog('warn', '\uD83D\uDEA8 EMERGENCY: Resource limits exceeded, performing emergency cleanup');\n \n try {\n // 1. Clear all logs immediately\n this._logCounts.clear();\n this._secureLog('info', '\uD83E\uDDF9 Emergency: All logs cleared');\n \n // 2. Clear message queue\n this.messageQueue.length = 0;\n this._secureLog('info', '\uD83E\uDDF9 Emergency: Message queue cleared');\n \n // 3. Enhanced IV history cleanup\n if (this._ivTrackingSystem) {\n this._ivTrackingSystem.usedIVs.clear();\n this._ivTrackingSystem.ivHistory.clear();\n this._ivTrackingSystem.sessionIVs.clear();\n this._ivTrackingSystem.collisionCount = 0;\n this._ivTrackingSystem.emergencyMode = false;\n this._secureLog('info', '\uD83E\uDDF9 Enhanced Emergency: IV tracking system cleared');\n }\n \n // 4. Clear processed message IDs\n this.processedMessageIds.clear();\n this._secureLog('info', '\uD83E\uDDF9 Emergency: Processed message IDs cleared');\n \n // 5. Enhanced decoy channels cleanup\n if (this.decoyChannels) {\n for (const [channelName, timer] of this.decoyTimers) {\n if (timer) clearTimeout(timer);\n }\n this.decoyChannels.clear();\n this.decoyTimers.clear();\n this._secureLog('info', '\uD83E\uDDF9 Enhanced Emergency: Decoy channels cleared');\n }\n \n // 6. Enhanced fake traffic cleanup\n if (this.fakeTrafficTimer) {\n clearTimeout(this.fakeTrafficTimer);\n this.fakeTrafficTimer = null;\n }\n if (this._fakeTrafficMessages) {\n this._fakeTrafficMessages.length = 0;\n this._secureLog('info', '\uD83E\uDDF9 Enhanced Emergency: Fake traffic messages cleared');\n }\n \n // 7. Clear chunk queue\n this.chunkQueue.length = 0;\n this._secureLog('info', '\uD83E\uDDF9 Emergency: Chunk queue cleared');\n \n // 8. Clear packet buffer\n if (this.packetBuffer) {\n this.packetBuffer.clear();\n this._secureLog('info', '\uD83E\uDDF9 Emergency: Packet buffer cleared');\n }\n \n // 9. Enhanced memory cleanup with quantum-resistant patterns\n this._secureMemoryManager.isCleaning = true;\n this._secureMemoryManager.cleanupQueue.length = 0;\n this._secureMemoryManager.memoryStats.lastCleanup = Date.now();\n \n // Force multiple garbage collection cycles\n if (typeof window.gc === 'function') {\n try {\n // Multiple GC cycles for thorough cleanup\n for (let i = 0; i < 3; i++) {\n window.gc();\n this._secureLog('info', `\uD83E\uDDF9 Enhanced Emergency: Garbage collection cycle ${i + 1}/3`);\n // Small delay between cycles\n if (i < 2) {\n const start = Date.now();\n while (Date.now() - start < 10) {\n // Busy wait for 10ms\n }\n }\n }\n } catch (e) {\n // Ignore GC errors\n }\n }\n \n this._secureMemoryManager.isCleaning = false;\n \n this._secureLog('info', '\u2705 Enhanced emergency cleanup completed successfully');\n \n } catch (error) {\n this._secureLog('error', '\u274C Enhanced emergency cleanup failed', {\n errorType: error?.constructor?.name || 'Unknown',\n message: error?.message || 'Unknown error'\n });\n \n // Rollback mechanism (simplified)\n this._secureMemoryManager.isCleaning = false;\n }\n }\n\n /**\n * Validate emergency cleanup success\n * @param {Object} originalState - Original state before cleanup\n * @returns {Object} Validation results\n */\n _validateEmergencyCleanup(originalState) {\n const currentState = {\n messageQueueSize: this.messageQueue.length,\n processedIdsSize: this.processedMessageIds.size,\n packetBufferSize: this.packetBuffer ? this.packetBuffer.size : 0,\n ivTrackingSize: this._ivTrackingSystem ? this._ivTrackingSystem.usedIVs.size : 0,\n decoyChannelsSize: this.decoyChannels ? this.decoyChannels.size : 0\n };\n \n const validation = {\n messageQueueCleared: currentState.messageQueueSize === 0,\n processedIdsCleared: currentState.processedIdsSize === 0,\n packetBufferCleared: currentState.packetBufferSize === 0,\n ivTrackingCleared: currentState.ivTrackingSize === 0,\n decoyChannelsCleared: currentState.decoyChannelsSize === 0,\n allCleared: (\n currentState.messageQueueSize === 0 &&\n currentState.processedIdsSize === 0 &&\n currentState.packetBufferSize === 0 &&\n currentState.ivTrackingSize === 0 &&\n currentState.decoyChannelsSize === 0\n )\n };\n \n return validation;\n }\n\n /**\n * Cleanup resources based on age and usage\n */\n _cleanupResources() {\n const now = Date.now();\n \n // Clean old processed message IDs (keep only last hour)\n if (this.processedMessageIds.size > this._emergencyThresholds.processedMessageIds) {\n this.processedMessageIds.clear();\n this._secureLog('info', '\uD83E\uDDF9 Old processed message IDs cleared');\n }\n \n // Clean old IVs\n if (this._ivTrackingSystem) {\n this._cleanupOldIVs();\n }\n \n // Clean old keys\n this.cleanupOldKeys();\n \n // Clean rate limiter\n if (window.EnhancedSecureCryptoUtils && window.EnhancedSecureCryptoUtils.rateLimiter) {\n window.EnhancedSecureCryptoUtils.rateLimiter.cleanup();\n }\n \n this._secureLog('info', '\uD83E\uDDF9 Resource cleanup completed');\n }\n\n /**\n * Monitor key security (replaces _startKeySecurityMonitoring)\n */\n _monitorKeySecurity() {\n if (this._keyStorageStats.activeKeys > 10) {\n this._secureLog('warn', '\u26A0\uFE0F High number of active keys detected. Consider rotation.');\n }\n \n if (Date.now() - (this._keyStorageStats.lastRotation || 0) > 3600000) {\n this._rotateKeys();\n }\n }\n\n /**\n * Send heartbeat message (called by unified scheduler)\n */\n _sendHeartbeat() {\n try {\n if (this.isConnected() && this.dataChannel && this.dataChannel.readyState === 'open') {\n this.dataChannel.send(JSON.stringify({ \n type: EnhancedSecureWebRTCManager.MESSAGE_TYPES.HEARTBEAT, \n timestamp: Date.now() \n }));\n \n this._heartbeatConfig.lastHeartbeat = Date.now();\n this._secureLog('debug', '\uD83D\uDC93 Heartbeat sent');\n }\n } catch (error) {\n this._secureLog('error', '\u274C Heartbeat failed:', { \n errorType: error?.constructor?.name || 'Unknown',\n message: error?.message || 'Unknown error'\n });\n }\n }\n\n /**\n * Comprehensive input validation to prevent DoS and injection attacks\n * @param {any} data - Data to validate\n * @param {string} context - Context for validation (e.g., 'sendMessage', 'sendSecureMessage')\n * @returns {Object} Validation result with isValid and sanitizedData\n */\n _validateInputData(data, context = 'unknown') {\n const validationResult = {\n isValid: false,\n sanitizedData: null,\n errors: [],\n warnings: []\n };\n\n try {\n // 1. Basic type validation\n if (data === null || data === undefined) {\n validationResult.errors.push('Data cannot be null or undefined');\n return validationResult;\n }\n\n // 2. Size validation for strings\n if (typeof data === 'string') {\n if (data.length > this._inputValidationLimits.maxStringLength) {\n validationResult.errors.push(`String too long: ${data.length} > ${this._inputValidationLimits.maxStringLength}`);\n return validationResult;\n }\n\n // 3. Malicious pattern detection for strings\n for (const pattern of this._maliciousPatterns) {\n if (pattern.test(data)) {\n validationResult.errors.push(`Malicious pattern detected: ${pattern.source}`);\n this._secureLog('warn', '\uD83D\uDEA8 Malicious pattern detected in input', {\n context: context,\n pattern: pattern.source,\n dataLength: data.length\n });\n return validationResult;\n }\n }\n\n // 4. Sanitize string data\n validationResult.sanitizedData = this._sanitizeInputString(data);\n validationResult.isValid = true;\n return validationResult;\n }\n\n // 5. Object validation\n if (typeof data === 'object') {\n // Check for circular references\n const seen = new WeakSet();\n const checkCircular = (obj, path = '') => {\n if (obj === null || typeof obj !== 'object') return;\n \n if (seen.has(obj)) {\n validationResult.errors.push(`Circular reference detected at path: ${path}`);\n return;\n }\n \n seen.add(obj);\n \n // Check object depth\n if (path.split('.').length > this._inputValidationLimits.maxObjectDepth) {\n validationResult.errors.push(`Object too deep: ${path.split('.').length} > ${this._inputValidationLimits.maxObjectDepth}`);\n return;\n }\n\n // Check array length\n if (Array.isArray(obj) && obj.length > this._inputValidationLimits.maxArrayLength) {\n validationResult.errors.push(`Array too long: ${obj.length} > ${this._inputValidationLimits.maxArrayLength}`);\n return;\n }\n\n // Recursively check all properties\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n checkCircular(obj[key], path ? `${path}.${key}` : key);\n }\n }\n };\n\n checkCircular(data);\n \n if (validationResult.errors.length > 0) {\n return validationResult;\n }\n\n // 6. Check total object size\n const objectSize = this._calculateObjectSize(data);\n if (objectSize > this._inputValidationLimits.maxMessageSize) {\n validationResult.errors.push(`Object too large: ${objectSize} bytes > ${this._inputValidationLimits.maxMessageSize} bytes`);\n return validationResult;\n }\n\n // 7. Sanitize object data\n validationResult.sanitizedData = this._sanitizeInputObject(data);\n validationResult.isValid = true;\n return validationResult;\n }\n\n // 8. ArrayBuffer validation\n if (data instanceof ArrayBuffer) {\n if (data.byteLength > this._inputValidationLimits.maxMessageSize) {\n validationResult.errors.push(`ArrayBuffer too large: ${data.byteLength} bytes > ${this._inputValidationLimits.maxMessageSize} bytes`);\n return validationResult;\n }\n \n validationResult.sanitizedData = data;\n validationResult.isValid = true;\n return validationResult;\n }\n\n // 9. Other types are not allowed\n validationResult.errors.push(`Unsupported data type: ${typeof data}`);\n return validationResult;\n\n } catch (error) {\n validationResult.errors.push(`Validation error: ${error.message}`);\n this._secureLog('error', '\u274C Input validation failed', {\n context: context,\n errorType: error?.constructor?.name || 'Unknown',\n message: error?.message || 'Unknown error'\n });\n return validationResult;\n }\n }\n\n /**\n * Calculate approximate object size in bytes\n * @param {any} obj - Object to calculate size for\n * @returns {number} Size in bytes\n */\n _calculateObjectSize(obj) {\n try {\n const jsonString = JSON.stringify(obj);\n return new TextEncoder().encode(jsonString).length;\n } catch (error) {\n // If JSON.stringify fails, estimate size\n return 1024 * 1024; // Assume 1MB to be safe\n }\n }\n\n /**\n * Sanitize string data for input validation\n * @param {string} str - String to sanitize\n * @returns {string} Sanitized string\n */\n _sanitizeInputString(str) {\n if (typeof str !== 'string') return str;\n \n // Remove null bytes\n str = str.replace(/\\0/g, '');\n \n // Normalize whitespace\n str = str.replace(/\\s+/g, ' ');\n \n // Trim\n str = str.trim();\n \n return str;\n }\n\n /**\n * Sanitize object data for input validation\n * @param {any} obj - Object to sanitize\n * @returns {any} Sanitized object\n */\n _sanitizeInputObject(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n \n if (Array.isArray(obj)) {\n return obj.map(item => this._sanitizeInputObject(item));\n }\n \n const sanitized = {};\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n const value = obj[key];\n if (typeof value === 'string') {\n sanitized[key] = this._sanitizeInputString(value);\n } else if (typeof value === 'object') {\n sanitized[key] = this._sanitizeInputObject(value);\n } else {\n sanitized[key] = value;\n }\n }\n }\n \n return sanitized;\n }\n\n /**\n * Rate limiting for message sending\n * @param {string} context - Context for rate limiting\n * @returns {boolean} true if rate limit allows\n */\n _checkRateLimit(context = 'message') {\n const now = Date.now();\n \n // Initialize rate limiter if not exists\n if (!this._rateLimiter) {\n this._rateLimiter = {\n messageCount: 0,\n lastReset: now,\n burstCount: 0,\n lastBurstReset: now\n };\n }\n \n // Reset counters if needed\n if (now - this._rateLimiter.lastReset > 60000) { // 1 minute\n this._rateLimiter.messageCount = 0;\n this._rateLimiter.lastReset = now;\n }\n \n if (now - this._rateLimiter.lastBurstReset > 1000) { // 1 second\n this._rateLimiter.burstCount = 0;\n this._rateLimiter.lastBurstReset = now;\n }\n \n // Check burst limit\n if (this._rateLimiter.burstCount >= this._inputValidationLimits.rateLimitBurstSize) {\n this._secureLog('warn', '\u26A0\uFE0F Rate limit burst exceeded', { context });\n return false;\n }\n \n // Check overall rate limit\n if (this._rateLimiter.messageCount >= this._inputValidationLimits.rateLimitMessagesPerMinute) {\n this._secureLog('warn', '\u26A0\uFE0F Rate limit exceeded', { context });\n return false;\n }\n \n // Increment counters\n this._rateLimiter.messageCount++;\n this._rateLimiter.burstCount++;\n \n return true;\n }\n\n // ============================================\n // SECURE KEY STORAGE MANAGEMENT\n // ============================================\n\n /**\n * Initializes the secure key storage\n */\n _initializeSecureKeyStorage() {\n // Initialize with the new class\n this._secureKeyStorage = new SecureKeyStorage();\n \n // Keep the stats structure for compatibility\n this._keyStorageStats = {\n totalKeys: 0,\n activeKeys: 0,\n lastAccess: null,\n lastRotation: null,\n };\n \n this._secureLog('info', '\uD83D\uDD10 Enhanced secure key storage initialized');\n }\n\n // Helper: ensure file transfer system is ready (lazy init on receiver)\n async _ensureFileTransferReady() {\n try {\n // If already initialized \u2014 done\n if (this.fileTransferSystem) {\n return true;\n }\n // Requires an open data channel and a verified connection\n if (!this.dataChannel || this.dataChannel.readyState !== 'open') {\n throw new Error('Data channel not open');\n }\n if (!this.isVerified) {\n throw new Error('Connection not verified');\n }\n // Initialization\n this.initializeFileTransfer();\n \n // \u041A\u0420\u0418\u0422\u0418\u0427\u0415\u0421\u041A\u041E\u0415 \u0418\u0421\u041F\u0420\u0410\u0412\u041B\u0415\u041D\u0418\u0415: \u0416\u0434\u0435\u043C \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u0441 \u0442\u0430\u0439\u043C\u0430\u0443\u0442\u043E\u043C\n let attempts = 0;\n const maxAttempts = 50; // 5 \u0441\u0435\u043A\u0443\u043D\u0434 \u043C\u0430\u043A\u0441\u0438\u043C\u0443\u043C\n while (!this.fileTransferSystem && attempts < maxAttempts) {\n await new Promise(r => setTimeout(r, 100));\n attempts++;\n }\n \n if (!this.fileTransferSystem) {\n throw new Error('File transfer system initialization timeout');\n }\n \n return true;\n } catch (e) {\n this._secureLog('error', '\u274C _ensureFileTransferReady failed', { \n errorType: e?.constructor?.name || 'Unknown',\n hasMessage: !!e?.message \n });\n return false;\n }\n }\n\n _getSecureKey(keyId) {\n return this._secureKeyStorage.retrieveKey(keyId);\n }\n\n async _setSecureKey(keyId, key) {\n if (!(key instanceof CryptoKey)) {\n this._secureLog('error', '\u274C Attempt to store non-CryptoKey');\n return false;\n }\n \n const success = await this._secureKeyStorage.storeKey(keyId, key, {\n version: this.currentKeyVersion,\n type: key.algorithm.name\n });\n \n if (success) {\n this._secureLog('info', `\uD83D\uDD11 Key ${keyId} stored securely with encryption`);\n }\n \n return success;\n }\n\n /**\n * Validates a key value\n * @param {CryptoKey} key - Key to validate\n * @returns {boolean} true if the key is valid\n */\n _validateKeyValue(key) {\n return key instanceof CryptoKey &&\n key.algorithm &&\n key.usages &&\n key.usages.length > 0;\n }\n\n _secureWipeKeys() {\n this._secureKeyStorage.secureWipeAll();\n this._secureLog('info', '\uD83E\uDDF9 All keys securely wiped and encrypted storage cleared');\n }\n\n /**\n * Validates key storage state\n * @returns {boolean} true if the storage is ready\n */\n _validateKeyStorage() {\n return this._secureKeyStorage instanceof SecureKeyStorage;\n }\n\n /**\n * Returns secure key storage statistics\n * @returns {object} Storage metrics\n */\n _getKeyStorageStats() {\n const stats = this._secureKeyStorage.getStorageStats();\n return {\n totalKeysCount: stats.totalKeys,\n activeKeysCount: stats.totalKeys,\n hasLastAccess: stats.metadata.some(m => m.lastAccessed),\n hasLastRotation: !!this._keyStorageStats.lastRotation,\n storageType: 'SecureKeyStorage',\n timestamp: Date.now()\n };\n }\n\n /**\n * Performs key rotation in storage\n */\n _rotateKeys() {\n const oldKeys = Array.from(this._secureKeyStorage.keys());\n this._secureKeyStorage.clear();\n this._keyStorageStats.lastRotation = Date.now();\n this._keyStorageStats.activeKeys = 0;\n this._secureLog('info', `\uD83D\uDD04 Key rotation completed. ${oldKeys.length} keys rotated`);\n }\n\n /**\n * Emergency key wipe (e.g., upon detecting a threat)\n */\n _emergencyKeyWipe() {\n this._secureWipeKeys();\n this._secureLog('error', '\uD83D\uDEA8 EMERGENCY: All keys wiped due to security threat');\n }\n\n /**\n * Starts key security monitoring\n * @deprecated Use unified scheduler instead\n */\n _startKeySecurityMonitoring() {\n // Functionality moved to unified scheduler\n this._secureLog('info', '\uD83D\uDD27 Key security monitoring moved to unified scheduler');\n }\n\n\n // ============================================\n // HELPER METHODS\n // ============================================\n /**\n * Constant-time key validation to prevent timing attacks\n * @param {CryptoKey} key - Key to validate\n * @returns {boolean} true if key is valid\n */\n _validateKeyConstantTime(key) {\n // Constant-time validation to prevent timing attacks\n let isValid = 0;\n \n // Check if key is CryptoKey instance (constant-time)\n try {\n const isCryptoKey = key instanceof CryptoKey;\n isValid += isCryptoKey ? 1 : 0;\n } catch {\n isValid += 0;\n }\n \n // Check algorithm (constant-time)\n try {\n const hasAlgorithm = !!(key && key.algorithm);\n isValid += hasAlgorithm ? 1 : 0;\n } catch {\n isValid += 0;\n }\n \n // Check type (constant-time)\n try {\n const hasType = !!(key && key.type);\n isValid += hasType ? 1 : 0;\n } catch {\n isValid += 0;\n }\n \n // Check extractable property (constant-time)\n try {\n const hasExtractable = key && key.extractable !== undefined;\n isValid += hasExtractable ? 1 : 0;\n } catch {\n isValid += 0;\n }\n \n // All checks must pass\n return isValid === 4;\n }\n\n /**\n * Constant-time key pair validation\n * @param {Object} keyPair - Key pair to validate\n * @returns {boolean} true if key pair is valid\n */\n _validateKeyPairConstantTime(keyPair) {\n if (!keyPair || typeof keyPair !== 'object') return false;\n \n const privateKeyValid = this._validateKeyConstantTime(keyPair.privateKey);\n const publicKeyValid = this._validateKeyConstantTime(keyPair.publicKey);\n \n // Constant-time AND operation\n return privateKeyValid && publicKeyValid;\n }\n\n /**\n * Enhanced secure logging system initialization\n */\n _initializeSecureLogging() {\n // Logging levels\n this._logLevels = {\n error: 0,\n warn: 1, \n info: 2,\n debug: 3,\n trace: 4\n };\n \n // Ultra-strict levels for production\n this._currentLogLevel = this._isProductionMode ? \n this._logLevels.error : // In production, ONLY critical errors\n this._logLevels.info; // In development, up to info\n \n // Reduced log limits to prevent data accumulation\n this._logCounts = new Map();\n this._maxLogCount = this._isProductionMode ? 5 : 50; // Reduced limits\n \n // Hard resource limits to prevent memory leaks\n this._resourceLimits = {\n maxLogEntries: this._isProductionMode ? 100 : 1000,\n maxMessageQueue: 1000,\n maxIVHistory: 10000,\n maxProcessedMessageIds: 5000,\n maxDecoyChannels: 100,\n maxFakeTrafficMessages: 500,\n maxChunkQueue: 200,\n maxPacketBuffer: 1000\n };\n \n // Emergency cleanup thresholds\n this._emergencyThresholds = {\n logEntries: this._resourceLimits.maxLogEntries * 0.8, // 80%\n messageQueue: this._resourceLimits.maxMessageQueue * 0.8,\n ivHistory: this._resourceLimits.maxIVHistory * 0.8,\n processedMessageIds: this._resourceLimits.maxProcessedMessageIds * 0.8\n };\n \n // Input validation limits to prevent DoS attacks\n this._inputValidationLimits = {\n maxStringLength: 100000, // 100KB for strings\n maxObjectDepth: 10, // Maximum object nesting depth\n maxArrayLength: 1000, // Maximum array length\n maxMessageSize: 1024 * 1024, // 1MB total message size\n maxConcurrentMessages: 10, // Maximum concurrent message processing\n rateLimitMessagesPerMinute: 60, // Rate limiting\n rateLimitBurstSize: 10 // Burst size for rate limiting\n };\n \n // Malicious pattern detection\n this._maliciousPatterns = [\n /)<[^<]*)*<\\/script>/gi, // Script tags\n /javascript:/gi, // JavaScript protocol\n /data:text\\/html/gi, // Data URLs with HTML\n /on\\w+\\s*=/gi, // Event handlers\n /eval\\s*\\(/gi, // eval() calls\n /document\\./gi, // Document object access\n /window\\./gi, // Window object access\n /localStorage/gi, // LocalStorage access\n /sessionStorage/gi, // SessionStorage access\n /fetch\\s*\\(/gi, // Fetch API calls\n /XMLHttpRequest/gi, // XHR calls\n /import\\s*\\(/gi, // Dynamic imports\n /require\\s*\\(/gi, // Require calls\n /process\\./gi, // Process object access\n /global/gi, // Global object access\n /__proto__/gi, // Prototype pollution\n /constructor/gi, // Constructor access\n /prototype/gi, // Prototype access\n /toString\\s*\\(/gi, // toString calls\n /valueOf\\s*\\(/gi // valueOf calls\n ];\n\n // Comprehensive blacklist with all sensitive patterns\n this._absoluteBlacklist = new Set([\n // Cryptographic keys\n 'encryptionKey', 'macKey', 'metadataKey', 'privateKey', 'publicKey',\n 'ecdhKeyPair', 'ecdsaKeyPair', 'peerPublicKey', 'nestedEncryptionKey',\n \n // Authentication and session data\n 'verificationCode', 'sessionSalt', 'keyFingerprint', 'sessionId',\n 'authChallenge', 'authProof', 'authToken', 'sessionToken',\n \n // Credentials and secrets\n 'password', 'token', 'secret', 'credential', 'signature',\n 'apiKey', 'accessKey', 'secretKey', 'privateKey',\n \n // Cryptographic materials\n 'hash', 'digest', 'nonce', 'iv', 'cipher', 'seed',\n 'entropy', 'random', 'salt', 'fingerprint',\n \n // JWT and session data\n 'jwt', 'bearer', 'refreshToken', 'accessToken',\n \n // File transfer sensitive data\n 'fileHash', 'fileSignature', 'transferKey', 'chunkKey'\n ]);\n\n // Minimal whitelist with strict validation\n this._safeFieldsWhitelist = new Set([\n // Basic status fields\n 'timestamp', 'type', 'status', 'state', 'level',\n 'isConnected', 'isVerified', 'isInitiator', 'version',\n \n // Counters and metrics (safe)\n 'count', 'total', 'active', 'inactive', 'success', 'failure',\n \n // Connection states (safe)\n 'readyState', 'connectionState', 'iceConnectionState',\n \n // Feature counts (safe)\n 'activeFeaturesCount', 'totalFeatures', 'stage',\n \n // Error types (safe)\n 'errorType', 'errorCode', 'phase', 'attempt'\n ]);\n \n // Initialize security monitoring\n this._initializeLogSecurityMonitoring();\n \n this._secureLog('info', `\uD83D\uDD27 Enhanced secure logging initialized (Production: ${this._isProductionMode})`);\n }\n\n /**\n * Initialize security monitoring for logging system\n */\n _initializeLogSecurityMonitoring() {\n // Security monitoring moved to unified scheduler\n this._logSecurityViolations = 0;\n this._maxLogSecurityViolations = 3;\n }\n\n /**\n * Audit logging system security\n */\n _auditLoggingSystemSecurity() {\n let violations = 0;\n \n // Check for excessive log counts (potential data leakage)\n for (const [key, count] of this._logCounts.entries()) {\n if (count > this._maxLogCount * 2) {\n violations++;\n this._originalConsole?.error?.(`\uD83D\uDEA8 LOG SECURITY: Excessive log count detected: ${key}`);\n }\n }\n \n // Check for blacklisted patterns in recent logs\n const recentLogs = Array.from(this._logCounts.keys());\n for (const logKey of recentLogs) {\n if (this._containsSensitiveContent(logKey)) {\n violations++;\n this._originalConsole?.error?.(`\uD83D\uDEA8 LOG SECURITY: Sensitive content in log key: ${logKey}`);\n }\n }\n \n // Emergency shutdown if too many violations\n this._logSecurityViolations += violations;\n if (this._logSecurityViolations >= this._maxLogSecurityViolations) {\n this._emergencyDisableLogging();\n this._originalConsole?.error?.('\uD83D\uDEA8 CRITICAL: Logging system disabled due to security violations');\n }\n }\n /**\n * Shim to redirect arbitrary console.log calls to _secureLog('info', ...)\n * Fixed syntax errors and improved error handling\n */\n _secureLogShim(...args) {\n try {\n // Validate arguments array\n if (!Array.isArray(args) || args.length === 0) {\n return;\n }\n \n // Proper destructuring with fallback\n const message = args[0];\n const restArgs = args.slice(1);\n \n // Handle different argument patterns\n if (restArgs.length === 0) {\n this._secureLog('info', String(message || ''));\n return;\n }\n \n if (restArgs.length === 1) {\n this._secureLog('info', String(message || ''), restArgs[0]);\n return;\n }\n \n // Proper object structure for multiple args\n this._secureLog('info', String(message || ''), { \n additionalArgs: restArgs,\n argCount: restArgs.length \n });\n } catch (error) {\n // Better error handling - fallback to original console if available\n try {\n if (this._originalConsole?.log) {\n this._originalConsole.log(...args);\n }\n } catch (fallbackError) {\n // Silent failure to prevent execution disruption\n }\n }\n }\n /**\n * Redirects global console.log to this instance's secure logger\n * Improved error handling and validation\n */\n /**\n * Setup own logger without touching global console\n */\n _setupOwnLogger() {\n // Create own logger without touching global console\n this.logger = {\n log: (message, data) => this._secureLog('info', message, data),\n info: (message, data) => this._secureLog('info', message, data),\n warn: (message, data) => this._secureLog('warn', message, data),\n error: (message, data) => this._secureLog('error', message, data),\n debug: (message, data) => this._secureLog('debug', message, data)\n };\n \n // In development, log to console; in production, use secure logging only\n if (EnhancedSecureWebRTCManager.DEBUG_MODE) {\n this._secureLog('info', '\uD83D\uDD12 Own logger created - development mode');\n } else {\n this._secureLog('info', '\uD83D\uDD12 Own logger created - production mode');\n }\n }\n /**\n * Production logging - use own logger with minimal output\n */\n _setupProductionLogging() {\n // In production, own logger becomes minimal\n if (this._isProductionMode) {\n this.logger = {\n log: () => {}, // No-op in production\n info: () => {}, // No-op in production\n warn: (message, data) => this._secureLog('warn', message, data),\n error: (message, data) => this._secureLog('error', message, data),\n debug: () => {} // No-op in production\n };\n \n this._secureLog('info', '\uD83D\uDD12 Production logging mode activated');\n }\n }\n /**\n * Secure logging with enhanced data protection\n * @param {string} level - Log level (error, warn, info, debug, trace)\n * @param {string} message - Message\n * @param {object} data - Optional payload (will be sanitized)\n */\n _secureLog(level, message, data = null) {\n // Pre-sanitization audit to prevent data leakage\n if (data && !this._auditLogMessage(message, data)) {\n // Log the attempt but block the actual data\n this._originalConsole?.error?.('\uD83D\uDEA8 SECURITY: Logging blocked due to potential data leakage');\n return;\n }\n \n // Check log level\n if (this._logLevels[level] > this._currentLogLevel) {\n return;\n }\n \n // Prevent log spam with better key generation\n const logKey = `${level}:${message.substring(0, 50)}`;\n const currentCount = this._logCounts.get(logKey) || 0;\n \n if (currentCount >= this._maxLogCount) {\n return;\n }\n \n this._logCounts.set(logKey, currentCount + 1);\n \n // Enhanced sanitization with multiple passes\n let sanitizedData = null;\n if (data) {\n // First pass: basic sanitization\n sanitizedData = this._sanitizeLogData(data);\n \n // Second pass: check if sanitized data still contains sensitive content\n if (this._containsSensitiveContent(JSON.stringify(sanitizedData))) {\n this._originalConsole?.error?.('\uD83D\uDEA8 SECURITY: Sanitized data still contains sensitive content - blocking log');\n return;\n }\n }\n \n // Production mode security - only log essential errors\n if (this._isProductionMode) {\n if (level === 'error') {\n // In production, only log error messages without sensitive data\n const safeMessage = this._sanitizeString(message);\n this._originalConsole?.error?.(safeMessage);\n }\n // Block all other log levels in production\n return;\n }\n \n // Development mode: full logging with sanitized data\n const logMethod = this._originalConsole?.[level] || this._originalConsole?.log;\n if (sanitizedData) {\n logMethod(message, sanitizedData);\n } else {\n logMethod(message);\n }\n }\n /**\n * Enhanced sanitization for log data with multiple security layers\n */\n _sanitizeLogData(data) {\n // Pre-check for sensitive content before processing\n if (typeof data === 'string') {\n return this._sanitizeString(data);\n }\n \n if (!data || typeof data !== 'object') {\n return data;\n }\n \n const sanitized = {};\n \n for (const [key, value] of Object.entries(data)) {\n const lowerKey = key.toLowerCase();\n \n // Enhanced blacklist with more comprehensive patterns\n const blacklistPatterns = [\n 'key', 'secret', 'token', 'password', 'credential', 'auth',\n 'fingerprint', 'salt', 'signature', 'private', 'encryption',\n 'mac', 'metadata', 'session', 'jwt', 'bearer', 'hash',\n 'digest', 'nonce', 'iv', 'cipher', 'seed', 'entropy'\n ];\n \n const isBlacklisted = this._absoluteBlacklist.has(key) || \n blacklistPatterns.some(pattern => lowerKey.includes(pattern));\n \n if (isBlacklisted) {\n sanitized[key] = '[SENSITIVE_DATA_BLOCKED]';\n continue;\n }\n \n // Enhanced whitelist with strict validation\n if (this._safeFieldsWhitelist.has(key)) {\n // Even whitelisted fields get sanitized if they contain sensitive data\n if (typeof value === 'string') {\n sanitized[key] = this._sanitizeString(value);\n } else {\n sanitized[key] = value;\n }\n continue;\n }\n \n // Enhanced type handling with security checks\n if (typeof value === 'boolean' || typeof value === 'number') {\n sanitized[key] = value;\n } else if (typeof value === 'string') {\n sanitized[key] = this._sanitizeString(value);\n } else if (value instanceof ArrayBuffer || value instanceof Uint8Array) {\n // Don't reveal actual byte lengths for security\n sanitized[key] = `[${value.constructor.name}( bytes)]`;\n } else if (value && typeof value === 'object') {\n // Recursive sanitization with depth limit and security check\n try {\n sanitized[key] = this._sanitizeLogData(value);\n } catch (error) {\n sanitized[key] = '[RECURSIVE_SANITIZATION_FAILED]';\n }\n } else {\n sanitized[key] = `[${typeof value}]`;\n }\n }\n \n // Final security check on sanitized data\n const sanitizedString = JSON.stringify(sanitized);\n if (this._containsSensitiveContent(sanitizedString)) {\n return { error: 'SANITIZATION_FAILED_SENSITIVE_CONTENT_DETECTED' };\n }\n \n return sanitized;\n }\n /**\n * Enhanced sanitization for strings with comprehensive pattern detection\n */\n _sanitizeString(str) {\n if (typeof str !== 'string' || str.length === 0) {\n return str;\n }\n \n // Comprehensive sensitive pattern detection\n const sensitivePatterns = [\n // Hex patterns (various lengths)\n /[a-f0-9]{16,}/i, // 16+ hex chars (covers short keys)\n /[a-f0-9]{8,}/i, // 8+ hex chars (covers shorter keys)\n \n // Base64 patterns (comprehensive)\n /[A-Za-z0-9+/]{16,}={0,2}/, // Base64 with padding\n /[A-Za-z0-9+/]{12,}/, // Base64 without padding\n /[A-Za-z0-9+/=]{10,}/, // Base64-like patterns\n \n // Base58 patterns (Bitcoin-style)\n /[1-9A-HJ-NP-Za-km-z]{16,}/, // Base58 strings\n \n // Base32 patterns\n /[A-Z2-7]{16,}={0,6}/, // Base32 with padding\n /[A-Z2-7]{12,}/, // Base32 without padding\n \n // Custom encoding patterns\n /[A-Za-z0-9\\-_]{16,}/, // URL-safe base64 variants\n /[A-Za-z0-9\\.\\-_]{16,}/, // JWT-like patterns\n \n // Long alphanumeric strings (potential keys)\n /\\b[A-Za-z0-9]{12,}\\b/, // 12+ alphanumeric chars\n /\\b[A-Za-z0-9]{8,}\\b/, // 8+ alphanumeric chars\n \n // PEM key patterns\n /BEGIN\\s+(PRIVATE|PUBLIC|RSA|DSA|EC)\\s+KEY/i,\n /END\\s+(PRIVATE|PUBLIC|RSA|DSA|EC)\\s+KEY/i,\n \n // JWT patterns\n /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,\n \n // API key patterns\n /(api[_-]?key|token|secret|password|credential)[\\s]*[:=][\\s]*[A-Za-z0-9\\-_]{8,}/i,\n \n // UUID patterns\n /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i,\n \n // Credit cards and SSN (existing patterns)\n /\\b\\d{4}[\\s-]?\\d{4}[\\s-]?\\d{4}[\\s-]?\\d{4}\\b/,\n /\\b\\d{3}-\\d{2}-\\d{4}\\b/,\n \n // Email patterns (more restrictive)\n /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}/,\n \n // Crypto-specific patterns\n /(fingerprint|hash|digest|signature)[\\s]*[:=][\\s]*[A-Za-z0-9\\-_]{8,}/i,\n /(encryption|mac|metadata)[\\s]*key[\\s]*[:=][\\s]*[A-Za-z0-9\\-_]{8,}/i,\n \n // Session and auth patterns\n /(session|auth|jwt|bearer)[\\s]*[:=][\\s]*[A-Za-z0-9\\-_]{8,}/i,\n ];\n \n // Check for sensitive patterns with early return\n for (const pattern of sensitivePatterns) {\n if (pattern.test(str)) {\n // Always fully hide sensitive data\n return '[SENSITIVE_DATA_REDACTED]';\n }\n }\n \n // Check for suspicious entropy (high randomness indicates keys)\n if (this._hasHighEntropy(str)) {\n return '[HIGH_ENTROPY_DATA_REDACTED]';\n }\n \n // Check for suspicious character distributions\n if (this._hasSuspiciousDistribution(str)) {\n return '[SUSPICIOUS_DATA_REDACTED]';\n }\n \n // For regular strings \u2014 limit length more aggressively\n if (str.length > 50) {\n return str.substring(0, 20) + '...[TRUNCATED]';\n }\n \n return str;\n }\n /**\n * Enhanced sensitive content detection\n */\n _containsSensitiveContent(str) {\n if (typeof str !== 'string') return false;\n \n // Use the same comprehensive patterns as _sanitizeString\n const sensitivePatterns = [\n /[a-f0-9]{16,}/i,\n /[A-Za-z0-9+/]{16,}={0,2}/,\n /[1-9A-HJ-NP-Za-km-z]{16,}/,\n /[A-Z2-7]{16,}={0,6}/,\n /\\b[A-Za-z0-9]{12,}\\b/,\n /BEGIN\\s+(PRIVATE|PUBLIC|RSA|DSA|EC)\\s+KEY/i,\n /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,\n /(api[_-]?key|token|secret|password|credential)[\\s]*[:=][\\s]*[A-Za-z0-9\\-_]{8,}/i,\n ];\n \n return sensitivePatterns.some(pattern => pattern.test(str)) ||\n this._hasHighEntropy(str) ||\n this._hasSuspiciousDistribution(str);\n }\n\n /**\n * Check for high entropy strings (likely cryptographic keys)\n */\n _hasHighEntropy(str) {\n if (str.length < 8) return false;\n \n // Calculate character frequency\n const charCount = {};\n for (const char of str) {\n charCount[char] = (charCount[char] || 0) + 1;\n }\n \n // Calculate Shannon entropy\n const length = str.length;\n let entropy = 0;\n \n for (const count of Object.values(charCount)) {\n const probability = count / length;\n entropy -= probability * Math.log2(probability);\n }\n \n // High entropy (>4.5 bits per character) suggests cryptographic data\n return entropy > 4.5;\n }\n\n /**\n * Check for suspicious character distributions\n */\n _hasSuspiciousDistribution(str) {\n if (str.length < 8) return false;\n \n // Check for uniform distribution of hex characters\n const hexChars = str.match(/[a-f0-9]/gi) || [];\n if (hexChars.length >= str.length * 0.8) {\n // If 80%+ are hex chars, likely a key\n return true;\n }\n \n // Check for base64-like distribution\n const base64Chars = str.match(/[A-Za-z0-9+/=]/g) || [];\n if (base64Chars.length >= str.length * 0.9) {\n // If 90%+ are base64 chars, likely encoded data\n return true;\n }\n \n // Check for very low character diversity (suggests random data)\n const uniqueChars = new Set(str).size;\n const diversityRatio = uniqueChars / str.length;\n \n // If diversity is too high (>0.8) for the length, likely random data\n if (diversityRatio > 0.8 && str.length > 16) {\n return true;\n }\n \n return false;\n }\n\n\n // ============================================\n // SECURE LOGGING SYSTEM\n // ============================================\n \n /**\n * Detects production mode\n */\n _detectProductionMode() {\n // Check various production mode indicators\n return (\n // Standard env variables\n (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production') ||\n // No debug flags\n (!this._debugMode) ||\n // Production domains\n (window.location.hostname && !window.location.hostname.includes('localhost') && \n !window.location.hostname.includes('127.0.0.1') && \n !window.location.hostname.includes('.local')) ||\n // Minified code (heuristic check)\n (typeof window.webpackHotUpdate === 'undefined' && !window.location.search.includes('debug'))\n );\n }\n // ============================================\n // FIXED SECURE GLOBAL API\n // ============================================\n \n /**\n * Sets up a secure global API with limited access\n */\n _setupSecureGlobalAPI() {\n // Log that we're starting API setup\n this._secureLog('info', '\uD83D\uDD12 Starting secure global API setup');\n \n // Create simple public API with safety checks\n const secureAPI = {};\n \n // Only bind methods that exist\n if (typeof this.sendMessage === 'function') {\n secureAPI.sendMessage = this.sendMessage.bind(this);\n }\n \n // Create simple getConnectionStatus method\n secureAPI.getConnectionStatus = () => ({\n isConnected: this.isConnected ? this.isConnected() : false,\n isVerified: this.isVerified || false,\n connectionState: this.peerConnection?.connectionState || 'disconnected'\n });\n \n // Create simple getSecurityStatus method\n secureAPI.getSecurityStatus = () => ({\n securityLevel: this.currentSecurityLevel || 'basic',\n stage: 'initialized',\n activeFeaturesCount: Object.values(this.securityFeatures || {}).filter(Boolean).length\n });\n \n if (typeof this.sendFile === 'function') {\n secureAPI.sendFile = this.sendFile.bind(this);\n }\n \n // Create simple getFileTransferStatus method\n secureAPI.getFileTransferStatus = () => ({\n initialized: !!this.fileTransferSystem,\n status: 'ready',\n activeTransfers: 0,\n receivingTransfers: 0\n });\n \n if (typeof this.disconnect === 'function') {\n secureAPI.disconnect = this.disconnect.bind(this);\n }\n \n // Create simple API object with safety checks\n const safeGlobalAPI = {\n ...secureAPI, // Spread only existing methods\n getConfiguration: () => ({\n fakeTraffic: this._config.fakeTraffic.enabled,\n decoyChannels: this._config.decoyChannels.enabled,\n packetPadding: this._config.packetPadding.enabled,\n antiFingerprinting: this._config.antiFingerprinting.enabled\n }),\n emergency: {}\n };\n \n // Only add emergency methods that exist\n if (typeof this._emergencyUnlockAllMutexes === 'function') {\n safeGlobalAPI.emergency.unlockAllMutexes = this._emergencyUnlockAllMutexes.bind(this);\n }\n \n if (typeof this._emergencyRecoverMutexSystem === 'function') {\n safeGlobalAPI.emergency.recoverMutexSystem = this._emergencyRecoverMutexSystem.bind(this);\n }\n \n if (typeof this._emergencyDisableLogging === 'function') {\n safeGlobalAPI.emergency.disableLogging = this._emergencyDisableLogging.bind(this);\n }\n \n if (typeof this._resetLoggingSystem === 'function') {\n safeGlobalAPI.emergency.resetLogging = this._resetLoggingSystem.bind(this);\n }\n \n // Add file transfer system status\n safeGlobalAPI.getFileTransferSystemStatus = () => ({\n initialized: !!this.fileTransferSystem,\n status: 'ready',\n activeTransfers: 0,\n receivingTransfers: 0\n });\n \n // Log available methods for debugging\n this._secureLog('info', '\uD83D\uDD12 API methods available', {\n sendMessage: !!secureAPI.sendMessage,\n getConnectionStatus: !!secureAPI.getConnectionStatus,\n getSecurityStatus: !!secureAPI.getSecurityStatus,\n sendFile: !!secureAPI.sendFile,\n getFileTransferStatus: !!secureAPI.getFileTransferStatus,\n disconnect: !!secureAPI.disconnect,\n getConfiguration: !!safeGlobalAPI.getConfiguration,\n emergencyMethods: Object.keys(safeGlobalAPI.emergency).length\n });\n\n // Apply Object.freeze to prevent modification\n Object.freeze(safeGlobalAPI);\n Object.freeze(safeGlobalAPI.emergency);\n\n // Export API once without monitoring\n this._createProtectedGlobalAPI(safeGlobalAPI);\n \n // Setup minimal protection\n this._setupMinimalGlobalProtection();\n \n // Log that API setup is complete\n this._secureLog('info', '\uD83D\uDD12 Secure global API setup completed successfully');\n }\n /**\n * Create simple global API export\n */\n _createProtectedGlobalAPI(safeGlobalAPI) {\n // Log that we're creating protected global API\n this._secureLog('info', '\uD83D\uDD12 Creating protected global API');\n \n // Simple API export without proxy or monitoring\n if (!window.secureBitChat) {\n this._exportAPI(safeGlobalAPI);\n } else {\n this._secureLog('warn', '\u26A0\uFE0F Global API already exists, skipping setup');\n }\n }\n \n /**\n * Simple API export without monitoring\n */\n _exportAPI(apiObject) {\n // Log that we're exporting API\n this._secureLog('info', '\uD83D\uDD12 Exporting API to window.secureBitChat');\n \n // Check if important methods are available\n if (!this._importantMethods || !this._importantMethods.defineProperty) {\n this._secureLog('error', '\u274C Important methods not available for API export, using fallback');\n // Fallback to direct Object.defineProperty\n Object.defineProperty(window, 'secureBitChat', {\n value: apiObject,\n writable: false,\n configurable: false,\n enumerable: true\n });\n } else {\n // One-time export with immutable properties\n this._importantMethods.defineProperty(window, 'secureBitChat', {\n value: apiObject,\n writable: false,\n configurable: false,\n enumerable: true\n });\n }\n \n this._secureLog('info', '\uD83D\uDD12 Secure API exported to window.secureBitChat');\n }\n \n /**\n * Setup minimal global protection\n */\n _setupMinimalGlobalProtection() {\n // Simple protection without monitoring (methods already stored)\n this._protectGlobalAPI();\n \n this._secureLog('info', '\uD83D\uDD12 Minimal global protection activated');\n }\n \n /**\n * Store important methods in closure for local use\n */\n _storeImportantMethods() {\n // Store references to important methods locally\n this._importantMethods = {\n defineProperty: Object.defineProperty,\n getOwnPropertyDescriptor: Object.getOwnPropertyDescriptor,\n freeze: Object.freeze,\n consoleLog: console.log,\n consoleError: console.error,\n consoleWarn: console.warn\n };\n \n this._secureLog('info', '\uD83D\uDD12 Important methods stored locally', {\n defineProperty: !!this._importantMethods.defineProperty,\n getOwnPropertyDescriptor: !!this._importantMethods.getOwnPropertyDescriptor,\n freeze: !!this._importantMethods.freeze\n });\n }\n\n /**\n * Simple protection without monitoring\n */\n _setupSimpleProtection() {\n this._secureLog('info', '\uD83D\uDD12 Simple protection activated - no monitoring');\n }\n\n /**\n * No global exposure prevention needed\n */\n _preventGlobalExposure() {\n this._secureLog('info', '\uD83D\uDD12 No global exposure prevention - using secure API export only');\n }\n /**\n * API integrity check - only at initialization\n */\n _verifyAPIIntegrity() {\n try {\n if (!window.secureBitChat) {\n this._secureLog('error', '\u274C SECURITY ALERT: Secure API has been removed!');\n return false;\n }\n \n const requiredMethods = ['sendMessage', 'getConnectionStatus', 'disconnect'];\n const missingMethods = requiredMethods.filter(method => \n typeof window.secureBitChat[method] !== 'function'\n );\n \n if (missingMethods.length > 0) {\n this._secureLog('error', '\u274C SECURITY ALERT: API tampering detected, missing methods:', { errorType: missingMethods?.constructor?.name || 'Unknown' });\n return false;\n }\n \n return true;\n } catch (error) {\n this._secureLog('error', '\u274C SECURITY ALERT: API integrity check failed:', { errorType: error?.constructor?.name || 'Unknown' });\n return false;\n }\n }\n // ============================================\n // ADDITIONAL SECURITY METHODS\n // ============================================\n \n /**\n * Simple global exposure check - only at initialization\n */\n _auditGlobalExposure() {\n // Only check once at initialization, no periodic scanning\n this._secureLog('info', '\uD83D\uDD12 Global exposure check completed at initialization');\n return [];\n }\n \n /**\n * No periodic security audits - only at initialization\n */\n _startSecurityAudit() {\n // Only audit once at initialization, no periodic checks\n this._secureLog('info', '\uD83D\uDD12 Security audit completed at initialization - no periodic monitoring');\n }\n \n /**\n * Simple global API protection\n */\n _protectGlobalAPI() {\n if (!window.secureBitChat) {\n this._secureLog('warn', '\u26A0\uFE0F Global API not found during protection setup');\n return;\n }\n\n try {\n // Validate API integrity once\n if (this._validateAPIIntegrityOnce()) {\n this._secureLog('info', '\uD83D\uDD12 Global API protection verified');\n }\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to verify global API protection', { \n errorType: error.constructor.name,\n errorMessage: error.message\n });\n }\n }\n \n /**\n * Validate API integrity once at initialization\n */\n _validateAPIIntegrityOnce() {\n try {\n // Check if API is properly configured\n if (!this._importantMethods || !this._importantMethods.getOwnPropertyDescriptor) {\n // Fallback to direct Object.getOwnPropertyDescriptor\n const descriptor = Object.getOwnPropertyDescriptor(window, 'secureBitChat');\n \n if (!descriptor || descriptor.configurable) {\n throw new Error('secureBitChat must not be reconfigurable!');\n }\n } else {\n const descriptor = this._importantMethods.getOwnPropertyDescriptor(window, 'secureBitChat');\n \n if (!descriptor || descriptor.configurable) {\n throw new Error('secureBitChat must not be reconfigurable!');\n }\n }\n \n this._secureLog('info', '\u2705 API integrity validated');\n return true;\n \n } catch (error) {\n this._secureLog('error', '\u274C API integrity validation failed', {\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n return false;\n }\n }\n \n /**\n * Secure memory wipe for sensitive data\n */\n _secureWipeMemory(data, context = 'unknown') {\n if (!data) return;\n \n try {\n // Different handling for different data types\n if (data instanceof ArrayBuffer) {\n this._secureWipeArrayBuffer(data, context);\n } else if (data instanceof Uint8Array) {\n this._secureWipeUint8Array(data, context);\n } else if (Array.isArray(data)) {\n this._secureWipeArray(data, context);\n } else if (typeof data === 'string') {\n this._secureWipeString(data, context);\n } else if (data instanceof CryptoKey) {\n this._secureWipeCryptoKey(data, context);\n } else if (typeof data === 'object') {\n this._secureWipeObject(data, context);\n }\n \n this._secureMemoryManager.memoryStats.totalCleanups++;\n \n } catch (error) {\n this._secureMemoryManager.memoryStats.failedCleanups++;\n this._secureLog('error', '\u274C Secure memory wipe failed', {\n context: context,\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n }\n }\n \n /**\n * Secure wipe for ArrayBuffer\n */\n _secureWipeArrayBuffer(buffer, context) {\n if (!buffer || buffer.byteLength === 0) return;\n \n try {\n const view = new Uint8Array(buffer);\n \n // Overwrite with random data first\n crypto.getRandomValues(view);\n \n // Overwrite with zeros\n view.fill(0);\n \n // Overwrite with ones\n view.fill(255);\n \n // Final zero overwrite\n view.fill(0);\n \n this._secureLog('debug', '\uD83D\uDD12 ArrayBuffer securely wiped', {\n context: context,\n size: buffer.byteLength\n });\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to wipe ArrayBuffer', {\n context: context,\n errorType: error.constructor.name\n });\n }\n }\n \n /**\n * Secure wipe for Uint8Array\n */\n _secureWipeUint8Array(array, context) {\n if (!array || array.length === 0) return;\n \n try {\n // Overwrite with random data first\n crypto.getRandomValues(array);\n \n // Overwrite with zeros\n array.fill(0);\n \n // Overwrite with ones\n array.fill(255);\n \n // Final zero overwrite\n array.fill(0);\n \n this._secureLog('debug', '\uD83D\uDD12 Uint8Array securely wiped', {\n context: context,\n size: array.length\n });\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to wipe Uint8Array', {\n context: context,\n errorType: error.constructor.name\n });\n }\n }\n \n /**\n * Secure wipe for arrays\n */\n _secureWipeArray(array, context) {\n if (!Array.isArray(array) || array.length === 0) return;\n \n try {\n // Recursively wipe each element\n array.forEach((item, index) => {\n if (item !== null && item !== undefined) {\n this._secureWipeMemory(item, `${context}[${index}]`);\n }\n });\n \n // Fill with nulls\n array.fill(null);\n \n this._secureLog('debug', '\uD83D\uDD12 Array securely wiped', {\n context: context,\n size: array.length\n });\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to wipe array', {\n context: context,\n errorType: error.constructor.name\n });\n }\n }\n \n /**\n * No string wiping - strings are immutable in JS\n */\n _secureWipeString(str, context) {\n // Strings are immutable in JavaScript, no need to wipe\n // Just remove the reference\n this._secureLog('debug', '\uD83D\uDD12 String reference removed (strings are immutable)', {\n context: context,\n length: str ? str.length : 0\n });\n }\n \n /**\n * CryptoKey cleanup - store in WeakMap for proper GC\n */\n _secureWipeCryptoKey(key, context) {\n if (!key || !(key instanceof CryptoKey)) return;\n \n try {\n // Store in WeakMap for proper garbage collection\n if (!this._cryptoKeyStorage) {\n this._cryptoKeyStorage = new WeakMap();\n }\n \n // Store reference for cleanup tracking\n this._cryptoKeyStorage.set(key, {\n context: context,\n timestamp: Date.now(),\n type: key.type\n });\n \n this._secureLog('debug', '\uD83D\uDD12 CryptoKey stored in WeakMap for cleanup', {\n context: context,\n type: key.type\n });\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to store CryptoKey for cleanup', {\n context: context,\n errorType: error.constructor.name\n });\n }\n }\n \n /**\n * Secure wipe for objects\n */\n _secureWipeObject(obj, context) {\n if (!obj || typeof obj !== 'object') return;\n \n try {\n // Recursively wipe all properties\n for (const [key, value] of Object.entries(obj)) {\n if (value !== null && value !== undefined) {\n this._secureWipeMemory(value, `${context}.${key}`);\n }\n // Set property to null\n obj[key] = null;\n }\n \n this._secureLog('debug', '\uD83D\uDD12 Object securely wiped', {\n context: context,\n properties: Object.keys(obj).length\n });\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to wipe object', {\n context: context,\n errorType: error.constructor.name\n });\n }\n }\n \n /**\n * Secure cleanup of cryptographic materials\n */\n _secureCleanupCryptographicMaterials() {\n try {\n // Secure wipe of key pairs\n if (this.ecdhKeyPair) {\n this._secureWipeMemory(this.ecdhKeyPair, 'ecdhKeyPair');\n this.ecdhKeyPair = null;\n }\n \n if (this.ecdsaKeyPair) {\n this._secureWipeMemory(this.ecdsaKeyPair, 'ecdsaKeyPair');\n this.ecdsaKeyPair = null;\n }\n \n // Secure wipe of derived keys\n if (this.encryptionKey) {\n this._secureWipeMemory(this.encryptionKey, 'encryptionKey');\n this.encryptionKey = null;\n }\n \n if (this.macKey) {\n this._secureWipeMemory(this.macKey, 'macKey');\n this.macKey = null;\n }\n \n if (this.metadataKey) {\n this._secureWipeMemory(this.metadataKey, 'metadataKey');\n this.metadataKey = null;\n }\n \n if (this.nestedEncryptionKey) {\n this._secureWipeMemory(this.nestedEncryptionKey, 'nestedEncryptionKey');\n this.nestedEncryptionKey = null;\n }\n \n // Secure wipe of session data\n if (this.sessionSalt) {\n this._secureWipeMemory(this.sessionSalt, 'sessionSalt');\n this.sessionSalt = null;\n }\n \n if (this.sessionId) {\n this._secureWipeMemory(this.sessionId, 'sessionId');\n this.sessionId = null;\n }\n \n if (this.verificationCode) {\n this._secureWipeMemory(this.verificationCode, 'verificationCode');\n this.verificationCode = null;\n }\n \n if (this.peerPublicKey) {\n this._secureWipeMemory(this.peerPublicKey, 'peerPublicKey');\n this.peerPublicKey = null;\n }\n \n if (this.keyFingerprint) {\n this._secureWipeMemory(this.keyFingerprint, 'keyFingerprint');\n this.keyFingerprint = null;\n }\n \n if (this.connectionId) {\n this._secureWipeMemory(this.connectionId, 'connectionId');\n this.connectionId = null;\n }\n \n this._secureLog('info', '\uD83D\uDD12 Cryptographic materials securely cleaned up');\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to cleanup cryptographic materials', {\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n }\n }\n \n /**\n * Force garbage collection if available\n */\n _forceGarbageCollection() {\n try {\n // Try to force garbage collection if available\n if (typeof window.gc === 'function') {\n window.gc();\n this._secureLog('debug', '\uD83D\uDD12 Garbage collection forced');\n } else if (typeof global.gc === 'function') {\n global.gc();\n this._secureLog('debug', '\uD83D\uDD12 Garbage collection forced (global)');\n } else {\n this._secureLog('debug', '\u26A0\uFE0F Garbage collection not available');\n }\n } catch (error) {\n this._secureLog('error', '\u274C Failed to force garbage collection', {\n errorType: error.constructor.name\n });\n }\n }\n \n /**\n * Perform periodic memory cleanup\n */\n _performPeriodicMemoryCleanup() {\n try {\n this._secureMemoryManager.isCleaning = true;\n \n // Clean up any remaining sensitive data\n this._secureCleanupCryptographicMaterials();\n \n // Clean up message queue if it's too large\n if (this.messageQueue && this.messageQueue.length > 100) {\n const excessMessages = this.messageQueue.splice(0, this.messageQueue.length - 50);\n excessMessages.forEach((message, index) => {\n this._secureWipeMemory(message, `periodicCleanup[${index}]`);\n });\n }\n \n // Clean up processed message IDs if too many\n if (this.processedMessageIds && this.processedMessageIds.size > 1000) {\n this.processedMessageIds.clear();\n }\n \n // Force garbage collection\n this._forceGarbageCollection();\n \n this._secureLog('debug', '\uD83D\uDD12 Periodic memory cleanup completed');\n \n } catch (error) {\n this._secureLog('error', '\u274C Error during periodic memory cleanup', {\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n } finally {\n this._secureMemoryManager.isCleaning = false;\n }\n }\n \n /**\n * Create secure error message without information disclosure\n */\n _createSecureErrorMessage(originalError, context = 'unknown') {\n try {\n // Categorize error for appropriate handling\n const category = this._categorizeError(originalError);\n \n // Generate safe error message based on category\n const safeMessage = this._getSafeErrorMessage(category, context);\n \n // Log detailed error internally for debugging\n this._secureLog('error', 'Internal error occurred', {\n category: category,\n context: context,\n errorType: originalError?.constructor?.name || 'Unknown',\n timestamp: Date.now()\n });\n \n // Track error frequency\n this._trackErrorFrequency(category);\n \n return safeMessage;\n \n } catch (error) {\n // Fallback to generic error if error handling fails\n this._secureLog('error', 'Error handling failed', {\n originalError: originalError?.message || 'Unknown',\n handlingError: error.message\n });\n return 'An unexpected error occurred';\n }\n }\n \n /**\n * Categorize error for appropriate handling\n */\n _categorizeError(error) {\n if (!error || !error.message) {\n return this._secureErrorHandler.errorCategories.UNKNOWN;\n }\n \n const message = error.message.toLowerCase();\n \n // Cryptographic errors\n if (message.includes('crypto') || \n message.includes('key') || \n message.includes('encrypt') || \n message.includes('decrypt') ||\n message.includes('sign') ||\n message.includes('verify') ||\n message.includes('ecdh') ||\n message.includes('ecdsa')) {\n return this._secureErrorHandler.errorCategories.CRYPTOGRAPHIC;\n }\n \n // Network errors\n if (message.includes('network') || \n message.includes('connection') || \n message.includes('timeout') ||\n message.includes('webrtc') ||\n message.includes('peer')) {\n return this._secureErrorHandler.errorCategories.NETWORK;\n }\n \n // Validation errors\n if (message.includes('invalid') || \n message.includes('validation') || \n message.includes('format') ||\n message.includes('type')) {\n return this._secureErrorHandler.errorCategories.VALIDATION;\n }\n \n // System errors\n if (message.includes('system') || \n message.includes('internal') || \n message.includes('memory') ||\n message.includes('resource')) {\n return this._secureErrorHandler.errorCategories.SYSTEM;\n }\n \n return this._secureErrorHandler.errorCategories.UNKNOWN;\n }\n \n /**\n * Get safe error message based on category\n */\n _getSafeErrorMessage(category, context) {\n const safeMessages = {\n [this._secureErrorHandler.errorCategories.CRYPTOGRAPHIC]: {\n 'key_generation': 'Security initialization failed',\n 'key_import': 'Security verification failed',\n 'key_derivation': 'Security setup failed',\n 'encryption': 'Message security failed',\n 'decryption': 'Message verification failed',\n 'signature': 'Authentication failed',\n 'default': 'Security operation failed'\n },\n [this._secureErrorHandler.errorCategories.NETWORK]: {\n 'connection': 'Connection failed',\n 'timeout': 'Connection timeout',\n 'peer': 'Peer connection failed',\n 'webrtc': 'Communication failed',\n 'default': 'Network operation failed'\n },\n [this._secureErrorHandler.errorCategories.VALIDATION]: {\n 'format': 'Invalid data format',\n 'type': 'Invalid data type',\n 'structure': 'Invalid data structure',\n 'default': 'Validation failed'\n },\n [this._secureErrorHandler.errorCategories.SYSTEM]: {\n 'memory': 'System resource error',\n 'resource': 'System resource unavailable',\n 'internal': 'Internal system error',\n 'default': 'System operation failed'\n },\n [this._secureErrorHandler.errorCategories.UNKNOWN]: {\n 'default': 'An unexpected error occurred'\n }\n };\n \n const categoryMessages = safeMessages[category] || safeMessages[this._secureErrorHandler.errorCategories.UNKNOWN];\n \n // Determine specific context for more precise message\n let specificContext = 'default';\n if (context.includes('key') || context.includes('crypto')) {\n specificContext = category === this._secureErrorHandler.errorCategories.CRYPTOGRAPHIC ? 'key_generation' : 'default';\n } else if (context.includes('connection') || context.includes('peer')) {\n specificContext = category === this._secureErrorHandler.errorCategories.NETWORK ? 'connection' : 'default';\n } else if (context.includes('validation') || context.includes('format')) {\n specificContext = category === this._secureErrorHandler.errorCategories.VALIDATION ? 'format' : 'default';\n }\n \n return categoryMessages[specificContext] || categoryMessages.default;\n }\n \n /**\n * Track error frequency for security monitoring\n */\n _trackErrorFrequency(category) {\n const now = Date.now();\n \n // Clean old error counts\n if (now - this._secureErrorHandler.lastErrorTime > 60000) { // 1 minute\n this._secureErrorHandler.errorCounts.clear();\n }\n \n // Increment error count\n const currentCount = this._secureErrorHandler.errorCounts.get(category) || 0;\n this._secureErrorHandler.errorCounts.set(category, currentCount + 1);\n this._secureErrorHandler.lastErrorTime = now;\n \n // Check if we're exceeding error threshold\n const totalErrors = Array.from(this._secureErrorHandler.errorCounts.values()).reduce((sum, count) => sum + count, 0);\n \n if (totalErrors > this._secureErrorHandler.errorThreshold) {\n this._secureErrorHandler.isInErrorMode = true;\n this._secureLog('warn', '\u26A0\uFE0F High error frequency detected - entering error mode', {\n totalErrors: totalErrors,\n threshold: this._secureErrorHandler.errorThreshold\n });\n }\n }\n \n /**\n * Throw secure error without information disclosure\n */\n _throwSecureError(originalError, context = 'unknown') {\n const secureMessage = this._createSecureErrorMessage(originalError, context);\n throw new Error(secureMessage);\n }\n \n /**\n * Get error handling statistics\n */\n _getErrorHandlingStats() {\n return {\n errorCounts: Object.fromEntries(this._secureErrorHandler.errorCounts),\n isInErrorMode: this._secureErrorHandler.isInErrorMode,\n lastErrorTime: this._secureErrorHandler.lastErrorTime,\n errorThreshold: this._secureErrorHandler.errorThreshold\n };\n }\n \n /**\n * Reset error handling system\n */\n _resetErrorHandlingSystem() {\n this._secureErrorHandler.errorCounts.clear();\n this._secureErrorHandler.isInErrorMode = false;\n this._secureErrorHandler.lastErrorTime = 0;\n \n this._secureLog('info', '\uD83D\uDD04 Error handling system reset');\n }\n \n /**\n * Get memory management statistics\n */\n _getMemoryManagementStats() {\n return {\n totalCleanups: this._secureMemoryManager.memoryStats.totalCleanups,\n failedCleanups: this._secureMemoryManager.memoryStats.failedCleanups,\n lastCleanup: this._secureMemoryManager.memoryStats.lastCleanup,\n isCleaning: this._secureMemoryManager.isCleaning,\n queueLength: this._secureMemoryManager.cleanupQueue.length\n };\n }\n \n /**\n * Validate API integrity and security\n */\n _validateAPIIntegrity() {\n try {\n // Check if API exists\n if (!window.secureBitChat) {\n this._secureLog('error', '\u274C Global API not found during integrity validation');\n return false;\n }\n \n // Validate required methods exist\n const requiredMethods = ['sendMessage', 'getConnectionStatus', 'getSecurityStatus', 'sendFile', 'disconnect'];\n const missingMethods = requiredMethods.filter(method => \n !window.secureBitChat[method] || typeof window.secureBitChat[method] !== 'function'\n );\n \n if (missingMethods.length > 0) {\n this._secureLog('error', '\u274C Global API integrity validation failed - missing methods', {\n missingMethods: missingMethods\n });\n return false;\n }\n \n // Test method binding integrity\n const testContext = { test: true };\n const boundMethods = requiredMethods.map(method => {\n try {\n return window.secureBitChat[method].bind(testContext);\n } catch (error) {\n return null;\n }\n });\n \n const unboundMethods = boundMethods.filter(method => method === null);\n if (unboundMethods.length > 0) {\n this._secureLog('error', '\u274C Global API integrity validation failed - method binding issues', {\n unboundMethods: unboundMethods.length\n });\n return false;\n }\n \n // Test API immutability\n try {\n const testProp = '_integrity_test_' + Date.now();\n Object.defineProperty(window.secureBitChat, testProp, {\n value: 'test',\n writable: true,\n configurable: true\n });\n \n this._secureLog('error', '\u274C Global API integrity validation failed - API is mutable');\n delete window.secureBitChat[testProp];\n return false;\n \n } catch (immutabilityError) {\n // This is expected - API should be immutable\n this._secureLog('debug', '\u2705 Global API immutability verified');\n }\n \n this._secureLog('info', '\u2705 Global API integrity validation passed');\n return true;\n \n } catch (error) {\n this._secureLog('error', '\u274C Global API integrity validation failed', {\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n return false;\n }\n }\n\n _validateCryptographicSecurity() {\n // Check if basic security features are available\n const criticalFeatures = ['hasRateLimiting'];\n const missingCritical = criticalFeatures.filter(feature => !this.securityFeatures[feature]);\n \n if (missingCritical.length > 0) {\n this._secureLog('error', '\uD83D\uDEA8 CRITICAL: Missing critical rate limiting feature', {\n missing: missingCritical,\n currentFeatures: this.securityFeatures,\n action: 'Rate limiting will be forced enabled'\n });\n\n missingCritical.forEach(feature => {\n this.securityFeatures[feature] = true;\n this._secureLog('warn', `\u26A0\uFE0F Forced enable critical: ${feature} = true`);\n });\n }\n\n // Log current security state\n const availableFeatures = Object.keys(this.securityFeatures).filter(f => this.securityFeatures[f]);\n const encryptionFeatures = ['hasEncryption', 'hasECDH', 'hasECDSA'].filter(f => this.securityFeatures[f]);\n \n this._secureLog('info', '\u2705 Cryptographic security validation passed', {\n criticalFeatures: criticalFeatures.length,\n availableFeatures: availableFeatures.length,\n encryptionFeatures: encryptionFeatures.length,\n totalSecurityFeatures: availableFeatures.length,\n note: 'Encryption features will be enabled after key generation',\n currentState: {\n hasEncryption: this.securityFeatures.hasEncryption,\n hasECDH: this.securityFeatures.hasECDH,\n hasECDSA: this.securityFeatures.hasECDSA,\n hasRateLimiting: this.securityFeatures.hasRateLimiting\n }\n });\n \n return true;\n }\n\n _syncSecurityFeaturesWithTariff() {\n if (!this.sessionManager || !this.sessionManager.isFeatureAllowedForSession) {\n this._secureLog('warn', '\u26A0\uFE0F Session manager not available, using safe default security features');\n\n // Keep existing features, only add new ones\n // Don't override hasEncryption and hasECDH if they're already true\n if (this.securityFeatures.hasEncryption === undefined) {\n this.securityFeatures.hasEncryption = false; // Will be set to true only after key generation\n }\n if (this.securityFeatures.hasECDH === undefined) {\n this.securityFeatures.hasECDH = false; // Will be set to true only after ECDH key generation\n }\n if (this.securityFeatures.hasECDSA === undefined) {\n this.securityFeatures.hasECDSA = false; // Will be set to true only after ECDSA key generation\n }\n if (this.securityFeatures.hasMutualAuth === undefined) {\n this.securityFeatures.hasMutualAuth = false; // Will be set to true only after mutual auth\n }\n if (this.securityFeatures.hasMetadataProtection === undefined) {\n this.securityFeatures.hasMetadataProtection = false;\n }\n if (this.securityFeatures.hasEnhancedReplayProtection === undefined) {\n this.securityFeatures.hasEnhancedReplayProtection = false;\n }\n if (this.securityFeatures.hasNonExtractableKeys === undefined) {\n this.securityFeatures.hasNonExtractableKeys = false;\n }\n if (this.securityFeatures.hasRateLimiting === undefined) {\n this.securityFeatures.hasRateLimiting = true; // Basic rate limiting always available\n }\n if (this.securityFeatures.hasEnhancedValidation === undefined) {\n this.securityFeatures.hasEnhancedValidation = false;\n }\n if (this.securityFeatures.hasPFS === undefined) {\n this.securityFeatures.hasPFS = false;\n }\n if (this.securityFeatures.hasNestedEncryption === undefined) {\n this.securityFeatures.hasNestedEncryption = false;\n }\n if (this.securityFeatures.hasPacketPadding === undefined) {\n this.securityFeatures.hasPacketPadding = false;\n }\n if (this.securityFeatures.hasPacketReordering === undefined) {\n this.securityFeatures.hasPacketReordering = false;\n }\n if (this.securityFeatures.hasAntiFingerprinting === undefined) {\n this.securityFeatures.hasAntiFingerprinting = false;\n }\n if (this.securityFeatures.hasFakeTraffic === undefined) {\n this.securityFeatures.hasFakeTraffic = false;\n }\n if (this.securityFeatures.hasDecoyChannels === undefined) {\n this.securityFeatures.hasDecoyChannels = false;\n }\n if (this.securityFeatures.hasMessageChunking === undefined) {\n this.securityFeatures.hasMessageChunking = false;\n }\n \n this._secureLog('info', '\u2705 Safe default security features applied (features will be enabled as they become available)');\n return;\n }\n\n let sessionType = 'demo'; \n\n if (this.sessionManager.isFeatureAllowedForSession('premium', 'hasFakeTraffic')) {\n sessionType = 'premium';\n } else if (this.sessionManager.isFeatureAllowedForSession('basic', 'hasECDSA')) {\n sessionType = 'basic';\n }\n \n this._secureLog('info', '\uD83D\uDD12 Syncing security features with tariff plan', { sessionType });\n\n const allFeatures = [\n 'hasEncryption', 'hasECDH', 'hasECDSA', 'hasMutualAuth',\n 'hasMetadataProtection', 'hasEnhancedReplayProtection',\n 'hasNonExtractableKeys', 'hasRateLimiting', 'hasEnhancedValidation', 'hasPFS',\n 'hasNestedEncryption', 'hasPacketPadding', 'hasPacketReordering',\n 'hasAntiFingerprinting', 'hasFakeTraffic', 'hasDecoyChannels', 'hasMessageChunking'\n ];\n \n allFeatures.forEach(feature => {\n const isAllowed = this.sessionManager.isFeatureAllowedForSession(sessionType, feature);\n \n if (this.securityFeatures[feature] !== isAllowed) {\n this._secureLog('info', `\uD83D\uDD04 Syncing ${feature}: ${this.securityFeatures[feature]} \u2192 ${isAllowed}`);\n this.securityFeatures[feature] = isAllowed;\n }\n });\n\n if (this.onStatusChange) {\n this.onStatusChange('security_synced', {\n type: 'tariff_sync',\n sessionType: sessionType,\n features: this.securityFeatures,\n message: `Security features synchronized with ${sessionType} tariff plan`\n });\n }\n \n this._secureLog('info', '\u2705 Security features synchronized with tariff plan', {\n sessionType,\n enabledFeatures: Object.keys(this.securityFeatures).filter(f => this.securityFeatures[f]).length,\n totalFeatures: Object.keys(this.securityFeatures).length\n });\n }\n \n /**\n * Emergency shutdown for critical issues\n */\n _emergencyShutdown(reason = 'Security breach') {\n this._secureLog('error', '\u274C EMERGENCY SHUTDOWN: ${reason}');\n \n try {\n // Clear critical data\n this.encryptionKey = null;\n this.macKey = null;\n this.metadataKey = null;\n this.verificationCode = null;\n this.keyFingerprint = null;\n this.connectionId = null;\n \n // Close connections\n if (this.dataChannel) {\n this.dataChannel.close();\n this.dataChannel = null;\n }\n if (this.peerConnection) {\n this.peerConnection.close();\n this.peerConnection = null;\n }\n \n // Clear buffers\n this.messageQueue = [];\n this.processedMessageIds.clear();\n this.packetBuffer.clear();\n \n // Notify UI\n if (this.onStatusChange) {\n this.onStatusChange('security_breach');\n }\n \n this._secureLog('info', '\uD83D\uDD12 Emergency shutdown completed');\n \n } catch (error) {\n this._secureLog('error', '\u274C Error during emergency shutdown:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }\n _finalizeSecureInitialization() {\n this._startKeySecurityMonitoring();\n \n // Verify API integrity\n if (!this._verifyAPIIntegrity()) {\n this._secureLog('error', '\u274C Security initialization failed');\n return;\n }\n\n this._startSecurityMonitoring();\n \n // Start periodic log cleanup\n setInterval(() => {\n this._cleanupLogs();\n }, 300000);\n \n this._secureLog('info', '\u2705 Secure WebRTC Manager initialization completed');\n this._secureLog('info', '\uD83D\uDD12 Global exposure protection: Monitoring only, no automatic removal');\n }\n /**\n * Start security monitoring\n * @deprecated Use unified scheduler instead\n */\n _startSecurityMonitoring() {\n // All security monitoring moved to unified scheduler\n this._secureLog('info', '\uD83D\uDD27 Security monitoring moved to unified scheduler');\n }\n /**\n * Validates connection readiness for sending data\n * @param {boolean} throwError - whether to throw on not ready\n * @returns {boolean} true if connection is ready\n */\n _validateConnection(throwError = true) {\n const isDataChannelReady = this.dataChannel && this.dataChannel.readyState === 'open';\n const isConnectionVerified = this.isVerified;\n const isValid = isDataChannelReady && isConnectionVerified;\n \n if (!isValid && throwError) {\n if (!isDataChannelReady) {\n throw new Error('Data channel not ready');\n }\n if (!isConnectionVerified) {\n throw new Error('Connection not verified');\n }\n }\n \n return isValid;\n }\n\n /**\n * Hard gate for traffic blocking without verification\n * This method enforces that NO traffic (including system messages and file transfers)\n * can pass through without proper cryptographic verification\n */\n _enforceVerificationGate(operation = 'unknown', throwError = true) {\n if (!this.isVerified) {\n const errorMessage = `SECURITY VIOLATION: ${operation} blocked - connection not cryptographically verified`;\n this._secureLog('error', errorMessage, {\n operation: operation,\n isVerified: this.isVerified,\n hasKeys: !!(this.encryptionKey && this.macKey),\n timestamp: Date.now()\n });\n \n if (throwError) {\n throw new Error(errorMessage);\n }\n return false;\n }\n return true;\n }\n\n /**\n * Safe method to set isVerified only after cryptographic verification\n * This is the ONLY method that should set isVerified = true\n */\n _setVerifiedStatus(verified, verificationMethod = 'unknown', verificationData = null) {\n if (verified) {\n // Validate that we have proper cryptographic verification\n if (!this.encryptionKey || !this.macKey) {\n throw new Error('Cannot set verified=true without encryption keys');\n }\n \n if (!verificationMethod || verificationMethod === 'unknown') {\n throw new Error('Cannot set verified=true without specifying verification method');\n }\n \n // Log the verification for audit trail\n this._secureLog('info', 'Connection verified through cryptographic verification', {\n verificationMethod: verificationMethod,\n hasEncryptionKey: !!this.encryptionKey,\n hasMacKey: !!this.macKey,\n keyFingerprint: this.keyFingerprint,\n timestamp: Date.now(),\n verificationData: verificationData ? 'provided' : 'none'\n });\n }\n \n this.isVerified = verified;\n \n if (verified) {\n this.onStatusChange('connected');\n } else {\n this.onStatusChange('disconnected');\n }\n }\n\n /**\n * Create AAD (Additional Authenticated Data) for file messages\n * This binds file messages to the current session and prevents replay attacks\n */\n _createFileMessageAAD(messageType, messageData = null) {\n // Verify that _createMessageAAD method is available\n if (typeof this._createMessageAAD !== 'function') {\n throw new Error('_createMessageAAD method is not available in _createFileMessageAAD. Manager may not be fully initialized.');\n }\n // Use the unified AAD creation method with file message flag\n return this._createMessageAAD(messageType, messageData, true);\n }\n\n /**\n * Validate AAD for file messages\n * This ensures file messages are bound to the correct session\n */\n _validateFileMessageAAD(aadString, expectedMessageType = null) {\n try {\n const aad = JSON.parse(aadString);\n \n // Validate session binding\n if (aad.sessionId !== (this.currentSession?.sessionId || 'unknown')) {\n throw new Error('AAD sessionId mismatch - possible replay attack');\n }\n \n if (aad.keyFingerprint !== (this.keyFingerprint || 'unknown')) {\n throw new Error('AAD keyFingerprint mismatch - possible key substitution attack');\n }\n \n // Validate message type if specified\n if (expectedMessageType && aad.messageType !== expectedMessageType) {\n throw new Error(`AAD messageType mismatch - expected ${expectedMessageType}, got ${aad.messageType}`);\n }\n \n // Validate timestamp (prevent very old messages)\n const now = Date.now();\n const messageAge = now - aad.timestamp;\n if (messageAge > 300000) { // 5 minutes\n throw new Error('AAD timestamp too old - possible replay attack');\n }\n \n return aad;\n } catch (error) {\n this._secureLog('error', 'AAD validation failed', { error: error.message, aadString });\n throw new Error(`AAD validation failed: ${error.message}`);\n }\n }\n\n /**\n * Extract DTLS fingerprint from SDP\n * This is essential for MITM protection\n */\n _extractDTLSFingerprintFromSDP(sdp) {\n try {\n if (!sdp || typeof sdp !== 'string') {\n throw new Error('Invalid SDP provided');\n }\n\n // Look for a=fingerprint lines in SDP with more flexible regex\n const fingerprintRegex = /a=fingerprint:([a-zA-Z0-9-]+)\\s+([A-Fa-f0-9:]+)/g;\n const fingerprints = [];\n let match;\n\n while ((match = fingerprintRegex.exec(sdp)) !== null) {\n fingerprints.push({\n algorithm: match[1].toLowerCase(),\n fingerprint: match[2].toLowerCase().replace(/:/g, '')\n });\n }\n\n if (fingerprints.length === 0) {\n // Try alternative fingerprint format\n const altFingerprintRegex = /fingerprint\\s*=\\s*([a-zA-Z0-9-]+)\\s+([A-Fa-f0-9:]+)/gi;\n while ((match = altFingerprintRegex.exec(sdp)) !== null) {\n fingerprints.push({\n algorithm: match[1].toLowerCase(),\n fingerprint: match[2].toLowerCase().replace(/:/g, '')\n });\n }\n }\n\n if (fingerprints.length === 0) {\n this._secureLog('warn', 'No DTLS fingerprints found in SDP - this may be normal for some WebRTC implementations', {\n sdpLength: sdp.length,\n sdpPreview: sdp.substring(0, 200) + '...'\n });\n throw new Error('No DTLS fingerprints found in SDP');\n }\n\n // Prefer SHA-256 fingerprints\n const sha256Fingerprint = fingerprints.find(fp => fp.algorithm === 'sha-256');\n if (sha256Fingerprint) {\n return sha256Fingerprint.fingerprint;\n }\n\n // Fallback to first available fingerprint\n return fingerprints[0].fingerprint;\n } catch (error) {\n this._secureLog('error', 'Failed to extract DTLS fingerprint from SDP', { \n error: error.message,\n sdpLength: sdp?.length || 0\n });\n throw new Error(`DTLS fingerprint extraction failed: ${error.message}`);\n }\n }\n\n /**\n * Validate DTLS fingerprint against expected value\n * This prevents MITM attacks by ensuring the remote peer has the expected certificate\n */\n _validateDTLSFingerprint(receivedFingerprint, expectedFingerprint, context = 'unknown') {\n try {\n if (!receivedFingerprint || !expectedFingerprint) {\n throw new Error('Missing fingerprint for validation');\n }\n\n // Normalize fingerprints (remove colons, convert to lowercase)\n const normalizedReceived = receivedFingerprint.toLowerCase().replace(/:/g, '');\n const normalizedExpected = expectedFingerprint.toLowerCase().replace(/:/g, '');\n\n if (normalizedReceived !== normalizedExpected) {\n this._secureLog('error', 'DTLS fingerprint mismatch - possible MITM attack', {\n context: context,\n received: normalizedReceived,\n expected: normalizedExpected,\n timestamp: Date.now()\n });\n \n throw new Error(`DTLS fingerprint mismatch - possible MITM attack in ${context}`);\n }\n\n this._secureLog('info', 'DTLS fingerprint validation successful', {\n context: context,\n fingerprint: normalizedReceived,\n timestamp: Date.now()\n });\n\n return true;\n } catch (error) {\n this._secureLog('error', 'DTLS fingerprint validation failed', { \n error: error.message, \n context: context \n });\n throw error;\n }\n }\n\n /**\n * Compute SAS (Short Authentication String) for MITM protection\n * Uses HKDF with DTLS fingerprints to generate a stable 7-digit verification code\n * @param {ArrayBuffer|Uint8Array} keyMaterialRaw - Shared secret or key fingerprint data\n * @param {string} localFP - Local DTLS fingerprint\n * @param {string} remoteFP - Remote DTLS fingerprint\n * @returns {Promise} 7-digit SAS code\n */\n async _computeSAS(keyMaterialRaw, localFP, remoteFP) {\n try {\n console.log('_computeSAS called with parameters:', {\n keyMaterialRaw: keyMaterialRaw ? `${keyMaterialRaw.constructor.name} (${keyMaterialRaw.length || keyMaterialRaw.byteLength} bytes)` : 'null/undefined',\n localFP: localFP ? `${localFP.substring(0, 20)}...` : 'null/undefined',\n remoteFP: remoteFP ? `${remoteFP.substring(0, 20)}...` : 'null/undefined'\n });\n \n if (!keyMaterialRaw || !localFP || !remoteFP) {\n const missing = [];\n if (!keyMaterialRaw) missing.push('keyMaterialRaw');\n if (!localFP) missing.push('localFP');\n if (!remoteFP) missing.push('remoteFP');\n throw new Error(`Missing required parameters for SAS computation: ${missing.join(', ')}`);\n }\n\n const enc = new TextEncoder();\n\n // \u0421\u043E\u043B\u044C \u0441\u0432\u044F\u0437\u044B\u0432\u0430\u0435\u043C \u0441 \u043E\u0431\u043E\u0438\u043C\u0438 DTLS-fingerprints (\u0432 \u043E\u0442\u0441\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u043C \u043F\u043E\u0440\u044F\u0434\u043A\u0435),\n // \u0447\u0442\u043E\u0431\u044B SAS \u00AB\u043F\u0440\u0438\u0432\u044F\u0437\u0430\u043B\u0441\u044F\u00BB \u043A \u0440\u0435\u0430\u043B\u044C\u043D\u043E\u043C\u0443 \u0442\u0440\u0430\u043D\u0441\u043F\u043E\u0440\u0442\u0443 \u0438 \u0435\u0433\u043E \u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u0430\u043C\n const salt = enc.encode(\n 'webrtc-sas|' + [localFP, remoteFP].sort().join('|')\n );\n\n // \u041F\u043E\u0434\u0433\u043E\u0442\u0430\u0432\u043B\u0438\u0432\u0430\u0435\u043C keyMaterialRaw \u0434\u043B\u044F \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\n let keyBuffer;\n if (keyMaterialRaw instanceof ArrayBuffer) {\n keyBuffer = keyMaterialRaw;\n } else if (keyMaterialRaw instanceof Uint8Array) {\n keyBuffer = keyMaterialRaw.buffer;\n } else if (typeof keyMaterialRaw === 'string') {\n // \u0415\u0441\u043B\u0438 \u044D\u0442\u043E \u0441\u0442\u0440\u043E\u043A\u0430 (\u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440, keyFingerprint), \u0434\u0435\u043A\u043E\u0434\u0438\u0440\u0443\u0435\u043C \u0435\u0451\n // \u041F\u0440\u0435\u0434\u043F\u043E\u043B\u0430\u0433\u0430\u0435\u043C, \u0447\u0442\u043E \u044D\u0442\u043E hex \u0441\u0442\u0440\u043E\u043A\u0430\n const hexString = keyMaterialRaw.replace(/:/g, '').replace(/\\s/g, '');\n const bytes = new Uint8Array(hexString.length / 2);\n for (let i = 0; i < hexString.length; i += 2) {\n bytes[i / 2] = parseInt(hexString.substr(i, 2), 16);\n }\n keyBuffer = bytes.buffer;\n } else {\n throw new Error('Invalid keyMaterialRaw type');\n }\n\n // \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u043C HKDF(SHA-256) \u0447\u0442\u043E\u0431\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C \u0441\u0442\u0430\u0431\u0438\u043B\u044C\u043D\u044B\u0435 64 \u0431\u0438\u0442\u0430 \u044D\u043D\u0442\u0440\u043E\u043F\u0438\u0438 \u0434\u043B\u044F \u043A\u043E\u0434\u0430\n const key = await crypto.subtle.importKey(\n 'raw',\n keyBuffer,\n 'HKDF',\n false,\n ['deriveBits']\n );\n\n const info = enc.encode('p2p-sas-v1');\n const bits = await crypto.subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt, info },\n key,\n 64 // 64 \u0431\u0438\u0442\u0430 \u0434\u043E\u0441\u0442\u0430\u0442\u043E\u0447\u043D\u043E \u0434\u043B\u044F 6\u20137 \u0437\u043D\u0430\u043A\u043E\u0432\n );\n\n const dv = new DataView(bits);\n // \u0421\u043C\u0435\u0448\u0438\u0432\u0430\u0435\u043C \u043E\u0431\u0430 32-\u0431\u0438\u0442\u043D\u044B\u0445 \u0441\u043B\u043E\u0432\u0430 \u0438 \u043F\u043E\u043B\u0443\u0447\u0430\u0435\u043C 7-\u0437\u043D\u0430\u0447\u043D\u044B\u0439 \u043A\u043E\u0434\n const n = (dv.getUint32(0) ^ dv.getUint32(4)) >>> 0;\n const sasCode = String(n % 10_000_000).padStart(7, '0'); // 7 \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432\n\n console.log('\uD83C\uDFAF _computeSAS computed code:', sasCode, '(type:', typeof sasCode, ')');\n\n this._secureLog('info', 'SAS code computed successfully', {\n localFP: localFP.substring(0, 16) + '...',\n remoteFP: remoteFP.substring(0, 16) + '...',\n sasLength: sasCode.length,\n timestamp: Date.now()\n });\n\n return sasCode;\n } catch (error) {\n this._secureLog('error', 'SAS computation failed', {\n error: error.message,\n keyMaterialType: typeof keyMaterialRaw,\n hasLocalFP: !!localFP,\n hasRemoteFP: !!remoteFP,\n timestamp: Date.now()\n });\n throw new Error(`SAS computation failed: ${error.message}`);\n }\n }\n\n /**\n * UTILITY: Decode hex keyFingerprint to Uint8Array for SAS computation\n * @param {string} hexString - Hex encoded keyFingerprint (e.g., \"aa:bb:cc:dd\")\n * @returns {Uint8Array} Decoded bytes\n */\n _decodeKeyFingerprint(hexString) {\n try {\n if (!hexString || typeof hexString !== 'string') {\n throw new Error('Invalid hex string provided');\n }\n\n // Use the utility from EnhancedSecureCryptoUtils\n return window.EnhancedSecureCryptoUtils.hexToUint8Array(hexString);\n } catch (error) {\n this._secureLog('error', 'Key fingerprint decoding failed', {\n error: error.message,\n inputType: typeof hexString,\n inputLength: hexString?.length || 0\n });\n throw new Error(`Key fingerprint decoding failed: ${error.message}`);\n }\n }\n\n /**\n * Emergency key wipe on fingerprint mismatch\n * This ensures no sensitive data remains if MITM is detected\n */\n _emergencyWipeOnFingerprintMismatch(reason = 'DTLS fingerprint mismatch') {\n try {\n this._secureLog('error', '\uD83D\uDEA8 EMERGENCY: Initiating security wipe due to fingerprint mismatch', {\n reason: reason,\n timestamp: Date.now()\n });\n\n // Wipe all cryptographic materials\n this._secureWipeKeys();\n this._secureWipeMemory(this.encryptionKey, 'emergency_wipe');\n this._secureWipeMemory(this.macKey, 'emergency_wipe');\n this._secureWipeMemory(this.metadataKey, 'emergency_wipe');\n \n // Wipe ephemeral keys for PFS\n this._wipeEphemeralKeys();\n \n // Hard wipe old keys for PFS\n this._hardWipeOldKeys();\n\n // Reset verification status\n this.isVerified = null;\n this.verificationCode = null;\n this.keyFingerprint = null;\n this.connectionId = null;\n this.expectedDTLSFingerprint = null;\n\n // Disconnect immediately\n this.disconnect();\n\n // Notify UI about security breach\n this.deliverMessageToUI('\uD83D\uDEA8 SECURITY BREACH: Connection terminated due to fingerprint mismatch. Possible MITM attack detected!', 'system');\n\n } catch (error) {\n this._secureLog('error', 'Failed to perform emergency wipe', { error: error.message });\n }\n }\n\n /**\n * Set expected DTLS fingerprint via out-of-band channel\n * This should be called after receiving the fingerprint through a secure channel\n * (e.g., QR code, voice call, in-person exchange, etc.)\n */\n setExpectedDTLSFingerprint(fingerprint, source = 'out_of_band') {\n try {\n if (!fingerprint || typeof fingerprint !== 'string') {\n throw new Error('Invalid fingerprint provided');\n }\n\n // Normalize fingerprint\n const normalizedFingerprint = fingerprint.toLowerCase().replace(/:/g, '');\n\n // Validate fingerprint format (should be hex string)\n if (!/^[a-f0-9]{40,64}$/.test(normalizedFingerprint)) {\n throw new Error('Invalid fingerprint format - must be hex string');\n }\n\n this.expectedDTLSFingerprint = normalizedFingerprint;\n\n this._secureLog('info', 'Expected DTLS fingerprint set via out-of-band channel', {\n source: source,\n fingerprint: normalizedFingerprint,\n timestamp: Date.now()\n });\n\n this.deliverMessageToUI(`\u2705 DTLS fingerprint set via ${source}. MITM protection enabled.`, 'system');\n\n } catch (error) {\n this._secureLog('error', 'Failed to set expected DTLS fingerprint', { error: error.message });\n throw error;\n }\n }\n\n /**\n * Get current DTLS fingerprint for out-of-band verification\n * This should be shared through a secure channel (QR code, voice, etc.)\n */\n getCurrentDTLSFingerprint() {\n try {\n if (!this.expectedDTLSFingerprint) {\n throw new Error('No DTLS fingerprint available - connection not established');\n }\n\n return this.expectedDTLSFingerprint;\n } catch (error) {\n this._secureLog('error', 'Failed to get current DTLS fingerprint', { error: error.message });\n throw error;\n }\n }\n\n /**\n * DEBUGGING: Temporarily disable strict DTLS validation\n * This should only be used for debugging connection issues\n */\n disableStrictDTLSValidation() {\n this.strictDTLSValidation = false;\n this._secureLog('warn', '\u26A0\uFE0F Strict DTLS validation disabled - security reduced', {\n timestamp: Date.now()\n });\n this.deliverMessageToUI('\u26A0\uFE0F DTLS validation disabled for debugging', 'system');\n }\n\n /**\n * SECURITY: Re-enable strict DTLS validation\n */\n enableStrictDTLSValidation() {\n this.strictDTLSValidation = true;\n this._secureLog('info', '\u2705 Strict DTLS validation re-enabled', {\n timestamp: Date.now()\n });\n this.deliverMessageToUI('\u2705 DTLS validation re-enabled', 'system');\n }\n\n /**\n * Generate ephemeral ECDH keys for Perfect Forward Secrecy\n * This ensures each session has unique, non-persistent keys\n */\n async _generateEphemeralECDHKeys() {\n try {\n this._secureLog('info', '\uD83D\uDD11 Generating ephemeral ECDH keys for PFS', {\n sessionStartTime: this.sessionStartTime,\n timestamp: Date.now()\n });\n\n // Generate new ephemeral ECDH key pair\n const ephemeralKeyPair = await window.EnhancedSecureCryptoUtils.generateECDHKeyPair();\n \n if (!ephemeralKeyPair || !this._validateKeyPairConstantTime(ephemeralKeyPair)) {\n throw new Error('Ephemeral ECDH key pair validation failed');\n }\n\n // Store ephemeral keys with session binding\n const sessionId = this.currentSession?.sessionId || `session_${Date.now()}`;\n this.ephemeralKeyPairs.set(sessionId, {\n keyPair: ephemeralKeyPair,\n timestamp: Date.now(),\n sessionId: sessionId\n });\n\n this._secureLog('info', '\u2705 Ephemeral ECDH keys generated for PFS', {\n sessionId: sessionId,\n timestamp: Date.now()\n });\n\n return ephemeralKeyPair;\n } catch (error) {\n this._secureLog('error', '\u274C Failed to generate ephemeral ECDH keys', { error: error.message });\n throw new Error(`Ephemeral key generation failed: ${error.message}`);\n }\n }\n\n /**\n * Hard wipe old keys for real PFS\n * This prevents retrospective decryption attacks\n */\n _hardWipeOldKeys() {\n try {\n this._secureLog('info', '\uD83E\uDDF9 Performing hard wipe of old keys for PFS', {\n oldKeysCount: this.oldKeys.size,\n timestamp: Date.now()\n });\n\n // Hard wipe all old keys\n for (const [version, keySet] of this.oldKeys.entries()) {\n if (keySet.encryptionKey) {\n this._secureWipeMemory(keySet.encryptionKey, 'pfs_key_wipe');\n }\n if (keySet.macKey) {\n this._secureWipeMemory(keySet.macKey, 'pfs_key_wipe');\n }\n if (keySet.metadataKey) {\n this._secureWipeMemory(keySet.metadataKey, 'pfs_key_wipe');\n }\n \n // Clear references\n keySet.encryptionKey = null;\n keySet.macKey = null;\n keySet.metadataKey = null;\n keySet.keyFingerprint = null;\n }\n\n // Clear the oldKeys map completely\n this.oldKeys.clear();\n\n // Force garbage collection if available\n if (typeof window.gc === 'function') {\n window.gc();\n }\n\n this._secureLog('info', '\u2705 Hard wipe of old keys completed for PFS', {\n timestamp: Date.now()\n });\n\n } catch (error) {\n this._secureLog('error', '\u274C Failed to perform hard wipe of old keys', { error: error.message });\n }\n }\n\n /**\n * Wipe ephemeral keys when session ends\n * This ensures session-specific keys are destroyed\n */\n _wipeEphemeralKeys() {\n try {\n this._secureLog('info', '\uD83E\uDDF9 Wiping ephemeral keys for PFS', {\n ephemeralKeysCount: this.ephemeralKeyPairs.size,\n timestamp: Date.now()\n });\n\n // Wipe all ephemeral key pairs\n for (const [sessionId, keyData] of this.ephemeralKeyPairs.entries()) {\n if (keyData.keyPair?.privateKey) {\n this._secureWipeMemory(keyData.keyPair.privateKey, 'ephemeral_key_wipe');\n }\n if (keyData.keyPair?.publicKey) {\n this._secureWipeMemory(keyData.keyPair.publicKey, 'ephemeral_key_wipe');\n }\n \n // Clear references\n keyData.keyPair = null;\n keyData.timestamp = null;\n keyData.sessionId = null;\n }\n\n // Clear the ephemeral keys map\n this.ephemeralKeyPairs.clear();\n\n // Force garbage collection if available\n if (typeof window.gc === 'function') {\n window.gc();\n }\n\n this._secureLog('info', '\u2705 Ephemeral keys wiped for PFS', {\n timestamp: Date.now()\n });\n\n } catch (error) {\n this._secureLog('error', '\u274C Failed to wipe ephemeral keys', { error: error.message });\n }\n }\n\n /**\n * Encrypt file messages with AAD\n * This ensures file messages are properly authenticated and bound to session\n */\n async _encryptFileMessage(messageData, aad) {\n try {\n if (!this.encryptionKey) {\n throw new Error('No encryption key available for file message');\n }\n\n // Convert message to string if it's an object\n const messageString = typeof messageData === 'string' ? messageData : JSON.stringify(messageData);\n \n // Encrypt with AAD using AES-GCM\n const encryptedData = await window.EnhancedSecureCryptoUtils.encryptDataWithAAD(\n messageString, \n this.encryptionKey, \n aad\n );\n \n // Create encrypted message wrapper\n const encryptedMessage = {\n type: 'encrypted_file_message',\n encryptedData: encryptedData,\n aad: aad,\n timestamp: Date.now(),\n keyFingerprint: this.keyFingerprint\n };\n \n return JSON.stringify(encryptedMessage);\n } catch (error) {\n this._secureLog('error', 'Failed to encrypt file message', { error: error.message });\n throw new Error(`File message encryption failed: ${error.message}`);\n }\n }\n\n /**\n * Decrypt file messages with AAD validation\n * This ensures file messages are properly authenticated and bound to session\n */\n async _decryptFileMessage(encryptedMessageString) {\n try {\n const encryptedMessage = JSON.parse(encryptedMessageString);\n \n if (encryptedMessage.type !== 'encrypted_file_message') {\n throw new Error('Invalid encrypted file message type');\n }\n \n // Validate key fingerprint\n if (encryptedMessage.keyFingerprint !== this.keyFingerprint) {\n throw new Error('Key fingerprint mismatch in encrypted file message');\n }\n \n // Validate AAD with sequence number\n const aad = this._validateMessageAAD(encryptedMessage.aad, 'file_message');\n \n if (!this.encryptionKey) {\n throw new Error('No encryption key available for file message decryption');\n }\n \n // Decrypt with AAD validation\n const decryptedData = await window.EnhancedSecureCryptoUtils.decryptDataWithAAD(\n encryptedMessage.encryptedData,\n this.encryptionKey,\n encryptedMessage.aad\n );\n \n return {\n decryptedData: decryptedData,\n aad: aad\n };\n } catch (error) {\n this._secureLog('error', 'Failed to decrypt file message', { error: error.message });\n throw new Error(`File message decryption failed: ${error.message}`);\n }\n }\n\n /**\n * Validates encryption keys readiness\n * @param {boolean} throwError - whether to throw on not ready\n * @returns {boolean} true if keys are ready\n */\n _validateEncryptionKeys(throwError = true) {\n const hasAllKeys = !!(this.encryptionKey && this.macKey && this.metadataKey);\n \n if (!hasAllKeys && throwError) {\n throw new Error('Encryption keys not initialized');\n }\n \n return hasAllKeys;\n }\n\n /**\n * Checks whether a message is a file-transfer message\n * @param {string|object} data - message payload\n * @returns {boolean} true if it's a file message\n */\n _isFileMessage(data) {\n if (typeof data === 'string') {\n try {\n const parsed = JSON.parse(data);\n return parsed.type && parsed.type.startsWith('file_');\n } catch {\n return false;\n }\n }\n \n if (typeof data === 'object' && data.type) {\n return data.type.startsWith('file_');\n }\n \n return false;\n }\n\n /**\n * Checks whether a message is a system message\n * @param {string|object} data - message payload \n * @returns {boolean} true if it's a system message\n */\n _isSystemMessage(data) {\n const systemTypes = [\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.HEARTBEAT,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_RESPONSE,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_CONFIRMED,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_BOTH_CONFIRMED,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.PEER_DISCONNECT,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.SECURITY_UPGRADE,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.KEY_ROTATION_SIGNAL,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.KEY_ROTATION_READY\n ];\n\n if (typeof data === 'string') {\n try {\n const parsed = JSON.parse(data);\n return systemTypes.includes(parsed.type);\n } catch {\n return false;\n }\n }\n \n if (typeof data === 'object' && data.type) {\n return systemTypes.includes(data.type);\n }\n \n return false;\n }\n\n /**\n * Checks whether a message is fake traffic\n * @param {any} data - message payload\n * @returns {boolean} true if it's a fake message\n */\n _isFakeMessage(data) {\n if (typeof data === 'string') {\n try {\n const parsed = JSON.parse(data);\n return parsed.type === EnhancedSecureWebRTCManager.MESSAGE_TYPES.FAKE || \n parsed.isFakeTraffic === true;\n } catch {\n return false;\n }\n }\n \n if (typeof data === 'object' && data !== null) {\n return data.type === EnhancedSecureWebRTCManager.MESSAGE_TYPES.FAKE || \n data.isFakeTraffic === true;\n }\n \n return false;\n }\n\n /**\n * Safely executes an operation with error handling\n * @param {Function} operation - operation to execute\n * @param {string} errorMessage - error message to log\n * @param {any} fallback - default value on error\n * @returns {any} operation result or fallback\n */\n _withErrorHandling(operation, errorMessage, fallback = null) {\n try {\n return operation();\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('error', '\u274C ${errorMessage}:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n return fallback;\n }\n }\n\n /**\n * Safely executes an async operation with error handling\n * @param {Function} operation - async operation\n * @param {string} errorMessage - error message to log\n * @param {any} fallback - default value on error\n * @returns {Promise} operation result or fallback\n */\n async _withAsyncErrorHandling(operation, errorMessage, fallback = null) {\n try {\n return await operation();\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('error', '\u274C ${errorMessage}:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n return fallback;\n }\n }\n\n /**\n * Checks rate limits\n * @returns {boolean} true if allowed to proceed\n */\n _checkRateLimit() {\n return window.EnhancedSecureCryptoUtils.rateLimiter.checkConnectionRate(this.rateLimiterId);\n }\n\n /**\n * Extracts message type from data\n * @param {string|object} data - message data\n * @returns {string|null} message type or null\n */\n _getMessageType(data) {\n if (typeof data === 'string') {\n try {\n const parsed = JSON.parse(data);\n return parsed.type || null;\n } catch {\n return null;\n }\n }\n \n if (typeof data === 'object' && data !== null) {\n return data.type || null;\n }\n \n return null;\n }\n\n /**\n * Resets notification flags for a new connection\n */\n _resetNotificationFlags() {\n this.lastSecurityLevelNotification = null;\n this.verificationNotificationSent = false;\n this.verificationInitiationSent = false;\n this.disconnectNotificationSent = false;\n this.reconnectionFailedNotificationSent = false;\n this.peerDisconnectNotificationSent = false;\n this.connectionClosedNotificationSent = false;\n this.fakeTrafficDisabledNotificationSent = false;\n this.advancedFeaturesDisabledNotificationSent = false;\n this.securityUpgradeNotificationSent = false;\n this.lastSecurityUpgradeStage = null;\n this.securityCalculationNotificationSent = false;\n this.lastSecurityCalculationLevel = null;\n }\n\n /**\n * Checks whether a message was filtered out\n * @param {any} result - processing result\n * @returns {boolean} true if filtered\n */\n _isFilteredMessage(result) {\n const filteredResults = Object.values(EnhancedSecureWebRTCManager.FILTERED_RESULTS);\n return filteredResults.includes(result);\n }\n /**\n * Enhanced log cleanup with security checks\n */\n _cleanupLogs() {\n // More aggressive cleanup to prevent data accumulation\n if (this._logCounts.size > 500) {\n this._logCounts.clear();\n this._secureLog('debug', '\uD83E\uDDF9 Log counts cleared due to size limit');\n }\n \n // Clean up old log entries to prevent memory leaks\n const now = Date.now();\n const maxAge = 300000; // 5 minutes\n \n // Check for suspicious log patterns\n let suspiciousCount = 0;\n for (const [key, count] of this._logCounts.entries()) {\n if (count > 10) {\n suspiciousCount++;\n }\n }\n \n // Emergency cleanup if too many suspicious patterns\n if (suspiciousCount > 20) {\n this._logCounts.clear();\n this._secureLog('warn', '\uD83D\uDEA8 Emergency log cleanup due to suspicious patterns');\n }\n \n // Reset security violation counter if system is stable\n if (this._logSecurityViolations > 0 && suspiciousCount < 5) {\n this._logSecurityViolations = Math.max(0, this._logSecurityViolations - 1);\n }\n \n // Clean up old IVs periodically\n if (!this._lastIVCleanupTime || Date.now() - this._lastIVCleanupTime > 300000) { // Every 5 minutes\n this._cleanupOldIVs();\n this._lastIVCleanupTime = Date.now();\n }\n \n // Periodic secure memory cleanup\n if (!this._secureMemoryManager.memoryStats.lastCleanup || \n Date.now() - this._secureMemoryManager.memoryStats.lastCleanup > 600000) { // Every 10 minutes\n this._performPeriodicMemoryCleanup();\n this._secureMemoryManager.memoryStats.lastCleanup = Date.now();\n }\n }\n /**\n * Secure logging stats with sensitive data protection\n */\n _getLoggingStats() {\n // Only return safe statistics\n const stats = {\n isProductionMode: this._isProductionMode,\n debugMode: this._debugMode,\n currentLogLevel: this._currentLogLevel,\n logCountsSize: this._logCounts.size,\n maxLogCount: this._maxLogCount,\n securityViolations: this._logSecurityViolations || 0,\n maxSecurityViolations: this._maxLogSecurityViolations || 3,\n systemStatus: this._currentLogLevel === -1 ? 'DISABLED' : 'ACTIVE'\n };\n \n // Sanitize any potentially sensitive data\n const sanitizedStats = {};\n for (const [key, value] of Object.entries(stats)) {\n if (typeof value === 'string' && this._containsSensitiveContent(value)) {\n sanitizedStats[key] = '[SENSITIVE_DATA_REDACTED]';\n } else {\n sanitizedStats[key] = value;\n }\n }\n \n return sanitizedStats;\n }\n /**\n * Enhanced emergency logging disable with cleanup\n */\n _emergencyDisableLogging() {\n // Immediately disable all logging levels\n this._currentLogLevel = -1;\n \n // Clear all log data to prevent memory leaks\n this._logCounts.clear();\n \n // Clear any cached sensitive data\n if (this._logSecurityViolations) {\n this._logSecurityViolations = 0;\n }\n \n // Override _secureLog to a secure no-op\n this._secureLog = () => {\n // Only allow emergency console errors\n if (arguments[0] === 'error' && this._originalConsole?.error) {\n this._originalConsole.error('\uD83D\uDEA8 SECURITY: Logging system disabled - potential data exposure prevented');\n }\n };\n \n // Store original functions before overriding\n this._originalSanitizeString = this._sanitizeString;\n this._originalSanitizeLogData = this._sanitizeLogData;\n this._originalAuditLogMessage = this._auditLogMessage;\n this._originalContainsSensitiveContent = this._containsSensitiveContent;\n \n // Override all logging methods to prevent bypass\n this._sanitizeString = () => '[LOGGING_DISABLED]';\n this._sanitizeLogData = () => ({ error: 'LOGGING_DISABLED' });\n this._auditLogMessage = () => false;\n this._containsSensitiveContent = () => true; // Block everything\n \n // Force garbage collection if available\n if (typeof window.gc === 'function') {\n try {\n window.gc();\n } catch (e) {\n // Ignore GC errors\n }\n }\n \n // Notify about the emergency shutdown\n this._originalConsole?.error?.('\uD83D\uDEA8 CRITICAL: Secure logging system disabled due to potential data exposure');\n }\n\n /**\n * Reset logging system after emergency shutdown\n * Use this function to restore normal logging functionality\n */\n _resetLoggingSystem() {\n this._secureLog('info', '\uD83D\uDD27 Resetting logging system after emergency shutdown');\n \n // Restore original sanitize functions\n this._sanitizeString = this._originalSanitizeString || ((str) => str);\n this._sanitizeLogData = this._originalSanitizeLogData || ((data) => data);\n this._auditLogMessage = this._originalAuditLogMessage || (() => true);\n this._containsSensitiveContent = this._originalContainsSensitiveContent || (() => false);\n \n // Reset security violation counters\n this._logSecurityViolations = 0;\n \n this._secureLog('info', '\u2705 Logging system reset successfully');\n }\n /**\n * Enhanced audit function for log message security\n */\n _auditLogMessage(message, data) {\n if (!data || typeof data !== 'object') return true;\n \n // Convert to string and check for sensitive content\n const dataString = JSON.stringify(data);\n \n // Check message itself for sensitive content\n if (this._containsSensitiveContent(message)) {\n this._emergencyDisableLogging();\n this._originalConsole?.error?.('\uD83D\uDEA8 SECURITY BREACH: Sensitive content detected in log message');\n return false;\n }\n \n // Check data string for sensitive content\n if (this._containsSensitiveContent(dataString)) {\n this._emergencyDisableLogging();\n this._originalConsole?.error?.('\uD83D\uDEA8 SECURITY BREACH: Sensitive content detected in log data');\n return false;\n }\n \n // Enhanced dangerous pattern detection\n const dangerousPatterns = [\n 'secret', 'token', 'password', 'credential', 'auth',\n 'fingerprint', 'salt', 'signature', 'private_key', 'api_key', 'private',\n 'encryption', 'mac', 'metadata', 'session', 'jwt', 'bearer',\n 'key', 'hash', 'digest', 'nonce', 'iv', 'cipher'\n ];\n \n const dataStringLower = dataString.toLowerCase();\n \n for (const pattern of dangerousPatterns) {\n if (dataStringLower.includes(pattern) && !this._safeFieldsWhitelist.has(pattern)) {\n this._emergencyDisableLogging();\n this._originalConsole?.error?.(`\uD83D\uDEA8 SECURITY BREACH: Dangerous pattern detected in log: ${pattern}`);\n return false;\n }\n }\n \n // Check for high entropy values in data\n for (const [key, value] of Object.entries(data)) {\n if (typeof value === 'string' && this._hasHighEntropy(value)) {\n this._emergencyDisableLogging();\n this._originalConsole?.error?.(`\uD83D\uDEA8 SECURITY BREACH: High entropy value detected in log field: ${key}`);\n return false;\n }\n }\n \n return true;\n }\n\n initializeFileTransfer() {\n try {\n this._secureLog('info', '\uD83D\uDD27 Initializing Enhanced Secure File Transfer system...');\n\n if (this.fileTransferSystem) {\n this._secureLog('info', '\u2705 File transfer system already initialized');\n return;\n }\n \n // Step-by-step readiness check\n const channelReady = !!(this.dataChannel && this.dataChannel.readyState === 'open');\n if (!channelReady) {\n this._secureLog('warn', '\u26A0\uFE0F Data channel not open, deferring file transfer initialization');\n if (this.dataChannel) {\n const initHandler = () => {\n this._secureLog('info', '\uD83D\uDD04 DataChannel opened, initializing file transfer...');\n this.initializeFileTransfer();\n };\n this.dataChannel.addEventListener('open', initHandler, { once: true });\n }\n return;\n }\n\n if (!this.isVerified) {\n this._secureLog('warn', '\u26A0\uFE0F Connection not verified yet, deferring file transfer initialization');\n setTimeout(() => this.initializeFileTransfer(), 500);\n return;\n }\n \n // FIX: Clean up previous system if present\n if (this.fileTransferSystem) {\n this._secureLog('info', '\uD83E\uDDF9 Cleaning up existing file transfer system');\n this.fileTransferSystem.cleanup();\n this.fileTransferSystem = null;\n }\n \n // Ensure encryption keys are present\n if (!this.encryptionKey || !this.macKey) {\n this._secureLog('warn', '\u26A0\uFE0F Encryption keys not ready, deferring file transfer initialization');\n setTimeout(() => this.initializeFileTransfer(), 1000);\n return;\n }\n \n // IMPORTANT: callback order: (onProgress, onComplete, onError, onFileReceived)\n const safeOnComplete = (summary) => {\n // Sender: finalize transfer, no Blob handling\n try {\n this._secureLog('info', '\uD83C\uDFC1 Sender transfer summary', { summary });\n // Optionally forward as progress/UI event\n if (this.onFileProgress) {\n this.onFileProgress({ type: 'complete', ...summary });\n }\n } catch (e) {\n this._secureLog('warn', '\u26A0\uFE0F onComplete handler failed:', { details: e.message });\n }\n };\n\n this.fileTransferSystem = new EnhancedSecureFileTransfer(\n this,\n this.onFileProgress || null,\n safeOnComplete,\n this.onFileError || null,\n this.onFileReceived || null\n );\n \n this._fileTransferActive = true;\n \n this._secureLog('info', '\u2705 Enhanced Secure File Transfer system initialized successfully');\n \n // Verify the system is ready\n const status = this.fileTransferSystem.getSystemStatus();\n this._secureLog('info', '\uD83D\uDD0D File transfer system status after init', { status });\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to initialize file transfer system', { errorType: error.constructor.name });\n this.fileTransferSystem = null;\n this._fileTransferActive = false;\n }\n }\n\n // ============================================\n // ENHANCED SECURITY INITIALIZATION\n // ============================================\n\n async initializeEnhancedSecurity() {\n try {\n // Generate nested encryption key\n await this.generateNestedEncryptionKey();\n \n // Initialize decoy channels\n if (this.decoyChannelConfig.enabled) {\n this.initializeDecoyChannels();\n }\n \n // Start fake traffic generation\n if (this.fakeTrafficConfig.enabled) {\n this.startFakeTrafficGeneration();\n }\n\n } catch (error) {\n this._secureLog('error', '\u274C Failed to initialize enhanced security', { errorType: error.constructor.name });\n }\n }\n \n // Generate fingerprint mask for anti-fingerprinting with enhanced randomization\n generateFingerprintMask() {\n // Enhanced randomization to prevent side-channel attacks\n const cryptoRandom = crypto.getRandomValues(new Uint8Array(128));\n \n const mask = {\n timingOffset: cryptoRandom[0] % 1000 + cryptoRandom[1] % 500, // 0-1500ms\n sizeVariation: (cryptoRandom[2] % 50 + 75) / 100, // 0.75 to 1.25\n noisePattern: Array.from(crypto.getRandomValues(new Uint8Array(64))), // Increased size\n headerVariations: [\n 'X-Client-Version', 'X-Session-ID', 'X-Request-ID', 'X-Timestamp', 'X-Signature',\n 'X-Secure', 'X-Encrypted', 'X-Protected', 'X-Safe', 'X-Anonymous', 'X-Private'\n ],\n noiseIntensity: cryptoRandom[3] % 100 + 50, // 50-150%\n sizeMultiplier: (cryptoRandom[4] % 50 + 75) / 100, // 0.75-1.25\n timingVariation: cryptoRandom[5] % 1000 + 100 // 100-1100ms\n };\n return mask;\n }\n\n // Security configuration for session type\n configureSecurityForSession(sessionType, securityLevel) {\n this._secureLog('info', `\uD83D\uDD27 Configuring security for ${sessionType} session (${securityLevel} level)`);\n \n this.currentSessionType = sessionType;\n this.currentSecurityLevel = securityLevel;\n \n if (window.sessionManager && window.sessionManager.isFeatureAllowedForSession) {\n this.sessionConstraints = {};\n \n Object.keys(this.securityFeatures).forEach(feature => {\n this.sessionConstraints[feature] = window.sessionManager.isFeatureAllowedForSession(sessionType, feature);\n });\n \n this.applySessionConstraints();\n \n this._secureLog('info', `\u2705 Security configured for ${sessionType}`, { constraints: this.sessionConstraints });\n\n if (!this._validateCryptographicSecurity()) {\n this._secureLog('error', '\uD83D\uDEA8 CRITICAL: Cryptographic security validation failed after session configuration');\n\n if (this.onStatusChange) {\n this.onStatusChange('security_breach', {\n type: 'crypto_security_failure',\n sessionType: sessionType,\n message: 'Cryptographic security validation failed after session configuration'\n });\n }\n }\n \n this.notifySecurityLevel();\n \n setTimeout(() => {\n this.calculateAndReportSecurityLevel();\n }, EnhancedSecureWebRTCManager.TIMEOUTS.SECURITY_CALC_DELAY);\n \n } else {\n this._secureLog('warn', '\u26A0\uFE0F Session manager not available, using default security');\n }\n }\n\n // Applying session restrictions\n applySessionConstraints() {\n if (!this.sessionConstraints) return;\n\n // Applying restrictions to security features\n Object.keys(this.sessionConstraints).forEach(feature => {\n const allowed = this.sessionConstraints[feature];\n \n if (!allowed && this.securityFeatures[feature]) {\n this._secureLog('info', `\uD83D\uDD12 Disabling ${feature} for ${this.currentSessionType} session`);\n this.securityFeatures[feature] = false;\n \n // Disabling linked configurations\n switch (feature) {\n case 'hasFakeTraffic':\n this.fakeTrafficConfig.enabled = false;\n this.stopFakeTrafficGeneration();\n break;\n case 'hasDecoyChannels':\n this.decoyChannelConfig.enabled = false;\n this.cleanupDecoyChannels();\n break;\n case 'hasPacketReordering':\n this.reorderingConfig.enabled = false;\n this.packetBuffer.clear();\n break;\n case 'hasAntiFingerprinting':\n this.antiFingerprintingConfig.enabled = false;\n break;\n case 'hasMessageChunking':\n this.chunkingConfig.enabled = false;\n break;\n }\n } else if (allowed && !this.securityFeatures[feature]) {\n this._secureLog('info', `\uD83D\uDD13 Enabling ${feature} for ${this.currentSessionType} session`);\n this.securityFeatures[feature] = true;\n \n // Enable linked configurations\n switch (feature) {\n case 'hasFakeTraffic':\n this.fakeTrafficConfig.enabled = true;\n if (this.isConnected()) {\n this.startFakeTrafficGeneration();\n }\n break;\n case 'hasDecoyChannels':\n this.decoyChannelConfig.enabled = true;\n if (this.isConnected()) {\n this.initializeDecoyChannels();\n }\n break;\n case 'hasPacketReordering':\n this.reorderingConfig.enabled = true;\n break;\n case 'hasAntiFingerprinting':\n this.antiFingerprintingConfig.enabled = true;\n break;\n case 'hasMessageChunking':\n this.chunkingConfig.enabled = true;\n break;\n }\n }\n });\n }\n deliverMessageToUI(message, type = 'received') {\n try {\n // Add debug logs\n this._secureLog('debug', '\uD83D\uDCE4 deliverMessageToUI called', {\n message: message,\n type: type,\n messageType: typeof message,\n hasOnMessage: !!this.onMessage\n });\n \n // Filter out file-transfer and system messages\n if (typeof message === 'object' && message.type) {\n const blockedTypes = [\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_TRANSFER_START,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_TRANSFER_RESPONSE,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_CHUNK,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.CHUNK_CONFIRMATION,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_TRANSFER_COMPLETE,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_TRANSFER_ERROR,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.HEARTBEAT,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_RESPONSE,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_CONFIRMED,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_BOTH_CONFIRMED,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.PEER_DISCONNECT,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.KEY_ROTATION_SIGNAL,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.KEY_ROTATION_READY,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.SECURITY_UPGRADE\n ];\n if (blockedTypes.includes(message.type)) {\n if (this._debugMode) {\n this._secureLog('warn', `\uD83D\uDED1 Blocked system/file message from UI: ${message.type}`);\n }\n return; // do not show in chat\n }\n }\n\n // Additional check for string messages containing JSON\n if (typeof message === 'string' && message.trim().startsWith('{')) {\n try {\n const parsedMessage = JSON.parse(message);\n if (parsedMessage.type) {\n const blockedTypes = [\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_TRANSFER_START,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_TRANSFER_RESPONSE,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_CHUNK,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.CHUNK_CONFIRMATION,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_TRANSFER_COMPLETE,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_TRANSFER_ERROR,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.HEARTBEAT,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_RESPONSE,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_CONFIRMED,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_BOTH_CONFIRMED,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.PEER_DISCONNECT,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.KEY_ROTATION_SIGNAL,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.KEY_ROTATION_READY,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.SECURITY_UPGRADE\n ];\n if (blockedTypes.includes(parsedMessage.type)) {\n if (this._debugMode) {\n this._secureLog('warn', `\uD83D\uDED1 Blocked system/file message from UI (string): ${parsedMessage.type}`);\n }\n return; // do not show in chat\n }\n }\n } catch (parseError) {\n // Not JSON \u2014 fine for plain text messages\n }\n }\n\n if (this.onMessage) {\n this._secureLog('debug', '\uD83D\uDCE4 Calling this.onMessage callback', { message, type });\n this.onMessage(message, type);\n } else {\n this._secureLog('warn', '\u26A0\uFE0F this.onMessage callback is null or undefined');\n }\n } catch (err) {\n this._secureLog('error', '\u274C Failed to deliver message to UI:', { errorType: err?.constructor?.name || 'Unknown' });\n }\n }\n\n\n // Security Level Notification\n notifySecurityLevel() {\n // Avoid duplicate notifications for the same security level\n if (this.lastSecurityLevelNotification === this.currentSecurityLevel) {\n return; // prevent duplication\n }\n \n this.lastSecurityLevelNotification = this.currentSecurityLevel;\n \n const levelMessages = {\n 'basic': '\uD83D\uDD12 Basic Security Active - Demo session with essential protection',\n 'enhanced': '\uD83D\uDD10 Enhanced Security Active - Paid session with advanced protection',\n 'maximum': '\uD83D\uDEE1\uFE0F Maximum Security Active - Premium session with complete protection'\n };\n\n const message = levelMessages[this.currentSecurityLevel] || levelMessages['basic'];\n \n if (this.onMessage) {\n this.deliverMessageToUI(message, 'system');\n }\n\n // Showing details of functions for paid sessions\n if (this.currentSecurityLevel !== 'basic' && this.onMessage) {\n const activeFeatures = Object.entries(this.securityFeatures)\n .filter(([key, value]) => value === true)\n .map(([key]) => key.replace('has', '').replace(/([A-Z])/g, ' $1').trim().toLowerCase())\n .slice(0, 5); \n\n this.deliverMessageToUI(`\uD83D\uDD27 Active: ${activeFeatures.join(', ')}...`, 'system');\n }\n }\n\n // Cleaning decoy channels\n cleanupDecoyChannels() {\n // Stopping decoy traffic\n for (const [channelName, timer] of this.decoyTimers.entries()) {\n clearTimeout(timer);\n }\n this.decoyTimers.clear();\n \n // Closing decoy channels\n for (const [channelName, channel] of this.decoyChannels.entries()) {\n if (channel.readyState === 'open') {\n channel.close();\n }\n }\n this.decoyChannels.clear();\n \n this._secureLog('info', '\uD83E\uDDF9 Decoy channels cleaned up');\n }\n\n // ============================================\n // 1. NESTED ENCRYPTION LAYER\n // ============================================\n\n async generateNestedEncryptionKey() {\n try {\n // Generate additional encryption key for nested encryption\n this.nestedEncryptionKey = await crypto.subtle.generateKey(\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt', 'decrypt']\n );\n \n // Generate random IV for nested encryption\n // No need for base IV or counter - each encryption gets fresh random IV\n // This ensures maximum entropy and prevents IV reuse attacks\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to generate nested encryption key:', { errorType: error?.constructor?.name || 'Unknown' });\n throw error;\n }\n }\n\n async applyNestedEncryption(data) {\n if (!this.nestedEncryptionKey || !this.securityFeatures.hasNestedEncryption) {\n return data;\n }\n\n try {\n // Generate cryptographically secure IV with reuse prevention\n const uniqueIV = this._generateSecureIV(\n EnhancedSecureWebRTCManager.SIZES.NESTED_ENCRYPTION_IV_SIZE, \n 'nestedEncryption'\n );\n \n // Encrypt data with nested layer\n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: uniqueIV },\n this.nestedEncryptionKey,\n data\n );\n \n // Combine IV and encrypted data\n const result = new Uint8Array(EnhancedSecureWebRTCManager.SIZES.NESTED_ENCRYPTION_IV_SIZE + encrypted.byteLength);\n result.set(uniqueIV, 0);\n result.set(new Uint8Array(encrypted), EnhancedSecureWebRTCManager.SIZES.NESTED_ENCRYPTION_IV_SIZE);\n \n this._secureLog('debug', '\u2705 Nested encryption applied with secure IV', {\n ivSize: uniqueIV.length,\n dataSize: data.byteLength,\n encryptedSize: encrypted.byteLength\n });\n \n return result.buffer;\n } catch (error) {\n this._secureLog('error', '\u274C Nested encryption failed:', { \n errorType: error?.constructor?.name || 'Unknown',\n errorMessage: error?.message || 'Unknown error'\n });\n \n // If IV generation failed due to emergency mode, disable nested encryption\n if (error.message.includes('emergency mode')) {\n this.securityFeatures.hasNestedEncryption = false;\n this._secureLog('warn', '\u26A0\uFE0F Nested encryption disabled due to IV emergency mode');\n }\n \n return data; // Fallback to original data\n }\n }\n\n async removeNestedEncryption(data) {\n if (!this.nestedEncryptionKey || !this.securityFeatures.hasNestedEncryption) {\n return data;\n }\n\n // Check that the data is actually encrypted with proper IV size\n if (!(data instanceof ArrayBuffer) || data.byteLength < EnhancedSecureWebRTCManager.SIZES.NESTED_ENCRYPTION_IV_SIZE + 16) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCDD Data not encrypted or too short for nested decryption (need IV + minimum encrypted data)');\n }\n return data;\n }\n\n try {\n const dataArray = new Uint8Array(data);\n const iv = dataArray.slice(0, EnhancedSecureWebRTCManager.SIZES.NESTED_ENCRYPTION_IV_SIZE);\n const encryptedData = dataArray.slice(EnhancedSecureWebRTCManager.SIZES.NESTED_ENCRYPTION_IV_SIZE);\n \n // Check that there is data to decrypt\n if (encryptedData.length === 0) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCDD No encrypted data found');\n }\n return data;\n }\n \n // Decrypt nested layer\n const decrypted = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: iv },\n this.nestedEncryptionKey,\n encryptedData\n );\n \n return decrypted;\n } catch (error) {\n // FIX: Better error handling\n if (error.name === 'OperationError') {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCDD Data not encrypted with nested encryption, skipping...');\n }\n } else {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Nested decryption failed:', { details: error.message });\n }\n }\n return data; // Fallback to original data\n }\n }\n\n // ============================================\n // 2. PACKET PADDING\n // ============================================\n\n applyPacketPadding(data) {\n if (!this.securityFeatures.hasPacketPadding) {\n return data;\n }\n\n try {\n const originalSize = data.byteLength;\n let paddingSize;\n \n if (this.paddingConfig.useRandomPadding) {\n // Generate random padding size\n paddingSize = Math.floor(Math.random() * \n (this.paddingConfig.maxPadding - this.paddingConfig.minPadding + 1)) + \n this.paddingConfig.minPadding;\n } else {\n // Use fixed padding size\n paddingSize = this.paddingConfig.minPadding;\n }\n \n // Generate random padding data\n const padding = crypto.getRandomValues(new Uint8Array(paddingSize));\n \n // Create padded message\n const paddedData = new Uint8Array(originalSize + paddingSize + 4);\n \n // Add original size (4 bytes)\n const sizeView = new DataView(paddedData.buffer, 0, 4);\n sizeView.setUint32(0, originalSize, false);\n \n // Add original data\n paddedData.set(new Uint8Array(data), 4);\n \n // Add padding\n paddedData.set(padding, 4 + originalSize);\n \n return paddedData.buffer;\n } catch (error) {\n this._secureLog('error', '\u274C Packet padding failed:', { errorType: error?.constructor?.name || 'Unknown' });\n return data; // Fallback to original data\n }\n }\n\n removePacketPadding(data) {\n if (!this.securityFeatures.hasPacketPadding) {\n return data;\n }\n\n try {\n const dataArray = new Uint8Array(data);\n \n // Check for minimum data length (4 bytes for size + minimum 1 byte of data)\n if (dataArray.length < 5) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Data too short for packet padding removal, skipping');\n }\n return data;\n }\n \n // Extract original size (first 4 bytes)\n const sizeView = new DataView(dataArray.buffer, 0, 4);\n const originalSize = sizeView.getUint32(0, false);\n \n // Checking the reasonableness of the size\n if (originalSize <= 0 || originalSize > dataArray.length - 4) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Invalid packet padding size, skipping removal');\n }\n return data;\n }\n \n // Extract original data\n const originalData = dataArray.slice(4, 4 + originalSize);\n \n return originalData.buffer;\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('error', '\u274C Packet padding removal failed:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n return data; // Fallback to original data\n }\n }\n\n // ============================================\n // 3. FAKE TRAFFIC GENERATION\n // ============================================\n\n startFakeTrafficGeneration() {\n if (!this.fakeTrafficConfig.enabled || !this.isConnected()) {\n return;\n }\n\n // Prevent multiple fake traffic generators\n if (this.fakeTrafficTimer) {\n this._secureLog('warn', '\u26A0\uFE0F Fake traffic generation already running');\n return;\n }\n\n const sendFakeMessage = async () => {\n if (!this.isConnected()) {\n this.stopFakeTrafficGeneration();\n return;\n }\n\n try {\n const fakeMessage = this.generateFakeMessage();\n await this.sendFakeMessage(fakeMessage);\n \n // FIX: Increase intervals to reduce load\n const nextInterval = this.fakeTrafficConfig.randomDecoyIntervals ? \n Math.random() * (this.fakeTrafficConfig.maxInterval - this.fakeTrafficConfig.minInterval) + \n this.fakeTrafficConfig.minInterval :\n this.fakeTrafficConfig.minInterval;\n \n // Minimum interval 15 seconds for stability\n const safeInterval = Math.max(nextInterval, EnhancedSecureWebRTCManager.TIMEOUTS.FAKE_TRAFFIC_MIN_INTERVAL);\n \n this.fakeTrafficTimer = setTimeout(sendFakeMessage, safeInterval);\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('error', '\u274C Fake traffic generation failed:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n this.stopFakeTrafficGeneration();\n }\n };\n\n // Start fake traffic generation with longer initial delay\n const initialDelay = Math.random() * this.fakeTrafficConfig.maxInterval + EnhancedSecureWebRTCManager.TIMEOUTS.DECOY_INITIAL_DELAY; // Add 5 seconds minimum\n this.fakeTrafficTimer = setTimeout(sendFakeMessage, initialDelay);\n }\n\n stopFakeTrafficGeneration() {\n if (this.fakeTrafficTimer) {\n clearTimeout(this.fakeTrafficTimer);\n this.fakeTrafficTimer = null;\n }\n }\n\n generateFakeMessage() {\n const pattern = this.fakeTrafficConfig.patterns[\n Math.floor(Math.random() * this.fakeTrafficConfig.patterns.length)\n ];\n \n const size = Math.floor(Math.random() * \n (this.fakeTrafficConfig.maxSize - this.fakeTrafficConfig.minSize + 1)) + \n this.fakeTrafficConfig.minSize;\n \n const fakeData = crypto.getRandomValues(new Uint8Array(size));\n \n return {\n type: EnhancedSecureWebRTCManager.MESSAGE_TYPES.FAKE, \n pattern: pattern,\n data: Array.from(fakeData).map(b => b.toString(16).padStart(2, '0')).join(''),\n timestamp: Date.now(),\n size: size,\n isFakeTraffic: true, \n source: 'fake_traffic_generator',\n fakeId: crypto.getRandomValues(new Uint32Array(1))[0].toString(36) \n };\n }\n\n // ============================================\n // EMERGENCY SHUT-OFF OF ADVANCED FUNCTIONS\n // ============================================\n\n emergencyDisableAdvancedFeatures() {\n this._secureLog('error', '\uD83D\uDEA8 Emergency disabling advanced security features due to errors');\n \n // Disable problematic functions\n this.securityFeatures.hasNestedEncryption = false;\n this.securityFeatures.hasPacketReordering = false;\n this.securityFeatures.hasAntiFingerprinting = false;\n \n // Disable configurations\n this.reorderingConfig.enabled = false;\n this.antiFingerprintingConfig.enabled = false;\n \n // Clear the buffers\n this.packetBuffer.clear();\n \n // Stopping fake traffic\n this.emergencyDisableFakeTraffic();\n \n this._secureLog('info', '\u2705 Advanced features disabled, keeping basic encryption');\n \n // Check that advanced-features-disabled notification wasn't already sent\n if (!this.advancedFeaturesDisabledNotificationSent) {\n this.advancedFeaturesDisabledNotificationSent = true;\n if (this.onMessage) {\n this.deliverMessageToUI('\uD83D\uDEA8 Advanced security features temporarily disabled due to compatibility issues', 'system');\n }\n }\n }\n\n async sendFakeMessage(fakeMessage) {\n if (!this._validateConnection(false)) {\n return;\n }\n\n try {\n this._secureLog('debug', '\uD83C\uDFAD Sending fake message', {\n hasPattern: !!fakeMessage.pattern,\n sizeRange: fakeMessage.size > 100 ? 'large' : 'small'\n });\n \n const fakeData = JSON.stringify({\n ...fakeMessage,\n type: EnhancedSecureWebRTCManager.MESSAGE_TYPES.FAKE, \n isFakeTraffic: true, \n timestamp: Date.now()\n });\n \n const fakeBuffer = new TextEncoder().encode(fakeData);\n const encryptedFake = await this.applySecurityLayers(fakeBuffer, true);\n this.dataChannel.send(encryptedFake);\n \n this._secureLog('debug', '\uD83C\uDFAD Fake message sent successfully', {\n pattern: fakeMessage.pattern\n });\n } catch (error) {\n this._secureLog('error', '\u274C Failed to send fake message', {\n error: error.message\n });\n }\n }\n\ncheckFakeTrafficStatus() {\n const status = {\n fakeTrafficEnabled: this.securityFeatures.hasFakeTraffic,\n fakeTrafficConfigEnabled: this.fakeTrafficConfig.enabled,\n timerActive: !!this.fakeTrafficTimer,\n patterns: this.fakeTrafficConfig.patterns,\n intervals: {\n min: this.fakeTrafficConfig.minInterval,\n max: this.fakeTrafficConfig.maxInterval\n }\n };\n \n if (this._debugMode) {\n this._secureLog('info', '\uD83C\uDFAD Fake Traffic Status', { status });\n }\n return status;\n }\nemergencyDisableFakeTraffic() {\n if (this._debugMode) {\n this._secureLog('error', '\uD83D\uDEA8 Emergency disabling fake traffic');\n }\n \n this.securityFeatures.hasFakeTraffic = false;\n this.fakeTrafficConfig.enabled = false;\n this.stopFakeTrafficGeneration();\n \n if (this._debugMode) {\n this._secureLog('info', '\u2705 Fake traffic disabled');\n }\n \n // Check that fake-traffic-disabled notification wasn't already sent\n if (!this.fakeTrafficDisabledNotificationSent) {\n this.fakeTrafficDisabledNotificationSent = true;\n if (this.onMessage) {\n this.deliverMessageToUI('\uD83D\uDEA8 Fake traffic emergency disabled', 'system');\n }\n }\n }\n async _applySecurityLayersWithoutMutex(data, isFakeMessage = false) {\n try {\n let processedData = data;\n \n if (isFakeMessage) {\n if (this.encryptionKey && typeof processedData === 'string') {\n processedData = await window.EnhancedSecureCryptoUtils.encryptData(processedData, this.encryptionKey);\n }\n return processedData;\n }\n \n // Nested Encryption (if enabled)\n if (this.securityFeatures.hasNestedEncryption && this.nestedEncryptionKey && processedData instanceof ArrayBuffer) {\n processedData = await this.applyNestedEncryption(processedData);\n }\n \n // Packet Reordering (if enabled)\n if (this.securityFeatures.hasPacketReordering && this.reorderingConfig?.enabled && processedData instanceof ArrayBuffer) {\n processedData = this.applyPacketReordering(processedData);\n }\n \n // Packet Padding (if enabled)\n if (this.securityFeatures.hasPacketPadding && processedData instanceof ArrayBuffer) {\n processedData = this.applyPacketPadding(processedData);\n }\n \n // Anti-Fingerprinting (if enabled)\n if (this.securityFeatures.hasAntiFingerprinting && processedData instanceof ArrayBuffer) {\n processedData = this.applyAntiFingerprinting(processedData);\n }\n \n // Final encryption (if keys are present)\n if (this.encryptionKey && typeof processedData === 'string') {\n processedData = await window.EnhancedSecureCryptoUtils.encryptData(processedData, this.encryptionKey);\n }\n \n return processedData;\n \n } catch (error) {\n this._secureLog('error', '\u274C Error in applySecurityLayersWithoutMutex:', { errorType: error?.constructor?.name || 'Unknown' });\n return data; // Return original data on error\n }\n}\n // ============================================\n // 4. MESSAGE CHUNKING\n // ============================================\n\n async processChunkedMessage(chunkData) {\n try {\n if (!this.chunkingConfig.addChunkHeaders) {\n // No headers, treat as regular message\n return this.processMessage(chunkData);\n }\n\n const chunkArray = new Uint8Array(chunkData);\n if (chunkArray.length < 16) {\n // Too small to be a chunk with header\n return this.processMessage(chunkData);\n }\n\n // Extract chunk header\n const headerView = new DataView(chunkArray.buffer, 0, 16);\n const messageId = headerView.getUint32(0, false);\n const chunkIndex = headerView.getUint32(4, false);\n const totalChunks = headerView.getUint32(8, false);\n const chunkSize = headerView.getUint32(12, false);\n\n // Extract chunk data\n const chunk = chunkArray.slice(16, 16 + chunkSize);\n\n // Store chunk in buffer\n if (!this.chunkQueue[messageId]) {\n this.chunkQueue[messageId] = {\n chunks: new Array(totalChunks),\n received: 0,\n timestamp: Date.now()\n };\n }\n\n const messageBuffer = this.chunkQueue[messageId];\n messageBuffer.chunks[chunkIndex] = chunk;\n messageBuffer.received++;\n\n this._secureLog('debug', `\uD83D\uDCE6 Received chunk ${chunkIndex + 1}/${totalChunks} for message ${messageId}`);\n\n // Check if all chunks received\n if (messageBuffer.received === totalChunks) {\n // Combine all chunks\n const totalSize = messageBuffer.chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const combinedData = new Uint8Array(totalSize);\n \n let offset = 0;\n for (const chunk of messageBuffer.chunks) {\n combinedData.set(chunk, offset);\n offset += chunk.length;\n }\n\n // Process complete message\n await this.processMessage(combinedData.buffer);\n \n // Clean up\n delete this.chunkQueue[messageId];\n \n this._secureLog('info', `\uD83D\uDCE6 Chunked message ${messageId} reassembled and processed`);\n }\n } catch (error) {\n this._secureLog('error', '\u274C Chunked message processing failed:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }\n\n // ============================================\n // 5. DECOY CHANNELS\n // ============================================\n\n initializeDecoyChannels() {\n if (!this.decoyChannelConfig.enabled || !this.peerConnection) {\n return;\n }\n\n // Prevent multiple initializations\n if (this.decoyChannels.size > 0) {\n this._secureLog('warn', '\u26A0\uFE0F Decoy channels already initialized, skipping...');\n return;\n }\n\n try {\n const numDecoyChannels = Math.min(\n this.decoyChannelConfig.maxDecoyChannels,\n this.decoyChannelConfig.decoyChannelNames.length\n );\n\n for (let i = 0; i < numDecoyChannels; i++) {\n const channelName = this.decoyChannelConfig.decoyChannelNames[i];\n const decoyChannel = this.peerConnection.createDataChannel(channelName, {\n ordered: Math.random() > 0.5,\n maxRetransmits: Math.floor(Math.random() * 3)\n });\n\n this.setupDecoyChannel(decoyChannel, channelName);\n this.decoyChannels.set(channelName, decoyChannel);\n }\n\n if (this._debugMode) {\n this._secureLog('info', `\uD83C\uDFAD Initialized ${numDecoyChannels} decoy channels`);\n }\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('error', '\u274C Failed to initialize decoy channels:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }\n }\n\n setupDecoyChannel(channel, channelName) {\n channel.onopen = () => {\n if (this._debugMode) {\n this._secureLog('debug', `\uD83C\uDFAD Decoy channel \"${channelName}\" opened`);\n }\n this.startDecoyTraffic(channel, channelName);\n };\n\n channel.onmessage = (event) => {\n if (this._debugMode) {\n this._secureLog('debug', `\uD83C\uDFAD Received decoy message on \"${channelName}\": ${event.data?.length || 'undefined'} bytes`);\n }\n };\n\n channel.onclose = () => {\n if (this._debugMode) {\n this._secureLog('debug', `\uD83C\uDFAD Decoy channel \"${channelName}\" closed`);\n }\n this.stopDecoyTraffic(channelName);\n };\n\n channel.onerror = (error) => {\n if (this._debugMode) {\n this._secureLog('error', `\u274C Decoy channel \"${channelName}\" error`, { error: error.message });\n }\n };\n }\n\n startDecoyTraffic(channel, channelName) {\n const sendDecoyData = async () => {\n if (channel.readyState !== 'open') {\n return;\n }\n\n try {\n const decoyData = this.generateDecoyData(channelName);\n channel.send(decoyData);\n \n const interval = this.decoyChannelConfig.randomDecoyIntervals ?\n Math.random() * 15000 + 10000 : \n 20000; \n \n this.decoyTimers.set(channelName, setTimeout(() => sendDecoyData(), interval));\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('error', `\u274C Failed to send decoy data on \"${channelName}\"`, { error: error.message });\n }\n }\n };\n\n const initialDelay = Math.random() * 10000 + 5000; \n this.decoyTimers.set(channelName, setTimeout(() => sendDecoyData(), initialDelay));\n }\n\n stopDecoyTraffic(channelName) {\n const timer = this.decoyTimers.get(channelName);\n if (timer) {\n clearTimeout(timer);\n this.decoyTimers.delete(channelName);\n }\n }\n\n generateDecoyData(channelName) {\n const decoyTypes = {\n 'sync': () => JSON.stringify({\n type: 'sync',\n timestamp: Date.now(),\n sequence: Math.floor(Math.random() * 1000),\n data: Array.from(crypto.getRandomValues(new Uint8Array(32)))\n .map(b => b.toString(16).padStart(2, '0')).join('')\n }),\n 'status': () => JSON.stringify({\n type: 'status',\n status: ['online', 'away', 'busy'][Math.floor(Math.random() * 3)],\n uptime: Math.floor(Math.random() * 3600),\n data: Array.from(crypto.getRandomValues(new Uint8Array(16)))\n .map(b => b.toString(16).padStart(2, '0')).join('')\n }),\n 'heartbeat': () => JSON.stringify({\n type: 'heartbeat',\n timestamp: Date.now(),\n data: Array.from(crypto.getRandomValues(new Uint8Array(24)))\n .map(b => b.toString(16).padStart(2, '0')).join('')\n }),\n 'metrics': () => JSON.stringify({\n type: 'metrics',\n cpu: Math.random() * 100,\n memory: Math.random() * 100,\n network: Math.random() * 1000,\n data: Array.from(crypto.getRandomValues(new Uint8Array(20)))\n .map(b => b.toString(16).padStart(2, '0')).join('')\n }),\n 'debug': () => JSON.stringify({\n type: 'debug',\n level: ['info', 'warn', 'error'][Math.floor(Math.random() * 3)],\n message: 'Debug message',\n data: Array.from(crypto.getRandomValues(new Uint8Array(28)))\n .map(b => b.toString(16).padStart(2, '0')).join('')\n })\n };\n\n return decoyTypes[channelName] ? decoyTypes[channelName]() : \n Array.from(crypto.getRandomValues(new Uint8Array(64)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n }\n\n // ============================================\n // 6. PACKET REORDERING PROTECTION\n // ============================================\n\n addReorderingHeaders(data) {\n if (!this.reorderingConfig.enabled) {\n return data;\n }\n\n try {\n const dataArray = new Uint8Array(data);\n const headerSize = this.reorderingConfig.useTimestamps ? 12 : 8;\n const header = new ArrayBuffer(headerSize);\n const headerView = new DataView(header);\n\n // Add sequence number\n if (this.reorderingConfig.useSequenceNumbers) {\n headerView.setUint32(0, this.sequenceNumber++, false);\n }\n\n // Add timestamp\n if (this.reorderingConfig.useTimestamps) {\n headerView.setUint32(4, Date.now(), false);\n }\n\n // Add data size\n headerView.setUint32(this.reorderingConfig.useTimestamps ? 8 : 4, dataArray.length, false);\n\n // Combine header and data\n const result = new Uint8Array(headerSize + dataArray.length);\n result.set(new Uint8Array(header), 0);\n result.set(dataArray, headerSize);\n\n return result.buffer;\n } catch (error) {\n this._secureLog('error', '\u274C Failed to add reordering headers:', { errorType: error?.constructor?.name || 'Unknown' });\n return data;\n }\n }\n\n async processReorderedPacket(data) {\n if (!this.reorderingConfig.enabled) {\n return this.processMessage(data);\n }\n\n try {\n const dataArray = new Uint8Array(data);\n const headerSize = this.reorderingConfig.useTimestamps ? 12 : 8;\n\n if (dataArray.length < headerSize) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Data too short for reordering headers, processing directly');\n }\n return this.processMessage(data);\n }\n\n const headerView = new DataView(dataArray.buffer, 0, headerSize);\n let sequence = 0;\n let timestamp = 0;\n let dataSize = 0;\n\n if (this.reorderingConfig.useSequenceNumbers) {\n sequence = headerView.getUint32(0, false);\n }\n\n if (this.reorderingConfig.useTimestamps) {\n timestamp = headerView.getUint32(4, false);\n }\n\n dataSize = headerView.getUint32(this.reorderingConfig.useTimestamps ? 8 : 4, false);\n\n if (dataSize > dataArray.length - headerSize || dataSize <= 0) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Invalid reordered packet data size, processing directly');\n }\n return this.processMessage(data);\n }\n\n const actualData = dataArray.slice(headerSize, headerSize + dataSize);\n\n try {\n const textData = new TextDecoder().decode(actualData);\n const content = JSON.parse(textData);\n if (content.type === 'fake' || content.isFakeTraffic === true) {\n if (this._debugMode) {\n this._secureLog('warn', `\uD83C\uDFAD BLOCKED: Reordered fake message: ${content.pattern || 'unknown'}`);\n }\n return; \n }\n } catch (e) {\n\n }\n\n this.packetBuffer.set(sequence, {\n data: actualData.buffer,\n timestamp: timestamp || Date.now()\n });\n\n await this.processOrderedPackets();\n\n } catch (error) {\n this._secureLog('error', '\u274C Failed to process reordered packet:', { errorType: error?.constructor?.name || 'Unknown' });\n return this.processMessage(data);\n }\n}\n\n// ============================================\n// IMPROVED PROCESSORDEREDPACKETS with filtering\n// ============================================\n\nasync processOrderedPackets() {\n const now = Date.now();\n const timeout = this.reorderingConfig.reorderTimeout;\n\n while (true) {\n const nextSequence = this.lastProcessedSequence + 1;\n const packet = this.packetBuffer.get(nextSequence);\n\n if (!packet) {\n const oldestPacket = this.findOldestPacket();\n if (oldestPacket && (now - oldestPacket.timestamp) > timeout) {\n this._secureLog('warn', '\u26A0\uFE0F Packet ${oldestPacket.sequence} timed out, processing out of order');\n \n try {\n const textData = new TextDecoder().decode(oldestPacket.data);\n const content = JSON.parse(textData);\n if (content.type === 'fake' || content.isFakeTraffic === true) {\n this._secureLog('warn', `\uD83C\uDFAD BLOCKED: Timed out fake message: ${content.pattern || 'unknown'}`);\n this.packetBuffer.delete(oldestPacket.sequence);\n this.lastProcessedSequence = oldestPacket.sequence;\n continue; \n }\n } catch (e) {\n }\n \n await this.processMessage(oldestPacket.data);\n this.packetBuffer.delete(oldestPacket.sequence);\n this.lastProcessedSequence = oldestPacket.sequence;\n } else {\n break; \n }\n } else {\n try {\n const textData = new TextDecoder().decode(packet.data);\n const content = JSON.parse(textData);\n if (content.type === 'fake' || content.isFakeTraffic === true) {\n this._secureLog('warn', `\uD83C\uDFAD BLOCKED: Ordered fake message: ${content.pattern || 'unknown'}`);\n this.packetBuffer.delete(nextSequence);\n this.lastProcessedSequence = nextSequence;\n continue; \n }\n } catch (e) {\n }\n \n await this.processMessage(packet.data);\n this.packetBuffer.delete(nextSequence);\n this.lastProcessedSequence = nextSequence;\n }\n }\n\n this.cleanupOldPackets(now, timeout);\n}\n\n\n findOldestPacket() {\n let oldest = null;\n for (const [sequence, packet] of this.packetBuffer.entries()) {\n if (!oldest || packet.timestamp < oldest.timestamp) {\n oldest = { sequence, ...packet };\n }\n }\n return oldest;\n }\n\n cleanupOldPackets(now, timeout) {\n for (const [sequence, packet] of this.packetBuffer.entries()) {\n if ((now - packet.timestamp) > timeout) {\n this._secureLog('warn', '\u26A0\uFE0F \uD83D\uDDD1\uFE0F Removing timed out packet ${sequence}');\n this.packetBuffer.delete(sequence);\n }\n }\n }\n\n // ============================================\n // 7. ANTI-FINGERPRINTING\n // ============================================\n\n applyAntiFingerprinting(data) {\n if (!this.antiFingerprintingConfig.enabled) {\n return data;\n }\n\n try {\n let processedData = data;\n\n // Add random noise\n if (this.antiFingerprintingConfig.addNoise) {\n processedData = this.addNoise(processedData);\n }\n\n // Randomize sizes\n if (this.antiFingerprintingConfig.randomizeSizes) {\n processedData = this.randomizeSize(processedData);\n }\n\n // Mask patterns\n if (this.antiFingerprintingConfig.maskPatterns) {\n processedData = this.maskPatterns(processedData);\n }\n\n // Add random headers\n if (this.antiFingerprintingConfig.useRandomHeaders) {\n processedData = this.addRandomHeaders(processedData);\n }\n\n return processedData;\n } catch (error) {\n this._secureLog('error', '\u274C Anti-fingerprinting failed:', { errorType: error?.constructor?.name || 'Unknown' });\n return data;\n }\n }\n\n addNoise(data) {\n const dataArray = new Uint8Array(data);\n const noiseSize = Math.floor(Math.random() * 32) + 8; // 8-40 bytes\n const noise = crypto.getRandomValues(new Uint8Array(noiseSize));\n \n const result = new Uint8Array(dataArray.length + noiseSize);\n result.set(dataArray, 0);\n result.set(noise, dataArray.length);\n \n return result.buffer;\n }\n\n randomizeSize(data) {\n const dataArray = new Uint8Array(data);\n const variation = this.fingerprintMask.sizeVariation;\n const targetSize = Math.floor(dataArray.length * variation);\n \n if (targetSize > dataArray.length) {\n // Add padding to increase size\n const padding = crypto.getRandomValues(new Uint8Array(targetSize - dataArray.length));\n const result = new Uint8Array(targetSize);\n result.set(dataArray, 0);\n result.set(padding, dataArray.length);\n return result.buffer;\n } else if (targetSize < dataArray.length) {\n // Truncate to decrease size\n return dataArray.slice(0, targetSize).buffer;\n }\n \n return data;\n }\n\n maskPatterns(data) {\n const dataArray = new Uint8Array(data);\n const result = new Uint8Array(dataArray.length);\n \n // Apply XOR with noise pattern\n for (let i = 0; i < dataArray.length; i++) {\n const noiseByte = this.fingerprintMask.noisePattern[i % this.fingerprintMask.noisePattern.length];\n result[i] = dataArray[i] ^ noiseByte;\n }\n \n return result.buffer;\n }\n\n addRandomHeaders(data) {\n const dataArray = new Uint8Array(data);\n const headerCount = Math.floor(Math.random() * 3) + 1; // 1-3 headers\n let totalHeaderSize = 0;\n \n // Calculate total header size\n for (let i = 0; i < headerCount; i++) {\n totalHeaderSize += 4 + Math.floor(Math.random() * 16) + 4; // size + data + checksum\n }\n \n const result = new Uint8Array(totalHeaderSize + dataArray.length);\n let offset = 0;\n \n // Add random headers\n for (let i = 0; i < headerCount; i++) {\n const headerName = this.fingerprintMask.headerVariations[\n Math.floor(Math.random() * this.fingerprintMask.headerVariations.length)\n ];\n const headerData = crypto.getRandomValues(new Uint8Array(Math.floor(Math.random() * 16) + 4));\n \n // Header structure: [size:4][name:4][data:variable][checksum:4]\n const headerView = new DataView(result.buffer, offset);\n headerView.setUint32(0, headerData.length + 8, false); // Total header size\n headerView.setUint32(4, this.hashString(headerName), false); // Name hash\n \n result.set(headerData, offset + 8);\n \n // Add checksum\n const checksum = this.calculateChecksum(result.slice(offset, offset + 8 + headerData.length));\n const checksumView = new DataView(result.buffer, offset + 8 + headerData.length);\n checksumView.setUint32(0, checksum, false);\n \n offset += 8 + headerData.length + 4;\n }\n \n // Add original data\n result.set(dataArray, offset);\n \n return result.buffer;\n }\n\n hashString(str) {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash;\n }\n return Math.abs(hash);\n }\n\n calculateChecksum(data) {\n let checksum = 0;\n for (let i = 0; i < data.length; i++) {\n checksum = (checksum + data[i]) & 0xFFFFFFFF;\n }\n return checksum;\n }\n\n // ============================================\n // ENHANCED MESSAGE SENDING AND RECEIVING\n // ============================================\n\n async removeSecurityLayers(data) {\n try {\n const status = this.getSecurityStatus();\n if (this._debugMode) {\n this._secureLog('debug', `\uD83D\uDD0D removeSecurityLayers (Stage ${status.stage})`, {\n dataType: typeof data,\n dataLength: data?.length || data?.byteLength || 0,\n activeFeatures: status.activeFeaturesCount\n });\n }\n\n if (!data) {\n this._secureLog('warn', '\u26A0\uFE0F Received empty data');\n return null;\n }\n\n let processedData = data;\n\n // IMPORTANT: Early check for fake messages\n if (typeof data === 'string') {\n try {\n const jsonData = JSON.parse(data);\n \n // PRIORITY ONE: Filtering out fake messages\n if (jsonData.type === 'fake') {\n if (this._debugMode) {\n this._secureLog('debug', `\uD83C\uDFAD Fake message filtered out: ${jsonData.pattern} (size: ${jsonData.size})`);\n }\n return 'FAKE_MESSAGE_FILTERED'; \n }\n \n // System messages \u2014 do NOT return for re-processing\n if (jsonData.type && ['heartbeat', 'verification', 'verification_response', 'peer_disconnect', 'key_rotation_signal', 'key_rotation_ready', 'security_upgrade'].includes(jsonData.type)) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDD27 System message detected, blocking from chat', { type: jsonData.type });\n }\n return 'SYSTEM_MESSAGE_FILTERED';\n }\n \n // File transfer messages \u2014 do NOT return for display\n if (jsonData.type && ['file_transfer_start', 'file_transfer_response', 'file_chunk', 'chunk_confirmation', 'file_transfer_complete', 'file_transfer_error'].includes(jsonData.type)) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCC1 File transfer message detected, blocking from chat', { type: jsonData.type });\n }\n return 'FILE_MESSAGE_FILTERED';\n }\n \n // Regular text messages - extract the actual message text\n if (jsonData.type === 'message') {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCDD Regular message detected, extracting text', { data: jsonData.data });\n }\n return jsonData.data; // Return the actual message text, not the JSON\n }\n \n // Enhanced messages\n if (jsonData.type === 'enhanced_message' && jsonData.data) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDD10 Enhanced message detected, decrypting...');\n }\n \n if (!this.encryptionKey || !this.macKey || !this.metadataKey) {\n this._secureLog('error', '\u274C Missing encryption keys');\n return null;\n }\n \n const decryptedResult = await window.EnhancedSecureCryptoUtils.decryptMessage(\n jsonData.data,\n this.encryptionKey,\n this.macKey,\n this.metadataKey\n );\n \n if (this._debugMode) {\n this._secureLog('debug', '\u2705 Enhanced message decrypted, extracting...');\n this._secureLog('debug', '\uD83D\uDD0D decryptedResult', {\n type: typeof decryptedResult,\n hasMessage: !!decryptedResult?.message,\n messageType: typeof decryptedResult?.message,\n messageLength: decryptedResult?.message?.length || 0,\n messageSample: decryptedResult?.message?.substring(0, 50) || 'no message'\n });\n }\n \n // CHECKING FOR FAKE MESSAGES AFTER DECRYPTION\n try {\n const decryptedContent = JSON.parse(decryptedResult.message);\n if (decryptedContent.type === 'fake' || decryptedContent.isFakeTraffic === true) {\n if (this._debugMode) {\n this._secureLog('warn', `\uD83C\uDFAD BLOCKED: Encrypted fake message: ${decryptedContent.pattern || 'unknown'}`);\n }\n return 'FAKE_MESSAGE_FILTERED';\n }\n } catch (e) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCDD Decrypted content is not JSON, treating as plain text message');\n }\n }\n \n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCE4 Returning decrypted message', { message: decryptedResult.message?.substring(0, 50) });\n }\n return decryptedResult.message;\n }\n \n // Regular messages\n if (jsonData.type === 'message' && jsonData.data) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCDD Regular message detected, extracting data');\n }\n return jsonData.data; // Return the actual message text\n }\n \n // If it's a regular message with type 'message', let it continue processing\n if (jsonData.type === 'message') {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCDD Regular message detected, returning for display');\n }\n return data; // Return the original JSON string for processing\n }\n \n // If it's not a special type, return the original data for display\n if (!jsonData.type || (jsonData.type !== 'fake' && !['heartbeat', 'verification', 'verification_response', 'peer_disconnect', 'key_rotation_signal', 'key_rotation_ready', 'enhanced_message', 'security_upgrade', 'file_transfer_start', 'file_transfer_response', 'file_chunk', 'chunk_confirmation', 'file_transfer_complete', 'file_transfer_error'].includes(jsonData.type))) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCDD Regular message detected, returning for display');\n }\n return data;\n }\n } catch (e) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCC4 Not JSON, processing as raw data');\n }\n // If it's not JSON, it might be a plain text message - return as-is\n return data;\n }\n }\n\n // Standard Decryption\n if (this.encryptionKey && typeof processedData === 'string' && processedData.length > 50) {\n try {\n const base64Regex = /^[A-Za-z0-9+/=]+$/;\n if (base64Regex.test(processedData.trim())) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDD13 Applying standard decryption...');\n }\n processedData = await window.EnhancedSecureCryptoUtils.decryptData(processedData, this.encryptionKey);\n if (this._debugMode) {\n this._secureLog('debug', '\u2705 Standard decryption successful');\n }\n \n // CHECKING FOR FAKE MESSAGES AFTER LEGACY DECRYPTION\n if (typeof processedData === 'string') {\n try {\n const legacyContent = JSON.parse(processedData);\n if (legacyContent.type === 'fake' || legacyContent.isFakeTraffic === true) {\n if (this._debugMode) {\n this._secureLog('warn', `\uD83C\uDFAD BLOCKED: Legacy fake message: ${legacyContent.pattern || 'unknown'}`);\n }\n return 'FAKE_MESSAGE_FILTERED';\n }\n } catch (e) {\n \n }\n processedData = new TextEncoder().encode(processedData).buffer;\n }\n }\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Standard decryption failed:', { details: error.message });\n }\n return data; \n }\n }\n\n if (this.securityFeatures.hasNestedEncryption && \n this.nestedEncryptionKey && \n processedData instanceof ArrayBuffer &&\n processedData.byteLength > 12) { \n \n try {\n processedData = await this.removeNestedEncryption(processedData);\n \n if (processedData instanceof ArrayBuffer) {\n try {\n const textData = new TextDecoder().decode(processedData);\n const nestedContent = JSON.parse(textData);\n if (nestedContent.type === 'fake' || nestedContent.isFakeTraffic === true) {\n if (this._debugMode) {\n this._secureLog('warn', `\uD83C\uDFAD BLOCKED: Nested fake message: ${nestedContent.pattern || 'unknown'}`);\n }\n return 'FAKE_MESSAGE_FILTERED';\n }\n } catch (e) {\n \n }\n }\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Nested decryption failed - skipping this layer:', { details: error.message });\n }\n }\n }\n\n if (this.securityFeatures.hasPacketReordering && \n this.reorderingConfig.enabled && \n processedData instanceof ArrayBuffer) {\n try {\n const headerSize = this.reorderingConfig.useTimestamps ? 12 : 8;\n if (processedData.byteLength > headerSize) {\n return await this.processReorderedPacket(processedData);\n }\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Reordering processing failed - using direct processing:', { details: error.message });\n }\n }\n }\n\n // Packet Padding Removal\n if (this.securityFeatures.hasPacketPadding && processedData instanceof ArrayBuffer) {\n try {\n processedData = this.removePacketPadding(processedData);\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Padding removal failed:', { details: error.message });\n }\n }\n }\n\n // Anti-Fingerprinting Removal\n if (this.securityFeatures.hasAntiFingerprinting && processedData instanceof ArrayBuffer) {\n try {\n processedData = this.removeAntiFingerprinting(processedData);\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Anti-fingerprinting removal failed:', { details: error.message });\n }\n }\n }\n\n // Final transformation\n if (processedData instanceof ArrayBuffer) {\n processedData = new TextDecoder().decode(processedData);\n }\n\n if (typeof processedData === 'string') {\n try {\n const finalContent = JSON.parse(processedData);\n if (finalContent.type === 'fake' || finalContent.isFakeTraffic === true) {\n if (this._debugMode) {\n this._secureLog('warn', `\uD83C\uDFAD BLOCKED: Final check fake message: ${finalContent.pattern || 'unknown'}`);\n }\n return 'FAKE_MESSAGE_FILTERED';\n }\n } catch (e) {\n }\n }\n\n return processedData;\n\n } catch (error) {\n this._secureLog('error', '\u274C Critical error in removeSecurityLayers:', { errorType: error?.constructor?.name || 'Unknown' });\n return data;\n }\n}\n\n removeAntiFingerprinting(data) {\n // This is a simplified version - in practice, you'd need to reverse all operations\n // For now, we'll just return the data as-is since the operations are mostly additive\n return data;\n }\n\n async applySecurityLayers(data, isFakeMessage = false) {\n try {\n let processedData = data;\n \n if (isFakeMessage) {\n if (this.encryptionKey && typeof processedData === 'string') {\n processedData = await window.EnhancedSecureCryptoUtils.encryptData(processedData, this.encryptionKey);\n }\n return processedData;\n }\n \n if (this.securityFeatures.hasNestedEncryption && this.nestedEncryptionKey && processedData instanceof ArrayBuffer) {\n processedData = await this.applyNestedEncryption(processedData);\n }\n \n if (this.securityFeatures.hasPacketReordering && this.reorderingConfig?.enabled && processedData instanceof ArrayBuffer) {\n processedData = this.applyPacketReordering(processedData);\n }\n \n if (this.securityFeatures.hasPacketPadding && processedData instanceof ArrayBuffer) {\n processedData = this.applyPacketPadding(processedData);\n }\n \n if (this.securityFeatures.hasAntiFingerprinting && processedData instanceof ArrayBuffer) {\n processedData = this.applyAntiFingerprinting(processedData);\n }\n \n if (this.encryptionKey && typeof processedData === 'string') {\n processedData = await window.EnhancedSecureCryptoUtils.encryptData(processedData, this.encryptionKey);\n }\n \n return processedData;\n \n } catch (error) {\n this._secureLog('error', '\u274C Error in applySecurityLayers:', { errorType: error?.constructor?.name || 'Unknown' });\n return data;\n }\n }\n\n async sendMessage(data) {\n // Comprehensive input validation\n const validation = this._validateInputData(data, 'sendMessage');\n if (!validation.isValid) {\n const errorMessage = `Input validation failed: ${validation.errors.join(', ')}`;\n this._secureLog('error', '\u274C Input validation failed in sendMessage', {\n errors: validation.errors,\n dataType: typeof data,\n dataLength: data?.length || data?.byteLength || 0\n });\n throw new Error(errorMessage);\n }\n\n // Rate limiting check\n if (!this._checkRateLimit('sendMessage')) {\n throw new Error('Rate limit exceeded for message sending');\n }\n\n // Enforce verification gate\n this._enforceVerificationGate('sendMessage');\n\n // Connection validation\n if (!this.dataChannel || this.dataChannel.readyState !== 'open') {\n throw new Error('Data channel not ready');\n }\n\n try {\n this._secureLog('debug', 'sendMessage called', {\n hasDataChannel: !!this.dataChannel,\n dataChannelReady: this.dataChannel?.readyState === 'open',\n isInitiator: this.isInitiator,\n isVerified: this.isVerified,\n connectionReady: this.peerConnection?.connectionState === 'connected'\n });\n\n this._secureLog('debug', '\uD83D\uDD0D sendMessage DEBUG', {\n dataType: typeof validation.sanitizedData,\n isString: typeof validation.sanitizedData === 'string',\n isArrayBuffer: validation.sanitizedData instanceof ArrayBuffer,\n dataLength: validation.sanitizedData?.length || validation.sanitizedData?.byteLength || 0,\n });\n\n // CRITICAL SECURITY FIX: File messages MUST be encrypted\n // No more bypassing encryption for file_* messages\n if (typeof validation.sanitizedData === 'string') {\n try {\n const parsed = JSON.parse(validation.sanitizedData);\n \n if (parsed.type && parsed.type.startsWith('file_')) {\n this._secureLog('debug', '\uD83D\uDCC1 File message detected - applying full encryption with AAD', { type: parsed.type });\n \n // Create AAD for file message\n const aad = this._createFileMessageAAD(parsed.type, parsed.data);\n \n // Encrypt file message with AAD\n const encryptedData = await this._encryptFileMessage(validation.sanitizedData, aad);\n \n this.dataChannel.send(encryptedData);\n return true;\n }\n } catch (jsonError) {\n // Not JSON \u2014 continue normal handling\n }\n }\n\n // For regular text messages, send via secure path with AAD\n if (typeof validation.sanitizedData === 'string') {\n // Verify that _createMessageAAD method is available\n if (typeof this._createMessageAAD !== 'function') {\n throw new Error('_createMessageAAD method is not available. Manager may not be fully initialized.');\n }\n \n // Create AAD with sequence number for anti-replay protection\n const aad = this._createMessageAAD('message', { content: validation.sanitizedData });\n \n return await this.sendSecureMessage({ \n type: 'message', \n data: validation.sanitizedData, \n timestamp: Date.now(),\n aad: aad // Include AAD for sequence number validation\n });\n }\n\n // For binary data, apply security layers with a limited mutex\n this._secureLog('debug', '\uD83D\uDD10 Applying security layers to non-string data');\n const securedData = await this._applySecurityLayersWithLimitedMutex(validation.sanitizedData, false);\n this.dataChannel.send(securedData);\n \n return true;\n } catch (error) {\n this._secureLog('error', '\u274C Failed to send message', { \n error: error.message,\n errorType: error.constructor.name\n });\n throw error;\n }\n }\n\n // FIX: New method applying security layers with limited mutex use\n async _applySecurityLayersWithLimitedMutex(data, isFakeMessage = false) {\n // Use mutex ONLY for cryptographic operations\n return this._withMutex('cryptoOperation', async (operationId) => {\n try {\n let processedData = data;\n \n if (isFakeMessage) {\n if (this.encryptionKey && typeof processedData === 'string') {\n processedData = await window.EnhancedSecureCryptoUtils.encryptData(processedData, this.encryptionKey);\n }\n return processedData;\n }\n \n if (this.securityFeatures.hasNestedEncryption && this.nestedEncryptionKey && processedData instanceof ArrayBuffer) {\n processedData = await this.applyNestedEncryption(processedData);\n }\n \n if (this.securityFeatures.hasPacketReordering && this.reorderingConfig?.enabled && processedData instanceof ArrayBuffer) {\n processedData = this.applyPacketReordering(processedData);\n }\n \n if (this.securityFeatures.hasPacketPadding && processedData instanceof ArrayBuffer) {\n processedData = this.applyPacketPadding(processedData);\n }\n \n if (this.securityFeatures.hasAntiFingerprinting && processedData instanceof ArrayBuffer) {\n processedData = this.applyAntiFingerprinting(processedData);\n }\n \n if (this.encryptionKey && typeof processedData === 'string') {\n processedData = await window.EnhancedSecureCryptoUtils.encryptData(processedData, this.encryptionKey);\n }\n \n return processedData;\n \n } catch (error) {\n this._secureLog('error', '\u274C Error in applySecurityLayers:', { errorType: error?.constructor?.name || 'Unknown' });\n return data;\n }\n }, 3000); // Short timeout for crypto operations\n}\n\n async sendSystemMessage(messageData) {\n // Block system messages without verification\n // Exception: Allow verification-related system messages\n const isVerificationMessage = messageData.type === 'verification_request' || \n messageData.type === 'verification_response' ||\n messageData.type === 'verification_required';\n \n if (!isVerificationMessage) {\n this._enforceVerificationGate('sendSystemMessage', false);\n }\n \n if (!this.dataChannel || this.dataChannel.readyState !== 'open') {\n this._secureLog('warn', '\u26A0\uFE0F Cannot send system message - data channel not ready');\n return false;\n }\n\n try {\n const systemMessage = JSON.stringify({\n type: messageData.type,\n data: messageData,\n timestamp: Date.now()\n });\n\n this._secureLog('debug', '\uD83D\uDD27 Sending system message', { type: messageData.type });\n this.dataChannel.send(systemMessage);\n return true;\n } catch (error) {\n this._secureLog('error', '\u274C Failed to send system message:', { errorType: error?.constructor?.name || 'Unknown' });\n return false;\n }\n }\n\n // FIX 1: Simplified mutex system for message processing\nasync processMessage(data) {\n try {\n this._secureLog('debug', '\uFFFD\uFFFD Processing message', {\n dataType: typeof data,\n isArrayBuffer: data instanceof ArrayBuffer,\n hasData: !!(data?.length || data?.byteLength)\n });\n \n // CRITICAL: Early check for file messages WITHOUT mutex\n if (typeof data === 'string') {\n try {\n const parsed = JSON.parse(data);\n\n // ============================================\n // FILE MESSAGES \u2014 PRIORITY 1 (WITHOUT MUTEX)\n // ============================================\n \n const fileMessageTypes = [\n 'file_transfer_start',\n 'file_transfer_response',\n 'file_chunk', \n 'chunk_confirmation',\n 'file_transfer_complete',\n 'file_transfer_error'\n ];\n\n // CRITICAL SECURITY FIX: Check for encrypted file messages first\n if (parsed.type === 'encrypted_file_message') {\n this._secureLog('debug', '\uD83D\uDCC1 Encrypted file message detected in processMessage');\n \n try {\n // Decrypt and validate file message\n const { decryptedData, aad } = await this._decryptFileMessage(data);\n \n // Parse decrypted data\n const decryptedParsed = JSON.parse(decryptedData);\n \n this._secureLog('debug', '\uD83D\uDCC1 File message decrypted successfully', { \n type: decryptedParsed.type,\n aadMessageType: aad.messageType \n });\n \n // Process decrypted file message\n if (this.fileTransferSystem && typeof this.fileTransferSystem.handleFileMessage === 'function') {\n await this.fileTransferSystem.handleFileMessage(decryptedParsed);\n return;\n }\n } catch (error) {\n this._secureLog('error', '\u274C Failed to decrypt file message', { error: error.message });\n return; // Drop invalid file message\n }\n }\n \n // Legacy unencrypted file messages - should not happen in secure mode\n if (parsed.type && fileMessageTypes.includes(parsed.type)) {\n this._secureLog('warn', '\u26A0\uFE0F Unencrypted file message detected - this should not happen in secure mode', { type: parsed.type });\n \n // Drop unencrypted file messages for security\n this._secureLog('error', '\u274C Dropping unencrypted file message for security', { type: parsed.type });\n return;\n }\n \n // ============================================\n // ENHANCED MESSAGES WITH AAD VALIDATION (WITHOUT MUTEX)\n // ============================================\n \n if (parsed.type === 'enhanced_message') {\n this._secureLog('debug', '\uD83D\uDD10 Enhanced message detected in processMessage');\n \n try {\n // Decrypt enhanced message\n const decryptedData = await window.EnhancedSecureCryptoUtils.decryptMessage(\n parsed.data,\n this.encryptionKey,\n this.macKey,\n this.metadataKey\n );\n \n // Parse decrypted data\n const decryptedParsed = JSON.parse(decryptedData.data);\n \n // Validate AAD with sequence number\n if (decryptedData.metadata && decryptedData.metadata.sequenceNumber !== undefined) {\n if (!this._validateIncomingSequenceNumber(decryptedData.metadata.sequenceNumber, 'enhanced_message')) {\n this._secureLog('warn', '\u26A0\uFE0F Enhanced message sequence number validation failed - possible replay attack', {\n received: decryptedData.metadata.sequenceNumber,\n expected: this.expectedSequenceNumber\n });\n return; // Drop message with invalid sequence number\n }\n }\n \n // Process decrypted message\n if (decryptedParsed.type === 'message' && this.onMessage && decryptedParsed.data) {\n this.deliverMessageToUI(decryptedParsed.data, 'received');\n }\n \n return;\n } catch (error) {\n this._secureLog('error', '\u274C Failed to decrypt enhanced message', { error: error.message });\n return; // Drop invalid enhanced message\n }\n }\n \n // ============================================\n // REGULAR USER MESSAGES (WITHOUT MUTEX)\n // ============================================\n \n if (parsed.type === 'message') {\n this._secureLog('debug', '\uD83D\uDCDD Regular user message detected in processMessage');\n if (this.onMessage && parsed.data) {\n this.deliverMessageToUI(parsed.data, 'received');\n }\n return;\n }\n \n // ============================================\n // SYSTEM MESSAGES (WITHOUT MUTEX)\n // ============================================\n \n if (parsed.type && ['heartbeat', 'verification', 'verification_response', 'verification_confirmed', 'verification_both_confirmed', 'peer_disconnect', 'security_upgrade'].includes(parsed.type)) {\n this.handleSystemMessage(parsed);\n return;\n }\n \n // ============================================\n // FAKE MESSAGES (WITHOUT MUTEX)\n // ============================================\n \n if (parsed.type === 'fake') {\n this._secureLog('warn', '\uD83C\uDFAD Fake message blocked in processMessage', { pattern: parsed.pattern });\n return;\n }\n \n } catch (jsonError) {\n // Not JSON \u2014 treat as text WITHOUT mutex\n if (this.onMessage) {\n this.deliverMessageToUI(data, 'received');\n }\n return;\n }\n }\n\n // ============================================\n // ENCRYPTED DATA PROCESSING (WITH MUTEX ONLY FOR CRYPTO)\n // ============================================\n \n // If here \u2014 apply security layers with limited mutex\n const originalData = await this._processEncryptedDataWithLimitedMutex(data);\n\n // Check processing result\n if (originalData === 'FAKE_MESSAGE_FILTERED' || \n originalData === 'FILE_MESSAGE_FILTERED' || \n originalData === 'SYSTEM_MESSAGE_FILTERED') {\n return;\n }\n \n if (!originalData) {\n this._secureLog('warn', '\u26A0\uFE0F No data returned from removeSecurityLayers');\n return;\n }\n\n // Handle result after removeSecurityLayers\n let messageText;\n \n if (typeof originalData === 'string') {\n try {\n const message = JSON.parse(originalData);\n \n // SECOND CHECK FOR FILE MESSAGES AFTER DECRYPTION\n if (message.type && fileMessageTypes.includes(message.type)) {\n this._secureLog('debug', '\uD83D\uDCC1 File message detected after decryption', { type: message.type });\n if (this.fileTransferSystem) {\n await this.fileTransferSystem.handleFileMessage(message);\n }\n return;\n }\n \n if (message.type && ['heartbeat', 'verification', 'verification_response', 'verification_confirmed', 'verification_both_confirmed', 'peer_disconnect', 'security_upgrade'].includes(message.type)) {\n this.handleSystemMessage(message);\n return;\n }\n \n if (message.type === 'fake') {\n this._secureLog('warn', `\uD83C\uDFAD Post-decryption fake message blocked: ${message.pattern}`);\n return;\n }\n \n // Regular messages\n if (message.type === 'message' && message.data) {\n messageText = message.data;\n } else {\n messageText = originalData;\n }\n } catch (e) {\n messageText = originalData;\n }\n } else if (originalData instanceof ArrayBuffer) {\n messageText = new TextDecoder().decode(originalData);\n } else if (originalData && typeof originalData === 'object' && originalData.message) {\n messageText = originalData.message;\n } else {\n this._secureLog('warn', '\u26A0\uFE0F Unexpected data type after processing:', { details: typeof originalData });\n return;\n }\n\n // Final check for fake and file messages\n if (messageText && messageText.trim().startsWith('{')) {\n try {\n const finalCheck = JSON.parse(messageText);\n if (finalCheck.type === 'fake') {\n this._secureLog('warn', `\uD83C\uDFAD Final fake message check blocked: ${finalCheck.pattern}`);\n return;\n }\n \n // Additional check for file and system messages\n const blockedTypes = [\n 'file_transfer_start', 'file_transfer_response', 'file_chunk', \n 'chunk_confirmation', 'file_transfer_complete', 'file_transfer_error',\n 'heartbeat', 'verification', 'verification_response', \n 'peer_disconnect', 'key_rotation_signal', 'key_rotation_ready', 'security_upgrade'\n ];\n \n if (finalCheck.type && blockedTypes.includes(finalCheck.type)) {\n this._secureLog('warn', `\uD83D\uDCC1 Final system/file message check blocked: ${finalCheck.type}`);\n return;\n }\n } catch (e) {\n // Not JSON \u2014 fine for plain text\n }\n }\n\n // Deliver message to the UI\n if (this.onMessage && messageText) {\n this._secureLog('debug', '\uD83D\uDCE4 Calling message handler with', { message: messageText.substring(0, 100) });\n this.deliverMessageToUI(messageText, 'received');\n }\n\n } catch (error) {\n this._secureLog('error', '\u274C Failed to process message:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n}\n\n // FIX: New method with limited mutex when processing encrypted data\n async _processEncryptedDataWithLimitedMutex(data) {\n // Use mutex ONLY for cryptographic operations\n return this._withMutex('cryptoOperation', async (operationId) => {\n this._secureLog('debug', '\uD83D\uDD10 Processing encrypted data with limited mutex', {\n operationId: operationId,\n dataType: typeof data\n });\n \n try {\n // Apply security layers\n const originalData = await this.removeSecurityLayers(data);\n return originalData;\n \n } catch (error) {\n this._secureLog('error', '\u274C Error processing encrypted data', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n return data; // Return original data on error\n }\n }, 2000); // Short timeout for crypto operations\n }\n\n notifySecurityUpdate() {\n try {\n this._secureLog('debug', '\uD83D\uDD12 Notifying about security level update', {\n isConnected: this.isConnected(),\n isVerified: this.isVerified,\n hasKeys: !!(this.encryptionKey && this.macKey && this.metadataKey),\n hasLastCalculation: !!this.lastSecurityCalculation\n });\n \n // Send an event about security level update\n document.dispatchEvent(new CustomEvent('security-level-updated', {\n detail: { \n timestamp: Date.now(), \n manager: 'webrtc',\n webrtcManager: this,\n isConnected: this.isConnected(),\n isVerified: this.isVerified,\n hasKeys: !!(this.encryptionKey && this.macKey && this.metadataKey),\n lastCalculation: this.lastSecurityCalculation\n }\n }));\n \n // FIX: Force header refresh with correct manager\n setTimeout(() => {\n // Removed global callback - use event system instead\n // if (window.forceHeaderSecurityUpdate) {\n // window.forceHeaderSecurityUpdate(this);\n // }\n }, 100);\n \n // FIX: Direct update if there is a calculation\n if (this.lastSecurityCalculation) {\n document.dispatchEvent(new CustomEvent('real-security-calculated', {\n detail: {\n securityData: this.lastSecurityCalculation,\n webrtcManager: this,\n timestamp: Date.now()\n }\n }));\n }\n \n } catch (error) {\n this._secureLog('error', '\u274C Error in notifySecurityUpdate', {\n error: error.message\n });\n }\n }\n\n handleSystemMessage(message) {\n this._secureLog('debug', '\uD83D\uDD27 Handling system message:', { type: message.type });\n \n switch (message.type) {\n case 'heartbeat':\n this.handleHeartbeat();\n break;\n case 'verification':\n this.handleVerificationRequest(message.data);\n break;\n case 'verification_response':\n this.handleVerificationResponse(message.data);\n break;\n case 'sas_code':\n this.handleSASCode(message.data);\n break;\n case 'verification_confirmed':\n this.handleVerificationConfirmed(message.data);\n break;\n case 'verification_both_confirmed':\n this.handleVerificationBothConfirmed(message.data);\n break;\n case 'peer_disconnect':\n this.handlePeerDisconnectNotification(message);\n break;\n case 'key_rotation_signal':\n this._secureLog('debug', '\uD83D\uDD04 Key rotation signal received (ignored for stability)');\n break;\n case 'key_rotation_ready':\n this._secureLog('debug', '\uD83D\uDD04 Key rotation ready signal received (ignored for stability)');\n break;\n case 'security_upgrade':\n this._secureLog('debug', '\uD83D\uDD12 Security upgrade notification received:', { type: message.type });\n // Security upgrade messages are handled internally, not displayed to user\n // to prevent duplicate system messages\n break;\n default:\n this._secureLog('debug', '\uD83D\uDD27 Unknown system message type:', { type: message.type });\n }\n }\n\n // ============================================\n // FUNCTION MANAGEMENT METHODS\n // ============================================\n\n // Method to enable Stage 2 functions\n enableStage2Security() {\n if (this.sessionConstraints?.hasPacketReordering) {\n this.securityFeatures.hasPacketReordering = true;\n this.reorderingConfig.enabled = true;\n }\n \n if (this.sessionConstraints?.hasAntiFingerprinting) {\n this.securityFeatures.hasAntiFingerprinting = true;\n this.antiFingerprintingConfig.enabled = true;\n if (this.currentSecurityLevel === 'enhanced') {\n this.antiFingerprintingConfig.randomizeSizes = false;\n this.antiFingerprintingConfig.maskPatterns = false;\n this.antiFingerprintingConfig.useRandomHeaders = false;\n }\n }\n \n this.notifySecurityUpgrade(2);\n setTimeout(() => {\n this.calculateAndReportSecurityLevel();\n }, 500);\n }\n\n // Method to enable Stage 3 features (traffic obfuscation)\n enableStage3Security() {\n if (this.currentSecurityLevel !== 'maximum') {\n this._secureLog('info', '\uD83D\uDD12 Stage 3 features only available for premium sessions');\n return;\n }\n \n if (this.sessionConstraints?.hasMessageChunking) {\n this.securityFeatures.hasMessageChunking = true;\n this.chunkingConfig.enabled = true;\n }\n \n if (this.sessionConstraints?.hasFakeTraffic) {\n this.securityFeatures.hasFakeTraffic = true;\n this.fakeTrafficConfig.enabled = true;\n this.startFakeTrafficGeneration();\n }\n \n this.notifySecurityUpgrade(3);\n setTimeout(() => {\n this.calculateAndReportSecurityLevel();\n }, 500);\n }\n\n // Method for enabling Stage 4 functions (maximum safety)\n enableStage4Security() {\n if (this.currentSecurityLevel !== 'maximum') {\n this._secureLog('info', '\uD83D\uDD12 Stage 4 features only available for premium sessions');\n return;\n }\n \n if (this.sessionConstraints?.hasDecoyChannels && this.isConnected() && this.isVerified) {\n this.securityFeatures.hasDecoyChannels = true;\n this.decoyChannelConfig.enabled = true;\n \n try {\n this.initializeDecoyChannels();\n } catch (error) {\n this._secureLog('warn', '\u26A0\uFE0F Decoy channels initialization failed:', { details: error.message });\n this.securityFeatures.hasDecoyChannels = false;\n this.decoyChannelConfig.enabled = false;\n }\n }\n \n // Full anti-fingerprinting for maximum sessions\n if (this.sessionConstraints?.hasAntiFingerprinting) {\n this.antiFingerprintingConfig.randomizeSizes = true;\n this.antiFingerprintingConfig.maskPatterns = true;\n this.antiFingerprintingConfig.useRandomHeaders = false; \n }\n \n this.notifySecurityUpgrade(4);\n setTimeout(() => {\n this.calculateAndReportSecurityLevel();\n }, 500);\n }\n\n forceSecurityUpdate() {\n setTimeout(() => {\n this.calculateAndReportSecurityLevel();\n this.notifySecurityUpdate();\n }, 100);\n }\n\n // Method for getting security status\n getSecurityStatus() {\n const activeFeatures = Object.entries(this.securityFeatures)\n .filter(([key, value]) => value === true)\n .map(([key]) => key);\n \n const stage = this.currentSecurityLevel === 'basic' ? 1 : \n this.currentSecurityLevel === 'enhanced' ? 2 :\n this.currentSecurityLevel === 'maximum' ? 4 : 1;\n \n return {\n stage: stage,\n sessionType: this.currentSessionType,\n securityLevel: this.currentSecurityLevel,\n activeFeatures: activeFeatures,\n totalFeatures: Object.keys(this.securityFeatures).length,\n activeFeaturesCount: activeFeatures.length,\n activeFeaturesNames: activeFeatures,\n sessionConstraints: this.sessionConstraints\n };\n }\n\n // Method to notify UI about security update\n notifySecurityUpgrade(stage) {\n const stageNames = {\n 1: 'Basic Enhanced',\n 2: 'Medium Security', \n 3: 'High Security',\n 4: 'Maximum Security'\n };\n \n const message = `\uD83D\uDD12 Security upgraded to Stage ${stage}: ${stageNames[stage]}`;\n \n // Avoid duplicate security-upgrade notifications\n if (!this.securityUpgradeNotificationSent || this.lastSecurityUpgradeStage !== stage) {\n this.securityUpgradeNotificationSent = true;\n this.lastSecurityUpgradeStage = stage;\n \n // Notify local UI via onMessage\n if (this.onMessage) {\n this.deliverMessageToUI(message, 'system');\n }\n }\n\n // Send security upgrade notification to peer via WebRTC\n if (this.dataChannel && this.dataChannel.readyState === 'open') {\n try {\n const securityNotification = {\n type: 'security_upgrade',\n stage: stage,\n stageName: stageNames[stage],\n message: message,\n timestamp: Date.now()\n };\n \n this._secureLog('debug', '\uD83D\uDD12 Sending security upgrade notification to peer:', { type: securityNotification.type, stage: securityNotification.stage });\n this.dataChannel.send(JSON.stringify(securityNotification));\n } catch (error) {\n this._secureLog('warn', '\u26A0\uFE0F Failed to send security upgrade notification to peer:', { details: error.message });\n }\n }\n\n const status = this.getSecurityStatus();\n }\n\n async calculateAndReportSecurityLevel() {\n try {\n if (!window.EnhancedSecureCryptoUtils) {\n this._secureLog('warn', '\u26A0\uFE0F EnhancedSecureCryptoUtils not available for security calculation');\n return null;\n }\n\n if (!this.isConnected() || !this.isVerified || !this.encryptionKey || !this.macKey) {\n this._secureLog('debug', '\u26A0\uFE0F WebRTC not ready for security calculation', {\n connected: this.isConnected(),\n verified: this.isVerified,\n hasEncryptionKey: !!this.encryptionKey,\n hasMacKey: !!this.macKey\n });\n return null;\n }\n\n this._secureLog('debug', '\uD83D\uDD0D Calculating real security level', {\n managerState: 'ready',\n hasAllKeys: !!(this.encryptionKey && this.macKey && this.metadataKey)\n });\n \n const securityData = await window.EnhancedSecureCryptoUtils.calculateSecurityLevel(this);\n \n this._secureLog('info', '\uD83D\uDD10 Real security level calculated', {\n hasSecurityLevel: !!securityData.level,\n scoreRange: securityData.score > 80 ? 'high' : securityData.score > 50 ? 'medium' : 'low',\n checksRatio: `${securityData.passedChecks}/${securityData.totalChecks}`,\n isRealCalculation: securityData.isRealData\n });\n\n this.lastSecurityCalculation = securityData;\n\n document.dispatchEvent(new CustomEvent('real-security-calculated', {\n detail: {\n securityData: securityData,\n webrtcManager: this,\n timestamp: Date.now(),\n source: 'calculateAndReportSecurityLevel'\n }\n }));\n\n if (securityData.isRealData && this.onMessage) {\n if (!this.securityCalculationNotificationSent || this.lastSecurityCalculationLevel !== securityData.level) {\n this.securityCalculationNotificationSent = true;\n this.lastSecurityCalculationLevel = securityData.level;\n \n const message = `\uD83D\uDD12 Security Level: ${securityData.level} (${securityData.score}%) - ${securityData.passedChecks}/${securityData.totalChecks} checks passed`;\n this.deliverMessageToUI(message, 'system');\n }\n }\n \n return securityData;\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to calculate real security level', {\n errorType: error.constructor.name\n });\n return null;\n }\n }\n\n // ============================================\n // AUTOMATIC STEP-BY-STEP SWITCHING ON\n // ============================================\n\n // Method for automatic feature enablement with stability check\n async autoEnableSecurityFeatures() {\n if (this.currentSessionType === 'demo') {\n this._secureLog('info', '\uD83D\uDD12 Demo session - keeping basic security only');\n await this.calculateAndReportSecurityLevel();\n this.notifySecurityUpgrade(1);\n return;\n }\n\n const checkStability = () => {\n const isStable = this.isConnected() && \n this.isVerified && \n this.connectionAttempts === 0 && \n this.messageQueue.length === 0 &&\n this.peerConnection?.connectionState === 'connected';\n return isStable;\n };\n \n this._secureLog('info', `\uD83D\uDD12 ${this.currentSessionType} session - starting graduated security activation`);\n await this.calculateAndReportSecurityLevel();\n this.notifySecurityUpgrade(1);\n \n if (this.currentSecurityLevel === 'enhanced' || this.currentSecurityLevel === 'maximum') {\n setTimeout(async () => {\n if (checkStability()) {\n console.log('\u2705 Activating Stage 2 for paid session');\n this.enableStage2Security();\n await this.calculateAndReportSecurityLevel(); \n \n // For maximum sessions, turn on Stage 3 and 4\n if (this.currentSecurityLevel === 'maximum') {\n setTimeout(async () => {\n if (checkStability()) {\n console.log('\u2705 Activating Stage 3 for premium session');\n this.enableStage3Security();\n await this.calculateAndReportSecurityLevel();\n \n setTimeout(async () => {\n if (checkStability()) {\n console.log('\u2705 Activating Stage 4 for premium session');\n this.enableStage4Security();\n await this.calculateAndReportSecurityLevel();\n }\n }, 20000);\n }\n }, 15000);\n }\n }\n }, 10000);\n }\n }\n\n // ============================================\n // CONNECTION MANAGEMENT WITH ENHANCED SECURITY\n // ============================================\n\n async establishConnection() {\n try {\n // Initialize enhanced security features\n await this.initializeEnhancedSecurity();\n \n // Start fake traffic generation\n if (this.fakeTrafficConfig.enabled) {\n this.startFakeTrafficGeneration();\n }\n \n // Initialize decoy channels\n if (this.decoyChannelConfig.enabled) {\n this.initializeDecoyChannels();\n }\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to establish enhanced connection:', { errorType: error?.constructor?.name || 'Unknown' });\n // Do not close the connection on setup errors \u2014 just log and continue\n this.onStatusChange('disconnected');\n throw error;\n }\n }\n\n disconnect() {\n try {\n console.log('\uD83D\uDD0C Disconnecting WebRTC Manager...');\n \n // Cleanup file transfer system\n if (this.fileTransferSystem) {\n console.log('\uD83E\uDDF9 Cleaning up file transfer system during disconnect...');\n this.fileTransferSystem.cleanup();\n this.fileTransferSystem = null;\n }\n \n // Stop fake traffic generation\n this.stopFakeTrafficGeneration();\n \n // Stop decoy traffic\n for (const [channelName, timer] of this.decoyTimers.entries()) {\n clearTimeout(timer);\n }\n this.decoyTimers.clear();\n \n // Close decoy channels\n for (const [channelName, channel] of this.decoyChannels.entries()) {\n if (channel.readyState === 'open') {\n channel.close();\n }\n }\n this.decoyChannels.clear();\n \n // Clean up packet buffer\n this.packetBuffer.clear();\n \n // Clean up chunk queue\n this.chunkQueue = [];\n \n // Wipe ephemeral keys for PFS on disconnect\n this._wipeEphemeralKeys();\n \n // Hard wipe old keys for PFS\n this._hardWipeOldKeys();\n\n // Clear verification states\n this._clearVerificationStates();\n\n } catch (error) {\n this._secureLog('error', '\u274C Error during enhanced disconnect:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }\n\n /**\n * Clear all verification states and data\n * Called when verification is rejected or connection is terminated\n */\n _clearVerificationStates() {\n try {\n console.log('\uD83E\uDDF9 Clearing verification states...');\n \n // Clear verification states\n this.localVerificationConfirmed = false;\n this.remoteVerificationConfirmed = false;\n this.bothVerificationsConfirmed = false;\n this.isVerified = false;\n this.verificationCode = null;\n this.pendingSASCode = null;\n \n // Clear key fingerprint and connection data\n this.keyFingerprint = null;\n this.expectedDTLSFingerprint = null;\n this.connectionId = null;\n \n // Clear processed message IDs\n this.processedMessageIds.clear();\n \n // Reset notification flags\n this.verificationNotificationSent = false;\n this.verificationInitiationSent = false;\n \n console.log('\u2705 Verification states cleared successfully');\n \n } catch (error) {\n this._secureLog('error', '\u274C Error clearing verification states:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }\n\n // Start periodic cleanup for rate limiting and security\n startPeriodicCleanup() {\n // Cleanup moved to unified scheduler\n this._secureLog('info', '\uD83D\uDD27 Periodic cleanup moved to unified scheduler');\n }\n\n // Calculate current security level with real verification\n async calculateSecurityLevel() {\n return await window.EnhancedSecureCryptoUtils.calculateSecurityLevel(this);\n }\n\n // PFS: Check if key rotation is needed\n shouldRotateKeys() {\n if (!this.isConnected() || !this.isVerified) {\n return false;\n }\n \n const now = Date.now();\n const timeSinceLastRotation = now - this.lastKeyRotation;\n \n // Rotate keys every 5 minutes or after 100 messages\n return timeSinceLastRotation > this.keyRotationInterval || \n this.messageCounter % 100 === 0;\n }\n\n // PFS: Rotate encryption keys for Perfect Forward Secrecy\n async rotateKeys() {\n return this._withMutex('keyOperation', async (operationId) => {\n this._secureLog('info', '\uD83D\uDD04 Starting key rotation with mutex', {\n operationId: operationId\n });\n \n // Validate state inside the critical section\n if (!this.isConnected() || !this.isVerified) {\n this._secureLog('warn', '\u26A0\uFE0F Key rotation aborted - connection not ready', {\n operationId: operationId,\n isConnected: this.isConnected(),\n isVerified: this.isVerified\n });\n return false;\n }\n \n // Ensure rotation is not already in progress\n if (this._keySystemState.isRotating) {\n this._secureLog('warn', '\u26A0\uFE0F Key rotation already in progress', {\n operationId: operationId\n });\n return false;\n }\n \n try {\n // Set rotation flag\n this._keySystemState.isRotating = true;\n this._keySystemState.lastOperation = 'rotation';\n this._keySystemState.lastOperationTime = Date.now();\n \n // Send rotation signal to peer\n const rotationSignal = {\n type: 'key_rotation_signal',\n newVersion: this.currentKeyVersion + 1,\n timestamp: Date.now(),\n operationId: operationId\n };\n \n if (this.dataChannel && this.dataChannel.readyState === 'open') {\n this.dataChannel.send(JSON.stringify(rotationSignal));\n } else {\n throw new Error('Data channel not ready for key rotation');\n }\n \n // Perform hard wipe of old keys for real PFS\n this._hardWipeOldKeys();\n \n // Wait for peer confirmation\n return new Promise((resolve) => {\n this.pendingRotation = {\n newVersion: this.currentKeyVersion + 1,\n operationId: operationId,\n resolve: resolve,\n timeout: setTimeout(() => {\n this._secureLog('error', '\u26A0\uFE0F Key rotation timeout', {\n operationId: operationId\n });\n this._keySystemState.isRotating = false;\n this.pendingRotation = null;\n resolve(false);\n }, 10000) // 10 seconds timeout\n };\n });\n \n } catch (error) {\n this._secureLog('error', '\u274C Key rotation failed in critical section', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n this._keySystemState.isRotating = false;\n return false;\n }\n }, 10000); // 10 seconds timeout for the entire operation\n }\n\n // Real PFS - Clean up old keys with hard wipe\n cleanupOldKeys() {\n const now = Date.now();\n const maxKeyAge = EnhancedSecureWebRTCManager.LIMITS.MAX_KEY_AGE; // 15 minutes - keys older than this are deleted\n \n let wipedKeysCount = 0;\n \n for (const [version, keySet] of this.oldKeys.entries()) {\n if (now - keySet.timestamp > maxKeyAge) {\n // Hard wipe old keys before deletion\n if (keySet.encryptionKey) {\n this._secureWipeMemory(keySet.encryptionKey, 'pfs_cleanup_wipe');\n }\n if (keySet.macKey) {\n this._secureWipeMemory(keySet.macKey, 'pfs_cleanup_wipe');\n }\n if (keySet.metadataKey) {\n this._secureWipeMemory(keySet.metadataKey, 'pfs_cleanup_wipe');\n }\n \n // Clear references\n keySet.encryptionKey = null;\n keySet.macKey = null;\n keySet.metadataKey = null;\n keySet.keyFingerprint = null;\n \n this.oldKeys.delete(version);\n wipedKeysCount++;\n \n this._secureLog('info', '\uD83E\uDDF9 Old PFS keys hard wiped and cleaned up', {\n version: version,\n age: Math.round((now - keySet.timestamp) / 1000) + 's',\n timestamp: Date.now()\n });\n }\n }\n \n if (wipedKeysCount > 0) {\n this._secureLog('info', `\u2705 PFS cleanup completed: ${wipedKeysCount} keys hard wiped`, {\n timestamp: Date.now()\n });\n }\n }\n\n // PFS: Get keys for specific version (for decryption)\n getKeysForVersion(version) {\n // First, we check the old keys (including version 0).\n const oldKeySet = this.oldKeys.get(version);\n if (oldKeySet && oldKeySet.encryptionKey && oldKeySet.macKey && oldKeySet.metadataKey) {\n return {\n encryptionKey: oldKeySet.encryptionKey,\n macKey: oldKeySet.macKey,\n metadataKey: oldKeySet.metadataKey\n };\n }\n \n // If this is the current version, return the current keys.\n if (version === this.currentKeyVersion) {\n if (this.encryptionKey && this.macKey && this.metadataKey) {\n return {\n encryptionKey: this.encryptionKey,\n macKey: this.macKey,\n metadataKey: this.metadataKey\n };\n }\n }\n \n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'No valid keys found for version', {\n requestedVersion: version,\n currentVersion: this.currentKeyVersion,\n availableVersions: Array.from(this.oldKeys.keys())\n });\n \n return null;\n }\n\n createPeerConnection() {\n const config = {\n iceServers: [\n { urls: 'stun:stun.l.google.com:19302' },\n { urls: 'stun:stun1.l.google.com:19302' },\n { urls: 'stun:stun2.l.google.com:19302' },\n { urls: 'stun:stun3.l.google.com:19302' },\n { urls: 'stun:stun4.l.google.com:19302' }\n ],\n iceCandidatePoolSize: 10,\n bundlePolicy: 'balanced'\n };\n\n this.peerConnection = new RTCPeerConnection(config);\n\n this.peerConnection.onconnectionstatechange = () => {\n const state = this.peerConnection.connectionState;\n console.log('Connection state:', state);\n \n if (state === 'connected' && !this.isVerified) {\n this.onStatusChange('verifying');\n } else if (state === 'connected' && this.isVerified) {\n this.onStatusChange('connected');\n } else if (state === 'disconnected' || state === 'closed') {\n // If this is an intentional disconnect, clear immediately.\n if (this.intentionalDisconnect) {\n this.onStatusChange('disconnected');\n setTimeout(() => this.disconnect(), 100);\n } else {\n this.onStatusChange('disconnected');\n // Clear verification states on unexpected disconnect\n this._clearVerificationStates();\n }\n } else if (state === 'failed') {\n // Do not auto-reconnect to avoid closing the session on errors\n this.onStatusChange('disconnected');\n // if (!this.intentionalDisconnect && this.connectionAttempts < this.maxConnectionAttempts) {\n // this.connectionAttempts++;\n // setTimeout(() => this.retryConnection(), 2000);\n // } else {\n // this.onStatusChange('disconnected');\n // // Do not call cleanupConnection automatically for 'failed'\n // // to avoid closing the session on connection errors\n // }\n } else {\n this.onStatusChange(state);\n }\n };\n\n this.peerConnection.ondatachannel = (event) => {\n console.log('\uD83D\uDD17 Data channel received:', {\n channelLabel: event.channel.label,\n channelState: event.channel.readyState,\n isInitiator: this.isInitiator,\n channelId: event.channel.id,\n protocol: event.channel.protocol\n });\n \n // CRITICAL: Store the received data channel\n if (event.channel.label === 'securechat') {\n console.log('\uD83D\uDD17 MAIN DATA CHANNEL RECEIVED (answerer side)');\n this.dataChannel = event.channel;\n this.setupDataChannel(event.channel);\n } else {\n console.log('\uD83D\uDD17 ADDITIONAL DATA CHANNEL RECEIVED:', event.channel.label);\n // Handle additional channels (heartbeat, etc.)\n if (event.channel.label === 'heartbeat') {\n this.heartbeatChannel = event.channel;\n }\n }\n };\n }\n\n setupDataChannel(channel) {\n console.log('\uD83D\uDD17 setupDataChannel called:', {\n channelLabel: channel.label,\n channelState: channel.readyState,\n isInitiator: this.isInitiator,\n isVerified: this.isVerified\n });\n\n this.dataChannel = channel;\n\n this.dataChannel.onopen = async () => {\n console.log('\uD83D\uDD17 Data channel opened:', {\n isInitiator: this.isInitiator,\n isVerified: this.isVerified,\n dataChannelState: this.dataChannel.readyState,\n dataChannelLabel: this.dataChannel.label\n });\n // Configure backpressure for large transfers\n try {\n if (this.dataChannel && typeof this.dataChannel.bufferedAmountLowThreshold === 'number') {\n // 1 MB threshold for bufferedamountlow event\n this.dataChannel.bufferedAmountLowThreshold = 1024 * 1024;\n }\n } catch (e) {\n // ignore\n }\n \n try {\n await this.establishConnection();\n\n this.initializeFileTransfer();\n \n } catch (error) {\n this._secureLog('error', '\u274C Error in establishConnection:', { errorType: error?.constructor?.name || 'Unknown' });\n // Continue despite errors\n }\n \n // CRITICAL: Send pending SAS code if available\n if (this.pendingSASCode && this.dataChannel && this.dataChannel.readyState === 'open') {\n try {\n const sasPayload = {\n type: 'sas_code',\n data: {\n code: this.pendingSASCode,\n timestamp: Date.now(),\n verificationMethod: 'SAS',\n securityLevel: 'MITM_PROTECTION_REQUIRED'\n }\n };\n console.log('\uD83D\uDCE4 Sending pending SAS code to Answer side:', this.pendingSASCode);\n this.dataChannel.send(JSON.stringify(sasPayload));\n this.pendingSASCode = null; // Clear after sending\n } catch (error) {\n console.error('Failed to send pending SAS code to Answer side:', error);\n }\n } else if (this.pendingSASCode) {\n console.log('\u26A0\uFE0F Cannot send SAS code - dataChannel not ready:', {\n hasDataChannel: !!this.dataChannel,\n readyState: this.dataChannel?.readyState,\n pendingSASCode: this.pendingSASCode\n });\n }\n \n if (this.isVerified) {\n this.onStatusChange('connected');\n this.processMessageQueue();\n \n setTimeout(async () => {\n await this.calculateAndReportSecurityLevel();\n this.autoEnableSecurityFeatures();\n this.notifySecurityUpdate();\n }, 500);\n } else {\n this.onStatusChange('verifying');\n this.initiateVerification();\n }\n this.startHeartbeat();\n };\n\n this.dataChannel.onclose = () => {\n if (!this.intentionalDisconnect) {\n this.onStatusChange('disconnected');\n // Clear verification states on data channel close\n this._clearVerificationStates();\n \n if (!this.connectionClosedNotificationSent) {\n this.connectionClosedNotificationSent = true;\n this.deliverMessageToUI('\uD83D\uDD0C Enhanced secure connection closed. Check connection status.', 'system');\n }\n } else {\n this.onStatusChange('disconnected');\n // Clear verification states on intentional disconnect\n this._clearVerificationStates();\n \n if (!this.connectionClosedNotificationSent) {\n this.connectionClosedNotificationSent = true;\n this.deliverMessageToUI('\uD83D\uDD0C Enhanced secure connection closed', 'system');\n }\n }\n \n // Wipe ephemeral keys when session ends for PFS\n this._wipeEphemeralKeys();\n \n this.stopHeartbeat();\n this.isVerified = false;\n };\n\n // FIX 2: Remove mutex entirely from message processing path\n this.dataChannel.onmessage = async (event) => {\n try {\n console.log('\uD83D\uDCE8 Raw message received:', {\n dataType: typeof event.data,\n dataLength: event.data?.length || event.data?.byteLength || 0,\n isString: typeof event.data === 'string'\n });\n\n // IMPORTANT: Process ALL messages WITHOUT mutex\n if (typeof event.data === 'string') {\n try {\n const parsed = JSON.parse(event.data);\n console.log('\uD83D\uDCE8 Parsed message:', {\n type: parsed.type,\n hasData: !!parsed.data,\n timestamp: parsed.timestamp\n });\n \n // ============================================\n // CRITICAL: FILE MESSAGES (WITHOUT MUTEX)\n // ============================================\n \n const fileMessageTypes = [\n 'file_transfer_start',\n 'file_transfer_response', \n 'file_chunk',\n 'chunk_confirmation',\n 'file_transfer_complete',\n 'file_transfer_error'\n ];\n \n if (parsed.type && fileMessageTypes.includes(parsed.type)) {\n console.log('\uD83D\uDCC1 File message intercepted at WebRTC level:', parsed.type);\n\n if (!this.fileTransferSystem) {\n try {\n if (this.isVerified && this.dataChannel && this.dataChannel.readyState === 'open') {\n this.initializeFileTransfer();\n\n let attempts = 0;\n const maxAttempts = 30;\n while (!this.fileTransferSystem && attempts < maxAttempts) {\n await new Promise(resolve => setTimeout(resolve, 100));\n attempts++;\n }\n }\n } catch (initError) {\n this._secureLog('error', '\u274C Failed to initialize file transfer system for receiver:', { errorType: initError?.constructor?.name || 'Unknown' });\n }\n }\n\n if (this.fileTransferSystem) {\n console.log('\uD83D\uDCC1 Forwarding to local file transfer system:', parsed.type);\n await this.fileTransferSystem.handleFileMessage(parsed);\n return;\n }\n // Attempt lazy initialization on receiver side\n this._secureLog('warn', '\u26A0\uFE0F File transfer system not ready, attempting lazy init...');\n try {\n await this._ensureFileTransferReady();\n if (this.fileTransferSystem) {\n await this.fileTransferSystem.handleFileMessage(parsed);\n return;\n }\n } catch (e) {\n this._secureLog('error', '\u274C Lazy init of file transfer failed:', { errorType: e?.message || e?.constructor?.name || 'Unknown' });\n }\n this._secureLog('error', '\u274C No file transfer system available for:', { errorType: parsed.type?.constructor?.name || 'Unknown' });\n return; // IMPORTANT: Do not process further\n }\n \n // ============================================\n // SYSTEM MESSAGES (WITHOUT MUTEX)\n // ============================================\n \n if (parsed.type && ['heartbeat', 'verification', 'verification_response', 'verification_confirmed', 'verification_both_confirmed', 'sas_code', 'peer_disconnect', 'security_upgrade'].includes(parsed.type)) {\n console.log('\uD83D\uDD27 System message detected:', parsed.type);\n this.handleSystemMessage(parsed);\n return;\n }\n \n // ============================================\n // REGULAR USER MESSAGES (WITHOUT MUTEX)\n // ============================================\n \n if (parsed.type === 'message' && parsed.data) {\n console.log('\uD83D\uDCDD User message detected:', parsed.data.substring(0, 50));\n if (this.onMessage) {\n this.deliverMessageToUI(parsed.data, 'received');\n }\n return;\n }\n \n // ============================================\n // ENHANCED MESSAGES (WITHOUT MUTEX)\n // ============================================\n \n if (parsed.type === 'enhanced_message' && parsed.data) {\n console.log('\uD83D\uDD10 Enhanced message detected, processing...');\n await this._processEnhancedMessageWithoutMutex(parsed);\n return;\n }\n \n // ============================================\n // FAKE MESSAGES (WITHOUT MUTEX)\n // ============================================\n \n if (parsed.type === 'fake') {\n console.log('\uD83C\uDFAD Fake message blocked:', parsed.pattern);\n return;\n }\n \n // ============================================\n // UNKNOWN MESSAGE TYPES\n // ============================================\n \n console.log('\u2753 Unknown message type:', parsed.type);\n \n } catch (jsonError) {\n // Not JSON \u2014 treat as regular text message\n console.log('\uD83D\uDCC4 Non-JSON message detected, treating as text');\n if (this.onMessage) {\n this.deliverMessageToUI(event.data, 'received');\n }\n return;\n }\n } else if (event.data instanceof ArrayBuffer) {\n // Binary data \u2014 process WITHOUT mutex\n console.log('\uD83D\uDD22 Binary data received, processing...');\n await this._processBinaryDataWithoutMutex(event.data);\n } else {\n console.log('\u2753 Unknown data type:', typeof event.data);\n }\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to process message in onmessage:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n };\n }\n // FIX 4: New method for processing binary data WITHOUT mutex\n async _processBinaryDataWithoutMutex(data) {\n try {\n console.log('\uD83D\uDD22 Processing binary data without mutex...');\n \n // Apply security layers WITHOUT mutex\n let processedData = data;\n \n // Nested Encryption Removal (if enabled)\n if (this.securityFeatures.hasNestedEncryption && \n this.nestedEncryptionKey && \n processedData instanceof ArrayBuffer &&\n processedData.byteLength > 12) {\n \n try {\n processedData = await this.removeNestedEncryption(processedData);\n } catch (error) {\n this._secureLog('warn', '\u26A0\uFE0F Nested decryption failed, continuing with original data');\n }\n }\n \n // Packet Padding Removal (if enabled)\n if (this.securityFeatures.hasPacketPadding && processedData instanceof ArrayBuffer) {\n try {\n processedData = this.removePacketPadding(processedData);\n } catch (error) {\n this._secureLog('warn', '\u26A0\uFE0F Packet padding removal failed, continuing with original data');\n }\n }\n \n // Anti-Fingerprinting Removal (if enabled)\n if (this.securityFeatures.hasAntiFingerprinting && processedData instanceof ArrayBuffer) {\n try {\n processedData = this.removeAntiFingerprinting(processedData);\n } catch (error) {\n this._secureLog('warn', '\u26A0\uFE0F Anti-fingerprinting removal failed, continuing with original data');\n }\n }\n \n // Convert to text\n if (processedData instanceof ArrayBuffer) {\n const textData = new TextDecoder().decode(processedData);\n \n // Check for fake messages\n try {\n const content = JSON.parse(textData);\n if (content.type === 'fake' || content.isFakeTraffic === true) {\n console.log(`\uD83C\uDFAD BLOCKED: Binary fake message: ${content.pattern || 'unknown'}`);\n return;\n }\n } catch (e) {\n // Not JSON \u2014 fine for plain text\n }\n \n // Deliver message to user\n if (this.onMessage) {\n this.deliverMessageToUI(textData, 'received');\n }\n }\n \n } catch (error) {\n this._secureLog('error', '\u274C Error processing binary data:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }\n // FIX 3: New method for processing enhanced messages WITHOUT mutex\n async _processEnhancedMessageWithoutMutex(parsedMessage) {\n try {\n console.log('\uD83D\uDD10 Processing enhanced message without mutex...');\n \n if (!this.encryptionKey || !this.macKey || !this.metadataKey) {\n this._secureLog('error', '\u274C Missing encryption keys for enhanced message');\n return;\n }\n \n const decryptedResult = await window.EnhancedSecureCryptoUtils.decryptMessage(\n parsedMessage.data,\n this.encryptionKey,\n this.macKey,\n this.metadataKey\n );\n \n if (decryptedResult && decryptedResult.message) {\n console.log('\u2705 Enhanced message decrypted successfully');\n \n // Try parsing JSON and showing nested text if it's a chat message\n try {\n const decryptedContent = JSON.parse(decryptedResult.message);\n if (decryptedContent.type === 'fake' || decryptedContent.isFakeTraffic === true) {\n console.log(`\uFFFD\uFFFD BLOCKED: Encrypted fake message: ${decryptedContent.pattern || 'unknown'}`);\n return;\n }\n if (decryptedContent && decryptedContent.type === 'message' && typeof decryptedContent.data === 'string') {\n if (this.onMessage) {\n this.deliverMessageToUI(decryptedContent.data, 'received');\n }\n return;\n }\n } catch (e) {\n // Not JSON \u2014 fine for plain text\n }\n \n // Otherwise pass as-is\n if (this.onMessage) {\n this.deliverMessageToUI(decryptedResult.message, 'received');\n }\n } else {\n this._secureLog('warn', '\u26A0\uFE0F No message content in decrypted result');\n }\n \n } catch (error) {\n this._secureLog('error', '\u274C Error processing enhanced message:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }\n /**\n * Creates a unique ID for an operation\n */\n _generateOperationId() {\n return `op_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n /**\n * Atomic mutex acquisition with enhanced race condition protection\n */\n async _acquireMutex(mutexName, operationId, timeout = 5000) {\n // Build correct mutex property name\n const mutexPropertyName = `_${mutexName}Mutex`;\n const mutex = this[mutexPropertyName];\n \n if (!mutex) {\n this._secureLog('error', `\u274C Unknown mutex: ${mutexName}`, {\n mutexPropertyName: mutexPropertyName,\n availableMutexes: this._getAvailableMutexes(),\n operationId: operationId\n });\n throw new Error(`Unknown mutex: ${mutexName}. Available: ${this._getAvailableMutexes().join(', ')}`);\n }\n \n // Validate operation ID\n if (!operationId || typeof operationId !== 'string') {\n throw new Error('Invalid operation ID for mutex acquisition');\n }\n \n return new Promise((resolve, reject) => {\n // Atomic lock attempt with immediate state check\n const attemptLock = () => {\n // Check if mutex is already locked by this operation\n if (mutex.lockId === operationId) {\n this._secureLog('warn', `\u26A0\uFE0F Mutex '${mutexName}' already locked by same operation`, {\n operationId: operationId\n });\n resolve();\n return;\n }\n \n // Atomic check and lock operation\n if (!mutex.locked) {\n // Set lock state atomically\n mutex.locked = true;\n mutex.lockId = operationId;\n mutex.lockTime = Date.now();\n \n this._secureLog('debug', `\uD83D\uDD12 Mutex '${mutexName}' acquired atomically`, {\n operationId: operationId,\n lockTime: mutex.lockTime\n });\n \n // Set timeout for automatic release with enhanced validation\n mutex.lockTimeout = setTimeout(() => {\n // Enhanced timeout handling with state validation\n this._handleMutexTimeout(mutexName, operationId, timeout);\n }, timeout);\n \n resolve();\n } else {\n // Add to queue with timeout\n const queueItem = { \n resolve, \n reject, \n operationId,\n timestamp: Date.now(),\n timeout: setTimeout(() => {\n // Remove from queue on timeout\n const index = mutex.queue.findIndex(item => item.operationId === operationId);\n if (index !== -1) {\n mutex.queue.splice(index, 1);\n reject(new Error(`Mutex acquisition timeout for '${mutexName}'`));\n }\n }, timeout)\n };\n \n mutex.queue.push(queueItem);\n \n this._secureLog('debug', `\u23F3 Operation queued for mutex '${mutexName}'`, {\n operationId: operationId,\n queueLength: mutex.queue.length,\n currentLockId: mutex.lockId\n });\n }\n };\n \n // Execute lock attempt immediately\n attemptLock();\n });\n }\n\n /**\n * Enhanced mutex release with strict validation and error handling\n */\n _releaseMutex(mutexName, operationId) {\n // Validate input parameters\n if (!mutexName || typeof mutexName !== 'string') {\n throw new Error('Invalid mutex name provided for release');\n }\n \n if (!operationId || typeof operationId !== 'string') {\n throw new Error('Invalid operation ID provided for mutex release');\n }\n \n // Build correct mutex property name\n const mutexPropertyName = `_${mutexName}Mutex`;\n const mutex = this[mutexPropertyName];\n \n if (!mutex) {\n this._secureLog('error', `\u274C Unknown mutex for release: ${mutexName}`, {\n mutexPropertyName: mutexPropertyName,\n availableMutexes: this._getAvailableMutexes(),\n operationId: operationId\n });\n throw new Error(`Unknown mutex for release: ${mutexName}`);\n }\n \n // Strict validation of lock ownership\n if (mutex.lockId !== operationId) {\n this._secureLog('error', `\u274C CRITICAL: Invalid mutex release attempt - potential race condition`, {\n mutexName: mutexName,\n expectedLockId: mutex.lockId,\n providedOperationId: operationId,\n mutexState: {\n locked: mutex.locked,\n lockTime: mutex.lockTime,\n queueLength: mutex.queue.length\n }\n });\n \n // Throw error instead of silent failure\n throw new Error(`Invalid mutex release attempt for '${mutexName}': expected '${mutex.lockId}', got '${operationId}'`);\n }\n \n // Validate mutex is actually locked\n if (!mutex.locked) {\n this._secureLog('error', `\u274C CRITICAL: Attempting to release unlocked mutex`, {\n mutexName: mutexName,\n operationId: operationId,\n mutexState: {\n locked: mutex.locked,\n lockId: mutex.lockId,\n lockTime: mutex.lockTime\n }\n });\n throw new Error(`Attempting to release unlocked mutex: ${mutexName}`);\n }\n \n try {\n // Clear timeout first\n if (mutex.lockTimeout) {\n clearTimeout(mutex.lockTimeout);\n mutex.lockTimeout = null;\n }\n \n // Calculate lock duration for monitoring\n const lockDuration = mutex.lockTime ? Date.now() - mutex.lockTime : 0;\n \n // Atomic release with state validation\n mutex.locked = false;\n mutex.lockId = null;\n mutex.lockTime = null;\n \n this._secureLog('debug', `\uD83D\uDD13 Mutex released successfully: ${mutexName}`, {\n operationId: operationId,\n lockDuration: lockDuration,\n queueLength: mutex.queue.length\n });\n \n // Process next in queue with enhanced error handling\n this._processNextInQueue(mutexName);\n \n } catch (error) {\n // If queue processing fails, ensure mutex is still released\n this._secureLog('error', `\u274C Error during mutex release queue processing`, {\n mutexName: mutexName,\n operationId: operationId,\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n \n // Ensure mutex is released even if queue processing fails\n mutex.locked = false;\n mutex.lockId = null;\n mutex.lockTime = null;\n mutex.lockTimeout = null;\n \n throw error;\n }\n }\n\n /**\n * Enhanced queue processing with comprehensive error handling\n */\n _processNextInQueue(mutexName) {\n const mutex = this[`_${mutexName}Mutex`];\n \n if (!mutex) {\n this._secureLog('error', `\u274C Mutex not found for queue processing: ${mutexName}`);\n return;\n }\n \n if (mutex.queue.length === 0) {\n return;\n }\n \n // Validate mutex state before processing queue\n if (mutex.locked) {\n this._secureLog('warn', `\u26A0\uFE0F Mutex '${mutexName}' is still locked, skipping queue processing`, {\n lockId: mutex.lockId,\n queueLength: mutex.queue.length\n });\n return;\n }\n \n // Get next item from queue atomically with validation\n const nextItem = mutex.queue.shift();\n \n if (!nextItem) {\n this._secureLog('warn', `\u26A0\uFE0F Empty queue item for mutex '${mutexName}'`);\n return;\n }\n \n // Validate queue item structure\n if (!nextItem.operationId || !nextItem.resolve || !nextItem.reject) {\n this._secureLog('error', `\u274C Invalid queue item structure for mutex '${mutexName}'`, {\n hasOperationId: !!nextItem.operationId,\n hasResolve: !!nextItem.resolve,\n hasReject: !!nextItem.reject\n });\n return;\n }\n \n try {\n // Clear timeout for this item\n if (nextItem.timeout) {\n clearTimeout(nextItem.timeout);\n }\n \n // Attempt to acquire lock for next item\n this._secureLog('debug', `\uD83D\uDD04 Processing next operation in queue for mutex '${mutexName}'`, {\n operationId: nextItem.operationId,\n queueRemaining: mutex.queue.length,\n timestamp: Date.now()\n });\n \n // Retry lock acquisition for queued operation with enhanced error handling\n setTimeout(async () => {\n try {\n await this._acquireMutex(mutexName, nextItem.operationId, 5000);\n \n this._secureLog('debug', `\u2705 Queued operation acquired mutex '${mutexName}'`, {\n operationId: nextItem.operationId,\n acquisitionTime: Date.now()\n });\n \n nextItem.resolve();\n \n } catch (error) {\n this._secureLog('error', `\u274C Queued operation failed to acquire mutex '${mutexName}'`, {\n operationId: nextItem.operationId,\n errorType: error.constructor.name,\n errorMessage: error.message,\n timestamp: Date.now()\n });\n \n // Reject with detailed error information\n nextItem.reject(new Error(`Queue processing failed for '${mutexName}': ${error.message}`));\n \n // Continue processing queue even if one item fails\n setTimeout(() => {\n this._processNextInQueue(mutexName);\n }, 50);\n }\n }, 10); // Small delay to prevent immediate re-acquisition\n \n } catch (error) {\n this._secureLog('error', `\u274C Critical error during queue processing for mutex '${mutexName}'`, {\n operationId: nextItem.operationId,\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n \n // Reject the operation and continue processing\n try {\n nextItem.reject(new Error(`Queue processing critical error: ${error.message}`));\n } catch (rejectError) {\n this._secureLog('error', `\u274C Failed to reject queue item`, {\n originalError: error.message,\n rejectError: rejectError.message\n });\n }\n \n // Continue processing remaining queue items\n setTimeout(() => {\n this._processNextInQueue(mutexName);\n }, 100);\n }\n }\n\n _getAvailableMutexes() {\n const mutexes = [];\n const propertyNames = Object.getOwnPropertyNames(this);\n \n for (const prop of propertyNames) {\n if (prop.endsWith('Mutex') && prop.startsWith('_')) {\n // Extract mutex name without prefix/suffix\n const mutexName = prop.slice(1, -5); // Remove '_' prefix and 'Mutex' suffix\n mutexes.push(mutexName);\n }\n }\n \n return mutexes;\n }\n\n /**\n * Enhanced mutex execution with atomic operations\n */\n async _withMutex(mutexName, operation, timeout = 5000) {\n const operationId = this._generateOperationId();\n \n // Validate mutex system before operation\n if (!this._validateMutexSystem()) {\n this._secureLog('error', '\u274C Mutex system not properly initialized', {\n operationId: operationId,\n mutexName: mutexName\n });\n throw new Error('Mutex system not properly initialized. Call _initializeMutexSystem() first.');\n }\n \n // Get mutex reference with validation\n const mutex = this[`_${mutexName}Mutex`];\n if (!mutex) {\n throw new Error(`Mutex '${mutexName}' not found`);\n }\n \n let mutexAcquired = false;\n \n try {\n // Atomic mutex acquisition with timeout\n await this._acquireMutex(mutexName, operationId, timeout);\n mutexAcquired = true;\n \n // Increment operation counter atomically\n const counterKey = `${mutexName}Operations`;\n if (this._operationCounters && this._operationCounters[counterKey] !== undefined) {\n this._operationCounters[counterKey]++;\n }\n \n // Execute operation with enhanced error handling\n const result = await operation(operationId);\n \n // Validate result before returning\n if (result === undefined && operation.name !== 'cleanup') {\n this._secureLog('warn', '\u26A0\uFE0F Mutex operation returned undefined result', {\n operationId: operationId,\n mutexName: mutexName,\n operationName: operation.name\n });\n }\n \n return result;\n \n } catch (error) {\n // Enhanced error logging with context\n this._secureLog('error', '\u274C Error in mutex operation', {\n operationId: operationId,\n mutexName: mutexName,\n errorType: error.constructor.name,\n errorMessage: error.message,\n mutexAcquired: mutexAcquired,\n mutexState: mutex ? {\n locked: mutex.locked,\n lockId: mutex.lockId,\n queueLength: mutex.queue.length\n } : 'null'\n });\n \n // If this is a key operation error, trigger emergency recovery\n if (mutexName === 'keyOperation') {\n this._handleKeyOperationError(error, operationId);\n }\n \n // Trigger emergency unlock for critical mutex errors\n if (error.message.includes('timeout') || error.message.includes('race condition')) {\n this._emergencyUnlockAllMutexes('errorHandler');\n }\n \n throw error;\n } finally {\n // Always release mutex in finally block with validation\n if (mutexAcquired) {\n try {\n await this._releaseMutex(mutexName, operationId);\n \n // Verify mutex was properly released\n if (mutex.locked && mutex.lockId === operationId) {\n this._secureLog('error', '\u274C Mutex release verification failed', {\n operationId: operationId,\n mutexName: mutexName\n });\n // Force release as fallback\n mutex.locked = false;\n mutex.lockId = null;\n mutex.lockTimeout = null;\n }\n \n } catch (releaseError) {\n this._secureLog('error', '\u274C Error releasing mutex in finally block', {\n operationId: operationId,\n mutexName: mutexName,\n releaseErrorType: releaseError.constructor.name,\n releaseErrorMessage: releaseError.message\n });\n \n // Force release on error\n mutex.locked = false;\n mutex.lockId = null;\n mutex.lockTimeout = null;\n }\n }\n }\n }\n\n _validateMutexSystem() {\n const requiredMutexes = ['keyOperation', 'cryptoOperation', 'connectionOperation'];\n \n for (const mutexName of requiredMutexes) {\n const mutexPropertyName = `_${mutexName}Mutex`;\n const mutex = this[mutexPropertyName];\n \n if (!mutex || typeof mutex !== 'object') {\n this._secureLog('error', `\u274C Missing or invalid mutex: ${mutexName}`, {\n mutexPropertyName: mutexPropertyName,\n mutexType: typeof mutex\n });\n return false;\n }\n \n // Validate mutex structure\n const requiredProps = ['locked', 'queue', 'lockId', 'lockTimeout'];\n for (const prop of requiredProps) {\n if (!(prop in mutex)) {\n this._secureLog('error', `\u274C Mutex ${mutexName} missing property: ${prop}`);\n return false;\n }\n }\n }\n \n return true;\n }\n\n /**\n * Enhanced emergency recovery of the mutex system\n */\n _emergencyRecoverMutexSystem() {\n this._secureLog('warn', '\uD83D\uDEA8 Emergency mutex system recovery initiated');\n \n try {\n // Emergency unlock all mutexes first\n this._emergencyUnlockAllMutexes('emergencyRecovery');\n \n // Force re-initialize the system\n this._initializeMutexSystem();\n \n // Validate recovery success\n if (!this._validateMutexSystem()) {\n throw new Error('Mutex system validation failed after recovery');\n }\n \n this._secureLog('info', '\u2705 Mutex system recovered successfully with validation');\n return true;\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to recover mutex system', {\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n \n // Last resort - force re-initialization\n try {\n this._initializeMutexSystem();\n this._secureLog('warn', '\u26A0\uFE0F Forced mutex system re-initialization completed');\n return true;\n } catch (reinitError) {\n this._secureLog('error', '\u274C CRITICAL: Forced re-initialization also failed', {\n originalError: error.message,\n reinitError: reinitError.message\n });\n return false;\n }\n }\n }\n\n /**\n * Atomic key generation with race condition protection\n */\n async _generateEncryptionKeys() {\n return this._withMutex('keyOperation', async (operationId) => {\n this._secureLog('info', '\uD83D\uDD11 Generating encryption keys with atomic mutex', {\n operationId: operationId\n });\n \n // Atomic state check and update using mutex lock\n const currentState = this._keySystemState;\n \n // Atomic check - if already initializing, wait or fail\n if (currentState.isInitializing) {\n this._secureLog('warn', '\u26A0\uFE0F Key generation already in progress, waiting for completion', {\n operationId: operationId,\n lastOperation: currentState.lastOperation,\n lastOperationTime: currentState.lastOperationTime\n });\n \n // Wait for existing operation to complete\n let waitAttempts = 0;\n const maxWaitAttempts = 50; // 5 seconds max wait\n \n while (currentState.isInitializing && waitAttempts < maxWaitAttempts) {\n await new Promise(resolve => setTimeout(resolve, 100));\n waitAttempts++;\n }\n \n if (currentState.isInitializing) {\n throw new Error('Key generation timeout - operation still in progress after 5 seconds');\n }\n }\n \n // Atomic state update within mutex protection\n try {\n // Set state atomically within mutex\n currentState.isInitializing = true;\n currentState.lastOperation = 'generation';\n currentState.lastOperationTime = Date.now();\n currentState.operationId = operationId;\n \n this._secureLog('debug', '\uD83D\uDD12 Atomic key generation state set', {\n operationId: operationId,\n timestamp: currentState.lastOperationTime\n });\n \n // Generate keys with individual error handling\n let ecdhKeyPair = null;\n let ecdsaKeyPair = null;\n \n // Generate ephemeral ECDH keys for PFS\n try {\n ecdhKeyPair = await this._generateEphemeralECDHKeys();\n \n // Validate ECDH keys immediately\n if (!ecdhKeyPair || !ecdhKeyPair.privateKey || !ecdhKeyPair.publicKey) {\n throw new Error('Ephemeral ECDH key pair validation failed');\n }\n \n // Constant-time validation for key types\n if (!this._validateKeyPairConstantTime(ecdhKeyPair)) {\n throw new Error('Ephemeral ECDH keys are not valid CryptoKey instances');\n }\n \n this._secureLog('debug', '\u2705 Ephemeral ECDH keys generated and validated for PFS', {\n operationId: operationId,\n privateKeyType: ecdhKeyPair.privateKey.algorithm?.name,\n publicKeyType: ecdhKeyPair.publicKey.algorithm?.name,\n isEphemeral: true\n });\n \n } catch (ecdhError) {\n this._secureLog('error', '\u274C Ephemeral ECDH key generation failed', {\n operationId: operationId,\n errorType: ecdhError.constructor.name\n });\n this._throwSecureError(ecdhError, 'ephemeral_ecdh_key_generation');\n }\n \n // Generate ECDSA keys with retry mechanism\n try {\n ecdsaKeyPair = await window.EnhancedSecureCryptoUtils.generateECDSAKeyPair();\n \n // Validate ECDSA keys immediately\n if (!ecdsaKeyPair || !ecdsaKeyPair.privateKey || !ecdsaKeyPair.publicKey) {\n throw new Error('ECDSA key pair validation failed');\n }\n \n // Constant-time validation for key types\n if (!this._validateKeyPairConstantTime(ecdsaKeyPair)) {\n throw new Error('ECDSA keys are not valid CryptoKey instances');\n }\n \n this._secureLog('debug', '\u2705 ECDSA keys generated and validated', {\n operationId: operationId,\n privateKeyType: ecdsaKeyPair.privateKey.algorithm?.name,\n publicKeyType: ecdsaKeyPair.publicKey.algorithm?.name\n });\n \n } catch (ecdsaError) {\n this._secureLog('error', '\u274C ECDSA key generation failed', {\n operationId: operationId,\n errorType: ecdsaError.constructor.name\n });\n this._throwSecureError(ecdsaError, 'ecdsa_key_generation');\n }\n \n // Final validation of both key pairs\n if (!ecdhKeyPair || !ecdsaKeyPair) {\n throw new Error('One or both key pairs failed to generate');\n }\n \n // Enable security features after successful key generation\n this._enableSecurityFeaturesAfterKeyGeneration(ecdhKeyPair, ecdsaKeyPair);\n \n this._secureLog('info', '\u2705 Encryption keys generated successfully with atomic protection', {\n operationId: operationId,\n hasECDHKeys: !!(ecdhKeyPair?.privateKey && ecdhKeyPair?.publicKey),\n hasECDSAKeys: !!(ecdsaKeyPair?.privateKey && ecdsaKeyPair?.publicKey),\n generationTime: Date.now() - currentState.lastOperationTime\n });\n \n return { ecdhKeyPair, ecdsaKeyPair };\n \n } catch (error) {\n // Ensure state is reset on any error\n this._secureLog('error', '\u274C Key generation failed, resetting state', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n throw error;\n } finally {\n // Always reset state in finally block\n currentState.isInitializing = false;\n currentState.operationId = null;\n \n this._secureLog('debug', '\uD83D\uDD13 Key generation state reset', {\n operationId: operationId\n });\n }\n });\n }\n\n /**\n * Enable security features after successful key generation\n */\n _enableSecurityFeaturesAfterKeyGeneration(ecdhKeyPair, ecdsaKeyPair) {\n try {\n // Enable encryption features based on available keys\n if (ecdhKeyPair && ecdhKeyPair.privateKey && ecdhKeyPair.publicKey) {\n this.securityFeatures.hasEncryption = true;\n this.securityFeatures.hasECDH = true;\n this._secureLog('info', '\uD83D\uDD12 ECDH encryption features enabled');\n }\n \n if (ecdsaKeyPair && ecdsaKeyPair.privateKey && ecdsaKeyPair.publicKey) {\n this.securityFeatures.hasECDSA = true;\n this._secureLog('info', '\uD83D\uDD12 ECDSA signature features enabled');\n }\n \n // Enable additional features that depend on encryption\n if (this.securityFeatures.hasEncryption) {\n this.securityFeatures.hasMetadataProtection = true;\n this.securityFeatures.hasEnhancedReplayProtection = true;\n this.securityFeatures.hasNonExtractableKeys = true;\n this._secureLog('info', '\uD83D\uDD12 Additional encryption-dependent features enabled');\n }\n \n // Enable PFS after ephemeral key generation\n if (ecdhKeyPair && this.ephemeralKeyPairs.size > 0) {\n this.securityFeatures.hasPFS = true;\n this._secureLog('info', '\uD83D\uDD12 Perfect Forward Secrecy enabled with ephemeral keys');\n }\n \n this._secureLog('info', '\uD83D\uDD12 Security features updated after key generation', {\n hasEncryption: this.securityFeatures.hasEncryption,\n hasECDH: this.securityFeatures.hasECDH,\n hasECDSA: this.securityFeatures.hasECDSA,\n hasMetadataProtection: this.securityFeatures.hasMetadataProtection,\n hasEnhancedReplayProtection: this.securityFeatures.hasEnhancedReplayProtection,\n hasNonExtractableKeys: this.securityFeatures.hasNonExtractableKeys,\n hasPFS: this.securityFeatures.hasPFS\n });\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to enable security features after key generation', {\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n }\n }\n\n /**\n * Enhanced emergency mutex unlocking with authorization and validation\n */\n _emergencyUnlockAllMutexes(callerContext = 'unknown') {\n // Validate caller authorization\n const authorizedCallers = [\n 'keyOperation', 'cryptoOperation', 'connectionOperation',\n 'emergencyRecovery', 'systemShutdown', 'errorHandler'\n ];\n \n if (!authorizedCallers.includes(callerContext)) {\n this._secureLog('error', `\uD83D\uDEA8 UNAUTHORIZED emergency mutex unlock attempt`, {\n callerContext: callerContext,\n authorizedCallers: authorizedCallers,\n timestamp: Date.now()\n });\n throw new Error(`Unauthorized emergency mutex unlock attempt by: ${callerContext}`);\n }\n \n const mutexes = ['keyOperation', 'cryptoOperation', 'connectionOperation'];\n \n this._secureLog('error', '\uD83D\uDEA8 EMERGENCY: Unlocking all mutexes with authorization and state cleanup', {\n callerContext: callerContext,\n timestamp: Date.now()\n });\n \n let unlockedCount = 0;\n let errorCount = 0;\n \n mutexes.forEach(mutexName => {\n const mutex = this[`_${mutexName}Mutex`];\n if (mutex) {\n try {\n // Clear timeout first\n if (mutex.lockTimeout) {\n clearTimeout(mutex.lockTimeout);\n }\n \n // Log mutex state before emergency unlock\n const previousState = {\n locked: mutex.locked,\n lockId: mutex.lockId,\n lockTime: mutex.lockTime,\n queueLength: mutex.queue.length\n };\n \n // Reset mutex state atomically\n mutex.locked = false;\n mutex.lockId = null;\n mutex.lockTimeout = null;\n mutex.lockTime = null;\n \n // Clear queue with proper error handling and logging\n let queueRejectCount = 0;\n mutex.queue.forEach(item => {\n try {\n if (item.reject && typeof item.reject === 'function') {\n item.reject(new Error(`Emergency mutex unlock for ${mutexName} by ${callerContext}`));\n queueRejectCount++;\n }\n } catch (rejectError) {\n this._secureLog('warn', `\u26A0\uFE0F Failed to reject queue item during emergency unlock`, {\n mutexName: mutexName,\n errorType: rejectError.constructor.name\n });\n }\n });\n \n // Clear queue array\n mutex.queue = [];\n \n unlockedCount++;\n \n this._secureLog('debug', `\uD83D\uDD13 Emergency unlocked mutex: ${mutexName}`, {\n previousState: previousState,\n queueRejectCount: queueRejectCount,\n callerContext: callerContext\n });\n \n } catch (error) {\n errorCount++;\n this._secureLog('error', `\u274C Error during emergency unlock of mutex: ${mutexName}`, {\n errorType: error.constructor.name,\n errorMessage: error.message,\n callerContext: callerContext\n });\n }\n }\n });\n \n // Reset key system state with validation\n if (this._keySystemState) {\n try {\n const previousKeyState = { ...this._keySystemState };\n \n this._keySystemState.isInitializing = false;\n this._keySystemState.isRotating = false;\n this._keySystemState.isDestroying = false;\n this._keySystemState.operationId = null;\n this._keySystemState.concurrentOperations = 0;\n \n this._secureLog('debug', `\uD83D\uDD13 Emergency reset key system state`, {\n previousState: previousKeyState,\n callerContext: callerContext\n });\n \n } catch (error) {\n this._secureLog('error', `\u274C Error resetting key system state during emergency unlock`, {\n errorType: error.constructor.name,\n errorMessage: error.message,\n callerContext: callerContext\n });\n }\n }\n \n // Log emergency unlock summary\n this._secureLog('info', `\uD83D\uDEA8 Emergency mutex unlock completed`, {\n callerContext: callerContext,\n unlockedCount: unlockedCount,\n errorCount: errorCount,\n totalMutexes: mutexes.length,\n timestamp: Date.now()\n });\n \n // Trigger system validation after emergency unlock\n setTimeout(() => {\n this._validateMutexSystemAfterEmergencyUnlock();\n }, 100);\n }\n\n /**\n * Handle key operation errors with recovery mechanisms\n */\n _handleKeyOperationError(error, operationId) {\n this._secureLog('error', '\uD83D\uDEA8 Key operation error detected, initiating recovery', {\n operationId: operationId,\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n \n // Reset key system state immediately\n if (this._keySystemState) {\n this._keySystemState.isInitializing = false;\n this._keySystemState.isRotating = false;\n this._keySystemState.isDestroying = false;\n this._keySystemState.operationId = null;\n }\n \n // Clear any partial key data\n this.ecdhKeyPair = null;\n this.ecdsaKeyPair = null;\n this.encryptionKey = null;\n this.macKey = null;\n this.metadataKey = null;\n \n // Trigger emergency recovery if needed\n if (error.message.includes('timeout') || error.message.includes('race condition')) {\n this._secureLog('warn', '\u26A0\uFE0F Race condition or timeout detected, triggering emergency recovery');\n this._emergencyRecoverMutexSystem();\n }\n }\n\n /**\n * Generate cryptographically secure IV with reuse prevention\n */\n _generateSecureIV(ivSize = 12, context = 'general') {\n // Check if we're in emergency mode\n if (this._ivTrackingSystem.emergencyMode) {\n this._secureLog('error', '\uD83D\uDEA8 CRITICAL: IV generation blocked - emergency mode active due to IV reuse');\n throw new Error('IV generation blocked - emergency mode active');\n }\n \n let attempts = 0;\n const maxAttempts = 100; // Prevent infinite loops\n \n while (attempts < maxAttempts) {\n attempts++;\n \n // Generate fresh IV with crypto.getRandomValues\n const iv = crypto.getRandomValues(new Uint8Array(ivSize));\n \n // Convert IV to string for tracking\n const ivString = Array.from(iv).map(b => b.toString(16).padStart(2, '0')).join('');\n \n // Check for IV reuse\n if (this._ivTrackingSystem.usedIVs.has(ivString)) {\n this._ivTrackingSystem.collisionCount++;\n this._secureLog('error', `\uD83D\uDEA8 CRITICAL: IV reuse detected!`, {\n context: context,\n attempt: attempts,\n collisionCount: this._ivTrackingSystem.collisionCount,\n ivString: ivString.substring(0, 16) + '...' // Log partial IV for debugging\n });\n \n // If too many collisions, trigger emergency mode\n if (this._ivTrackingSystem.collisionCount > 5) {\n this._ivTrackingSystem.emergencyMode = true;\n this._secureLog('error', '\uD83D\uDEA8 CRITICAL: Emergency mode activated due to excessive IV reuse');\n throw new Error('Emergency mode: Excessive IV reuse detected');\n }\n \n continue; // Try again\n }\n \n // Validate IV entropy\n if (!this._validateIVEntropy(iv)) {\n this._ivTrackingSystem.entropyValidation.entropyFailures++;\n this._secureLog('warn', `\u26A0\uFE0F Low entropy IV detected`, {\n context: context,\n attempt: attempts,\n entropyFailures: this._ivTrackingSystem.entropyValidation.entropyFailures\n });\n \n // If too many entropy failures, trigger emergency mode\n if (this._ivTrackingSystem.entropyValidation.entropyFailures > 10) {\n this._ivTrackingSystem.emergencyMode = true;\n this._secureLog('error', '\uD83D\uDEA8 CRITICAL: Emergency mode activated due to low entropy IVs');\n throw new Error('Emergency mode: Low entropy IVs detected');\n }\n \n continue; // Try again\n }\n \n // Track IV usage\n this._ivTrackingSystem.usedIVs.add(ivString);\n this._ivTrackingSystem.ivHistory.set(ivString, {\n timestamp: Date.now(),\n context: context,\n attempt: attempts\n });\n \n // Track per-session IVs\n if (this.sessionId) {\n if (!this._ivTrackingSystem.sessionIVs.has(this.sessionId)) {\n this._ivTrackingSystem.sessionIVs.set(this.sessionId, new Set());\n }\n this._ivTrackingSystem.sessionIVs.get(this.sessionId).add(ivString);\n }\n \n // Validate RNG periodically\n this._validateRNGQuality();\n \n this._secureLog('debug', `\u2705 Secure IV generated`, {\n context: context,\n attempt: attempts,\n ivSize: ivSize,\n totalIVs: this._ivTrackingSystem.usedIVs.size\n });\n \n return iv;\n }\n \n // If we can't generate a unique IV after max attempts\n this._secureLog('error', `\u274C Failed to generate unique IV after ${maxAttempts} attempts`, {\n context: context,\n totalIVs: this._ivTrackingSystem.usedIVs.size\n });\n throw new Error(`Failed to generate unique IV after ${maxAttempts} attempts`);\n }\n \n /**\n * Validate IV entropy to detect weak RNG\n */\n _validateIVEntropy(iv) {\n this._ivTrackingSystem.entropyValidation.entropyTests++;\n \n // Calculate byte distribution\n const byteCounts = new Array(256).fill(0);\n for (let i = 0; i < iv.length; i++) {\n byteCounts[iv[i]]++;\n }\n \n // Multi-dimensional entropy analysis\n const entropyResults = {\n shannon: 0,\n min: 0,\n collision: 0,\n compression: 0,\n quantum: 0\n };\n \n // 1. Shannon entropy calculation\n let shannonEntropy = 0;\n const totalBytes = iv.length;\n \n for (let i = 0; i < 256; i++) {\n if (byteCounts[i] > 0) {\n const probability = byteCounts[i] / totalBytes;\n shannonEntropy -= probability * Math.log2(probability);\n }\n }\n entropyResults.shannon = shannonEntropy;\n \n // 2. Min-entropy calculation (worst-case scenario)\n const maxCount = Math.max(...byteCounts);\n const maxProbability = maxCount / totalBytes;\n entropyResults.min = -Math.log2(maxProbability);\n \n // 3. Collision entropy calculation\n let collisionSum = 0;\n for (let i = 0; i < 256; i++) {\n if (byteCounts[i] > 0) {\n const probability = byteCounts[i] / totalBytes;\n collisionSum += probability * probability;\n }\n }\n entropyResults.collision = -Math.log2(collisionSum);\n \n // 4. Compression-based entropy estimation\n const ivString = Array.from(iv).map(b => String.fromCharCode(b)).join('');\n const compressedLength = this._estimateCompressedLength(ivString);\n entropyResults.compression = (1 - compressedLength / totalBytes) * 8;\n \n // 5. Quantum-resistant entropy analysis\n entropyResults.quantum = this._calculateQuantumResistantEntropy(iv);\n \n // Enhanced suspicious pattern detection\n const hasSuspiciousPatterns = this._detectAdvancedSuspiciousPatterns(iv);\n \n // Multi-criteria validation\n const minEntropyThreshold = this._ivTrackingSystem.entropyValidation.minEntropy;\n const isValid = (\n entropyResults.shannon >= minEntropyThreshold &&\n entropyResults.min >= minEntropyThreshold * 0.8 &&\n entropyResults.collision >= minEntropyThreshold * 0.9 &&\n entropyResults.compression >= minEntropyThreshold * 0.7 &&\n entropyResults.quantum >= minEntropyThreshold * 0.6 &&\n !hasSuspiciousPatterns\n );\n \n if (!isValid) {\n this._secureLog('warn', `\u26A0\uFE0F Enhanced IV entropy validation failed`, {\n shannon: entropyResults.shannon.toFixed(2),\n min: entropyResults.min.toFixed(2),\n collision: entropyResults.collision.toFixed(2),\n compression: entropyResults.compression.toFixed(2),\n quantum: entropyResults.quantum.toFixed(2),\n minThreshold: minEntropyThreshold,\n hasSuspiciousPatterns: hasSuspiciousPatterns\n });\n }\n \n return isValid;\n }\n \n /**\n * Estimate compressed length for entropy calculation\n * @param {string} data - Data to estimate compression\n * @returns {number} Estimated compressed length\n */\n _estimateCompressedLength(data) {\n // Simple LZ77-like compression estimation\n let compressedLength = 0;\n let i = 0;\n \n while (i < data.length) {\n let matchLength = 0;\n let matchDistance = 0;\n \n // Look for repeated patterns\n for (let j = Math.max(0, i - 255); j < i; j++) {\n let k = 0;\n while (i + k < data.length && data[i + k] === data[j + k] && k < 255) {\n k++;\n }\n if (k > matchLength) {\n matchLength = k;\n matchDistance = i - j;\n }\n }\n \n if (matchLength >= 3) {\n compressedLength += 3; // Distance + length + literal\n i += matchLength;\n } else {\n compressedLength += 1;\n i += 1;\n }\n }\n \n return compressedLength;\n }\n\n /**\n * Calculate quantum-resistant entropy\n * @param {Uint8Array} data - Data to analyze\n * @returns {number} Quantum-resistant entropy score\n */\n _calculateQuantumResistantEntropy(data) {\n // Quantum-resistant entropy analysis\n let quantumScore = 0;\n \n // 1. Check for quantum-vulnerable patterns\n const hasQuantumVulnerablePatterns = this._detectQuantumVulnerablePatterns(data);\n if (hasQuantumVulnerablePatterns) {\n quantumScore -= 2;\n }\n \n // 2. Analyze bit distribution\n const bitDistribution = this._analyzeBitDistribution(data);\n quantumScore += bitDistribution.score;\n \n // 3. Check for periodicity\n const periodicity = this._detectPeriodicity(data);\n quantumScore -= periodicity * 0.5;\n \n // 4. Normalize to 0-8 range\n return Math.max(0, Math.min(8, quantumScore));\n }\n\n /**\n * Detect quantum-vulnerable patterns\n * @param {Uint8Array} data - Data to analyze\n * @returns {boolean} true if quantum-vulnerable patterns found\n */\n _detectQuantumVulnerablePatterns(data) {\n // Check for patterns vulnerable to quantum attacks\n const patterns = [\n [0, 0, 0, 0, 0, 0, 0, 0], // All zeros\n [255, 255, 255, 255, 255, 255, 255, 255], // All ones\n [0, 1, 0, 1, 0, 1, 0, 1], // Alternating\n [1, 0, 1, 0, 1, 0, 1, 0] // Alternating reverse\n ];\n \n for (const pattern of patterns) {\n for (let i = 0; i <= data.length - pattern.length; i++) {\n let match = true;\n for (let j = 0; j < pattern.length; j++) {\n if (data[i + j] !== pattern[j]) {\n match = false;\n break;\n }\n }\n if (match) return true;\n }\n }\n \n return false;\n }\n\n /**\n * Analyze bit distribution\n * @param {Uint8Array} data - Data to analyze\n * @returns {Object} Bit distribution analysis\n */\n _analyzeBitDistribution(data) {\n let ones = 0;\n let totalBits = data.length * 8;\n \n for (const byte of data) {\n ones += (byte >>> 0).toString(2).split('1').length - 1;\n }\n \n const zeroRatio = (totalBits - ones) / totalBits;\n const oneRatio = ones / totalBits;\n \n // Ideal distribution is 50/50\n const deviation = Math.abs(0.5 - oneRatio);\n const score = Math.max(0, 8 - deviation * 16);\n \n return { score, zeroRatio, oneRatio, deviation };\n }\n\n /**\n * Detect periodicity in data\n * @param {Uint8Array} data - Data to analyze\n * @returns {number} Periodicity score (0-1)\n */\n _detectPeriodicity(data) {\n if (data.length < 16) return 0;\n \n let maxPeriodicity = 0;\n \n // Check for periods from 2 to data.length/2\n for (let period = 2; period <= data.length / 2; period++) {\n let matches = 0;\n let totalChecks = 0;\n \n for (let i = 0; i < data.length - period; i++) {\n if (data[i] === data[i + period]) {\n matches++;\n }\n totalChecks++;\n }\n \n if (totalChecks > 0) {\n const periodicity = matches / totalChecks;\n maxPeriodicity = Math.max(maxPeriodicity, periodicity);\n }\n }\n \n return maxPeriodicity;\n }\n\n /**\n * Enhanced suspicious pattern detection\n * @param {Uint8Array} iv - IV to check\n * @returns {boolean} true if suspicious patterns found\n */\n _detectAdvancedSuspiciousPatterns(iv) {\n // Enhanced pattern detection with quantum-resistant analysis\n const patterns = [\n // Sequential patterns\n [0, 1, 2, 3, 4, 5, 6, 7],\n [255, 254, 253, 252, 251, 250, 249, 248],\n \n // Repeated patterns\n [0, 0, 0, 0, 0, 0, 0, 0],\n [255, 255, 255, 255, 255, 255, 255, 255],\n \n // Alternating patterns\n [0, 255, 0, 255, 0, 255, 0, 255],\n [255, 0, 255, 0, 255, 0, 255, 0]\n ];\n \n for (const pattern of patterns) {\n for (let i = 0; i <= iv.length - pattern.length; i++) {\n let match = true;\n for (let j = 0; j < pattern.length; j++) {\n if (iv[i + j] !== pattern[j]) {\n match = false;\n break;\n }\n }\n if (match) return true;\n }\n }\n \n // Check for low entropy regions\n const entropyMap = this._calculateLocalEntropy(iv);\n const lowEntropyRegions = entropyMap.filter(e => e < 3.0).length;\n \n return lowEntropyRegions > iv.length * 0.3; // More than 30% low entropy\n }\n\n /**\n * Calculate local entropy for pattern detection\n * @param {Uint8Array} data - Data to analyze\n * @returns {Array} Array of local entropy values\n */\n _calculateLocalEntropy(data) {\n const windowSize = 8;\n const entropyMap = [];\n \n for (let i = 0; i <= data.length - windowSize; i++) {\n const window = data.slice(i, i + windowSize);\n const charCount = {};\n \n for (const byte of window) {\n charCount[byte] = (charCount[byte] || 0) + 1;\n }\n \n let entropy = 0;\n for (const count of Object.values(charCount)) {\n const probability = count / windowSize;\n entropy -= probability * Math.log2(probability);\n }\n \n entropyMap.push(entropy);\n }\n \n return entropyMap;\n }\n\n /**\n * Detect suspicious patterns in IVs\n */\n _detectSuspiciousIVPatterns(iv) {\n // Check for all zeros or all ones\n const allZeros = iv.every(byte => byte === 0);\n const allOnes = iv.every(byte => byte === 255);\n \n if (allZeros || allOnes) {\n return true;\n }\n \n // Check for sequential patterns\n let sequentialCount = 0;\n for (let i = 1; i < iv.length; i++) {\n if (iv[i] === iv[i-1] + 1 || iv[i] === iv[i-1] - 1) {\n sequentialCount++;\n } else {\n sequentialCount = 0;\n }\n \n if (sequentialCount >= 3) {\n return true; // Suspicious sequential pattern\n }\n }\n \n // Check for repeated patterns\n for (let patternLength = 2; patternLength <= Math.floor(iv.length / 2); patternLength++) {\n for (let start = 0; start <= iv.length - patternLength * 2; start++) {\n const pattern1 = iv.slice(start, start + patternLength);\n const pattern2 = iv.slice(start + patternLength, start + patternLength * 2);\n \n if (pattern1.every((byte, index) => byte === pattern2[index])) {\n return true; // Repeated pattern detected\n }\n }\n }\n \n return false;\n }\n \n /**\n * Clean up old IVs with strict limits\n */\n _cleanupOldIVs() {\n const now = Date.now();\n const maxAge = 1800000; // Reduced to 30 minutes for better security\n let cleanedCount = 0;\n const cleanupBatch = [];\n \n // Aggressive cleanup with quantum-resistant patterns\n // Enforce maximum IV history size with batch processing\n if (this._ivTrackingSystem.ivHistory.size > this._ivTrackingSystem.maxIVHistorySize) {\n const ivArray = Array.from(this._ivTrackingSystem.ivHistory.entries());\n const toRemove = ivArray.slice(0, ivArray.length - this._ivTrackingSystem.maxIVHistorySize);\n \n for (const [ivString] of toRemove) {\n cleanupBatch.push(ivString);\n cleanedCount++;\n \n // Process in batches to prevent memory spikes\n if (cleanupBatch.length >= 100) {\n this._processCleanupBatch(cleanupBatch);\n cleanupBatch.length = 0;\n }\n }\n }\n \n // Clean up old IVs from history by age with enhanced security\n for (const [ivString, metadata] of this._ivTrackingSystem.ivHistory.entries()) {\n if (now - metadata.timestamp > maxAge) {\n cleanupBatch.push(ivString);\n cleanedCount++;\n \n // Process in batches to prevent memory spikes\n if (cleanupBatch.length >= 100) {\n this._processCleanupBatch(cleanupBatch);\n cleanupBatch.length = 0;\n }\n }\n }\n \n // Process remaining batch\n if (cleanupBatch.length > 0) {\n this._processCleanupBatch(cleanupBatch);\n }\n \n // Enhanced session IV cleanup with entropy preservation\n for (const [sessionId, sessionIVs] of this._ivTrackingSystem.sessionIVs.entries()) {\n if (sessionIVs.size > this._ivTrackingSystem.maxSessionIVs) {\n const ivArray = Array.from(sessionIVs);\n const toRemove = ivArray.slice(0, ivArray.length - this._ivTrackingSystem.maxSessionIVs);\n \n for (const ivString of toRemove) {\n sessionIVs.delete(ivString);\n this._ivTrackingSystem.usedIVs.delete(ivString);\n this._ivTrackingSystem.ivHistory.delete(ivString);\n cleanedCount++;\n }\n }\n }\n \n // Force garbage collection if available and significant cleanup occurred\n if (typeof window.gc === 'function' && cleanedCount > 50) {\n try {\n window.gc();\n } catch (e) {\n // Ignore GC errors\n }\n }\n \n if (cleanedCount > 0) {\n this._secureLog('debug', `\uD83E\uDDF9 Enhanced cleanup: ${cleanedCount} old IVs removed`, {\n cleanedCount: cleanedCount,\n remainingIVs: this._ivTrackingSystem.usedIVs.size,\n remainingHistory: this._ivTrackingSystem.ivHistory.size,\n memoryPressure: this._calculateMemoryPressure()\n });\n }\n }\n \n /**\n * Process cleanup batch with constant-time operations\n * @param {Array} batch - Batch of items to clean up\n */\n _processCleanupBatch(batch) {\n // Constant-time batch processing\n for (const item of batch) {\n this._ivTrackingSystem.usedIVs.delete(item);\n this._ivTrackingSystem.ivHistory.delete(item);\n }\n }\n\n /**\n * Calculate memory pressure for adaptive cleanup\n * @returns {number} Memory pressure score (0-100)\n */\n _calculateMemoryPressure() {\n const totalIVs = this._ivTrackingSystem.usedIVs.size;\n const maxAllowed = this._resourceLimits.maxIVHistory;\n \n return Math.min(100, Math.floor((totalIVs / maxAllowed) * 100));\n }\n\n /**\n * Get IV tracking system statistics\n */\n _getIVTrackingStats() {\n return {\n totalIVs: this._ivTrackingSystem.usedIVs.size,\n collisionCount: this._ivTrackingSystem.collisionCount,\n entropyTests: this._ivTrackingSystem.entropyValidation.entropyTests,\n entropyFailures: this._ivTrackingSystem.entropyValidation.entropyFailures,\n rngTests: this._ivTrackingSystem.rngValidation.testsPerformed,\n weakRngDetected: this._ivTrackingSystem.rngValidation.weakRngDetected,\n emergencyMode: this._ivTrackingSystem.emergencyMode,\n sessionCount: this._ivTrackingSystem.sessionIVs.size,\n lastCleanup: this._lastIVCleanupTime || 0\n };\n }\n \n /**\n * Reset IV tracking system (for testing or emergency recovery)\n */\n _resetIVTrackingSystem() {\n this._secureLog('warn', '\uD83D\uDD04 Resetting IV tracking system');\n \n this._ivTrackingSystem.usedIVs.clear();\n this._ivTrackingSystem.ivHistory.clear();\n this._ivTrackingSystem.sessionIVs.clear();\n this._ivTrackingSystem.collisionCount = 0;\n this._ivTrackingSystem.entropyValidation.entropyTests = 0;\n this._ivTrackingSystem.entropyValidation.entropyFailures = 0;\n this._ivTrackingSystem.rngValidation.testsPerformed = 0;\n this._ivTrackingSystem.rngValidation.weakRngDetected = false;\n this._ivTrackingSystem.emergencyMode = false;\n \n this._secureLog('info', '\u2705 IV tracking system reset completed');\n }\n \n /**\n * Validate RNG quality\n */\n _validateRNGQuality() {\n const now = Date.now();\n \n // Validate RNG every 1000 IV generations\n if (this._ivTrackingSystem.rngValidation.testsPerformed % 1000 === 0) {\n try {\n // Generate test IVs and validate\n const testIVs = [];\n for (let i = 0; i < 100; i++) {\n testIVs.push(crypto.getRandomValues(new Uint8Array(12)));\n }\n \n // Check for duplicates in test set\n const testIVStrings = testIVs.map(iv => Array.from(iv).map(b => b.toString(16).padStart(2, '0')).join(''));\n const uniqueTestIVs = new Set(testIVStrings);\n \n if (uniqueTestIVs.size < 95) { // Allow some tolerance\n this._ivTrackingSystem.rngValidation.weakRngDetected = true;\n this._secureLog('error', '\uD83D\uDEA8 CRITICAL: Weak RNG detected in validation test', {\n uniqueIVs: uniqueTestIVs.size,\n totalTests: testIVs.length\n });\n }\n \n this._ivTrackingSystem.rngValidation.lastValidation = now;\n \n } catch (error) {\n this._secureLog('error', '\u274C RNG validation failed', {\n errorType: error.constructor.name\n });\n }\n }\n \n this._ivTrackingSystem.rngValidation.testsPerformed++;\n }\n \n /**\n * Handle mutex timeout with enhanced state validation\n */\n _handleMutexTimeout(mutexName, operationId, timeout) {\n const mutex = this[`_${mutexName}Mutex`];\n \n if (!mutex) {\n this._secureLog('error', `\u274C Mutex '${mutexName}' not found during timeout handling`);\n return;\n }\n \n // Validate timeout conditions\n if (mutex.lockId !== operationId) {\n this._secureLog('warn', `\u26A0\uFE0F Timeout for different operation ID on mutex '${mutexName}'`, {\n expectedOperationId: operationId,\n actualLockId: mutex.lockId,\n locked: mutex.locked\n });\n return;\n }\n \n if (!mutex.locked) {\n this._secureLog('warn', `\u26A0\uFE0F Timeout for already unlocked mutex '${mutexName}'`, {\n operationId: operationId\n });\n return;\n }\n \n try {\n // Calculate lock duration for monitoring\n const lockDuration = mutex.lockTime ? Date.now() - mutex.lockTime : 0;\n \n this._secureLog('warn', `\u26A0\uFE0F Mutex '${mutexName}' auto-released due to timeout`, {\n operationId: operationId,\n lockDuration: lockDuration,\n timeout: timeout,\n queueLength: mutex.queue.length\n });\n \n // Atomic release with state validation\n mutex.locked = false;\n mutex.lockId = null;\n mutex.lockTimeout = null;\n mutex.lockTime = null;\n \n // Process next in queue with error handling\n setTimeout(() => {\n try {\n this._processNextInQueue(mutexName);\n } catch (queueError) {\n this._secureLog('error', `\u274C Error processing queue after timeout for mutex '${mutexName}'`, {\n errorType: queueError.constructor.name,\n errorMessage: queueError.message\n });\n }\n }, 10);\n \n } catch (error) {\n this._secureLog('error', `\u274C Critical error during mutex timeout handling for '${mutexName}'`, {\n operationId: operationId,\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n \n // Force emergency unlock if timeout handling fails\n try {\n this._emergencyUnlockAllMutexes('timeoutHandler');\n } catch (emergencyError) {\n this._secureLog('error', `\u274C Emergency unlock failed during timeout handling`, {\n originalError: error.message,\n emergencyError: emergencyError.message\n });\n }\n }\n }\n\n /**\n * Validate mutex system after emergency unlock\n */\n _validateMutexSystemAfterEmergencyUnlock() {\n const mutexes = ['keyOperation', 'cryptoOperation', 'connectionOperation'];\n let validationErrors = 0;\n \n this._secureLog('info', '\uD83D\uDD0D Validating mutex system after emergency unlock');\n \n mutexes.forEach(mutexName => {\n const mutex = this[`_${mutexName}Mutex`];\n \n if (!mutex) {\n validationErrors++;\n this._secureLog('error', `\u274C Mutex '${mutexName}' not found after emergency unlock`);\n return;\n }\n \n // Validate mutex state consistency\n if (mutex.locked) {\n validationErrors++;\n this._secureLog('error', `\u274C Mutex '${mutexName}' still locked after emergency unlock`, {\n lockId: mutex.lockId,\n lockTime: mutex.lockTime\n });\n }\n \n if (mutex.lockId !== null) {\n validationErrors++;\n this._secureLog('error', `\u274C Mutex '${mutexName}' still has lock ID after emergency unlock`, {\n lockId: mutex.lockId\n });\n }\n \n if (mutex.lockTimeout !== null) {\n validationErrors++;\n this._secureLog('error', `\u274C Mutex '${mutexName}' still has timeout after emergency unlock`);\n }\n \n if (mutex.queue.length > 0) {\n validationErrors++;\n this._secureLog('error', `\u274C Mutex '${mutexName}' still has queue items after emergency unlock`, {\n queueLength: mutex.queue.length\n });\n }\n });\n \n // Validate key system state\n if (this._keySystemState) {\n if (this._keySystemState.isInitializing || \n this._keySystemState.isRotating || \n this._keySystemState.isDestroying) {\n validationErrors++;\n this._secureLog('error', `\u274C Key system state not properly reset after emergency unlock`, {\n isInitializing: this._keySystemState.isInitializing,\n isRotating: this._keySystemState.isRotating,\n isDestroying: this._keySystemState.isDestroying\n });\n }\n }\n \n if (validationErrors === 0) {\n this._secureLog('info', '\u2705 Mutex system validation passed after emergency unlock');\n } else {\n this._secureLog('error', `\u274C Mutex system validation failed after emergency unlock`, {\n validationErrors: validationErrors\n });\n \n // Force re-initialization if validation fails\n setTimeout(() => {\n this._emergencyRecoverMutexSystem();\n }, 1000);\n }\n }\n /**\n * NEW: Diagnostics of the mutex system state\n */\n _getMutexSystemDiagnostics() {\n const diagnostics = {\n timestamp: Date.now(),\n systemValid: this._validateMutexSystem(),\n mutexes: {},\n counters: { ...this._operationCounters },\n keySystemState: { ...this._keySystemState }\n };\n \n const mutexNames = ['keyOperation', 'cryptoOperation', 'connectionOperation'];\n \n mutexNames.forEach(mutexName => {\n const mutexPropertyName = `_${mutexName}Mutex`;\n const mutex = this[mutexPropertyName];\n \n if (mutex) {\n diagnostics.mutexes[mutexName] = {\n locked: mutex.locked,\n lockId: mutex.lockId,\n queueLength: mutex.queue.length,\n hasTimeout: !!mutex.lockTimeout\n };\n } else {\n diagnostics.mutexes[mutexName] = { error: 'not_found' };\n }\n });\n \n return diagnostics;\n }\n\n /**\n * FULLY FIXED createSecureOffer()\n * With race-condition protection and improved security\n */\n async createSecureOffer() {\n console.log('\uD83C\uDFAF createSecureOffer called');\n return this._withMutex('connectionOperation', async (operationId) => {\n this._secureLog('info', '\uD83D\uDCE4 Creating secure offer with mutex', {\n operationId: operationId,\n connectionAttempts: this.connectionAttempts,\n currentState: this.peerConnection?.connectionState || 'none'\n });\n \n try {\n // ============================================\n // PHASE 1: INITIALIZATION AND VALIDATION\n // ============================================\n console.log('\uD83C\uDFAF PHASE 1: Initialization and validation');\n \n // Reset notification flags for a new connection\n this._resetNotificationFlags();\n \n // Rate limiting check\n if (!this._checkRateLimit()) {\n throw new Error('Connection rate limit exceeded. Please wait before trying again.');\n }\n \n // Reset attempt counters\n this.connectionAttempts = 0;\n \n // Generate session salt (64 bytes for v4.0)\n this.sessionSalt = window.EnhancedSecureCryptoUtils.generateSalt();\n console.log('\uD83C\uDFAF PHASE 1 completed: Session salt generated');\n \n this._secureLog('debug', '\uD83E\uDDC2 Session salt generated', {\n operationId: operationId,\n saltLength: this.sessionSalt.length,\n isValidSalt: Array.isArray(this.sessionSalt) && this.sessionSalt.length === 64\n });\n \n // ============================================\n // PHASE 2: SECURE KEY GENERATION\n // ============================================\n console.log('\uD83C\uDFAF PHASE 2: Secure key generation');\n \n // Secure key generation via mutex\n const keyPairs = await this._generateEncryptionKeys();\n this.ecdhKeyPair = keyPairs.ecdhKeyPair;\n this.ecdsaKeyPair = keyPairs.ecdsaKeyPair;\n \n // Validate generated keys\n if (!this.ecdhKeyPair?.privateKey || !this.ecdhKeyPair?.publicKey) {\n throw new Error('Failed to generate valid ECDH key pair');\n }\n \n if (!this.ecdsaKeyPair?.privateKey || !this.ecdsaKeyPair?.publicKey) {\n throw new Error('Failed to generate valid ECDSA key pair');\n }\n \n // ============================================\n // PHASE 3: MITM PROTECTION AND FINGERPRINTING\n // ============================================\n console.log('\uD83C\uDFAF PHASE 3: MITM protection and fingerprinting');\n \n // MITM Protection: Compute unique key fingerprints\n const ecdhFingerprint = await window.EnhancedSecureCryptoUtils.calculateKeyFingerprint(\n await crypto.subtle.exportKey('spki', this.ecdhKeyPair.publicKey)\n );\n const ecdsaFingerprint = await window.EnhancedSecureCryptoUtils.calculateKeyFingerprint(\n await crypto.subtle.exportKey('spki', this.ecdsaKeyPair.publicKey)\n );\n \n // Validate fingerprints\n if (!ecdhFingerprint || !ecdsaFingerprint) {\n throw new Error('Failed to generate key fingerprints');\n }\n \n this._secureLog('info', 'Generated unique key pairs for MITM protection', {\n operationId: operationId,\n hasECDHFingerprint: !!ecdhFingerprint,\n hasECDSAFingerprint: !!ecdsaFingerprint,\n fingerprintLength: ecdhFingerprint.length,\n timestamp: Date.now()\n });\n \n // ============================================\n // PHASE 4: EXPORT SIGNED KEYS\n // ============================================\n console.log('\uD83C\uDFAF PHASE 4: Export signed keys');\n \n // Export keys with digital signatures\n const ecdhPublicKeyData = await window.EnhancedSecureCryptoUtils.exportPublicKeyWithSignature(\n this.ecdhKeyPair.publicKey,\n this.ecdsaKeyPair.privateKey,\n 'ECDH'\n );\n \n const ecdsaPublicKeyData = await window.EnhancedSecureCryptoUtils.exportPublicKeyWithSignature(\n this.ecdsaKeyPair.publicKey,\n this.ecdsaKeyPair.privateKey,\n 'ECDSA'\n );\n \n // CRITICAL: Strict validation of exported data with hard disconnect on failure\n // - Any validation failure in critical security path must abort connection\n // - No fallback allowed for cryptographic validation\n // - Prevent bypass of security checks through syntax/validation errors\n \n if (!ecdhPublicKeyData || typeof ecdhPublicKeyData !== 'object') {\n this._secureLog('error', 'CRITICAL: ECDH key export failed - invalid object structure', { operationId });\n throw new Error('CRITICAL SECURITY FAILURE: ECDH key export validation failed - hard abort required');\n }\n \n if (!ecdhPublicKeyData.keyData || !ecdhPublicKeyData.signature) {\n this._secureLog('error', 'CRITICAL: ECDH key export incomplete - missing keyData or signature', { \n operationId,\n hasKeyData: !!ecdhPublicKeyData.keyData,\n hasSignature: !!ecdhPublicKeyData.signature \n });\n throw new Error('CRITICAL SECURITY FAILURE: ECDH key export incomplete - hard abort required');\n }\n \n if (!ecdsaPublicKeyData || typeof ecdsaPublicKeyData !== 'object') {\n this._secureLog('error', 'CRITICAL: ECDSA key export failed - invalid object structure', { operationId });\n throw new Error('CRITICAL SECURITY FAILURE: ECDSA key export validation failed - hard abort required');\n }\n \n if (!ecdsaPublicKeyData.keyData || !ecdsaPublicKeyData.signature) {\n this._secureLog('error', 'CRITICAL: ECDSA key export incomplete - missing keyData or signature', { \n operationId,\n hasKeyData: !!ecdsaPublicKeyData.keyData,\n hasSignature: !!ecdsaPublicKeyData.signature \n });\n throw new Error('CRITICAL SECURITY FAILURE: ECDSA key export incomplete - hard abort required');\n }\n \n // ============================================\n // PHASE 5: UPDATE SECURITY FEATURES\n // ============================================\n console.log('\uD83C\uDFAF PHASE 5: Update security features');\n \n // Atomic update of security features\n this._updateSecurityFeatures({\n hasEncryption: true,\n hasECDH: true,\n hasECDSA: true,\n hasMutualAuth: true,\n hasMetadataProtection: true,\n hasEnhancedReplayProtection: true,\n hasNonExtractableKeys: true,\n hasRateLimiting: true,\n hasEnhancedValidation: true,\n hasPFS: true\n });\n \n // ============================================\n // PHASE 6: INITIALIZE PEER CONNECTION\n // ============================================\n console.log('\uD83C\uDFAF PHASE 6: Initialize peer connection');\n \n this.isInitiator = true;\n this.onStatusChange('connecting');\n \n // Create peer connection\n this.createPeerConnection();\n \n // Create main data channel\n this.dataChannel = this.peerConnection.createDataChannel('securechat', {\n ordered: true\n });\n \n // Setup data channel\n this.setupDataChannel(this.dataChannel);\n \n this._secureLog('debug', '\uD83D\uDD17 Data channel created', {\n operationId: operationId,\n channelLabel: this.dataChannel.label,\n channelOrdered: this.dataChannel.ordered\n });\n \n // ============================================\n // PHASE 7: CREATE SDP OFFER\n // ============================================\n console.log('\uD83C\uDFAF PHASE 7: Create SDP offer');\n \n // Create WebRTC offer\n console.log('\uD83C\uDFAF Creating WebRTC offer...');\n const offer = await this.peerConnection.createOffer({\n offerToReceiveAudio: false,\n offerToReceiveVideo: false\n });\n console.log('\uD83C\uDFAF WebRTC offer created successfully');\n \n // Set local description\n console.log('\uD83C\uDFAF Setting local description...');\n await this.peerConnection.setLocalDescription(offer);\n console.log('\uD83C\uDFAF Local description set successfully');\n \n // Extract and store our DTLS fingerprint for out-of-band verification\n console.log('\uD83C\uDFAF Extracting DTLS fingerprint...');\n try {\n const ourFingerprint = this._extractDTLSFingerprintFromSDP(offer.sdp);\n this.expectedDTLSFingerprint = ourFingerprint;\n console.log('\uD83C\uDFAF DTLS fingerprint extracted successfully');\n \n this._secureLog('info', 'Generated DTLS fingerprint for out-of-band verification', {\n fingerprint: ourFingerprint,\n context: 'offer_creation'\n });\n \n // Notify UI that fingerprint is ready for out-of-band verification\n this.deliverMessageToUI(`\uD83D\uDD10 DTLS fingerprint ready for verification: ${ourFingerprint}`, 'system');\n } catch (error) {\n this._secureLog('error', 'Failed to extract DTLS fingerprint from offer', { error: error.message });\n // Continue without fingerprint validation (fallback mode)\n }\n \n // Await ICE gathering\n await this.waitForIceGathering();\n \n this._secureLog('debug', '\uD83E\uDDCA ICE gathering completed', {\n operationId: operationId,\n iceGatheringState: this.peerConnection.iceGatheringState,\n connectionState: this.peerConnection.connectionState\n });\n \n // ============================================\n // PHASE 8: GENERATE SAS FOR OUT-OF-BAND VERIFICATION\n // ============================================\n console.log('\uD83C\uDFAF PHASE 8: Generate SAS for out-of-band verification');\n\n this.verificationCode = window.EnhancedSecureCryptoUtils.generateVerificationCode();\n console.log('\uD83C\uDFAF Placeholder verification code generated:', this.verificationCode);\n \n // Validate verification code\n if (!this.verificationCode || this.verificationCode.length < EnhancedSecureWebRTCManager.SIZES.VERIFICATION_CODE_MIN_LENGTH) {\n throw new Error('Failed to generate valid verification code');\n }\n \n // ============================================\n // PHASE 9: MUTUAL AUTHENTICATION CHALLENGE\n // ============================================\n console.log('\uD83C\uDFAF PHASE 9: Mutual authentication challenge');\n \n // Generate challenge for mutual authentication\n const authChallenge = window.EnhancedSecureCryptoUtils.generateMutualAuthChallenge();\n \n if (!authChallenge) {\n throw new Error('Failed to generate mutual authentication challenge');\n }\n \n // ============================================\n // PHASE 10: SESSION ID FOR MITM PROTECTION\n // ============================================\n console.log('\uD83C\uDFAF PHASE 10: Session ID for MITM protection');\n \n // MITM Protection: Generate session-specific ID\n this.sessionId = Array.from(crypto.getRandomValues(new Uint8Array(EnhancedSecureWebRTCManager.SIZES.SESSION_ID_LENGTH)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n \n // Validate session ID\n if (!this.sessionId || this.sessionId.length !== (EnhancedSecureWebRTCManager.SIZES.SESSION_ID_LENGTH * 2)) {\n throw new Error('Failed to generate valid session ID');\n }\n \n // Generate connection ID for AAD\n this.connectionId = Array.from(crypto.getRandomValues(new Uint8Array(8)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n \n // ============================================\n // PHASE 11: SECURITY LEVEL CALCULATION\n // ============================================\n console.log('\uD83C\uDFAF PHASE 11: Security level calculation');\n \n // Preliminary security level calculation\n let securityLevel;\n try {\n securityLevel = await this.calculateSecurityLevel();\n } catch (error) {\n this._secureLog('warn', '\u26A0\uFE0F Security level calculation failed, using fallback', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n \n // Fallback value\n securityLevel = {\n level: 'enhanced',\n score: 75,\n passedChecks: 10,\n totalChecks: 15,\n isRealData: false\n };\n }\n \n // ============================================\n // PHASE 12: CREATE OFFER PACKAGE\n // ============================================\n console.log('\uD83C\uDFAF PHASE 12: Create offer package');\n \n const currentTimestamp = Date.now();\n console.log('\uD83C\uDFAF Creating offer package object...');\n \n const offerPackage = {\n // Core information\n type: 'enhanced_secure_offer',\n sdp: this.peerConnection.localDescription.sdp,\n version: '4.0',\n timestamp: currentTimestamp,\n \n // Cryptographic keys\n ecdhPublicKey: ecdhPublicKeyData,\n ecdsaPublicKey: ecdsaPublicKeyData,\n \n // Session data\n salt: this.sessionSalt,\n sessionId: this.sessionId,\n connectionId: this.connectionId,\n \n // Authentication\n verificationCode: this.verificationCode,\n authChallenge: authChallenge,\n \n // Security metadata\n securityLevel: securityLevel,\n \n // Additional fields for validation\n keyFingerprints: {\n ecdh: ecdhFingerprint.substring(0, 16), // First 16 chars for validation\n ecdsa: ecdsaFingerprint.substring(0, 16)\n },\n \n // Optional capabilities info\n capabilities: {\n supportsFileTransfer: true,\n supportsEnhancedSecurity: true,\n supportsKeyRotation: true,\n supportsFakeTraffic: this.fakeTrafficConfig.enabled,\n supportsDecoyChannels: this.decoyChannelConfig.enabled\n }\n };\n console.log('\uD83C\uDFAF Offer package object created successfully');\n \n // ============================================\n // PHASE 13: VALIDATE OFFER PACKAGE\n // ============================================\n console.log('\uD83C\uDFAF PHASE 13: Validate offer package');\n \n // Final validation of the generated package\n console.log('\uD83C\uDFAF Validating offer package...');\n try {\n const validationResult = this.validateEnhancedOfferData(offerPackage);\n console.log('\uD83C\uDFAF Validation result:', validationResult);\n if (!validationResult) {\n console.log('\uD83C\uDFAF Offer package validation FAILED');\n throw new Error('Generated offer package failed validation');\n }\n console.log('\uD83C\uDFAF Offer package validation PASSED');\n } catch (validationError) {\n console.log('\uD83C\uDFAF Validation ERROR:', validationError.message);\n throw new Error(`Offer package validation error: ${validationError.message}`);\n }\n \n // ============================================\n // PHASE 14: LOGGING AND EVENTS\n // ============================================\n console.log('\uD83C\uDFAF PHASE 14: Logging and events');\n \n this._secureLog('info', 'Enhanced secure offer created successfully', {\n operationId: operationId,\n version: offerPackage.version,\n hasECDSA: true,\n hasMutualAuth: true,\n hasSessionId: !!offerPackage.sessionId,\n securityLevel: securityLevel.level,\n timestamp: currentTimestamp,\n capabilitiesCount: Object.keys(offerPackage.capabilities).length\n });\n \n // Dispatch event about new connection\n document.dispatchEvent(new CustomEvent('new-connection', {\n detail: { \n type: 'offer',\n timestamp: currentTimestamp,\n securityLevel: securityLevel.level,\n operationId: operationId\n }\n }));\n \n // ============================================\n // PHASE 15: RETURN RESULT\n // ============================================\n console.log('\uD83C\uDFAF PHASE 15: Return result');\n \n console.log('\uD83C\uDFAF createSecureOffer completed successfully, returning offerPackage');\n return offerPackage;\n \n } catch (error) {\n // ============================================\n // ERROR HANDLING\n // ============================================\n \n this._secureLog('error', '\u274C Enhanced secure offer creation failed in critical section', {\n operationId: operationId,\n errorType: error.constructor.name,\n errorMessage: error.message,\n phase: this._determineErrorPhase(error),\n connectionAttempts: this.connectionAttempts\n });\n \n // Cleanup state on error\n this._cleanupFailedOfferCreation();\n \n // Update status\n this.onStatusChange('disconnected');\n \n // Re-throw for upper-level handling\n throw error;\n }\n }, 15000); // 15 seconds timeout for the entire offer creation\n }\n\n /**\n * HELPER: Determine the phase where the error occurred\n */\n _determineErrorPhase(error) {\n const message = error.message.toLowerCase();\n \n if (message.includes('rate limit')) return 'rate_limiting';\n if (message.includes('key pair') || message.includes('generate')) return 'key_generation';\n if (message.includes('fingerprint')) return 'fingerprinting';\n if (message.includes('export') || message.includes('signature')) return 'key_export';\n if (message.includes('peer connection')) return 'webrtc_setup';\n if (message.includes('offer') || message.includes('sdp')) return 'sdp_creation';\n if (message.includes('verification')) return 'verification_setup';\n if (message.includes('session')) return 'session_setup';\n if (message.includes('validation')) return 'package_validation';\n \n return 'unknown';\n }\n\n /**\n * Secure cleanup state after failed offer creation\n */\n _cleanupFailedOfferCreation() {\n try {\n // Secure wipe of cryptographic materials\n this._secureCleanupCryptographicMaterials();\n \n // Close peer connection if it was created\n if (this.peerConnection) {\n this.peerConnection.close();\n this.peerConnection = null;\n }\n \n // Clear data channel\n if (this.dataChannel) {\n this.dataChannel.close();\n this.dataChannel = null;\n }\n \n // Reset flags\n this.isInitiator = false;\n this.isVerified = false;\n \n // Reset security features to baseline\n this._updateSecurityFeatures({\n hasEncryption: false,\n hasECDH: false,\n hasECDSA: false,\n hasMutualAuth: false,\n hasMetadataProtection: false,\n hasEnhancedReplayProtection: false,\n hasNonExtractableKeys: false,\n hasEnhancedValidation: false,\n hasPFS: false\n });\n \n // Force garbage collection\n this._forceGarbageCollection();\n \n this._secureLog('debug', '\uD83D\uDD12 Failed offer creation cleanup completed with secure memory wipe');\n \n } catch (cleanupError) {\n this._secureLog('error', '\u274C Error during offer creation cleanup', {\n errorType: cleanupError.constructor.name,\n errorMessage: cleanupError.message\n });\n }\n }\n\n /**\n * HELPER: Atomic update of security features (if not added yet)\n */\n _updateSecurityFeatures(updates) {\n const oldFeatures = { ...this.securityFeatures };\n \n try {\n Object.assign(this.securityFeatures, updates);\n \n this._secureLog('debug', '\uD83D\uDD27 Security features updated', {\n updatedCount: Object.keys(updates).length,\n totalFeatures: Object.keys(this.securityFeatures).length\n });\n \n } catch (error) {\n // Roll back on error\n this.securityFeatures = oldFeatures;\n this._secureLog('error', '\u274C Security features update failed, rolled back', {\n errorType: error.constructor.name\n });\n throw error;\n }\n }\n\n /**\n * FULLY FIXED METHOD createSecureAnswer()\n * With race-condition protection and enhanced security\n */\n async createSecureAnswer(offerData) {\n console.log('\uD83C\uDFAF createSecureAnswer called with offerData:', offerData ? 'present' : 'null');\n return this._withMutex('connectionOperation', async (operationId) => {\n this._secureLog('info', '\uD83D\uDCE8 Creating secure answer with mutex', {\n operationId: operationId,\n hasOfferData: !!offerData,\n offerType: offerData?.type,\n offerVersion: offerData?.version,\n offerTimestamp: offerData?.timestamp\n });\n \n try {\n // ============================================\n // PHASE 1: PRE-VALIDATION OF OFFER\n // ============================================\n \n // Reset notification flags for a new connection\n this._resetNotificationFlags();\n \n this._secureLog('debug', 'Starting enhanced offer validation', {\n operationId: operationId,\n hasOfferData: !!offerData,\n offerType: offerData?.type,\n hasECDHKey: !!offerData?.ecdhPublicKey,\n hasECDSAKey: !!offerData?.ecdsaPublicKey,\n hasSalt: !!offerData?.salt\n });\n \n // Strict input validation\n if (!this.validateEnhancedOfferData(offerData)) {\n throw new Error('Invalid connection data format - failed enhanced validation');\n }\n \n // Rate limiting check\n if (!window.EnhancedSecureCryptoUtils.rateLimiter.checkConnectionRate(this.rateLimiterId)) {\n throw new Error('Connection rate limit exceeded. Please wait before trying again.');\n }\n \n // ============================================\n // PHASE 2: SECURITY AND ANTI-REPLAY PROTECTION\n // ============================================\n \n // MITM Protection: Validate offer data structure\n if (!offerData.timestamp || !offerData.version) {\n throw new Error('Missing required security fields in offer data \u2013 possible MITM attack');\n }\n \n // Replay attack protection (window reduced to 5 minutes)\n const offerAge = Date.now() - offerData.timestamp;\n const MAX_OFFER_AGE = 300000; // 5 minutes instead of 1 hour\n \n if (offerAge > MAX_OFFER_AGE) {\n this._secureLog('error', 'Offer data is too old - possible replay attack', {\n operationId: operationId,\n offerAge: Math.round(offerAge / 1000),\n maxAllowedAge: Math.round(MAX_OFFER_AGE / 1000),\n timestamp: offerData.timestamp\n });\n \n // Notify the main code about the replay attack\n if (this.onAnswerError) {\n this.onAnswerError('replay_attack', 'Offer data is too old \u2013 possible replay attack');\n }\n \n throw new Error('Offer data is too old \u2013 possible replay attack');\n }\n \n // Protocol version compatibility check\n if (offerData.version !== '4.0') {\n this._secureLog('warn', 'Protocol version mismatch detected', {\n operationId: operationId,\n expectedVersion: '4.0',\n receivedVersion: offerData.version\n });\n \n // For backward compatibility with v3.0, a fallback can be added\n if (offerData.version !== '3.0') {\n throw new Error(`Unsupported protocol version: ${offerData.version}`);\n }\n }\n \n // ============================================\n // PHASE 3: EXTRACT AND VALIDATE SESSION SALT\n // ============================================\n \n // Set session salt from offer\n this.sessionSalt = offerData.salt;\n \n // Validate session salt\n if (!Array.isArray(this.sessionSalt)) {\n throw new Error('Invalid session salt format - must be array');\n }\n \n const expectedSaltLength = offerData.version === '4.0' ? 64 : 32;\n if (this.sessionSalt.length !== expectedSaltLength) {\n throw new Error(`Invalid session salt length: expected ${expectedSaltLength}, got ${this.sessionSalt.length}`);\n }\n \n // MITM Protection: Check salt integrity\n const saltFingerprint = await window.EnhancedSecureCryptoUtils.calculateKeyFingerprint(this.sessionSalt);\n \n this._secureLog('info', 'Session salt validated successfully', {\n operationId: operationId,\n saltLength: this.sessionSalt.length,\n saltFingerprint: saltFingerprint.substring(0, 8)\n });\n \n // ============================================\n // PHASE 4: SECURE GENERATION OF OUR KEYS\n // ============================================\n \n // Secure generation of our keys via mutex\n const keyPairs = await this._generateEncryptionKeys();\n this.ecdhKeyPair = keyPairs.ecdhKeyPair;\n this.ecdsaKeyPair = keyPairs.ecdsaKeyPair;\n \n // Additional validation of generated keys\n if (!(this.ecdhKeyPair?.privateKey instanceof CryptoKey)) {\n this._secureLog('error', 'Local ECDH private key is not a CryptoKey', {\n operationId: operationId,\n hasKeyPair: !!this.ecdhKeyPair,\n privateKeyType: typeof this.ecdhKeyPair?.privateKey,\n privateKeyAlgorithm: this.ecdhKeyPair?.privateKey?.algorithm?.name\n });\n throw new Error('Local ECDH private key is not a valid CryptoKey');\n }\n \n // ============================================\n // PHASE 5: IMPORT AND VERIFY PEER KEYS\n // ============================================\n \n // Import peer ECDSA public key for signature verification\n let peerECDSAPublicKey;\n \n try {\n peerECDSAPublicKey = await crypto.subtle.importKey(\n 'spki',\n new Uint8Array(offerData.ecdsaPublicKey.keyData),\n {\n name: 'ECDSA',\n namedCurve: 'P-384'\n },\n false,\n ['verify']\n );\n } catch (error) {\n this._throwSecureError(error, 'ecdsa_key_import');\n }\n \n // ============================================\n // PHASE 6: IMPORT AND VERIFY ECDH KEY\n // ============================================\n \n // Import and verify ECDH public key using verified ECDSA key\n let peerECDHPublicKey;\n \n try {\n peerECDHPublicKey = await window.EnhancedSecureCryptoUtils.importSignedPublicKey(\n offerData.ecdhPublicKey,\n peerECDSAPublicKey,\n 'ECDH'\n );\n } catch (error) {\n this._secureLog('error', 'Failed to import signed ECDH public key', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n this._throwSecureError(error, 'ecdh_key_import');\n }\n \n // Final validation of ECDH key\n if (!(peerECDHPublicKey instanceof CryptoKey)) {\n this._secureLog('error', 'Peer ECDH public key is not a CryptoKey', {\n operationId: operationId,\n publicKeyType: typeof peerECDHPublicKey,\n publicKeyAlgorithm: peerECDHPublicKey?.algorithm?.name\n });\n throw new Error('Peer ECDH public key is not a valid CryptoKey');\n }\n \n // Save peer key for PFS rotation\n this.peerPublicKey = peerECDHPublicKey;\n \n // ============================================\n // PHASE 7: DERIVE SHARED ENCRYPTION KEYS\n // ============================================\n \n // Derive shared keys with metadata protection\n let derivedKeys;\n \n try {\n derivedKeys = await window.EnhancedSecureCryptoUtils.deriveSharedKeys(\n this.ecdhKeyPair.privateKey,\n peerECDHPublicKey,\n this.sessionSalt\n );\n } catch (error) {\n this._secureLog('error', 'Failed to derive shared keys', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n this._throwSecureError(error, 'key_derivation');\n }\n \n // Securely set keys via helper\n await this._setEncryptionKeys(\n derivedKeys.encryptionKey,\n derivedKeys.macKey,\n derivedKeys.metadataKey,\n derivedKeys.fingerprint\n );\n \n // Additional validation of installed keys\n if (!(this.encryptionKey instanceof CryptoKey) || \n !(this.macKey instanceof CryptoKey) || \n !(this.metadataKey instanceof CryptoKey)) {\n \n this._secureLog('error', 'Invalid key types after derivation', {\n operationId: operationId,\n encryptionKeyType: typeof this.encryptionKey,\n macKeyType: typeof this.macKey,\n metadataKeyType: typeof this.metadataKey\n });\n throw new Error('Invalid key types after derivation');\n }\n \n // Set verification code from offer\n this.verificationCode = offerData.verificationCode;\n \n this._secureLog('info', 'Encryption keys derived and set successfully', {\n operationId: operationId,\n hasEncryptionKey: !!this.encryptionKey,\n hasMacKey: !!this.macKey,\n hasMetadataKey: !!this.metadataKey,\n hasKeyFingerprint: !!this.keyFingerprint,\n mitmProtection: 'enabled',\n signatureVerified: true\n });\n \n // ============================================\n // PHASE 8: UPDATE SECURITY FEATURES\n // ============================================\n \n // Atomic update of security features\n this._updateSecurityFeatures({\n hasEncryption: true,\n hasECDH: true,\n hasECDSA: true,\n hasMutualAuth: true,\n hasMetadataProtection: true,\n hasEnhancedReplayProtection: true,\n hasNonExtractableKeys: true,\n hasRateLimiting: true,\n hasEnhancedValidation: true,\n hasPFS: true\n });\n \n // PFS: Initialize key version tracking\n this.currentKeyVersion = 0;\n this.lastKeyRotation = Date.now();\n this.keyVersions.set(0, {\n salt: this.sessionSalt,\n timestamp: this.lastKeyRotation,\n messageCount: 0\n });\n \n // ============================================\n // PHASE 9: CREATE AUTHENTICATION PROOF\n // ============================================\n \n // Create proof for mutual authentication\n let authProof;\n \n if (offerData.authChallenge) {\n try {\n authProof = await window.EnhancedSecureCryptoUtils.createAuthProof(\n offerData.authChallenge,\n this.ecdsaKeyPair.privateKey,\n this.ecdsaKeyPair.publicKey\n );\n } catch (error) {\n this._secureLog('error', 'Failed to create authentication proof', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n this._throwSecureError(error, 'authentication_proof_creation');\n }\n } else {\n this._secureLog('warn', 'No auth challenge in offer - mutual auth disabled', {\n operationId: operationId\n });\n }\n \n // ============================================\n // PHASE 10: INITIALIZE WEBRTC\n // ============================================\n \n this.isInitiator = false;\n this.onStatusChange('connecting');\n \n // DEBUG: Check keyFingerprint before calling onKeyExchange\n console.log('Before onKeyExchange - keyFingerprint:', this.keyFingerprint);\n this.onKeyExchange(this.keyFingerprint);\n \n // Create peer connection first\n this.createPeerConnection();\n \n // Validate DTLS fingerprint before setting remote description\n if (this.strictDTLSValidation) {\n try {\n const receivedFingerprint = this._extractDTLSFingerprintFromSDP(offerData.sdp);\n \n if (this.expectedDTLSFingerprint) {\n this._validateDTLSFingerprint(receivedFingerprint, this.expectedDTLSFingerprint, 'offer_validation');\n } else {\n // Store fingerprint for future validation (first connection)\n this.expectedDTLSFingerprint = receivedFingerprint;\n this._secureLog('info', 'Stored DTLS fingerprint for future validation', {\n fingerprint: receivedFingerprint,\n context: 'first_connection'\n });\n }\n } catch (error) {\n this._secureLog('warn', 'DTLS fingerprint validation failed - continuing in fallback mode', { \n error: error.message,\n context: 'offer_validation'\n });\n // Continue without strict fingerprint validation for first connection\n // This allows the connection to proceed while maintaining security awareness\n }\n } else {\n this._secureLog('info', 'DTLS fingerprint validation disabled - proceeding without validation');\n }\n\n // Set remote description from offer\n try {\n this._secureLog('debug', 'Setting remote description from offer', {\n operationId: operationId,\n sdpLength: offerData.sdp?.length || 0\n });\n \n await this.peerConnection.setRemoteDescription(new RTCSessionDescription({\n type: 'offer',\n sdp: offerData.sdp\n }));\n \n this._secureLog('debug', 'Remote description set successfully', {\n operationId: operationId,\n signalingState: this.peerConnection.signalingState\n });\n } catch (error) {\n this._secureLog('error', 'Failed to set remote description', { \n error: error.message,\n operationId: operationId\n });\n this._throwSecureError(error, 'webrtc_remote_description');\n }\n \n this._secureLog('debug', '\uD83D\uDD17 Remote description set successfully', {\n operationId: operationId,\n connectionState: this.peerConnection.connectionState,\n signalingState: this.peerConnection.signalingState\n });\n \n // ============================================\n // PHASE 11: CREATE SDP ANSWER\n // ============================================\n \n // Create WebRTC answer\n let answer;\n \n try {\n answer = await this.peerConnection.createAnswer({\n offerToReceiveAudio: false,\n offerToReceiveVideo: false\n });\n } catch (error) {\n this._throwSecureError(error, 'webrtc_create_answer');\n }\n \n // Set local description\n try {\n await this.peerConnection.setLocalDescription(answer);\n } catch (error) {\n this._throwSecureError(error, 'webrtc_local_description');\n }\n \n // Extract and store our DTLS fingerprint for out-of-band verification\n try {\n const ourFingerprint = this._extractDTLSFingerprintFromSDP(answer.sdp);\n this.expectedDTLSFingerprint = ourFingerprint;\n \n this._secureLog('info', 'Generated DTLS fingerprint for out-of-band verification', {\n fingerprint: ourFingerprint,\n context: 'answer_creation'\n });\n \n // Notify UI that fingerprint is ready for out-of-band verification\n this.deliverMessageToUI(`\uD83D\uDD10 DTLS fingerprint ready for verification: ${ourFingerprint}`, 'system');\n } catch (error) {\n this._secureLog('error', 'Failed to extract DTLS fingerprint from answer', { error: error.message });\n // Continue without fingerprint validation (fallback mode)\n }\n \n \n // Await ICE gathering\n await this.waitForIceGathering();\n \n this._secureLog('debug', '\uD83E\uDDCA ICE gathering completed for answer', {\n operationId: operationId,\n iceGatheringState: this.peerConnection.iceGatheringState,\n connectionState: this.peerConnection.connectionState\n });\n \n // ============================================\n // PHASE 12: EXPORT OUR KEYS\n // ============================================\n \n // Export our keys with signatures\n const ecdhPublicKeyData = await window.EnhancedSecureCryptoUtils.exportPublicKeyWithSignature(\n this.ecdhKeyPair.publicKey,\n this.ecdsaKeyPair.privateKey,\n 'ECDH'\n );\n \n const ecdsaPublicKeyData = await window.EnhancedSecureCryptoUtils.exportPublicKeyWithSignature(\n this.ecdsaKeyPair.publicKey,\n this.ecdsaKeyPair.privateKey,\n 'ECDSA'\n );\n \n if (!ecdhPublicKeyData || typeof ecdhPublicKeyData !== 'object') {\n this._secureLog('error', 'CRITICAL: ECDH key export failed - invalid object structure', { operationId });\n throw new Error('CRITICAL SECURITY FAILURE: ECDH key export validation failed - hard abort required');\n }\n \n if (!ecdhPublicKeyData.keyData || !ecdhPublicKeyData.signature) {\n this._secureLog('error', 'CRITICAL: ECDH key export incomplete - missing keyData or signature', { \n operationId,\n hasKeyData: !!ecdhPublicKeyData.keyData,\n hasSignature: !!ecdhPublicKeyData.signature \n });\n throw new Error('CRITICAL SECURITY FAILURE: ECDH key export incomplete - hard abort required');\n }\n \n if (!ecdsaPublicKeyData || typeof ecdsaPublicKeyData !== 'object') {\n this._secureLog('error', 'CRITICAL: ECDSA key export failed - invalid object structure', { operationId });\n throw new Error('CRITICAL SECURITY FAILURE: ECDSA key export validation failed - hard abort required');\n }\n \n if (!ecdsaPublicKeyData.keyData || !ecdsaPublicKeyData.signature) {\n this._secureLog('error', 'CRITICAL: ECDSA key export incomplete - missing keyData or signature', { \n operationId,\n hasKeyData: !!ecdsaPublicKeyData.keyData,\n hasSignature: !!ecdsaPublicKeyData.signature \n });\n throw new Error('CRITICAL SECURITY FAILURE: ECDSA key export incomplete - hard abort required');\n }\n \n // ============================================\n // PHASE 13: SECURITY LEVEL CALCULATION\n // ============================================\n \n // Calculate security level\n let securityLevel;\n \n try {\n securityLevel = await this.calculateSecurityLevel();\n } catch (error) {\n this._secureLog('warn', '\u26A0\uFE0F Security level calculation failed, using fallback', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n \n // Fallback value\n securityLevel = {\n level: 'enhanced',\n score: 80,\n passedChecks: 12,\n totalChecks: 15,\n isRealData: false\n };\n }\n \n // ============================================\n // PHASE 14: CREATE ANSWER PACKAGE\n // ============================================\n \n const currentTimestamp = Date.now();\n \n const answerPackage = {\n // Core information\n type: 'enhanced_secure_answer',\n sdp: this.peerConnection.localDescription.sdp,\n version: '4.0',\n timestamp: currentTimestamp,\n \n // Cryptographic keys\n ecdhPublicKey: ecdhPublicKeyData,\n ecdsaPublicKey: ecdsaPublicKeyData,\n \n // Authentication\n authProof: authProof,\n \n // Security metadata\n securityLevel: securityLevel,\n \n // Additional security fields\n sessionConfirmation: {\n saltFingerprint: saltFingerprint.substring(0, 16),\n keyDerivationSuccess: true,\n mutualAuthEnabled: !!authProof\n },\n \n // Answerer capabilities\n capabilities: {\n supportsFileTransfer: true,\n supportsEnhancedSecurity: true,\n supportsKeyRotation: true,\n supportsFakeTraffic: this.fakeTrafficConfig.enabled,\n supportsDecoyChannels: this.decoyChannelConfig.enabled,\n protocolVersion: '4.0'\n }\n };\n \n // ============================================\n // PHASE 15: VALIDATION AND LOGGING\n // ============================================\n \n // Final validation of the answer package\n if (!answerPackage.sdp || !answerPackage.ecdhPublicKey || !answerPackage.ecdsaPublicKey) {\n throw new Error('Generated answer package is incomplete');\n }\n \n this._secureLog('info', 'Enhanced secure answer created successfully', {\n operationId: operationId,\n version: answerPackage.version,\n hasECDSA: true,\n hasMutualAuth: !!authProof,\n hasSessionConfirmation: !!answerPackage.sessionConfirmation,\n securityLevel: securityLevel.level,\n timestamp: currentTimestamp,\n processingTime: currentTimestamp - offerData.timestamp\n });\n \n // Dispatch event about new connection\n document.dispatchEvent(new CustomEvent('new-connection', {\n detail: { \n type: 'answer',\n timestamp: currentTimestamp,\n securityLevel: securityLevel.level,\n operationId: operationId\n }\n }));\n \n // ============================================\n // PHASE 16: SCHEDULE SECURITY CALCULATIONS\n // ============================================\n \n // Plan security calculation after connection\n setTimeout(async () => {\n try {\n const realSecurityData = await this.calculateAndReportSecurityLevel();\n if (realSecurityData) {\n this.notifySecurityUpdate();\n this._secureLog('info', '\u2705 Post-connection security level calculated', {\n operationId: operationId,\n level: realSecurityData.level\n });\n }\n } catch (error) {\n this._secureLog('error', '\u274C Error calculating post-connection security', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n }\n }, 1000);\n \n // Retry if the first calculation fails\n setTimeout(async () => {\n if (!this.lastSecurityCalculation || this.lastSecurityCalculation.score < 50) {\n this._secureLog('info', '\uD83D\uDD04 Retrying security calculation', {\n operationId: operationId\n });\n await this.calculateAndReportSecurityLevel();\n this.notifySecurityUpdate();\n }\n }, 3000);\n \n // Final security update\n this.notifySecurityUpdate();\n \n // ============================================\n // PHASE 17: RETURN RESULT\n // ============================================\n \n return answerPackage;\n \n } catch (error) {\n // ============================================\n // ERROR HANDLING\n // ============================================\n \n this._secureLog('error', '\u274C Enhanced secure answer creation failed in critical section', {\n operationId: operationId,\n errorType: error.constructor.name,\n errorMessage: error.message,\n phase: this._determineAnswerErrorPhase(error),\n offerAge: offerData?.timestamp ? Date.now() - offerData.timestamp : 'unknown'\n });\n \n // Cleanup state on error\n this._cleanupFailedAnswerCreation();\n \n // Update status\n this.onStatusChange('disconnected');\n \n // Special handling of security errors\n if (this.onAnswerError) {\n if (error.message.includes('too old') || error.message.includes('replay')) {\n this.onAnswerError('replay_attack', error.message);\n } else if (error.message.includes('MITM') || error.message.includes('signature')) {\n this.onAnswerError('security_violation', error.message);\n } else if (error.message.includes('validation') || error.message.includes('format')) {\n this.onAnswerError('invalid_format', error.message);\n } else {\n this.onAnswerError('general_error', error.message);\n }\n }\n \n // Re-throw for upper-level handling\n throw error;\n }\n }, 20000); // 20 seconds timeout for the entire answer creation (longer than offer)\n }\n\n /**\n * HELPER: Determine error phase for answer\n */\n _determineAnswerErrorPhase(error) {\n const message = error.message.toLowerCase();\n \n if (message.includes('validation') || message.includes('format')) return 'offer_validation';\n if (message.includes('rate limit')) return 'rate_limiting';\n if (message.includes('replay') || message.includes('too old')) return 'replay_protection';\n if (message.includes('salt')) return 'salt_validation';\n if (message.includes('key pair') || message.includes('generate')) return 'key_generation';\n if (message.includes('import') || message.includes('ecdsa') || message.includes('ecdh')) return 'key_import';\n if (message.includes('signature') || message.includes('mitm')) return 'signature_verification';\n if (message.includes('derive') || message.includes('shared')) return 'key_derivation';\n if (message.includes('auth') || message.includes('proof')) return 'authentication';\n if (message.includes('remote description') || message.includes('local description')) return 'webrtc_setup';\n if (message.includes('answer') || message.includes('sdp')) return 'sdp_creation';\n if (message.includes('export')) return 'key_export';\n if (message.includes('security level')) return 'security_calculation';\n \n return 'unknown';\n }\n\n /**\n * HELPER: Cleanup state after failed answer creation\n */\n /**\n * Secure cleanup state after failed answer creation\n */\n _cleanupFailedAnswerCreation() {\n try {\n // Secure wipe of cryptographic materials\n this._secureCleanupCryptographicMaterials();\n \n // Secure wipe of PFS key versions\n this.currentKeyVersion = 0;\n this.keyVersions.clear();\n this.oldKeys.clear();\n \n // Close peer connection if created\n if (this.peerConnection) {\n this.peerConnection.close();\n this.peerConnection = null;\n }\n \n // Clear data channel\n if (this.dataChannel) {\n this.dataChannel.close();\n this.dataChannel = null;\n }\n \n // Reset flags and counters\n this.isInitiator = false;\n this.isVerified = false;\n this.sequenceNumber = 0;\n this.expectedSequenceNumber = 0;\n this.messageCounter = 0;\n this.processedMessageIds.clear();\n this.replayWindow.clear(); // Clear replay window\n \n // Reset security features to baseline\n this._updateSecurityFeatures({\n hasEncryption: false,\n hasECDH: false,\n hasECDSA: false,\n hasMutualAuth: false,\n hasMetadataProtection: false,\n hasEnhancedReplayProtection: false,\n hasNonExtractableKeys: false,\n hasEnhancedValidation: false,\n hasPFS: false\n });\n \n // Force garbage collection\n this._forceGarbageCollection();\n \n this._secureLog('debug', '\uD83D\uDD12 Failed answer creation cleanup completed with secure memory wipe');\n \n } catch (cleanupError) {\n this._secureLog('error', '\u274C Error during answer creation cleanup', {\n errorType: cleanupError.constructor.name,\n errorMessage: cleanupError.message\n });\n }\n }\n\n /**\n * HELPER: Securely set encryption keys (if not set yet)\n */\n async _setEncryptionKeys(encryptionKey, macKey, metadataKey, keyFingerprint) {\n return this._withMutex('keyOperation', async (operationId) => {\n this._secureLog('info', '\uD83D\uDD10 Setting encryption keys with mutex', {\n operationId: operationId\n });\n \n // Validate all keys before setting\n if (!(encryptionKey instanceof CryptoKey) ||\n !(macKey instanceof CryptoKey) ||\n !(metadataKey instanceof CryptoKey)) {\n throw new Error('Invalid key types provided');\n }\n \n if (!keyFingerprint || typeof keyFingerprint !== 'string') {\n throw new Error('Invalid key fingerprint provided');\n }\n \n // Atomically set all keys\n const oldKeys = {\n encryptionKey: this.encryptionKey,\n macKey: this.macKey,\n metadataKey: this.metadataKey,\n keyFingerprint: this.keyFingerprint\n };\n \n try {\n this.encryptionKey = encryptionKey;\n this.macKey = macKey;\n this.metadataKey = metadataKey;\n this.keyFingerprint = keyFingerprint;\n \n // Reset counters\n this.sequenceNumber = 0;\n this.expectedSequenceNumber = 0;\n this.messageCounter = 0;\n this.processedMessageIds.clear();\n this.replayWindow.clear(); // Clear replay window\n \n this._secureLog('info', '\u2705 Encryption keys set successfully', {\n operationId: operationId,\n hasAllKeys: !!(this.encryptionKey && this.macKey && this.metadataKey),\n hasFingerprint: !!this.keyFingerprint\n });\n \n return true;\n \n } catch (error) {\n // Roll back on error\n this.encryptionKey = oldKeys.encryptionKey;\n this.macKey = oldKeys.macKey;\n this.metadataKey = oldKeys.metadataKey;\n this.keyFingerprint = oldKeys.keyFingerprint;\n \n this._secureLog('error', '\u274C Key setting failed, rolled back', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n \n throw error;\n }\n });\n }\n\n async handleSecureAnswer(answerData) {\n console.log('\uD83C\uDFAF handleSecureAnswer called with answerData:', answerData ? 'present' : 'null');\n try {\n \n if (!answerData || typeof answerData !== 'object' || Array.isArray(answerData)) {\n this._secureLog('error', 'CRITICAL: Invalid answer data structure', { \n hasAnswerData: !!answerData,\n answerDataType: typeof answerData,\n isArray: Array.isArray(answerData)\n });\n throw new Error('CRITICAL SECURITY FAILURE: Answer data must be a non-null object');\n }\n \n if (answerData.type !== 'enhanced_secure_answer' || !answerData.sdp) {\n this._secureLog('error', 'CRITICAL: Invalid answer format', { \n type: answerData.type,\n hasSdp: !!answerData.sdp\n });\n throw new Error('CRITICAL SECURITY FAILURE: Invalid answer format - hard abort required');\n }\n\n // CRITICAL: Strict validation of ECDH public key structure\n if (!answerData.ecdhPublicKey || typeof answerData.ecdhPublicKey !== 'object' || Array.isArray(answerData.ecdhPublicKey)) {\n this._secureLog('error', 'CRITICAL: Invalid ECDH public key structure in answer', { \n hasEcdhKey: !!answerData.ecdhPublicKey,\n ecdhKeyType: typeof answerData.ecdhPublicKey,\n isArray: Array.isArray(answerData.ecdhPublicKey)\n });\n throw new Error('CRITICAL SECURITY FAILURE: Missing or invalid ECDH public key structure');\n }\n \n if (!answerData.ecdhPublicKey.keyData || !answerData.ecdhPublicKey.signature) {\n this._secureLog('error', 'CRITICAL: ECDH key missing keyData or signature in answer', { \n hasKeyData: !!answerData.ecdhPublicKey.keyData,\n hasSignature: !!answerData.ecdhPublicKey.signature\n });\n throw new Error('CRITICAL SECURITY FAILURE: ECDH key missing keyData or signature');\n }\n\n // CRITICAL: Strict validation of ECDSA public key structure\n if (!answerData.ecdsaPublicKey || typeof answerData.ecdsaPublicKey !== 'object' || Array.isArray(answerData.ecdsaPublicKey)) {\n this._secureLog('error', 'CRITICAL: Invalid ECDSA public key structure in answer', { \n hasEcdsaKey: !!answerData.ecdsaPublicKey,\n ecdsaKeyType: typeof answerData.ecdsaPublicKey,\n isArray: Array.isArray(answerData.ecdsaPublicKey)\n });\n throw new Error('CRITICAL SECURITY FAILURE: Missing or invalid ECDSA public key structure');\n }\n \n if (!answerData.ecdsaPublicKey.keyData || !answerData.ecdsaPublicKey.signature) {\n this._secureLog('error', 'CRITICAL: ECDSA key missing keyData or signature in answer', { \n hasKeyData: !!answerData.ecdsaPublicKey.keyData,\n hasSignature: !!answerData.ecdsaPublicKey.signature\n });\n throw new Error('CRITICAL SECURITY FAILURE: ECDSA key missing keyData or signature');\n }\n\n // Additional MITM protection: Validate answer data structure\n if (!answerData.timestamp || !answerData.version) {\n throw new Error('Missing required fields in response data \u2013 possible MITM attack');\n }\n\n // MITM Protection: Verify session ID if present (for enhanced security)\n if (answerData.sessionId && this.sessionId && answerData.sessionId !== this.sessionId) {\n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'Session ID mismatch detected - possible MITM attack', {\n expectedSessionId: this.sessionId,\n receivedSessionId: answerData.sessionId\n });\n throw new Error('Session ID mismatch \u2013 possible MITM attack');\n }\n\n // Check for replay attacks (reject answers older than 1 hour)\n const answerAge = Date.now() - answerData.timestamp;\n if (answerAge > 3600000) { // 1 hour in milliseconds\n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'Answer data is too old - possible replay attack', {\n answerAge: answerAge,\n timestamp: answerData.timestamp\n });\n \n // Notify the main code about the replay attack error\n if (this.onAnswerError) {\n this.onAnswerError('replay_attack', 'Response data is too old \u2013 possible replay attack');\n }\n \n throw new Error('Response data is too old \u2013 possible replay attack');\n }\n\n // Check protocol version compatibility\n if (answerData.version !== '4.0') {\n window.EnhancedSecureCryptoUtils.secureLog.log('warn', 'Incompatible protocol version in answer', {\n expectedVersion: '4.0',\n receivedVersion: answerData.version\n });\n }\n\n // Import ECDSA public key for verification (self-signed)\n const peerECDSAPublicKey = await crypto.subtle.importKey(\n 'spki',\n new Uint8Array(answerData.ecdsaPublicKey.keyData),\n {\n name: 'ECDSA',\n namedCurve: 'P-384'\n },\n false,\n ['verify']\n );\n\n\n // Now import and verify the ECDH public key using the verified ECDSA key\n const peerPublicKey = await window.EnhancedSecureCryptoUtils.importPublicKeyFromSignedPackage(\n answerData.ecdhPublicKey,\n peerECDSAPublicKey\n );\n \n // Additional MITM protection: Verify session salt integrity\n if (!this.sessionSalt || this.sessionSalt.length !== 64) {\n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'Invalid session salt detected - possible session hijacking', {\n saltLength: this.sessionSalt ? this.sessionSalt.length : 0\n });\n throw new Error('Invalid session salt \u2013 possible session hijacking attempt');\n }\n\n // Verify that the session salt hasn't been tampered with\n const expectedSaltHash = await window.EnhancedSecureCryptoUtils.calculateKeyFingerprint(this.sessionSalt);\n window.EnhancedSecureCryptoUtils.secureLog.log('info', 'Session salt integrity verified', {\n saltFingerprint: expectedSaltHash.substring(0, 8)\n });\n\n // Additional validation: Ensure all keys are CryptoKey instances before derivation\n if (!(this.ecdhKeyPair?.privateKey instanceof CryptoKey)) {\n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'Local ECDH private key is not a CryptoKey in handleSecureAnswer', {\n hasKeyPair: !!this.ecdhKeyPair,\n privateKeyType: typeof this.ecdhKeyPair?.privateKey,\n privateKeyAlgorithm: this.ecdhKeyPair?.privateKey?.algorithm?.name\n });\n throw new Error('Local ECDH private key is not a CryptoKey');\n }\n \n if (!(peerPublicKey instanceof CryptoKey)) {\n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'Peer ECDH public key is not a CryptoKey in handleSecureAnswer', {\n publicKeyType: typeof peerPublicKey,\n publicKeyAlgorithm: peerPublicKey?.algorithm?.name\n });\n throw new Error('Peer ECDH public key is not a CryptoKey');\n }\n\n // Store peer's public key for PFS key rotation\n this.peerPublicKey = peerPublicKey;\n \n // Initialize connection ID if not already set\n if (!this.connectionId) {\n this.connectionId = Array.from(crypto.getRandomValues(new Uint8Array(8)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n }\n\n \n const derivedKeys = await window.EnhancedSecureCryptoUtils.deriveSharedKeys(\n this.ecdhKeyPair.privateKey,\n peerPublicKey,\n this.sessionSalt\n );\n \n this.encryptionKey = derivedKeys.encryptionKey;\n this.macKey = derivedKeys.macKey;\n this.metadataKey = derivedKeys.metadataKey;\n this.keyFingerprint = derivedKeys.fingerprint;\n this.sequenceNumber = 0;\n this.expectedSequenceNumber = 0;\n this.messageCounter = 0;\n this.processedMessageIds.clear();\n this.replayWindow.clear(); // Clear replay window\n // Validate that all keys are properly set\n if (!(this.encryptionKey instanceof CryptoKey) || \n !(this.macKey instanceof CryptoKey) || \n !(this.metadataKey instanceof CryptoKey)) {\n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'Invalid key types after derivation in handleSecureAnswer', {\n encryptionKeyType: typeof this.encryptionKey,\n macKeyType: typeof this.macKey,\n metadataKeyType: typeof this.metadataKey,\n encryptionKeyAlgorithm: this.encryptionKey?.algorithm?.name,\n macKeyAlgorithm: this.macKey?.algorithm?.name,\n metadataKeyAlgorithm: this.metadataKey?.algorithm?.name\n });\n throw new Error('Invalid key types after export');\n }\n \n this._secureLog('info', 'Encryption keys set in handleSecureAnswer', {\n hasEncryptionKey: !!this.encryptionKey,\n hasMacKey: !!this.macKey,\n hasMetadataKey: !!this.metadataKey,\n hasKeyFingerprint: !!this.keyFingerprint,\n mitmProtection: 'enabled',\n signatureVerified: true\n });\n \n // Update security features for initiator after successful key exchange\n this.securityFeatures.hasMutualAuth = true;\n this.securityFeatures.hasMetadataProtection = true;\n this.securityFeatures.hasEnhancedReplayProtection = true;\n this.securityFeatures.hasPFS = true;\n \n // PFS: Initialize key version tracking\n this.currentKeyVersion = 0;\n this.lastKeyRotation = Date.now();\n this.keyVersions.set(0, {\n salt: this.sessionSalt,\n timestamp: this.lastKeyRotation,\n messageCount: 0\n });\n \n this.onKeyExchange(this.keyFingerprint);\n\n // Compute SAS for MITM protection (Offer side - Answer handler)\n try {\n console.log('Starting SAS computation for Offer side (Answer handler)');\n const remoteFP = this._extractDTLSFingerprintFromSDP(answerData.sdp); // \u0443\u0436\u0435 \u0435\u0441\u0442\u044C \u0432 \u043A\u043E\u0434\u0435\n const localFP = this.expectedDTLSFingerprint; // \u0442\u044B \u0435\u0433\u043E \u0441\u043E\u0445\u0440\u0430\u043D\u044F\u0435\u0448\u044C \u043F\u0440\u0438 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0438 \u043E\u0444\u0444\u0435\u0440\u0430/\u043E\u0442\u0432\u0435\u0442\u0430\n const keyBytes = this._decodeKeyFingerprint(this.keyFingerprint); // \u0443\u0442\u0438\u043B\u0438\u0442\u0430 \u0434\u0435\u043A\u043E\u0434\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F\n console.log('SAS computation parameters:', { \n remoteFP: remoteFP ? remoteFP.substring(0, 16) + '...' : 'null/undefined', \n localFP: localFP ? localFP.substring(0, 16) + '...' : 'null/undefined', \n keyBytesLength: keyBytes ? keyBytes.length : 'null/undefined',\n keyBytesType: keyBytes ? keyBytes.constructor.name : 'null/undefined'\n });\n\n this.verificationCode = await this._computeSAS(keyBytes, localFP, remoteFP);\n this.onStatusChange?.('verifying'); // \u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u043C SAS \u0438 \u0436\u0434\u0451\u043C \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F\n this.onVerificationRequired(this.verificationCode);\n \n // CRITICAL: Store SAS code to send when data channel opens\n this.pendingSASCode = this.verificationCode;\n console.log('\uD83D\uDCE4 SAS code ready to send when data channel opens:', this.verificationCode);\n \n this._secureLog('info', 'SAS verification code generated for MITM protection (Offer side)', {\n sasCode: this.verificationCode,\n localFP: localFP.substring(0, 16) + '...',\n remoteFP: remoteFP.substring(0, 16) + '...',\n timestamp: Date.now()\n });\n } catch (sasError) {\n console.error('SAS computation failed in handleSecureAnswer (Offer side):', sasError);\n this._secureLog('error', 'SAS computation failed in handleSecureAnswer (Offer side)', {\n error: sasError.message,\n stack: sasError.stack,\n timestamp: Date.now()\n });\n }\n\n // Validate DTLS fingerprint before setting remote description\n if (this.strictDTLSValidation) {\n try {\n const receivedFingerprint = this._extractDTLSFingerprintFromSDP(answerData.sdp);\n \n if (this.expectedDTLSFingerprint) {\n this._validateDTLSFingerprint(receivedFingerprint, this.expectedDTLSFingerprint, 'answer_validation');\n } else {\n // Store fingerprint for future validation (first connection)\n this.expectedDTLSFingerprint = receivedFingerprint;\n this._secureLog('info', 'Stored DTLS fingerprint for future validation', {\n fingerprint: receivedFingerprint,\n context: 'first_connection'\n });\n }\n } catch (error) {\n this._secureLog('warn', 'DTLS fingerprint validation failed - continuing in fallback mode', { \n error: error.message,\n context: 'answer_validation'\n });\n\n }\n } else {\n this._secureLog('info', 'DTLS fingerprint validation disabled - proceeding without validation');\n }\n\n this._secureLog('debug', 'Setting remote description from answer', {\n sdpLength: answerData.sdp?.length || 0\n });\n \n await this.peerConnection.setRemoteDescription({\n type: 'answer',\n sdp: answerData.sdp\n });\n \n this._secureLog('debug', 'Remote description set successfully from answer', {\n signalingState: this.peerConnection.signalingState\n });\n \n console.log('Enhanced secure connection established');\n\n setTimeout(async () => {\n try {\n const securityData = await this.calculateAndReportSecurityLevel();\n if (securityData) {\n console.log('\u2705 Security level calculated after connection:', securityData.level);\n this.notifySecurityUpdate();\n }\n } catch (error) {\n this._secureLog('error', '\u274C Error calculating security after connection:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }, 1000);\n setTimeout(async () => {\n if (!this.lastSecurityCalculation || this.lastSecurityCalculation.score < 50) {\n console.log('\uD83D\uDD04 Retrying security calculation...');\n await this.calculateAndReportSecurityLevel();\n this.notifySecurityUpdate();\n }\n }, 3000);\n this.notifySecurityUpdate();\n } catch (error) {\n this._secureLog('error', 'Enhanced secure answer handling failed', {\n errorType: error.constructor.name\n });\n this.onStatusChange('failed');\n\n if (this.onAnswerError) {\n if (error.message.includes('too old') || error.message.includes('\u0441\u043B\u0438\u0448\u043A\u043E\u043C \u0441\u0442\u0430\u0440\u044B\u0435')) {\n this.onAnswerError('replay_attack', error.message);\n } else if (error.message.includes('MITM') || error.message.includes('signature') || error.message.includes('\u043F\u043E\u0434\u043F\u0438\u0441\u044C')) {\n this.onAnswerError('security_violation', error.message);\n } else {\n this.onAnswerError('general_error', error.message);\n }\n }\n \n throw error;\n }\n }\n\n forceSecurityUpdate() {\n console.log('\uD83D\uDD04 Force security update requested');\n setTimeout(async () => {\n try {\n const securityData = await this.calculateAndReportSecurityLevel();\n if (securityData) {\n this.notifySecurityUpdate();\n console.log('\u2705 Force security update completed');\n }\n } catch (error) {\n this._secureLog('error', '\u274C Force security update failed:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }, 100);\n }\n\n initiateVerification() {\n \n if (this.isInitiator) {\n // Ensure verification initiation notice wasn't already sent\n if (!this.verificationInitiationSent) {\n this.verificationInitiationSent = true;\n this.deliverMessageToUI('\uD83D\uDD10 CRITICAL: Compare verification code with peer out-of-band (voice/video/in-person) to prevent MITM attack!', 'system');\n this.deliverMessageToUI(`\uD83D\uDD10 Your verification code: ${this.verificationCode}`, 'system');\n this.deliverMessageToUI('\uD83D\uDD10 Ask peer to confirm this exact code before allowing traffic!', 'system');\n }\n } else {\n // Answer side: Wait for SAS code from Offer side\n console.log('\uD83D\uDCE5 Answer side: Waiting for SAS code from Offer side');\n this.deliverMessageToUI('\uD83D\uDCE5 Waiting for verification code from peer...', 'system');\n }\n }\n\n confirmVerification() {\n \n try {\n console.log('\uD83D\uDCE4 confirmVerification - sending local confirmation');\n \n // Mark local verification as confirmed\n this.localVerificationConfirmed = true;\n \n // Send confirmation to peer\n const confirmationPayload = {\n type: 'verification_confirmed',\n data: {\n timestamp: Date.now(),\n verificationMethod: 'SAS',\n securityLevel: 'MITM_PROTECTION_REQUIRED'\n }\n };\n \n console.log('\uD83D\uDCE4 Sending verification confirmation:', confirmationPayload);\n this.dataChannel.send(JSON.stringify(confirmationPayload));\n \n // Notify UI about state change\n if (this.onVerificationStateChange) {\n this.onVerificationStateChange({\n localConfirmed: this.localVerificationConfirmed,\n remoteConfirmed: this.remoteVerificationConfirmed,\n bothConfirmed: this.bothVerificationsConfirmed\n });\n }\n \n // Check if both parties have confirmed\n this._checkBothVerificationsConfirmed();\n \n // Notify UI about local confirmation\n this.deliverMessageToUI('\u2705 You confirmed the verification code. Waiting for peer confirmation...', 'system');\n \n this.processMessageQueue();\n } catch (error) {\n this._secureLog('error', '\u274C SAS verification failed:', { errorType: error?.constructor?.name || 'Unknown' });\n this.deliverMessageToUI('\u274C SAS verification failed', 'system');\n }\n }\n\n _checkBothVerificationsConfirmed() {\n // Check if both parties have confirmed verification\n if (this.localVerificationConfirmed && this.remoteVerificationConfirmed && !this.bothVerificationsConfirmed) {\n console.log('\uD83C\uDF89 Both parties confirmed verification!');\n this.bothVerificationsConfirmed = true;\n \n // Notify both parties that verification is complete\n const bothConfirmedPayload = {\n type: 'verification_both_confirmed',\n data: {\n timestamp: Date.now(),\n verificationMethod: 'SAS',\n securityLevel: 'MITM_PROTECTION_COMPLETE'\n }\n };\n \n console.log('\uD83D\uDCE4 Sending both confirmed notification:', bothConfirmedPayload);\n this.dataChannel.send(JSON.stringify(bothConfirmedPayload));\n \n // Notify UI about state change\n if (this.onVerificationStateChange) {\n this.onVerificationStateChange({\n localConfirmed: this.localVerificationConfirmed,\n remoteConfirmed: this.remoteVerificationConfirmed,\n bothConfirmed: this.bothVerificationsConfirmed\n });\n }\n \n // Set verified status and open chat after 2 second delay\n this.deliverMessageToUI('\uD83C\uDF89 Both parties confirmed! Opening secure chat in 2 seconds...', 'system');\n \n setTimeout(() => {\n this._setVerifiedStatus(true, 'MUTUAL_SAS_CONFIRMED', { \n code: this.verificationCode,\n timestamp: Date.now()\n });\n this._enforceVerificationGate('mutual_confirmed', false);\n this.onStatusChange?.('verified');\n }, 2000);\n }\n }\n\n handleVerificationConfirmed(data) {\n // Handle peer's verification confirmation\n console.log('\uD83D\uDCE5 Received verification confirmation from peer');\n this.remoteVerificationConfirmed = true;\n \n // Notify UI about peer confirmation\n this.deliverMessageToUI('\u2705 Peer confirmed the verification code. Waiting for your confirmation...', 'system');\n \n // Notify UI about state change\n if (this.onVerificationStateChange) {\n this.onVerificationStateChange({\n localConfirmed: this.localVerificationConfirmed,\n remoteConfirmed: this.remoteVerificationConfirmed,\n bothConfirmed: this.bothVerificationsConfirmed\n });\n }\n \n // Check if both parties have confirmed\n this._checkBothVerificationsConfirmed();\n }\n\n handleVerificationBothConfirmed(data) {\n // Handle notification that both parties have confirmed\n console.log('\uD83D\uDCE5 Received both confirmed notification from peer');\n this.bothVerificationsConfirmed = true;\n \n // Notify UI about state change\n if (this.onVerificationStateChange) {\n this.onVerificationStateChange({\n localConfirmed: this.localVerificationConfirmed,\n remoteConfirmed: this.remoteVerificationConfirmed,\n bothConfirmed: this.bothVerificationsConfirmed\n });\n }\n \n // Set verified status and open chat after 2 second delay\n this.deliverMessageToUI('\uD83C\uDF89 Both parties confirmed! Opening secure chat in 2 seconds...', 'system');\n \n setTimeout(() => {\n this._setVerifiedStatus(true, 'MUTUAL_SAS_CONFIRMED', { \n code: this.verificationCode,\n timestamp: Date.now()\n });\n this._enforceVerificationGate('mutual_confirmed', false);\n this.onStatusChange?.('verified');\n }, 2000);\n }\n\n handleVerificationRequest(data) {\n \n console.log('\uD83D\uDD0D handleVerificationRequest called with:');\n console.log(' - receivedCode:', data.code, '(type:', typeof data.code, ')');\n console.log(' - expectedCode:', this.verificationCode, '(type:', typeof this.verificationCode, ')');\n console.log(' - codesMatch:', data.code === this.verificationCode);\n console.log(' - data object:', data);\n \n if (data.code === this.verificationCode) {\n // \u2705 SAS verification successful - MITM protection confirmed\n const responsePayload = {\n type: 'verification_response',\n data: {\n ok: true,\n timestamp: Date.now(),\n verificationMethod: 'SAS', // Indicate SAS was used\n securityLevel: 'MITM_PROTECTED'\n }\n };\n this.dataChannel.send(JSON.stringify(responsePayload));\n \n // Ensure verification success notice wasn't already sent\n if (!this.verificationNotificationSent) {\n this.verificationNotificationSent = true;\n this.deliverMessageToUI('\u2705 SAS verification successful! MITM protection confirmed. Channel is now secure!', 'system');\n }\n \n this.processMessageQueue();\n } else {\n // \u274C SAS verification failed - possible MITM attack\n console.log('\u274C SAS verification failed - codes do not match, disconnecting');\n const responsePayload = {\n type: 'verification_response',\n data: {\n ok: false,\n timestamp: Date.now(),\n reason: 'code_mismatch'\n }\n };\n this.dataChannel.send(JSON.stringify(responsePayload));\n \n this._secureLog('error', 'SAS verification failed - possible MITM attack', {\n receivedCode: data.code,\n expectedCode: this.verificationCode,\n timestamp: Date.now()\n });\n \n this.deliverMessageToUI('\u274C SAS verification failed! Possible MITM attack detected. Connection aborted for safety!', 'system');\n this.disconnect();\n }\n }\n\n handleSASCode(data) {\n \n console.log('\uD83D\uDCE5 Received SAS code from Offer side:', data.code);\n \n this.verificationCode = data.code;\n this.onStatusChange?.('verifying'); // \u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u043C SAS \u0438 \u0436\u0434\u0451\u043C \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F\n this.onVerificationRequired(this.verificationCode);\n \n this._secureLog('info', 'SAS code received from Offer side', {\n sasCode: this.verificationCode,\n timestamp: Date.now()\n });\n }\n\n handleVerificationResponse(data) {\n \n if (data.ok === true) {\n \n // Log successful mutual SAS verification\n this._secureLog('info', 'Mutual SAS verification completed - MITM protection active', {\n verificationMethod: data.verificationMethod || 'SAS',\n securityLevel: data.securityLevel || 'MITM_PROTECTED',\n timestamp: Date.now()\n });\n \n // Ensure verification success notice wasn't already sent\n if (!this.verificationNotificationSent) {\n this.verificationNotificationSent = true;\n this.deliverMessageToUI('\u2705 Mutual SAS verification complete! MITM protection active. Channel is now secure!', 'system');\n }\n \n this.processMessageQueue();\n } else {\n // \u274C Peer verification failed - connection not secure\n this._secureLog('error', 'Peer SAS verification failed - connection not secure', {\n responseData: data,\n timestamp: Date.now()\n });\n \n this.deliverMessageToUI('\u274C Peer verification failed! Connection not secure!', 'system');\n this.disconnect();\n }\n }\n\n validateOfferData(offerData) {\n return offerData &&\n offerData.type === 'enhanced_secure_offer' &&\n offerData.sdp &&\n offerData.publicKey &&\n offerData.salt &&\n offerData.verificationCode &&\n Array.isArray(offerData.publicKey) &&\n Array.isArray(offerData.salt) &&\n offerData.salt.length === 32;\n }\n\n validateEnhancedOfferData(offerData) {\n console.log('\uD83C\uDFAF validateEnhancedOfferData called with:', offerData ? 'valid object' : 'null/undefined');\n try {\n // CRITICAL: Strict type checking to prevent syntax errors\n if (!offerData || typeof offerData !== 'object' || Array.isArray(offerData)) {\n this._secureLog('error', 'CRITICAL: Invalid offer data structure', { \n hasOfferData: !!offerData,\n offerDataType: typeof offerData,\n isArray: Array.isArray(offerData)\n });\n throw new Error('CRITICAL SECURITY FAILURE: Offer data must be a non-null object');\n }\n\n // Basic required fields for all versions\n const basicFields = ['type', 'sdp'];\n for (const field of basicFields) {\n if (!offerData[field]) {\n throw new Error(`Missing required field: ${field}`);\n }\n }\n\n // Validate offer type (support both v3.0 and v4.0 formats)\n if (!['enhanced_secure_offer', 'secure_offer'].includes(offerData.type)) {\n throw new Error('Invalid offer type');\n }\n\n // Check if this is v4.0 format with enhanced features\n const isV4Format = offerData.version === '4.0' && offerData.ecdhPublicKey && offerData.ecdsaPublicKey;\n \n if (isV4Format) {\n // v4.0 enhanced validation\n const v4RequiredFields = [\n 'ecdhPublicKey', 'ecdsaPublicKey', 'salt', 'verificationCode',\n 'authChallenge', 'timestamp', 'version', 'securityLevel'\n ];\n\n for (const field of v4RequiredFields) {\n if (!offerData[field]) {\n throw new Error(`Missing v4.0 field: ${field}`);\n }\n }\n\n // Validate salt (must be 64 bytes for v4.0)\n if (!Array.isArray(offerData.salt) || offerData.salt.length !== 64) {\n throw new Error('Salt must be exactly 64 bytes for v4.0');\n }\n\n // Validate timestamp (not older than 1 hour)\n const offerAge = Date.now() - offerData.timestamp;\n if (offerAge > 3600000) {\n throw new Error('Offer is too old (older than 1 hour)');\n }\n\n // CRITICAL: Strict validation of key structures to prevent syntax errors\n if (!offerData.ecdhPublicKey || typeof offerData.ecdhPublicKey !== 'object' || Array.isArray(offerData.ecdhPublicKey)) {\n this._secureLog('error', 'CRITICAL: Invalid ECDH public key structure', { \n hasEcdhKey: !!offerData.ecdhPublicKey,\n ecdhKeyType: typeof offerData.ecdhPublicKey,\n isArray: Array.isArray(offerData.ecdhPublicKey)\n });\n throw new Error('CRITICAL SECURITY FAILURE: Invalid ECDH public key structure - hard abort required');\n }\n\n if (!offerData.ecdsaPublicKey || typeof offerData.ecdsaPublicKey !== 'object' || Array.isArray(offerData.ecdsaPublicKey)) {\n this._secureLog('error', 'CRITICAL: Invalid ECDSA public key structure', { \n hasEcdsaKey: !!offerData.ecdsaPublicKey,\n ecdsaKeyType: typeof offerData.ecdsaPublicKey,\n isArray: Array.isArray(offerData.ecdsaPublicKey)\n });\n throw new Error('CRITICAL SECURITY FAILURE: Invalid ECDSA public key structure - hard abort required');\n }\n\n // CRITICAL: Validate key internal structure to prevent syntax errors\n if (!offerData.ecdhPublicKey.keyData || !offerData.ecdhPublicKey.signature) {\n this._secureLog('error', 'CRITICAL: ECDH key missing keyData or signature', { \n hasKeyData: !!offerData.ecdhPublicKey.keyData,\n hasSignature: !!offerData.ecdhPublicKey.signature\n });\n throw new Error('CRITICAL SECURITY FAILURE: ECDH key missing keyData or signature');\n }\n\n if (!offerData.ecdsaPublicKey.keyData || !offerData.ecdsaPublicKey.signature) {\n this._secureLog('error', 'CRITICAL: ECDSA key missing keyData or signature', { \n hasKeyData: !!offerData.ecdsaPublicKey.keyData,\n hasSignature: !!offerData.ecdsaPublicKey.signature\n });\n throw new Error('CRITICAL SECURITY FAILURE: ECDSA key missing keyData or signature');\n }\n\n if (typeof offerData.verificationCode !== 'string' || offerData.verificationCode.length < 6) {\n throw new Error('Invalid SAS verification code format - MITM protection required');\n }\n\n this._secureLog('info', 'v4.0 offer validation passed', {\n version: offerData.version,\n hasSecurityLevel: !!offerData.securityLevel?.level,\n offerAge: Math.round(offerAge / 1000) + 's'\n });\n } else {\n // v3.0 backward compatibility validation\n // NOTE: v3.0 has limited security - SAS verification is still critical\n const v3RequiredFields = ['publicKey', 'salt', 'verificationCode'];\n for (const field of v3RequiredFields) {\n if (!offerData[field]) {\n throw new Error(`Missing v3.0 field: ${field}`);\n }\n }\n\n // Validate salt (32 bytes for v3.0)\n if (!Array.isArray(offerData.salt) || offerData.salt.length !== 32) {\n throw new Error('Salt must be exactly 32 bytes for v3.0');\n }\n\n // Validate public key\n if (!Array.isArray(offerData.publicKey)) {\n throw new Error('Invalid public key format for v3.0');\n }\n\n window.EnhancedSecureCryptoUtils.secureLog.log('info', 'v3.0 offer validation passed (backward compatibility)', {\n version: 'v3.0',\n legacy: true\n });\n }\n\n // Validate SDP structure (basic check for all versions)\n if (typeof offerData.sdp !== 'string' || !offerData.sdp.includes('v=0')) {\n throw new Error('Invalid SDP structure');\n }\n\n console.log('\uD83C\uDFAF validateEnhancedOfferData completed successfully');\n return true;\n } catch (error) {\n console.log('\uD83C\uDFAF validateEnhancedOfferData ERROR:', error.message);\n this._secureLog('error', 'CRITICAL: Security validation failed - hard abort required', {\n error: error.message,\n errorType: error.constructor.name,\n timestamp: Date.now()\n });\n\n throw new Error(`CRITICAL SECURITY VALIDATION FAILURE: ${error.message}`);\n }\n }\n\n async sendSecureMessage(message) {\n // Comprehensive input validation\n const validation = this._validateInputData(message, 'sendSecureMessage');\n if (!validation.isValid) {\n const errorMessage = `Input validation failed: ${validation.errors.join(', ')}`;\n this._secureLog('error', '\u274C Input validation failed in sendSecureMessage', {\n errors: validation.errors,\n messageType: typeof message\n });\n throw new Error(errorMessage);\n }\n\n // Rate limiting check\n if (!this._checkRateLimit('sendSecureMessage')) {\n throw new Error('Rate limit exceeded for secure message sending');\n }\n\n // Enforce verification gate\n this._enforceVerificationGate('sendSecureMessage');\n\n // Quick readiness check WITHOUT mutex\n if (!this.isConnected()) {\n if (validation.sanitizedData && typeof validation.sanitizedData === 'object' && validation.sanitizedData.type && validation.sanitizedData.type.startsWith('file_')) {\n throw new Error('Connection not ready for file transfer. Please ensure the connection is established and verified.');\n }\n this.messageQueue.push(validation.sanitizedData);\n throw new Error('Connection not ready. Message queued for sending.');\n }\n \n // Use mutex ONLY for cryptographic operations\n return this._withMutex('cryptoOperation', async (operationId) => {\n // Re-check inside critical section\n if (!this.isConnected() || !this.isVerified) {\n throw new Error('Connection lost during message preparation');\n }\n \n // Validate keys inside critical section\n if (!this.encryptionKey || !this.macKey || !this.metadataKey) {\n throw new Error('Encryption keys not initialized');\n }\n \n // Additional rate limiting check\n if (!window.EnhancedSecureCryptoUtils.rateLimiter.checkMessageRate(this.rateLimiterId)) {\n throw new Error('Message rate limit exceeded (60 messages per minute)');\n }\n \n try {\n // Accept strings and objects; stringify objects\n const textToSend = typeof validation.sanitizedData === 'string' ? validation.sanitizedData : JSON.stringify(validation.sanitizedData);\n const sanitizedMessage = window.EnhancedSecureCryptoUtils.sanitizeMessage(textToSend);\n const messageId = `msg_${Date.now()}_${this.messageCounter++}`;\n \n // Create AAD with sequence number for anti-replay protection\n if (typeof this._createMessageAAD !== 'function') {\n throw new Error('_createMessageAAD method is not available in sendSecureMessage. Manager may not be fully initialized.');\n }\n const aad = message.aad || this._createMessageAAD('enhanced_message', { content: sanitizedMessage });\n \n // Use enhanced encryption with AAD and sequence number\n const encryptedData = await window.EnhancedSecureCryptoUtils.encryptMessage(\n sanitizedMessage,\n this.encryptionKey,\n this.macKey,\n this.metadataKey,\n messageId,\n JSON.parse(aad).sequenceNumber // Use sequence number from AAD\n );\n \n const payload = {\n type: 'enhanced_message',\n data: encryptedData,\n keyVersion: this.currentKeyVersion,\n version: '4.0'\n };\n \n this.dataChannel.send(JSON.stringify(payload));\n // Locally display only plain strings to avoid UI duplication\n if (typeof validation.sanitizedData === 'string') {\n this.deliverMessageToUI(validation.sanitizedData, 'sent');\n }\n \n this._secureLog('debug', '\uD83D\uDCE4 Secure message sent successfully', {\n operationId: operationId,\n messageLength: sanitizedMessage.length,\n keyVersion: this.currentKeyVersion\n });\n \n } catch (error) {\n this._secureLog('error', '\u274C Secure message sending failed', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n throw error;\n }\n }, 2000); // Reduced timeout for crypto operations\n }\n\n processMessageQueue() {\n while (this.messageQueue.length > 0 && this.isConnected() && this.isVerified) {\n const message = this.messageQueue.shift();\n this.sendSecureMessage(message).catch(console.error);\n }\n }\n\n startHeartbeat() {\n // Heartbeat moved to unified scheduler with connection validation\n this._secureLog('info', '\uD83D\uDD27 Heartbeat moved to unified scheduler');\n \n // Store heartbeat configuration for scheduler\n this._heartbeatConfig = {\n enabled: true,\n interval: EnhancedSecureWebRTCManager.TIMEOUTS.HEARTBEAT_INTERVAL,\n lastHeartbeat: 0\n };\n }\n\n stopHeartbeat() {\n // Heartbeat stopped via unified scheduler\n if (this._heartbeatConfig) {\n this._heartbeatConfig.enabled = false;\n }\n }\n\n /**\n * Stop all active timers and cleanup scheduler\n */\n _stopAllTimers() {\n this._secureLog('info', '\uD83D\uDD27 Stopping all timers and cleanup scheduler');\n \n // Stop maintenance scheduler\n if (this._maintenanceScheduler) {\n clearInterval(this._maintenanceScheduler);\n this._maintenanceScheduler = null;\n }\n \n // Stop heartbeat\n if (this._heartbeatConfig) {\n this._heartbeatConfig.enabled = false;\n }\n \n // Clear all timer references\n if (this._activeTimers) {\n this._activeTimers.forEach(timer => {\n if (timer) clearInterval(timer);\n });\n this._activeTimers.clear();\n }\n \n this._secureLog('info', '\u2705 All timers stopped successfully');\n }\n\n handleHeartbeat() {\n console.log('Heartbeat received - connection alive');\n }\n\n waitForIceGathering() {\n return new Promise((resolve) => {\n if (this.peerConnection.iceGatheringState === 'complete') {\n resolve();\n return;\n }\n\n const checkState = () => {\n if (this.peerConnection && this.peerConnection.iceGatheringState === 'complete') {\n this.peerConnection.removeEventListener('icegatheringstatechange', checkState);\n resolve();\n }\n };\n \n this.peerConnection.addEventListener('icegatheringstatechange', checkState);\n \n setTimeout(() => {\n if (this.peerConnection) {\n this.peerConnection.removeEventListener('icegatheringstatechange', checkState);\n }\n resolve();\n }, EnhancedSecureWebRTCManager.TIMEOUTS.ICE_GATHERING_TIMEOUT);\n });\n }\n\n retryConnection() {\n console.log(`Retrying connection (attempt ${this.connectionAttempts}/${this.maxConnectionAttempts})`);\n this.onStatusChange('retrying');\n }\n\n isConnected() {\n const hasDataChannel = !!this.dataChannel;\n const dataChannelState = this.dataChannel?.readyState;\n const isDataChannelOpen = dataChannelState === 'open';\n const isVerified = this.isVerified;\n const connectionState = this.peerConnection?.connectionState;\n \n return this.dataChannel && this.dataChannel.readyState === 'open' && this.isVerified;\n }\n\n getConnectionInfo() {\n return {\n fingerprint: this.keyFingerprint,\n isConnected: this.isConnected(),\n isVerified: this.isVerified,\n connectionState: this.peerConnection?.connectionState,\n iceConnectionState: this.peerConnection?.iceConnectionState,\n verificationCode: this.verificationCode\n };\n }\n\n disconnect() {\n // Stop all timers first\n this._stopAllTimers();\n \n if (this.fileTransferSystem) {\n this.fileTransferSystem.cleanup();\n }\n this.intentionalDisconnect = true;\n \n window.EnhancedSecureCryptoUtils.secureLog.log('info', 'Starting intentional disconnect');\n\n this.sendDisconnectNotification();\n\n setTimeout(() => {\n this.sendDisconnectNotification(); \n }, 100);\n\n document.dispatchEvent(new CustomEvent('peer-disconnect', {\n detail: { \n reason: 'user_disconnect',\n timestamp: Date.now()\n }\n }));\n }\n \n handleUnexpectedDisconnect() {\n this.sendDisconnectNotification();\n this.isVerified = false;\n \n // Ensure disconnect notification wasn't already sent\n if (!this.disconnectNotificationSent) {\n this.disconnectNotificationSent = true;\n this.deliverMessageToUI('\uD83D\uDD0C Connection lost. Attempting to reconnect...', 'system');\n }\n \n // Cleanup file transfer system on unexpected disconnect\n if (this.fileTransferSystem) {\n console.log('\uD83E\uDDF9 Cleaning up file transfer system on unexpected disconnect...');\n this.fileTransferSystem.cleanup();\n this.fileTransferSystem = null;\n }\n \n document.dispatchEvent(new CustomEvent('peer-disconnect', {\n detail: { \n reason: 'connection_lost',\n timestamp: Date.now()\n }\n }));\n\n }\n \n sendDisconnectNotification() {\n try {\n if (this.dataChannel && this.dataChannel.readyState === 'open') {\n const notification = {\n type: 'peer_disconnect',\n timestamp: Date.now(),\n reason: this.intentionalDisconnect ? 'user_disconnect' : 'connection_lost'\n };\n\n for (let i = 0; i < 3; i++) {\n try {\n this.dataChannel.send(JSON.stringify(notification));\n window.EnhancedSecureCryptoUtils.secureLog.log('info', 'Disconnect notification sent', {\n reason: notification.reason,\n attempt: i + 1\n });\n break;\n } catch (sendError) {\n if (i === 2) { \n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'Failed to send disconnect notification', {\n error: sendError.message\n });\n }\n }\n }\n }\n } catch (error) {\n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'Could not send disconnect notification', {\n error: error.message\n });\n }\n }\n \n attemptReconnection() {\n // Ensure reconnection-failed notification wasn't already sent\n if (!this.reconnectionFailedNotificationSent) {\n this.reconnectionFailedNotificationSent = true;\n this.deliverMessageToUI('\u274C Unable to reconnect. A new connection is required.', 'system');\n }\n\n }\n \n handlePeerDisconnectNotification(data) {\n const reason = data.reason || 'unknown';\n const reasonText = reason === 'user_disconnect' ? 'manually disconnected.' : 'connection lost.';\n \n // Ensure peer-disconnect notification wasn't already sent\n if (!this.peerDisconnectNotificationSent) {\n this.peerDisconnectNotificationSent = true;\n this.deliverMessageToUI(`\uD83D\uDC4B Peer ${reasonText}`, 'system');\n }\n \n this.onStatusChange('peer_disconnected');\n \n this.intentionalDisconnect = false;\n this.isVerified = false;\n this.stopHeartbeat();\n \n this.onKeyExchange(''); \n this.onVerificationRequired(''); \n\n document.dispatchEvent(new CustomEvent('peer-disconnect', {\n detail: { \n reason: reason,\n timestamp: Date.now()\n }\n }));\n\n setTimeout(() => {\n this.disconnect();\n }, 2000);\n \n window.EnhancedSecureCryptoUtils.secureLog.log('info', 'Peer disconnect notification processed', {\n reason: reason\n });\n }\n \n /**\n * Secure disconnect with complete memory cleanup\n */\n disconnect() {\n this.stopHeartbeat();\n this.isVerified = false;\n this.processedMessageIds.clear();\n this.messageCounter = 0;\n \n // Secure cleanup of cryptographic materials\n this._secureCleanupCryptographicMaterials();\n \n // Secure wipe of PFS key versions\n this.keyVersions.clear();\n this.oldKeys.clear();\n this.currentKeyVersion = 0;\n this.lastKeyRotation = Date.now();\n \n // Reset message counters\n this.sequenceNumber = 0;\n this.expectedSequenceNumber = 0;\n this.replayWindow.clear(); // Clear replay window\n \n // Reset security features\n this.securityFeatures = {\n hasEncryption: true,\n hasECDH: true,\n hasECDSA: true, \n hasMutualAuth: true, \n hasMetadataProtection: true, \n hasEnhancedReplayProtection: true, \n hasNonExtractableKeys: true, \n hasRateLimiting: true, \n hasEnhancedValidation: true, \n hasPFS: true \n };\n \n // Close connections\n if (this.dataChannel) {\n this.dataChannel.close();\n this.dataChannel = null;\n }\n if (this.peerConnection) {\n this.peerConnection.close();\n this.peerConnection = null;\n }\n \n // Secure wipe of message queue\n if (this.messageQueue && this.messageQueue.length > 0) {\n this.messageQueue.forEach((message, index) => {\n this._secureWipeMemory(message, `messageQueue[${index}]`);\n });\n this.messageQueue = [];\n }\n \n // Force garbage collection\n this._forceGarbageCollection();\n \n document.dispatchEvent(new CustomEvent('connection-cleaned', {\n detail: { \n timestamp: Date.now(),\n reason: this.intentionalDisconnect ? 'user_cleanup' : 'automatic_cleanup'\n }\n }));\n\n // Notify UI about complete cleanup\n this.onStatusChange('disconnected');\n this.onKeyExchange('');\n this.onVerificationRequired('');\n \n this._secureLog('info', '\uD83D\uDD12 Connection securely cleaned up with complete memory wipe');\n \n // Reset the intentional disconnect flag\n this.intentionalDisconnect = false;\n }\n // Public method to send files\n async sendFile(file) {\n // Enforce verification gate for file transfers\n this._enforceVerificationGate('sendFile');\n \n if (!this.isConnected()) {\n throw new Error('Connection not ready for file transfer. Please ensure the connection is established.');\n }\n\n if (!this.fileTransferSystem) {\n console.log('\uD83D\uDD04 File transfer system not initialized, attempting to initialize...');\n this.initializeFileTransfer();\n \n // Allow time for initialization\n await new Promise(resolve => setTimeout(resolve, 500));\n \n if (!this.fileTransferSystem) {\n throw new Error('File transfer system could not be initialized. Please try reconnecting.');\n }\n }\n\n // Verify key readiness\n if (!this.encryptionKey || !this.macKey) {\n throw new Error('Encryption keys not ready. Please wait for connection to be fully established.');\n }\n\n // Debug logging for file transfer system\n console.log('\uD83D\uDD0D Debug: File transfer system in sendFile:', {\n hasFileTransferSystem: !!this.fileTransferSystem,\n fileTransferSystemType: this.fileTransferSystem.constructor?.name,\n hasWebrtcManager: !!this.fileTransferSystem.webrtcManager,\n webrtcManagerType: this.fileTransferSystem.webrtcManager?.constructor?.name\n });\n\n try {\n console.log('\uD83D\uDE80 Starting file transfer for:', file.name, `(${(file.size / 1024 / 1024).toFixed(2)} MB)`);\n const fileId = await this.fileTransferSystem.sendFile(file);\n console.log('\u2705 File transfer initiated successfully with ID:', fileId);\n return fileId;\n } catch (error) {\n this._secureLog('error', '\u274C File transfer error:', { errorType: error?.constructor?.name || 'Unknown' });\n \n // Re-throw with a clearer message\n if (error.message.includes('Connection not ready')) {\n throw new Error('Connection not ready for file transfer. Check connection status.');\n } else if (error.message.includes('Encryption keys not initialized')) {\n throw new Error('Encryption keys not initialized. Try reconnecting.');\n } else if (error.message.includes('Transfer timeout')) {\n throw new Error('File transfer timeout. Check connection and try again.');\n } else {\n throw error;\n }\n }\n }\n\n // Get active file transfers\n getFileTransfers() {\n if (!this.fileTransferSystem) {\n return { sending: [], receiving: [] };\n }\n \n try {\n // Check available methods in file transfer system\n let sending = [];\n let receiving = [];\n \n if (typeof this.fileTransferSystem.getActiveTransfers === 'function') {\n sending = this.fileTransferSystem.getActiveTransfers();\n } else {\n this._secureLog('warn', '\u26A0\uFE0F getActiveTransfers method not available in file transfer system');\n }\n \n if (typeof this.fileTransferSystem.getReceivingTransfers === 'function') {\n receiving = this.fileTransferSystem.getReceivingTransfers();\n } else {\n this._secureLog('warn', '\u26A0\uFE0F getReceivingTransfers method not available in file transfer system');\n }\n \n return {\n sending: sending || [],\n receiving: receiving || []\n };\n } catch (error) {\n this._secureLog('error', '\u274C Error getting file transfers:', { errorType: error?.constructor?.name || 'Unknown' });\n return { sending: [], receiving: [] };\n }\n }\n\n // Get file transfer system status\n getFileTransferStatus() {\n if (!this.fileTransferSystem) {\n return {\n initialized: false,\n status: 'not_initialized',\n message: 'File transfer system not initialized'\n };\n }\n \n const activeTransfers = this.fileTransferSystem.getActiveTransfers();\n const receivingTransfers = this.fileTransferSystem.getReceivingTransfers();\n \n return {\n initialized: true,\n status: 'ready',\n activeTransfers: activeTransfers.length,\n receivingTransfers: receivingTransfers.length,\n totalTransfers: activeTransfers.length + receivingTransfers.length\n };\n }\n\n // Cancel file transfer\n cancelFileTransfer(fileId) {\n if (!this.fileTransferSystem) return false;\n return this.fileTransferSystem.cancelTransfer(fileId);\n }\n\n // Force cleanup of file transfer system\n cleanupFileTransferSystem() {\n if (this.fileTransferSystem) {\n console.log('\uD83E\uDDF9 Force cleaning up file transfer system...');\n this.fileTransferSystem.cleanup();\n this.fileTransferSystem = null;\n return true;\n }\n return false;\n }\n\n // Reinitialize file transfer system\n reinitializeFileTransfer() {\n try {\n console.log('\uD83D\uDD04 Reinitializing file transfer system...');\n if (this.fileTransferSystem) {\n this.fileTransferSystem.cleanup();\n }\n this.initializeFileTransfer();\n return true;\n } catch (error) {\n this._secureLog('error', '\u274C Failed to reinitialize file transfer system:', { errorType: error?.constructor?.name || 'Unknown' });\n return false;\n }\n }\n\n // Set file transfer callbacks\n setFileTransferCallbacks(onProgress, onReceived, onError) {\n this.onFileProgress = onProgress;\n this.onFileReceived = onReceived;\n this.onFileError = onError;\n \n console.log('\uD83D\uDD27 File transfer callbacks set:', {\n hasProgress: !!onProgress,\n hasReceived: !!onReceived,\n hasError: !!onError\n });\n \n // Reinitialize file transfer system if it exists to update callbacks\n if (this.fileTransferSystem) {\n console.log('\uD83D\uDD04 Reinitializing file transfer system with new callbacks...');\n this.initializeFileTransfer();\n }\n }\n\n // ============================================\n // SESSION ACTIVATION HANDLING\n // ============================================\n\n async handleSessionActivation(sessionData) {\n try {\n console.log('\uD83D\uDD10 Handling session activation:', sessionData);\n \n // Update session state\n this.currentSession = sessionData;\n this.sessionManager = sessionData.sessionManager;\n \n // FIX: More lenient checks for activation\n const hasKeys = !!(this.encryptionKey && this.macKey);\n const hasSession = !!(this.sessionManager && (this.sessionManager.hasActiveSession?.() || sessionData.sessionId));\n \n console.log('\uD83D\uDD0D Session activation status:', {\n hasKeys: hasKeys,\n hasSession: hasSession,\n sessionType: sessionData.sessionType,\n isDemo: sessionData.isDemo\n });\n \n // Force connection status if there is an active session\n if (hasSession) {\n console.log('\uD83D\uDD13 Session activated - forcing connection status to connected');\n this.onStatusChange('connected');\n \n console.log('\u26A0\uFE0F Session activated but NOT verified - cryptographic verification still required');\n }\n\n setTimeout(() => {\n try {\n this.initializeFileTransfer();\n } catch (error) {\n this._secureLog('warn', '\u26A0\uFE0F File transfer initialization failed during session activation:', { details: error.message });\n }\n }, 1000);\n \n console.log('\u2705 Session activation handled successfully');\n \n if (this.fileTransferSystem && this.isConnected()) {\n console.log('\uD83D\uDD04 Synchronizing file transfer keys after session activation...');\n \n if (typeof this.fileTransferSystem.onSessionUpdate === 'function') {\n this.fileTransferSystem.onSessionUpdate({\n keyFingerprint: this.keyFingerprint,\n sessionSalt: this.sessionSalt,\n hasMacKey: !!this.macKey\n });\n }\n }\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to handle session activation:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }\n // Method to check readiness of file transfers\ncheckFileTransferReadiness() {\n const status = {\n hasFileTransferSystem: !!this.fileTransferSystem,\n hasDataChannel: !!this.dataChannel,\n dataChannelState: this.dataChannel?.readyState,\n isConnected: this.isConnected(),\n isVerified: this.isVerified,\n hasEncryptionKey: !!this.encryptionKey,\n hasMacKey: !!this.macKey,\n ready: false\n };\n \n status.ready = status.hasFileTransferSystem && \n status.hasDataChannel && \n status.dataChannelState === 'open' && \n status.isConnected && \n status.isVerified;\n \n console.log('\uD83D\uDD0D File transfer readiness check:', status);\n return status;\n }\n\n // Method to force re-initialize file transfer system\n forceReinitializeFileTransfer() {\n try {\n console.log('\uD83D\uDD04 Force reinitializing file transfer system...');\n \n if (this.fileTransferSystem) {\n this.fileTransferSystem.cleanup();\n this.fileTransferSystem = null;\n }\n \n // Small delay before reinitialization\n setTimeout(() => {\n this.initializeFileTransfer();\n }, 500);\n \n return true;\n } catch (error) {\n this._secureLog('error', '\u274C Failed to force reinitialize file transfer:', { errorType: error?.constructor?.name || 'Unknown' });\n return false;\n }\n }\n\n // Method to get diagnostic information\n getFileTransferDiagnostics() {\n const diagnostics = {\n timestamp: new Date().toISOString(),\n webrtcManager: {\n hasDataChannel: !!this.dataChannel,\n dataChannelState: this.dataChannel?.readyState,\n isConnected: this.isConnected(),\n isVerified: this.isVerified,\n isInitiator: this.isInitiator,\n hasEncryptionKey: !!this.encryptionKey,\n hasMacKey: !!this.macKey,\n hasMetadataKey: !!this.metadataKey,\n hasKeyFingerprint: !!this.keyFingerprint,\n hasSessionSalt: !!this.sessionSalt\n },\n fileTransferSystem: null,\n globalState: {\n fileTransferActive: this._fileTransferActive || false,\n hasFileTransferSystem: !!this.fileTransferSystem,\n fileTransferSystemType: this.fileTransferSystem ? 'EnhancedSecureFileTransfer' : 'none'\n }\n };\n \n if (this.fileTransferSystem) {\n try {\n diagnostics.fileTransferSystem = this.fileTransferSystem.getSystemStatus();\n } catch (error) {\n diagnostics.fileTransferSystem = { error: error.message };\n }\n }\n \n return diagnostics;\n }\n\n getSupportedFileTypes() {\n if (!this.fileTransferSystem) {\n return { error: 'File transfer system not initialized' };\n }\n \n try {\n return this.fileTransferSystem.getSupportedFileTypes();\n } catch (error) {\n return { error: error.message };\n }\n }\n\n validateFile(file) {\n if (!this.fileTransferSystem) {\n return { \n isValid: false, \n errors: ['File transfer system not initialized'],\n fileType: null,\n fileSize: file?.size || 0,\n formattedSize: '0 B'\n };\n }\n \n try {\n return this.fileTransferSystem.validateFile(file);\n } catch (error) {\n return { \n isValid: false, \n errors: [error.message],\n fileType: null,\n fileSize: file?.size || 0,\n formattedSize: '0 B'\n };\n }\n }\n\n getFileTypeInfo() {\n if (!this.fileTransferSystem) {\n return { error: 'File transfer system not initialized' };\n }\n \n try {\n return this.fileTransferSystem.getFileTypeInfo();\n } catch (error) {\n return { error: error.message };\n }\n }\n\n async forceInitializeFileTransfer(options = {}) {\n const abortController = new AbortController();\n const { signal = abortController.signal, timeout = 6000 } = options;\n\n if (signal && signal !== abortController.signal) {\n signal.addEventListener('abort', () => abortController.abort());\n }\n try {\n if (!this.isVerified) {\n throw new Error('Connection not verified');\n }\n \n if (!this.dataChannel || this.dataChannel.readyState !== 'open') {\n throw new Error('Data channel not open');\n }\n \n if (!this.encryptionKey || !this.macKey) {\n throw new Error('Encryption keys not ready');\n }\n\n if (this.fileTransferSystem) {\n this.fileTransferSystem.cleanup();\n this.fileTransferSystem = null;\n }\n\n this.initializeFileTransfer();\n\n let attempts = 0;\n const maxAttempts = 50;\n const checkInterval = 100; \n const maxWaitTime = maxAttempts * checkInterval; \n\n const initializationPromise = new Promise((resolve, reject) => {\n const checkInitialization = () => {\n if (abortController.signal.aborted) {\n reject(new Error('Operation cancelled'));\n return;\n }\n \n if (this.fileTransferSystem) {\n resolve(true);\n return;\n }\n \n if (attempts >= maxAttempts) {\n reject(new Error(`Initialization timeout after ${maxWaitTime}ms`));\n return;\n }\n \n attempts++;\n setTimeout(checkInitialization, checkInterval);\n };\n \n checkInitialization();\n });\n\n await Promise.race([\n initializationPromise,\n new Promise((_, reject) => \n setTimeout(() => reject(new Error(`Global timeout after ${timeout}ms`)), timeout)\n )\n ]);\n \n if (this.fileTransferSystem) {\n return true;\n } else {\n throw new Error('Force initialization timeout');\n }\n \n } catch (error) {\n if (error.name === 'AbortError' || error.message.includes('cancelled')) {\n this._secureLog('info', '\u23F9\uFE0F File transfer initialization cancelled by user');\n return { cancelled: true };\n }\n \n this._secureLog('error', '\u274C Force file transfer initialization failed:', { \n errorType: error?.constructor?.name || 'Unknown',\n message: error.message,\n attempts: attempts\n });\n return { error: error.message, attempts: attempts };\n }\n }\n\n cancelFileTransferInitialization() {\n try {\n if (this.fileTransferSystem) {\n this.fileTransferSystem.cleanup();\n this.fileTransferSystem = null;\n this._fileTransferActive = false;\n this._secureLog('info', '\u23F9\uFE0F File transfer initialization cancelled');\n return true;\n }\n return false;\n } catch (error) {\n this._secureLog('error', '\u274C Failed to cancel file transfer initialization:', { \n errorType: error?.constructor?.name || 'Unknown' \n });\n return false;\n }\n }\n \n getFileTransferSystemStatus() {\n if (!this.fileTransferSystem) {\n return { available: false, status: 'not_initialized' };\n }\n \n try {\n const status = this.fileTransferSystem.getSystemStatus();\n return {\n available: true,\n status: status.status || 'unknown',\n activeTransfers: status.activeTransfers || 0,\n receivingTransfers: status.receivingTransfers || 0,\n systemType: 'EnhancedSecureFileTransfer'\n };\n } catch (error) {\n this._secureLog('error', '\u274C Failed to get file transfer system status:', { \n errorType: error?.constructor?.name || 'Unknown' \n });\n return { available: false, status: 'error', error: error.message };\n }\n }\n\n _validateNestedEncryptionSecurity() {\n if (this.securityFeatures.hasNestedEncryption && this.nestedEncryptionKey) {\n // Test secure IV generation with reuse prevention\n try {\n const testIV1 = this._generateSecureIV(EnhancedSecureWebRTCManager.SIZES.NESTED_ENCRYPTION_IV_SIZE, 'securityTest1');\n const testIV2 = this._generateSecureIV(EnhancedSecureWebRTCManager.SIZES.NESTED_ENCRYPTION_IV_SIZE, 'securityTest2');\n \n // Verify IVs are different and properly tracked\n if (testIV1.every((byte, index) => byte === testIV2[index])) {\n this._secureLog('error', '\u274C CRITICAL: Nested encryption security validation failed - IVs are identical!');\n return false;\n }\n \n // Verify IV tracking system is working\n const stats = this._getIVTrackingStats();\n if (stats.totalIVs < 2) {\n this._secureLog('error', '\u274C CRITICAL: IV tracking system not working properly');\n return false;\n }\n \n this._secureLog('info', '\u2705 Nested encryption security validation passed - secure IV generation working');\n return true;\n } catch (error) {\n this._secureLog('error', '\u274C CRITICAL: Nested encryption security validation failed:', {\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n return false;\n }\n }\n return true;\n }\n}\n\nclass SecureKeyStorage {\n constructor() {\n // Use WeakMap for automatic garbage collection of unused keys\n this._keyStore = new WeakMap();\n this._keyMetadata = new Map(); // Metadata doesn't need WeakMap\n this._keyReferences = new Map(); // Strong references for active keys\n \n // Master encryption key for storage encryption\n this._storageMasterKey = null;\n this._initializeStorageMaster();\n\n setTimeout(() => {\n if (!this.validateStorageIntegrity()) {\n console.error('\u274C CRITICAL: Key storage integrity check failed');\n }\n }, 100);\n \n }\n\n async _initializeStorageMaster() {\n // Generate a master key for encrypting stored keys\n this._storageMasterKey = await crypto.subtle.generateKey(\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt', 'decrypt']\n );\n }\n\n async storeKey(keyId, cryptoKey, metadata = {}) {\n if (!(cryptoKey instanceof CryptoKey)) {\n throw new Error('Only CryptoKey objects can be stored');\n }\n\n try {\n // For non-extractable keys, we can only store a reference\n if (!cryptoKey.extractable) {\n // Store the key reference directly without encryption\n this._keyReferences.set(keyId, cryptoKey);\n this._keyMetadata.set(keyId, {\n ...metadata,\n created: Date.now(),\n lastAccessed: Date.now(),\n extractable: false,\n encrypted: false // Mark as not encrypted\n });\n return true;\n }\n\n // For extractable keys, proceed with encryption\n const keyData = await crypto.subtle.exportKey('jwk', cryptoKey);\n const encryptedKeyData = await this._encryptKeyData(keyData);\n \n // Validate that extractable keys are properly encrypted\n if (!encryptedKeyData || encryptedKeyData.byteLength === 0) {\n throw new Error('Failed to encrypt extractable key data');\n }\n\n // Create a storage object\n const storageObject = {\n id: keyId,\n encryptedData: encryptedKeyData,\n algorithm: cryptoKey.algorithm,\n usages: cryptoKey.usages,\n extractable: cryptoKey.extractable,\n type: cryptoKey.type,\n timestamp: Date.now()\n };\n\n // Use WeakMap with the CryptoKey as the key\n this._keyStore.set(cryptoKey, storageObject);\n \n // Store reference for retrieval by ID\n this._keyReferences.set(keyId, cryptoKey);\n \n // Store metadata separately\n this._keyMetadata.set(keyId, {\n ...metadata,\n created: Date.now(),\n lastAccessed: Date.now(),\n extractable: true,\n encrypted: true // Mark extractable keys as encrypted\n });\n\n return true;\n } catch (error) {\n console.error('Failed to store key securely:', error);\n return false;\n }\n }\n\n async retrieveKey(keyId) {\n const metadata = this._keyMetadata.get(keyId);\n if (!metadata) {\n return null;\n }\n\n // Update access time\n metadata.lastAccessed = Date.now();\n\n // For non-encrypted keys (non-extractable), return directly\n if (!metadata.encrypted) {\n // Only non-extractable keys should be non-encrypted\n if (metadata.extractable === false) {\n return this._keyReferences.get(keyId);\n } else {\n // This should never happen - extractable keys must be encrypted\n this._secureLog('error', '\u274C SECURITY VIOLATION: Extractable key marked as non-encrypted', {\n keyId,\n extractable: metadata.extractable,\n encrypted: metadata.encrypted\n });\n return null;\n }\n }\n\n // For encrypted keys, decrypt and recreate\n try {\n const cryptoKey = this._keyReferences.get(keyId);\n const storedData = this._keyStore.get(cryptoKey);\n \n if (!storedData) {\n return null;\n }\n\n // Decrypt the key data\n const decryptedKeyData = await this._decryptKeyData(storedData.encryptedData);\n \n // Recreate the CryptoKey\n const recreatedKey = await crypto.subtle.importKey(\n 'jwk',\n decryptedKeyData,\n storedData.algorithm,\n storedData.extractable,\n storedData.usages\n );\n \n return recreatedKey;\n } catch (error) {\n console.error('Failed to retrieve key:', error);\n return null;\n }\n }\n\n async _encryptKeyData(keyData) {\n const dataToEncrypt = typeof keyData === 'object' \n ? JSON.stringify(keyData) \n : keyData;\n \n const encoder = new TextEncoder();\n const data = encoder.encode(dataToEncrypt);\n \n const iv = crypto.getRandomValues(new Uint8Array(12));\n \n const encryptedData = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n this._storageMasterKey,\n data\n );\n\n // Return IV + encrypted data\n const result = new Uint8Array(iv.length + encryptedData.byteLength);\n result.set(iv, 0);\n result.set(new Uint8Array(encryptedData), iv.length);\n \n return result;\n }\n\n async _decryptKeyData(encryptedData) {\n const iv = encryptedData.slice(0, 12);\n const data = encryptedData.slice(12);\n \n const decryptedData = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv },\n this._storageMasterKey,\n data\n );\n\n const decoder = new TextDecoder();\n const jsonString = decoder.decode(decryptedData);\n \n try {\n return JSON.parse(jsonString);\n } catch {\n return decryptedData;\n }\n }\n\n secureWipe(keyId) {\n const cryptoKey = this._keyReferences.get(keyId);\n \n if (cryptoKey) {\n // Remove from WeakMap (will be GC'd)\n this._keyStore.delete(cryptoKey);\n // Remove strong reference\n this._keyReferences.delete(keyId);\n // Remove metadata\n this._keyMetadata.delete(keyId);\n }\n\n // Overwrite memory locations if possible\n if (typeof window.gc === 'function') {\n window.gc();\n }\n }\n\n secureWipeAll() {\n // Clear all references\n this._keyReferences.clear();\n this._keyMetadata.clear();\n \n // WeakMap entries will be garbage collected\n this._keyStore = new WeakMap();\n \n // Force garbage collection if available\n if (typeof window.gc === 'function') {\n window.gc();\n }\n }\n\n // Validate storage integrity\n validateStorageIntegrity() {\n const violations = [];\n \n for (const [keyId, metadata] of this._keyMetadata.entries()) {\n // Check: extractable keys must be encrypted\n if (metadata.extractable === true && metadata.encrypted !== true) {\n violations.push({\n keyId,\n type: 'EXTRACTABLE_KEY_NOT_ENCRYPTED',\n metadata\n });\n }\n \n // Check: non-extractable keys should not be encrypted\n if (metadata.extractable === false && metadata.encrypted === true) {\n violations.push({\n keyId,\n type: 'NON_EXTRACTABLE_KEY_ENCRYPTED',\n metadata\n });\n }\n }\n \n if (violations.length > 0) {\n console.error('\u274C Storage integrity violations detected:', violations);\n return false;\n }\n \n return true;\n }\n\n getStorageStats() {\n return {\n totalKeys: this._keyReferences.size,\n metadata: Array.from(this._keyMetadata.entries()).map(([id, meta]) => ({\n id,\n created: meta.created,\n lastAccessed: meta.lastAccessed,\n age: Date.now() - meta.created\n }))\n };\n }\n\n // Method _generateNextSequenceNumber moved to constructor area for early availability\n\n /**\n * Validate incoming message sequence number\n * This prevents replay attacks and ensures message ordering\n */\n _validateIncomingSequenceNumber(receivedSeq, context = 'unknown') {\n try {\n if (!this.replayProtectionEnabled) {\n return true; // Skip validation if disabled\n }\n\n // Check if sequence number is within acceptable range\n if (receivedSeq < this.expectedSequenceNumber - this.replayWindowSize) {\n this._secureLog('warn', '\u26A0\uFE0F Sequence number too old - possible replay attack', {\n received: receivedSeq,\n expected: this.expectedSequenceNumber,\n context: context,\n timestamp: Date.now()\n });\n return false;\n }\n\n // Check if sequence number is too far ahead (DoS protection)\n if (receivedSeq > this.expectedSequenceNumber + this.maxSequenceGap) {\n this._secureLog('warn', '\u26A0\uFE0F Sequence number gap too large - possible DoS attack', {\n received: receivedSeq,\n expected: this.expectedSequenceNumber,\n gap: receivedSeq - this.expectedSequenceNumber,\n context: context,\n timestamp: Date.now()\n });\n return false;\n }\n\n // Check if sequence number is already in replay window\n if (this.replayWindow.has(receivedSeq)) {\n this._secureLog('warn', '\u26A0\uFE0F Duplicate sequence number detected - replay attack', {\n received: receivedSeq,\n context: context,\n timestamp: Date.now()\n });\n return false;\n }\n\n // Add to replay window\n this.replayWindow.add(receivedSeq);\n \n // Maintain sliding window size\n if (this.replayWindow.size > this.replayWindowSize) {\n const oldestSeq = Math.min(...this.replayWindow);\n this.replayWindow.delete(oldestSeq);\n }\n\n // Update expected sequence number if this is the next expected\n if (receivedSeq === this.expectedSequenceNumber) {\n this.expectedSequenceNumber++;\n \n // Clean up replay window entries that are no longer needed\n while (this.replayWindow.has(this.expectedSequenceNumber - this.replayWindowSize - 1)) {\n this.replayWindow.delete(this.expectedSequenceNumber - this.replayWindowSize - 1);\n }\n }\n\n this._secureLog('debug', '\u2705 Sequence number validation successful', {\n received: receivedSeq,\n expected: this.expectedSequenceNumber,\n context: context,\n timestamp: Date.now()\n });\n\n return true;\n } catch (error) {\n this._secureLog('error', '\u274C Sequence number validation failed', {\n error: error.message,\n context: context,\n timestamp: Date.now()\n });\n return false;\n }\n }\n\n // Method _createMessageAAD moved to constructor area for early availability\n\n /**\n * Validate message AAD with sequence number\n * This ensures message integrity and prevents replay attacks\n */\n _validateMessageAAD(aadString, expectedMessageType = null) {\n try {\n const aad = JSON.parse(aadString);\n \n // Validate session binding\n if (aad.sessionId !== (this.currentSession?.sessionId || 'unknown')) {\n throw new Error('AAD sessionId mismatch - possible replay attack');\n }\n \n if (aad.keyFingerprint !== (this.keyFingerprint || 'unknown')) {\n throw new Error('AAD keyFingerprint mismatch - possible key substitution attack');\n }\n \n // Validate sequence number\n if (!this._validateIncomingSequenceNumber(aad.sequenceNumber, aad.messageType)) {\n throw new Error('Sequence number validation failed - possible replay or DoS attack');\n }\n \n // Validate message type if specified\n if (expectedMessageType && aad.messageType !== expectedMessageType) {\n throw new Error(`AAD messageType mismatch - expected ${expectedMessageType}, got ${aad.messageType}`);\n }\n \n return aad;\n } catch (error) {\n this._secureLog('error', 'AAD validation failed', { error: error.message, aadString });\n throw new Error(`AAD validation failed: ${error.message}`);\n }\n }\n\n /**\n * Get anti-replay protection status\n * This shows the current state of replay protection\n */\n getAntiReplayStatus() {\n const status = {\n replayProtectionEnabled: this.replayProtectionEnabled,\n replayWindowSize: this.replayWindowSize,\n currentReplayWindowSize: this.replayWindow.size,\n sequenceNumber: this.sequenceNumber,\n expectedSequenceNumber: this.expectedSequenceNumber,\n maxSequenceGap: this.maxSequenceGap,\n replayWindowEntries: Array.from(this.replayWindow).sort((a, b) => a - b)\n };\n\n this._secureLog('info', 'Anti-replay status retrieved', status);\n return status;\n }\n\n /**\n * Configure anti-replay protection\n * This allows fine-tuning of replay protection parameters\n */\n configureAntiReplayProtection(config) {\n try {\n if (config.windowSize !== undefined) {\n if (config.windowSize < 16 || config.windowSize > 1024) {\n throw new Error('Replay window size must be between 16 and 1024');\n }\n this.replayWindowSize = config.windowSize;\n }\n\n if (config.maxGap !== undefined) {\n if (config.maxGap < 10 || config.maxGap > 1000) {\n throw new Error('Max sequence gap must be between 10 and 1000');\n }\n this.maxSequenceGap = config.maxGap;\n }\n\n if (config.enabled !== undefined) {\n this.replayProtectionEnabled = config.enabled;\n }\n\n this._secureLog('info', 'Anti-replay protection configured', config);\n return true;\n } catch (error) {\n this._secureLog('error', 'Failed to configure anti-replay protection', { error: error.message });\n return false;\n }\n }\n\n\n}\n\nexport { EnhancedSecureWebRTCManager };", "class PayPerSessionManager {\n constructor(config = {}) {\n this.sessionPrices = {\n demo: { sats: 0, hours: 0.1, usd: 0.00, securityLevel: 'basic' }, \n basic: { sats: 5000, hours: 1, usd: 2.00, securityLevel: 'enhanced' },\n premium: { sats: 20000, hours: 6, usd: 8.00, securityLevel: 'maximum' }\n };\n \n this.currentSession = null;\n this.sessionTimer = null;\n this.onSessionExpired = null;\n this.staticLightningAddress = \"dullpastry62@walletofsatoshi.com\";\n \n // Storage of used preimage to prevent reuse\n this.usedPreimages = new Set();\n this.preimageCleanupInterval = null;\n \n // FIXED DEMO mode: Stricter control\n this.demoSessions = new Map(); \n this.maxDemoSessionsPerUser = 3; \n this.demoCooldownPeriod = 24 * 60 * 60 * 1000; \n this.demoSessionCooldown = 1 * 60 * 1000; \n this.demoSessionMaxDuration = 6 * 60 * 1000; \n \n // NEW: Global tracking of active demo sessions\n this.activeDemoSessions = new Set(); \n this.maxGlobalDemoSessions = 10; \n \n // NEW: Tracking of terminated sessions to prevent rapid reconnection\n this.completedDemoSessions = new Map(); \n this.minTimeBetweenCompletedSessions = 15 * 60 * 1000; \n\n // Minimum cost for paid sessions (protection against micropayment attacks)\n this.minimumPaymentSats = 1000;\n \n this.verificationConfig = {\n method: config.method || 'lnbits',\n apiUrl: config.apiUrl || 'https://demo.lnbits.com',\n apiKey: config.apiKey || 'a7226682253f4dd7bdb2d9487a9a59f8', \n walletId: config.walletId || '649903697b03457d8b12c4eae7b2fab9',\n isDemo: config.isDemo !== undefined ? config.isDemo : true,\n demoTimeout: 30000, \n retryAttempts: 3,\n invoiceExpiryMinutes: 15\n };\n \n // Rate limiting for API requests\n this.lastApiCall = 0;\n this.apiCallMinInterval = 1000; \n \n // Run periodic tasks\n this.startPreimageCleanup();\n this.startDemoSessionCleanup();\n this.startActiveDemoSessionCleanup();\n \n this.globalDemoCounter = 0;\n this.memoryStorage = new Map();\n this.currentTabId = null;\n this.tabHeartbeatInterval = null;\n this.initializePersistentStorage();\n this.performEnhancedCleanup();\n const multiTabCheck = this.checkMultiTabProtection();\n if (!multiTabCheck.allowed) {\n console.warn('\u274C Multi-tab protection triggered:', multiTabCheck.message);\n }\n \n console.log('\uD83D\uDCB0 PayPerSessionManager initialized with TIERED security levels');\n \n setInterval(() => {\n this.savePersistentData();\n }, 30000);\n this.notifySecurityUpdate = () => {\n document.dispatchEvent(new CustomEvent('security-level-updated', {\n detail: { timestamp: Date.now(), manager: 'webrtc' }\n }));\n };\n console.log('\uD83D\uDCB0 PayPerSessionManager initialized with ENHANCED secure demo mode and auto-save');\n }\n\n getSecurityLevelForSession(sessionType) {\n const pricing = this.sessionPrices[sessionType];\n if (!pricing) return 'basic';\n \n return pricing.securityLevel || 'basic';\n }\n\n // Check if the function is allowed for the given session type\n isFeatureAllowedForSession(sessionType, feature) {\n const securityLevel = this.getSecurityLevelForSession(sessionType);\n \n const featureMatrix = {\n 'basic': {\n // DEMO \u0441\u0435\u0441\u0441\u0438\u0438 - \u0442\u043E\u043B\u044C\u043A\u043E \u0431\u0430\u0437\u043E\u0432\u044B\u0435 \u0444\u0443\u043D\u043A\u0446\u0438\u0438\n hasEncryption: true,\n hasECDH: true,\n hasECDSA: false,\n hasMutualAuth: false,\n hasMetadataProtection: false,\n hasEnhancedReplayProtection: false,\n hasNonExtractableKeys: false,\n hasRateLimiting: true,\n hasEnhancedValidation: false,\n hasPFS: false,\n \n // Advanced features are DISABLED for demo\n hasNestedEncryption: false,\n hasPacketPadding: false,\n hasPacketReordering: false,\n hasAntiFingerprinting: false,\n hasFakeTraffic: false,\n hasDecoyChannels: false,\n hasMessageChunking: false\n },\n 'enhanced': {\n // BASIC paid sessions - improved security\n hasEncryption: true,\n hasECDH: true,\n hasECDSA: true,\n hasMutualAuth: true,\n hasMetadataProtection: true,\n hasEnhancedReplayProtection: true,\n hasNonExtractableKeys: true,\n hasRateLimiting: true,\n hasEnhancedValidation: true,\n hasPFS: true,\n \n // Partially enabled advanced features\n hasNestedEncryption: true,\n hasPacketPadding: true,\n hasPacketReordering: false, \n hasAntiFingerprinting: false,\n hasFakeTraffic: false, \n hasDecoyChannels: false,\n hasMessageChunking: false\n },\n 'maximum': {\n // PREMIUM sessions - all functions included\n hasEncryption: true,\n hasECDH: true,\n hasECDSA: true,\n hasMutualAuth: true,\n hasMetadataProtection: true,\n hasEnhancedReplayProtection: true,\n hasNonExtractableKeys: true,\n hasRateLimiting: true,\n hasEnhancedValidation: true,\n hasPFS: true,\n \n // ALL advanced features\n hasNestedEncryption: true,\n hasPacketPadding: true,\n hasPacketReordering: true,\n hasAntiFingerprinting: true,\n hasFakeTraffic: true,\n hasDecoyChannels: true,\n hasMessageChunking: true\n }\n };\n\n return featureMatrix[securityLevel]?.[feature] || false;\n }\n\n // ============================================\n // FIXED DEMO MODE: Improved controls and management\n // ============================================\n\n startActiveDemoSessionCleanup() {\n setInterval(() => {\n const now = Date.now();\n let cleanedCount = 0;\n \n for (const preimage of this.activeDemoSessions) {\n const demoTimestamp = this.extractDemoTimestamp(preimage);\n if (demoTimestamp && (now - demoTimestamp) > this.demoSessionMaxDuration) {\n this.activeDemoSessions.delete(preimage);\n cleanedCount++;\n }\n }\n \n if (cleanedCount > 0) {\n console.log(`\uD83E\uDDF9 Cleaned ${cleanedCount} expired active demo sessions`);\n }\n }, 30000); \n }\n \n\n startDemoSessionCleanup() {\n setInterval(() => {\n const now = Date.now();\n const maxAge = 25 * 60 * 60 * 1000; \n \n let cleanedCount = 0;\n for (const [identifier, data] of this.demoSessions.entries()) {\n if (now - data.lastUsed > maxAge) {\n this.demoSessions.delete(identifier);\n cleanedCount++;\n }\n \n if (data.sessions) {\n const originalCount = data.sessions.length;\n data.sessions = data.sessions.filter(session => \n now - session.timestamp < maxAge\n );\n \n if (data.sessions.length === 0 && now - data.lastUsed > maxAge) {\n this.demoSessions.delete(identifier);\n cleanedCount++;\n }\n }\n }\n \n for (const [identifier, sessions] of this.completedDemoSessions.entries()) {\n const filteredSessions = sessions.filter(session => \n now - session.endTime < maxAge\n );\n \n if (filteredSessions.length === 0) {\n this.completedDemoSessions.delete(identifier);\n } else {\n this.completedDemoSessions.set(identifier, filteredSessions);\n }\n }\n \n if (cleanedCount > 0) {\n console.log(`\uD83E\uDDF9 Cleaned ${cleanedCount} old demo session records`);\n }\n }, 60 * 60 * 1000); \n }\n\n // IMPROVED user fingerprint generation\n generateAdvancedUserFingerprint() {\n try {\n const basicComponents = [\n navigator.userAgent || '',\n navigator.language || '',\n screen.width + 'x' + screen.height,\n Intl.DateTimeFormat().resolvedOptions().timeZone || '',\n navigator.hardwareConcurrency || 0,\n navigator.deviceMemory || 0,\n navigator.platform || '',\n navigator.cookieEnabled ? '1' : '0',\n window.screen.colorDepth || 0,\n window.screen.pixelDepth || 0,\n navigator.maxTouchPoints || 0,\n navigator.onLine ? '1' : '0'\n ];\n\n const hardwareComponents = [];\n \n // WebGL fingerprint \n try {\n const canvas = document.createElement('canvas');\n const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');\n if (gl) {\n const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');\n if (debugInfo) {\n hardwareComponents.push(gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) || '');\n hardwareComponents.push(gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) || '');\n }\n hardwareComponents.push(gl.getParameter(gl.VERSION) || '');\n hardwareComponents.push(gl.getParameter(gl.SHADING_LANGUAGE_VERSION) || '');\n }\n } catch (e) {\n hardwareComponents.push('webgl_error');\n }\n\n // Canvas print \n try {\n const canvas = document.createElement('canvas');\n canvas.width = 200;\n canvas.height = 50;\n const ctx = canvas.getContext('2d');\n ctx.textBaseline = 'top';\n ctx.font = '14px Arial';\n ctx.fillText('SecureBit Demo Fingerprint \uD83D\uDD12', 2, 2);\n ctx.fillStyle = 'rgba(255,0,0,0.5)';\n ctx.fillRect(50, 10, 20, 20);\n hardwareComponents.push(canvas.toDataURL());\n } catch (e) {\n hardwareComponents.push('canvas_error');\n }\n\n // Audio fingerprint \n try {\n const audioContext = new (window.AudioContext || window.webkitAudioContext)();\n const oscillator = audioContext.createOscillator();\n const analyser = audioContext.createAnalyser();\n const gain = audioContext.createGain();\n \n oscillator.connect(analyser);\n analyser.connect(gain);\n gain.connect(audioContext.destination);\n \n oscillator.frequency.setValueAtTime(1000, audioContext.currentTime);\n gain.gain.setValueAtTime(0, audioContext.currentTime);\n \n hardwareComponents.push(audioContext.sampleRate.toString());\n hardwareComponents.push(audioContext.state);\n hardwareComponents.push(analyser.frequencyBinCount.toString());\n \n audioContext.close();\n } catch (e) {\n hardwareComponents.push('audio_error');\n }\n\n // CPU Performance \n const cpuBenchmark = this.performCPUBenchmark();\n hardwareComponents.push(cpuBenchmark);\n\n const allComponents = [...basicComponents, ...hardwareComponents];\n\n let primaryHash = 0;\n let secondaryHash = 0;\n let tertiaryHash = 0;\n \n const primaryStr = allComponents.slice(0, 8).join('|');\n const secondaryStr = allComponents.slice(8, 16).join('|');\n const tertiaryStr = allComponents.slice(16).join('|');\n \n for (let i = 0; i < primaryStr.length; i++) {\n const char = primaryStr.charCodeAt(i);\n primaryHash = ((primaryHash << 7) - primaryHash) + char;\n primaryHash = primaryHash & primaryHash;\n }\n\n for (let i = 0; i < secondaryStr.length; i++) {\n const char = secondaryStr.charCodeAt(i);\n secondaryHash = ((secondaryHash << 11) - secondaryHash) + char;\n secondaryHash = secondaryHash & secondaryHash;\n }\n \n for (let i = 0; i < tertiaryStr.length; i++) {\n const char = tertiaryStr.charCodeAt(i);\n tertiaryHash = ((tertiaryHash << 13) - tertiaryHash) + char;\n tertiaryHash = tertiaryHash & tertiaryHash;\n }\n \n const combined = `${Math.abs(primaryHash).toString(36)}_${Math.abs(secondaryHash).toString(36)}_${Math.abs(tertiaryHash).toString(36)}`;\n \n console.log('\uD83D\uDD12 Enhanced fingerprint generated:', {\n components: allComponents.length,\n primaryLength: primaryStr.length,\n secondaryLength: secondaryStr.length,\n tertiaryLength: tertiaryStr.length,\n fingerprintLength: combined.length\n });\n \n return combined;\n \n } catch (error) {\n console.warn('Failed to generate enhanced fingerprint:', error);\n return 'fallback_' + Date.now().toString(36) + '_' + Math.random().toString(36).substr(2, 9);\n }\n }\n\n performCPUBenchmark() {\n const start = performance.now();\n let result = 0;\n \n for (let i = 0; i < 100000; i++) {\n result += Math.sin(i) * Math.cos(i);\n }\n \n const end = performance.now();\n const duration = Math.round(end - start);\n \n if (duration < 5) return 'fast_cpu';\n if (duration < 15) return 'medium_cpu';\n if (duration < 30) return 'slow_cpu';\n return 'very_slow_cpu';\n }\n\n initializePersistentStorage() {\n this.storageKeys = {\n demoSessions: 'sb_demo_sessions_v2',\n completedSessions: 'sb_completed_sessions_v2',\n globalCounter: 'sb_global_demo_counter_v2',\n lastCleanup: 'sb_last_cleanup_v2',\n hardwareFingerprint: 'sb_hw_fingerprint_v2'\n };\n \n this.loadPersistentData();\n }\n\n loadPersistentData() {\n try {\n const savedDemoSessions = this.getFromStorage(this.storageKeys.demoSessions);\n if (savedDemoSessions) {\n const parsed = JSON.parse(savedDemoSessions);\n for (const [key, value] of Object.entries(parsed)) {\n this.demoSessions.set(key, value);\n }\n }\n \n const savedCompletedSessions = this.getFromStorage(this.storageKeys.completedSessions);\n if (savedCompletedSessions) {\n const parsed = JSON.parse(savedCompletedSessions);\n for (const [key, value] of Object.entries(parsed)) {\n this.completedDemoSessions.set(key, value);\n }\n }\n \n const savedGlobalCounter = this.getFromStorage(this.storageKeys.globalCounter);\n if (savedGlobalCounter) {\n this.globalDemoCounter = parseInt(savedGlobalCounter) || 0;\n } else {\n this.globalDemoCounter = 0;\n }\n \n console.log('\uD83D\uDCCA Persistent data loaded:', {\n demoSessions: this.demoSessions.size,\n completedSessions: this.completedDemoSessions.size,\n globalCounter: this.globalDemoCounter\n });\n \n } catch (error) {\n console.warn('Failed to load persistent data:', error);\n this.globalDemoCounter = 0;\n }\n }\n\n savePersistentData() {\n try {\n const demoSessionsObj = Object.fromEntries(this.demoSessions);\n this.setToStorage(this.storageKeys.demoSessions, JSON.stringify(demoSessionsObj));\n \n const completedSessionsObj = Object.fromEntries(this.completedDemoSessions);\n this.setToStorage(this.storageKeys.completedSessions, JSON.stringify(completedSessionsObj));\n \n this.setToStorage(this.storageKeys.globalCounter, this.globalDemoCounter.toString());\n \n this.setToStorage(this.storageKeys.lastCleanup, Date.now().toString());\n \n } catch (error) {\n console.warn('Failed to save persistent data:', error);\n }\n }\n\n getFromStorage(key) {\n try {\n if (typeof localStorage !== 'undefined') {\n const value = localStorage.getItem(key);\n if (value) return value;\n }\n } catch (e) {}\n \n try {\n if (typeof sessionStorage !== 'undefined') {\n const value = sessionStorage.getItem(key);\n if (value) return value;\n }\n } catch (e) {}\n \n try {\n if ('caches' in window) {\n }\n } catch (e) {}\n \n return null;\n }\n\n setToStorage(key, value) {\n try {\n if (typeof localStorage !== 'undefined') {\n localStorage.setItem(key, value);\n }\n } catch (e) {}\n \n try {\n if (typeof sessionStorage !== 'undefined') {\n sessionStorage.setItem(key, value);\n }\n } catch (e) {}\n \n if (!this.memoryStorage) this.memoryStorage = new Map();\n this.memoryStorage.set(key, value);\n }\n\n checkAntiResetProtection(userFingerprint) {\n if (!this.globalDemoCounter) {\n this.globalDemoCounter = 0;\n }\n \n const hardwareFingerprint = this.getHardwareFingerprint();\n \n const savedHardwareFingerprint = this.getFromStorage(this.storageKeys.hardwareFingerprint);\n \n if (savedHardwareFingerprint && savedHardwareFingerprint !== hardwareFingerprint) {\n console.warn('\uD83D\uDEA8 Hardware fingerprint mismatch detected - possible reset attempt');\n \n this.globalDemoCounter += 5;\n this.savePersistentData();\n \n return {\n isValid: false,\n reason: 'hardware_mismatch',\n penalty: 5\n };\n }\n \n this.setToStorage(this.storageKeys.hardwareFingerprint, hardwareFingerprint);\n \n if (this.globalDemoCounter >= 10) {\n return {\n isValid: false,\n reason: 'global_limit_exceeded',\n globalCount: this.globalDemoCounter\n };\n }\n \n return {\n isValid: true,\n globalCount: this.globalDemoCounter\n };\n }\n\n getHardwareFingerprint() {\n const components = [];\n\n components.push(navigator.hardwareConcurrency || 0);\n components.push(navigator.deviceMemory || 0);\n \n try {\n const canvas = document.createElement('canvas');\n const gl = canvas.getContext('webgl');\n if (gl) {\n const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');\n if (debugInfo) {\n components.push(gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) || '');\n components.push(gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) || '');\n }\n }\n } catch (e) {\n components.push('webgl_unavailable');\n }\n \n components.push(screen.width);\n components.push(screen.height);\n components.push(screen.colorDepth);\n\n components.push(Intl.DateTimeFormat().resolvedOptions().timeZone);\n \n let hash = 0;\n const str = components.join('|');\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash;\n }\n \n return Math.abs(hash).toString(36);\n }\n\n registerEnhancedDemoSessionUsage(userFingerprint, preimage) {\n const session = this.registerDemoSessionUsage(userFingerprint, preimage);\n \n this.savePersistentData();\n\n console.log('\uD83D\uDCCA Enhanced demo session registered:', {\n userFingerprint: userFingerprint.substring(0, 12),\n globalCount: this.globalDemoCounter,\n sessionId: session.sessionId,\n timestamp: new Date().toISOString()\n });\n \n return session;\n }\n\n // COMPLETELY REWRITTEN demo session limits check\n checkEnhancedDemoSessionLimits(userFingerprint) {\n const antiResetCheck = this.checkAntiResetProtection(userFingerprint);\n if (!antiResetCheck.isValid) {\n return {\n allowed: false,\n reason: antiResetCheck.reason,\n message: this.getAntiResetMessage(antiResetCheck),\n globalCount: antiResetCheck.globalCount,\n penalty: antiResetCheck.penalty\n };\n }\n \n const regularCheck = this.checkDemoSessionLimits(userFingerprint);\n \n if (regularCheck.allowed) {\n this.globalDemoCounter++;\n this.savePersistentData();\n }\n \n return {\n ...regularCheck,\n globalCount: this.globalDemoCounter\n };\n }\n\n\n\n getAntiResetMessage(antiResetCheck) {\n switch (antiResetCheck.reason) {\n case 'hardware_mismatch':\n return 'An attempt to reset restrictions was detected. Access to demo mode is temporarily restricted.';\n case 'global_limit_exceeded':\n return `Global demo session limit exceeded (${antiResetCheck.globalCount}/10). A paid session is required to continue.`;\n default:\n return 'Access to demo mode is restricted for security reasons.';\n }\n }\n\n\n\n // FIXED demo session usage registration\n registerDemoSessionUsage(userFingerprint, preimage) {\n const now = Date.now();\n const userData = this.demoSessions.get(userFingerprint) || {\n count: 0,\n lastUsed: 0,\n sessions: [],\n firstUsed: now\n };\n \n userData.count++;\n userData.lastUsed = now;\n \n // Add a new session with preimage for tracking\n const newSession = {\n timestamp: now,\n sessionId: crypto.getRandomValues(new Uint32Array(1))[0].toString(36),\n duration: this.demoSessionMaxDuration,\n preimage: preimage, \n status: 'active'\n };\n \n userData.sessions.push(newSession);\n \n // Clear old sessions (only those older than 24 hours)\n userData.sessions = userData.sessions.filter(session => \n now - session.timestamp < this.demoCooldownPeriod\n );\n \n // NEW: Add to global set of active sessions\n this.activeDemoSessions.add(preimage);\n \n this.demoSessions.set(userFingerprint, userData);\n \n console.log(`\uD83D\uDCCA Demo session registered for user ${userFingerprint.substring(0, 12)} (${userData.sessions.length}/${this.maxDemoSessionsPerUser} today)`);\n console.log(`\uD83C\uDF10 Global active demo sessions: ${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}`);\n \n return newSession;\n }\n\n performEnhancedCleanup() {\n const now = Date.now();\n const lastCleanup = parseInt(this.getFromStorage(this.storageKeys.lastCleanup)) || 0;\n \n if (now - lastCleanup < 6 * 60 * 60 * 1000) {\n return;\n }\n \n console.log('\uD83E\uDDF9 Performing enhanced cleanup...');\n \n const maxAge = 25 * 60 * 60 * 1000;\n let cleanedSessions = 0;\n \n for (const [identifier, data] of this.demoSessions.entries()) {\n if (now - data.lastUsed > maxAge) {\n this.demoSessions.delete(identifier);\n cleanedSessions++;\n }\n }\n \n let cleanedCompleted = 0;\n for (const [identifier, sessions] of this.completedDemoSessions.entries()) {\n const filteredSessions = sessions.filter(session => \n now - session.endTime < maxAge\n );\n \n if (filteredSessions.length === 0) {\n this.completedDemoSessions.delete(identifier);\n cleanedCompleted++;\n } else {\n this.completedDemoSessions.set(identifier, filteredSessions);\n }\n }\n \n const weekAgo = 7 * 24 * 60 * 60 * 1000;\n if (now - lastCleanup > weekAgo) {\n this.globalDemoCounter = Math.max(0, this.globalDemoCounter - 3);\n console.log('\uD83D\uDD04 Global demo counter reset (weekly):', this.globalDemoCounter);\n }\n \n this.savePersistentData();\n \n console.log('\u2705 Enhanced cleanup completed:', {\n cleanedSessions,\n cleanedCompleted,\n globalCounter: this.globalDemoCounter\n });\n }\n\n checkMultiTabProtection() {\n const tabId = 'tab_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);\n const activeTabsKey = 'sb_active_tabs';\n \n try {\n const activeTabsStr = this.getFromStorage(activeTabsKey);\n const activeTabs = activeTabsStr ? JSON.parse(activeTabsStr) : [];\n \n const now = Date.now();\n const validTabs = activeTabs.filter(tab => now - tab.timestamp < 30000);\n \n if (validTabs.length >= 2) {\n return {\n allowed: false,\n reason: 'multiple_tabs',\n message: 'Demo mode is only available in one tab at a time..'\n };\n }\n\n validTabs.push({\n tabId: tabId,\n timestamp: now\n });\n \n this.setToStorage(activeTabsKey, JSON.stringify(validTabs));\n this.currentTabId = tabId;\n\n this.startTabHeartbeat();\n \n return {\n allowed: true,\n tabId: tabId\n };\n \n } catch (error) {\n console.warn('Multi-tab protection error:', error);\n return { allowed: true }; \n }\n }\n\n startTabHeartbeat() {\n if (this.tabHeartbeatInterval) {\n clearInterval(this.tabHeartbeatInterval);\n }\n \n this.tabHeartbeatInterval = setInterval(() => {\n this.updateTabHeartbeat();\n }, 10000); \n }\n\n updateTabHeartbeat() {\n if (!this.currentTabId) return;\n \n try {\n const activeTabsKey = 'sb_active_tabs';\n const activeTabsStr = this.getFromStorage(activeTabsKey);\n const activeTabs = activeTabsStr ? JSON.parse(activeTabsStr) : [];\n \n const updatedTabs = activeTabs.map(tab => {\n if (tab.tabId === this.currentTabId) {\n return {\n ...tab,\n timestamp: Date.now()\n };\n }\n return tab;\n });\n \n this.setToStorage(activeTabsKey, JSON.stringify(updatedTabs));\n \n } catch (error) {\n console.warn('Tab heartbeat update failed:', error);\n }\n }\n\n // NEW method: Register demo session completion\n registerDemoSessionCompletion(userFingerprint, sessionDuration, preimage) {\n const now = Date.now();\n \n // Remove from active sessions\n if (preimage) {\n this.activeDemoSessions.delete(preimage);\n }\n \n // Add to completed sessions\n const completedSessions = this.completedDemoSessions.get(userFingerprint) || [];\n completedSessions.push({\n endTime: now,\n duration: sessionDuration,\n preimage: preimage ? preimage.substring(0, 16) + '...' : 'unknown' // \u041B\u043E\u0433\u0438\u0440\u0443\u0435\u043C \u0442\u043E\u043B\u044C\u043A\u043E \u0447\u0430\u0441\u0442\u044C \u0434\u043B\u044F \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E\u0441\u0442\u0438\n });\n \n // Store only the last completed sessions\n const filteredSessions = completedSessions\n .filter(session => now - session.endTime < this.minTimeBetweenCompletedSessions)\n .slice(-5); \n \n this.completedDemoSessions.set(userFingerprint, filteredSessions);\n \n // Update the status in the user's master data\n const userData = this.demoSessions.get(userFingerprint);\n if (userData && userData.sessions) {\n const session = userData.sessions.find(s => s.preimage === preimage);\n if (session) {\n session.status = 'completed';\n session.endTime = now;\n }\n }\n \n console.log(`\u2705 Demo session completed for user ${userFingerprint.substring(0, 12)}`);\n console.log(`\uD83C\uDF10 Global active demo sessions: ${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}`);\n }\n\n // ENHANCED demo preimage generation with additional protection\n generateSecureDemoPreimage() {\n try {\n const timestamp = Date.now();\n const randomBytes = crypto.getRandomValues(new Uint8Array(24));\n const timestampBytes = new Uint8Array(4);\n const versionBytes = new Uint8Array(4);\n \n // Pack the timestamp\n const timestampSeconds = Math.floor(timestamp / 1000);\n timestampBytes[0] = (timestampSeconds >>> 24) & 0xFF;\n timestampBytes[1] = (timestampSeconds >>> 16) & 0xFF;\n timestampBytes[2] = (timestampSeconds >>> 8) & 0xFF;\n timestampBytes[3] = timestampSeconds & 0xFF;\n \n // IMPROVED version marker with additional protection\n versionBytes[0] = 0xDE; \n versionBytes[1] = 0xE0; \n versionBytes[2] = 0x00; \n versionBytes[3] = 0x02; \n \n const combined = new Uint8Array(32);\n combined.set(versionBytes, 0);\n combined.set(timestampBytes, 4);\n combined.set(randomBytes, 8);\n \n const preimage = Array.from(combined).map(b => b.toString(16).padStart(2, '0')).join('');\n \n console.log(`\uD83C\uDFAE Generated SECURE demo preimage v2: ${preimage.substring(0, 16)}...`);\n return preimage;\n \n } catch (error) {\n console.error('Failed to generate demo preimage:', error);\n throw new Error('Failed to generate secure demo preimage');\n }\n }\n\n // UPDATED demo preimage check\n isDemoPreimage(preimage) {\n if (!preimage || typeof preimage !== 'string' || preimage.length !== 64) {\n return false;\n }\n \n // Check the demo marker (support versions 1 and 2)\n const lower = preimage.toLowerCase();\n return lower.startsWith('dee00001') || lower.startsWith('dee00002');\n }\n\n // Extract timestamp from demo preimage\n extractDemoTimestamp(preimage) {\n if (!this.isDemoPreimage(preimage)) {\n return null;\n }\n \n try {\n const timestampHex = preimage.slice(8, 16);\n const timestampSeconds = parseInt(timestampHex, 16);\n return timestampSeconds * 1000;\n } catch (error) {\n console.error('Failed to extract demo timestamp:', error);\n return null;\n }\n }\n\n // ============================================\n // VALIDATION AND CHECKS\n // ============================================\n\n validateSessionType(sessionType) {\n if (!sessionType || typeof sessionType !== 'string') {\n throw new Error('Session type must be a non-empty string');\n }\n \n if (!this.sessionPrices[sessionType]) {\n throw new Error(`Invalid session type: ${sessionType}. Allowed: ${Object.keys(this.sessionPrices).join(', ')}`);\n }\n \n const pricing = this.sessionPrices[sessionType];\n \n if (sessionType === 'demo') {\n return true;\n }\n \n if (pricing.sats < this.minimumPaymentSats) {\n throw new Error(`Session type ${sessionType} below minimum payment threshold (${this.minimumPaymentSats} sats)`);\n }\n \n return true;\n }\n\n calculateEntropy(str) {\n const freq = {};\n for (let char of str) {\n freq[char] = (freq[char] || 0) + 1;\n }\n \n let entropy = 0;\n const length = str.length;\n for (let char in freq) {\n const p = freq[char] / length;\n entropy -= p * Math.log2(p);\n }\n \n return entropy;\n }\n\n // ============================================\n // ENHANCED verification with additional checks\n // ============================================\n\n async verifyCryptographically(preimage, paymentHash) {\n try {\n // Basic validation\n if (!preimage || typeof preimage !== 'string' || preimage.length !== 64) {\n throw new Error('Invalid preimage format');\n }\n \n if (!/^[0-9a-fA-F]{64}$/.test(preimage)) {\n throw new Error('Preimage must be valid hexadecimal');\n }\n \n if (this.isDemoPreimage(preimage)) {\n console.log('\uD83C\uDFAE Demo preimage detected - performing ENHANCED validation...');\n \n // CHECK 1: Preimage duplicates\n if (this.usedPreimages.has(preimage)) {\n throw new Error('Demo preimage already used - replay attack prevented');\n }\n \n // CHECK 2: Global Activity\n if (this.activeDemoSessions.has(preimage)) {\n throw new Error('Demo preimage already active - concurrent usage prevented');\n }\n \n // CHECK 3: Timestamp validation\n const demoTimestamp = this.extractDemoTimestamp(preimage);\n if (!demoTimestamp) {\n throw new Error('Invalid demo preimage timestamp');\n }\n \n const now = Date.now();\n const age = now - demoTimestamp;\n \n // Demo preimage must not be older than 15 minutes\n if (age > 15 * 60 * 1000) {\n throw new Error(`Demo preimage expired (age: ${Math.round(age / (60 * 1000))} minutes)`);\n }\n\n if (age < -2 * 60 * 1000) {\n throw new Error('Demo preimage timestamp from future - possible clock manipulation');\n }\n \n // CHECK 4: FIXED calling limits - use the CORRECT method\n const userFingerprint = this.generateAdvancedUserFingerprint(); \n const limitsCheck = this.checkEnhancedDemoSessionLimits(userFingerprint); \n \n if (!limitsCheck.allowed) {\n throw new Error(`Demo session limits exceeded: ${limitsCheck.message}`);\n }\n \n // FIX: For demo sessions, do NOT add preimage to usedPreimages here,\n // as this will only be done after successful activation\n this.registerEnhancedDemoSessionUsage(userFingerprint, preimage); \n \n console.log('\u2705 Demo preimage ENHANCED validation passed');\n return true;\n }\n \n // For regular preimage - standard checks\n if (this.usedPreimages.has(preimage)) {\n throw new Error('Preimage already used - replay attack prevented');\n }\n \n // Checking entropy\n const entropy = this.calculateEntropy(preimage);\n if (entropy < 3.5) {\n throw new Error(`Preimage has insufficient entropy: ${entropy.toFixed(2)}`);\n }\n \n // Cryptographic verification SHA256(preimage) = paymentHash\n const preimageBytes = new Uint8Array(preimage.match(/.{2}/g).map(byte => parseInt(byte, 16)));\n const hashBuffer = await crypto.subtle.digest('SHA-256', preimageBytes);\n const computedHash = Array.from(new Uint8Array(hashBuffer))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n \n const isValid = computedHash === paymentHash.toLowerCase();\n \n if (isValid) {\n this.usedPreimages.add(preimage);\n console.log('\u2705 Standard preimage cryptographic validation passed');\n }\n \n return isValid;\n \n } catch (error) {\n console.error('\u274C Cryptographic verification failed:', error.message);\n return false;\n }\n }\n\n\n // ============================================\n // LIGHTNING NETWORK INTEGRATION\n // ============================================\n\n // Creating a Lightning invoice\n async createLightningInvoice(sessionType) {\n const pricing = this.sessionPrices[sessionType];\n if (!pricing) throw new Error('Invalid session type');\n\n try {\n console.log(`Creating ${sessionType} invoice for ${pricing.sats} sats...`);\n\n const now = Date.now();\n if (now - this.lastApiCall < this.apiCallMinInterval) {\n throw new Error('API rate limit: please wait before next request');\n }\n this.lastApiCall = now;\n\n const healthCheck = await fetch(`${this.verificationConfig.apiUrl}/api/v1/health`, {\n method: 'GET',\n headers: {\n 'X-Api-Key': this.verificationConfig.apiKey\n },\n signal: AbortSignal.timeout(5000)\n });\n\n if (!healthCheck.ok) {\n throw new Error(`LNbits API unavailable: ${healthCheck.status}`);\n }\n\n const response = await fetch(`${this.verificationConfig.apiUrl}/api/v1/payments`, {\n method: 'POST',\n headers: {\n 'X-Api-Key': this.verificationConfig.apiKey,\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n out: false,\n amount: pricing.sats,\n memo: `SecureBit.chat ${sessionType} session (${pricing.hours}h) - ${Date.now()}`,\n unit: 'sat',\n expiry: this.verificationConfig.invoiceExpiryMinutes * 60\n }),\n signal: AbortSignal.timeout(10000)\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n console.error('LNbits API error response:', errorText);\n throw new Error(`LNbits API error ${response.status}: ${errorText}`);\n }\n\n const data = await response.json();\n \n console.log('\u2705 Lightning invoice created successfully');\n \n return {\n paymentRequest: data.bolt11 || data.payment_request,\n paymentHash: data.payment_hash,\n checkingId: data.checking_id || data.payment_hash,\n amount: data.amount || pricing.sats,\n sessionType: sessionType,\n createdAt: Date.now(),\n expiresAt: Date.now() + (this.verificationConfig.invoiceExpiryMinutes * 60 * 1000),\n description: data.description || data.memo || `SecureBit.chat ${sessionType} session`,\n bolt11: data.bolt11 || data.payment_request,\n memo: data.memo || `SecureBit.chat ${sessionType} session`\n };\n\n } catch (error) {\n console.error('\u274C Lightning invoice creation failed:', error);\n \n if (this.verificationConfig.isDemo && error.message.includes('API')) {\n console.log('\uD83D\uDD04 Creating demo invoice for testing...');\n return this.createDemoInvoice(sessionType);\n }\n \n throw error;\n }\n }\n\n // Creating a demo invoice for testing\n createDemoInvoice(sessionType) {\n const pricing = this.sessionPrices[sessionType];\n const demoHash = Array.from(crypto.getRandomValues(new Uint8Array(32)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n \n return {\n paymentRequest: `lntb${pricing.sats}1p${demoHash.substring(0, 16)}...`,\n paymentHash: demoHash,\n checkingId: demoHash,\n amount: pricing.sats,\n sessionType: sessionType,\n createdAt: Date.now(),\n expiresAt: Date.now() + (5 * 60 * 1000),\n description: `SecureBit.chat ${sessionType} session (DEMO)`,\n isDemo: true\n };\n }\n\n // Checking payment status via LNbits\n async checkPaymentStatus(checkingId) {\n try {\n console.log(`\uD83D\uDD0D Checking payment status for: ${checkingId?.substring(0, 8)}...`);\n\n const now = Date.now();\n if (now - this.lastApiCall < this.apiCallMinInterval) {\n throw new Error('API rate limit exceeded');\n }\n this.lastApiCall = now;\n\n const response = await fetch(`${this.verificationConfig.apiUrl}/api/v1/payments/${checkingId}`, {\n method: 'GET',\n headers: {\n 'X-Api-Key': this.verificationConfig.apiKey,\n 'Content-Type': 'application/json'\n },\n signal: AbortSignal.timeout(10000)\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n console.error('Payment status check failed:', errorText);\n throw new Error(`Payment check failed: ${response.status} - ${errorText}`);\n }\n\n const data = await response.json();\n console.log('\uD83D\uDCCA Payment status retrieved successfully');\n \n return {\n paid: data.paid || false,\n preimage: data.preimage || null,\n details: data.details || {},\n amount: data.amount || 0,\n fee: data.fee || 0,\n timestamp: data.timestamp || Date.now(),\n bolt11: data.bolt11 || null\n };\n\n } catch (error) {\n console.error('\u274C Payment status check error:', error);\n \n if (this.verificationConfig.isDemo && error.message.includes('API')) {\n console.log('\uD83D\uDD04 Returning demo payment status...');\n return {\n paid: false,\n preimage: null,\n details: { demo: true },\n amount: 0,\n fee: 0,\n timestamp: Date.now()\n };\n }\n \n throw error;\n }\n }\n\n // Payment verification via LNbits API\n async verifyPaymentLNbits(preimage, paymentHash) {\n try {\n console.log(`\uD83D\uDD10 Verifying payment via LNbits API...`);\n \n if (!this.verificationConfig.apiUrl || !this.verificationConfig.apiKey) {\n throw new Error('LNbits API configuration missing');\n }\n\n const now = Date.now();\n if (now - this.lastApiCall < this.apiCallMinInterval) {\n throw new Error('API rate limit: please wait before next verification');\n }\n this.lastApiCall = now;\n\n const response = await fetch(`${this.verificationConfig.apiUrl}/api/v1/payments/${paymentHash}`, {\n method: 'GET',\n headers: {\n 'X-Api-Key': this.verificationConfig.apiKey,\n 'Content-Type': 'application/json'\n },\n signal: AbortSignal.timeout(10000)\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n console.error('LNbits verification failed:', errorText);\n throw new Error(`API request failed: ${response.status} - ${errorText}`);\n }\n\n const paymentData = await response.json();\n console.log('\uD83D\uDCCB Payment verification data received from LNbits');\n \n const isPaid = paymentData.paid === true;\n const preimageMatches = paymentData.preimage === preimage;\n const amountValid = paymentData.amount >= this.minimumPaymentSats;\n \n const paymentTimestamp = paymentData.timestamp || paymentData.time || 0;\n const paymentAge = now - (paymentTimestamp * 1000);\n const maxPaymentAge = 24 * 60 * 60 * 1000;\n \n if (paymentAge > maxPaymentAge && paymentTimestamp > 0) {\n throw new Error(`Payment too old: ${Math.round(paymentAge / (60 * 60 * 1000))} hours (max: 24h)`);\n }\n \n if (isPaid && preimageMatches && amountValid) {\n console.log('\u2705 Payment verified successfully via LNbits');\n return {\n verified: true,\n amount: paymentData.amount,\n fee: paymentData.fee || 0,\n timestamp: paymentTimestamp || now,\n method: 'lnbits',\n verificationTime: now,\n paymentAge: paymentAge\n };\n }\n\n console.log('\u274C LNbits payment verification failed:', {\n paid: isPaid,\n preimageMatch: preimageMatches,\n amountValid: amountValid,\n paymentAge: Math.round(paymentAge / (60 * 1000)) + ' minutes'\n });\n \n return {\n verified: false,\n reason: 'Payment verification failed: not paid, preimage mismatch, insufficient amount, or payment too old',\n method: 'lnbits',\n details: {\n paid: isPaid,\n preimageMatch: preimageMatches,\n amountValid: amountValid,\n paymentAge: paymentAge\n }\n };\n \n } catch (error) {\n console.error('\u274C LNbits payment verification failed:', error);\n return {\n verified: false,\n reason: error.message,\n method: 'lnbits',\n error: true\n };\n }\n }\n\n // ============================================\n // BASIC LOGIC OF PAYMENT VERIFICATION\n // ============================================\n\n // The main method of payment verification\n async verifyPayment(preimage, paymentHash) {\n console.log(`\uD83D\uDD10 Starting payment verification...`);\n \n try {\n if (!preimage || !paymentHash) {\n throw new Error('Missing preimage or payment hash');\n }\n \n if (typeof preimage !== 'string' || typeof paymentHash !== 'string') {\n throw new Error('Preimage and payment hash must be strings');\n }\n \n // Special demo preimage processing with ENHANCED checks\n if (this.isDemoPreimage(preimage)) {\n console.log('\uD83C\uDFAE Processing demo session verification...');\n \n // Cryptographic verification already includes all necessary checks\n const cryptoValid = await this.verifyCryptographically(preimage, paymentHash);\n if (!cryptoValid) {\n return { \n verified: false, \n reason: 'Demo preimage verification failed',\n stage: 'crypto'\n };\n }\n \n console.log('\u2705 Demo session verified successfully');\n return { \n verified: true, \n method: 'demo',\n sessionType: 'demo',\n isDemo: true,\n warning: 'Demo session - limited duration (6 minutes)'\n };\n }\n \n // Cryptographic verification for regular preimage\n const cryptoValid = await this.verifyCryptographically(preimage, paymentHash);\n if (!cryptoValid) {\n return { \n verified: false, \n reason: 'Cryptographic verification failed',\n stage: 'crypto'\n };\n }\n\n console.log('\u2705 Cryptographic verification passed');\n\n // Check via Lightning Network (if not demo mode)\n if (!this.verificationConfig.isDemo) {\n switch (this.verificationConfig.method) {\n case 'lnbits':\n const lnbitsResult = await this.verifyPaymentLNbits(preimage, paymentHash);\n if (!lnbitsResult.verified) {\n return {\n verified: false,\n reason: lnbitsResult.reason || 'LNbits verification failed',\n stage: 'lightning',\n details: lnbitsResult.details\n };\n }\n return lnbitsResult;\n \n default:\n console.warn('Unknown verification method, using crypto-only verification');\n return { \n verified: true, \n method: 'crypto-only',\n warning: 'Lightning verification skipped - unknown method'\n };\n }\n } else {\n console.warn('\uD83D\uDEA8 DEMO MODE: Lightning payment verification bypassed - FOR DEVELOPMENT ONLY');\n return { \n verified: true, \n method: 'demo-mode',\n warning: 'DEMO MODE - Lightning verification bypassed'\n };\n }\n \n } catch (error) {\n console.error('\u274C Payment verification failed:', error);\n return { \n verified: false, \n reason: error.message,\n stage: 'error'\n };\n }\n }\n\n // ============================================\n // SESSION MANAGEMENT\n // ============================================\n\n // ============================================\n // REWORKED session activation methods\n // ============================================\n\n async safeActivateSession(sessionType, preimage, paymentHash) {\n try {\n console.log(`\uD83D\uDE80 Attempting to activate ${sessionType} session...`);\n \n if (!sessionType || !preimage || !paymentHash) {\n return { \n success: false, \n reason: 'Missing required parameters: sessionType, preimage, or paymentHash' \n };\n }\n \n try {\n this.validateSessionType(sessionType);\n } catch (error) {\n return { success: false, reason: error.message };\n }\n \n if (this.hasActiveSession()) {\n return { \n success: false, \n reason: 'Active session already exists. Please wait for it to expire or disconnect.' \n };\n }\n \n if (sessionType === 'demo') {\n if (!this.isDemoPreimage(preimage)) {\n return {\n success: false,\n reason: 'Invalid demo preimage format. Please use the generated demo preimage.'\n };\n }\n \n const userFingerprint = this.generateAdvancedUserFingerprint();\n const demoCheck = this.checkEnhancedDemoSessionLimits(userFingerprint);\n \n if (!demoCheck.allowed) {\n console.log(`\u26A0\uFE0F Demo session cooldown active, but allowing activation for development`);\n \n if (demoCheck.reason === 'global_limit_exceeded') {\n return {\n success: false,\n reason: demoCheck.message,\n demoLimited: true,\n timeUntilNext: demoCheck.timeUntilNext,\n remaining: demoCheck.remaining\n };\n }\n \n console.log(`\uD83D\uDD04 Bypassing demo cooldown for development purposes`);\n }\n \n if (this.activeDemoSessions.has(preimage)) {\n if (!this.currentSession || !this.hasActiveSession()) {\n console.log(`\uD83D\uDD04 Demo session with preimage ${preimage.substring(0, 16)}... was interrupted, allowing reactivation`);\n this.activeDemoSessions.delete(preimage);\n } else {\n return {\n success: false,\n reason: 'Demo session with this preimage is already active',\n demoLimited: true\n };\n }\n }\n }\n \n let verificationResult;\n \n if (sessionType === 'demo') {\n console.log('\uD83C\uDFAE Using special demo verification for activation...');\n verificationResult = await this.verifyDemoSessionForActivation(preimage, paymentHash);\n } else {\n verificationResult = await this.verifyPayment(preimage, paymentHash);\n }\n \n if (!verificationResult.verified) {\n return {\n success: false,\n reason: verificationResult.reason,\n stage: verificationResult.stage,\n method: verificationResult.method,\n demoLimited: verificationResult.demoLimited,\n timeUntilNext: verificationResult.timeUntilNext,\n remaining: verificationResult.remaining\n };\n }\n \n // Session activation\n const session = this.activateSession(sessionType, preimage);\n \n console.log(`\u2705 Session activated successfully: ${sessionType} via ${verificationResult.method}`);\n return {\n success: true,\n sessionType: sessionType,\n method: verificationResult.method,\n details: verificationResult,\n timeLeft: this.getTimeLeft(),\n sessionId: session.id,\n warning: verificationResult.warning,\n isDemo: verificationResult.isDemo || false,\n remaining: verificationResult.remaining\n };\n \n } catch (error) {\n console.error('\u274C Session activation failed:', error);\n return {\n success: false,\n reason: error.message,\n method: 'error'\n };\n }\n }\n\n // REWORKED session activation\n activateSession(sessionType, preimage) {\n if (this.hasActiveSession()) {\n return this.currentSession;\n }\n if (this.sessionTimer) {\n clearInterval(this.sessionTimer);\n this.sessionTimer = null;\n }\n\n const pricing = this.sessionPrices[sessionType];\n const now = Date.now();\n \n let duration;\n if (sessionType === 'demo') {\n duration = this.demoSessionMaxDuration;\n } else {\n duration = pricing.hours * 60 * 60 * 1000;\n }\n \n const expiresAt = now + duration;\n const sessionId = Array.from(crypto.getRandomValues(new Uint8Array(16)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n\n this.currentSession = {\n id: sessionId,\n type: sessionType,\n startTime: now,\n expiresAt: expiresAt,\n preimage: preimage,\n isDemo: sessionType === 'demo',\n securityLevel: this.getSecurityLevelForSession(sessionType)\n };\n\n this.startSessionTimer();\n \n if (sessionType === 'demo') {\n setTimeout(() => {\n this.handleDemoSessionExpiry(preimage);\n }, duration);\n }\n \n const durationMinutes = Math.round(duration / (60 * 1000));\n const securityLevel = this.currentSession ? this.currentSession.securityLevel : 'unknown';\n console.log(`\uD83D\uDCC5 Session ${sessionId.substring(0, 8)}... activated for ${durationMinutes} minutes with ${securityLevel} security`);\n \n if (sessionType === 'demo') {\n this.activeDemoSessions.add(preimage);\n this.usedPreimages.add(preimage);\n console.log(`\uD83C\uDF10 Demo session added to active sessions. Total: ${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}`);\n }\n \n // SENDING SECURITY LEVEL INFORMATION TO WebRTC\n const activatedSession = this.currentSession; \n setTimeout(() => {\n if (activatedSession) {\n this.notifySessionActivated(activatedSession);\n }\n // Notify WebRTC manager about session type\n if (window.webrtcManager && window.webrtcManager.configureSecurityForSession && activatedSession) {\n const securityLevel = activatedSession.securityLevel || this.getSecurityLevelForSession(sessionType);\n window.webrtcManager.configureSecurityForSession(sessionType, securityLevel);\n }\n }, 100);\n \n return this.currentSession;\n }\n\n // UPDATED method for getting session information\n getSessionInfo() {\n if (!this.currentSession) {\n return null;\n }\n\n const securityLevel = this.getSecurityLevelForSession(this.currentSession.type);\n const pricing = this.sessionPrices[this.currentSession.type];\n\n return {\n ...this.currentSession,\n securityLevel: securityLevel,\n securityDescription: this.getSecurityDescription(securityLevel),\n pricing: pricing,\n timeLeft: this.getTimeLeft(),\n isConnected: this.hasActiveSession()\n };\n }\n\n getSecurityDescription(level) {\n const descriptions = {\n 'basic': {\n title: 'Basic Security',\n features: [\n 'End-to-end encryption',\n 'Basic key exchange',\n 'Rate limiting',\n 'Message integrity'\n ],\n limitations: [\n 'No advanced obfuscation',\n 'No traffic padding',\n 'No decoy channels'\n ]\n },\n 'enhanced': {\n title: 'Enhanced Security',\n features: [\n 'All basic features',\n 'ECDSA signatures',\n 'Metadata protection',\n 'Perfect forward secrecy',\n 'Nested encryption',\n 'Packet padding'\n ],\n limitations: [\n 'Limited traffic obfuscation',\n 'No fake traffic generation'\n ]\n },\n 'maximum': {\n title: 'Maximum Security',\n features: [\n 'All enhanced features',\n 'Traffic obfuscation',\n 'Fake traffic generation',\n 'Decoy channels',\n 'Anti-fingerprinting',\n 'Message chunking',\n 'Packet reordering protection'\n ],\n limitations: []\n }\n };\n\n return descriptions[level] || descriptions['basic'];\n }\n\n notifySessionActivated(session = null) {\n const targetSession = session || this.currentSession;\n\n if (!targetSession) return;\n if (targetSession.notified) {\n return;\n }\n \n const timeLeft = Math.max(0, targetSession.expiresAt - Date.now());\n const sessionType = targetSession.type;\n \n\n \n if (window.updateSessionTimer) {\n window.updateSessionTimer(timeLeft, sessionType);\n }\n \n document.dispatchEvent(new CustomEvent('session-activated', {\n detail: {\n sessionId: targetSession.id,\n timeLeft: timeLeft,\n sessionType: sessionType,\n isDemo: targetSession.isDemo,\n timestamp: Date.now()\n }\n }));\n \n if (window.forceUpdateHeader) {\n window.forceUpdateHeader(timeLeft, sessionType);\n }\n\n if (window.debugSessionManager) {\n window.debugSessionManager();\n }\n targetSession.notified = true;\n }\n\n handleDemoSessionExpiry(preimage) {\n if (this.currentSession && this.currentSession.preimage === preimage) {\n const userFingerprint = this.generateAdvancedUserFingerprint(); \n const sessionDuration = Date.now() - this.currentSession.startTime;\n \n this.registerDemoSessionCompletion(userFingerprint, sessionDuration, preimage);\n \n console.log(`\u23F0 Demo session auto-expired for preimage ${preimage.substring(0, 16)}...`);\n }\n }\n\n startSessionTimer() {\n if (this.sessionTimer) {\n clearInterval(this.sessionTimer);\n }\n\n this.sessionTimer = setInterval(() => {\n if (!this.hasActiveSession()) {\n this.expireSession();\n }\n }, 60000);\n }\n\n expireSession() {\n if (this.sessionTimer) {\n clearInterval(this.sessionTimer);\n this.sessionTimer = null;\n }\n \n const expiredSession = this.currentSession;\n \n if (expiredSession && expiredSession.isDemo) {\n const userFingerprint = this.generateAdvancedUserFingerprint(); \n const sessionDuration = Date.now() - expiredSession.startTime;\n this.registerDemoSessionCompletion(userFingerprint, sessionDuration, expiredSession.preimage);\n }\n \n this.currentSession = null;\n \n if (expiredSession) {\n console.log(`\u23F0 Session ${expiredSession.id.substring(0, 8)}... expired`);\n }\n \n if (this.onSessionExpired) {\n this.onSessionExpired();\n }\n }\n\n hasActiveSession() {\n if (!this.currentSession) {\n return false;\n }\n \n const isActive = Date.now() < this.currentSession.expiresAt;\n \n return isActive;\n }\n\n getTimeLeft() {\n if (!this.currentSession) return 0;\n return Math.max(0, this.currentSession.expiresAt - Date.now());\n }\n\n forceUpdateTimer() {\n if (this.currentSession) {\n const timeLeft = this.getTimeLeft();\n if (window.DEBUG_MODE && Math.floor(Date.now() / 30000) !== Math.floor((Date.now() - 1000) / 30000)) {\n console.log(`\u23F1\uFE0F Timer updated: ${Math.ceil(timeLeft / 1000)}s left`);\n }\n return timeLeft;\n }\n return 0;\n }\n\n // ============================================\n // DEMO MODE: Custom Methods\n // ============================================\n\n // UPDATED demo session creation\n createDemoSession() {\n const userFingerprint = this.generateAdvancedUserFingerprint(); \n const demoCheck = this.checkEnhancedDemoSessionLimits(userFingerprint); \n \n if (!demoCheck.allowed) {\n return {\n success: false,\n reason: demoCheck.message,\n timeUntilNext: demoCheck.timeUntilNext,\n remaining: demoCheck.remaining,\n blockingReason: demoCheck.reason\n };\n }\n \n // Checking the global limit\n if (this.activeDemoSessions.size >= this.maxGlobalDemoSessions) {\n return {\n success: false,\n reason: `Too many demo sessions active globally (${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}). Please try again later.`,\n blockingReason: 'global_limit',\n globalActive: this.activeDemoSessions.size,\n globalLimit: this.maxGlobalDemoSessions\n };\n }\n \n try {\n const demoPreimage = this.generateSecureDemoPreimage();\n const demoPaymentHash = 'demo_' + Array.from(crypto.getRandomValues(new Uint8Array(16)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n \n return {\n success: true,\n sessionType: 'demo',\n preimage: demoPreimage,\n paymentHash: demoPaymentHash,\n duration: this.sessionPrices.demo.hours,\n durationMinutes: Math.round(this.demoSessionMaxDuration / (60 * 1000)),\n warning: `Demo session - limited to ${Math.round(this.demoSessionMaxDuration / (60 * 1000))} minutes`,\n remaining: demoCheck.remaining - 1,\n globalActive: this.activeDemoSessions.size + 1,\n globalLimit: this.maxGlobalDemoSessions\n };\n } catch (error) {\n console.error('Failed to create demo session:', error);\n return {\n success: false,\n reason: 'Failed to generate demo session. Please try again.',\n remaining: demoCheck.remaining\n };\n }\n }\n\n\n // UPDATED information about demo limits\n getDemoSessionInfo() {\n const userFingerprint = this.generateAdvancedUserFingerprint(); \n const userData = this.demoSessions.get(userFingerprint);\n const now = Date.now();\n \n if (!userData) {\n return {\n available: this.maxDemoSessionsPerUser,\n used: 0,\n total: this.maxDemoSessionsPerUser,\n nextAvailable: 'immediately',\n cooldownMinutes: 0,\n durationMinutes: Math.round(this.demoSessionMaxDuration / (60 * 1000)),\n canUseNow: this.activeDemoSessions.size < this.maxGlobalDemoSessions,\n globalActive: this.activeDemoSessions.size,\n globalLimit: this.maxGlobalDemoSessions,\n debugInfo: 'New user, no restrictions'\n };\n }\n \n // Counting sessions for the last 24 hours\n const sessionsLast24h = userData.sessions.filter(session => \n now - session.timestamp < this.demoCooldownPeriod\n );\n \n const available = Math.max(0, this.maxDemoSessionsPerUser - sessionsLast24h.length);\n \n // We check all possible blockages\n let cooldownMs = 0;\n let nextAvailable = 'immediately';\n let blockingReason = null;\n let debugInfo = '';\n \n // Global limit\n if (this.activeDemoSessions.size >= this.maxGlobalDemoSessions) {\n nextAvailable = 'when global limit decreases';\n blockingReason = 'global_limit';\n debugInfo = `Global limit: ${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}`;\n }\n // Daily limit\n else if (available === 0) {\n const oldestSession = Math.min(...sessionsLast24h.map(s => s.timestamp));\n cooldownMs = this.demoCooldownPeriod - (now - oldestSession);\n nextAvailable = `${Math.ceil(cooldownMs / (60 * 1000))} minutes`;\n blockingReason = 'daily_limit';\n debugInfo = `Daily limit reached: ${sessionsLast24h.length}/${this.maxDemoSessionsPerUser}`;\n }\n // Cooldown between sessions\n else if (userData.lastUsed && (now - userData.lastUsed) < this.demoSessionCooldown) {\n cooldownMs = this.demoSessionCooldown - (now - userData.lastUsed);\n nextAvailable = `${Math.ceil(cooldownMs / (60 * 1000))} minutes`;\n blockingReason = 'session_cooldown';\n const lastUsedMinutes = Math.round((now - userData.lastUsed) / (60 * 1000));\n debugInfo = `Cooldown active: last used ${lastUsedMinutes}min ago, need ${Math.ceil(cooldownMs / (60 * 1000))}min more`;\n }\n // Cooldown after completed session\n else {\n const completedSessions = this.completedDemoSessions.get(userFingerprint) || [];\n const recentCompletedSessions = completedSessions.filter(session =>\n now - session.endTime < this.minTimeBetweenCompletedSessions\n );\n \n if (recentCompletedSessions.length > 0) {\n const lastCompletedSession = Math.max(...recentCompletedSessions.map(s => s.endTime));\n cooldownMs = this.minTimeBetweenCompletedSessions - (now - lastCompletedSession);\n nextAvailable = `${Math.ceil(cooldownMs / (60 * 1000))} minutes`;\n blockingReason = 'completion_cooldown';\n const completedMinutes = Math.round((now - lastCompletedSession) / (60 * 1000));\n debugInfo = `Completion cooldown: last session ended ${completedMinutes}min ago`;\n } else {\n debugInfo = `Ready to use: ${available} sessions available`;\n }\n }\n \n const canUseNow = available > 0 && \n cooldownMs <= 0 && \n this.activeDemoSessions.size < this.maxGlobalDemoSessions;\n \n return {\n available: available,\n used: sessionsLast24h.length,\n total: this.maxDemoSessionsPerUser,\n nextAvailable: nextAvailable,\n cooldownMinutes: Math.ceil(cooldownMs / (60 * 1000)),\n durationMinutes: Math.round(this.demoSessionMaxDuration / (60 * 1000)),\n canUseNow: canUseNow,\n blockingReason: blockingReason,\n globalActive: this.activeDemoSessions.size,\n globalLimit: this.maxGlobalDemoSessions,\n completionCooldownMinutes: Math.round(this.minTimeBetweenCompletedSessions / (60 * 1000)),\n sessionCooldownMinutes: Math.round(this.demoSessionCooldown / (60 * 1000)),\n debugInfo: debugInfo,\n lastUsed: userData.lastUsed ? new Date(userData.lastUsed).toLocaleString() : 'Never'\n };\n }\n\n\n\n // ============================================\n // ADDITIONAL VERIFICATION METHODS\n // ============================================\n\n // Verification method via LND (Lightning Network Daemon)\n async verifyPaymentLND(preimage, paymentHash) {\n try {\n if (!this.verificationConfig.nodeUrl || !this.verificationConfig.macaroon) {\n throw new Error('LND configuration missing');\n }\n\n const response = await fetch(`${this.verificationConfig.nodeUrl}/v1/invoice/${paymentHash}`, {\n method: 'GET',\n headers: {\n 'Grpc-Metadata-macaroon': this.verificationConfig.macaroon,\n 'Content-Type': 'application/json'\n },\n signal: AbortSignal.timeout(10000)\n });\n\n if (!response.ok) {\n throw new Error(`LND API request failed: ${response.status}`);\n }\n\n const invoiceData = await response.json();\n \n if (invoiceData.settled && invoiceData.r_preimage === preimage) {\n return {\n verified: true,\n amount: invoiceData.value,\n method: 'lnd',\n timestamp: Date.now()\n };\n }\n\n return { verified: false, reason: 'LND verification failed', method: 'lnd' };\n } catch (error) {\n console.error('LND payment verification failed:', error);\n return { verified: false, reason: error.message, method: 'lnd' };\n }\n }\n\n // Verification method via CLN (Core Lightning)\n async verifyPaymentCLN(preimage, paymentHash) {\n try {\n if (!this.verificationConfig.nodeUrl) {\n throw new Error('CLN configuration missing');\n }\n\n const response = await fetch(`${this.verificationConfig.nodeUrl}/v1/listinvoices`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n payment_hash: paymentHash\n }),\n signal: AbortSignal.timeout(10000)\n });\n\n if (!response.ok) {\n throw new Error(`CLN API request failed: ${response.status}`);\n }\n\n const data = await response.json();\n \n if (data.invoices && data.invoices.length > 0) {\n const invoice = data.invoices[0];\n if (invoice.status === 'paid' && invoice.payment_preimage === preimage) {\n return {\n verified: true,\n amount: invoice.amount_msat / 1000,\n method: 'cln',\n timestamp: Date.now()\n };\n }\n }\n\n return { verified: false, reason: 'CLN verification failed', method: 'cln' };\n } catch (error) {\n console.error('CLN payment verification failed:', error);\n return { verified: false, reason: error.message, method: 'cln' };\n }\n }\n\n // Verification method via BTCPay Server\n async verifyPaymentBTCPay(preimage, paymentHash) {\n try {\n if (!this.verificationConfig.apiUrl || !this.verificationConfig.apiKey) {\n throw new Error('BTCPay Server configuration missing');\n }\n\n const response = await fetch(`${this.verificationConfig.apiUrl}/api/v1/invoices/${paymentHash}`, {\n method: 'GET',\n headers: {\n 'Authorization': `Bearer ${this.verificationConfig.apiKey}`,\n 'Content-Type': 'application/json'\n },\n signal: AbortSignal.timeout(10000)\n });\n\n if (!response.ok) {\n throw new Error(`BTCPay API request failed: ${response.status}`);\n }\n\n const invoiceData = await response.json();\n \n if (invoiceData.status === 'Settled' && \n invoiceData.payment && \n invoiceData.payment.preimage === preimage) {\n return {\n verified: true,\n amount: invoiceData.amount,\n method: 'btcpay',\n timestamp: Date.now()\n };\n }\n\n return { verified: false, reason: 'BTCPay verification failed', method: 'btcpay' };\n } catch (error) {\n console.error('BTCPay payment verification failed:', error);\n return { verified: false, reason: error.message, method: 'btcpay' };\n }\n }\n\n // ============================================\n // UTILITY METHODS\n // ============================================\n\n // Creating a regular invoice (not a demo)\n createInvoice(sessionType) {\n this.validateSessionType(sessionType);\n const pricing = this.sessionPrices[sessionType];\n\n const randomBytes = crypto.getRandomValues(new Uint8Array(32));\n const timestamp = Date.now();\n const sessionEntropy = crypto.getRandomValues(new Uint8Array(16));\n \n const combinedEntropy = new Uint8Array(48);\n combinedEntropy.set(randomBytes, 0);\n combinedEntropy.set(new Uint8Array(new BigUint64Array([BigInt(timestamp)]).buffer), 32);\n combinedEntropy.set(sessionEntropy, 40);\n \n const paymentHash = Array.from(crypto.getRandomValues(new Uint8Array(32)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n\n return {\n amount: pricing.sats,\n memo: `SecureBit.chat ${sessionType} session (${pricing.hours}h) - ${timestamp}`,\n sessionType: sessionType,\n timestamp: timestamp,\n paymentHash: paymentHash,\n lightningAddress: this.staticLightningAddress,\n entropy: Array.from(sessionEntropy).map(b => b.toString(16).padStart(2, '0')).join(''),\n expiresAt: timestamp + (this.verificationConfig.invoiceExpiryMinutes * 60 * 1000)\n };\n }\n\n // Checking if a session can be activated\n canActivateSession() {\n return !this.hasActiveSession();\n }\n\n // Reset session (if there are security errors)\n resetSession() {\n if (this.sessionTimer) {\n clearInterval(this.sessionTimer);\n this.sessionTimer = null;\n }\n \n const resetSession = this.currentSession;\n \n // IMPORTANT: For demo sessions, we register forced termination\n if (resetSession && resetSession.isDemo) {\n const userFingerprint = this.generateAdvancedUserFingerprint(); \n const sessionDuration = Date.now() - resetSession.startTime;\n this.registerDemoSessionCompletion(userFingerprint, sessionDuration, resetSession.preimage);\n }\n \n this.currentSession = null;\n this.sessionStartTime = null;\n this.sessionEndTime = null;\n \n if (resetSession && resetSession.preimage) {\n this.activeDemoSessions.delete(resetSession.preimage);\n }\n \n document.dispatchEvent(new CustomEvent('session-reset', {\n detail: { \n timestamp: Date.now(),\n reason: 'security_reset'\n }\n }));\n \n setTimeout(() => {\n if (this.currentSession) {\n this.currentSession = null;\n }\n }, 100);\n }\n\n // Cleaning old preimages (every 24 hours)\n startPreimageCleanup() {\n this.preimageCleanupInterval = setInterval(() => {\n if (this.usedPreimages.size > 10000) {\n const oldSize = this.usedPreimages.size;\n this.usedPreimages.clear();\n console.log(`\uD83E\uDDF9 Cleaned ${oldSize} old preimages for memory management`);\n }\n }, 24 * 60 * 60 * 1000);\n }\n\n // Complete manager cleanup\n cleanup() {\n if (this.sessionTimer) {\n clearInterval(this.sessionTimer);\n this.sessionTimer = null;\n }\n if (this.preimageCleanupInterval) {\n clearInterval(this.preimageCleanupInterval);\n this.preimageCleanupInterval = null;\n }\n \n // IMPORTANT: We register the end of the current demo session during cleanup\n if (this.currentSession && this.currentSession.isDemo) {\n const userFingerprint = this.generateAdvancedUserFingerprint(); \n const sessionDuration = Date.now() - this.currentSession.startTime;\n this.registerDemoSessionCompletion(userFingerprint, sessionDuration, this.currentSession.preimage);\n }\n \n this.currentSession = null;\n this.sessionStartTime = null;\n this.sessionEndTime = null;\n \n if (this.currentSession && this.currentSession.preimage) {\n this.activeDemoSessions.delete(this.currentSession.preimage);\n }\n \n document.dispatchEvent(new CustomEvent('session-cleanup', {\n detail: { \n timestamp: Date.now(),\n reason: 'complete_cleanup'\n }\n }));\n \n setTimeout(() => {\n if (this.currentSession) {\n this.currentSession = null;\n }\n }, 100);\n }\n\n getUsageStats() {\n const stats = {\n totalDemoUsers: this.demoSessions.size,\n usedPreimages: this.usedPreimages.size,\n activeDemoSessions: this.activeDemoSessions.size,\n globalDemoLimit: this.maxGlobalDemoSessions,\n currentSession: this.currentSession ? {\n type: this.currentSession.type,\n timeLeft: this.getTimeLeft(),\n isDemo: this.currentSession.isDemo\n } : null,\n config: {\n maxDemoSessions: this.maxDemoSessionsPerUser,\n demoCooldown: this.demoSessionCooldown / (60 * 1000),\n demoMaxDuration: this.demoSessionMaxDuration / (60 * 1000),\n completionCooldown: this.minTimeBetweenCompletedSessions / (60 * 1000)\n }\n };\n \n return stats;\n }\n\n getVerifiedDemoSession() {\n const userFingerprint = this.generateAdvancedUserFingerprint(); \n const userData = this.demoSessions.get(userFingerprint);\n \n console.log('\uD83D\uDD0D Searching for verified demo session:', {\n userFingerprint: userFingerprint.substring(0, 12),\n hasUserData: !!userData,\n sessionsCount: userData?.sessions?.length || 0,\n currentSession: this.currentSession ? {\n type: this.currentSession.type,\n timeLeft: this.getTimeLeft(),\n isActive: this.hasActiveSession()\n } : null\n });\n \n if (!userData || !userData.sessions || userData.sessions.length === 0) {\n console.log('\u274C No user data or sessions found');\n return null;\n }\n\n const lastSession = userData.sessions[userData.sessions.length - 1];\n if (!lastSession || !lastSession.preimage) {\n console.log('\u274C Last session is invalid:', lastSession);\n return null;\n }\n \n if (!this.isDemoPreimage(lastSession.preimage)) {\n console.log('\u274C Last session preimage is not demo format:', lastSession.preimage.substring(0, 16) + '...');\n return null;\n }\n \n if (this.activeDemoSessions.has(lastSession.preimage)) {\n console.log('\u26A0\uFE0F Demo session is already in activeDemoSessions, checking if truly active...');\n if (this.hasActiveSession()) {\n console.log('\u274C Demo session is truly active, cannot reactivate');\n return null;\n } else {\n console.log('\uD83D\uDD04 Demo session was interrupted, can be reactivated');\n }\n }\n \n const verifiedSession = {\n preimage: lastSession.preimage,\n paymentHash: lastSession.paymentHash || 'demo_' + Date.now(),\n sessionType: 'demo',\n timestamp: lastSession.timestamp\n };\n \n console.log('\u2705 Found verified demo session:', {\n preimage: verifiedSession.preimage.substring(0, 16) + '...',\n timestamp: new Date(verifiedSession.timestamp).toLocaleTimeString(),\n canActivate: !this.hasActiveSession()\n });\n \n return verifiedSession;\n }\n\n checkDemoSessionLimits(userFingerprint) {\n const userData = this.demoSessions.get(userFingerprint);\n const now = Date.now();\n \n console.log(`\uD83D\uDD0D Checking demo limits for user ${userFingerprint.substring(0, 12)}...`);\n \n // CHECK 1: Global limit of simultaneous demo sessions\n if (this.activeDemoSessions.size >= this.maxGlobalDemoSessions) {\n console.log(`\u274C Global demo limit reached: ${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}`);\n return {\n allowed: false,\n reason: 'global_limit_exceeded',\n message: `Too many demo sessions active globally (${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}). Please try again later.`,\n remaining: 0,\n debugInfo: `Global sessions: ${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}`\n };\n }\n \n if (!userData) {\n // First demo session for this user\n console.log(`\u2705 First demo session for user ${userFingerprint.substring(0, 12)}`);\n return { \n allowed: true, \n reason: 'first_demo_session',\n remaining: this.maxDemoSessionsPerUser,\n debugInfo: 'First time user'\n };\n }\n \n // CHECK 2: Limit sessions per 24 hours (STRICT check)\n const sessionsLast24h = userData.sessions.filter(session => \n now - session.timestamp < this.demoCooldownPeriod\n );\n \n console.log(`\uD83D\uDCCA Sessions in last 24h for user ${userFingerprint.substring(0, 12)}: ${sessionsLast24h.length}/${this.maxDemoSessionsPerUser}`);\n \n if (sessionsLast24h.length >= this.maxDemoSessionsPerUser) {\n const oldestSession = Math.min(...sessionsLast24h.map(s => s.timestamp));\n const timeUntilNext = this.demoCooldownPeriod - (now - oldestSession);\n \n console.log(`\u274C Daily demo limit exceeded for user ${userFingerprint.substring(0, 12)}`);\n return { \n allowed: false, \n reason: 'daily_limit_exceeded',\n timeUntilNext: timeUntilNext,\n message: `Daily demo limit reached (${this.maxDemoSessionsPerUser}/day). Next session available in ${Math.ceil(timeUntilNext / (60 * 1000))} minutes.`,\n remaining: 0,\n debugInfo: `Used ${sessionsLast24h.length}/${this.maxDemoSessionsPerUser} today`\n };\n }\n \n // CHECK 3: Cooldown between sessions (FIXED LOGIC)\n if (userData.lastUsed && (now - userData.lastUsed) < this.demoSessionCooldown) {\n const timeUntilNext = this.demoSessionCooldown - (now - userData.lastUsed);\n const minutesLeft = Math.ceil(timeUntilNext / (60 * 1000));\n \n console.log(`\u23F0 Cooldown active for user ${userFingerprint.substring(0, 12)}: ${minutesLeft} minutes`);\n \n return { \n allowed: false, \n reason: 'session_cooldown',\n timeUntilNext: timeUntilNext,\n message: `Please wait ${minutesLeft} minutes between demo sessions. This prevents abuse and ensures fair access for all users.`,\n remaining: this.maxDemoSessionsPerUser - sessionsLast24h.length,\n debugInfo: `Cooldown: ${minutesLeft}min left, last used: ${Math.round((now - userData.lastUsed) / (60 * 1000))}min ago`\n };\n }\n \n // CHECK 4: NEW - Check for completed sessions\n const completedSessions = this.completedDemoSessions.get(userFingerprint) || [];\n const recentCompletedSessions = completedSessions.filter(session =>\n now - session.endTime < this.minTimeBetweenCompletedSessions\n );\n \n if (recentCompletedSessions.length > 0) {\n const lastCompletedSession = Math.max(...recentCompletedSessions.map(s => s.endTime));\n const timeUntilNext = this.minTimeBetweenCompletedSessions - (now - lastCompletedSession);\n \n console.log(`\u23F0 Recent session completed, waiting period active for user ${userFingerprint.substring(0, 12)}`);\n return {\n allowed: false,\n reason: 'recent_session_completed',\n timeUntilNext: timeUntilNext,\n message: `Please wait ${Math.ceil(timeUntilNext / (60 * 1000))} minutes after your last session before starting a new one.`,\n remaining: this.maxDemoSessionsPerUser - sessionsLast24h.length,\n debugInfo: `Last session ended ${Math.round((now - lastCompletedSession) / (60 * 1000))}min ago`\n };\n }\n \n console.log(`\u2705 Demo session approved for user ${userFingerprint.substring(0, 12)}`);\n return { \n allowed: true, \n reason: 'within_limits',\n remaining: this.maxDemoSessionsPerUser - sessionsLast24h.length,\n debugInfo: `Available: ${this.maxDemoSessionsPerUser - sessionsLast24h.length}/${this.maxDemoSessionsPerUser}`\n };\n }\n\n createDemoSessionForActivation() {\n const userFingerprint = this.generateAdvancedUserFingerprint(); // \u0418\u0421\u041F\u0420\u0410\u0412\u041B\u0415\u041D\u041E!\n \n if (this.activeDemoSessions.size >= this.maxGlobalDemoSessions) {\n return {\n success: false,\n reason: `Too many demo sessions active globally (${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}). Please try again later.`,\n blockingReason: 'global_limit'\n };\n }\n \n try {\n const demoPreimage = this.generateSecureDemoPreimage();\n const demoPaymentHash = 'demo_' + Array.from(crypto.getRandomValues(new Uint8Array(16)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n \n console.log('\uD83D\uDD04 Created demo session for activation:', {\n preimage: demoPreimage.substring(0, 16) + '...',\n paymentHash: demoPaymentHash.substring(0, 16) + '...'\n });\n \n return {\n success: true,\n sessionType: 'demo',\n preimage: demoPreimage,\n paymentHash: demoPaymentHash,\n duration: this.sessionPrices.demo.hours,\n durationMinutes: Math.round(this.demoSessionMaxDuration / (60 * 1000)),\n warning: `Demo session - limited to ${Math.round(this.demoSessionMaxDuration / (60 * 1000))} minutes`,\n globalActive: this.activeDemoSessions.size + 1,\n globalLimit: this.maxGlobalDemoSessions\n };\n } catch (error) {\n console.error('Failed to create demo session for activation:', error);\n return {\n success: false,\n reason: 'Failed to generate demo session for activation. Please try again.'\n };\n }\n }\n\n async verifyDemoSessionForActivation(preimage, paymentHash) {\n console.log('\uD83C\uDFAE Verifying demo session for activation (bypassing limits)...');\n \n try {\n if (!preimage || !paymentHash) {\n throw new Error('Missing preimage or payment hash');\n }\n \n if (typeof preimage !== 'string' || typeof paymentHash !== 'string') {\n throw new Error('Preimage and payment hash must be strings');\n }\n \n if (!this.isDemoPreimage(preimage)) {\n throw new Error('Invalid demo preimage format');\n }\n \n const entropy = this.calculateEntropy(preimage);\n if (entropy < 3.5) {\n throw new Error(`Demo preimage has insufficient entropy: ${entropy.toFixed(2)}`);\n }\n \n if (this.activeDemoSessions.has(preimage)) {\n throw new Error('Demo session with this preimage is already active');\n }\n \n console.log('\u2705 Demo session verified for activation successfully');\n return { \n verified: true, \n method: 'demo-activation',\n sessionType: 'demo',\n isDemo: true,\n warning: 'Demo session - limited duration (6 minutes)'\n };\n \n } catch (error) {\n console.error('\u274C Demo session verification for activation failed:', error);\n return { \n verified: false, \n reason: error.message,\n stage: 'demo-activation'\n };\n }\n }\n}\n\nexport { PayPerSessionManager };", "// SessionTimer Component - v4.02.985 - ECDH + DTLS + SAS\nconst SessionTimer = ({ timeLeft, sessionType, sessionManager, onDisconnect }) => {\n const [currentTime, setCurrentTime] = React.useState(timeLeft || 0);\n const [showExpiredMessage, setShowExpiredMessage] = React.useState(false);\n const [initialized, setInitialized] = React.useState(false);\n const [connectionBroken, setConnectionBroken] = React.useState(false);\n \n\n const [loggedHidden, setLoggedHidden] = React.useState(false);\n\n React.useEffect(() => {\n if (connectionBroken) {\n if (!loggedHidden) {\n console.log('\u23F1\uFE0F SessionTimer initialization skipped - connection broken');\n setLoggedHidden(true);\n }\n return;\n }\n \n let initialTime = 0;\n \n if (sessionManager?.hasActiveSession()) {\n initialTime = sessionManager.getTimeLeft();\n } else if (timeLeft && timeLeft > 0) {\n initialTime = timeLeft;\n }\n\n if (initialTime <= 0) {\n setCurrentTime(0);\n setInitialized(false);\n setLoggedHidden(true);\n return;\n }\n\n if (connectionBroken) {\n setCurrentTime(0);\n setInitialized(false);\n setLoggedHidden(true);\n return;\n }\n setCurrentTime(initialTime);\n setInitialized(true);\n setLoggedHidden(false); \n }, [sessionManager, connectionBroken]);\n\n React.useEffect(() => {\n if (connectionBroken) {\n if (!loggedHidden) {\n setLoggedHidden(true);\n }\n return;\n }\n \n if (timeLeft && timeLeft > 0) {\n setCurrentTime(timeLeft);\n }\n setLoggedHidden(false);\n }, [timeLeft, connectionBroken]);\n\n React.useEffect(() => {\n if (!initialized) {\n return;\n }\n\n if (connectionBroken) {\n if (!loggedHidden) {\n setLoggedHidden(true);\n }\n return;\n }\n\n if (!currentTime || currentTime <= 0 || !sessionManager) {\n return;\n }\n\n const interval = setInterval(() => {\n if (connectionBroken) {\n setCurrentTime(0);\n clearInterval(interval);\n return;\n }\n \n if (sessionManager?.hasActiveSession()) {\n const newTime = sessionManager.getTimeLeft();\n setCurrentTime(newTime);\n\n if (window.DEBUG_MODE && Math.floor(Date.now() / 30000) !== Math.floor((Date.now() - 1000) / 30000)) {\n console.log('\u23F1\uFE0F Timer tick:', Math.floor(newTime / 1000) + 's');\n }\n\n if (newTime <= 0) {\n setShowExpiredMessage(true);\n setTimeout(() => setShowExpiredMessage(false), 5000);\n clearInterval(interval);\n }\n } else {\n setCurrentTime(0);\n clearInterval(interval);\n }\n }, 1000);\n\n return () => {\n clearInterval(interval);\n };\n }, [initialized, currentTime, sessionManager, connectionBroken]);\n\n React.useEffect(() => {\n const handleSessionTimerUpdate = (event) => {\n if (connectionBroken) {\n return;\n }\n \n if (event.detail.timeLeft && event.detail.timeLeft > 0) {\n setCurrentTime(event.detail.timeLeft);\n }\n };\n\n const handleForceHeaderUpdate = (event) => {\n if (connectionBroken) {\n return;\n }\n \n if (sessionManager && sessionManager.hasActiveSession()) {\n const newTime = sessionManager.getTimeLeft();\n setCurrentTime(newTime);\n } else {\n setCurrentTime(event.detail.timeLeft);\n }\n };\n\n const handlePeerDisconnect = (event) => {\n setConnectionBroken(true);\n setCurrentTime(0);\n setShowExpiredMessage(false);\n setLoggedHidden(false);\n };\n\n const handleNewConnection = (event) => {\n setConnectionBroken(false);\n setLoggedHidden(false); \n };\n\n const handleConnectionCleaned = (event) => {\n setConnectionBroken(true);\n setCurrentTime(0);\n setShowExpiredMessage(false);\n setInitialized(false);\n setLoggedHidden(false);\n };\n\n const handleSessionReset = (event) => {\n setConnectionBroken(true);\n setCurrentTime(0);\n setShowExpiredMessage(false);\n setInitialized(false);\n setLoggedHidden(false);\n };\n\n const handleSessionCleanup = (event) => {\n setConnectionBroken(true);\n setCurrentTime(0);\n setShowExpiredMessage(false);\n setInitialized(false);\n setLoggedHidden(false);\n };\n\n const handleDisconnected = (event) => {\n setConnectionBroken(true);\n setCurrentTime(0);\n setShowExpiredMessage(false);\n setInitialized(false);\n setLoggedHidden(false);\n };\n\n document.addEventListener('session-timer-update', handleSessionTimerUpdate);\n document.addEventListener('force-header-update', handleForceHeaderUpdate);\n document.addEventListener('peer-disconnect', handlePeerDisconnect);\n document.addEventListener('new-connection', handleNewConnection);\n document.addEventListener('connection-cleaned', handleConnectionCleaned);\n document.addEventListener('session-reset', handleSessionReset);\n document.addEventListener('session-cleanup', handleSessionCleanup);\n document.addEventListener('disconnected', handleDisconnected);\n\n return () => {\n document.removeEventListener('session-timer-update', handleSessionTimerUpdate);\n document.removeEventListener('force-header-update', handleForceHeaderUpdate);\n document.removeEventListener('peer-disconnect', handlePeerDisconnect);\n document.removeEventListener('new-connection', handleNewConnection);\n document.removeEventListener('connection-cleaned', handleConnectionCleaned);\n document.removeEventListener('session-reset', handleSessionReset);\n document.removeEventListener('session-cleanup', handleSessionCleanup);\n document.removeEventListener('disconnected', handleDisconnected);\n };\n }, [sessionManager]);\n\n if (showExpiredMessage) {\n return React.createElement('div', {\n className: 'session-timer expired flex items-center space-x-2 px-3 py-1.5 rounded-lg animate-pulse',\n style: { background: 'linear-gradient(135deg, rgba(239, 68, 68, 0.2) 0%, rgba(220, 38, 38, 0.2) 100%)' }\n }, [\n React.createElement('i', {\n key: 'icon',\n className: 'fas fa-exclamation-triangle text-red-400'\n }),\n React.createElement('span', {\n key: 'message',\n className: 'text-red-400 text-sm font-medium'\n }, 'Session Expired!')\n ]);\n }\n\n if (!sessionManager) {\n if (!loggedHidden) {\n console.log('\u23F1\uFE0F SessionTimer hidden - no sessionManager');\n setLoggedHidden(true);\n }\n return null;\n }\n\n if (connectionBroken) {\n if (!loggedHidden) {\n console.log('\u23F1\uFE0F SessionTimer hidden - connection broken');\n setLoggedHidden(true);\n }\n return null;\n }\n\n if (!currentTime || currentTime <= 0) {\n if (!loggedHidden) {\n console.log('\u23F1\uFE0F SessionTimer hidden - no time left, currentTime:', currentTime);\n setLoggedHidden(true);\n }\n return null;\n }\n\n if (loggedHidden) {\n setLoggedHidden(false);\n }\n\n const totalMinutes = Math.floor(currentTime / (60 * 1000));\n const totalSeconds = Math.floor(currentTime / 1000);\n \n const isDemo = sessionType === 'demo';\n const isWarning = isDemo ? totalMinutes <= 2 : totalMinutes <= 10;\n const isCritical = isDemo ? totalSeconds <= 60 : totalMinutes <= 5;\n\n const formatTime = (ms) => {\n const hours = Math.floor(ms / (60 * 60 * 1000));\n const minutes = Math.floor((ms % (60 * 60 * 1000)) / (60 * 1000));\n const seconds = Math.floor((ms % (60 * 1000)) / 1000);\n\n if (hours > 0) {\n return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;\n } else {\n return `${minutes}:${seconds.toString().padStart(2, '0')}`;\n }\n };\n\n const getTimerStyle = () => {\n const totalDuration = sessionType === 'demo' ? 6 * 60 * 1000 : 60 * 60 * 1000;\n const timeProgress = (totalDuration - currentTime) / totalDuration;\n \n let backgroundColor, textColor, iconColor, iconClass, shouldPulse;\n \n if (timeProgress <= 0.33) {\n backgroundColor = 'linear-gradient(135deg, rgba(34, 197, 94, 0.15) 0%, rgba(22, 163, 74, 0.15) 100%)';\n textColor = 'text-green-400';\n iconColor = 'text-green-400';\n iconClass = 'fas fa-clock';\n shouldPulse = false;\n } else if (timeProgress <= 0.66) {\n backgroundColor = 'linear-gradient(135deg, rgba(234, 179, 8, 0.15) 0%, rgba(202, 138, 4, 0.15) 100%)';\n textColor = 'text-yellow-400';\n iconColor = 'text-yellow-400';\n iconClass = 'fas fa-clock';\n shouldPulse = false;\n } else {\n backgroundColor = 'linear-gradient(135deg, rgba(239, 68, 68, 0.15) 0%, rgba(220, 38, 38, 0.15) 100%)';\n textColor = 'text-red-400';\n iconColor = 'text-red-400';\n iconClass = 'fas fa-exclamation-triangle';\n shouldPulse = true;\n }\n \n return { backgroundColor, textColor, iconColor, iconClass, shouldPulse };\n };\n\n const timerStyle = getTimerStyle();\n \n const handleTimerClick = () => {\n if (onDisconnect && typeof onDisconnect === 'function') {\n onDisconnect();\n }\n };\n\n return React.createElement('div', {\n className: `session-timer flex items-center space-x-2 px-3 py-1.5 rounded-lg transition-all duration-500 cursor-pointer hover:opacity-80 ${\n isDemo ? 'demo-session' : ''\n } ${timerStyle.shouldPulse ? 'animate-pulse' : ''}`,\n style: { background: timerStyle.backgroundColor },\n onClick: handleTimerClick,\n title: 'Click to disconnect and clear session'\n }, [\n React.createElement('i', {\n key: 'icon',\n className: `${timerStyle.iconClass} ${timerStyle.iconColor}`\n }),\n React.createElement('span', {\n key: 'time',\n className: `text-sm font-mono font-semibold ${timerStyle.textColor}`\n }, formatTime(currentTime)),\n React.createElement('div', {\n key: 'progress',\n className: 'ml-2 w-16 h-1 bg-gray-700 rounded-full overflow-hidden'\n }, [\n React.createElement('div', {\n key: 'progress-bar',\n className: `${timerStyle.textColor.replace('text-', 'bg-')} h-full rounded-full transition-all duration-500`,\n style: { \n width: `${Math.max(0, Math.min(100, (currentTime / (sessionType === 'demo' ? 6 * 60 * 1000 : 60 * 60 * 1000)) * 100))}%`\n }\n })\n ])\n ]);\n};\n\nwindow.SessionTimer = SessionTimer;\n\nwindow.updateSessionTimer = (newTimeLeft, newSessionType) => {\n document.dispatchEvent(new CustomEvent('session-timer-update', {\n detail: { timeLeft: newTimeLeft, sessionType: newSessionType }\n }));\n};\n\n", "const EnhancedMinimalHeader = ({ \n status, \n fingerprint, \n verificationCode, \n onDisconnect, \n isConnected, \n securityLevel, \n sessionManager, \n sessionTimeLeft,\n webrtcManager \n}) => {\n const [currentTimeLeft, setCurrentTimeLeft] = React.useState(sessionTimeLeft || 0);\n const [hasActiveSession, setHasActiveSession] = React.useState(false);\n const [sessionType, setSessionType] = React.useState('unknown');\n const [realSecurityLevel, setRealSecurityLevel] = React.useState(null);\n const [lastSecurityUpdate, setLastSecurityUpdate] = React.useState(0);\n\n // ============================================\n // FIXED SECURITY UPDATE LOGIC\n // ============================================\n \n React.useEffect(() => {\n let isUpdating = false; \n let lastUpdateAttempt = 0; \n \n const updateRealSecurityStatus = async () => {\n const now = Date.now();\n if (now - lastUpdateAttempt < 10000) { \n return;\n }\n\n if (isUpdating) {\n return;\n }\n \n isUpdating = true;\n lastUpdateAttempt = now;\n \n try {\n if (!webrtcManager || !isConnected) {\n return;\n }\n \n const activeWebrtcManager = webrtcManager;\n \n let realSecurityData = null;\n \n if (typeof activeWebrtcManager.getRealSecurityLevel === 'function') {\n realSecurityData = await activeWebrtcManager.getRealSecurityLevel();\n } else if (typeof activeWebrtcManager.calculateAndReportSecurityLevel === 'function') {\n realSecurityData = await activeWebrtcManager.calculateAndReportSecurityLevel();\n } else {\n realSecurityData = await window.EnhancedSecureCryptoUtils.calculateSecurityLevel(activeWebrtcManager);\n }\n \n if (window.DEBUG_MODE) {\n console.log('\uD83D\uDD10 REAL security level calculated:', {\n level: realSecurityData?.level,\n score: realSecurityData?.score,\n passedChecks: realSecurityData?.passedChecks,\n totalChecks: realSecurityData?.totalChecks,\n isRealData: realSecurityData?.isRealData,\n sessionType: realSecurityData?.sessionType,\n maxPossibleScore: realSecurityData?.maxPossibleScore,\n verificationResults: realSecurityData?.verificationResults ? Object.keys(realSecurityData.verificationResults) : []\n });\n }\n \n if (realSecurityData && realSecurityData.isRealData !== false) {\n const currentScore = realSecurityLevel?.score || 0;\n const newScore = realSecurityData.score || 0;\n\n if (currentScore !== newScore || !realSecurityLevel) {\n setRealSecurityLevel(realSecurityData);\n setLastSecurityUpdate(now);\n \n if (window.DEBUG_MODE) {\n console.log('\u2705 Security level updated in header component:', {\n oldScore: currentScore,\n newScore: newScore,\n sessionType: realSecurityData.sessionType\n });\n }\n } else if (window.DEBUG_MODE) {\n console.log('\u2139\uFE0F Security level unchanged, skipping update');\n }\n } else {\n console.warn('\u26A0\uFE0F Security calculation returned invalid data');\n }\n \n } catch (error) {\n console.error('\u274C Error in real security calculation:', error);\n } finally {\n isUpdating = false;\n }\n };\n\n if (isConnected) {\n updateRealSecurityStatus();\n \n if (!realSecurityLevel || realSecurityLevel.score < 50) {\n const retryInterval = setInterval(() => {\n if (!realSecurityLevel || realSecurityLevel.score < 50) {\n updateRealSecurityStatus();\n } else {\n clearInterval(retryInterval);\n }\n }, 5000); \n \n setTimeout(() => clearInterval(retryInterval), 30000);\n }\n }\n\n const interval = setInterval(updateRealSecurityStatus, 30000);\n \n return () => clearInterval(interval);\n }, [webrtcManager, isConnected, lastSecurityUpdate, realSecurityLevel]);\n\n // ============================================\n // FIXED EVENT HANDLERS\n // ============================================\n\n React.useEffect(() => {\n const handleSecurityUpdate = (event) => {\n if (window.DEBUG_MODE) {\n console.log('\uD83D\uDD12 Security level update event received:', event.detail);\n }\n\n setTimeout(() => {\n setLastSecurityUpdate(0);\n }, 100);\n };\n\n const handleRealSecurityCalculated = (event) => {\n if (window.DEBUG_MODE) {\n console.log('\uD83D\uDD10 Real security calculated event:', event.detail);\n }\n \n if (event.detail && event.detail.securityData) {\n setRealSecurityLevel(event.detail.securityData);\n setLastSecurityUpdate(Date.now());\n }\n };\n\n document.addEventListener('security-level-updated', handleSecurityUpdate);\n document.addEventListener('real-security-calculated', handleRealSecurityCalculated);\n \n window.forceHeaderSecurityUpdate = (webrtcManager) => {\n if (window.DEBUG_MODE) {\n console.log('\uD83D\uDD04 Force header security update called');\n }\n \n if (webrtcManager && window.EnhancedSecureCryptoUtils) {\n window.EnhancedSecureCryptoUtils.calculateSecurityLevel(webrtcManager)\n .then(securityData => {\n if (securityData && securityData.isRealData !== false) {\n setRealSecurityLevel(securityData);\n setLastSecurityUpdate(Date.now());\n console.log('\u2705 Header security level force-updated');\n }\n })\n .catch(error => {\n console.error('\u274C Force update failed:', error);\n });\n } else {\n setLastSecurityUpdate(0); \n }\n };\n\n return () => {\n document.removeEventListener('security-level-updated', handleSecurityUpdate);\n document.removeEventListener('real-security-calculated', handleRealSecurityCalculated);\n };\n }, []);\n\n // ============================================\n // REST of the component logic\n // ============================================\n\n React.useEffect(() => {\n const updateSessionInfo = () => {\n if (sessionManager) {\n const isActive = sessionManager.hasActiveSession();\n const timeLeft = sessionManager.getTimeLeft();\n const currentSession = sessionManager.currentSession;\n \n setHasActiveSession(isActive);\n setCurrentTimeLeft(timeLeft);\n setSessionType(currentSession?.type || 'unknown');\n }\n };\n\n updateSessionInfo();\n const interval = setInterval(updateSessionInfo, 1000);\n return () => clearInterval(interval);\n }, [sessionManager]);\n\n React.useEffect(() => {\n if (sessionManager?.hasActiveSession()) {\n setCurrentTimeLeft(sessionManager.getTimeLeft());\n setHasActiveSession(true);\n } else {\n setHasActiveSession(false);\n setRealSecurityLevel(null);\n setLastSecurityUpdate(0);\n setSessionType('unknown');\n }\n }, [sessionManager, sessionTimeLeft]);\n\n React.useEffect(() => {\n const handleForceUpdate = (event) => {\n if (sessionManager) {\n const isActive = sessionManager.hasActiveSession();\n const timeLeft = sessionManager.getTimeLeft();\n const currentSession = sessionManager.currentSession;\n \n setHasActiveSession(isActive);\n setCurrentTimeLeft(timeLeft);\n setSessionType(currentSession?.type || 'unknown');\n }\n };\n\n // Connection cleanup handler (use existing event from module)\n const handleConnectionCleaned = () => {\n if (window.DEBUG_MODE) {\n console.log('\uD83E\uDDF9 Connection cleaned - clearing security data in header');\n }\n\n setRealSecurityLevel(null);\n setLastSecurityUpdate(0);\n\n setHasActiveSession(false);\n setCurrentTimeLeft(0);\n setSessionType('unknown');\n };\n\n const handlePeerDisconnect = () => {\n if (window.DEBUG_MODE) {\n console.log('\uD83D\uDC4B Peer disconnect detected - clearing security data in header');\n }\n\n setRealSecurityLevel(null);\n setLastSecurityUpdate(0);\n };\n\n document.addEventListener('force-header-update', handleForceUpdate);\n document.addEventListener('peer-disconnect', handlePeerDisconnect);\n document.addEventListener('connection-cleaned', handleConnectionCleaned);\n \n return () => {\n document.removeEventListener('force-header-update', handleForceUpdate);\n document.removeEventListener('peer-disconnect', handlePeerDisconnect);\n document.removeEventListener('connection-cleaned', handleConnectionCleaned);\n };\n }, [sessionManager]);\n\n // ============================================\n // SECURITY INDICATOR CLICK HANDLER\n // ============================================\n\n const handleSecurityClick = (event) => {\n // Check if it's a right-click or Ctrl+click to disconnect\n if (event && (event.button === 2 || event.ctrlKey || event.metaKey)) {\n if (onDisconnect && typeof onDisconnect === 'function') {\n onDisconnect();\n return;\n }\n }\n\n if (!realSecurityLevel) {\n alert('Security verification in progress...\\nPlease wait for real-time cryptographic verification to complete.');\n return;\n }\n\n // Detailed information about the REAL security check\n let message = `\uD83D\uDD12 REAL-TIME SECURITY VERIFICATION\\n\\n`;\n message += `Security Level: ${realSecurityLevel.level} (${realSecurityLevel.score}%)\\n`;\n message += `Session Type: ${realSecurityLevel.sessionType || 'demo'}\\n`;\n message += `Verification Time: ${new Date(realSecurityLevel.timestamp).toLocaleTimeString()}\\n`;\n message += `Data Source: ${realSecurityLevel.isRealData ? 'Real Cryptographic Tests' : 'Simulated Data'}\\n\\n`;\n \n if (realSecurityLevel.verificationResults) {\n message += 'DETAILED CRYPTOGRAPHIC TESTS:\\n';\n message += '=' + '='.repeat(40) + '\\n';\n \n const passedTests = Object.entries(realSecurityLevel.verificationResults).filter(([key, result]) => result.passed);\n const failedTests = Object.entries(realSecurityLevel.verificationResults).filter(([key, result]) => !result.passed);\n \n if (passedTests.length > 0) {\n message += '\u2705 PASSED TESTS:\\n';\n passedTests.forEach(([key, result]) => {\n const testName = key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase());\n message += ` ${testName}: ${result.details}\\n`;\n });\n message += '\\n';\n }\n \n if (failedTests.length > 0) {\n message += '\u274C UNAVAILABLE/Failed TESTS:\\n';\n failedTests.forEach(([key, result]) => {\n const testName = key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase());\n message += ` ${testName}: ${result.details}\\n`;\n });\n message += '\\n';\n }\n \n message += `SUMMARY:\\n`;\n message += `Passed: ${realSecurityLevel.passedChecks}/${realSecurityLevel.totalChecks} tests\\n`;\n }\n \n // Add information about what is available in other sessions\n message += `\\n\uD83D\uDCCB WHAT'S AVAILABLE IN OTHER SESSIONS:\\n`;\n message += '=' + '='.repeat(40) + '\\n';\n \n if (realSecurityLevel.sessionType === 'demo') {\n message += `\uD83D\uDD12 BASIC SESSION (5,000 sat - $2.00):\\n`;\n message += ` \u2022 ECDSA Digital Signatures\\n`;\n message += ` \u2022 Metadata Protection\\n`;\n message += ` \u2022 Perfect Forward Secrecy\\n`;\n message += ` \u2022 Nested Encryption\\n`;\n message += ` \u2022 Packet Padding\\n\\n`;\n \n message += `\uD83D\uDE80 PREMIUM SESSION (20,000 sat - $8.00):\\n`;\n message += ` \u2022 All Basic + Enhanced features\\n`;\n message += ` \u2022 Traffic Obfuscation\\n`;\n message += ` \u2022 Fake Traffic Generation\\n`;\n message += ` \u2022 Decoy Channels\\n`;\n message += ` \u2022 Anti-Fingerprinting\\n`;\n message += ` \u2022 Message Chunking\\n`;\n message += ` \u2022 Advanced Replay Protection\\n`;\n } else if (realSecurityLevel.sessionType === 'basic') {\n message += `\uD83D\uDE80 PREMIUM SESSION (20,000 sat - $8.00):\\n`;\n message += ` \u2022 Traffic Obfuscation\\n`;\n message += ` \u2022 Fake Traffic Generation\\n`;\n message += ` \u2022 Decoy Channels\\n`;\n message += ` \u2022 Anti-Fingerprinting\\n`;\n message += ` \u2022 Message Chunking\\n`;\n message += ` \u2022 Advanced Replay Protection\\n`;\n }\n \n message += `\\n${realSecurityLevel.details || 'Real cryptographic verification completed'}`;\n \n if (realSecurityLevel.isRealData) {\n message += '\\n\\n\u2705 This is REAL-TIME verification using actual cryptographic functions.';\n } else {\n message += '\\n\\n\u26A0\uFE0F Warning: This data may be simulated. Connection may not be fully established.';\n }\n \n alert(message);\n };\n\n // ============================================\n // DISPLAY UTILITIES\n // ============================================\n\n const getStatusConfig = () => {\n switch (status) {\n case 'connected':\n return {\n text: 'Connected',\n className: 'status-connected',\n badgeClass: 'bg-green-500/10 text-green-400 border-green-500/20'\n };\n case 'verifying':\n return {\n text: 'Verifying...',\n className: 'status-verifying',\n badgeClass: 'bg-purple-500/10 text-purple-400 border-purple-500/20'\n };\n case 'connecting':\n return {\n text: 'Connecting...',\n className: 'status-connecting',\n badgeClass: 'bg-blue-500/10 text-blue-400 border-blue-500/20'\n };\n case 'retrying':\n return {\n text: 'Retrying...',\n className: 'status-connecting',\n badgeClass: 'bg-yellow-500/10 text-yellow-400 border-yellow-500/20'\n };\n case 'failed':\n return {\n text: 'Error',\n className: 'status-failed',\n badgeClass: 'bg-red-500/10 text-red-400 border-red-500/20'\n };\n case 'reconnecting':\n return {\n text: 'Reconnecting...',\n className: 'status-connecting',\n badgeClass: 'bg-yellow-500/10 text-yellow-400 border-yellow-500/20'\n };\n case 'peer_disconnected':\n return {\n text: 'Peer disconnected',\n className: 'status-failed',\n badgeClass: 'bg-orange-500/10 text-orange-400 border-orange-500/20'\n };\n default:\n return {\n text: 'Not connected',\n className: 'status-disconnected',\n badgeClass: 'bg-gray-500/10 text-gray-400 border-gray-500/20'\n };\n }\n };\n\n const config = getStatusConfig();\n const displaySecurityLevel = realSecurityLevel || securityLevel;\n \n const shouldShowTimer = hasActiveSession && currentTimeLeft > 0 && window.SessionTimer;\n\n // ============================================\n // DATA RELIABILITY INDICATOR\n // ============================================\n\n const getSecurityIndicatorDetails = () => {\n if (!displaySecurityLevel) {\n return {\n tooltip: 'Security verification in progress...',\n isVerified: false,\n dataSource: 'loading'\n };\n }\n \n const isRealData = displaySecurityLevel.isRealData !== false;\n const baseTooltip = `${displaySecurityLevel.level} (${displaySecurityLevel.score}%)`;\n \n if (isRealData) {\n return {\n tooltip: `${baseTooltip} - Real-time verification \u2705\\nRight-click or Ctrl+click to disconnect`,\n isVerified: true,\n dataSource: 'real'\n };\n } else {\n return {\n tooltip: `${baseTooltip} - Estimated (connection establishing...)\\nRight-click or Ctrl+click to disconnect`,\n isVerified: false,\n dataSource: 'estimated'\n };\n }\n };\n\n const securityDetails = getSecurityIndicatorDetails();\n\n // ============================================\n // ADDING global methods for debugging\n // ============================================\n\n React.useEffect(() => {\n window.debugHeaderSecurity = () => {\n console.log('\uD83D\uDD0D Header Security Debug:', {\n realSecurityLevel,\n lastSecurityUpdate,\n isConnected,\n webrtcManagerProp: !!webrtcManager,\n windowWebrtcManager: !!window.webrtcManager,\n cryptoUtils: !!window.EnhancedSecureCryptoUtils,\n displaySecurityLevel: displaySecurityLevel,\n securityDetails: securityDetails\n });\n };\n \n return () => {\n delete window.debugHeaderSecurity;\n };\n }, [realSecurityLevel, lastSecurityUpdate, isConnected, webrtcManager, displaySecurityLevel, securityDetails]);\n\n // ============================================\n // RENDER\n // ============================================\n\n return React.createElement('header', {\n className: 'header-minimal sticky top-0 z-50'\n }, [\n React.createElement('div', {\n key: 'container',\n className: 'max-w-7xl mx-auto px-4 sm:px-6 lg:px-8'\n }, [\n React.createElement('div', {\n key: 'content',\n className: 'flex items-center justify-between h-16'\n }, [\n // Logo and Title\n React.createElement('div', {\n key: 'logo-section',\n className: 'flex items-center space-x-2 sm:space-x-3'\n }, [\n React.createElement('div', {\n key: 'logo',\n className: 'icon-container w-8 h-8 sm:w-10 sm:h-10'\n }, [\n React.createElement('i', {\n className: 'fas fa-shield-halved accent-orange text-sm sm:text-base'\n })\n ]),\n React.createElement('div', {\n key: 'title-section'\n }, [\n React.createElement('h1', {\n key: 'title',\n className: 'text-lg sm:text-xl font-semibold text-primary'\n }, 'SecureBit.chat'),\n React.createElement('p', {\n key: 'subtitle',\n className: 'text-xs sm:text-sm text-muted hidden sm:block'\n }, 'End-to-end freedom v4.02.985')\n ])\n ]),\n\n // Status and Controls - Responsive\n React.createElement('div', {\n key: 'status-section',\n className: 'flex items-center space-x-2 sm:space-x-3'\n }, [\n // Session Timer\n shouldShowTimer && React.createElement(window.SessionTimer, {\n key: 'session-timer',\n timeLeft: currentTimeLeft,\n sessionType: sessionType,\n sessionManager: sessionManager,\n onDisconnect: onDisconnect\n }),\n\n displaySecurityLevel && React.createElement('div', {\n key: 'security-level',\n className: 'hidden md:flex items-center space-x-2 cursor-pointer hover:opacity-80 transition-opacity duration-200',\n onClick: handleSecurityClick,\n onContextMenu: (e) => {\n e.preventDefault();\n if (onDisconnect && typeof onDisconnect === 'function') {\n onDisconnect();\n }\n },\n title: securityDetails.tooltip\n }, [\n React.createElement('div', {\n key: 'security-icon',\n className: `w-6 h-6 rounded-full flex items-center justify-center relative ${\n displaySecurityLevel.color === 'green' ? 'bg-green-500/20' :\n displaySecurityLevel.color === 'orange' ? 'bg-orange-500/20' :\n displaySecurityLevel.color === 'yellow' ? 'bg-yellow-500/20' : 'bg-red-500/20'\n } ${securityDetails.isVerified ? '' : 'animate-pulse'}`\n }, [\n React.createElement('i', {\n className: `fas fa-shield-alt text-xs ${\n displaySecurityLevel.color === 'green' ? 'text-green-400' :\n displaySecurityLevel.color === 'orange' ? 'text-orange-400' :\n displaySecurityLevel.color === 'yellow' ? 'text-yellow-400' : 'text-red-400'\n }`\n })\n ]),\n React.createElement('div', {\n key: 'security-info',\n className: 'flex flex-col'\n }, [\n React.createElement('div', {\n key: 'security-level-text',\n className: 'text-xs font-medium text-primary flex items-center space-x-1'\n }, [\n React.createElement('span', {}, `${displaySecurityLevel.level} (${displaySecurityLevel.score}%)`)\n ]),\n React.createElement('div', {\n key: 'security-details',\n className: 'text-xs text-muted mt-1 hidden lg:block'\n }, securityDetails.dataSource === 'real' ? \n `${displaySecurityLevel.passedChecks || 0}/${displaySecurityLevel.totalChecks || 0} tests` :\n (displaySecurityLevel.details || `Stage ${displaySecurityLevel.stage || 1}`)\n ),\n React.createElement('div', {\n key: 'security-progress',\n className: 'w-16 h-1 bg-gray-600 rounded-full overflow-hidden'\n }, [\n React.createElement('div', {\n key: 'progress-bar',\n className: `h-full transition-all duration-500 ${\n displaySecurityLevel.color === 'green' ? 'bg-green-400' :\n displaySecurityLevel.color === 'orange' ? 'bg-orange-400' :\n displaySecurityLevel.color === 'yellow' ? 'bg-yellow-400' : 'bg-red-400'\n }`,\n style: { width: `${displaySecurityLevel.score}%` }\n })\n ])\n ])\n ]),\n\n // Mobile Security Indicator\n displaySecurityLevel && React.createElement('div', {\n key: 'mobile-security',\n className: 'md:hidden flex items-center'\n }, [\n React.createElement('div', {\n key: 'mobile-security-icon',\n className: `w-8 h-8 rounded-full flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity duration-200 relative ${\n displaySecurityLevel.color === 'green' ? 'bg-green-500/20' :\n displaySecurityLevel.color === 'orange' ? 'bg-orange-500/20' :\n displaySecurityLevel.color === 'yellow' ? 'bg-yellow-500/20' : 'bg-red-500/20'\n } ${securityDetails.isVerified ? '' : 'animate-pulse'}`,\n title: securityDetails.tooltip,\n onClick: handleSecurityClick,\n onContextMenu: (e) => {\n e.preventDefault();\n if (onDisconnect && typeof onDisconnect === 'function') {\n onDisconnect();\n }\n }\n }, [\n React.createElement('i', {\n className: `fas fa-shield-alt text-sm ${\n displaySecurityLevel.color === 'green' ? 'text-green-400' :\n displaySecurityLevel.color === 'orange' ? 'text-orange-400' :\n displaySecurityLevel.color === 'yellow' ? 'text-yellow-400' : 'text-red-400'\n }`\n })\n ])\n ]),\n\n // Status Badge\n React.createElement('div', {\n key: 'status-badge',\n className: `px-2 sm:px-3 py-1.5 rounded-lg border ${config.badgeClass} flex items-center space-x-1 sm:space-x-2`\n }, [\n React.createElement('span', {\n key: 'status-dot',\n className: `status-dot ${config.className}`\n }),\n React.createElement('span', {\n key: 'status-text',\n className: 'text-xs sm:text-sm font-medium'\n }, config.text)\n ]),\n\n // Disconnect Button\n isConnected && React.createElement('button', {\n key: 'disconnect-btn',\n onClick: onDisconnect,\n className: 'p-1.5 sm:px-3 sm:py-1.5 bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/20 rounded-lg transition-all duration-200 text-sm'\n }, [\n React.createElement('i', {\n className: 'fas fa-power-off sm:mr-2'\n }),\n React.createElement('span', {\n className: 'hidden sm:inline'\n }, 'Disconnect')\n ])\n ])\n ])\n ])\n ]);\n};\n\nwindow.EnhancedMinimalHeader = EnhancedMinimalHeader;\n", "const SessionTypeSelector = ({ onSelectType, onCancel, sessionManager }) => {\n const [selectedType, setSelectedType] = React.useState(null);\n const [demoInfo, setDemoInfo] = React.useState(null);\n const [refreshTimer, setRefreshTimer] = React.useState(null);\n const [lastRefresh, setLastRefresh] = React.useState(Date.now());\n\n // We receive up-to-date information about demo limits\n const updateDemoInfo = React.useCallback(() => {\n if (sessionManager && sessionManager.getDemoSessionInfo) {\n try {\n const info = sessionManager.getDemoSessionInfo();\n if (window.DEBUG_MODE) {\n console.log('\uD83D\uDD04 Demo info updated:', info);\n }\n setDemoInfo(info);\n setLastRefresh(Date.now());\n } catch (error) {\n console.error('Failed to get demo info:', error);\n }\n }\n }, [sessionManager]);\n\n // Update information on load and every 10 seconds\n React.useEffect(() => {\n updateDemoInfo();\n const interval = setInterval(updateDemoInfo, 10000); \n setRefreshTimer(interval);\n return () => {\n if (interval) clearInterval(interval);\n };\n }, [updateDemoInfo]);\n\n // Clear timer on unmount\n React.useEffect(() => {\n return () => {\n if (refreshTimer) {\n clearInterval(refreshTimer);\n }\n };\n }, [refreshTimer]);\n\n const sessionTypes = [\n { \n id: 'demo', \n name: 'Demo', \n duration: '6 minutes', \n price: '0 sat', \n usd: '$0.00', \n popular: false,\n securityLevel: 'Basic',\n securityBadge: 'BASIC',\n securityColor: 'bg-blue-500/20 text-blue-300',\n description: 'Limited testing session with basic security',\n features: [\n 'Basic end-to-end encryption', \n 'Simple key exchange', \n 'Message integrity',\n 'Rate limiting'\n ],\n limitations: [\n 'No advanced security features',\n 'No traffic obfuscation',\n 'No metadata protection'\n ]\n },\n { \n id: 'basic', \n name: 'Basic', \n duration: '1 hour', \n price: '5,000 sat', \n usd: '$2.00',\n securityLevel: 'Enhanced',\n securityBadge: 'ENHANCED',\n securityColor: 'bg-orange-500/20 text-orange-300',\n popular: true,\n description: 'Full featured session with enhanced security',\n features: [\n 'All basic features',\n 'ECDSA digital signatures', \n 'Metadata protection', \n 'Perfect forward secrecy',\n 'Nested encryption',\n 'Packet padding',\n 'Complete ASN.1 validation',\n 'OID and EC point verification',\n 'SPKI structure validation',\n '18-layer security architecture',\n 'ASN.1 Validated'\n ],\n limitations: [\n 'Limited traffic obfuscation',\n 'No fake traffic generation'\n ]\n },\n { \n id: 'premium', \n name: 'Premium', \n duration: '6 hours', \n price: '20,000 sat', \n usd: '$8.00',\n securityLevel: 'Maximum',\n securityBadge: 'MAXIMUM',\n securityColor: 'bg-green-500/20 text-green-300',\n description: 'Extended session with maximum security protection',\n features: [\n 'All enhanced features',\n 'Traffic obfuscation', \n 'Fake traffic generation',\n 'Decoy channels',\n 'Anti-fingerprinting',\n 'Message chunking',\n 'Advanced replay protection',\n 'Complete ASN.1 validation',\n 'OID and EC point verification',\n 'SPKI structure validation',\n '18-layer security architecture',\n 'ASN.1 Validated'\n ],\n limitations: []\n }\n ];\n\n const handleTypeSelect = (typeId) => {\n console.log(`\uD83C\uDFAF Selecting session type: ${typeId}`);\n \n if (typeId === 'demo') {\n if (demoInfo && !demoInfo.canUseNow) {\n let message = `Demo session not available.\\n\\n`;\n \n if (demoInfo.blockingReason === 'global_limit') {\n message += `Reason: Too many global demo sessions active (${demoInfo.globalActive}/${demoInfo.globalLimit})\\n`;\n message += `Please try again in a few minutes.`;\n } else if (demoInfo.blockingReason === 'daily_limit') {\n message += `Reason: Daily limit reached (${demoInfo.used}/${demoInfo.total})\\n`;\n message += `Next available: ${demoInfo.nextAvailable}`;\n } else if (demoInfo.blockingReason === 'session_cooldown') {\n message += `Reason: Cooldown between sessions\\n`;\n message += `Next available: ${demoInfo.nextAvailable}`;\n } else if (demoInfo.blockingReason === 'completion_cooldown') {\n message += `Reason: Wait period after last session\\n`;\n message += `Next available: ${demoInfo.nextAvailable}`;\n } else {\n message += `Next available: ${demoInfo.nextAvailable}`;\n }\n \n alert(message);\n return;\n }\n }\n setSelectedType(typeId);\n };\n\n const formatCooldownTime = (minutes) => {\n if (minutes >= 60) {\n const hours = Math.floor(minutes / 60);\n const remainingMinutes = minutes % 60;\n return `${hours}h ${remainingMinutes}m`;\n }\n return `${minutes}m`;\n };\n\n return React.createElement('div', { className: 'space-y-6' }, [\n React.createElement('div', { key: 'header', className: 'text-center' }, [\n React.createElement('h3', { \n key: 'title', \n className: 'text-xl font-semibold text-white mb-2' \n }, 'Choose Your Session'),\n React.createElement('p', { \n key: 'subtitle', \n className: 'text-gray-300 text-sm' \n }, 'Different security levels for different needs')\n ]),\n \n React.createElement('div', { key: 'types', className: 'space-y-4' }, \n sessionTypes.map(type => {\n const isDemo = type.id === 'demo';\n const isDisabled = isDemo && demoInfo && !demoInfo.canUseNow;\n \n return React.createElement('div', {\n key: type.id,\n onClick: () => !isDisabled && handleTypeSelect(type.id),\n className: `relative card-minimal ${selectedType === type.id ? 'card-minimal--selected' : ''} rounded-lg p-5 border-2 transition-all ${\n selectedType === type.id\n ? 'border-orange-500 bg-orange-500/15 ring-2 ring-orange-400 ring-offset-2 ring-offset-black/30'\n : 'border-gray-600 hover:border-orange-400'\n } ${type.popular && selectedType !== type.id ? 'ring-2 ring-orange-500/30' : ''} ${\n isDisabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'\n }`\n }, [\n // Popular badge\n type.popular && React.createElement('div', { \n key: 'popular-badge', \n className: 'absolute -top-2 right-3 bg-orange-500 text-white text-xs px-3 py-1 rounded-full font-medium' \n }, 'Most Popular'),\n \n React.createElement('div', { key: 'content', className: 'space-y-4' }, [\n // Header with name and security level\n React.createElement('div', { key: 'header', className: 'flex items-start justify-between' }, [\n React.createElement('div', { key: 'title-section' }, [\n React.createElement('div', { key: 'name-row', className: 'flex items-center gap-3 mb-2' }, [\n React.createElement('h4', { \n key: 'name', \n className: 'text-xl font-bold text-white' \n }, type.name),\n isDemo && React.createElement('span', {\n key: 'free-badge',\n className: 'text-xs bg-blue-500/20 text-blue-300 px-2 py-1 rounded-full font-medium'\n }, 'FREE'),\n React.createElement('span', {\n key: 'security-badge',\n className: `text-xs px-2 py-1 rounded-full font-medium ${type.securityColor}`\n }, type.securityBadge)\n ]),\n React.createElement('p', { \n key: 'duration', \n className: 'text-gray-300 font-medium mb-1' \n }, `Duration: ${type.duration}`),\n React.createElement('p', {\n key: 'description',\n className: 'text-sm text-gray-400'\n }, type.description)\n ]),\n React.createElement('div', { key: 'pricing', className: 'text-right' }, [\n React.createElement('div', { \n key: 'sats', \n className: `text-xl font-bold ${isDemo ? 'text-green-400' : 'text-orange-400'}` \n }, type.price),\n React.createElement('div', { \n key: 'usd', \n className: 'text-sm text-gray-400' \n }, type.usd)\n ])\n ]),\n\n // Demo status info\n isDemo && demoInfo && React.createElement('div', {\n key: 'demo-status',\n className: 'p-3 bg-blue-900/20 border border-blue-700/30 rounded-lg'\n }, [\n React.createElement('div', {\n key: 'availability',\n className: `text-sm font-medium ${demoInfo.canUseNow ? 'text-green-400' : 'text-yellow-400'}`\n }, demoInfo.canUseNow ? \n `\u2705 Available (${demoInfo.available}/${demoInfo.total} today)` : \n `\u23F0 Next: ${demoInfo.nextAvailable}`\n ),\n demoInfo.globalActive > 0 && React.createElement('div', {\n key: 'global-status',\n className: 'text-blue-300 text-xs mt-1'\n }, `\uD83C\uDF10 Global: ${demoInfo.globalActive}/${demoInfo.globalLimit} active`)\n ]),\n\n // Security features\n React.createElement('div', { key: 'features-section', className: 'space-y-3' }, [\n React.createElement('div', { key: 'features' }, [\n React.createElement('h5', {\n key: 'features-title',\n className: 'text-sm font-medium text-green-300 mb-2 flex items-center'\n }, [\n React.createElement('i', {\n key: 'shield-icon',\n className: 'fas fa-shield-alt mr-2'\n }),\n 'Security Features'\n ]),\n React.createElement('div', {\n key: 'features-list',\n className: 'grid grid-cols-1 gap-1'\n }, type.features.map((feature, index) => \n React.createElement('div', {\n key: index,\n className: 'flex items-center gap-2 text-xs text-gray-300'\n }, [\n React.createElement('i', {\n key: 'check',\n className: 'fas fa-check text-green-400 w-3'\n }),\n React.createElement('span', {\n key: 'text'\n }, feature)\n ])\n ))\n ]),\n\n // Limitations (if any)\n type.limitations && type.limitations.length > 0 && React.createElement('div', { key: 'limitations' }, [\n React.createElement('h5', {\n key: 'limitations-title',\n className: 'text-sm font-medium text-yellow-300 mb-2 flex items-center'\n }, [\n React.createElement('i', {\n key: 'info-icon',\n className: 'fas fa-info-circle mr-2'\n }),\n 'Limitations'\n ]),\n React.createElement('div', {\n key: 'limitations-list',\n className: 'grid grid-cols-1 gap-1'\n }, type.limitations.map((limitation, index) => \n React.createElement('div', {\n key: index,\n className: 'flex items-center gap-2 text-xs text-gray-400'\n }, [\n React.createElement('i', {\n key: 'minus',\n className: 'fas fa-minus text-yellow-400 w-3'\n }),\n React.createElement('span', {\n key: 'text'\n }, limitation)\n ])\n ))\n ])\n ])\n ])\n ])\n })\n ),\n \n demoInfo && React.createElement('div', { \n key: 'demo-info', \n className: 'bg-gradient-to-r from-blue-900/20 to-purple-900/20 border border-blue-700/50 rounded-lg p-4' \n }, [\n React.createElement('div', { \n key: 'demo-header', \n className: 'flex items-center gap-2 text-blue-300 text-sm font-medium mb-3' \n }, [\n React.createElement('i', {\n key: 'icon',\n className: 'fas fa-info-circle'\n }),\n React.createElement('span', {\n key: 'title'\n }, 'Demo Session Information')\n ]),\n React.createElement('div', { \n key: 'demo-details', \n className: 'grid grid-cols-1 md:grid-cols-2 gap-3 text-blue-200 text-xs' \n }, [\n React.createElement('div', { key: 'limits', className: 'space-y-1' }, [\n React.createElement('div', { key: 'daily' }, `\uD83D\uDCC5 Daily limit: ${demoInfo.total} sessions`),\n React.createElement('div', { key: 'duration' }, `\u23F1\uFE0F Duration: ${demoInfo.durationMinutes} minutes each`),\n React.createElement('div', { key: 'cooldown' }, `\u23F0 Cooldown: ${demoInfo.sessionCooldownMinutes} min between sessions`)\n ]),\n React.createElement('div', { key: 'status', className: 'space-y-1' }, [\n React.createElement('div', { key: 'used' }, `\uD83D\uDCCA Used today: ${demoInfo.used}/${demoInfo.total}`),\n React.createElement('div', { key: 'global' }, `\uD83C\uDF10 Global active: ${demoInfo.globalActive}/${demoInfo.globalLimit}`),\n React.createElement('div', { \n key: 'next', \n className: demoInfo.canUseNow ? 'text-green-300' : 'text-yellow-300' \n }, `\uD83C\uDFAF Status: ${demoInfo.canUseNow ? 'Available now' : demoInfo.nextAvailable}`)\n ])\n ]),\n React.createElement('div', {\n key: 'security-note',\n className: 'mt-3 p-2 bg-yellow-500/10 border border-yellow-500/20 rounded text-yellow-200 text-xs'\n }, '\u26A0\uFE0F Demo sessions use basic security only. Upgrade to paid sessions for enhanced protection.'),\n React.createElement('div', {\n key: 'last-updated',\n className: 'text-xs text-gray-400 mt-2 text-center'\n }, `Last updated: ${new Date(lastRefresh).toLocaleTimeString()}`)\n ]),\n\n // Action buttons\n React.createElement('div', { key: 'buttons', className: 'flex space-x-3' }, [\n React.createElement('button', { \n key: 'continue', \n onClick: () => {\n if (selectedType) {\n console.log(`\uD83D\uDE80 Proceeding with session type: ${selectedType}`);\n onSelectType(selectedType);\n }\n }, \n disabled: !selectedType || (selectedType === 'demo' && demoInfo && !demoInfo.canUseNow), \n className: 'flex-1 lightning-button text-white py-3 px-4 rounded-lg font-medium disabled:opacity-50 disabled:cursor-not-allowed transition-all' \n }, [\n React.createElement('i', { \n key: 'icon',\n className: selectedType === 'demo' ? 'fas fa-play mr-2' : 'fas fa-bolt mr-2' \n }), \n selectedType === 'demo' ? 'Start Demo Session' : 'Continue to Payment'\n ]),\n React.createElement('button', { \n key: 'cancel', \n onClick: onCancel, \n className: 'px-6 py-3 bg-gray-600 hover:bg-gray-500 text-white rounded-lg transition-all' \n }, 'Cancel'),\n \n ])\n ]);\n};\n\nwindow.SessionTypeSelector = SessionTypeSelector;", "const React = window.React;\nconst { useState, useEffect } = React;\n\nconst IntegratedLightningPayment = ({ sessionType, onSuccess, onCancel, paymentManager }) => {\n const [paymentMethod, setPaymentMethod] = useState('webln');\n const [preimage, setPreimage] = useState('');\n const [isProcessing, setIsProcessing] = useState(false);\n const [error, setError] = useState('');\n const [invoice, setInvoice] = useState(null);\n const [paymentStatus, setPaymentStatus] = useState('pending'); // pending, created, paid, expired\n const [qrCodeUrl, setQrCodeUrl] = useState('');\n\n useEffect(() => {\n createInvoice();\n }, [sessionType]);\n\n const createInvoice = async () => {\n if (sessionType === 'free') {\n setPaymentStatus('free');\n return;\n }\n\n setIsProcessing(true);\n setError('');\n\n try {\n \n if (!paymentManager) {\n throw new Error('Payment manager not available. Please check sessionManager initialization.');\n }\n\n const createdInvoice = await paymentManager.createLightningInvoice(sessionType);\n\n if (!createdInvoice) {\n throw new Error('Failed to create invoice');\n }\n\n setInvoice(createdInvoice);\n setPaymentStatus('created');\n\n if (createdInvoice.paymentRequest) {\n try {\n const dataUrl = await window.generateQRCode(createdInvoice.paymentRequest, { size: 300, margin: 2, errorCorrectionLevel: 'M' });\n setQrCodeUrl(dataUrl);\n } catch (e) {\n console.warn('QR local generation failed, showing placeholder');\n const dataUrl = await window.generateQRCode(createdInvoice.paymentRequest, { size: 300 });\n setQrCodeUrl(dataUrl);\n }\n }\n\n } catch (err) {\n console.error('Invoice creation failed:', err);\n setError(`Error creating invoice: ${err.message}`);\n } finally {\n setIsProcessing(false);\n }\n };\n\n const handleWebLNPayment = async () => {\n if (!window.webln) {\n setError('WebLN is not supported. Please use the Alby or Zeus wallet. SecureBit.chat v4.02.442 - ASN.1 Validated requires WebLN for Lightning payments.');\n return;\n }\n\n if (!invoice || !invoice.paymentRequest) {\n setError('Invoice is not ready for payment');\n return;\n }\n\n setIsProcessing(true);\n setError('');\n\n try {\n await window.webln.enable();\n \n const result = await window.webln.sendPayment(invoice.paymentRequest);\n \n if (result.preimage) {\n setPaymentStatus('paid');\n await activateSession(result.preimage);\n } else {\n setError('Payment does not contain preimage');\n }\n } catch (err) {\n console.error('WebLN payment failed:', err);\n setError(`WebLN Error: ${err.message}`);\n } finally {\n setIsProcessing(false);\n }\n };\n\n const handleManualVerification = async () => {\n const trimmedPreimage = preimage.trim();\n \n if (!trimmedPreimage) {\n setError('Enter payment preimage');\n return;\n }\n \n if (trimmedPreimage.length !== 64) {\n setError('The preimage must be exactly 64 characters long.');\n return;\n }\n \n if (!/^[0-9a-fA-F]{64}$/.test(trimmedPreimage)) {\n setError('The preimage must contain only hexadecimal characters (0-9, a-f, A-F).');\n return;\n }\n \n if (trimmedPreimage === '1'.repeat(64) || \n trimmedPreimage === 'a'.repeat(64) || \n trimmedPreimage === 'f'.repeat(64)) {\n setError('The entered preimage is too weak. Please verify the key..');\n return;\n }\n \n setError('');\n setIsProcessing(true);\n\n try {\n await activateSession(trimmedPreimage);\n } catch (err) {\n setError(`Activation error: ${err.message}`);\n } finally {\n setIsProcessing(false);\n }\n };\n\n const activateSession = async (preimageValue) => {\n try {\n \n let result;\n if (paymentManager) {\n const paymentHash = invoice?.paymentHash || 'dummy_hash';\n result = await paymentManager.safeActivateSession(sessionType, preimageValue, paymentHash);\n } else {\n console.warn('Payment manager not available, using fallback');\n // Fallback if paymentManager is unavailable\n result = { success: true, method: 'fallback' };\n }\n\n if (result.success) {\n setPaymentStatus('paid');\n onSuccess(preimageValue, invoice);\n } else {\n console.error('\u274C Session activation failed:', result);\n throw new Error(`Session activation failed: ${result.reason}`);\n }\n\n } catch (err) {\n console.error('\u274C Session activation failed:', err);\n throw err;\n }\n };\n\n const handleFreeSession = async () => {\n setIsProcessing(true);\n try {\n await activateSession('0'.repeat(64));\n } catch (err) {\n setError(`Free session activation error: ${err.message}`);\n } finally {\n setIsProcessing(false);\n }\n };\n\n const copyToClipboard = (text) => {\n navigator.clipboard.writeText(text).then(() => {\n });\n };\n\n const pricing = {\n free: { sats: 1, hours: 1/60 },\n basic: { sats: 500, hours: 1 },\n premium: { sats: 1000, hours: 4 },\n extended: { sats: 2000, hours: 24 }\n }[sessionType];\n\n return React.createElement('div', { className: 'space-y-4 max-w-md mx-auto' }, [\n React.createElement('div', { key: 'header', className: 'text-center' }, [\n React.createElement('h3', { \n key: 'title', \n className: 'text-xl font-semibold text-white mb-2' \n }, sessionType === 'free' ? 'Free session' : 'Lightning payment'),\n React.createElement('div', { \n key: 'amount', \n className: 'text-2xl font-bold text-orange-400' \n }, sessionType === 'free' \n ? '0 sat per minute' \n : `${pricing.sats} \u0441\u0430\u0442 \u0437\u0430 ${pricing.hours}\u0447`\n ),\n sessionType !== 'free' && React.createElement('div', { \n key: 'usd', \n className: 'text-sm text-gray-400 mt-1' \n }, `\u2248 $${(pricing.sats * 0.0004).toFixed(2)} USD`)\n ]),\n\n // Loading State\n isProcessing && paymentStatus === 'pending' && React.createElement('div', { \n key: 'loading', \n className: 'text-center' \n }, [\n React.createElement('div', { \n key: 'spinner', \n className: 'text-orange-400' \n }, [\n React.createElement('i', { className: 'fas fa-spinner fa-spin mr-2' }),\n 'Creating invoice...'\n ])\n ]),\n\n // Free Session\n sessionType === 'free' && React.createElement('div', { \n key: 'free-session', \n className: 'space-y-3' \n }, [\n React.createElement('div', { \n key: 'info', \n className: 'p-3 bg-blue-500/10 border border-blue-500/20 rounded text-blue-300 text-sm' \n }, 'A free 1-minute session will be activated.'),\n React.createElement('button', { \n key: 'start-btn',\n onClick: handleFreeSession,\n disabled: isProcessing,\n className: 'w-full bg-blue-600 hover:bg-blue-500 text-white py-3 px-4 rounded-lg font-medium disabled:opacity-50'\n }, [\n React.createElement('i', { \n key: 'icon',\n className: `fas ${isProcessing ? 'fa-spinner fa-spin' : 'fa-play'} mr-2` \n }),\n isProcessing ? 'Activation...' : 'Start free session'\n ])\n ]),\n\n // Paid Sessions\n sessionType !== 'free' && paymentStatus === 'created' && invoice && React.createElement('div', { \n key: 'paid-session', \n className: 'space-y-4' \n }, [\n // QR Code\n qrCodeUrl && React.createElement('div', { \n key: 'qr-section', \n className: 'text-center' \n }, [\n React.createElement('div', { \n key: 'qr-container', \n className: 'bg-white p-4 rounded-lg inline-block' \n }, [\n React.createElement('img', { \n key: 'qr-img',\n src: qrCodeUrl, \n alt: 'Payment QR Code', \n className: 'w-48 h-48' \n })\n ]),\n React.createElement('div', { \n key: 'qr-hint', \n className: 'text-xs text-gray-400 mt-2' \n }, 'Scan the QR code with any Lightning wallet')\n ]),\n\n // Payment Request\n invoice.paymentRequest && React.createElement('div', { \n key: 'payment-request', \n className: 'space-y-2' \n }, [\n React.createElement('div', { \n key: 'label', \n className: 'text-sm font-medium text-white' \n }, 'Payment Request:'),\n React.createElement('div', { \n key: 'request',\n className: 'p-3 bg-gray-800 rounded border text-xs font-mono text-gray-300 cursor-pointer hover:bg-gray-700',\n onClick: () => copyToClipboard(invoice.paymentRequest)\n }, [\n invoice.paymentRequest.substring(0, 50) + '...',\n React.createElement('i', { key: 'copy-icon', className: 'fas fa-copy ml-2 text-orange-400' })\n ])\n ]),\n\n // WebLN Payment\n React.createElement('div', { \n key: 'webln-section', \n className: 'space-y-3' \n }, [\n React.createElement('h4', { \n key: 'webln-title', \n className: 'text-white font-medium flex items-center' \n }, [\n React.createElement('i', { key: 'bolt-icon', className: 'fas fa-bolt text-orange-400 mr-2' }),\n 'WebLN wallet (Alby, Zeus)'\n ]),\n React.createElement('button', { \n key: 'webln-btn',\n onClick: handleWebLNPayment,\n disabled: isProcessing,\n className: 'w-full bg-orange-600 hover:bg-orange-500 text-white py-3 px-4 rounded-lg font-medium disabled:opacity-50'\n }, [\n React.createElement('i', { \n key: 'webln-icon',\n className: `fas ${isProcessing ? 'fa-spinner fa-spin' : 'fa-bolt'} mr-2` \n }),\n isProcessing ? 'Processing...' : 'Pay via WebLN'\n ])\n ]),\n\n // Manual Payment\n React.createElement('div', { \n key: 'divider', \n className: 'text-center text-gray-400' \n }, 'or'),\n \n React.createElement('div', { \n key: 'manual-section', \n className: 'space-y-3' \n }, [\n React.createElement('h4', { \n key: 'manual-title', \n className: 'text-white font-medium' \n }, 'Manual payment verification'),\n React.createElement('input', { \n key: 'preimage-input',\n type: 'text',\n value: preimage,\n onChange: (e) => setPreimage(e.target.value),\n placeholder: 'Enter the preimage after payment...',\n className: 'w-full p-3 bg-gray-800 border border-gray-600 rounded text-white placeholder-gray-400 text-sm'\n }),\n React.createElement('button', { \n key: 'verify-btn',\n onClick: handleManualVerification,\n disabled: isProcessing,\n className: 'w-full bg-green-600 hover:bg-green-500 text-white py-3 px-4 rounded-lg font-medium disabled:opacity-50'\n }, [\n React.createElement('i', { \n key: 'verify-icon',\n className: `fas ${isProcessing ? 'fa-spinner fa-spin' : 'fa-check'} mr-2` \n }),\n isProcessing ? 'Verification...' : 'Confirm payment'\n ])\n ])\n ]),\n\n // Success State\n paymentStatus === 'paid' && React.createElement('div', { \n key: 'success', \n className: 'text-center p-4 bg-green-500/10 border border-green-500/20 rounded' \n }, [\n React.createElement('i', { key: 'success-icon', className: 'fas fa-check-circle text-green-400 text-2xl mb-2' }),\n React.createElement('div', { key: 'success-text', className: 'text-green-300 font-medium' }, 'Payment confirmed!'),\n React.createElement('div', { key: 'success-subtext', className: 'text-green-400 text-sm' }, 'Session activated')\n ]),\n\n // Error State\n error && React.createElement('div', { \n key: 'error', \n className: 'p-3 bg-red-500/10 border border-red-500/20 rounded text-red-400 text-sm' \n }, [\n React.createElement('i', { key: 'error-icon', className: 'fas fa-exclamation-triangle mr-2' }),\n error,\n error.includes('invoice') && React.createElement('button', { \n key: 'retry-btn',\n onClick: createInvoice,\n className: 'ml-2 text-orange-400 hover:text-orange-300 underline'\n }, 'Try again')\n ]),\n\n // Cancel Button\n React.createElement('button', { \n key: 'cancel-btn',\n onClick: onCancel,\n className: 'w-full bg-gray-600 hover:bg-gray-500 text-white py-2 px-4 rounded'\n }, 'Cancel')\n ]);\n};\n\nwindow.LightningPayment = IntegratedLightningPayment;", "const React = window.React;\nconst { useState, useEffect, useRef } = React;\n\nconst PaymentModal = ({ isOpen, onClose, sessionManager, onSessionPurchased }) => {\n const [step, setStep] = React.useState('select');\n const [selectedType, setSelectedType] = React.useState(null);\n const [invoice, setInvoice] = React.useState(null);\n const [paymentStatus, setPaymentStatus] = React.useState('pending');\n const [error, setError] = React.useState('');\n const [paymentMethod, setPaymentMethod] = React.useState('webln'); \n const [preimageInput, setPreimageInput] = React.useState('');\n const [isProcessing, setIsProcessing] = React.useState(false);\n const [qrCodeUrl, setQrCodeUrl] = React.useState('');\n const [paymentTimer, setPaymentTimer] = React.useState(null);\n const [timeLeft, setTimeLeft] = React.useState(0);\n const [showSecurityDetails, setShowSecurityDetails] = React.useState(false);\n const pollInterval = React.useRef(null);\n\n React.useEffect(() => {\n if (!isOpen) {\n resetModal();\n if (pollInterval.current) {\n clearInterval(pollInterval.current);\n }\n if (paymentTimer) {\n clearInterval(paymentTimer);\n }\n }\n }, [isOpen]);\n\n const resetModal = () => {\n setStep('select');\n setSelectedType(null);\n setInvoice(null);\n setPaymentStatus('pending');\n setError('');\n setPaymentMethod('webln');\n setPreimageInput('');\n setIsProcessing(false);\n setQrCodeUrl('');\n setTimeLeft(0);\n setShowSecurityDetails(false);\n };\n\n const getSecurityFeaturesInfo = (sessionType) => {\n const features = {\n demo: {\n title: 'Demo Session - Basic Security',\n description: 'Limited testing session with basic security features',\n available: [\n '\uD83D\uDD10 Basic end-to-end encryption (AES-GCM 256)',\n '\uD83D\uDD11 Simple key exchange (ECDH P-384)',\n '\u2705 Message integrity verification',\n '\u26A1 Rate limiting protection'\n ],\n unavailable: [\n '\uD83D\uDD10 ECDSA Digital Signatures',\n '\uD83D\uDEE1\uFE0F Metadata Protection',\n '\uD83D\uDD04 Perfect Forward Secrecy',\n '\uD83D\uDD10 Nested Encryption',\n '\uD83D\uDCE6 Packet Padding',\n '\uD83C\uDFAD Traffic Obfuscation',\n '\uD83C\uDFAA Fake Traffic Generation',\n '\uD83D\uDD75\uFE0F Decoy Channels',\n '\uD83D\uDEAB Anti-Fingerprinting',\n '\uD83D\uDCDD Message Chunking',\n '\uD83D\uDD04 Advanced Replay Protection'\n ],\n upgrade: {\n next: 'Basic Session (5,000 sat - $2.00)',\n features: [\n '\uD83D\uDD10 ECDSA Digital Signatures',\n '\uD83D\uDEE1\uFE0F Metadata Protection',\n '\uD83D\uDD04 Perfect Forward Secrecy',\n '\uD83D\uDD10 Nested Encryption',\n '\uD83D\uDCE6 Packet Padding'\n ]\n }\n },\n basic: {\n title: 'Basic Session - Enhanced Security',\n description: 'Full featured session with enhanced security features',\n available: [\n '\uD83D\uDD10 Basic end-to-end encryption (AES-GCM 256)',\n '\uD83D\uDD11 Simple key exchange (ECDH P-384)',\n '\u2705 Message integrity verification',\n '\u26A1 Rate limiting protection',\n '\uD83D\uDD10 ECDSA Digital Signatures',\n '\uD83D\uDEE1\uFE0F Metadata Protection',\n '\uD83D\uDD04 Perfect Forward Secrecy',\n '\uD83D\uDD10 Nested Encryption',\n '\uD83D\uDCE6 Packet Padding',\n '\uD83D\uDD12 Complete ASN.1 validation',\n '\uD83D\uDD0D OID and EC point verification',\n '\uD83C\uDFD7\uFE0F SPKI structure validation',\n '\uD83D\uDEE1\uFE0F 18-layer security architecture'\n ],\n unavailable: [\n '\uD83C\uDFAD Traffic Obfuscation',\n '\uD83C\uDFAA Fake Traffic Generation',\n '\uD83D\uDD75\uFE0F Decoy Channels',\n '\uD83D\uDEAB Anti-Fingerprinting',\n '\uD83D\uDCDD Message Chunking',\n '\uD83D\uDD04 Advanced Replay Protection'\n ],\n upgrade: {\n next: 'Premium Session (20,000 sat - $8.00)',\n features: [\n '\uD83C\uDFAD Traffic Obfuscation',\n '\uD83C\uDFAA Fake Traffic Generation',\n '\uD83D\uDD75\uFE0F Decoy Channels',\n '\uD83D\uDEAB Anti-Fingerprinting',\n '\uD83D\uDCDD Message Chunking',\n '\uD83D\uDD04 Advanced Replay Protection'\n ]\n }\n },\n premium: {\n title: 'Premium Session - Maximum Security',\n description: 'Extended session with maximum security protection',\n available: [\n '\uD83D\uDD10 Basic end-to-end encryption (AES-GCM 256)',\n '\uD83D\uDD11 Simple key exchange (ECDH P-384)',\n '\u2705 Message integrity verification',\n '\u26A1 Rate limiting protection',\n '\uD83D\uDD10 ECDSA Digital Signatures',\n '\uD83D\uDEE1\uFE0F Metadata Protection',\n '\uD83D\uDD04 Perfect Forward Secrecy',\n '\uD83D\uDD10 Nested Encryption',\n '\uD83D\uDCE6 Packet Padding',\n '\uD83C\uDFAD Traffic Obfuscation',\n '\uD83C\uDFAA Fake Traffic Generation',\n '\uD83D\uDD75\uFE0F Decoy Channels',\n '\uD83D\uDEAB Anti-Fingerprinting',\n '\uD83D\uDCDD Message Chunking',\n '\uD83D\uDD04 Advanced Replay Protection',\n '\uD83D\uDD12 Complete ASN.1 validation',\n '\uD83D\uDD0D OID and EC point verification',\n '\uD83C\uDFD7\uFE0F SPKI structure validation',\n '\uD83D\uDEE1\uFE0F 18-layer security architecture',\n '\uD83D\uDE80 ASN.1 Validated'\n ],\n unavailable: [],\n upgrade: {\n next: 'Maximum security achieved!',\n features: ['\uD83C\uDF89 All security features unlocked!']\n }\n }\n };\n \n return features[sessionType] || features.demo;\n };\n\n const handleSelectType = async (type) => {\n setSelectedType(type);\n setError('');\n \n if (type === 'demo') {\n try {\n if (!sessionManager || !sessionManager.createDemoSession) {\n throw new Error('Demo session manager not available');\n }\n \n const demoSession = sessionManager.createDemoSession();\n if (!demoSession.success) {\n throw new Error(demoSession.reason);\n }\n \n setInvoice({ \n sessionType: 'demo',\n amount: 0,\n paymentHash: demoSession.paymentHash,\n memo: `Demo session (${demoSession.durationMinutes} minutes)`,\n createdAt: Date.now(),\n isDemo: true,\n preimage: demoSession.preimage,\n warning: demoSession.warning,\n securityLevel: 'Basic'\n });\n setPaymentStatus('demo');\n } catch (error) {\n setError(`Demo session creation failed: ${error.message}`);\n return;\n }\n } else {\n await createRealInvoice(type);\n }\n setStep('payment');\n };\n\n const createRealInvoice = async (type) => {\n setPaymentStatus('creating');\n setIsProcessing(true);\n setError('');\n\n try {\n console.log(`Creating Lightning invoice for ${type} session...`);\n \n if (!sessionManager) {\n throw new Error('Session manager not initialized');\n }\n\n const createdInvoice = await sessionManager.createLightningInvoice(type);\n \n if (!createdInvoice || !createdInvoice.paymentRequest) {\n throw new Error('Failed to create Lightning invoice');\n }\n\n createdInvoice.securityLevel = sessionManager.getSecurityLevelForSession(type);\n\n setInvoice(createdInvoice);\n setPaymentStatus('created');\n\n try {\n const dataUrl = await window.generateQRCode(createdInvoice.paymentRequest, { size: 300, margin: 2, errorCorrectionLevel: 'M' });\n setQrCodeUrl(dataUrl);\n } catch (e) {\n console.warn('QR local generation failed, showing placeholder');\n const dataUrl = await window.generateQRCode(createdInvoice.paymentRequest, { size: 300 });\n setQrCodeUrl(dataUrl);\n }\n\n const expirationTime = 15 * 60 * 1000;\n setTimeLeft(expirationTime);\n \n const timer = setInterval(() => {\n setTimeLeft(prev => {\n const newTime = prev - 1000;\n if (newTime <= 0) {\n clearInterval(timer);\n setPaymentStatus('expired');\n setError('Payment time has expired. Create a new invoice.');\n return 0;\n }\n return newTime;\n });\n }, 1000);\n setPaymentTimer(timer);\n\n startPaymentPolling(createdInvoice.checkingId);\n\n console.log('\u2705 Lightning invoice created successfully:', createdInvoice);\n\n } catch (err) {\n console.error('\u274C Invoice creation failed:', err);\n setError(`Invoice creation error: ${err.message}`);\n setPaymentStatus('failed');\n } finally {\n setIsProcessing(false);\n }\n };\n\n const startPaymentPolling = (checkingId) => {\n if (pollInterval.current) {\n clearInterval(pollInterval.current);\n }\n\n pollInterval.current = setInterval(async () => {\n try {\n const status = await sessionManager.checkPaymentStatus(checkingId);\n \n if (status.paid && status.preimage) {\n clearInterval(pollInterval.current);\n setPaymentStatus('paid');\n await handlePaymentSuccess(status.preimage);\n }\n } catch (error) {\n console.warn('Payment status check failed:', error);\n }\n }, 3000); \n };\n\n const handleWebLNPayment = async () => {\n if (!window.webln) {\n setError('WebLN is not supported. Please install the Alby or Zeus wallet.');\n return;\n }\n\n if (!invoice || !invoice.paymentRequest) {\n setError('Invoice is not ready for payment.');\n return;\n }\n\n setIsProcessing(true);\n setError('');\n setPaymentStatus('paying');\n\n try {\n await window.webln.enable();\n \n const result = await window.webln.sendPayment(invoice.paymentRequest);\n \n if (result.preimage) {\n setPaymentStatus('paid');\n await handlePaymentSuccess(result.preimage);\n } else {\n throw new Error('Payment does not contain preimage');\n }\n } catch (err) {\n console.error('\u274C WebLN payment failed:', err);\n setError(`WebLN payment error: ${err.message}`);\n setPaymentStatus('created'); \n } finally {\n setIsProcessing(false);\n }\n };\n\n const handleManualVerification = async () => {\n const trimmedPreimage = preimageInput.trim();\n \n if (!trimmedPreimage) {\n setError('Enter payment preimage');\n return;\n }\n \n if (trimmedPreimage.length !== 64) {\n setError('The preimage must be exactly 64 characters long.');\n return;\n }\n \n if (!/^[0-9a-fA-F]{64}$/.test(trimmedPreimage)) {\n setError('The preimage must contain only hexadecimal characters (0-9, a-f, A-F).');\n return;\n }\n \n const dummyPreimages = ['1'.repeat(64), 'a'.repeat(64), 'f'.repeat(64), '0'.repeat(64)];\n if (dummyPreimages.includes(trimmedPreimage) && selectedType !== 'demo') {\n setError('The entered preimage is invalid. Please use the actual preimage from the payment.');\n return;\n }\n \n setIsProcessing(true);\n setError('');\n setPaymentStatus('paying');\n\n try {\n await handlePaymentSuccess(trimmedPreimage);\n } catch (err) {\n setError(err.message);\n setPaymentStatus('created');\n } finally {\n setIsProcessing(false);\n }\n };\n\n const handleDemoSession = async () => {\n setIsProcessing(true);\n setError('');\n \n try {\n if (!invoice?.preimage) {\n throw new Error('Demo preimage not available');\n }\n \n const isValid = await sessionManager.verifyPayment(invoice.preimage, invoice.paymentHash);\n \n if (isValid && isValid.verified) {\n onSessionPurchased({ \n type: 'demo', \n preimage: invoice.preimage,\n paymentHash: invoice.paymentHash,\n amount: 0,\n isDemo: true,\n warning: invoice.warning,\n securityLevel: 'basic'\n });\n \n setTimeout(() => {\n onClose();\n }, 1500);\n } else {\n throw new Error(isValid?.reason || 'Demo session verification failed');\n }\n } catch (err) {\n setError(`Demo session activation error: ${err.message}`);\n } finally {\n setIsProcessing(false);\n }\n };\n\n const handlePaymentSuccess = async (preimage) => {\n try {\n console.log('\uD83D\uDD0D Verifying payment...', { selectedType, preimage });\n \n let isValid;\n if (selectedType === 'demo') {\n return;\n } else {\n isValid = await sessionManager.verifyPayment(preimage, invoice.paymentHash);\n }\n \n if (isValid) {\n if (pollInterval.current) {\n clearInterval(pollInterval.current);\n }\n if (paymentTimer) {\n clearInterval(paymentTimer);\n }\n\n onSessionPurchased({ \n type: selectedType, \n preimage,\n paymentHash: invoice.paymentHash,\n amount: invoice.amount,\n securityLevel: invoice.securityLevel || (selectedType === 'basic' ? 'enhanced' : 'maximum')\n });\n \n setTimeout(() => {\n onClose();\n }, 1500);\n \n } else {\n throw new Error('Payment verification failed. Please check the preimage for correctness or try again.');\n }\n } catch (error) {\n console.error('\u274C Payment verification failed:', error);\n throw error;\n }\n };\n\n const copyToClipboard = async (text) => {\n try {\n await navigator.clipboard.writeText(text);\n } catch (err) {\n console.error('Failed to copy:', err);\n }\n };\n\n const formatTime = (ms) => {\n const minutes = Math.floor(ms / 60000);\n const seconds = Math.floor((ms % 60000) / 1000);\n return `${minutes}:${seconds.toString().padStart(2, '0')}`;\n };\n\n const getSecurityBadgeColor = (level) => {\n switch (level?.toLowerCase()) {\n case 'basic': return 'bg-blue-500/20 text-blue-300 border-blue-500/30';\n case 'enhanced': return 'bg-orange-500/20 text-orange-300 border-orange-500/30';\n case 'maximum': return 'bg-green-500/20 text-green-300 border-green-500/30';\n default: return 'bg-gray-500/20 text-gray-300 border-gray-500/30';\n }\n };\n\n const pricing = sessionManager?.sessionPrices || {\n demo: { sats: 0, hours: 0.1, usd: 0.00 },\n basic: { sats: 5000, hours: 1, usd: 2.00 },\n premium: { sats: 20000, hours: 6, usd: 8.00 }\n };\n\n if (!isOpen) return null;\n\n return React.createElement('div', { \n className: 'fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4' \n }, [\n React.createElement('div', { \n key: 'modal', \n className: 'card-minimal rounded-xl p-6 max-w-lg w-full max-h-[90vh] overflow-y-auto custom-scrollbar' \n }, [\n React.createElement('div', { \n key: 'header', \n className: 'flex items-center justify-between mb-6' \n }, [\n React.createElement('h2', { \n key: 'title', \n className: 'text-xl font-semibold text-primary' \n }, step === 'select' ? 'Select session type' : \n step === 'details' ? 'Security Features Details' : 'Session payment'),\n React.createElement('button', { \n key: 'close',\n onClick: onClose, \n className: 'text-gray-400 hover:text-white transition-colors' \n }, React.createElement('i', { className: 'fas fa-times' }))\n ]),\n\n step === 'select' && window.SessionTypeSelector && React.createElement(window.SessionTypeSelector, { \n key: 'selector', \n onSelectType: handleSelectType, \n onCancel: onClose,\n sessionManager: sessionManager\n }),\n\n step === 'payment' && React.createElement('div', { \n key: 'payment-step', \n className: 'space-y-6' \n }, [\n React.createElement('div', { \n key: 'session-info', \n className: 'text-center p-4 bg-orange-500/10 border border-orange-500/20 rounded-lg' \n }, [\n React.createElement('h3', { \n key: 'session-title', \n className: 'text-lg font-semibold text-orange-400 mb-2' \n }, [\n `${selectedType.charAt(0).toUpperCase() + selectedType.slice(1)} session`,\n invoice?.securityLevel && React.createElement('span', {\n key: 'security-badge',\n className: `text-xs px-2 py-1 rounded-full border ${getSecurityBadgeColor(invoice.securityLevel)}`\n }, invoice.securityLevel.toUpperCase())\n ]),\n React.createElement('div', { \n key: 'session-details', \n className: 'text-sm text-secondary' \n }, [\n React.createElement('div', { key: 'amount' }, `${pricing[selectedType].sats} sat for ${pricing[selectedType].hours}h`),\n pricing[selectedType].usd > 0 && React.createElement('div', { \n key: 'usd', \n className: 'text-gray-400' \n }, `\u2248 ${pricing[selectedType].usd} USD`),\n React.createElement('button', {\n key: 'details-btn',\n onClick: () => setStep('details'),\n className: 'mt-2 text-xs text-blue-400 hover:text-blue-300 underline cursor-pointer'\n }, '\uD83D\uDCCB View Security Details')\n ])\n ]),\n\n timeLeft > 0 && paymentStatus === 'created' && React.createElement('div', { \n key: 'timer', \n className: 'text-center p-3 bg-yellow-500/10 border border-yellow-500/20 rounded' \n }, [\n React.createElement('div', { \n key: 'timer-text', \n className: 'text-yellow-400 font-medium' \n }, `\u23F1\uFE0F Time to pay: ${formatTime(timeLeft)}`)\n ]),\n\n paymentStatus === 'demo' && React.createElement('div', { \n key: 'demo-payment', \n className: 'space-y-4' \n }, [\n React.createElement('div', { \n key: 'demo-info', \n className: 'p-4 bg-green-500/10 border border-green-500/20 rounded text-green-300 text-sm text-center' \n }, [\n React.createElement('div', { key: 'demo-title', className: 'font-medium mb-1' }, '\uD83C\uDFAE Demo Session Available'),\n React.createElement('div', { key: 'demo-details', className: 'text-xs' }, \n `Limited to ${invoice?.durationMinutes || 6} minutes for testing`)\n ]),\n invoice?.warning && React.createElement('div', {\n key: 'demo-warning',\n className: 'p-3 bg-yellow-500/10 border border-yellow-500/20 rounded text-yellow-300 text-xs text-center'\n }, invoice.warning),\n React.createElement('div', {\n key: 'demo-preimage',\n className: 'p-3 bg-gray-800/50 rounded border border-gray-600 text-xs font-mono text-gray-300'\n }, [\n React.createElement('div', { key: 'preimage-label', className: 'text-gray-400 mb-1' }, 'Demo Preimage:'),\n React.createElement('div', { key: 'preimage-value', className: 'break-all' }, \n invoice?.preimage || 'Generating...')\n ]),\n React.createElement('button', { \n key: 'demo-btn',\n onClick: handleDemoSession,\n disabled: isProcessing,\n className: 'w-full bg-green-600 hover:bg-green-500 text-white py-3 px-4 rounded-lg font-medium disabled:opacity-50 disabled:cursor-not-allowed'\n }, [\n React.createElement('i', { \n key: 'demo-icon',\n className: `fas ${isProcessing ? 'fa-spinner fa-spin' : 'fa-play'} mr-2` \n }),\n isProcessing ? 'Activating...' : 'Activate Demo Session'\n ])\n ]),\n\n paymentStatus === 'creating' && React.createElement('div', { \n key: 'creating', \n className: 'text-center p-4' \n }, [\n React.createElement('i', { className: 'fas fa-spinner fa-spin text-orange-400 text-2xl mb-2' }),\n React.createElement('div', { className: 'text-primary' }, 'Creating Lightning invoice...'),\n React.createElement('div', { className: 'text-secondary text-sm mt-1' }, 'Connecting to the Lightning Network...')\n ]),\n\n (paymentStatus === 'created' || paymentStatus === 'paying') && invoice && React.createElement('div', { \n key: 'payment-methods', \n className: 'space-y-6' \n }, [\n qrCodeUrl && React.createElement('div', { \n key: 'qr-section', \n className: 'text-center' \n }, [\n React.createElement('div', { \n key: 'qr-container', \n className: 'bg-white p-4 rounded-lg inline-block' \n }, [\n React.createElement('img', { \n key: 'qr-img',\n src: qrCodeUrl, \n alt: 'Lightning Payment QR Code', \n className: 'w-48 h-48' \n })\n ]),\n React.createElement('div', { \n key: 'qr-hint', \n className: 'text-xs text-gray-400 mt-2' \n }, 'Scan with any Lightning wallet')\n ]),\n\n invoice.paymentRequest && React.createElement('div', { \n key: 'payment-request', \n className: 'space-y-2' \n }, [\n React.createElement('div', { \n key: 'pr-label', \n className: 'text-sm font-medium text-primary' \n }, 'Lightning Payment Request:'),\n React.createElement('div', { \n key: 'pr-container',\n className: 'p-3 bg-gray-800/50 rounded border border-gray-600 text-xs font-mono text-gray-300 cursor-pointer hover:bg-gray-700/50 transition-colors',\n onClick: () => copyToClipboard(invoice.paymentRequest),\n title: 'Click to copy'\n }, [\n invoice.paymentRequest.substring(0, 60) + '...',\n React.createElement('i', { key: 'copy-icon', className: 'fas fa-copy ml-2 text-orange-400' })\n ])\n ]),\n\n // WebLN Payment\n React.createElement('div', { \n key: 'webln-section', \n className: 'space-y-3' \n }, [\n React.createElement('h4', { \n key: 'webln-title', \n className: 'text-primary font-medium flex items-center' \n }, [\n React.createElement('i', { key: 'bolt-icon', className: 'fas fa-bolt text-orange-400 mr-2' }),\n 'WebLN wallet (recommended)'\n ]),\n React.createElement('div', { \n key: 'webln-info', \n className: 'text-xs text-gray-400 mb-2' \n }, 'Alby, Zeus, or other WebLN-compatible wallets'),\n React.createElement('button', { \n key: 'webln-btn',\n onClick: handleWebLNPayment,\n disabled: isProcessing || paymentStatus === 'paying',\n className: 'w-full bg-orange-600 hover:bg-orange-500 text-white py-3 px-4 rounded-lg font-medium disabled:opacity-50 disabled:cursor-not-allowed transition-colors'\n }, [\n React.createElement('i', { \n key: 'webln-icon',\n className: `fas ${isProcessing ? 'fa-spinner fa-spin' : 'fa-bolt'} mr-2` \n }),\n paymentStatus === 'paying' ? 'Processing payment...' : 'Pay via WebLN'\n ])\n ]),\n\n // Divider\n React.createElement('div', { \n key: 'divider', \n className: 'text-center text-gray-400 text-sm' \n }, '\u2014 or \u2014'),\n \n // Manual Verification\n React.createElement('div', { \n key: 'manual-section', \n className: 'space-y-3' \n }, [\n React.createElement('h4', { \n key: 'manual-title', \n className: 'text-primary font-medium' \n }, 'Manual payment confirmation'),\n React.createElement('div', { \n key: 'manual-info', \n className: 'text-xs text-gray-400' \n }, 'Pay the invoice in any wallet and enter the preimage.:'),\n React.createElement('input', { \n key: 'preimage-input',\n type: 'text',\n value: preimageInput,\n onChange: (e) => setPreimageInput(e.target.value),\n placeholder: 'Enter the preimage (64 hex characters)...',\n className: 'w-full p-3 bg-gray-800 border border-gray-600 rounded text-white placeholder-gray-400 text-sm font-mono',\n maxLength: 64\n }),\n React.createElement('button', { \n key: 'verify-btn',\n onClick: handleManualVerification,\n disabled: isProcessing || !preimageInput.trim(),\n className: 'w-full bg-green-600 hover:bg-green-500 text-white py-3 px-4 rounded-lg font-medium disabled:opacity-50 disabled:cursor-not-allowed transition-colors'\n }, [\n React.createElement('i', { \n key: 'verify-icon',\n className: `fas ${isProcessing ? 'fa-spinner fa-spin' : 'fa-check'} mr-2` \n }),\n isProcessing ? 'Checking payment...' : 'Confirm payment'\n ])\n ])\n ]),\n\n // Success State\n paymentStatus === 'paid' && React.createElement('div', { \n key: 'success', \n className: 'text-center p-6 bg-green-500/10 border border-green-500/20 rounded-lg' \n }, [\n React.createElement('i', { key: 'success-icon', className: 'fas fa-check-circle text-green-400 text-3xl mb-3' }),\n React.createElement('div', { key: 'success-title', className: 'text-green-300 font-semibold text-lg mb-1' }, '\u2705 Payment confirmed!'),\n React.createElement('div', { key: 'success-text', className: 'text-green-400 text-sm' }, 'The session will be activated upon connecting to the chat.')\n ]),\n\n // Error State\n error && React.createElement('div', { \n key: 'error', \n className: 'p-4 bg-red-500/10 border border-red-500/20 rounded-lg' \n }, [\n React.createElement('div', { \n key: 'error-content', \n className: 'flex items-start space-x-3' \n }, [\n React.createElement('i', { key: 'error-icon', className: 'fas fa-exclamation-triangle text-red-400 mt-0.5' }),\n React.createElement('div', { key: 'error-text', className: 'flex-1' }, [\n React.createElement('div', { key: 'error-message', className: 'text-red-400 text-sm' }, error),\n (error.includes('invoice') || paymentStatus === 'failed') && React.createElement('button', { \n key: 'retry-btn',\n onClick: () => createRealInvoice(selectedType),\n className: 'mt-2 text-orange-400 hover:text-orange-300 underline text-sm'\n }, 'Create a new invoice')\n ])\n ])\n ]),\n\n paymentStatus !== 'paid' && React.createElement('div', { \n key: 'back-section', \n className: 'pt-4 border-t border-gray-600' \n }, [\n React.createElement('button', { \n key: 'back-btn',\n onClick: () => setStep('select'),\n className: 'w-full bg-gray-600 hover:bg-gray-500 text-white py-2 px-4 rounded transition-colors'\n }, [\n React.createElement('i', { key: 'back-icon', className: 'fas fa-arrow-left mr-2' }),\n 'Choose another session'\n ])\n ])\n ]),\n\n // Security Details Step\n step === 'details' && React.createElement('div', { \n key: 'details-step', \n className: 'space-y-6' \n }, [\n React.createElement('div', { \n key: 'details-header', \n className: 'text-center p-4 bg-blue-500/10 border border-blue-500/20 rounded-lg' \n }, [\n React.createElement('h3', { \n key: 'details-title', \n className: 'text-lg font-semibold text-blue-400 mb-2' \n }, getSecurityFeaturesInfo(selectedType).title),\n React.createElement('p', { \n key: 'details-description', \n className: 'text-sm text-blue-300' \n }, getSecurityFeaturesInfo(selectedType).description)\n ]),\n\n // Available Features\n React.createElement('div', { key: 'available-features' }, [\n React.createElement('h4', {\n key: 'available-title',\n className: 'text-sm font-medium text-green-300 mb-3 flex items-center'\n }, [\n React.createElement('i', {\n key: 'check-icon',\n className: 'fas fa-check-circle mr-2'\n }),\n 'Available Security Features'\n ]),\n React.createElement('div', {\n key: 'available-list',\n className: 'grid grid-cols-1 gap-2'\n }, getSecurityFeaturesInfo(selectedType).available.map((feature, index) => \n React.createElement('div', {\n key: index,\n className: 'flex items-center gap-2 text-sm text-green-300'\n }, [\n React.createElement('i', {\n key: 'check',\n className: 'fas fa-check text-green-400 w-4'\n }),\n React.createElement('span', {\n key: 'text'\n }, feature)\n ])\n ))\n ]),\n\n // Unavailable Features (if any)\n getSecurityFeaturesInfo(selectedType).unavailable.length > 0 && React.createElement('div', { key: 'unavailable-features' }, [\n React.createElement('h4', {\n key: 'unavailable-title',\n className: 'text-sm font-medium text-red-300 mb-3 flex items-center'\n }, [\n React.createElement('i', {\n key: 'minus-icon',\n className: 'fas fa-minus-circle mr-2'\n }),\n 'Not Available in This Session'\n ]),\n React.createElement('div', {\n key: 'unavailable-list',\n className: 'grid grid-cols-1 gap-2'\n }, getSecurityFeaturesInfo(selectedType).unavailable.map((feature, index) => \n React.createElement('div', {\n key: index,\n className: 'flex items-center gap-2 text-sm text-red-300'\n }, [\n React.createElement('i', {\n key: 'minus',\n className: 'fas fa-minus text-red-400 w-4'\n }),\n React.createElement('span', {\n key: 'text'\n }, feature)\n ])\n ))\n ]),\n\n // Upgrade Information\n React.createElement('div', { key: 'upgrade-info' }, [\n React.createElement('h4', {\n key: 'upgrade-title',\n className: 'text-sm font-medium text-blue-300 mb-3 flex items-center'\n }, [\n React.createElement('i', {\n key: 'upgrade-icon',\n className: 'fas fa-arrow-up mr-2'\n }),\n 'Upgrade for More Security'\n ]),\n React.createElement('div', {\n key: 'upgrade-content',\n className: 'p-3 bg-blue-500/10 border border-blue-500/20 rounded-lg'\n }, [\n React.createElement('div', {\n key: 'upgrade-next',\n className: 'text-sm font-medium text-blue-300 mb-2'\n }, getSecurityFeaturesInfo(selectedType).upgrade.next),\n React.createElement('div', {\n key: 'upgrade-features',\n className: 'grid grid-cols-1 gap-1'\n }, getSecurityFeaturesInfo(selectedType).upgrade.features.map((feature, index) => \n React.createElement('div', {\n key: index,\n className: 'flex items-center gap-2 text-xs text-blue-300'\n }, [\n React.createElement('i', {\n key: 'arrow',\n className: 'fas fa-arrow-right text-blue-400 w-3'\n }),\n React.createElement('span', {\n key: 'text'\n }, feature)\n ])\n ))\n ])\n ]),\n\n // Back Button\n React.createElement('div', { \n key: 'details-back-section', \n className: 'pt-4 border-t border-gray-600' \n }, [\n React.createElement('button', { \n key: 'details-back-btn',\n onClick: () => setStep('payment'),\n className: 'w-full bg-gray-600 hover:bg-gray-500 text-white py-2 px-4 rounded transition-colors'\n }, [\n React.createElement('i', { key: 'back-icon', className: 'fas fa-arrow-left mr-2' }),\n 'Back to Payment'\n ])\n ])\n ])\n ])\n ]);\n};\n\nwindow.PaymentModal = PaymentModal;", "const DownloadApps = () => {\r\n const apps = [\r\n { id: 'web', name: 'Web App', subtitle: 'Browser Version', icon: 'fas fa-globe', platform: 'Web', isActive: true, url: 'https://securebitchat.github.io/securebit-chat/', color: 'green' },\r\n { id: 'windows', name: 'Windows', subtitle: 'Desktop App', icon: 'fab fa-windows', platform: 'Desktop', isActive: false, url: '#', color: 'blue' },\r\n { id: 'macos', name: 'macOS', subtitle: 'Desktop App', icon: 'fab fa-apple', platform: 'Desktop', isActive: false, url: '#', color: 'gray' },\r\n { id: 'linux', name: 'Linux', subtitle: 'Desktop App', icon: 'fab fa-linux', platform: 'Desktop', isActive: false, url: '#', color: 'orange' },\r\n { id: 'ios', name: 'iOS', subtitle: 'iPhone & iPad', icon: 'fab fa-apple', platform: 'Mobile', isActive: false, url: 'https://apps.apple.com/app/securebit-chat/', color: 'blue' },\r\n { id: 'android', name: 'Android', subtitle: 'Google Play', icon: 'fab fa-android', platform: 'Mobile', isActive: false, url: 'https://play.google.com/store/apps/details?id=com.securebit.chat', color: 'green' }\r\n ];\r\n\r\n const handleDownload = (app) => {\r\n if (app.isActive) window.open(app.url, '_blank');\r\n };\r\n\r\n const desktopApps = apps.filter(a => a.platform !== 'Mobile');\r\n const mobileApps = apps.filter(a => a.platform === 'Mobile');\r\n\r\n const cardSize = \"w-28 h-28\"; \r\n\r\n return React.createElement('div', { className: \"mt-20 px-6\" }, [\r\n // Header\r\n React.createElement('div', { key: 'header', className: \"text-center max-w-3xl mx-auto mb-12\" }, [\r\n React.createElement('h3', { key: 'title', className: \"text-3xl font-bold text-primary mb-3\" }, 'Download SecureBit.chat'),\r\n React.createElement('p', { key: 'subtitle', className: \"text-secondary text-lg mb-5\" }, 'Stay secure on every device. Choose your platform and start chatting privately.')\r\n ]),\r\n\r\n React.createElement('div', { key: 'desktop-row', className: \"hidden sm:flex justify-center flex-wrap gap-6 mb-6\" },\r\n desktopApps.map(app =>\r\n React.createElement('div', {\r\n key: app.id,\r\n className: `group relative ${cardSize} rounded-2xl overflow-hidden card-minimal cursor-pointer`\r\n }, [\r\n React.createElement('i', {\r\n key: 'bg-icon',\r\n className: `${app.icon} absolute text-[3rem] text-white/10 top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 pointer-events-none transition-all duration-500 group-hover:scale-105`\r\n }),\r\n React.createElement('div', {\r\n key: 'overlay',\r\n className: \"absolute inset-0 bg-black/30 backdrop-blur-md flex flex-col items-center justify-center text-center opacity-0 transition-opacity duration-300 group-hover:opacity-100\"\r\n }, [\r\n React.createElement('h4', { key: 'name', className: `text-sm font-semibold text-primary mb-1` }, app.name),\r\n React.createElement('p', { key: 'subtitle', className: `text-xs text-secondary mb-2` }, app.subtitle),\r\n app.isActive ?\r\n React.createElement('button', {\r\n key: 'btn',\r\n onClick: () => handleDownload(app),\r\n className: `px-2 py-1 rounded-xl bg-emerald-500 text-black font-medium hover:bg-emerald-600 transition-colors text-xs`\r\n }, app.id === \"web\" ? \"Launch\" : \"Download\")\r\n :\r\n React.createElement('span', { key: 'coming', className: \"text-gray-400 font-medium text-xs\" }, \"Coming Soon\")\r\n ])\r\n ])\r\n )\r\n ),\r\n\r\n React.createElement('div', { key: 'mobile-row', className: \"flex justify-center gap-6\" },\r\n mobileApps.map(app =>\r\n React.createElement('div', {\r\n key: app.id,\r\n className: `group relative ${cardSize} rounded-2xl overflow-hidden card-minimal cursor-pointer`\r\n }, [\r\n React.createElement('i', {\r\n key: 'bg-icon',\r\n className: `${app.icon} absolute text-[3rem] text-white/10 top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 pointer-events-none transition-all duration-500 group-hover:scale-105`\r\n }),\r\n React.createElement('div', {\r\n key: 'overlay',\r\n className: \"absolute inset-0 bg-black/30 backdrop-blur-md flex flex-col items-center justify-center text-center opacity-0 transition-opacity duration-300 group-hover:opacity-100\"\r\n }, [\r\n React.createElement('h4', { key: 'name', className: `text-sm font-semibold text-primary mb-1` }, app.name),\r\n React.createElement('p', { key: 'subtitle', className: `text-xs text-secondary mb-2` }, app.subtitle),\r\n app.isActive ?\r\n React.createElement('button', {\r\n key: 'btn',\r\n onClick: () => handleDownload(app),\r\n className: `px-2 py-1 rounded-xl bg-emerald-500 text-black font-medium hover:bg-emerald-600 transition-colors text-xs`\r\n }, \"Download\")\r\n :\r\n React.createElement('span', { key: 'coming', className: \"text-gray-400 font-medium text-xs\" }, \"Coming Soon\")\r\n ])\r\n ])\r\n )\r\n )\r\n ]);\r\n};\r\n\r\nwindow.DownloadApps = DownloadApps;\r\n", "// File Transfer Component for Chat Interface - Fixed Version\r\nconst FileTransferComponent = ({ webrtcManager, isConnected }) => {\r\n const [dragOver, setDragOver] = React.useState(false);\r\n const [transfers, setTransfers] = React.useState({ sending: [], receiving: [] });\r\n const [readyFiles, setReadyFiles] = React.useState([]); // \u0444\u0430\u0439\u043B\u044B, \u0433\u043E\u0442\u043E\u0432\u044B\u0435 \u043A \u0441\u043A\u0430\u0447\u0438\u0432\u0430\u043D\u0438\u044E\r\n const fileInputRef = React.useRef(null);\r\n\r\n // Update transfers periodically\r\n React.useEffect(() => {\r\n if (!isConnected || !webrtcManager) return;\r\n\r\n const updateTransfers = () => {\r\n const currentTransfers = webrtcManager.getFileTransfers();\r\n setTransfers(currentTransfers);\r\n };\r\n\r\n const interval = setInterval(updateTransfers, 500);\r\n return () => clearInterval(interval);\r\n }, [isConnected, webrtcManager]);\r\n\r\n // Setup file transfer callbacks - \u0418\u0421\u041F\u0420\u0410\u0412\u041B\u0415\u041D\u0418\u0415: \u041D\u0415 \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C \u043F\u0440\u043E\u043C\u0435\u0436\u0443\u0442\u043E\u0447\u043D\u044B\u0435 \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u0432 \u0447\u0430\u0442\r\n React.useEffect(() => {\r\n if (!webrtcManager) return;\r\n\r\n webrtcManager.setFileTransferCallbacks(\r\n // Progress callback - \u0422\u041E\u041B\u042C\u041A\u041E \u043E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C UI, \u041D\u0415 \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C \u0432 \u0447\u0430\u0442\r\n (progress) => {\r\n // \u041E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C \u0442\u043E\u043B\u044C\u043A\u043E \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u043E\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435\r\n const currentTransfers = webrtcManager.getFileTransfers();\r\n setTransfers(currentTransfers);\r\n \r\n // \u041D\u0415 \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u0432 \u0447\u0430\u0442!\r\n },\r\n \r\n // File received callback - \u0434\u043E\u0431\u0430\u0432\u043B\u044F\u0435\u043C \u043A\u043D\u043E\u043F\u043A\u0443 \u0441\u043A\u0430\u0447\u0438\u0432\u0430\u043D\u0438\u044F \u0432 UI\r\n (fileData) => {\r\n // \u0414\u043E\u0431\u0430\u0432\u043B\u044F\u0435\u043C \u0432 \u0441\u043F\u0438\u0441\u043E\u043A \u0433\u043E\u0442\u043E\u0432\u044B\u0445 \u043A \u0441\u043A\u0430\u0447\u0438\u0432\u0430\u043D\u0438\u044E\r\n setReadyFiles(prev => {\r\n // \u0438\u0437\u0431\u0435\u0433\u0430\u0435\u043C \u0434\u0443\u0431\u043B\u0435\u0439 \u043F\u043E fileId\r\n if (prev.some(f => f.fileId === fileData.fileId)) return prev;\r\n return [...prev, {\r\n fileId: fileData.fileId,\r\n fileName: fileData.fileName,\r\n fileSize: fileData.fileSize,\r\n mimeType: fileData.mimeType,\r\n getBlob: fileData.getBlob,\r\n getObjectURL: fileData.getObjectURL,\r\n revokeObjectURL: fileData.revokeObjectURL\r\n }];\r\n });\r\n\r\n // \u041E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C \u0441\u043F\u0438\u0441\u043E\u043A \u0430\u043A\u0442\u0438\u0432\u043D\u044B\u0445 \u043F\u0435\u0440\u0435\u0434\u0430\u0447\r\n const currentTransfers = webrtcManager.getFileTransfers();\r\n setTransfers(currentTransfers);\r\n },\r\n \r\n // Error callback\r\n (error) => {\r\n const currentTransfers = webrtcManager.getFileTransfers();\r\n setTransfers(currentTransfers);\r\n \r\n // \u0418\u0421\u041F\u0420\u0410\u0412\u041B\u0415\u041D\u0418\u0415: \u041D\u0415 \u0434\u0443\u0431\u043B\u0438\u0440\u0443\u0435\u043C \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u043E\u0431 \u043E\u0448\u0438\u0431\u043A\u0430\u0445\r\n // \u0423\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u043E\u0431 \u043E\u0448\u0438\u0431\u043A\u0430\u0445 \u0443\u0436\u0435 \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u044F\u044E\u0442\u0441\u044F \u0432 WebRTC \u043C\u0435\u043D\u0435\u0434\u0436\u0435\u0440\u0435\r\n }\r\n );\r\n }, [webrtcManager]);\r\n\r\n const handleFileSelect = async (files) => {\r\n if (!isConnected || !webrtcManager) {\r\n alert('\u0421\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 \u043D\u0435 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u043E. \u0421\u043D\u0430\u0447\u0430\u043B\u0430 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0435 \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435.');\r\n return;\r\n }\r\n\r\n // \u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u0430\u044F \u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0430 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u044F \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\r\n if (!webrtcManager.isConnected() || !webrtcManager.isVerified) {\r\n alert('\u0421\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 \u043D\u0435 \u0433\u043E\u0442\u043E\u0432\u043E \u0434\u043B\u044F \u043F\u0435\u0440\u0435\u0434\u0430\u0447\u0438 \u0444\u0430\u0439\u043B\u043E\u0432. \u0414\u043E\u0436\u0434\u0438\u0442\u0435\u0441\u044C \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438 \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F.');\r\n return;\r\n }\r\n\r\n for (const file of files) {\r\n try {\r\n // \u041A\u0420\u0418\u0422\u0418\u0427\u0415\u0421\u041A\u041E\u0415 \u0418\u0421\u041F\u0420\u0410\u0412\u041B\u0415\u041D\u0418\u0415: \u0412\u0430\u043B\u0438\u0434\u0430\u0446\u0438\u044F \u0444\u0430\u0439\u043B\u0430 \u043F\u0435\u0440\u0435\u0434 \u043E\u0442\u043F\u0440\u0430\u0432\u043A\u043E\u0439\r\n const validation = webrtcManager.validateFile(file);\r\n if (!validation.isValid) {\r\n const errorMessage = validation.errors.join('. ');\r\n alert(`\u0424\u0430\u0439\u043B ${file.name} \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u0435\u043D: ${errorMessage}`);\r\n continue;\r\n }\r\n\r\n await webrtcManager.sendFile(file);\r\n } catch (error) {\r\n // \u0411\u043E\u043B\u0435\u0435 \u043C\u044F\u0433\u043A\u0430\u044F \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430 \u043E\u0448\u0438\u0431\u043E\u043A - \u043D\u0435 \u0437\u0430\u043A\u0440\u044B\u0432\u0430\u0435\u043C \u0441\u0435\u0441\u0441\u0438\u044E\r\n \r\n // \u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u043C \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044E \u043E\u0448\u0438\u0431\u043A\u0443, \u043D\u043E \u043D\u0435 \u0437\u0430\u043A\u0440\u044B\u0432\u0430\u0435\u043C \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435\r\n if (error.message.includes('Connection not ready')) {\r\n alert(`\u0424\u0430\u0439\u043B ${file.name} \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u0435\u043D \u0441\u0435\u0439\u0447\u0430\u0441. \u041F\u0440\u043E\u0432\u0435\u0440\u044C\u0442\u0435 \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 \u0438 \u043F\u043E\u043F\u0440\u043E\u0431\u0443\u0439\u0442\u0435 \u0441\u043D\u043E\u0432\u0430.`);\r\n } else if (error.message.includes('File too large') || error.message.includes('exceeds maximum')) {\r\n alert(`\u0424\u0430\u0439\u043B ${file.name} \u0441\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0439: ${error.message}`);\r\n } else if (error.message.includes('Maximum concurrent transfers')) {\r\n alert(`\u0414\u043E\u0441\u0442\u0438\u0433\u043D\u0443\u0442 \u043B\u0438\u043C\u0438\u0442 \u043E\u0434\u043D\u043E\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0445 \u043F\u0435\u0440\u0435\u0434\u0430\u0447. \u0414\u043E\u0436\u0434\u0438\u0442\u0435\u0441\u044C \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u044F \u0442\u0435\u043A\u0443\u0449\u0438\u0445 \u043F\u0435\u0440\u0435\u0434\u0430\u0447.`);\r\n } else if (error.message.includes('File type not allowed')) {\r\n alert(`\u0422\u0438\u043F \u0444\u0430\u0439\u043B\u0430 ${file.name} \u043D\u0435 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F: ${error.message}`);\r\n } else {\r\n alert(`\u041E\u0448\u0438\u0431\u043A\u0430 \u043E\u0442\u043F\u0440\u0430\u0432\u043A\u0438 \u0444\u0430\u0439\u043B\u0430 ${file.name}: ${error.message}`);\r\n }\r\n }\r\n }\r\n };\r\n\r\n const handleDrop = (e) => {\r\n e.preventDefault();\r\n setDragOver(false);\r\n \r\n const files = Array.from(e.dataTransfer.files);\r\n handleFileSelect(files);\r\n };\r\n\r\n const handleDragOver = (e) => {\r\n e.preventDefault();\r\n setDragOver(true);\r\n };\r\n\r\n const handleDragLeave = (e) => {\r\n e.preventDefault();\r\n setDragOver(false);\r\n };\r\n\r\n const handleFileInputChange = (e) => {\r\n const files = Array.from(e.target.files);\r\n handleFileSelect(files);\r\n e.target.value = ''; // Reset input\r\n };\r\n\r\n const formatFileSize = (bytes) => {\r\n if (bytes === 0) return '0 B';\r\n const k = 1024;\r\n const sizes = ['B', 'KB', 'MB', 'GB'];\r\n const i = Math.floor(Math.log(bytes) / Math.log(k));\r\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\r\n };\r\n\r\n const getStatusIcon = (status) => {\r\n switch (status) {\r\n case 'metadata_sent':\r\n case 'preparing':\r\n return 'fas fa-cog fa-spin';\r\n case 'transmitting':\r\n case 'receiving':\r\n return 'fas fa-exchange-alt fa-pulse';\r\n case 'assembling':\r\n return 'fas fa-puzzle-piece fa-pulse';\r\n case 'completed':\r\n return 'fas fa-check text-green-400';\r\n case 'failed':\r\n return 'fas fa-times text-red-400';\r\n default:\r\n return 'fas fa-circle';\r\n }\r\n };\r\n\r\n const getStatusText = (status) => {\r\n switch (status) {\r\n case 'metadata_sent':\r\n return '\u041F\u043E\u0434\u0433\u043E\u0442\u043E\u0432\u043A\u0430...';\r\n case 'transmitting':\r\n return '\u041E\u0442\u043F\u0440\u0430\u0432\u043A\u0430...';\r\n case 'receiving':\r\n return '\u041F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u0435...';\r\n case 'assembling':\r\n return '\u0421\u0431\u043E\u0440\u043A\u0430 \u0444\u0430\u0439\u043B\u0430...';\r\n case 'completed':\r\n return '\u0417\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u043E';\r\n case 'failed':\r\n return '\u041E\u0448\u0438\u0431\u043A\u0430';\r\n default:\r\n return status;\r\n }\r\n };\r\n\r\n if (!isConnected) {\r\n return React.createElement('div', {\r\n className: \"p-4 text-center text-muted\"\r\n }, '\u041F\u0435\u0440\u0435\u0434\u0430\u0447\u0430 \u0444\u0430\u0439\u043B\u043E\u0432 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430 \u0442\u043E\u043B\u044C\u043A\u043E \u043F\u0440\u0438 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u043D\u043E\u043C \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0438');\r\n }\r\n\r\n // \u041F\u0440\u043E\u0432\u0435\u0440\u044F\u0435\u043C \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435 \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\r\n const isConnectionReady = webrtcManager && webrtcManager.isConnected() && webrtcManager.isVerified;\r\n \r\n if (!isConnectionReady) {\r\n return React.createElement('div', {\r\n className: \"p-4 text-center text-yellow-600\"\r\n }, [\r\n React.createElement('i', {\r\n key: 'icon',\r\n className: 'fas fa-exclamation-triangle mr-2'\r\n }),\r\n '\u0421\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 \u0443\u0441\u0442\u0430\u043D\u0430\u0432\u043B\u0438\u0432\u0430\u0435\u0442\u0441\u044F... \u041F\u0435\u0440\u0435\u0434\u0430\u0447\u0430 \u0444\u0430\u0439\u043B\u043E\u0432 \u0431\u0443\u0434\u0435\u0442 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430 \u043F\u043E\u0441\u043B\u0435 \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438.'\r\n ]);\r\n }\r\n\r\n return React.createElement('div', {\r\n className: \"file-transfer-component\"\r\n }, [\r\n // File Drop Zone\r\n React.createElement('div', {\r\n key: 'drop-zone',\r\n className: `file-drop-zone ${dragOver ? 'drag-over' : ''}`,\r\n onDrop: handleDrop,\r\n onDragOver: handleDragOver,\r\n onDragLeave: handleDragLeave,\r\n onClick: () => fileInputRef.current?.click()\r\n }, [\r\n React.createElement('div', {\r\n key: 'drop-content',\r\n className: \"drop-content\"\r\n }, [\r\n React.createElement('i', {\r\n key: 'icon',\r\n className: 'fas fa-cloud-upload-alt text-2xl mb-2 text-blue-400'\r\n }),\r\n React.createElement('p', {\r\n key: 'text',\r\n className: \"text-primary font-medium\"\r\n }, 'Drag files here or click to select'),\r\n React.createElement('p', {\r\n key: 'subtext',\r\n className: \"text-muted text-sm\"\r\n }, 'Maximum size: 100 MB per file')\r\n ])\r\n ]),\r\n\r\n // Hidden file input\r\n React.createElement('input', {\r\n key: 'file-input',\r\n ref: fileInputRef,\r\n type: 'file',\r\n multiple: true,\r\n className: 'hidden',\r\n onChange: handleFileInputChange\r\n }),\r\n\r\n // Active Transfers\r\n (transfers.sending.length > 0 || transfers.receiving.length > 0) && React.createElement('div', {\r\n key: 'transfers',\r\n className: \"active-transfers mt-4\"\r\n }, [\r\n React.createElement('h4', {\r\n key: 'title',\r\n className: \"text-primary font-medium mb-3 flex items-center\"\r\n }, [\r\n React.createElement('i', {\r\n key: 'icon',\r\n className: 'fas fa-exchange-alt mr-2'\r\n }),\r\n '\u041F\u0435\u0440\u0435\u0434\u0430\u0447\u0430 \u0444\u0430\u0439\u043B\u043E\u0432'\r\n ]),\r\n\r\n // Sending files\r\n ...transfers.sending.map(transfer => \r\n React.createElement('div', {\r\n key: `send-${transfer.fileId}`,\r\n className: \"transfer-item bg-blue-500/10 border border-blue-500/20 rounded-lg p-3 mb-2\"\r\n }, [\r\n React.createElement('div', {\r\n key: 'header',\r\n className: \"flex items-center justify-between mb-2\"\r\n }, [\r\n React.createElement('div', {\r\n key: 'info',\r\n className: \"flex items-center\"\r\n }, [\r\n React.createElement('i', {\r\n key: 'icon',\r\n className: 'fas fa-upload text-blue-400 mr-2'\r\n }),\r\n React.createElement('span', {\r\n key: 'name',\r\n className: \"text-primary font-medium text-sm\"\r\n }, transfer.fileName),\r\n React.createElement('span', {\r\n key: 'size',\r\n className: \"text-muted text-xs ml-2\"\r\n }, formatFileSize(transfer.fileSize))\r\n ]),\r\n React.createElement('button', {\r\n key: 'cancel',\r\n onClick: () => webrtcManager.cancelFileTransfer(transfer.fileId),\r\n className: \"text-red-400 hover:text-red-300 text-xs\"\r\n }, [\r\n React.createElement('i', {\r\n className: 'fas fa-times'\r\n })\r\n ])\r\n ]),\r\n React.createElement('div', {\r\n key: 'progress',\r\n className: \"progress-bar\"\r\n }, [\r\n React.createElement('div', {\r\n key: 'fill',\r\n className: \"progress-fill bg-blue-400\",\r\n style: { width: `${transfer.progress}%` }\r\n }),\r\n React.createElement('div', {\r\n key: 'text',\r\n className: \"progress-text text-xs flex items-center justify-between\"\r\n }, [\r\n React.createElement('span', {\r\n key: 'status',\r\n className: \"flex items-center\"\r\n }, [\r\n React.createElement('i', {\r\n key: 'icon',\r\n className: `${getStatusIcon(transfer.status)} mr-1`\r\n }),\r\n getStatusText(transfer.status)\r\n ]),\r\n React.createElement('span', {\r\n key: 'percent'\r\n }, `${transfer.progress.toFixed(1)}%`)\r\n ])\r\n ])\r\n ])\r\n ),\r\n\r\n // Receiving files\r\n ...transfers.receiving.map(transfer => \r\n React.createElement('div', {\r\n key: `recv-${transfer.fileId}`,\r\n className: \"transfer-item bg-green-500/10 border border-green-500/20 rounded-lg p-3 mb-2\"\r\n }, [\r\n React.createElement('div', {\r\n key: 'header',\r\n className: \"flex items-center justify-between mb-2\"\r\n }, [\r\n React.createElement('div', {\r\n key: 'info',\r\n className: \"flex items-center\"\r\n }, [\r\n React.createElement('i', {\r\n key: 'icon',\r\n className: 'fas fa-download text-green-400 mr-2'\r\n }),\r\n React.createElement('span', {\r\n key: 'name',\r\n className: \"text-primary font-medium text-sm\"\r\n }, transfer.fileName),\r\n React.createElement('span', {\r\n key: 'size',\r\n className: \"text-muted text-xs ml-2\"\r\n }, formatFileSize(transfer.fileSize))\r\n ]),\r\n React.createElement('div', { key: 'actions', className: 'flex items-center space-x-2' }, [\r\n (() => {\r\n const rf = readyFiles.find(f => f.fileId === transfer.fileId);\r\n if (!rf || transfer.status !== 'completed') return null;\r\n return React.createElement('button', {\r\n key: 'download',\r\n className: 'text-green-400 hover:text-green-300 text-xs flex items-center',\r\n onClick: async () => {\r\n try {\r\n const url = await rf.getObjectURL();\r\n const a = document.createElement('a');\r\n a.href = url;\r\n a.download = rf.fileName || 'file';\r\n a.click();\r\n rf.revokeObjectURL(url);\r\n } catch (e) {\r\n alert('Failed to start download: ' + e.message);\r\n }\r\n }\r\n }, [\r\n React.createElement('i', { key: 'i', className: 'fas fa-download mr-1' }),\r\n 'Download'\r\n ]);\r\n })(),\r\n React.createElement('button', {\r\n key: 'cancel',\r\n onClick: () => webrtcManager.cancelFileTransfer(transfer.fileId),\r\n className: \"text-red-400 hover:text-red-300 text-xs\"\r\n }, [\r\n React.createElement('i', {\r\n className: 'fas fa-times'\r\n })\r\n ])\r\n ])\r\n ]),\r\n React.createElement('div', {\r\n key: 'progress',\r\n className: \"progress-bar\"\r\n }, [\r\n React.createElement('div', {\r\n key: 'fill',\r\n className: \"progress-fill bg-green-400\",\r\n style: { width: `${transfer.progress}%` }\r\n }),\r\n React.createElement('div', {\r\n key: 'text',\r\n className: \"progress-text text-xs flex items-center justify-between\"\r\n }, [\r\n React.createElement('span', {\r\n key: 'status',\r\n className: \"flex items-center\"\r\n }, [\r\n React.createElement('i', {\r\n key: 'icon',\r\n className: `${getStatusIcon(transfer.status)} mr-1`\r\n }),\r\n getStatusText(transfer.status)\r\n ]),\r\n React.createElement('span', {\r\n key: 'percent'\r\n }, `${transfer.progress.toFixed(1)}%`)\r\n ])\r\n ])\r\n ])\r\n )\r\n ])\r\n ]);\r\n};\r\n\r\n// Export\r\nwindow.FileTransferComponent = FileTransferComponent;", "import { EnhancedSecureCryptoUtils } from '../crypto/EnhancedSecureCryptoUtils.js';\r\nimport { EnhancedSecureWebRTCManager } from '../network/EnhancedSecureWebRTCManager.js';\r\nimport { PayPerSessionManager } from '../session/PayPerSessionManager.js';\r\nimport { EnhancedSecureFileTransfer } from '../transfer/EnhancedSecureFileTransfer.js';\r\n\r\n// Import UI components (side-effect: they attach themselves to window.*)\r\nimport '../components/ui/SessionTimer.jsx';\r\nimport '../components/ui/Header.jsx';\r\nimport '../components/ui/SessionTypeSelector.jsx';\r\nimport '../components/ui/LightningPayment.jsx';\r\nimport '../components/ui/PaymentModal.jsx';\r\nimport '../components/ui/DownloadApps.jsx';\r\nimport '../components/ui/FileTransfer.jsx';\r\n\r\n// Expose to global for legacy usage inside app code\r\nwindow.EnhancedSecureCryptoUtils = EnhancedSecureCryptoUtils;\r\nwindow.EnhancedSecureWebRTCManager = EnhancedSecureWebRTCManager;\r\nwindow.PayPerSessionManager = PayPerSessionManager;\r\nwindow.EnhancedSecureFileTransfer = EnhancedSecureFileTransfer;\r\n\r\n// Mount application once DOM and modules are ready\r\nconst start = () => {\r\n if (typeof window.initializeApp === 'function') {\r\n window.initializeApp();\r\n } else if (window.DEBUG_MODE) {\r\n console.error('initializeApp is not defined on window');\r\n }\r\n};\r\n\r\nif (document.readyState === 'loading') {\r\n document.addEventListener('DOMContentLoaded', start);\r\n} else {\r\n start();\r\n}\r\n"], - "mappings": ";AAAA,IAAM,4BAAN,MAAM,2BAA0B;AAAA,EAE5B,OAAO,eAAe,oBAAI,QAAQ;AAAA;AAAA;AAAA,EAKlC,OAAO,eAAe,KAAK;AACvB,QAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM;AACzC,aAAO;AAAA,IACX;AAEA,QAAI,MAAM,QAAQ,GAAG,GAAG;AACpB,aAAO,IAAI,IAAI,2BAA0B,cAAc;AAAA,IAC3D;AAEA,UAAM,YAAY,CAAC;AACnB,WAAO,KAAK,GAAG,EAAE,KAAK,EAAE,QAAQ,SAAO;AACnC,gBAAU,GAAG,IAAI,2BAA0B,eAAe,IAAI,GAAG,CAAC;AAAA,IACtE,CAAC;AACD,WAAO;AAAA,EACX;AAAA;AAAA,EAGA,OAAO,gBAAgB,KAAK,eAAe,MAAM,iBAAiB,CAAC,GAAG;AAClE,QAAI,EAAE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,CAAC;AAAA,UACL,CAAC;AAAA,UACD,MAAM,cAAc,OAAO;AAAA,YACvB,KAAK;AAAA,YACL,WAAW;AAAA,UACf,GAAG;AAAA,YACC,MAAM,cAAc,OAAO;AAAA,cACvB,KAAK;AAAA,cACL,WAAW;AAAA,cACX,OAAO,EAAE,OAAO,GAAG,SAAS,QAAQ,IAAI;AAAA,YAC5C,CAAC;AAAA,YACD,MAAM,cAAc,OAAO;AAAA,cACvB,KAAK;AAAA,cACL,WAAW;AAAA,YACf,GAAG;AAAA,cACC,MAAM,cAAc,QAAQ;AAAA,gBACxB,KAAK;AAAA,gBACL,WAAW;AAAA,cACf,GAAG;AAAA,gBACC,MAAM,cAAc,KAAK;AAAA,kBACrB,KAAK;AAAA,kBACL,WAAW,GAAG,cAAc,SAAS,MAAM,CAAC;AAAA,gBAChD,CAAC;AAAA,gBACD,cAAc,SAAS,MAAM;AAAA,cACjC,CAAC;AAAA,cACD,MAAM,cAAc,QAAQ;AAAA,gBACxB,KAAK;AAAA,cACT,GAAG,GAAG,SAAS,SAAS,QAAQ,CAAC,CAAC,GAAG;AAAA,YACzC,CAAC;AAAA,UACL,CAAC;AAAA,QACL,CAAC;AAAA,MACL;AAAA,IACJ,CAAC;AAAA,EACL,CAAC;AACL;AAGA,OAAO,wBAAwB;;;ACvZ/B,OAAO,4BAA4B;AACnC,OAAO,8BAA8B;AACrC,OAAO,uBAAuB;AAC9B,OAAO,6BAA6B;AAGpC,IAAM,QAAQ,MAAM;AAClB,MAAI,OAAO,OAAO,kBAAkB,YAAY;AAC9C,WAAO,cAAc;AAAA,EACvB,WAAW,OAAO,YAAY;AAC5B,YAAQ,MAAM,wCAAwC;AAAA,EACxD;AACF;AAEA,IAAI,SAAS,eAAe,WAAW;AACrC,WAAS,iBAAiB,oBAAoB,KAAK;AACrD,OAAO;AACL,QAAM;AACR;", + "sourcesContent": ["class EnhancedSecureCryptoUtils {\n\n static _keyMetadata = new WeakMap();\n \n // Initialize secure logging system after class definition\n\n // Utility to sort object keys for deterministic serialization\n static sortObjectKeys(obj) {\n if (typeof obj !== 'object' || obj === null) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(EnhancedSecureCryptoUtils.sortObjectKeys);\n }\n\n const sortedObj = {};\n Object.keys(obj).sort().forEach(key => {\n sortedObj[key] = EnhancedSecureCryptoUtils.sortObjectKeys(obj[key]);\n });\n return sortedObj;\n }\n\n // Utility to assert CryptoKey type and properties\n static assertCryptoKey(key, expectedName = null, expectedUsages = []) {\n if (!(key instanceof CryptoKey)) throw new Error('Expected CryptoKey');\n if (expectedName && key.algorithm?.name !== expectedName) {\n throw new Error(`Expected algorithm ${expectedName}, got ${key.algorithm?.name}`);\n }\n for (const u of expectedUsages) {\n if (!key.usages || !key.usages.includes(u)) {\n throw new Error(`Missing required key usage: ${u}`);\n }\n }\n }\n // Helper function to convert ArrayBuffer to Base64\n static arrayBufferToBase64(buffer) {\n let binary = '';\n const bytes = new Uint8Array(buffer);\n const len = bytes.byteLength;\n for (let i = 0; i < len; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n }\n\n // Helper function to convert Base64 to ArrayBuffer\n static base64ToArrayBuffer(base64) {\n try {\n // Validate input\n if (typeof base64 !== 'string' || !base64) {\n throw new Error('Invalid base64 input: must be a non-empty string');\n }\n\n // Remove any whitespace and validate base64 format\n const cleanBase64 = base64.trim();\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(cleanBase64)) {\n throw new Error('Invalid base64 format');\n }\n\n // Handle empty string case\n if (cleanBase64 === '') {\n return new ArrayBuffer(0);\n }\n\n const binaryString = atob(cleanBase64);\n const len = binaryString.length;\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes.buffer;\n } catch (error) {\n console.error('Base64 to ArrayBuffer conversion failed:', error.message);\n throw new Error(`Base64 conversion error: ${error.message}`);\n }\n }\n\n // Helper function to convert hex string to Uint8Array\n static hexToUint8Array(hexString) {\n try {\n if (!hexString || typeof hexString !== 'string') {\n throw new Error('Invalid hex string input: must be a non-empty string');\n }\n\n // Remove colons and spaces from hex string (e.g., \"aa:bb:cc\" -> \"aabbcc\")\n const cleanHex = hexString.replace(/:/g, '').replace(/\\s/g, '');\n \n // Validate hex format\n if (!/^[0-9a-fA-F]*$/.test(cleanHex)) {\n throw new Error('Invalid hex format: contains non-hex characters');\n }\n \n // Ensure even length\n if (cleanHex.length % 2 !== 0) {\n throw new Error('Invalid hex format: odd length');\n }\n\n // Convert hex string to bytes\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = parseInt(cleanHex.substr(i, 2), 16);\n }\n \n return bytes;\n } catch (error) {\n console.error('Hex to Uint8Array conversion failed:', error.message);\n throw new Error(`Hex conversion error: ${error.message}`);\n }\n }\n\n static async encryptData(data, password) {\n try {\n const dataString = typeof data === 'string' ? data : JSON.stringify(data);\n const salt = crypto.getRandomValues(new Uint8Array(16));\n const encoder = new TextEncoder();\n const passwordBuffer = encoder.encode(password);\n\n const keyMaterial = await crypto.subtle.importKey(\n 'raw',\n passwordBuffer,\n { name: 'PBKDF2' },\n false,\n ['deriveKey']\n );\n\n const key = await crypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt: salt,\n iterations: 100000,\n hash: 'SHA-256',\n },\n keyMaterial,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt']\n );\n\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const dataBuffer = encoder.encode(dataString);\n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: iv },\n key,\n dataBuffer\n );\n\n const encryptedPackage = {\n version: '1.0',\n salt: Array.from(salt),\n iv: Array.from(iv),\n data: Array.from(new Uint8Array(encrypted)),\n timestamp: Date.now(),\n };\n\n const packageString = JSON.stringify(encryptedPackage);\n return EnhancedSecureCryptoUtils.arrayBufferToBase64(new TextEncoder().encode(packageString).buffer);\n\n } catch (error) {\n console.error('Encryption failed:', error.message);\n throw new Error(`Encryption error: ${error.message}`);\n }\n }\n\n static async decryptData(encryptedData, password) {\n try {\n const packageBuffer = EnhancedSecureCryptoUtils.base64ToArrayBuffer(encryptedData);\n const packageString = new TextDecoder().decode(packageBuffer);\n const encryptedPackage = JSON.parse(packageString);\n\n if (!encryptedPackage.version || !encryptedPackage.salt || !encryptedPackage.iv || !encryptedPackage.data) {\n throw new Error('Invalid encrypted data format');\n }\n\n const salt = new Uint8Array(encryptedPackage.salt);\n const iv = new Uint8Array(encryptedPackage.iv);\n const encrypted = new Uint8Array(encryptedPackage.data);\n\n const encoder = new TextEncoder();\n const passwordBuffer = encoder.encode(password);\n\n const keyMaterial = await crypto.subtle.importKey(\n 'raw',\n passwordBuffer,\n { name: 'PBKDF2' },\n false,\n ['deriveKey']\n );\n\n const key = await crypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt: salt,\n iterations: 100000,\n hash: 'SHA-256'\n },\n keyMaterial,\n { name: 'AES-GCM', length: 256 },\n false,\n ['decrypt']\n );\n\n const decrypted = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv },\n key,\n encrypted\n );\n\n const decryptedString = new TextDecoder().decode(decrypted);\n\n try {\n return JSON.parse(decryptedString);\n } catch {\n return decryptedString;\n }\n\n } catch (error) {\n console.error('Decryption failed:', error.message);\n throw new Error(`Decryption error: ${error.message}`);\n }\n }\n\n \n // Generate secure password for data exchange\n static generateSecurePassword() {\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;:,.<>?';\n const length = 32; \n const randomValues = new Uint32Array(length);\n crypto.getRandomValues(randomValues);\n \n let password = '';\n for (let i = 0; i < length; i++) {\n password += chars[randomValues[i] % chars.length];\n }\n return password;\n }\n\n // Real security level calculation with actual verification\n static async calculateSecurityLevel(securityManager) {\n let score = 0;\n const maxScore = 100; // Fixed: Changed from 110 to 100 for cleaner percentage\n const verificationResults = {};\n \n try {\n // Fallback to basic calculation if securityManager is not fully initialized\n if (!securityManager || !securityManager.securityFeatures) {\n console.warn('Security manager not fully initialized, using fallback calculation');\n return {\n level: 'INITIALIZING',\n score: 0,\n color: 'gray',\n verificationResults: {},\n timestamp: Date.now(),\n details: 'Security system initializing...',\n isRealData: false\n };\n }\n\n // Check session type to determine available features\n const sessionType = securityManager.currentSessionType || 'demo';\n const isDemoSession = sessionType === 'demo';\n \n // 1. Base encryption verification (20 points) - Available in demo\n try {\n if (await EnhancedSecureCryptoUtils.verifyEncryption(securityManager)) {\n score += 20;\n verificationResults.encryption = { passed: true, details: 'AES-GCM encryption verified', points: 20 };\n } else {\n verificationResults.encryption = { passed: false, details: 'Encryption not working', points: 0 };\n }\n } catch (error) {\n verificationResults.encryption = { passed: false, details: `Encryption check failed: ${error.message}`, points: 0 };\n }\n \n // 2. Simple key exchange verification (15 points) - Available in demo\n try {\n if (await EnhancedSecureCryptoUtils.verifyECDHKeyExchange(securityManager)) {\n score += 15;\n verificationResults.keyExchange = { passed: true, details: 'Simple key exchange verified', points: 15 };\n } else {\n verificationResults.keyExchange = { passed: false, details: 'Key exchange failed', points: 0 };\n }\n } catch (error) {\n verificationResults.keyExchange = { passed: false, details: `Key exchange check failed: ${error.message}`, points: 0 };\n }\n \n // 3. Message integrity verification (10 points) - Available in demo\n if (await EnhancedSecureCryptoUtils.verifyMessageIntegrity(securityManager)) {\n score += 10;\n verificationResults.messageIntegrity = { passed: true, details: 'Message integrity verified', points: 10 };\n } else {\n verificationResults.messageIntegrity = { passed: false, details: 'Message integrity failed', points: 0 };\n }\n \n // 4. Rate limiting verification (5 points) - Available in demo\n if (await EnhancedSecureCryptoUtils.verifyRateLimiting(securityManager)) {\n score += 5;\n verificationResults.rateLimiting = { passed: true, details: 'Rate limiting active', points: 5 };\n } else {\n verificationResults.rateLimiting = { passed: false, details: 'Rate limiting not working', points: 0 };\n }\n \n // 5. ECDSA signatures verification (15 points) - Only for enhanced sessions\n if (!isDemoSession && await EnhancedSecureCryptoUtils.verifyECDSASignatures(securityManager)) {\n score += 15;\n verificationResults.ecdsa = { passed: true, details: 'ECDSA signatures verified', points: 15 };\n } else {\n const reason = isDemoSession ? 'Enhanced session required - feature not available' : 'ECDSA signatures failed';\n verificationResults.ecdsa = { passed: false, details: reason, points: 0 };\n }\n \n // 6. Metadata protection verification (10 points) - Only for enhanced sessions\n if (!isDemoSession && await EnhancedSecureCryptoUtils.verifyMetadataProtection(securityManager)) {\n score += 10;\n verificationResults.metadataProtection = { passed: true, details: 'Metadata protection verified', points: 10 };\n } else {\n const reason = isDemoSession ? 'Enhanced session required - feature not available' : 'Metadata protection failed';\n verificationResults.metadataProtection = { passed: false, details: reason, points: 0 };\n }\n \n // 7. Perfect Forward Secrecy verification (10 points) - Only for enhanced sessions\n if (!isDemoSession && await EnhancedSecureCryptoUtils.verifyPFS(securityManager)) {\n score += 10;\n verificationResults.pfs = { passed: true, details: 'Perfect Forward Secrecy active', points: 10 };\n } else {\n const reason = isDemoSession ? 'Enhanced session required - feature not available' : 'PFS not active';\n verificationResults.pfs = { passed: false, details: reason, points: 0 };\n }\n \n // 8. Nested encryption verification (5 points) - Only for enhanced sessions\n if (!isDemoSession && await EnhancedSecureCryptoUtils.verifyNestedEncryption(securityManager)) {\n score += 5;\n verificationResults.nestedEncryption = { passed: true, details: 'Nested encryption active', points: 5 };\n } else {\n const reason = isDemoSession ? 'Enhanced session required - feature not available' : 'Nested encryption failed';\n verificationResults.nestedEncryption = { passed: false, details: reason, points: 0 };\n }\n \n // 9. Packet padding verification (5 points) - Only for enhanced sessions\n if (!isDemoSession && await EnhancedSecureCryptoUtils.verifyPacketPadding(securityManager)) {\n score += 5;\n verificationResults.packetPadding = { passed: true, details: 'Packet padding active', points: 5 };\n } else {\n const reason = isDemoSession ? 'Enhanced session required - feature not available' : 'Packet padding failed';\n verificationResults.packetPadding = { passed: false, details: reason, points: 0 };\n }\n \n // 10. Advanced features verification (10 points) - Only for premium sessions\n if (sessionType === 'premium' && await EnhancedSecureCryptoUtils.verifyAdvancedFeatures(securityManager)) {\n score += 10;\n verificationResults.advancedFeatures = { passed: true, details: 'Advanced features active', points: 10 };\n } else {\n const reason = sessionType === 'demo' ? 'Premium session required - feature not available' : \n sessionType === 'basic' ? 'Premium session required - feature not available' : 'Advanced features failed';\n verificationResults.advancedFeatures = { passed: false, details: reason, points: 0 };\n }\n \n const percentage = Math.round((score / maxScore) * 100);\n \n // Calculate available checks based on session type\n const availableChecks = isDemoSession ? 4 : 10; // Demo: encryption(20) + key exchange(15) + message integrity(10) + rate limiting(5) = 50 points\n const passedChecks = Object.values(verificationResults).filter(r => r.passed).length;\n \n const result = {\n level: percentage >= 85 ? 'HIGH' : percentage >= 65 ? 'MEDIUM' : percentage >= 35 ? 'LOW' : 'CRITICAL',\n score: percentage,\n color: percentage >= 85 ? 'green' : percentage >= 65 ? 'orange' : percentage >= 35 ? 'yellow' : 'red',\n verificationResults,\n timestamp: Date.now(),\n details: `Real verification: ${score}/${maxScore} security checks passed (${passedChecks}/${availableChecks} available)`,\n isRealData: true,\n passedChecks: passedChecks,\n totalChecks: availableChecks,\n sessionType: sessionType,\n maxPossibleScore: isDemoSession ? 50 : 100 // Demo sessions can only get max 50 points (4 checks)\n };\n \n console.log('Real security level calculated:', {\n score: percentage,\n level: result.level,\n passedChecks: passedChecks,\n totalChecks: availableChecks,\n sessionType: sessionType,\n maxPossibleScore: result.maxPossibleScore\n });\n \n return result;\n } catch (error) {\n console.error('Security level calculation failed:', error.message);\n return {\n level: 'UNKNOWN',\n score: 0,\n color: 'red',\n verificationResults: {},\n timestamp: Date.now(),\n details: `Verification failed: ${error.message}`,\n isRealData: false\n };\n }\n }\n\n // Real verification functions\n static async verifyEncryption(securityManager) {\n try {\n if (!securityManager.encryptionKey) return false;\n \n // Test actual encryption/decryption\n const testData = 'Test encryption verification';\n const encoder = new TextEncoder();\n const testBuffer = encoder.encode(testData);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n \n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n securityManager.encryptionKey,\n testBuffer\n );\n \n const decrypted = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv },\n securityManager.encryptionKey,\n encrypted\n );\n \n const decryptedText = new TextDecoder().decode(decrypted);\n return decryptedText === testData;\n } catch (error) {\n console.error('Encryption verification failed:', error.message);\n return false;\n }\n }\n \n static async verifyECDHKeyExchange(securityManager) {\n try {\n if (!securityManager.ecdhKeyPair || !securityManager.ecdhKeyPair.privateKey || !securityManager.ecdhKeyPair.publicKey) {\n return false;\n }\n \n // Test that keys are actually ECDH keys\n const keyType = securityManager.ecdhKeyPair.privateKey.algorithm.name;\n const curve = securityManager.ecdhKeyPair.privateKey.algorithm.namedCurve;\n \n return keyType === 'ECDH' && (curve === 'P-384' || curve === 'P-256');\n } catch (error) {\n console.error('ECDH verification failed:', error.message);\n return false;\n }\n }\n \n static async verifyECDSASignatures(securityManager) {\n try {\n if (!securityManager.ecdsaKeyPair || !securityManager.ecdsaKeyPair.privateKey || !securityManager.ecdsaKeyPair.publicKey) {\n return false;\n }\n \n // Test actual signing and verification\n const testData = 'Test ECDSA signature verification';\n const encoder = new TextEncoder();\n const testBuffer = encoder.encode(testData);\n \n const signature = await crypto.subtle.sign(\n { name: 'ECDSA', hash: 'SHA-256' },\n securityManager.ecdsaKeyPair.privateKey,\n testBuffer\n );\n \n const isValid = await crypto.subtle.verify(\n { name: 'ECDSA', hash: 'SHA-256' },\n securityManager.ecdsaKeyPair.publicKey,\n signature,\n testBuffer\n );\n \n return isValid;\n } catch (error) {\n console.error('ECDSA verification failed:', error.message);\n return false;\n }\n }\n \n static async verifyMessageIntegrity(securityManager) {\n try {\n // Check if macKey exists and is a valid CryptoKey\n if (!securityManager.macKey || !(securityManager.macKey instanceof CryptoKey)) {\n console.warn('MAC key not available or invalid for message integrity verification');\n return false;\n }\n \n // Test message integrity with HMAC\n const testData = 'Test message integrity verification';\n const encoder = new TextEncoder();\n const testBuffer = encoder.encode(testData);\n \n const hmac = await crypto.subtle.sign(\n { name: 'HMAC', hash: 'SHA-256' },\n securityManager.macKey,\n testBuffer\n );\n \n const isValid = await crypto.subtle.verify(\n { name: 'HMAC', hash: 'SHA-256' },\n securityManager.macKey,\n hmac,\n testBuffer\n );\n \n return isValid;\n } catch (error) {\n console.error('Message integrity verification failed:', error.message);\n return false;\n }\n }\n \n static async verifyNestedEncryption(securityManager) {\n try {\n // Check if nestedEncryptionKey exists and is a valid CryptoKey\n if (!securityManager.nestedEncryptionKey || !(securityManager.nestedEncryptionKey instanceof CryptoKey)) {\n console.warn('Nested encryption key not available or invalid');\n return false;\n }\n \n // Test nested encryption\n const testData = 'Test nested encryption verification';\n const encoder = new TextEncoder();\n const testBuffer = encoder.encode(testData);\n \n // Simulate nested encryption\n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: crypto.getRandomValues(new Uint8Array(12)) },\n securityManager.nestedEncryptionKey,\n testBuffer\n );\n \n return encrypted && encrypted.byteLength > 0;\n } catch (error) {\n console.error('Nested encryption verification failed:', error.message);\n return false;\n }\n }\n \n static async verifyPacketPadding(securityManager) {\n try {\n if (!securityManager.paddingConfig || !securityManager.paddingConfig.enabled) return false;\n \n // Test packet padding functionality\n const testData = 'Test packet padding verification';\n const encoder = new TextEncoder();\n const testBuffer = encoder.encode(testData);\n \n // Simulate packet padding\n const paddingSize = Math.floor(Math.random() * (securityManager.paddingConfig.maxPadding - securityManager.paddingConfig.minPadding)) + securityManager.paddingConfig.minPadding;\n const paddedData = new Uint8Array(testBuffer.byteLength + paddingSize);\n paddedData.set(new Uint8Array(testBuffer), 0);\n \n return paddedData.byteLength >= testBuffer.byteLength + securityManager.paddingConfig.minPadding;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Packet padding verification failed', { error: error.message });\n return false;\n }\n }\n \n static async verifyAdvancedFeatures(securityManager) {\n try {\n // Test advanced features like traffic obfuscation, fake traffic, etc.\n const hasFakeTraffic = securityManager.fakeTrafficConfig && securityManager.fakeTrafficConfig.enabled;\n const hasDecoyChannels = securityManager.decoyChannelsConfig && securityManager.decoyChannelsConfig.enabled;\n const hasAntiFingerprinting = securityManager.antiFingerprintingConfig && securityManager.antiFingerprintingConfig.enabled;\n \n return hasFakeTraffic || hasDecoyChannels || hasAntiFingerprinting;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Advanced features verification failed', { error: error.message });\n return false;\n }\n }\n \n static async verifyMutualAuth(securityManager) {\n try {\n if (!securityManager.isVerified || !securityManager.verificationCode) return false;\n \n // Test mutual authentication\n return securityManager.isVerified && securityManager.verificationCode.length > 0;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Mutual auth verification failed', { error: error.message });\n return false;\n }\n }\n \n static async verifyMetadataProtection(securityManager) {\n try {\n if (!securityManager.metadataKey) return false;\n \n // Test metadata protection\n const testData = 'Test metadata protection verification';\n const encoder = new TextEncoder();\n const testBuffer = encoder.encode(testData);\n \n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: crypto.getRandomValues(new Uint8Array(12)) },\n securityManager.metadataKey,\n testBuffer\n );\n \n return encrypted && encrypted.byteLength > 0;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Metadata protection verification failed', { error: error.message });\n return false;\n }\n }\n \n static async verifyReplayProtection(securityManager) {\n try {\n if (!securityManager.processedMessageIds || !securityManager.sequenceNumber) return false;\n \n // Test replay protection\n const testId = Date.now().toString();\n if (securityManager.processedMessageIds.has(testId)) return false;\n \n securityManager.processedMessageIds.add(testId);\n return true;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Replay protection verification failed', { error: error.message });\n return false;\n }\n }\n \n static async verifyNonExtractableKeys(securityManager) {\n try {\n if (!securityManager.encryptionKey) return false;\n \n // Test if keys are non-extractable\n const keyData = await crypto.subtle.exportKey('raw', securityManager.encryptionKey);\n return keyData && keyData.byteLength > 0;\n } catch (error) {\n // If export fails, keys are non-extractable (which is good)\n return true;\n }\n }\n \n static async verifyEnhancedValidation(securityManager) {\n try {\n if (!securityManager.securityFeatures) return false;\n \n // Test enhanced validation features\n const hasValidation = securityManager.securityFeatures.hasEnhancedValidation || \n securityManager.securityFeatures.hasEnhancedReplayProtection;\n \n return hasValidation;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Enhanced validation verification failed', { error: error.message });\n return false;\n }\n }\n \n static async verifyRateLimiting(securityManager) {\n try {\n const testId = 'test_' + Date.now();\n const canProceed = await EnhancedSecureCryptoUtils.rateLimiter.checkMessageRate(testId, 1, 60000);\n \n return securityManager.rateLimiterId && \n EnhancedSecureCryptoUtils.rateLimiter &&\n typeof EnhancedSecureCryptoUtils.rateLimiter.checkMessageRate === 'function' &&\n canProceed === true;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Rate limiting verification failed', { error: error.message });\n return false;\n }\n }\n \n static async verifyPFS(securityManager) {\n try {\n // Check if PFS is active\n return securityManager.securityFeatures &&\n securityManager.securityFeatures.hasPFS === true &&\n securityManager.keyRotationInterval &&\n securityManager.currentKeyVersion !== undefined &&\n securityManager.keyVersions &&\n securityManager.keyVersions instanceof Map;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'PFS verification failed', { error: error.message });\n return false;\n }\n }\n\n // Rate limiting implementation\n static rateLimiter = {\n messages: new Map(),\n connections: new Map(),\n locks: new Map(),\n \n async checkMessageRate(identifier, limit = 60, windowMs = 60000) {\n if (typeof identifier !== 'string' || identifier.length > 256) {\n return false;\n }\n \n const key = `msg_${identifier}`;\n\n if (this.locks.has(key)) {\n\n await new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * 10) + 5));\n return this.checkMessageRate(identifier, limit, windowMs);\n }\n \n this.locks.set(key, true);\n \n try {\n const now = Date.now();\n \n if (!this.messages.has(key)) {\n this.messages.set(key, []);\n }\n \n const timestamps = this.messages.get(key);\n \n const validTimestamps = timestamps.filter(ts => now - ts < windowMs);\n \n if (validTimestamps.length >= limit) {\n return false; \n }\n \n validTimestamps.push(now);\n this.messages.set(key, validTimestamps);\n return true;\n } finally {\n this.locks.delete(key);\n }\n },\n \n async checkConnectionRate(identifier, limit = 5, windowMs = 300000) {\n if (typeof identifier !== 'string' || identifier.length > 256) {\n return false;\n }\n \n const key = `conn_${identifier}`;\n \n if (this.locks.has(key)) {\n await new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * 10) + 5));\n return this.checkConnectionRate(identifier, limit, windowMs);\n }\n \n this.locks.set(key, true);\n \n try {\n const now = Date.now();\n \n if (!this.connections.has(key)) {\n this.connections.set(key, []);\n }\n \n const timestamps = this.connections.get(key);\n const validTimestamps = timestamps.filter(ts => now - ts < windowMs);\n \n if (validTimestamps.length >= limit) {\n return false;\n }\n \n validTimestamps.push(now);\n this.connections.set(key, validTimestamps);\n return true;\n } finally {\n this.locks.delete(key);\n }\n },\n \n cleanup() {\n const now = Date.now();\n const maxAge = 3600000; \n \n for (const [key, timestamps] of this.messages.entries()) {\n if (this.locks.has(key)) continue;\n \n const valid = timestamps.filter(ts => now - ts < maxAge);\n if (valid.length === 0) {\n this.messages.delete(key);\n } else {\n this.messages.set(key, valid);\n }\n }\n \n for (const [key, timestamps] of this.connections.entries()) {\n if (this.locks.has(key)) continue;\n \n const valid = timestamps.filter(ts => now - ts < maxAge);\n if (valid.length === 0) {\n this.connections.delete(key);\n } else {\n this.connections.set(key, valid);\n }\n }\n\n for (const lockKey of this.locks.keys()) {\n const keyTimestamp = parseInt(lockKey.split('_').pop()) || 0;\n if (now - keyTimestamp > 30000) {\n this.locks.delete(lockKey);\n }\n }\n }\n};\n\n static validateSalt(salt) {\n if (!salt || salt.length !== 64) {\n throw new Error('Salt must be exactly 64 bytes');\n }\n \n const uniqueBytes = new Set(salt);\n if (uniqueBytes.size < 16) {\n throw new Error('Salt has insufficient entropy');\n }\n \n return true;\n }\n\n // Secure logging without data leaks\n static secureLog = {\n logs: [],\n maxLogs: 100,\n isProductionMode: false,\n \n // Initialize production mode detection\n init() {\n this.isProductionMode = this._detectProductionMode();\n if (this.isProductionMode) {\n console.log('[SecureChat] Production mode detected - sensitive logging disabled');\n }\n },\n \n _detectProductionMode() {\n return (\n (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production') ||\n (!window.DEBUG_MODE && !window.DEVELOPMENT_MODE) ||\n (window.location.hostname && !window.location.hostname.includes('localhost') && \n !window.location.hostname.includes('127.0.0.1') && \n !window.location.hostname.includes('.local')) ||\n (typeof window.webpackHotUpdate === 'undefined' && !window.location.search.includes('debug'))\n );\n },\n \n log(level, message, context = {}) {\n const sanitizedContext = this.sanitizeContext(context);\n const logEntry = {\n timestamp: Date.now(),\n level,\n message,\n context: sanitizedContext,\n id: crypto.getRandomValues(new Uint32Array(1))[0]\n };\n \n this.logs.push(logEntry);\n \n // Keep only recent logs\n if (this.logs.length > this.maxLogs) {\n this.logs = this.logs.slice(-this.maxLogs);\n }\n \n // Production-safe console output\n if (this.isProductionMode) {\n if (level === 'error') {\n // \u0412 production \u043F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u043C \u0442\u043E\u043B\u044C\u043A\u043E \u043A\u043E\u0434 \u043E\u0448\u0438\u0431\u043A\u0438 \u0431\u0435\u0437 \u0434\u0435\u0442\u0430\u043B\u0435\u0439\n console.error(`\u274C [SecureChat] ${message} [ERROR_CODE: ${this._generateErrorCode(message)}]`);\n } else if (level === 'warn') {\n // \u0412 production \u043F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u043C \u0442\u043E\u043B\u044C\u043A\u043E \u043F\u0440\u0435\u0434\u0443\u043F\u0440\u0435\u0436\u0434\u0435\u043D\u0438\u0435 \u0431\u0435\u0437 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430\n console.warn(`\u26A0\uFE0F [SecureChat] ${message}`);\n } else {\n // \u0412 production \u043D\u0435 \u043F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u043C info/debug \u043B\u043E\u0433\u0438\n return;\n }\n } else {\n // Development mode - \u043F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u043C \u0432\u0441\u0435\n if (level === 'error') {\n console.error(`\u274C [SecureChat] ${message}`, { errorType: sanitizedContext?.constructor?.name || 'Unknown' });\n } else if (level === 'warn') {\n console.warn(`\u26A0\uFE0F [SecureChat] ${message}`, { details: sanitizedContext });\n } else {\n console.log(`[SecureChat] ${message}`, sanitizedContext);\n }\n }\n },\n \n // \u0413\u0435\u043D\u0435\u0440\u0438\u0440\u0443\u0435\u0442 \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u044B\u0439 \u043A\u043E\u0434 \u043E\u0448\u0438\u0431\u043A\u0438 \u0434\u043B\u044F production\n _generateErrorCode(message) {\n const hash = message.split('').reduce((a, b) => {\n a = ((a << 5) - a) + b.charCodeAt(0);\n return a & a;\n }, 0);\n return Math.abs(hash).toString(36).substring(0, 6).toUpperCase();\n },\n \n sanitizeContext(context) {\n if (!context || typeof context !== 'object') {\n return context;\n }\n \n const sensitivePatterns = [\n /key/i, /secret/i, /password/i, /token/i, /signature/i,\n /challenge/i, /proof/i, /salt/i, /iv/i, /nonce/i, /hash/i,\n /fingerprint/i, /mac/i, /private/i, /encryption/i, /decryption/i\n ];\n \n const sanitized = {};\n for (const [key, value] of Object.entries(context)) {\n const isSensitive = sensitivePatterns.some(pattern => \n pattern.test(key) || (typeof value === 'string' && pattern.test(value))\n );\n \n if (isSensitive) {\n sanitized[key] = '[REDACTED]';\n } else if (typeof value === 'string' && value.length > 100) {\n sanitized[key] = value.substring(0, 100) + '...[TRUNCATED]';\n } else if (value instanceof ArrayBuffer || value instanceof Uint8Array) {\n sanitized[key] = `[${value.constructor.name}(${value.byteLength || value.length} bytes)]`;\n } else if (value && typeof value === 'object' && !Array.isArray(value)) {\n // \u0420\u0435\u043A\u0443\u0440\u0441\u0438\u0432\u043D\u0430\u044F \u0441\u0430\u043D\u0438\u0442\u0438\u0437\u0430\u0446\u0438\u044F \u0434\u043B\u044F \u043E\u0431\u044A\u0435\u043A\u0442\u043E\u0432\n sanitized[key] = this.sanitizeContext(value);\n } else {\n sanitized[key] = value;\n }\n }\n return sanitized;\n },\n \n getLogs(level = null) {\n if (level) {\n return this.logs.filter(log => log.level === level);\n }\n return [...this.logs];\n },\n \n clearLogs() {\n this.logs = [];\n },\n \n // \u041C\u0435\u0442\u043E\u0434 \u0434\u043B\u044F \u043E\u0442\u043F\u0440\u0430\u0432\u043A\u0438 \u043E\u0448\u0438\u0431\u043E\u043A \u043D\u0430 \u0441\u0435\u0440\u0432\u0435\u0440 \u0432 production\n async sendErrorToServer(errorCode, message, context = {}) {\n if (!this.isProductionMode) {\n return; // \u0412 development \u043D\u0435 \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C\n }\n \n try {\n // \u041E\u0442\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C \u0442\u043E\u043B\u044C\u043A\u043E \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u0443\u044E \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044E\n const safeErrorData = {\n errorCode,\n timestamp: Date.now(),\n userAgent: navigator.userAgent.substring(0, 100),\n url: window.location.href.substring(0, 100)\n };\n \n // \u0417\u0434\u0435\u0441\u044C \u043C\u043E\u0436\u043D\u043E \u0434\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u043E\u0442\u043F\u0440\u0430\u0432\u043A\u0443 \u043D\u0430 \u0441\u0435\u0440\u0432\u0435\u0440\n // await fetch('/api/error-log', { method: 'POST', body: JSON.stringify(safeErrorData) });\n \n if (window.DEBUG_MODE) {\n console.log('[SecureChat] Error logged to server:', safeErrorData);\n }\n } catch (e) {\n // \u041D\u0435 \u043B\u043E\u0433\u0438\u0440\u0443\u0435\u043C \u043E\u0448\u0438\u0431\u043A\u0438 \u043B\u043E\u0433\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F\n }\n }\n };\n\n // Generate ECDH key pair for secure key exchange (non-extractable) with fallback\n static async generateECDHKeyPair() {\n try {\n // Try P-384 first\n try {\n const keyPair = await crypto.subtle.generateKey(\n {\n name: 'ECDH',\n namedCurve: 'P-384'\n },\n false, // Non-extractable for enhanced security\n ['deriveKey']\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'ECDH key pair generated successfully (P-384)', {\n curve: 'P-384',\n extractable: false\n });\n \n return keyPair;\n } catch (p384Error) {\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'P-384 generation failed, trying P-256', { error: p384Error.message });\n \n // Fallback to P-256\n const keyPair = await crypto.subtle.generateKey(\n {\n name: 'ECDH',\n namedCurve: 'P-256'\n },\n false, // Non-extractable for enhanced security\n ['deriveKey']\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'ECDH key pair generated successfully (P-256 fallback)', {\n curve: 'P-256',\n extractable: false\n });\n \n return keyPair;\n }\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'ECDH key generation failed', { error: error.message });\n throw new Error('Failed to create keys for secure exchange');\n }\n }\n\n // Generate ECDSA key pair for digital signatures with fallback\n static async generateECDSAKeyPair() {\n try {\n // Try P-384 first\n try {\n const keyPair = await crypto.subtle.generateKey(\n {\n name: 'ECDSA',\n namedCurve: 'P-384'\n },\n false, // Non-extractable for enhanced security\n ['sign', 'verify']\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'ECDSA key pair generated successfully (P-384)', {\n curve: 'P-384',\n extractable: false\n });\n \n return keyPair;\n } catch (p384Error) {\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'P-384 generation failed, trying P-256', { error: p384Error.message });\n \n // Fallback to P-256\n const keyPair = await crypto.subtle.generateKey(\n {\n name: 'ECDSA',\n namedCurve: 'P-256'\n },\n false, // Non-extractable for enhanced security\n ['sign', 'verify']\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'ECDSA key pair generated successfully (P-256 fallback)', {\n curve: 'P-256',\n extractable: false\n });\n \n return keyPair;\n }\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'ECDSA key generation failed', { error: error.message });\n throw new Error('Failed to generate keys for digital signatures');\n }\n }\n\n // Sign data with ECDSA (P-384 or P-256)\n static async signData(privateKey, data) {\n try {\n const encoder = new TextEncoder();\n const dataBuffer = typeof data === 'string' ? encoder.encode(data) : data;\n \n // Try SHA-384 first, fallback to SHA-256\n try {\n const signature = await crypto.subtle.sign(\n {\n name: 'ECDSA',\n hash: 'SHA-384'\n },\n privateKey,\n dataBuffer\n );\n \n return Array.from(new Uint8Array(signature));\n } catch (sha384Error) {\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'SHA-384 signing failed, trying SHA-256', { error: sha384Error.message });\n \n const signature = await crypto.subtle.sign(\n {\n name: 'ECDSA',\n hash: 'SHA-256'\n },\n privateKey,\n dataBuffer\n );\n \n return Array.from(new Uint8Array(signature));\n }\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Data signing failed', { error: error.message });\n throw new Error('Failed to sign data');\n }\n }\n\n // Verify ECDSA signature (P-384 or P-256)\n static async verifySignature(publicKey, signature, data) {\n try {\n const encoder = new TextEncoder();\n const dataBuffer = typeof data === 'string' ? encoder.encode(data) : data;\n const signatureBuffer = new Uint8Array(signature);\n \n // Try SHA-384 first, fallback to SHA-256\n try {\n const isValid = await crypto.subtle.verify(\n {\n name: 'ECDSA',\n hash: 'SHA-384'\n },\n publicKey,\n signatureBuffer,\n dataBuffer\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Signature verification completed (SHA-384)', {\n isValid,\n dataSize: dataBuffer.length\n });\n \n return isValid;\n } catch (sha384Error) {\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'SHA-384 verification failed, trying SHA-256', { error: sha384Error.message });\n \n const isValid = await crypto.subtle.verify(\n {\n name: 'ECDSA',\n hash: 'SHA-256'\n },\n publicKey,\n signatureBuffer,\n dataBuffer\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Signature verification completed (SHA-256 fallback)', {\n isValid,\n dataSize: dataBuffer.length\n });\n \n return isValid;\n }\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Signature verification failed', { error: error.message });\n throw new Error('Failed to verify digital signature');\n }\n }\n\n // Enhanced DER/SPKI validation with full ASN.1 parsing\n static async validateKeyStructure(keyData, expectedAlgorithm = 'ECDH') {\n try {\n if (!Array.isArray(keyData) || keyData.length === 0) {\n throw new Error('Invalid key data format');\n }\n\n const keyBytes = new Uint8Array(keyData);\n\n // Size limits to prevent DoS\n if (keyBytes.length < 50) {\n throw new Error('Key data too short - invalid SPKI structure');\n }\n if (keyBytes.length > 2000) {\n throw new Error('Key data too long - possible attack');\n }\n\n // Parse ASN.1 DER structure\n const asn1 = EnhancedSecureCryptoUtils.parseASN1(keyBytes);\n \n // Validate SPKI structure\n if (!asn1 || asn1.tag !== 0x30) {\n throw new Error('Invalid SPKI structure - missing SEQUENCE tag');\n }\n\n // SPKI should have exactly 2 elements: AlgorithmIdentifier and BIT STRING\n if (asn1.children.length !== 2) {\n throw new Error(`Invalid SPKI structure - expected 2 elements, got ${asn1.children.length}`);\n }\n\n // Validate AlgorithmIdentifier\n const algIdentifier = asn1.children[0];\n if (algIdentifier.tag !== 0x30) {\n throw new Error('Invalid AlgorithmIdentifier - not a SEQUENCE');\n }\n\n // Parse algorithm OID\n const algOid = algIdentifier.children[0];\n if (algOid.tag !== 0x06) {\n throw new Error('Invalid algorithm OID - not an OBJECT IDENTIFIER');\n }\n\n // Validate algorithm OID based on expected algorithm\n const oidBytes = algOid.value;\n const oidString = EnhancedSecureCryptoUtils.oidToString(oidBytes);\n \n // Check for expected algorithms\n const validAlgorithms = {\n 'ECDH': ['1.2.840.10045.2.1'], // id-ecPublicKey\n 'ECDSA': ['1.2.840.10045.2.1'], // id-ecPublicKey (same as ECDH)\n 'RSA': ['1.2.840.113549.1.1.1'], // rsaEncryption\n 'AES-GCM': ['2.16.840.1.101.3.4.1.6', '2.16.840.1.101.3.4.1.46'] // AES-128-GCM, AES-256-GCM\n };\n\n const expectedOids = validAlgorithms[expectedAlgorithm];\n if (!expectedOids) {\n throw new Error(`Unknown algorithm: ${expectedAlgorithm}`);\n }\n\n if (!expectedOids.includes(oidString)) {\n throw new Error(`Invalid algorithm OID: expected ${expectedOids.join(' or ')}, got ${oidString}`);\n }\n\n // For EC algorithms, validate curve parameters\n if (expectedAlgorithm === 'ECDH' || expectedAlgorithm === 'ECDSA') {\n if (algIdentifier.children.length < 2) {\n throw new Error('Missing curve parameters for EC key');\n }\n\n const curveOid = algIdentifier.children[1];\n if (curveOid.tag !== 0x06) {\n throw new Error('Invalid curve OID - not an OBJECT IDENTIFIER');\n }\n\n const curveOidString = EnhancedSecureCryptoUtils.oidToString(curveOid.value);\n \n // Only allow P-256 and P-384 curves\n const validCurves = {\n '1.2.840.10045.3.1.7': 'P-256', // secp256r1\n '1.3.132.0.34': 'P-384' // secp384r1\n };\n\n if (!validCurves[curveOidString]) {\n throw new Error(`Invalid or unsupported curve OID: ${curveOidString}`);\n }\n\n EnhancedSecureCryptoUtils.secureLog.log('info', 'EC key curve validated', {\n curve: validCurves[curveOidString],\n oid: curveOidString\n });\n }\n\n // Validate public key BIT STRING\n const publicKeyBitString = asn1.children[1];\n if (publicKeyBitString.tag !== 0x03) {\n throw new Error('Invalid public key - not a BIT STRING');\n }\n\n // Check for unused bits (should be 0 for public keys)\n if (publicKeyBitString.value[0] !== 0x00) {\n throw new Error(`Invalid BIT STRING - unexpected unused bits: ${publicKeyBitString.value[0]}`);\n }\n\n // For EC keys, validate point format\n if (expectedAlgorithm === 'ECDH' || expectedAlgorithm === 'ECDSA') {\n const pointData = publicKeyBitString.value.slice(1); // Skip unused bits byte\n \n // Check for uncompressed point format (0x04)\n if (pointData[0] !== 0x04) {\n throw new Error(`Invalid EC point format: expected uncompressed (0x04), got 0x${pointData[0].toString(16)}`);\n }\n\n // Validate point size based on curve\n const expectedSizes = {\n 'P-256': 65, // 1 + 32 + 32\n 'P-384': 97 // 1 + 48 + 48\n };\n\n // We already validated the curve above, so we can determine expected size\n const curveOidString = EnhancedSecureCryptoUtils.oidToString(algIdentifier.children[1].value);\n const curveName = curveOidString === '1.2.840.10045.3.1.7' ? 'P-256' : 'P-384';\n const expectedSize = expectedSizes[curveName];\n\n if (pointData.length !== expectedSize) {\n throw new Error(`Invalid EC point size for ${curveName}: expected ${expectedSize}, got ${pointData.length}`);\n }\n }\n\n // Additional validation: try to import the key\n try {\n const algorithm = expectedAlgorithm === 'ECDSA' || expectedAlgorithm === 'ECDH'\n ? { name: expectedAlgorithm, namedCurve: 'P-384' }\n : { name: expectedAlgorithm };\n\n const usages = expectedAlgorithm === 'ECDSA' ? ['verify'] : [];\n \n await crypto.subtle.importKey('spki', keyBytes.buffer, algorithm, false, usages);\n } catch (importError) {\n // Try P-256 as fallback for EC keys\n if (expectedAlgorithm === 'ECDSA' || expectedAlgorithm === 'ECDH') {\n try {\n const algorithm = { name: expectedAlgorithm, namedCurve: 'P-256' };\n const usages = expectedAlgorithm === 'ECDSA' ? ['verify'] : [];\n await crypto.subtle.importKey('spki', keyBytes.buffer, algorithm, false, usages);\n } catch (fallbackError) {\n throw new Error(`Key import validation failed: ${fallbackError.message}`);\n }\n } else {\n throw new Error(`Key import validation failed: ${importError.message}`);\n }\n }\n\n EnhancedSecureCryptoUtils.secureLog.log('info', 'Key structure validation passed', {\n keyLen: keyBytes.length,\n algorithm: expectedAlgorithm,\n asn1Valid: true,\n oidValid: true,\n importValid: true\n });\n\n return true;\n } catch (err) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Key structure validation failed', {\n error: err.message,\n algorithm: expectedAlgorithm\n });\n throw new Error(`Invalid key structure: ${err.message}`);\n }\n }\n\n // ASN.1 DER parser helper\n static parseASN1(bytes, offset = 0) {\n if (offset >= bytes.length) {\n return null;\n }\n\n const tag = bytes[offset];\n let lengthOffset = offset + 1;\n \n if (lengthOffset >= bytes.length) {\n throw new Error('Truncated ASN.1 structure');\n }\n\n let length = bytes[lengthOffset];\n let valueOffset = lengthOffset + 1;\n\n // Handle long form length\n if (length & 0x80) {\n const numLengthBytes = length & 0x7f;\n if (numLengthBytes > 4) {\n throw new Error('ASN.1 length too large');\n }\n \n length = 0;\n for (let i = 0; i < numLengthBytes; i++) {\n if (valueOffset + i >= bytes.length) {\n throw new Error('Truncated ASN.1 length');\n }\n length = (length << 8) | bytes[valueOffset + i];\n }\n valueOffset += numLengthBytes;\n }\n\n if (valueOffset + length > bytes.length) {\n throw new Error('ASN.1 structure extends beyond data');\n }\n\n const value = bytes.slice(valueOffset, valueOffset + length);\n const node = {\n tag: tag,\n length: length,\n value: value,\n children: []\n };\n\n // Parse children for SEQUENCE and SET\n if (tag === 0x30 || tag === 0x31) {\n let childOffset = 0;\n while (childOffset < value.length) {\n const child = EnhancedSecureCryptoUtils.parseASN1(value, childOffset);\n if (!child) break;\n node.children.push(child);\n childOffset = childOffset + 1 + child.lengthBytes + child.length;\n }\n }\n\n // Calculate how many bytes were used for length encoding\n node.lengthBytes = valueOffset - lengthOffset;\n \n return node;\n }\n\n // OID decoder helper\n static oidToString(bytes) {\n if (!bytes || bytes.length === 0) {\n throw new Error('Empty OID');\n }\n\n const parts = [];\n \n // First byte encodes first two components\n const first = Math.floor(bytes[0] / 40);\n const second = bytes[0] % 40;\n parts.push(first);\n parts.push(second);\n\n // Decode remaining components\n let value = 0;\n for (let i = 1; i < bytes.length; i++) {\n value = (value << 7) | (bytes[i] & 0x7f);\n if (!(bytes[i] & 0x80)) {\n parts.push(value);\n value = 0;\n }\n }\n\n return parts.join('.');\n }\n\n // Helper to validate and sanitize OID string\n static validateOidString(oidString) {\n // OID format: digits separated by dots\n const oidRegex = /^[0-9]+(\\.[0-9]+)*$/;\n if (!oidRegex.test(oidString)) {\n throw new Error(`Invalid OID format: ${oidString}`);\n }\n\n const parts = oidString.split('.').map(Number);\n \n // First component must be 0, 1, or 2\n if (parts[0] > 2) {\n throw new Error(`Invalid OID first component: ${parts[0]}`);\n }\n\n // If first component is 0 or 1, second must be <= 39\n if ((parts[0] === 0 || parts[0] === 1) && parts[1] > 39) {\n throw new Error(`Invalid OID second component: ${parts[1]} (must be <= 39 for first component ${parts[0]})`);\n }\n\n return true;\n }\n\n // Export public key for transmission with signature \n static async exportPublicKeyWithSignature(publicKey, signingKey, keyType = 'ECDH') {\n try {\n // Validate key type\n if (!['ECDH', 'ECDSA'].includes(keyType)) {\n throw new Error('Invalid key type');\n }\n \n const exported = await crypto.subtle.exportKey('spki', publicKey);\n const keyData = Array.from(new Uint8Array(exported));\n \n await EnhancedSecureCryptoUtils.validateKeyStructure(keyData, keyType);\n \n // Create signed key package\n const keyPackage = {\n keyType,\n keyData,\n timestamp: Date.now(),\n version: '4.0'\n };\n \n // Sign the key package\n const packageString = JSON.stringify(keyPackage);\n const signature = await EnhancedSecureCryptoUtils.signData(signingKey, packageString);\n \n const signedPackage = {\n ...keyPackage,\n signature\n };\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Public key exported with signature', {\n keyType,\n keySize: keyData.length,\n signed: true\n });\n \n return signedPackage;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Public key export failed', {\n error: error.message,\n keyType\n });\n throw new Error(`Failed to export ${keyType} key: ${error.message}`);\n }\n }\n\n // Import and verify signed public key\n static async importSignedPublicKey(signedPackage, verifyingKey, expectedKeyType = 'ECDH') {\n try {\n // Validate package structure\n if (!signedPackage || typeof signedPackage !== 'object') {\n throw new Error('Invalid signed package format');\n }\n \n const { keyType, keyData, timestamp, version, signature } = signedPackage;\n \n if (!keyType || !keyData || !timestamp || !signature) {\n throw new Error('Missing required fields in signed package');\n }\n \n if (!EnhancedSecureCryptoUtils.constantTimeCompare(keyType, expectedKeyType)) {\n throw new Error(`Key type mismatch: expected ${expectedKeyType}, got ${keyType}`);\n }\n \n // Check timestamp (reject keys older than 1 hour)\n const keyAge = Date.now() - timestamp;\n if (keyAge > 3600000) {\n throw new Error('Signed key package is too old');\n }\n \n await EnhancedSecureCryptoUtils.validateKeyStructure(keyData, keyType);\n \n // Verify signature\n const packageCopy = { keyType, keyData, timestamp, version };\n const packageString = JSON.stringify(packageCopy);\n const isValidSignature = await EnhancedSecureCryptoUtils.verifySignature(verifyingKey, signature, packageString);\n \n if (!isValidSignature) {\n throw new Error('Invalid signature on key package - possible MITM attack');\n }\n \n // Import the key with fallback support\n const keyBytes = new Uint8Array(keyData);\n \n // Try P-384 first\n try {\n const algorithm = keyType === 'ECDH' ?\n { name: 'ECDH', namedCurve: 'P-384' }\n : { name: 'ECDSA', namedCurve: 'P-384' };\n \n const keyUsages = keyType === 'ECDH' ? [] : ['verify'];\n \n const publicKey = await crypto.subtle.importKey(\n 'spki',\n keyBytes,\n algorithm,\n false, // Non-extractable\n keyUsages\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Signed public key imported successfully (P-384)', {\n keyType,\n signatureValid: true,\n keyAge: Math.round(keyAge / 1000) + 's'\n });\n \n return publicKey;\n } catch (p384Error) {\n // Fallback to P-256\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'P-384 import failed, trying P-256', {\n error: p384Error.message\n });\n \n const algorithm = keyType === 'ECDH' ?\n { name: 'ECDH', namedCurve: 'P-256' }\n : { name: 'ECDSA', namedCurve: 'P-256' };\n \n const keyUsages = keyType === 'ECDH' ? [] : ['verify'];\n \n const publicKey = await crypto.subtle.importKey(\n 'spki',\n keyBytes,\n algorithm,\n false, // Non-extractable\n keyUsages\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Signed public key imported successfully (P-256 fallback)', {\n keyType,\n signatureValid: true,\n keyAge: Math.round(keyAge / 1000) + 's'\n });\n \n return publicKey;\n }\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Signed public key import failed', {\n error: error.message,\n expectedKeyType\n });\n throw new Error(`Failed to import the signed key: ${error.message}`);\n }\n }\n\n // Legacy export for backward compatibility\n static async exportPublicKey(publicKey) {\n try {\n const exported = await crypto.subtle.exportKey('spki', publicKey);\n const keyData = Array.from(new Uint8Array(exported));\n \n await EnhancedSecureCryptoUtils.validateKeyStructure(keyData, 'ECDH');\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Legacy public key exported', { keySize: keyData.length });\n return keyData;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Legacy public key export failed', { error: error.message });\n throw new Error('Failed to export the public key');\n }\n }\n\n // Legacy import for backward compatibility with fallback\n static async importPublicKey(keyData) {\n try {\n await EnhancedSecureCryptoUtils.validateKeyStructure(keyData, 'ECDH');\n \n const keyBytes = new Uint8Array(keyData);\n \n // Try P-384 first\n try {\n const publicKey = await crypto.subtle.importKey(\n 'spki',\n keyBytes,\n {\n name: 'ECDH',\n namedCurve: 'P-384'\n },\n false, // Non-extractable\n []\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Legacy public key imported (P-384)', { keySize: keyData.length });\n return publicKey;\n } catch (p384Error) {\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'P-384 import failed, trying P-256', { error: p384Error.message });\n \n // Fallback to P-256\n const publicKey = await crypto.subtle.importKey(\n 'spki',\n keyBytes,\n {\n name: 'ECDH',\n namedCurve: 'P-256'\n },\n false, // Non-extractable\n []\n );\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Legacy public key imported (P-256 fallback)', { keySize: keyData.length });\n return publicKey;\n }\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Legacy public key import failed', { error: error.message });\n throw new Error('Failed to import the public key');\n }\n }\n\n\n // Method to check if a key is trusted\n static isKeyTrusted(keyOrFingerprint) {\n if (keyOrFingerprint instanceof CryptoKey) {\n const meta = EnhancedSecureCryptoUtils._keyMetadata.get(keyOrFingerprint);\n return meta ? meta.trusted === true : false;\n } else if (keyOrFingerprint && keyOrFingerprint._securityMetadata) {\n // Check by key metadata\n return keyOrFingerprint._securityMetadata.trusted === true;\n }\n\n return false;\n }\n\n static async importPublicKeyFromSignedPackage(signedPackage, verifyingKey = null, options = {}) {\n try {\n if (!signedPackage || !signedPackage.keyData || !signedPackage.signature) {\n throw new Error('Invalid signed key package format');\n }\n\n // Validate all required fields are present\n const requiredFields = ['keyData', 'signature', 'keyType', 'timestamp', 'version'];\n const missingFields = requiredFields.filter(field => !signedPackage[field]);\n\n if (missingFields.length > 0) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Missing required fields in signed package', {\n missingFields: missingFields,\n availableFields: Object.keys(signedPackage)\n });\n throw new Error(`Required fields are missing in the signed package: ${missingFields.join(', ')}`);\n }\n\n // SECURITY ENHANCEMENT: MANDATORY signature verification for signed packages\n if (!verifyingKey) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'SECURITY VIOLATION: Signed package received without verifying key', {\n keyType: signedPackage.keyType,\n keySize: signedPackage.keyData.length,\n timestamp: signedPackage.timestamp,\n version: signedPackage.version,\n securityRisk: 'HIGH - Potential MITM attack vector'\n });\n\n // REJECT the signed package if no verifying key provided\n throw new Error('CRITICAL SECURITY ERROR: Signed key package received without a verification key. ' +\n 'This may indicate a possible MITM attack attempt. Import rejected for security reasons.');\n }\n\n // \u041E\u0411\u041D\u041E\u0412\u041B\u0415\u041D\u041E: \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u043C \u0443\u043B\u0443\u0447\u0448\u0435\u043D\u043D\u0443\u044E \u0432\u0430\u043B\u0438\u0434\u0430\u0446\u0438\u044E\n await EnhancedSecureCryptoUtils.validateKeyStructure(signedPackage.keyData, signedPackage.keyType || 'ECDH');\n\n // MANDATORY signature verification when verifyingKey is provided\n const packageCopy = { ...signedPackage };\n delete packageCopy.signature;\n const packageString = JSON.stringify(packageCopy);\n const isValidSignature = await EnhancedSecureCryptoUtils.verifySignature(verifyingKey, signedPackage.signature, packageString);\n\n if (!isValidSignature) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'SECURITY BREACH: Invalid signature detected - MITM attack prevented', {\n keyType: signedPackage.keyType,\n keySize: signedPackage.keyData.length,\n timestamp: signedPackage.timestamp,\n version: signedPackage.version,\n attackPrevented: true\n });\n throw new Error('CRITICAL SECURITY ERROR: Invalid key signature detected. ' +\n 'This indicates a possible MITM attack attempt. Key import rejected.');\n }\n\n // Additional MITM protection: Check for key reuse and suspicious patterns\n const keyFingerprint = await EnhancedSecureCryptoUtils.calculateKeyFingerprint(signedPackage.keyData);\n\n // Log successful verification with security details\n EnhancedSecureCryptoUtils.secureLog.log('info', 'SECURE: Signature verification passed for signed package', {\n keyType: signedPackage.keyType,\n keySize: signedPackage.keyData.length,\n timestamp: signedPackage.timestamp,\n version: signedPackage.version,\n signatureVerified: true,\n securityLevel: 'HIGH',\n keyFingerprint: keyFingerprint.substring(0, 8) // Only log first 8 chars for security\n });\n\n // Import the public key with fallback\n const keyBytes = new Uint8Array(signedPackage.keyData);\n const keyType = signedPackage.keyType || 'ECDH';\n\n // Try P-384 first\n try {\n const publicKey = await crypto.subtle.importKey(\n 'spki',\n keyBytes,\n {\n name: keyType,\n namedCurve: 'P-384'\n },\n false, // Non-extractable\n keyType === 'ECDSA' ? ['verify'] : []\n );\n\n // Use WeakMap to store metadata\n EnhancedSecureCryptoUtils._keyMetadata.set(publicKey, {\n trusted: true,\n verificationStatus: 'VERIFIED_SECURE',\n verificationTimestamp: Date.now()\n });\n\n return publicKey;\n } catch (p384Error) {\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'P-384 import failed, trying P-256', { error: p384Error.message });\n\n // Fallback to P-256\n const publicKey = await crypto.subtle.importKey(\n 'spki',\n keyBytes,\n {\n name: keyType,\n namedCurve: 'P-256'\n },\n false, // Non-extractable\n keyType === 'ECDSA' ? ['verify'] : []\n );\n\n // Use WeakMap to store metadata\n EnhancedSecureCryptoUtils._keyMetadata.set(publicKey, {\n trusted: true,\n verificationStatus: 'VERIFIED_SECURE',\n verificationTimestamp: Date.now()\n });\n\n return publicKey;\n }\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Signed package key import failed', {\n error: error.message,\n securityImplications: 'Potential security breach prevented'\n });\n throw new Error(`Failed to import the public key from the signed package: ${error.message}`);\n }\n }\n\n // Enhanced key derivation with metadata protection and 64-byte salt\n static async deriveSharedKeys(privateKey, publicKey, salt) {\n try {\n // Validate input parameters are CryptoKey instances\n if (!(privateKey instanceof CryptoKey)) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Private key is not a CryptoKey', {\n privateKeyType: typeof privateKey,\n privateKeyAlgorithm: privateKey?.algorithm?.name\n });\n throw new Error('The private key is not a valid CryptoKey.');\n }\n \n if (!(publicKey instanceof CryptoKey)) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Public key is not a CryptoKey', {\n publicKeyType: typeof publicKey,\n publicKeyAlgorithm: publicKey?.algorithm?.name\n });\n throw new Error('The private key is not a valid CryptoKey.');\n }\n \n // Validate salt size (should be 64 bytes for enhanced security)\n if (!salt || salt.length !== 64) {\n throw new Error('Salt must be exactly 64 bytes for enhanced security');\n }\n \n const saltBytes = new Uint8Array(salt);\n const encoder = new TextEncoder();\n \n // Enhanced context info with version and additional entropy\n const contextInfo = encoder.encode('SecureBit.chat v4.0 Enhanced Security Edition');\n \n // Derive master shared secret with enhanced parameters\n // Try SHA-384 first, fallback to SHA-256\n let sharedSecret;\n try {\n sharedSecret = await crypto.subtle.deriveKey(\n {\n name: 'ECDH',\n public: publicKey\n },\n privateKey,\n {\n name: 'HKDF',\n hash: 'SHA-384',\n salt: saltBytes,\n info: contextInfo\n },\n false, // Non-extractable\n ['deriveKey']\n );\n } catch (sha384Error) {\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'SHA-384 key derivation failed, trying SHA-256', { \n error: sha384Error.message,\n privateKeyType: typeof privateKey,\n publicKeyType: typeof publicKey,\n privateKeyAlgorithm: privateKey?.algorithm?.name,\n publicKeyAlgorithm: publicKey?.algorithm?.name\n });\n \n sharedSecret = await crypto.subtle.deriveKey(\n {\n name: 'ECDH',\n public: publicKey\n },\n privateKey,\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: saltBytes,\n info: contextInfo\n },\n false, // Non-extractable\n ['deriveKey']\n );\n }\n\n // Derive message encryption key with fallback\n let encryptionKey;\n try {\n encryptionKey = await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-384',\n salt: saltBytes,\n info: encoder.encode('message-encryption-v4')\n },\n sharedSecret,\n {\n name: 'AES-GCM',\n length: 256\n },\n false, // Non-extractable for enhanced security\n ['encrypt', 'decrypt']\n );\n } catch (sha384Error) {\n encryptionKey = await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: saltBytes,\n info: encoder.encode('message-encryption-v4')\n },\n sharedSecret,\n {\n name: 'AES-GCM',\n length: 256\n },\n false, // Non-extractable for enhanced security\n ['encrypt', 'decrypt']\n );\n }\n\n // Derive MAC key for message authentication with fallback\n let macKey;\n try {\n macKey = await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-384',\n salt: saltBytes,\n info: encoder.encode('message-authentication-v4')\n },\n sharedSecret,\n {\n name: 'HMAC',\n hash: 'SHA-384'\n },\n false, // Non-extractable\n ['sign', 'verify']\n );\n } catch (sha384Error) {\n macKey = await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: saltBytes,\n info: encoder.encode('message-authentication-v4')\n },\n sharedSecret,\n {\n name: 'HMAC',\n hash: 'SHA-256'\n },\n false, // Non-extractable\n ['sign', 'verify']\n );\n }\n\n // Derive separate metadata encryption key with fallback\n let metadataKey;\n try {\n metadataKey = await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-384',\n salt: saltBytes,\n info: encoder.encode('metadata-protection-v4')\n },\n sharedSecret,\n {\n name: 'AES-GCM',\n length: 256\n },\n false, // Non-extractable\n ['encrypt', 'decrypt']\n );\n } catch (sha384Error) {\n metadataKey = await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: saltBytes,\n info: encoder.encode('metadata-protection-v4')\n },\n sharedSecret,\n {\n name: 'AES-GCM',\n length: 256\n },\n false, // Non-extractable\n ['encrypt', 'decrypt']\n );\n }\n\n // Generate temporary extractable key for fingerprint calculation with fallback\n let fingerprintKey;\n try {\n fingerprintKey = await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-384',\n salt: saltBytes,\n info: encoder.encode('fingerprint-generation-v4')\n },\n sharedSecret,\n {\n name: 'AES-GCM',\n length: 256\n },\n true, // Extractable only for fingerprint\n ['encrypt', 'decrypt']\n );\n } catch (sha384Error) {\n fingerprintKey = await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: saltBytes,\n info: encoder.encode('fingerprint-generation-v4')\n },\n sharedSecret,\n {\n name: 'AES-GCM',\n length: 256\n },\n true, // Extractable only for fingerprint\n ['encrypt', 'decrypt']\n );\n }\n\n // Generate key fingerprint for verification\n const fingerprintKeyData = await crypto.subtle.exportKey('raw', fingerprintKey);\n const fingerprint = await EnhancedSecureCryptoUtils.generateKeyFingerprint(Array.from(new Uint8Array(fingerprintKeyData)));\n\n // Validate that all derived keys are CryptoKey instances\n if (!(encryptionKey instanceof CryptoKey)) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Derived encryption key is not a CryptoKey', {\n encryptionKeyType: typeof encryptionKey,\n encryptionKeyAlgorithm: encryptionKey?.algorithm?.name\n });\n throw new Error('The derived encryption key is not a valid CryptoKey.');\n }\n \n if (!(macKey instanceof CryptoKey)) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Derived MAC key is not a CryptoKey', {\n macKeyType: typeof macKey,\n macKeyAlgorithm: macKey?.algorithm?.name\n });\n throw new Error('The derived MAC key is not a valid CryptoKey.');\n }\n \n if (!(metadataKey instanceof CryptoKey)) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Derived metadata key is not a CryptoKey', {\n metadataKeyType: typeof metadataKey,\n metadataKeyAlgorithm: metadataKey?.algorithm?.name\n });\n throw new Error('The derived metadata key is not a valid CryptoKey.');\n }\n\n EnhancedSecureCryptoUtils.secureLog.log('info', 'Enhanced shared keys derived successfully', {\n saltSize: salt.length,\n hasMetadataKey: true,\n nonExtractable: true,\n version: '4.0',\n allKeysValid: true\n });\n\n return {\n encryptionKey,\n macKey,\n metadataKey,\n fingerprint,\n timestamp: Date.now(),\n version: '4.0'\n };\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Enhanced key derivation failed', { error: error.message });\n throw new Error(`Failed to create shared encryption keys: ${error.message}`);\n }\n }\n\n static async generateKeyFingerprint(keyData) {\n const keyBuffer = new Uint8Array(keyData);\n const hashBuffer = await crypto.subtle.digest('SHA-384', keyBuffer);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.slice(0, 12).map(b => b.toString(16).padStart(2, '0')).join(':');\n }\n\n // Generate mutual authentication challenge\n static generateMutualAuthChallenge() {\n const challenge = crypto.getRandomValues(new Uint8Array(48)); // Increased to 48 bytes\n const timestamp = Date.now();\n const nonce = crypto.getRandomValues(new Uint8Array(16));\n \n return {\n challenge: Array.from(challenge),\n timestamp,\n nonce: Array.from(nonce),\n version: '4.0'\n };\n }\n\n // Create cryptographic proof for mutual authentication\n static async createAuthProof(challenge, privateKey, publicKey) {\n try {\n if (!challenge || !challenge.challenge || !challenge.timestamp || !challenge.nonce) {\n throw new Error('Invalid challenge structure');\n }\n \n // Check challenge age (max 2 minutes)\n const challengeAge = Date.now() - challenge.timestamp;\n if (challengeAge > 120000) {\n throw new Error('Challenge expired');\n }\n \n // Create proof data\n const proofData = {\n challenge: challenge.challenge,\n timestamp: challenge.timestamp,\n nonce: challenge.nonce,\n responseTimestamp: Date.now(),\n publicKeyHash: await EnhancedSecureCryptoUtils.hashPublicKey(publicKey)\n };\n \n // Sign the proof\n const proofString = JSON.stringify(proofData);\n const signature = await EnhancedSecureCryptoUtils.signData(privateKey, proofString);\n \n const proof = {\n ...proofData,\n signature,\n version: '4.0'\n };\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Authentication proof created', {\n challengeAge: Math.round(challengeAge / 1000) + 's'\n });\n \n return proof;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Authentication proof creation failed', { error: error.message });\n throw new Error(`Failed to create cryptographic proof: ${error.message}`);\n }\n }\n\n // Verify mutual authentication proof\n static async verifyAuthProof(proof, challenge, publicKey) {\n try {\n await new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * 20) + 5));\n // Assert the public key is valid and has the correct usage\n EnhancedSecureCryptoUtils.assertCryptoKey(publicKey, 'ECDSA', ['verify']);\n\n if (!proof || !challenge || !publicKey) {\n throw new Error('Missing required parameters for proof verification');\n }\n\n // Validate proof structure\n const requiredFields = ['challenge', 'timestamp', 'nonce', 'responseTimestamp', 'publicKeyHash', 'signature'];\n for (const field of requiredFields) {\n if (!proof[field]) {\n throw new Error(`Missing required field: ${field}`);\n }\n }\n\n // Verify challenge matches\n if (!EnhancedSecureCryptoUtils.constantTimeCompareArrays(proof.challenge, challenge.challenge) ||\n proof.timestamp !== challenge.timestamp ||\n !EnhancedSecureCryptoUtils.constantTimeCompareArrays(proof.nonce, challenge.nonce)) {\n throw new Error('Challenge mismatch - possible replay attack');\n }\n\n // Check response time (max 5 minutes)\n const responseAge = Date.now() - proof.responseTimestamp;\n if (responseAge > 300000) {\n throw new Error('Proof response expired');\n }\n\n // Verify public key hash\n const expectedHash = await EnhancedSecureCryptoUtils.hashPublicKey(publicKey);\n if (!EnhancedSecureCryptoUtils.constantTimeCompare(proof.publicKeyHash, expectedHash)) {\n throw new Error('Public key hash mismatch');\n }\n\n // Verify signature\n const proofCopy = { ...proof };\n delete proofCopy.signature;\n const proofString = JSON.stringify(proofCopy);\n const isValidSignature = await EnhancedSecureCryptoUtils.verifySignature(publicKey, proof.signature, proofString);\n\n if (!isValidSignature) {\n throw new Error('Invalid proof signature');\n }\n\n EnhancedSecureCryptoUtils.secureLog.log('info', 'Authentication proof verified successfully', {\n responseAge: Math.round(responseAge / 1000) + 's'\n });\n\n return true;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Authentication proof verification failed', { error: error.message });\n throw new Error(`Failed to verify cryptographic proof: ${error.message}`);\n }\n }\n\n // Hash public key for verification\n static async hashPublicKey(publicKey) {\n try {\n const exported = await crypto.subtle.exportKey('spki', publicKey);\n const hash = await crypto.subtle.digest('SHA-384', exported);\n const hashArray = Array.from(new Uint8Array(hash));\n return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Public key hashing failed', { error: error.message });\n throw new Error('Failed to create hash of the public key');\n }\n }\n\n // Legacy authentication challenge for backward compatibility\n static generateAuthChallenge() {\n const challenge = crypto.getRandomValues(new Uint8Array(32));\n return Array.from(challenge);\n }\n\n // Generate verification code for out-of-band authentication\n static generateVerificationCode() {\n const chars = '0123456789ABCDEF';\n let result = '';\n const values = crypto.getRandomValues(new Uint8Array(6));\n for (let i = 0; i < 6; i++) {\n result += chars[values[i] % chars.length];\n }\n return result.match(/.{1,2}/g).join('-');\n }\n\n // Enhanced message encryption with metadata protection and sequence numbers\n static async encryptMessage(message, encryptionKey, macKey, metadataKey, messageId, sequenceNumber = 0) {\n try {\n if (!message || typeof message !== 'string') {\n throw new Error('Invalid message format');\n }\n\n EnhancedSecureCryptoUtils.assertCryptoKey(encryptionKey, 'AES-GCM', ['encrypt']);\n EnhancedSecureCryptoUtils.assertCryptoKey(macKey, 'HMAC', ['sign']);\n EnhancedSecureCryptoUtils.assertCryptoKey(metadataKey, 'AES-GCM', ['encrypt']);\n\n const encoder = new TextEncoder();\n const messageData = encoder.encode(message);\n const messageIv = crypto.getRandomValues(new Uint8Array(12));\n const metadataIv = crypto.getRandomValues(new Uint8Array(12));\n const timestamp = Date.now();\n\n const paddingSize = 16 - (messageData.length % 16);\n const paddedMessage = new Uint8Array(messageData.length + paddingSize);\n paddedMessage.set(messageData);\n const padding = crypto.getRandomValues(new Uint8Array(paddingSize));\n paddedMessage.set(padding, messageData.length);\n\n const encryptedMessage = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: messageIv },\n encryptionKey,\n paddedMessage\n );\n\n const metadata = {\n id: messageId,\n timestamp: timestamp,\n sequenceNumber: sequenceNumber,\n originalLength: messageData.length,\n version: '4.0'\n };\n\n const metadataStr = JSON.stringify(EnhancedSecureCryptoUtils.sortObjectKeys(metadata));\n const encryptedMetadata = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: metadataIv },\n metadataKey,\n encoder.encode(metadataStr)\n );\n\n const payload = {\n messageIv: Array.from(messageIv),\n messageData: Array.from(new Uint8Array(encryptedMessage)),\n metadataIv: Array.from(metadataIv),\n metadataData: Array.from(new Uint8Array(encryptedMetadata)),\n version: '4.0'\n };\n\n const sortedPayload = EnhancedSecureCryptoUtils.sortObjectKeys(payload);\n const payloadStr = JSON.stringify(sortedPayload);\n\n const mac = await crypto.subtle.sign(\n 'HMAC',\n macKey,\n encoder.encode(payloadStr)\n );\n\n payload.mac = Array.from(new Uint8Array(mac));\n\n EnhancedSecureCryptoUtils.secureLog.log('info', 'Message encrypted with metadata protection', {\n messageId,\n sequenceNumber,\n hasMetadataProtection: true,\n hasPadding: true\n });\n\n return payload;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Message encryption failed', {\n error: error.message,\n messageId\n });\n throw new Error(`Failed to encrypt the message: ${error.message}`);\n }\n }\n\n // Enhanced message decryption with metadata protection and sequence validation\n static async decryptMessage(encryptedPayload, encryptionKey, macKey, metadataKey, expectedSequenceNumber = null) {\n try {\n EnhancedSecureCryptoUtils.assertCryptoKey(encryptionKey, 'AES-GCM', ['decrypt']);\n EnhancedSecureCryptoUtils.assertCryptoKey(macKey, 'HMAC', ['verify']);\n EnhancedSecureCryptoUtils.assertCryptoKey(metadataKey, 'AES-GCM', ['decrypt']);\n\n const requiredFields = ['messageIv', 'messageData', 'metadataIv', 'metadataData', 'mac', 'version'];\n for (const field of requiredFields) {\n if (!encryptedPayload[field]) {\n throw new Error(`Missing required field: ${field}`);\n }\n }\n\n const payloadCopy = { ...encryptedPayload };\n delete payloadCopy.mac;\n const sortedPayloadCopy = EnhancedSecureCryptoUtils.sortObjectKeys(payloadCopy);\n const payloadStr = JSON.stringify(sortedPayloadCopy);\n\n const macValid = await crypto.subtle.verify(\n 'HMAC',\n macKey,\n new Uint8Array(encryptedPayload.mac),\n new TextEncoder().encode(payloadStr)\n );\n\n if (!macValid) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'MAC verification failed', {\n payloadFields: Object.keys(encryptedPayload),\n macLength: encryptedPayload.mac?.length\n });\n throw new Error('Message authentication failed - possible tampering');\n }\n\n const metadataIv = new Uint8Array(encryptedPayload.metadataIv);\n const metadataData = new Uint8Array(encryptedPayload.metadataData);\n\n const decryptedMetadataBuffer = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: metadataIv },\n metadataKey,\n metadataData\n );\n\n const metadataStr = new TextDecoder().decode(decryptedMetadataBuffer);\n const metadata = JSON.parse(metadataStr);\n\n if (!metadata.id || !metadata.timestamp || metadata.sequenceNumber === undefined || !metadata.originalLength) {\n throw new Error('Invalid metadata structure');\n }\n\n const messageAge = Date.now() - metadata.timestamp;\n if (messageAge > 300000) {\n throw new Error('Message expired (older than 5 minutes)');\n }\n\n if (expectedSequenceNumber !== null) {\n if (metadata.sequenceNumber < expectedSequenceNumber) {\n EnhancedSecureCryptoUtils.secureLog.log('warn', 'Received message with lower sequence number, possible queued message', {\n expected: expectedSequenceNumber,\n received: metadata.sequenceNumber,\n messageId: metadata.id\n });\n } else if (metadata.sequenceNumber > expectedSequenceNumber + 10) {\n throw new Error(`Sequence number gap too large: expected around ${expectedSequenceNumber}, got ${metadata.sequenceNumber}`);\n }\n }\n\n const messageIv = new Uint8Array(encryptedPayload.messageIv);\n const messageData = new Uint8Array(encryptedPayload.messageData);\n\n const decryptedMessageBuffer = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: messageIv },\n encryptionKey,\n messageData\n );\n\n const paddedMessage = new Uint8Array(decryptedMessageBuffer);\n const originalMessage = paddedMessage.slice(0, metadata.originalLength);\n\n const decoder = new TextDecoder();\n const message = decoder.decode(originalMessage);\n\n EnhancedSecureCryptoUtils.secureLog.log('info', 'Message decrypted successfully', {\n messageId: metadata.id,\n sequenceNumber: metadata.sequenceNumber,\n messageAge: Math.round(messageAge / 1000) + 's'\n });\n\n return {\n message: message,\n messageId: metadata.id,\n timestamp: metadata.timestamp,\n sequenceNumber: metadata.sequenceNumber\n };\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Message decryption failed', { error: error.message });\n throw new Error(`Failed to decrypt the message: ${error.message}`);\n }\n }\n\n // Enhanced input sanitization\n static sanitizeMessage(message) {\n if (typeof message !== 'string') {\n throw new Error('Message must be a string');\n }\n \n return message\n .replace(/)<[^<]*)*<\\/script>/gi, '')\n .replace(/javascript:/gi, '')\n .replace(/data:/gi, '')\n .replace(/vbscript:/gi, '')\n .replace(/onload\\s*=/gi, '')\n .replace(/onerror\\s*=/gi, '')\n .replace(/onclick\\s*=/gi, '')\n .trim()\n .substring(0, 2000); // Increased limit\n }\n\n // Generate cryptographically secure salt (64 bytes for enhanced security)\n static generateSalt() {\n return Array.from(crypto.getRandomValues(new Uint8Array(64)));\n }\n\n // Calculate key fingerprint for MITM protection\n static async calculateKeyFingerprint(keyData) {\n try {\n const encoder = new TextEncoder();\n const keyBytes = new Uint8Array(keyData);\n \n // Create a hash of the key data for fingerprinting\n const hashBuffer = await crypto.subtle.digest('SHA-256', keyBytes);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n \n // Convert to hexadecimal string\n const fingerprint = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n \n EnhancedSecureCryptoUtils.secureLog.log('info', 'Key fingerprint calculated', {\n keySize: keyData.length,\n fingerprintLength: fingerprint.length\n });\n \n return fingerprint;\n } catch (error) {\n EnhancedSecureCryptoUtils.secureLog.log('error', 'Key fingerprint calculation failed', { error: error.message });\n throw new Error('Failed to compute the key fingerprint');\n }\n }\n\n static constantTimeCompare(a, b) {\n const strA = typeof a === 'string' ? a : JSON.stringify(a);\n const strB = typeof b === 'string' ? b : JSON.stringify(b);\n \n if (strA.length !== strB.length) {\n let dummy = 0;\n for (let i = 0; i < Math.max(strA.length, strB.length); i++) {\n dummy |= (strA.charCodeAt(i % strA.length) || 0) ^ (strB.charCodeAt(i % strB.length) || 0);\n }\n return false;\n }\n \n let result = 0;\n for (let i = 0; i < strA.length; i++) {\n result |= strA.charCodeAt(i) ^ strB.charCodeAt(i);\n }\n \n return result === 0;\n }\n\n static constantTimeCompareArrays(arr1, arr2) {\n if (!Array.isArray(arr1) || !Array.isArray(arr2)) {\n return false;\n }\n \n if (arr1.length !== arr2.length) {\n let dummy = 0;\n const maxLen = Math.max(arr1.length, arr2.length);\n for (let i = 0; i < maxLen; i++) {\n dummy |= (arr1[i % arr1.length] || 0) ^ (arr2[i % arr2.length] || 0);\n }\n return false;\n }\n \n let result = 0;\n for (let i = 0; i < arr1.length; i++) {\n result |= arr1[i] ^ arr2[i];\n }\n \n return result === 0;\n }\n \n /**\n * CRITICAL SECURITY: Encrypt data with AAD (Additional Authenticated Data)\n * This method provides authenticated encryption with additional data binding\n */\n static async encryptDataWithAAD(data, key, aad) {\n try {\n const dataString = typeof data === 'string' ? data : JSON.stringify(data);\n const encoder = new TextEncoder();\n const dataBuffer = encoder.encode(dataString);\n const aadBuffer = encoder.encode(aad);\n\n // Generate random IV\n const iv = crypto.getRandomValues(new Uint8Array(12));\n\n // Encrypt with AAD\n const encrypted = await crypto.subtle.encrypt(\n { \n name: 'AES-GCM', \n iv: iv,\n additionalData: aadBuffer\n },\n key,\n dataBuffer\n );\n\n // Package encrypted data\n const encryptedPackage = {\n version: '1.0',\n iv: Array.from(iv),\n data: Array.from(new Uint8Array(encrypted)),\n aad: aad,\n timestamp: Date.now()\n };\n\n const packageString = JSON.stringify(encryptedPackage);\n const packageBuffer = encoder.encode(packageString);\n \n return EnhancedSecureCryptoUtils.arrayBufferToBase64(packageBuffer);\n } catch (error) {\n throw new Error(`AAD encryption failed: ${error.message}`);\n }\n }\n\n /**\n * CRITICAL SECURITY: Decrypt data with AAD validation\n * This method provides authenticated decryption with additional data validation\n */\n static async decryptDataWithAAD(encryptedData, key, expectedAad) {\n try {\n const packageBuffer = EnhancedSecureCryptoUtils.base64ToArrayBuffer(encryptedData);\n const packageString = new TextDecoder().decode(packageBuffer);\n const encryptedPackage = JSON.parse(packageString);\n\n if (!encryptedPackage.version || !encryptedPackage.iv || !encryptedPackage.data || !encryptedPackage.aad) {\n throw new Error('Invalid encrypted data format');\n }\n\n // Validate AAD matches expected\n if (encryptedPackage.aad !== expectedAad) {\n throw new Error('AAD mismatch - possible tampering or replay attack');\n }\n\n const iv = new Uint8Array(encryptedPackage.iv);\n const encrypted = new Uint8Array(encryptedPackage.data);\n const aadBuffer = new TextEncoder().encode(encryptedPackage.aad);\n\n // Decrypt with AAD validation\n const decrypted = await crypto.subtle.decrypt(\n { \n name: 'AES-GCM', \n iv: iv,\n additionalData: aadBuffer\n },\n key,\n encrypted\n );\n\n const decryptedString = new TextDecoder().decode(decrypted);\n\n try {\n return JSON.parse(decryptedString);\n } catch {\n return decryptedString;\n }\n } catch (error) {\n throw new Error(`AAD decryption failed: ${error.message}`);\n }\n }\n\n // Initialize secure logging system after class definition\n static {\n if (EnhancedSecureCryptoUtils.secureLog && typeof EnhancedSecureCryptoUtils.secureLog.init === 'function') {\n EnhancedSecureCryptoUtils.secureLog.init();\n }\n }\n}\n\nexport { EnhancedSecureCryptoUtils };", "// ============================================\n// SECURE FILE TRANSFER CONTEXT\n// ============================================\nclass SecureFileTransferContext {\n static #instance = null;\n static #contextKey = Symbol('SecureFileTransferContext');\n \n static getInstance() {\n if (!this.#instance) {\n this.#instance = new SecureFileTransferContext();\n }\n return this.#instance;\n }\n \n #fileTransferSystem = null;\n #active = false;\n #securityLevel = 'high';\n \n setFileTransferSystem(system) {\n if (!(system instanceof EnhancedSecureFileTransfer)) {\n throw new Error('Invalid file transfer system instance');\n }\n this.#fileTransferSystem = system;\n this.#active = true;\n console.log('\uD83D\uDD12 Secure file transfer context initialized');\n }\n \n getFileTransferSystem() {\n return this.#fileTransferSystem;\n }\n \n isActive() {\n return this.#active && this.#fileTransferSystem !== null;\n }\n \n deactivate() {\n this.#active = false;\n this.#fileTransferSystem = null;\n console.log('\uD83D\uDD12 Secure file transfer context deactivated');\n }\n \n getSecurityLevel() {\n return this.#securityLevel;\n }\n \n setSecurityLevel(level) {\n if (['low', 'medium', 'high'].includes(level)) {\n this.#securityLevel = level;\n }\n }\n}\n\n// ============================================\n// SECURITY ERROR HANDLER\n// ============================================\n\nclass SecurityErrorHandler {\n static #allowedErrors = new Set([\n 'File size exceeds maximum limit',\n 'Unsupported file type',\n 'Transfer timeout',\n 'Connection lost',\n 'Invalid file data',\n 'File transfer failed',\n 'Transfer cancelled',\n 'Network error',\n 'File not found',\n 'Permission denied'\n ]);\n \n static sanitizeError(error) {\n const message = error.message || error;\n\n for (const allowed of this.#allowedErrors) {\n if (message.includes(allowed)) {\n return allowed;\n }\n }\n\n console.error('\uD83D\uDD12 Internal file transfer error:', {\n message: error.message,\n stack: error.stack,\n timestamp: new Date().toISOString()\n });\n\n return 'File transfer failed';\n }\n \n static logSecurityEvent(event, details = {}) {\n console.warn('\uD83D\uDD12 Security event:', {\n event,\n timestamp: new Date().toISOString(),\n ...details\n });\n }\n}\n\n// ============================================\n// FILE METADATA SIGNATURE SYSTEM\n// ============================================\n\nclass FileMetadataSigner {\n static async signFileMetadata(metadata, privateKey) {\n try {\n const encoder = new TextEncoder();\n const data = encoder.encode(JSON.stringify({\n fileId: metadata.fileId,\n fileName: metadata.fileName,\n fileSize: metadata.fileSize,\n fileHash: metadata.fileHash,\n timestamp: metadata.timestamp,\n version: metadata.version || '2.0'\n }));\n \n const signature = await crypto.subtle.sign(\n 'RSASSA-PKCS1-v1_5',\n privateKey,\n data\n );\n \n return Array.from(new Uint8Array(signature));\n } catch (error) {\n SecurityErrorHandler.logSecurityEvent('signature_failed', { error: error.message });\n throw new Error('Failed to sign file metadata');\n }\n }\n \n static async verifyFileMetadata(metadata, signature, publicKey) {\n try {\n const encoder = new TextEncoder();\n const data = encoder.encode(JSON.stringify({\n fileId: metadata.fileId,\n fileName: metadata.fileName,\n fileSize: metadata.fileSize,\n fileHash: metadata.fileHash,\n timestamp: metadata.timestamp,\n version: metadata.version || '2.0'\n }));\n \n const signatureBuffer = new Uint8Array(signature);\n \n const isValid = await crypto.subtle.verify(\n 'RSASSA-PKCS1-v1_5',\n publicKey,\n signatureBuffer,\n data\n );\n \n if (!isValid) {\n SecurityErrorHandler.logSecurityEvent('invalid_signature', { fileId: metadata.fileId });\n }\n \n return isValid;\n } catch (error) {\n SecurityErrorHandler.logSecurityEvent('verification_failed', { error: error.message });\n return false;\n }\n }\n}\n\n// ============================================\n// \u0422\u041E\u0427\u041D\u042B\u0415 \u0418\u0421\u041F\u0420\u0410\u0412\u041B\u0415\u041D\u0418\u042F \u0411\u0415\u0417\u041E\u041F\u0410\u0421\u041D\u041E\u0421\u0422\u0418\n// ============================================\n\nclass MessageSizeValidator {\n static MAX_MESSAGE_SIZE = 1024 * 1024; // 1MB\n \n static isMessageSizeValid(message) {\n const messageString = JSON.stringify(message);\n const sizeInBytes = new Blob([messageString]).size;\n \n if (sizeInBytes > this.MAX_MESSAGE_SIZE) {\n SecurityErrorHandler.logSecurityEvent('message_too_large', {\n size: sizeInBytes,\n limit: this.MAX_MESSAGE_SIZE\n });\n throw new Error('Message too large');\n }\n \n return true;\n }\n}\n\nclass AtomicOperations {\n constructor() {\n this.locks = new Map();\n }\n \n async withLock(key, operation) {\n if (this.locks.has(key)) {\n await this.locks.get(key);\n }\n \n const lockPromise = (async () => {\n try {\n return await operation();\n } finally {\n this.locks.delete(key);\n }\n })();\n \n this.locks.set(key, lockPromise);\n return lockPromise;\n }\n}\n\n// Rate limiting \u0434\u043B\u044F \u0437\u0430\u0449\u0438\u0442\u044B \u043E\u0442 \u0441\u043F\u0430\u043C\u0430\nclass RateLimiter {\n constructor(maxRequests, windowMs) {\n this.maxRequests = maxRequests;\n this.windowMs = windowMs;\n this.requests = new Map();\n }\n \n isAllowed(identifier) {\n const now = Date.now();\n const windowStart = now - this.windowMs;\n \n if (!this.requests.has(identifier)) {\n this.requests.set(identifier, []);\n }\n \n const userRequests = this.requests.get(identifier);\n \n const validRequests = userRequests.filter(time => time > windowStart);\n this.requests.set(identifier, validRequests);\n \n if (validRequests.length >= this.maxRequests) {\n SecurityErrorHandler.logSecurityEvent('rate_limit_exceeded', {\n identifier,\n requestCount: validRequests.length,\n limit: this.maxRequests\n });\n return false;\n }\n \n validRequests.push(now);\n return true;\n }\n}\n\nclass SecureMemoryManager {\n static secureWipe(buffer) {\n if (buffer instanceof ArrayBuffer) {\n const view = new Uint8Array(buffer);\n crypto.getRandomValues(view);\n } else if (buffer instanceof Uint8Array) {\n crypto.getRandomValues(buffer);\n }\n }\n \n static secureDelete(obj, prop) {\n if (obj[prop]) {\n this.secureWipe(obj[prop]);\n delete obj[prop];\n }\n }\n}\n\nclass EnhancedSecureFileTransfer {\n constructor(webrtcManager, onProgress, onComplete, onError, onFileReceived) {\n this.webrtcManager = webrtcManager;\n this.onProgress = onProgress;\n this.onComplete = onComplete;\n this.onError = onError;\n this.onFileReceived = onFileReceived;\n \n // Validate webrtcManager\n if (!webrtcManager) {\n throw new Error('webrtcManager is required for EnhancedSecureFileTransfer');\n }\n \n SecureFileTransferContext.getInstance().setFileTransferSystem(this);\n \n this.atomicOps = new AtomicOperations();\n this.rateLimiter = new RateLimiter(10, 60000);\n\n this.signingKey = null;\n this.verificationKey = null;\n \n // Transfer settings\n this.CHUNK_SIZE = 64 * 1024; // 64 KB\n this.MAX_FILE_SIZE = 100 * 1024 * 1024; // 100 MB limit\n this.MAX_CONCURRENT_TRANSFERS = 3;\n this.CHUNK_TIMEOUT = 30000; // 30 seconds per chunk\n this.RETRY_ATTEMPTS = 3;\n\n this.FILE_TYPE_RESTRICTIONS = {\n documents: {\n extensions: ['.pdf', '.doc', '.docx', '.txt', '.md', '.rtf', '.odt'],\n mimeTypes: [\n 'application/pdf',\n 'application/msword',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'text/plain',\n 'text/markdown',\n 'application/rtf',\n 'application/vnd.oasis.opendocument.text'\n ],\n maxSize: 50 * 1024 * 1024, // 50 MB\n category: 'Documents',\n description: 'PDF, DOC, TXT, MD, RTF, ODT'\n },\n \n images: {\n extensions: ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.ico'],\n mimeTypes: [\n 'image/jpeg',\n 'image/png',\n 'image/gif',\n 'image/webp',\n 'image/bmp',\n 'image/svg+xml',\n 'image/x-icon'\n ],\n maxSize: 25 * 1024 * 1024, // 25 MB\n category: 'Images',\n description: 'JPG, PNG, GIF, WEBP, BMP, SVG, ICO'\n },\n \n archives: {\n extensions: ['.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.xz'],\n mimeTypes: [\n 'application/zip',\n 'application/x-rar-compressed',\n 'application/x-7z-compressed',\n 'application/x-tar',\n 'application/gzip',\n 'application/x-bzip2',\n 'application/x-xz'\n ],\n maxSize: 100 * 1024 * 1024, // 100 MB\n category: 'Archives',\n description: 'ZIP, RAR, 7Z, TAR, GZ, BZ2, XZ'\n },\n \n media: {\n extensions: ['.mp3', '.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.ogg', '.wav'],\n mimeTypes: [\n 'audio/mpeg',\n 'video/mp4',\n 'video/x-msvideo',\n 'video/x-matroska',\n 'video/quicktime',\n 'video/x-ms-wmv',\n 'video/x-flv',\n 'video/webm',\n 'audio/ogg',\n 'audio/wav'\n ],\n maxSize: 100 * 1024 * 1024, // 100 MB\n category: 'Media',\n description: 'MP3, MP4, AVI, MKV, MOV, WMV, FLV, WEBM, OGG, WAV'\n },\n \n general: {\n extensions: [], \n mimeTypes: [], \n maxSize: 50 * 1024 * 1024, // 50 MB\n category: 'General',\n description: 'Any file type up to size limits'\n }\n };\n \n // Active transfers tracking\n this.activeTransfers = new Map(); // fileId -> transfer state\n this.receivingTransfers = new Map(); // fileId -> receiving state\n this.transferQueue = []; // Queue for pending transfers\n this.pendingChunks = new Map();\n \n // Session key derivation\n this.sessionKeys = new Map(); // fileId -> derived session key\n \n // Security\n this.processedChunks = new Set(); // Prevent replay attacks\n this.transferNonces = new Map(); // fileId -> current nonce counter\n this.receivedFileBuffers = new Map(); // fileId -> { buffer:ArrayBuffer, type:string, name:string, size:number }\n\n this.setupFileMessageHandlers();\n\n if (this.webrtcManager) {\n this.webrtcManager.fileTransferSystem = this;\n }\n }\n\n // ============================================\n // FILE TYPE VALIDATION SYSTEM\n // ============================================\n\n getFileType(file) {\n const fileName = file.name.toLowerCase();\n const fileExtension = fileName.substring(fileName.lastIndexOf('.'));\n const mimeType = file.type.toLowerCase();\n\n for (const [typeKey, typeConfig] of Object.entries(this.FILE_TYPE_RESTRICTIONS)) {\n if (typeKey === 'general') continue; // \u041F\u0440\u043E\u043F\u0443\u0441\u043A\u0430\u0435\u043C \u043E\u0431\u0449\u0438\u0439 \u0442\u0438\u043F\n\n if (typeConfig.extensions.includes(fileExtension)) {\n return {\n type: typeKey,\n category: typeConfig.category,\n description: typeConfig.description,\n maxSize: typeConfig.maxSize,\n allowed: true\n };\n }\n\n if (typeConfig.mimeTypes.includes(mimeType)) {\n return {\n type: typeKey,\n category: typeConfig.category,\n description: typeConfig.description,\n maxSize: typeConfig.maxSize,\n allowed: true\n };\n }\n }\n\n const generalConfig = this.FILE_TYPE_RESTRICTIONS.general;\n return {\n type: 'general',\n category: generalConfig.category,\n description: generalConfig.description,\n maxSize: generalConfig.maxSize,\n allowed: true\n };\n }\n\n validateFile(file) {\n const fileType = this.getFileType(file);\n const errors = [];\n\n if (file.size > fileType.maxSize) {\n errors.push(`File size (${this.formatFileSize(file.size)}) exceeds maximum allowed for ${fileType.category} (${this.formatFileSize(fileType.maxSize)})`);\n }\n\n if (!fileType.allowed) {\n errors.push(`File type not allowed. Supported types: ${fileType.description}`);\n }\n\n if (file.size > this.MAX_FILE_SIZE) {\n errors.push(`File size (${this.formatFileSize(file.size)}) exceeds general limit (${this.formatFileSize(this.MAX_FILE_SIZE)})`);\n }\n \n return {\n isValid: errors.length === 0,\n errors: errors,\n fileType: fileType,\n fileSize: file.size,\n formattedSize: this.formatFileSize(file.size)\n };\n }\n\n formatFileSize(bytes) {\n if (bytes === 0) return '0 B';\n const k = 1024;\n const sizes = ['B', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n }\n\n getSupportedFileTypes() {\n const supportedTypes = {};\n \n for (const [typeKey, typeConfig] of Object.entries(this.FILE_TYPE_RESTRICTIONS)) {\n if (typeKey === 'general') continue;\n \n supportedTypes[typeKey] = {\n category: typeConfig.category,\n description: typeConfig.description,\n extensions: typeConfig.extensions,\n maxSize: this.formatFileSize(typeConfig.maxSize),\n maxSizeBytes: typeConfig.maxSize\n };\n }\n \n return supportedTypes;\n }\n\n getFileTypeInfo() {\n return {\n supportedTypes: this.getSupportedFileTypes(),\n generalMaxSize: this.formatFileSize(this.MAX_FILE_SIZE),\n generalMaxSizeBytes: this.MAX_FILE_SIZE,\n restrictions: this.FILE_TYPE_RESTRICTIONS\n };\n }\n\n // ============================================\n // ENCODING HELPERS (Base64 for efficient transport)\n // ============================================\n arrayBufferToBase64(buffer) {\n const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n let binary = '';\n const len = bytes.byteLength;\n for (let i = 0; i < len; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n }\n\n base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const len = binaryString.length;\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n }\n\n // ============================================\n // PUBLIC ACCESSORS FOR RECEIVED FILES\n // ============================================\n getReceivedFileMeta(fileId) {\n const entry = this.receivedFileBuffers.get(fileId);\n if (!entry) return null;\n return { fileId, fileName: entry.name, fileSize: entry.size, mimeType: entry.type };\n }\n\n async getBlob(fileId) {\n const entry = this.receivedFileBuffers.get(fileId);\n if (!entry) return null;\n return new Blob([entry.buffer], { type: entry.type });\n }\n\n async getObjectURL(fileId) {\n const blob = await this.getBlob(fileId);\n if (!blob) return null;\n return URL.createObjectURL(blob);\n }\n\n revokeObjectURL(url) {\n try { URL.revokeObjectURL(url); } catch (_) {}\n }\n\n setupFileMessageHandlers() {\n if (!this.webrtcManager.dataChannel) {\n const setupRetry = setInterval(() => {\n if (this.webrtcManager.dataChannel) {\n clearInterval(setupRetry);\n this.setupMessageInterception();\n }\n }, 100);\n\n setTimeout(() => {\n clearInterval(setupRetry);\n }, 5000);\n \n return;\n }\n \n // \u0415\u0441\u043B\u0438 dataChannel \u0443\u0436\u0435 \u0433\u043E\u0442\u043E\u0432, \u0441\u0440\u0430\u0437\u0443 \u043D\u0430\u0441\u0442\u0440\u0430\u0438\u0432\u0430\u0435\u043C\n this.setupMessageInterception();\n }\n\n setupMessageInterception() {\n try {\n if (!this.webrtcManager.dataChannel) {\n return;\n }\n\n if (this.webrtcManager) {\n this.webrtcManager.fileTransferSystem = this;\n }\n\n if (this.webrtcManager.dataChannel.onmessage) {\n this.originalOnMessage = this.webrtcManager.dataChannel.onmessage;\n }\n\n this.webrtcManager.dataChannel.onmessage = async (event) => {\n try {\n if (event.data.length > MessageSizeValidator.MAX_MESSAGE_SIZE) {\n console.warn('\uD83D\uDD12 Message too large, ignoring');\n SecurityErrorHandler.logSecurityEvent('oversized_message_blocked');\n return;\n }\n \n if (typeof event.data === 'string') {\n try {\n const parsed = JSON.parse(event.data);\n \n MessageSizeValidator.isMessageSizeValid(parsed);\n \n if (this.isFileTransferMessage(parsed)) {\n await this.handleFileMessage(parsed);\n return; \n }\n } catch (parseError) {\n if (parseError.message === 'Message too large') {\n return; \n }\n }\n }\n\n if (this.originalOnMessage) {\n return this.originalOnMessage.call(this.webrtcManager.dataChannel, event);\n }\n } catch (error) {\n console.error('\u274C Error in file system message interception:', error);\n if (this.originalOnMessage) {\n return this.originalOnMessage.call(this.webrtcManager.dataChannel, event);\n }\n }\n };\n } catch (error) {\n console.error('\u274C Failed to set up message interception:', error);\n }\n }\n\n isFileTransferMessage(message) {\n if (!message || typeof message !== 'object' || !message.type) {\n return false;\n }\n \n const fileMessageTypes = [\n 'file_transfer_start',\n 'file_transfer_response', \n 'file_chunk',\n 'chunk_confirmation',\n 'file_transfer_complete',\n 'file_transfer_error'\n ];\n \n return fileMessageTypes.includes(message.type);\n }\n\n async handleFileMessage(message) {\n try {\n if (!this.webrtcManager.fileTransferSystem) {\n try {\n if (typeof this.webrtcManager.initializeFileTransfer === 'function') {\n this.webrtcManager.initializeFileTransfer();\n \n let attempts = 0;\n const maxAttempts = 50; \n while (!this.webrtcManager.fileTransferSystem && attempts < maxAttempts) {\n await new Promise(resolve => setTimeout(resolve, 100));\n attempts++;\n }\n \n if (!this.webrtcManager.fileTransferSystem) {\n throw new Error('File transfer system initialization timeout');\n }\n } else {\n throw new Error('initializeFileTransfer method not available');\n }\n } catch (initError) {\n console.error('\u274C Failed to initialize file transfer system:', initError);\n if (message.fileId) {\n const errorMessage = {\n type: 'file_transfer_error',\n fileId: message.fileId,\n error: 'File transfer system not available',\n timestamp: Date.now()\n };\n await this.sendSecureMessage(errorMessage);\n }\n return;\n }\n }\n \n switch (message.type) {\n case 'file_transfer_start':\n await this.handleFileTransferStart(message);\n break;\n \n case 'file_transfer_response':\n this.handleTransferResponse(message);\n break;\n \n case 'file_chunk':\n await this.handleFileChunk(message);\n break;\n \n case 'chunk_confirmation':\n this.handleChunkConfirmation(message);\n break;\n \n case 'file_transfer_complete':\n this.handleTransferComplete(message);\n break;\n \n case 'file_transfer_error':\n this.handleTransferError(message);\n break;\n \n default:\n console.warn('\u26A0\uFE0F Unknown file message type:', message.type);\n }\n \n } catch (error) {\n console.error('\u274C Error handling file message:', error);\n\n if (message.fileId) {\n const errorMessage = {\n type: 'file_transfer_error',\n fileId: message.fileId,\n error: error.message,\n timestamp: Date.now()\n };\n await this.sendSecureMessage(errorMessage);\n }\n }\n }\n\n // ============================================\n // SIMPLIFIED KEY DERIVATION - USE SHARED DATA\n // ============================================\n\n async deriveFileSessionKey(fileId) {\n try {\n \n if (!this.webrtcManager.keyFingerprint || !this.webrtcManager.sessionSalt) {\n throw new Error('WebRTC session data not available');\n }\n\n const fileSalt = crypto.getRandomValues(new Uint8Array(32));\n\n const encoder = new TextEncoder();\n const fingerprintData = encoder.encode(this.webrtcManager.keyFingerprint);\n const fileIdData = encoder.encode(fileId);\n\n const sessionSaltArray = new Uint8Array(this.webrtcManager.sessionSalt);\n const combinedSeed = new Uint8Array(\n fingerprintData.length + \n sessionSaltArray.length + \n fileSalt.length + \n fileIdData.length\n );\n \n let offset = 0;\n combinedSeed.set(fingerprintData, offset);\n offset += fingerprintData.length;\n combinedSeed.set(sessionSaltArray, offset);\n offset += sessionSaltArray.length;\n combinedSeed.set(fileSalt, offset);\n offset += fileSalt.length;\n combinedSeed.set(fileIdData, offset);\n\n const keyMaterial = await crypto.subtle.digest('SHA-256', combinedSeed);\n\n const fileSessionKey = await crypto.subtle.importKey(\n 'raw',\n keyMaterial,\n { name: 'AES-GCM' },\n false,\n ['encrypt', 'decrypt']\n );\n\n this.sessionKeys.set(fileId, {\n key: fileSessionKey,\n salt: Array.from(fileSalt),\n created: Date.now()\n });\n\n return { key: fileSessionKey, salt: Array.from(fileSalt) };\n\n } catch (error) {\n console.error('\u274C Failed to derive file session key:', error);\n throw error;\n }\n }\n\n async deriveFileSessionKeyFromSalt(fileId, saltArray) {\n try {\n if (!saltArray || !Array.isArray(saltArray) || saltArray.length !== 32) {\n throw new Error(`Invalid salt: ${saltArray?.length || 0} bytes`);\n }\n \n if (!this.webrtcManager.keyFingerprint || !this.webrtcManager.sessionSalt) {\n throw new Error('WebRTC session data not available');\n }\n\n const encoder = new TextEncoder();\n const fingerprintData = encoder.encode(this.webrtcManager.keyFingerprint);\n const fileIdData = encoder.encode(fileId);\n\n const fileSalt = new Uint8Array(saltArray);\n const sessionSaltArray = new Uint8Array(this.webrtcManager.sessionSalt);\n\n const combinedSeed = new Uint8Array(\n fingerprintData.length + \n sessionSaltArray.length + \n fileSalt.length + \n fileIdData.length\n );\n \n let offset = 0;\n combinedSeed.set(fingerprintData, offset);\n offset += fingerprintData.length;\n combinedSeed.set(sessionSaltArray, offset);\n offset += sessionSaltArray.length;\n combinedSeed.set(fileSalt, offset);\n offset += fileSalt.length;\n combinedSeed.set(fileIdData, offset);\n\n const keyMaterial = await crypto.subtle.digest('SHA-256', combinedSeed);\n\n const fileSessionKey = await crypto.subtle.importKey(\n 'raw',\n keyMaterial,\n { name: 'AES-GCM' },\n false,\n ['encrypt', 'decrypt']\n );\n\n this.sessionKeys.set(fileId, {\n key: fileSessionKey,\n salt: saltArray,\n created: Date.now()\n });\n\n return fileSessionKey;\n\n } catch (error) {\n console.error('\u274C Failed to derive session key from salt:', error);\n throw error;\n }\n }\n\n // ============================================\n // FILE TRANSFER IMPLEMENTATION\n // ============================================\n\n async sendFile(file) {\n try {\n // Validate webrtcManager\n if (!this.webrtcManager) {\n throw new Error('WebRTC Manager not initialized');\n }\n\n const clientId = this.getClientIdentifier();\n if (!this.rateLimiter.isAllowed(clientId)) {\n SecurityErrorHandler.logSecurityEvent('rate_limit_exceeded', { clientId });\n throw new Error('Rate limit exceeded. Please wait before sending another file.');\n }\n\n if (!file || !file.size) {\n throw new Error('Invalid file object');\n }\n\n const validation = this.validateFile(file);\n if (!validation.isValid) {\n const errorMessage = validation.errors.join('. ');\n throw new Error(errorMessage);\n }\n\n if (this.activeTransfers.size >= this.MAX_CONCURRENT_TRANSFERS) {\n throw new Error('Maximum concurrent transfers reached');\n }\n\n // Generate unique file ID\n const fileId = `file_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n \n // Calculate file hash for integrity verification\n const fileHash = await this.calculateFileHash(file);\n \n // Derive session key for this file\n const keyResult = await this.deriveFileSessionKey(fileId);\n const sessionKey = keyResult.key;\n const salt = keyResult.salt;\n \n // Create transfer state\n const transferState = {\n fileId: fileId,\n file: file,\n fileHash: fileHash,\n sessionKey: sessionKey,\n salt: salt, \n totalChunks: Math.ceil(file.size / this.CHUNK_SIZE),\n sentChunks: 0,\n confirmedChunks: 0,\n startTime: Date.now(),\n status: 'preparing',\n retryCount: 0,\n lastChunkTime: Date.now()\n };\n\n this.activeTransfers.set(fileId, transferState);\n this.transferNonces.set(fileId, 0);\n\n // Send file metadata first\n await this.sendFileMetadata(transferState);\n \n // Start chunk transmission\n await this.startChunkTransmission(transferState);\n \n return fileId;\n\n } catch (error) {\n const safeError = SecurityErrorHandler.sanitizeError(error);\n console.error('\u274C File sending failed:', safeError);\n if (this.onError) this.onError(safeError);\n throw new Error(safeError);\n }\n }\n\n async sendFileMetadata(transferState) {\n try {\n const metadata = {\n type: 'file_transfer_start',\n fileId: transferState.fileId,\n fileName: transferState.file.name,\n fileSize: transferState.file.size,\n fileType: transferState.file.type || 'application/octet-stream',\n fileHash: transferState.fileHash,\n totalChunks: transferState.totalChunks,\n chunkSize: this.CHUNK_SIZE,\n salt: transferState.salt, \n timestamp: Date.now(),\n version: '2.0'\n };\n\n if (this.signingKey) {\n try {\n metadata.signature = await FileMetadataSigner.signFileMetadata(metadata, this.signingKey);\n console.log('\uD83D\uDD12 File metadata signed successfully');\n } catch (signError) {\n SecurityErrorHandler.logSecurityEvent('signature_failed', { \n fileId: transferState.fileId, \n error: signError.message \n });\n }\n }\n\n // Send metadata through secure channel\n await this.sendSecureMessage(metadata);\n \n transferState.status = 'metadata_sent';\n\n } catch (error) {\n const safeError = SecurityErrorHandler.sanitizeError(error);\n console.error('\u274C Failed to send file metadata:', safeError);\n transferState.status = 'failed';\n throw new Error(safeError);\n }\n }\n\n async startChunkTransmission(transferState) {\n try {\n transferState.status = 'transmitting';\n \n const file = transferState.file;\n const totalChunks = transferState.totalChunks;\n \n for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {\n const start = chunkIndex * this.CHUNK_SIZE;\n const end = Math.min(start + this.CHUNK_SIZE, file.size);\n \n // Read chunk from file\n const chunkData = await this.readFileChunk(file, start, end);\n \n // Send chunk (\u0441 \u0443\u0447\u0451\u0442\u043E\u043C backpressure)\n await this.sendFileChunk(transferState, chunkIndex, chunkData);\n \n // Update progress\n transferState.sentChunks++;\n const progress = Math.round((transferState.sentChunks / totalChunks) * 95) + 5; // 5-100%\n\n await this.waitForBackpressure();\n }\n \n transferState.status = 'waiting_confirmation';\n \n // Timeout for completion confirmation\n setTimeout(() => {\n if (this.activeTransfers.has(transferState.fileId)) {\n const state = this.activeTransfers.get(transferState.fileId);\n if (state.status === 'waiting_confirmation') {\n this.cleanupTransfer(transferState.fileId);\n }\n }\n }, 30000);\n \n } catch (error) {\n const safeError = SecurityErrorHandler.sanitizeError(error);\n console.error('\u274C Chunk transmission failed:', safeError);\n transferState.status = 'failed';\n throw new Error(safeError);\n }\n }\n\n async readFileChunk(file, start, end) {\n try {\n const blob = file.slice(start, end);\n return await blob.arrayBuffer();\n } catch (error) {\n const safeError = SecurityErrorHandler.sanitizeError(error);\n console.error('\u274C Failed to read file chunk:', safeError);\n throw new Error(safeError);\n }\n }\n\n async sendFileChunk(transferState, chunkIndex, chunkData) {\n try {\n const sessionKey = transferState.sessionKey;\n const nonce = crypto.getRandomValues(new Uint8Array(12));\n \n // Encrypt chunk data\n const encryptedChunk = await crypto.subtle.encrypt(\n {\n name: 'AES-GCM',\n iv: nonce\n },\n sessionKey,\n chunkData\n );\n \n // Use Base64 to drastically reduce JSON overhead\n const encryptedB64 = this.arrayBufferToBase64(new Uint8Array(encryptedChunk));\n const chunkMessage = {\n type: 'file_chunk',\n fileId: transferState.fileId,\n chunkIndex: chunkIndex,\n totalChunks: transferState.totalChunks,\n nonce: Array.from(nonce),\n encryptedDataB64: encryptedB64,\n chunkSize: chunkData.byteLength,\n timestamp: Date.now()\n };\n\n await this.waitForBackpressure();\n // Send chunk through secure channel\n await this.sendSecureMessage(chunkMessage);\n \n } catch (error) {\n const safeError = SecurityErrorHandler.sanitizeError(error);\n console.error('\u274C Failed to send file chunk:', safeError);\n throw new Error(safeError);\n }\n }\n\n async sendSecureMessage(message) {\n\n const messageString = JSON.stringify(message);\n const dc = this.webrtcManager?.dataChannel;\n const maxRetries = 10;\n let attempt = 0;\n const wait = (ms) => new Promise(r => setTimeout(r, ms));\n\n while (true) {\n try {\n if (!dc || dc.readyState !== 'open') {\n throw new Error('Data channel not ready');\n }\n await this.waitForBackpressure();\n dc.send(messageString);\n return; // success\n } catch (error) {\n const msg = String(error?.message || '');\n const queueFull = msg.includes('send queue is full') || msg.includes('bufferedAmount');\n const opErr = error?.name === 'OperationError';\n if ((queueFull || opErr) && attempt < maxRetries) {\n attempt++;\n await this.waitForBackpressure();\n await wait(Math.min(50 * attempt, 500));\n continue;\n }\n console.error('\u274C Failed to send secure message:', error);\n throw error;\n }\n }\n }\n\n async waitForBackpressure() {\n try {\n const dc = this.webrtcManager?.dataChannel;\n if (!dc) return;\n\n if (typeof dc.bufferedAmountLowThreshold === 'number') {\n if (dc.bufferedAmount > dc.bufferedAmountLowThreshold) {\n await new Promise(resolve => {\n const handler = () => {\n dc.removeEventListener('bufferedamountlow', handler);\n resolve();\n };\n dc.addEventListener('bufferedamountlow', handler, { once: true });\n });\n }\n return;\n }\n\n const softLimit = 4 * 1024 * 1024;\n while (dc.bufferedAmount > softLimit) {\n await new Promise(r => setTimeout(r, 20));\n }\n } catch (_) {\n // ignore\n }\n }\n\n async calculateFileHash(file) {\n try {\n const arrayBuffer = await file.arrayBuffer();\n const hashBuffer = await crypto.subtle.digest('SHA-256', arrayBuffer);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n } catch (error) {\n console.error('\u274C File hash calculation failed:', error);\n throw error;\n }\n }\n\n // ============================================\n // MESSAGE HANDLERS\n // ============================================\n\n async handleFileTransferStart(metadata) {\n try {\n // Validate metadata\n if (!metadata.fileId || !metadata.fileName || !metadata.fileSize) {\n throw new Error('Invalid file transfer metadata');\n }\n\n if (metadata.signature && this.verificationKey) {\n try {\n const isValid = await FileMetadataSigner.verifyFileMetadata(\n metadata, \n metadata.signature, \n this.verificationKey\n );\n \n if (!isValid) {\n SecurityErrorHandler.logSecurityEvent('invalid_metadata_signature', { \n fileId: metadata.fileId \n });\n throw new Error('Invalid file metadata signature');\n }\n \n console.log('\uD83D\uDD12 File metadata signature verified successfully');\n } catch (verifyError) {\n SecurityErrorHandler.logSecurityEvent('verification_failed', { \n fileId: metadata.fileId, \n error: verifyError.message \n });\n throw new Error('File metadata verification failed');\n }\n }\n \n // Check if we already have this transfer\n if (this.receivingTransfers.has(metadata.fileId)) {\n return;\n }\n \n // Derive session key from salt\n const sessionKey = await this.deriveFileSessionKeyFromSalt(\n metadata.fileId,\n metadata.salt\n );\n \n // Create receiving transfer state\n const receivingState = {\n fileId: metadata.fileId,\n fileName: metadata.fileName,\n fileSize: metadata.fileSize,\n fileType: metadata.fileType || 'application/octet-stream',\n fileHash: metadata.fileHash,\n totalChunks: metadata.totalChunks,\n chunkSize: metadata.chunkSize || this.CHUNK_SIZE,\n sessionKey: sessionKey,\n salt: metadata.salt,\n receivedChunks: new Map(),\n receivedCount: 0,\n startTime: Date.now(),\n lastChunkTime: Date.now(),\n status: 'receiving'\n };\n \n this.receivingTransfers.set(metadata.fileId, receivingState);\n \n // Send acceptance response\n const response = {\n type: 'file_transfer_response',\n fileId: metadata.fileId,\n accepted: true,\n timestamp: Date.now()\n };\n \n await this.sendSecureMessage(response);\n\n // Process buffered chunks if any\n if (this.pendingChunks.has(metadata.fileId)) {\n const bufferedChunks = this.pendingChunks.get(metadata.fileId);\n \n for (const [chunkIndex, chunkMessage] of bufferedChunks.entries()) {\n await this.handleFileChunk(chunkMessage);\n }\n \n this.pendingChunks.delete(metadata.fileId);\n }\n \n } catch (error) {\n const safeError = SecurityErrorHandler.sanitizeError(error);\n console.error('\u274C Failed to handle file transfer start:', safeError);\n \n // Send error response\n const errorResponse = {\n type: 'file_transfer_response',\n fileId: metadata.fileId,\n accepted: false,\n error: safeError, \n timestamp: Date.now()\n };\n await this.sendSecureMessage(errorResponse);\n }\n }\n\n async handleFileChunk(chunkMessage) {\n return this.atomicOps.withLock(\n `chunk-${chunkMessage.fileId}`, \n async () => {\n try {\n let receivingState = this.receivingTransfers.get(chunkMessage.fileId);\n \n // Buffer early chunks if transfer not yet initialized\n if (!receivingState) {\n if (!this.pendingChunks.has(chunkMessage.fileId)) {\n this.pendingChunks.set(chunkMessage.fileId, new Map());\n }\n \n this.pendingChunks.get(chunkMessage.fileId).set(chunkMessage.chunkIndex, chunkMessage);\n return;\n }\n \n // Update last chunk time\n receivingState.lastChunkTime = Date.now();\n \n // Check if chunk already received\n if (receivingState.receivedChunks.has(chunkMessage.chunkIndex)) {\n return;\n }\n \n // Validate chunk\n if (chunkMessage.chunkIndex < 0 || chunkMessage.chunkIndex >= receivingState.totalChunks) {\n throw new Error(`Invalid chunk index: ${chunkMessage.chunkIndex}`);\n }\n \n // Decrypt chunk\n const nonce = new Uint8Array(chunkMessage.nonce);\n // Backward compatible: prefer Base64, fallback to numeric array\n let encryptedData;\n if (chunkMessage.encryptedDataB64) {\n encryptedData = this.base64ToUint8Array(chunkMessage.encryptedDataB64);\n } else if (chunkMessage.encryptedData) {\n encryptedData = new Uint8Array(chunkMessage.encryptedData);\n } else {\n throw new Error('Missing encrypted data');\n }\n \n const decryptedChunk = await crypto.subtle.decrypt(\n {\n name: 'AES-GCM',\n iv: nonce\n },\n receivingState.sessionKey,\n encryptedData\n );\n \n // Verify chunk size\n if (decryptedChunk.byteLength !== chunkMessage.chunkSize) {\n throw new Error(`Chunk size mismatch: expected ${chunkMessage.chunkSize}, got ${decryptedChunk.byteLength}`);\n }\n \n // Store chunk\n receivingState.receivedChunks.set(chunkMessage.chunkIndex, decryptedChunk);\n receivingState.receivedCount++;\n \n // Send chunk confirmation\n const confirmation = {\n type: 'chunk_confirmation',\n fileId: chunkMessage.fileId,\n chunkIndex: chunkMessage.chunkIndex,\n timestamp: Date.now()\n };\n await this.sendSecureMessage(confirmation);\n \n // Check if all chunks received\n if (receivingState.receivedCount === receivingState.totalChunks) {\n await this.assembleFile(receivingState);\n }\n \n } catch (error) {\n const safeError = SecurityErrorHandler.sanitizeError(error);\n console.error('\u274C Failed to handle file chunk:', safeError);\n \n // Send error notification\n const errorMessage = {\n type: 'file_transfer_error',\n fileId: chunkMessage.fileId,\n error: safeError, \n chunkIndex: chunkMessage.chunkIndex,\n timestamp: Date.now()\n };\n await this.sendSecureMessage(errorMessage);\n \n // Mark transfer as failed\n const receivingState = this.receivingTransfers.get(chunkMessage.fileId);\n if (receivingState) {\n receivingState.status = 'failed';\n }\n \n if (this.onError) {\n this.onError(`Chunk processing failed: ${safeError}`);\n }\n }\n }\n );\n }\n\n async assembleFile(receivingState) {\n try {\n receivingState.status = 'assembling';\n \n // Verify we have all chunks\n for (let i = 0; i < receivingState.totalChunks; i++) {\n if (!receivingState.receivedChunks.has(i)) {\n throw new Error(`Missing chunk ${i}`);\n }\n }\n \n // Combine all chunks in order\n const chunks = [];\n for (let i = 0; i < receivingState.totalChunks; i++) {\n const chunk = receivingState.receivedChunks.get(i);\n chunks.push(new Uint8Array(chunk));\n }\n \n // Calculate total size\n const totalSize = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n \n // Verify total size matches expected\n if (totalSize !== receivingState.fileSize) {\n throw new Error(`File size mismatch: expected ${receivingState.fileSize}, got ${totalSize}`);\n }\n \n // Combine into single array\n const fileData = new Uint8Array(totalSize);\n let offset = 0;\n for (const chunk of chunks) {\n fileData.set(chunk, offset);\n offset += chunk.length;\n }\n \n // Verify file integrity\n const receivedHash = await this.calculateFileHashFromData(fileData);\n if (receivedHash !== receivingState.fileHash) {\n throw new Error('File integrity check failed - hash mismatch');\n }\n\n const fileBuffer = fileData.buffer;\n const fileBlob = new Blob([fileBuffer], { type: receivingState.fileType });\n \n receivingState.endTime = Date.now();\n receivingState.status = 'completed';\n\n this.receivedFileBuffers.set(receivingState.fileId, {\n buffer: fileBuffer,\n type: receivingState.fileType,\n name: receivingState.fileName,\n size: receivingState.fileSize\n });\n\n if (this.onFileReceived) {\n const getBlob = async () => new Blob([this.receivedFileBuffers.get(receivingState.fileId).buffer], { type: receivingState.fileType });\n const getObjectURL = async () => {\n const blob = await getBlob();\n return URL.createObjectURL(blob);\n };\n const revokeObjectURL = (url) => {\n try { URL.revokeObjectURL(url); } catch (_) {}\n };\n\n this.onFileReceived({\n fileId: receivingState.fileId,\n fileName: receivingState.fileName,\n fileSize: receivingState.fileSize,\n mimeType: receivingState.fileType,\n transferTime: receivingState.endTime - receivingState.startTime,\n // backward-compatibility for existing UIs\n fileBlob,\n getBlob,\n getObjectURL,\n revokeObjectURL\n });\n }\n \n // Send completion confirmation\n const completionMessage = {\n type: 'file_transfer_complete',\n fileId: receivingState.fileId,\n success: true,\n timestamp: Date.now()\n };\n await this.sendSecureMessage(completionMessage);\n \n // Cleanup\n if (this.receivingTransfers.has(receivingState.fileId)) {\n const rs = this.receivingTransfers.get(receivingState.fileId);\n if (rs && rs.receivedChunks) rs.receivedChunks.clear();\n }\n this.receivingTransfers.delete(receivingState.fileId);\n \n } catch (error) {\n console.error('\u274C File assembly failed:', error);\n receivingState.status = 'failed';\n \n if (this.onError) {\n this.onError(`File assembly failed: ${error.message}`);\n }\n \n // Send error notification\n const errorMessage = {\n type: 'file_transfer_complete',\n fileId: receivingState.fileId,\n success: false,\n error: error.message,\n timestamp: Date.now()\n };\n await this.sendSecureMessage(errorMessage);\n \n // Cleanup failed transfer\n this.cleanupReceivingTransfer(receivingState.fileId);\n }\n }\n\n async calculateFileHashFromData(data) {\n try {\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n } catch (error) {\n console.error('\u274C Hash calculation failed:', error);\n throw error;\n }\n }\n\n handleTransferResponse(response) {\n try {\n const transferState = this.activeTransfers.get(response.fileId);\n \n if (!transferState) {\n return;\n }\n \n if (response.accepted) {\n transferState.status = 'accepted';\n } else {\n transferState.status = 'rejected';\n \n if (this.onError) {\n this.onError(`Transfer rejected: ${response.error || 'Unknown reason'}`);\n }\n \n this.cleanupTransfer(response.fileId);\n }\n } catch (error) {\n console.error('\u274C Failed to handle transfer response:', error);\n }\n }\n\n handleChunkConfirmation(confirmation) {\n try {\n const transferState = this.activeTransfers.get(confirmation.fileId);\n if (!transferState) {\n return;\n }\n \n transferState.confirmedChunks++;\n transferState.lastChunkTime = Date.now();\n } catch (error) {\n console.error('\u274C Failed to handle chunk confirmation:', error);\n }\n }\n\n handleTransferComplete(completion) {\n try {\n const transferState = this.activeTransfers.get(completion.fileId);\n if (!transferState) {\n return;\n }\n \n if (completion.success) {\n transferState.status = 'completed';\n transferState.endTime = Date.now();\n \n if (this.onComplete) {\n this.onComplete({\n fileId: transferState.fileId,\n fileName: transferState.file.name,\n fileSize: transferState.file.size,\n transferTime: transferState.endTime - transferState.startTime,\n status: 'completed'\n });\n }\n } else {\n transferState.status = 'failed';\n \n if (this.onError) {\n this.onError(`Transfer failed: ${completion.error || 'Unknown error'}`);\n }\n }\n \n this.cleanupTransfer(completion.fileId);\n \n } catch (error) {\n console.error('\u274C Failed to handle transfer completion:', error);\n }\n }\n\n handleTransferError(errorMessage) {\n try {\n const transferState = this.activeTransfers.get(errorMessage.fileId);\n if (transferState) {\n transferState.status = 'failed';\n this.cleanupTransfer(errorMessage.fileId);\n }\n \n const receivingState = this.receivingTransfers.get(errorMessage.fileId);\n if (receivingState) {\n receivingState.status = 'failed';\n this.cleanupReceivingTransfer(errorMessage.fileId);\n }\n \n if (this.onError) {\n this.onError(`Transfer error: ${errorMessage.error || 'Unknown error'}`);\n }\n \n } catch (error) {\n console.error('\u274C Failed to handle transfer error:', error);\n }\n }\n\n // ============================================\n // UTILITY METHODS\n // ============================================\n\n getActiveTransfers() {\n return Array.from(this.activeTransfers.values()).map(transfer => ({\n fileId: transfer.fileId,\n fileName: transfer.file?.name || 'Unknown',\n fileSize: transfer.file?.size || 0,\n progress: Math.round((transfer.sentChunks / transfer.totalChunks) * 100),\n status: transfer.status,\n startTime: transfer.startTime\n }));\n }\n\n getReceivingTransfers() {\n return Array.from(this.receivingTransfers.values()).map(transfer => ({\n fileId: transfer.fileId,\n fileName: transfer.fileName || 'Unknown',\n fileSize: transfer.fileSize || 0,\n progress: Math.round((transfer.receivedCount / transfer.totalChunks) * 100),\n status: transfer.status,\n startTime: transfer.startTime\n }));\n }\n\n cancelTransfer(fileId) {\n try {\n if (this.activeTransfers.has(fileId)) {\n this.cleanupTransfer(fileId);\n return true;\n }\n if (this.receivingTransfers.has(fileId)) {\n this.cleanupReceivingTransfer(fileId);\n return true;\n }\n return false;\n } catch (error) {\n console.error('\u274C Failed to cancel transfer:', error);\n return false;\n }\n }\n\n cleanupTransfer(fileId) {\n this.activeTransfers.delete(fileId);\n this.sessionKeys.delete(fileId);\n this.transferNonces.delete(fileId);\n \n // Remove processed chunk IDs for this transfer\n for (const chunkId of this.processedChunks) {\n if (chunkId.startsWith(fileId)) {\n this.processedChunks.delete(chunkId);\n }\n }\n }\n\n // \u2705 \u0423\u041B\u0423\u0427\u0428\u0415\u041D\u041D\u0410\u042F \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u0430\u044F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 \u043F\u0430\u043C\u044F\u0442\u0438 \u0434\u043B\u044F \u043F\u0440\u0435\u0434\u043E\u0442\u0432\u0440\u0430\u0449\u0435\u043D\u0438\u044F use-after-free\n cleanupReceivingTransfer(fileId) {\n try {\n // \u0411\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E \u043E\u0447\u0438\u0449\u0430\u0435\u043C pending chunks\n this.pendingChunks.delete(fileId);\n \n const receivingState = this.receivingTransfers.get(fileId);\n if (receivingState) {\n // \u2705 \u0411\u0415\u0417\u041E\u041F\u0410\u0421\u041D\u0410\u042F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 receivedChunks \u0441 \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0439 \u0437\u0430\u0449\u0438\u0442\u043E\u0439\n if (receivingState.receivedChunks && receivingState.receivedChunks.size > 0) {\n for (const [index, chunk] of receivingState.receivedChunks) {\n try {\n // \u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u0430\u044F \u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0430 \u043D\u0430 \u0432\u0430\u043B\u0438\u0434\u043D\u043E\u0441\u0442\u044C chunk\n if (chunk && (chunk instanceof ArrayBuffer || chunk instanceof Uint8Array)) {\n SecureMemoryManager.secureWipe(chunk);\n \n // \u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u0430\u044F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 - \u0437\u0430\u043F\u043E\u043B\u043D\u044F\u0435\u043C \u043D\u0443\u043B\u044F\u043C\u0438 \u043F\u0435\u0440\u0435\u0434 \u0443\u0434\u0430\u043B\u0435\u043D\u0438\u0435\u043C\n if (chunk instanceof ArrayBuffer) {\n const view = new Uint8Array(chunk);\n view.fill(0);\n } else if (chunk instanceof Uint8Array) {\n chunk.fill(0);\n }\n }\n } catch (chunkError) {\n console.warn('\u26A0\uFE0F Failed to securely wipe chunk:', chunkError);\n }\n }\n receivingState.receivedChunks.clear();\n }\n \n // \u2705 \u0411\u0415\u0417\u041E\u041F\u0410\u0421\u041D\u0410\u042F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 session key\n if (receivingState.sessionKey) {\n try {\n // \u0414\u043B\u044F CryptoKey \u043D\u0435\u043B\u044C\u0437\u044F \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E \u043E\u0447\u0438\u0441\u0442\u0438\u0442\u044C, \u043D\u043E \u043C\u043E\u0436\u0435\u043C \u0443\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u0441\u044B\u043B\u043A\u0443\n receivingState.sessionKey = null;\n } catch (keyError) {\n console.warn('\u26A0\uFE0F Failed to clear session key:', keyError);\n }\n }\n \n // \u2705 \u0411\u0415\u0417\u041E\u041F\u0410\u0421\u041D\u0410\u042F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 \u0434\u0440\u0443\u0433\u0438\u0445 \u0447\u0443\u0432\u0441\u0442\u0432\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0445 \u0434\u0430\u043D\u043D\u044B\u0445\n if (receivingState.salt) {\n try {\n if (Array.isArray(receivingState.salt)) {\n receivingState.salt.fill(0);\n }\n receivingState.salt = null;\n } catch (saltError) {\n console.warn('\u26A0\uFE0F Failed to clear salt:', saltError);\n }\n }\n \n // \u041E\u0447\u0438\u0449\u0430\u0435\u043C \u0432\u0441\u0435 \u0441\u0432\u043E\u0439\u0441\u0442\u0432\u0430 receivingState\n for (const [key, value] of Object.entries(receivingState)) {\n if (value && typeof value === 'object') {\n if (value instanceof ArrayBuffer || value instanceof Uint8Array) {\n SecureMemoryManager.secureWipe(value);\n } else if (Array.isArray(value)) {\n value.fill(0);\n }\n receivingState[key] = null;\n }\n }\n }\n \n // \u0423\u0434\u0430\u043B\u044F\u0435\u043C \u0438\u0437 \u043E\u0441\u043D\u043E\u0432\u043D\u044B\u0445 \u043A\u043E\u043B\u043B\u0435\u043A\u0446\u0438\u0439\n this.receivingTransfers.delete(fileId);\n this.sessionKeys.delete(fileId);\n \n // \u2705 \u0411\u0415\u0417\u041E\u041F\u0410\u0421\u041D\u0410\u042F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 \u0444\u0438\u043D\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u0431\u0443\u0444\u0435\u0440\u0430 \u0444\u0430\u0439\u043B\u0430\n const fileBuffer = this.receivedFileBuffers.get(fileId);\n if (fileBuffer) {\n try {\n if (fileBuffer.buffer) {\n SecureMemoryManager.secureWipe(fileBuffer.buffer);\n \n // \u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u0430\u044F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 - \u0437\u0430\u043F\u043E\u043B\u043D\u044F\u0435\u043C \u043D\u0443\u043B\u044F\u043C\u0438\n const view = new Uint8Array(fileBuffer.buffer);\n view.fill(0);\n }\n \n // \u041E\u0447\u0438\u0449\u0430\u0435\u043C \u0432\u0441\u0435 \u0441\u0432\u043E\u0439\u0441\u0442\u0432\u0430 fileBuffer\n for (const [key, value] of Object.entries(fileBuffer)) {\n if (value && typeof value === 'object') {\n if (value instanceof ArrayBuffer || value instanceof Uint8Array) {\n SecureMemoryManager.secureWipe(value);\n }\n fileBuffer[key] = null;\n }\n }\n \n this.receivedFileBuffers.delete(fileId);\n } catch (bufferError) {\n console.warn('\u26A0\uFE0F Failed to securely clear file buffer:', bufferError);\n // \u041F\u0440\u0438\u043D\u0443\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u043E \u0443\u0434\u0430\u043B\u044F\u0435\u043C \u0434\u0430\u0436\u0435 \u043F\u0440\u0438 \u043E\u0448\u0438\u0431\u043A\u0435\n this.receivedFileBuffers.delete(fileId);\n }\n }\n \n // \u2705 \u0411\u0415\u0417\u041E\u041F\u0410\u0421\u041D\u0410\u042F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 processed chunks\n const chunksToRemove = [];\n for (const chunkId of this.processedChunks) {\n if (chunkId.startsWith(fileId)) {\n chunksToRemove.push(chunkId);\n }\n }\n \n // \u0423\u0434\u0430\u043B\u044F\u0435\u043C \u0432 \u043E\u0442\u0434\u0435\u043B\u044C\u043D\u043E\u043C \u0446\u0438\u043A\u043B\u0435 \u0434\u043B\u044F \u0438\u0437\u0431\u0435\u0436\u0430\u043D\u0438\u044F \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F \u043A\u043E\u043B\u043B\u0435\u043A\u0446\u0438\u0438 \u0432\u043E \u0432\u0440\u0435\u043C\u044F \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0438\n for (const chunkId of chunksToRemove) {\n this.processedChunks.delete(chunkId);\n }\n \n // \u041F\u0440\u0438\u043D\u0443\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u0430\u044F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 \u043F\u0430\u043C\u044F\u0442\u0438\n if (typeof global !== 'undefined' && global.gc) {\n try {\n global.gc();\n } catch (gcError) {\n // \u0418\u0433\u043D\u043E\u0440\u0438\u0440\u0443\u0435\u043C \u043E\u0448\u0438\u0431\u043A\u0438 GC\n }\n }\n \n console.log(`\uD83D\uDD12 Memory safely cleaned for file transfer: ${fileId}`);\n \n } catch (error) {\n console.error('\u274C Error during secure memory cleanup:', error);\n \n // \u041F\u0440\u0438\u043D\u0443\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u0430\u044F \u043E\u0447\u0438\u0441\u0442\u043A\u0430 \u0434\u0430\u0436\u0435 \u043F\u0440\u0438 \u043E\u0448\u0438\u0431\u043A\u0435\n this.receivingTransfers.delete(fileId);\n this.sessionKeys.delete(fileId);\n this.receivedFileBuffers.delete(fileId);\n this.pendingChunks.delete(fileId);\n \n throw new Error(`Memory cleanup failed: ${error.message}`);\n }\n }\n\n getTransferStatus(fileId) {\n if (this.activeTransfers.has(fileId)) {\n const transfer = this.activeTransfers.get(fileId);\n return {\n type: 'sending',\n fileId: transfer.fileId,\n fileName: transfer.file.name,\n progress: Math.round((transfer.sentChunks / transfer.totalChunks) * 100),\n status: transfer.status,\n startTime: transfer.startTime\n };\n }\n \n if (this.receivingTransfers.has(fileId)) {\n const transfer = this.receivingTransfers.get(fileId);\n return {\n type: 'receiving',\n fileId: transfer.fileId,\n fileName: transfer.fileName,\n progress: Math.round((transfer.receivedCount / transfer.totalChunks) * 100),\n status: transfer.status,\n startTime: transfer.startTime\n };\n }\n \n return null;\n }\n\n getSystemStatus() {\n return {\n initialized: true,\n activeTransfers: this.activeTransfers.size,\n receivingTransfers: this.receivingTransfers.size,\n totalTransfers: this.activeTransfers.size + this.receivingTransfers.size,\n maxConcurrentTransfers: this.MAX_CONCURRENT_TRANSFERS,\n maxFileSize: this.MAX_FILE_SIZE,\n chunkSize: this.CHUNK_SIZE,\n hasWebrtcManager: !!this.webrtcManager,\n isConnected: this.webrtcManager?.isConnected?.() || false,\n hasDataChannel: !!this.webrtcManager?.dataChannel,\n dataChannelState: this.webrtcManager?.dataChannel?.readyState,\n isVerified: this.webrtcManager?.isVerified,\n hasEncryptionKey: !!this.webrtcManager?.encryptionKey,\n hasMacKey: !!this.webrtcManager?.macKey,\n linkedToWebRTCManager: this.webrtcManager?.fileTransferSystem === this,\n supportedFileTypes: this.getSupportedFileTypes(),\n fileTypeInfo: this.getFileTypeInfo()\n };\n }\n\n cleanup() {\n SecureFileTransferContext.getInstance().deactivate();\n\n if (this.webrtcManager && this.webrtcManager.dataChannel && this.originalOnMessage) {\n this.webrtcManager.dataChannel.onmessage = this.originalOnMessage;\n this.originalOnMessage = null;\n }\n \n if (this.webrtcManager && this.originalProcessMessage) {\n this.webrtcManager.processMessage = this.originalProcessMessage;\n this.originalProcessMessage = null;\n }\n \n if (this.webrtcManager && this.originalRemoveSecurityLayers) {\n this.webrtcManager.removeSecurityLayers = this.originalRemoveSecurityLayers;\n this.originalRemoveSecurityLayers = null;\n }\n \n // Cleanup all active transfers with secure memory wiping\n for (const fileId of this.activeTransfers.keys()) {\n this.cleanupTransfer(fileId);\n }\n \n for (const fileId of this.receivingTransfers.keys()) {\n this.cleanupReceivingTransfer(fileId);\n }\n\n if (this.atomicOps) {\n this.atomicOps.locks.clear();\n }\n \n if (this.rateLimiter) {\n this.rateLimiter.requests.clear();\n }\n \n // Clear all state\n this.pendingChunks.clear();\n this.activeTransfers.clear();\n this.receivingTransfers.clear();\n this.transferQueue.length = 0;\n this.sessionKeys.clear();\n this.transferNonces.clear();\n this.processedChunks.clear();\n\n this.clearKeys();\n }\n\n // ============================================\n // SESSION UPDATE HANDLER - FIXED\n // ============================================\n \n onSessionUpdate(sessionData) {\n // Clear session keys cache for resync\n this.sessionKeys.clear();\n }\n\n // ============================================\n // DEBUGGING AND DIAGNOSTICS\n // ============================================\n\n diagnoseFileTransferIssue() {\n const diagnosis = {\n timestamp: new Date().toISOString(),\n fileTransferSystem: {\n initialized: !!this,\n hasWebrtcManager: !!this.webrtcManager,\n webrtcManagerType: this.webrtcManager?.constructor?.name,\n linkedToWebRTCManager: this.webrtcManager?.fileTransferSystem === this\n },\n webrtcManager: {\n hasDataChannel: !!this.webrtcManager?.dataChannel,\n dataChannelState: this.webrtcManager?.dataChannel?.readyState,\n isConnected: this.webrtcManager?.isConnected?.() || false,\n isVerified: this.webrtcManager?.isVerified,\n hasEncryptionKey: !!this.webrtcManager?.encryptionKey,\n hasMacKey: !!this.webrtcManager?.macKey,\n hasKeyFingerprint: !!this.webrtcManager?.keyFingerprint,\n hasSessionSalt: !!this.webrtcManager?.sessionSalt\n },\n securityContext: {\n contextActive: SecureFileTransferContext.getInstance().isActive(),\n securityLevel: SecureFileTransferContext.getInstance().getSecurityLevel(),\n hasAtomicOps: !!this.atomicOps,\n hasRateLimiter: !!this.rateLimiter\n },\n transfers: {\n activeTransfers: this.activeTransfers.size,\n receivingTransfers: this.receivingTransfers.size,\n pendingChunks: this.pendingChunks.size,\n sessionKeys: this.sessionKeys.size\n },\n fileTypeSupport: {\n supportedTypes: this.getSupportedFileTypes(),\n generalMaxSize: this.formatFileSize(this.MAX_FILE_SIZE),\n restrictions: Object.keys(this.FILE_TYPE_RESTRICTIONS)\n }\n };\n \n return diagnosis;\n }\n\n async debugKeyDerivation(fileId) {\n try {\n if (!this.webrtcManager.keyFingerprint || !this.webrtcManager.sessionSalt) {\n throw new Error('Session data not available');\n }\n \n // Test sender derivation\n const senderResult = await this.deriveFileSessionKey(fileId);\n \n // Test receiver derivation with same salt\n const receiverKey = await this.deriveFileSessionKeyFromSalt(fileId, senderResult.salt);\n \n // Test encryption/decryption\n const testData = new TextEncoder().encode('test data');\n const nonce = crypto.getRandomValues(new Uint8Array(12));\n \n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: nonce },\n senderResult.key,\n testData\n );\n \n const decrypted = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: nonce },\n receiverKey,\n encrypted\n );\n \n const decryptedText = new TextDecoder().decode(decrypted);\n \n if (decryptedText === 'test data') {\n return { success: true, message: 'All tests passed' };\n } else {\n throw new Error('Decryption verification failed');\n }\n \n } catch (error) {\n console.error('\u274C Key derivation test failed:', error);\n return { success: false, error: error.message };\n }\n }\n\n // ============================================\n // ALTERNATIVE METHOD OF INITIALIZING HANDLERS\n // ============================================\n\n registerWithWebRTCManager() {\n if (!this.webrtcManager) {\n throw new Error('WebRTC manager not available');\n }\n\n this.webrtcManager.fileTransferSystem = this;\n\n this.webrtcManager.setFileMessageHandler = (handler) => {\n this.webrtcManager._fileMessageHandler = handler;\n };\n\n this.webrtcManager.setFileMessageHandler((message) => {\n return this.handleFileMessage(message);\n });\n }\n\n static createFileMessageFilter(fileTransferSystem) {\n return async (event) => {\n try {\n if (typeof event.data === 'string') {\n const parsed = JSON.parse(event.data);\n \n if (fileTransferSystem.isFileTransferMessage(parsed)) {\n await fileTransferSystem.handleFileMessage(parsed);\n return true; \n }\n }\n } catch (error) {\n }\n \n return false; \n };\n }\n\n // ============================================\n // SECURITY KEY MANAGEMENT\n // ============================================\n\n setSigningKey(privateKey) {\n if (!privateKey || !(privateKey instanceof CryptoKey)) {\n throw new Error('Invalid private key for signing');\n }\n this.signingKey = privateKey;\n console.log('\uD83D\uDD12 Signing key set successfully');\n }\n\n setVerificationKey(publicKey) {\n if (!publicKey || !(publicKey instanceof CryptoKey)) {\n throw new Error('Invalid public key for verification');\n }\n this.verificationKey = publicKey;\n console.log('\uD83D\uDD12 Verification key set successfully');\n }\n\n async generateSigningKeyPair() {\n try {\n const keyPair = await crypto.subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: 2048,\n publicExponent: new Uint8Array([1, 0, 1]),\n hash: 'SHA-256'\n },\n true, // extractable\n ['sign', 'verify']\n );\n \n this.signingKey = keyPair.privateKey;\n this.verificationKey = keyPair.publicKey;\n \n console.log('\uD83D\uDD12 RSA key pair generated successfully');\n return keyPair;\n } catch (error) {\n const safeError = SecurityErrorHandler.sanitizeError(error);\n console.error('\u274C Failed to generate signing key pair:', safeError);\n throw new Error(safeError);\n }\n }\n\n clearKeys() {\n this.signingKey = null;\n this.verificationKey = null;\n console.log('\uD83D\uDD12 Security keys cleared');\n }\n\n getSecurityStatus() {\n return {\n signingEnabled: this.signingKey !== null,\n verificationEnabled: this.verificationKey !== null,\n contextActive: SecureFileTransferContext.getInstance().isActive(),\n securityLevel: SecureFileTransferContext.getInstance().getSecurityLevel()\n };\n }\n\n getClientIdentifier() {\n return this.webrtcManager?.connectionId || \n this.webrtcManager?.keyFingerprint?.substring(0, 16) || \n 'default-client';\n }\n \n destroy() {\n SecureFileTransferContext.getInstance().deactivate();\n this.clearKeys();\n console.log('\uD83D\uDD12 File transfer system destroyed safely');\n }\n}\n\nexport { EnhancedSecureFileTransfer };", "// Import EnhancedSecureFileTransfer\nimport { EnhancedSecureFileTransfer } from '../transfer/EnhancedSecureFileTransfer.js';\n\n// MUTEX SYSTEM FIXES - RESOLVING MESSAGE DELIVERY ISSUES\n// ============================================\n// Issue: After introducing the Mutex system, messages stopped being delivered between users\n// Fix: Simplified locking logic \u2014 mutex is used ONLY for critical operations\n// - Regular messages are processed WITHOUT mutex\n// - File messages are processed WITHOUT mutex \n// - Mutex is used ONLY for cryptographic operations\n// ============================================\n\nclass EnhancedSecureWebRTCManager {\n // ============================================\n // CONSTANTS\n // ============================================\n \n static TIMEOUTS = {\n KEY_ROTATION_INTERVAL: 300000, // 5 minutes\n CONNECTION_TIMEOUT: 10000, // 10 seconds \n HEARTBEAT_INTERVAL: 30000, // 30 seconds\n SECURITY_CALC_DELAY: 1000, // 1 second\n SECURITY_CALC_RETRY_DELAY: 3000, // 3 seconds\n CLEANUP_INTERVAL: 300000, // 5 minutes (periodic cleanup)\n CLEANUP_CHECK_INTERVAL: 60000, // 1 minute (cleanup check)\n ICE_GATHERING_TIMEOUT: 10000, // 10 seconds\n DISCONNECT_CLEANUP_DELAY: 500, // 500ms\n PEER_DISCONNECT_CLEANUP: 2000, // 2 seconds\n STAGE2_ACTIVATION_DELAY: 10000, // 10 seconds\n STAGE3_ACTIVATION_DELAY: 15000, // 15 seconds \n STAGE4_ACTIVATION_DELAY: 20000, // 20 seconds\n FILE_TRANSFER_INIT_DELAY: 1000, // 1 second\n FAKE_TRAFFIC_MIN_INTERVAL: 15000, // 15 seconds\n FAKE_TRAFFIC_MAX_INTERVAL: 30000, // 30 seconds\n DECOY_INITIAL_DELAY: 5000, // 5 seconds\n DECOY_TRAFFIC_MIN: 10000, // 10 seconds\n DECOY_TRAFFIC_MAX: 25000, // 25 seconds\n REORDER_TIMEOUT: 3000, // 3 seconds\n RETRY_CONNECTION_DELAY: 2000 // 2 seconds\n };\n\n static LIMITS = {\n MAX_CONNECTION_ATTEMPTS: 3,\n MAX_OLD_KEYS: 3,\n MAX_PROCESSED_MESSAGE_IDS: 1000,\n MAX_OUT_OF_ORDER_PACKETS: 5,\n MAX_DECOY_CHANNELS: 1,\n MESSAGE_RATE_LIMIT: 60, // messages per minute\n MAX_KEY_AGE: 900000, // 15 minutes\n OFFER_MAX_AGE: 3600000, // 1 hour\n SALT_SIZE_V3: 32, // bytes\n SALT_SIZE_V4: 64 // bytes\n };\n\n static SIZES = {\n VERIFICATION_CODE_MIN_LENGTH: 6,\n FAKE_TRAFFIC_MIN_SIZE: 32,\n FAKE_TRAFFIC_MAX_SIZE: 128,\n PACKET_PADDING_MIN: 64,\n PACKET_PADDING_MAX: 512,\n CHUNK_SIZE_MAX: 2048,\n CHUNK_DELAY_MIN: 100,\n CHUNK_DELAY_MAX: 500,\n FINGERPRINT_DISPLAY_LENGTH: 8,\n SESSION_ID_LENGTH: 16,\n NESTED_ENCRYPTION_IV_SIZE: 12\n };\n\n static MESSAGE_TYPES = {\n // Regular messages\n MESSAGE: 'message',\n ENHANCED_MESSAGE: 'enhanced_message',\n \n // System messages\n HEARTBEAT: 'heartbeat',\n VERIFICATION: 'verification',\n VERIFICATION_RESPONSE: 'verification_response',\n VERIFICATION_CONFIRMED: 'verification_confirmed',\n VERIFICATION_BOTH_CONFIRMED: 'verification_both_confirmed',\n PEER_DISCONNECT: 'peer_disconnect',\n SECURITY_UPGRADE: 'security_upgrade',\n KEY_ROTATION_SIGNAL: 'key_rotation_signal',\n KEY_ROTATION_READY: 'key_rotation_ready',\n \n // File transfer messages\n FILE_TRANSFER_START: 'file_transfer_start',\n FILE_TRANSFER_RESPONSE: 'file_transfer_response',\n FILE_CHUNK: 'file_chunk',\n CHUNK_CONFIRMATION: 'chunk_confirmation',\n FILE_TRANSFER_COMPLETE: 'file_transfer_complete',\n FILE_TRANSFER_ERROR: 'file_transfer_error',\n \n // Fake traffic\n FAKE: 'fake'\n };\n\n static FILTERED_RESULTS = {\n FAKE_MESSAGE: 'FAKE_MESSAGE_FILTERED',\n FILE_MESSAGE: 'FILE_MESSAGE_FILTERED', \n SYSTEM_MESSAGE: 'SYSTEM_MESSAGE_FILTERED'\n };\n\n // Static debug flag instead of this._debugMode\n static DEBUG_MODE = false; // Set to true during development, false in production\n\n\n constructor(onMessage, onStatusChange, onKeyExchange, onVerificationRequired, onAnswerError = null, onVerificationStateChange = null, config = {}) {\n // Determine runtime mode\n this._isProductionMode = this._detectProductionMode();\n // Use static flag instead of this._debugMode\n this._debugMode = !this._isProductionMode && EnhancedSecureWebRTCManager.DEBUG_MODE;\n \n // Configuration from constructor parameters instead of global flags\n this._config = {\n fakeTraffic: {\n enabled: config.fakeTraffic?.enabled ?? true,\n minInterval: config.fakeTraffic?.minInterval ?? EnhancedSecureWebRTCManager.TIMEOUTS.FAKE_TRAFFIC_MIN_INTERVAL,\n maxInterval: config.fakeTraffic?.maxInterval ?? EnhancedSecureWebRTCManager.TIMEOUTS.FAKE_TRAFFIC_MAX_INTERVAL,\n minSize: config.fakeTraffic?.minSize ?? EnhancedSecureWebRTCManager.SIZES.FAKE_TRAFFIC_MIN_SIZE,\n maxSize: config.fakeTraffic?.maxSize ?? EnhancedSecureWebRTCManager.SIZES.FAKE_TRAFFIC_MAX_SIZE,\n patterns: config.fakeTraffic?.patterns ?? ['heartbeat', 'status', 'sync']\n },\n decoyChannels: {\n enabled: config.decoyChannels?.enabled ?? true,\n maxDecoyChannels: config.decoyChannels?.maxDecoyChannels ?? EnhancedSecureWebRTCManager.LIMITS.MAX_DECOY_CHANNELS,\n decoyChannelNames: config.decoyChannels?.decoyChannelNames ?? ['heartbeat'],\n sendDecoyData: config.decoyChannels?.sendDecoyData ?? true,\n randomDecoyIntervals: config.decoyChannels?.randomDecoyIntervals ?? true\n },\n packetPadding: {\n enabled: config.packetPadding?.enabled ?? true,\n minPadding: config.packetPadding?.minPadding ?? EnhancedSecureWebRTCManager.SIZES.PACKET_PADDING_MIN,\n maxPadding: config.packetPadding?.maxPadding ?? EnhancedSecureWebRTCManager.SIZES.PACKET_PADDING_MAX,\n useRandomPadding: config.packetPadding?.useRandomPadding ?? true,\n preserveMessageSize: config.packetPadding?.preserveMessageSize ?? false\n },\n antiFingerprinting: {\n enabled: config.antiFingerprinting?.enabled ?? false,\n randomizeTiming: config.antiFingerprinting?.randomizeTiming ?? true,\n randomizeSizes: config.antiFingerprinting?.randomizeSizes ?? false,\n addNoise: config.antiFingerprinting?.addNoise ?? true,\n maskPatterns: config.antiFingerprinting?.maskPatterns ?? false,\n useRandomHeaders: config.antiFingerprinting?.useRandomHeaders ?? false\n }\n };\n\n // Initialize own logging system\n this._initializeSecureLogging();\n this._setupOwnLogger();\n this._setupProductionLogging();\n \n // Store important methods first\n this._storeImportantMethods();\n \n // Setup global API after storing methods\n this._setupSecureGlobalAPI();\n if (!window.EnhancedSecureCryptoUtils) {\n throw new Error('EnhancedSecureCryptoUtils is not loaded. Please ensure the module is loaded first.');\n }\n this.getSecurityData = () => {\n // Return only public information\n return this.lastSecurityCalculation ? {\n level: this.lastSecurityCalculation.level,\n score: this.lastSecurityCalculation.score,\n timestamp: this.lastSecurityCalculation.timestamp,\n // Do NOT return check details or sensitive data\n } : null;\n };\n this._secureLog('info', '\uD83D\uDD12 Enhanced WebRTC Manager initialized with secure API');\n this.currentSessionType = null;\n this.currentSecurityLevel = 'basic';\n this.sessionConstraints = null;\n this.peerConnection = null;\n this.dataChannel = null;\n\n\n this.onMessage = onMessage;\n this.onStatusChange = onStatusChange;\n this.onKeyExchange = onKeyExchange;\n this.onVerificationStateChange = onVerificationStateChange;\n\n this.onVerificationRequired = onVerificationRequired;\n this.onAnswerError = onAnswerError; // Callback for response processing errors\n this.isInitiator = false;\n this.connectionAttempts = 0;\n this.maxConnectionAttempts = EnhancedSecureWebRTCManager.LIMITS.MAX_CONNECTION_ATTEMPTS;\n try {\n this._initializeMutexSystem();\n} catch (error) {\n this._secureLog('error', '\u274C Failed to initialize mutex system', {\n errorType: error.constructor.name\n });\n throw new Error('Critical: Mutex system initialization failed');\n}\n\n// Post-initialization validation of the mutex system\nif (!this._validateMutexSystem()) {\n this._secureLog('error', '\u274C Mutex system validation failed after initialization');\n throw new Error('Critical: Mutex system validation failed');\n}\n\nif (typeof window !== 'undefined') {\n this._secureLog('info', '\uD83D\uDD12 Emergency mutex handlers will be available through secure API');\n}\n\nthis._secureLog('info', '\uD83D\uDD12 Enhanced Mutex system fully initialized and validated');\n this.heartbeatInterval = null;\n this.messageQueue = [];\n this.ecdhKeyPair = null;\n this.ecdsaKeyPair = null;\n if (this.fileTransferSystem) {\n this.fileTransferSystem.cleanup();\n this.fileTransferSystem = null;\n }\n this.verificationCode = null;\n this.pendingSASCode = null;\n this.isVerified = false;\n this.processedMessageIds = new Set();\n \n // Mutual verification states\n this.localVerificationConfirmed = false;\n this.remoteVerificationConfirmed = false;\n this.bothVerificationsConfirmed = false;\n \n // Store expected DTLS fingerprint for validation\n this.expectedDTLSFingerprint = null;\n this.strictDTLSValidation = true; // Can be disabled for debugging\n \n // Real Perfect Forward Secrecy implementation\n this.ephemeralKeyPairs = new Map(); // Store ephemeral keys for current session only\n this.sessionStartTime = Date.now(); // Track session lifetime for PFS\n this.messageCounter = 0;\n this.sequenceNumber = 0;\n this.expectedSequenceNumber = 0;\n this.sessionSalt = null;\n \n // Anti-Replay and Message Ordering Protection\n this.replayWindowSize = 64; // Sliding window for replay protection\n this.replayWindow = new Set(); // Track recent sequence numbers\n this.maxSequenceGap = 100; // Maximum allowed sequence gap\n this.replayProtectionEnabled = true; // Enable/disable replay protection\n this.sessionId = null; // MITM protection: Session identifier\n this.connectionId = Array.from(crypto.getRandomValues(new Uint8Array(8)))\n .map(b => b.toString(16).padStart(2, '0')).join(''); // Connection identifier for AAD\n this.peerPublicKey = null; // Store peer's public key for PFS\n this.rateLimiterId = null;\n this.intentionalDisconnect = false;\n this.lastCleanupTime = Date.now();\n \n // Reset notification flags for new connection\n this._resetNotificationFlags();\n \n \n\n this.verificationInitiationSent = false;\n this.disconnectNotificationSent = false;\n this.reconnectionFailedNotificationSent = false;\n this.peerDisconnectNotificationSent = false;\n this.connectionClosedNotificationSent = false;\n this.fakeTrafficDisabledNotificationSent = false;\n this.advancedFeaturesDisabledNotificationSent = false;\n this.securityUpgradeNotificationSent = false;\n this.lastSecurityUpgradeStage = null;\n this.securityCalculationNotificationSent = false;\n this.lastSecurityCalculationLevel = null;\n \n // File transfer integration\n this.fileTransferSystem = null;\n this.onFileProgress = null;\n \n // ============================================\n // IV REUSE PREVENTION SYSTEM\n // ============================================\n // IV REUSE PREVENTION SYSTEM WITH LIMITS\n // ============================================\n this._ivTrackingSystem = {\n usedIVs: new Set(), // Track all used IVs to prevent reuse\n ivHistory: new Map(), // Track IV usage with timestamps (max 10k entries)\n collisionCount: 0, // Track potential collisions\n maxIVHistorySize: 10000, // Maximum IV history size\n maxSessionIVs: 1000, // Maximum IVs per session\n entropyValidation: {\n minEntropy: 3.0, // Minimum entropy threshold\n entropyTests: 0,\n entropyFailures: 0\n },\n rngValidation: {\n testsPerformed: 0,\n weakRngDetected: false,\n lastValidation: 0\n },\n sessionIVs: new Map(), // Track IVs per session\n emergencyMode: false // Emergency mode if IV reuse detected\n };\n \n // IV cleanup tracking\n this._lastIVCleanupTime = null;\n \n // ============================================\n // SECURE ERROR HANDLING SYSTEM\n // ============================================\n this._secureErrorHandler = {\n errorCategories: {\n CRYPTOGRAPHIC: 'cryptographic',\n NETWORK: 'network',\n VALIDATION: 'validation',\n SYSTEM: 'system',\n UNKNOWN: 'unknown'\n },\n errorMappings: new Map(), // Map internal errors to safe messages\n errorCounts: new Map(), // Track error frequencies\n lastErrorTime: 0,\n errorThreshold: 10, // Max errors per minute\n isInErrorMode: false\n };\n \n // ============================================\n // SECURE MEMORY MANAGEMENT SYSTEM\n // ============================================\n this._secureMemoryManager = {\n sensitiveData: new WeakMap(), // Track sensitive data for secure cleanup\n cleanupQueue: [], // Queue for deferred cleanup operations\n isCleaning: false, // Prevent concurrent cleanup operations\n cleanupInterval: null, // Periodic cleanup timer\n memoryStats: {\n totalCleanups: 0,\n failedCleanups: 0,\n lastCleanup: 0\n }\n };\n this.onFileReceived = null;\n this.onFileError = null;\n \n // PFS (Perfect Forward Secrecy) Implementation\n this.keyRotationInterval = EnhancedSecureWebRTCManager.TIMEOUTS.KEY_ROTATION_INTERVAL;\n this.lastKeyRotation = Date.now();\n this.currentKeyVersion = 0;\n this.keyVersions = new Map(); // Store key versions for PFS\n this.oldKeys = new Map(); // Store old keys temporarily for decryption\n this.maxOldKeys = EnhancedSecureWebRTCManager.LIMITS.MAX_OLD_KEYS; // Keep last 3 key versions for decryption\n this.peerConnection = null;\n this.dataChannel = null;\n \n\n this.securityFeatures = {\n\n hasEncryption: true, \n hasECDH: true, \n hasECDSA: false, \n hasMutualAuth: false, \n hasMetadataProtection: false, \n hasEnhancedReplayProtection: false, \n hasNonExtractableKeys: false, \n hasRateLimiting: true, \n hasEnhancedValidation: false, \n hasPFS: true, // Real Perfect Forward Secrecy enabled \n \n // Advanced Features (Session Managed) \n hasNestedEncryption: false, \n hasPacketPadding: false, \n hasPacketReordering: false, \n hasAntiFingerprinting: false, \n hasFakeTraffic: false, \n hasDecoyChannels: false, \n hasMessageChunking: false \n };\n this._secureLog('info', '\uD83D\uDD12 Enhanced WebRTC Manager initialized with tiered security');\n \n // Log configuration for debugging\n this._secureLog('info', '\uD83D\uDD12 Configuration loaded from constructor parameters', {\n fakeTraffic: this._config.fakeTraffic.enabled,\n decoyChannels: this._config.decoyChannels.enabled,\n packetPadding: this._config.packetPadding.enabled,\n antiFingerprinting: this._config.antiFingerprinting.enabled\n });\n \n // XSS Hardening - replace all window.DEBUG_MODE references\n this._hardenDebugModeReferences();\n \n // Initialize unified scheduler for all maintenance tasks\n this._initializeUnifiedScheduler();\n \n this._syncSecurityFeaturesWithTariff();\n \n if (!this._validateCryptographicSecurity()) {\n this._secureLog('error', '\uD83D\uDEA8 CRITICAL: Cryptographic security validation failed after tariff sync');\n throw new Error('Critical cryptographic features are missing after tariff synchronization');\n }\n // ============================================\n // ENHANCED SECURITY FEATURES\n // ============================================\n \n // 1. Nested Encryption Layer\n this.nestedEncryptionKey = null;\n // Removed nestedEncryptionIV and nestedEncryptionCounter\n // Each nested encryption now generates fresh random IV for maximum security\n \n // 2. Packet Padding\n this.paddingConfig = {\n enabled: this._config.packetPadding.enabled,\n minPadding: this._config.packetPadding.minPadding,\n maxPadding: this._config.packetPadding.maxPadding,\n useRandomPadding: this._config.packetPadding.useRandomPadding,\n preserveMessageSize: this._config.packetPadding.preserveMessageSize\n };\n \n // 3. Fake Traffic Generation\n this.fakeTrafficConfig = {\n enabled: this._config.fakeTraffic.enabled,\n minInterval: this._config.fakeTraffic.minInterval,\n maxInterval: this._config.fakeTraffic.maxInterval,\n minSize: this._config.fakeTraffic.minSize,\n maxSize: this._config.fakeTraffic.maxSize,\n patterns: this._config.fakeTraffic.patterns\n };\n this.fakeTrafficTimer = null;\n this.lastFakeTraffic = 0;\n \n // 4. Message Chunking\n this.chunkingConfig = {\n enabled: false,\n maxChunkSize: EnhancedSecureWebRTCManager.SIZES.CHUNK_SIZE_MAX, \n minDelay: EnhancedSecureWebRTCManager.SIZES.CHUNK_DELAY_MIN,\n maxDelay: EnhancedSecureWebRTCManager.SIZES.CHUNK_DELAY_MAX,\n useRandomDelays: true,\n addChunkHeaders: true\n };\n this.chunkQueue = [];\n this.chunkingInProgress = false;\n \n // 5. Decoy Channels\n this.decoyChannels = new Map();\n this.decoyChannelConfig = {\n enabled: this._config.decoyChannels.enabled,\n maxDecoyChannels: this._config.decoyChannels.maxDecoyChannels,\n decoyChannelNames: this._config.decoyChannels.decoyChannelNames,\n sendDecoyData: this._config.decoyChannels.sendDecoyData,\n randomDecoyIntervals: this._config.decoyChannels.randomDecoyIntervals\n };\n this.decoyTimers = new Map();\n \n // 6. Packet Reordering Protection\n this.reorderingConfig = {\n enabled: false, \n maxOutOfOrder: EnhancedSecureWebRTCManager.LIMITS.MAX_OUT_OF_ORDER_PACKETS, \n reorderTimeout: EnhancedSecureWebRTCManager.TIMEOUTS.REORDER_TIMEOUT, \n useSequenceNumbers: true,\n useTimestamps: true\n };\n this.packetBuffer = new Map(); // sequence -> {data, timestamp}\n this.lastProcessedSequence = -1;\n \n // 7. Anti-Fingerprinting\n this.antiFingerprintingConfig = {\n enabled: this._config.antiFingerprinting.enabled,\n randomizeTiming: this._config.antiFingerprinting.randomizeTiming,\n randomizeSizes: this._config.antiFingerprinting.randomizeSizes,\n addNoise: this._config.antiFingerprinting.addNoise,\n maskPatterns: this._config.antiFingerprinting.maskPatterns,\n useRandomHeaders: this._config.antiFingerprinting.useRandomHeaders\n };\n this.fingerprintMask = this.generateFingerprintMask();\n \n // Initialize rate limiter ID\n this.rateLimiterId = `webrtc_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n \n // Start periodic cleanup\n this.startPeriodicCleanup();\n \n this.initializeEnhancedSecurity(); \n \n // ============================================\n // MUTEX SYSTEM TO PREVENT RACE CONDITIONS\n // ============================================\n\n // Mutex for key operations\n this._keyOperationMutex = {\n locked: false,\n queue: [],\n lockId: null,\n lockTimeout: null\n };\n\n // Mutex for encryption/decryption operations\n this._cryptoOperationMutex = {\n locked: false,\n queue: [],\n lockId: null,\n lockTimeout: null\n };\n\n // Mutex for connection initialization\n this._connectionOperationMutex = {\n locked: false,\n queue: [],\n lockId: null,\n lockTimeout: null\n };\n\n // Key system state\n this._keySystemState = {\n isInitializing: false,\n isRotating: false,\n isDestroying: false,\n lastOperation: null,\n lastOperationTime: Date.now()\n };\n\n // Operation counters\n this._operationCounters = {\n keyOperations: 0,\n cryptoOperations: 0,\n connectionOperations: 0\n };\n\n }\n \n /**\n * Create AAD with sequence number for anti-replay protection\n * This binds each message to its sequence number and prevents replay attacks\n */\n _createMessageAAD(messageType, messageData = null, isFileMessage = false) {\n try {\n const aad = {\n sessionId: this.currentSession?.sessionId || this.sessionId || 'unknown',\n keyFingerprint: this.keyFingerprint || 'unknown',\n sequenceNumber: this._generateNextSequenceNumber(),\n messageType: messageType,\n timestamp: Date.now(),\n connectionId: this.connectionId || 'unknown',\n isFileMessage: isFileMessage\n };\n\n // Add message-specific data if available\n if (messageData && typeof messageData === 'object') {\n if (messageData.fileId) aad.fileId = messageData.fileId;\n if (messageData.chunkIndex !== undefined) aad.chunkIndex = messageData.chunkIndex;\n if (messageData.totalChunks !== undefined) aad.totalChunks = messageData.totalChunks;\n }\n\n return JSON.stringify(aad);\n } catch (error) {\n this._secureLog('error', '\u274C Failed to create message AAD', {\n errorType: error.constructor.name,\n message: error.message,\n messageType: messageType\n });\n // Fallback to basic AAD\n return JSON.stringify({\n sessionId: 'unknown',\n keyFingerprint: 'unknown',\n sequenceNumber: Date.now(),\n messageType: messageType,\n timestamp: Date.now(),\n connectionId: 'unknown',\n isFileMessage: isFileMessage\n });\n }\n }\n \n /**\n * Generate next sequence number for outgoing messages\n * This ensures unique ordering and prevents replay attacks\n */\n _generateNextSequenceNumber() {\n const nextSeq = this.sequenceNumber++;\n \n // Reset sequence number if it gets too large\n if (this.sequenceNumber > Number.MAX_SAFE_INTEGER - 1000) {\n this.sequenceNumber = 0;\n this.expectedSequenceNumber = 0;\n this.replayWindow.clear();\n this._secureLog('warn', '\u26A0\uFE0F Sequence number reset due to overflow', {\n timestamp: Date.now()\n });\n }\n \n return nextSeq;\n }\n \n /**\n * Enhanced mutex system initialization with atomic protection\n */\n _initializeMutexSystem() {\n // Initialize standard mutexes with enhanced state tracking\n this._keyOperationMutex = {\n locked: false,\n queue: [],\n lockId: null,\n lockTimeout: null,\n lockTime: null,\n operationCount: 0\n };\n\n this._cryptoOperationMutex = {\n locked: false,\n queue: [],\n lockId: null,\n lockTimeout: null,\n lockTime: null,\n operationCount: 0\n };\n\n this._connectionOperationMutex = {\n locked: false,\n queue: [],\n lockId: null,\n lockTimeout: null,\n lockTime: null,\n operationCount: 0\n };\n\n // Enhanced key system state with atomic operation tracking\n this._keySystemState = {\n isInitializing: false,\n isRotating: false,\n isDestroying: false,\n lastOperation: null,\n lastOperationTime: Date.now(),\n operationId: null,\n concurrentOperations: 0,\n maxConcurrentOperations: 1\n };\n\n // Operation counters with atomic increments\n this._operationCounters = {\n keyOperations: 0,\n cryptoOperations: 0,\n connectionOperations: 0,\n totalOperations: 0,\n failedOperations: 0\n };\n\n this._secureLog('info', '\uD83D\uDD12 Enhanced mutex system initialized with atomic protection', {\n mutexes: ['keyOperation', 'cryptoOperation', 'connectionOperation'],\n timestamp: Date.now(),\n features: ['atomic_operations', 'race_condition_protection', 'enhanced_state_tracking']\n });\n }\n\n /**\n * XSS Hardening - Debug mode references validation\n * This method is called during initialization to ensure XSS hardening\n */\n _hardenDebugModeReferences() {\n // Log that we're hardening debug mode references\n this._secureLog('info', '\uD83D\uDD12 XSS Hardening: Debug mode references already replaced');\n }\n\n /**\n * Unified scheduler for all maintenance tasks\n * Replaces multiple setInterval calls with a single, controlled scheduler\n */\n _initializeUnifiedScheduler() {\n // Single scheduler interval for all maintenance tasks\n this._maintenanceScheduler = setInterval(() => {\n this._executeMaintenanceCycle();\n }, 300000); // Every 5 minutes\n \n // Log scheduler initialization\n this._secureLog('info', '\uD83D\uDD27 Unified maintenance scheduler initialized (5-minute cycle)');\n \n // Store scheduler reference for cleanup\n this._activeTimers = new Set([this._maintenanceScheduler]);\n }\n\n /**\n * Execute all maintenance tasks in a single cycle\n */\n _executeMaintenanceCycle() {\n try {\n this._secureLog('info', '\uD83D\uDD27 Starting maintenance cycle');\n \n // 1. Log cleanup and security audit\n this._cleanupLogs();\n this._auditLoggingSystemSecurity();\n \n // 2. Security monitoring\n this._verifyAPIIntegrity();\n this._validateCryptographicSecurity();\n this._syncSecurityFeaturesWithTariff();\n \n // 3. Resource cleanup\n this._cleanupResources();\n this._enforceResourceLimits();\n \n // 4. Key monitoring (if connected)\n if (this.isConnected && this.isVerified) {\n this._monitorKeySecurity();\n }\n \n // 5. Global exposure monitoring (debug mode only)\n if (this._debugMode) {\n this._monitorGlobalExposure();\n }\n \n // 6. Heartbeat (if enabled and connected)\n if (this._heartbeatConfig && this._heartbeatConfig.enabled && this.isConnected()) {\n this._sendHeartbeat();\n }\n \n this._secureLog('info', '\uD83D\uDD27 Maintenance cycle completed successfully');\n \n } catch (error) {\n this._secureLog('error', '\u274C Maintenance cycle failed', {\n errorType: error?.constructor?.name || 'Unknown',\n message: error?.message || 'Unknown error'\n });\n \n // Emergency cleanup on failure\n this._emergencyCleanup();\n }\n }\n\n /**\n * Enforce hard resource limits with emergency cleanup\n */\n _enforceResourceLimits() {\n const violations = [];\n \n // Check log entries\n if (this._logCounts.size > this._resourceLimits.maxLogEntries) {\n violations.push('log_entries');\n }\n \n // Check message queue\n if (this.messageQueue.length > this._resourceLimits.maxMessageQueue) {\n violations.push('message_queue');\n }\n \n // Check IV history\n if (this._ivTrackingSystem && this._ivTrackingSystem.ivHistory.size > this._resourceLimits.maxIVHistory) {\n violations.push('iv_history');\n }\n \n // Check processed message IDs\n if (this.processedMessageIds.size > this._resourceLimits.maxProcessedMessageIds) {\n violations.push('processed_message_ids');\n }\n \n // Check decoy channels\n if (this.decoyChannels.size > this._resourceLimits.maxDecoyChannels) {\n violations.push('decoy_channels');\n }\n \n // Check fake traffic messages\n if (this._fakeTrafficMessages && this._fakeTrafficMessages.length > this._resourceLimits.maxFakeTrafficMessages) {\n violations.push('fake_traffic_messages');\n }\n \n // Check chunk queue\n if (this.chunkQueue.length > this._resourceLimits.maxChunkQueue) {\n violations.push('chunk_queue');\n }\n \n // Check packet buffer\n if (this.packetBuffer && this.packetBuffer.size > this._resourceLimits.maxPacketBuffer) {\n violations.push('packet_buffer');\n }\n \n // If violations detected, trigger emergency cleanup\n if (violations.length > 0) {\n this._secureLog('warn', '\u26A0\uFE0F Resource limit violations detected', { violations });\n this._emergencyCleanup();\n }\n }\n\n /**\n * Emergency cleanup when resource limits are exceeded\n */\n _emergencyCleanup() {\n this._secureLog('warn', '\uD83D\uDEA8 EMERGENCY: Resource limits exceeded, performing emergency cleanup');\n \n try {\n // 1. Clear all logs immediately\n this._logCounts.clear();\n this._secureLog('info', '\uD83E\uDDF9 Emergency: All logs cleared');\n \n // 2. Clear message queue\n this.messageQueue.length = 0;\n this._secureLog('info', '\uD83E\uDDF9 Emergency: Message queue cleared');\n \n // 3. Enhanced IV history cleanup\n if (this._ivTrackingSystem) {\n this._ivTrackingSystem.usedIVs.clear();\n this._ivTrackingSystem.ivHistory.clear();\n this._ivTrackingSystem.sessionIVs.clear();\n this._ivTrackingSystem.collisionCount = 0;\n this._ivTrackingSystem.emergencyMode = false;\n this._secureLog('info', '\uD83E\uDDF9 Enhanced Emergency: IV tracking system cleared');\n }\n \n // 4. Clear processed message IDs\n this.processedMessageIds.clear();\n this._secureLog('info', '\uD83E\uDDF9 Emergency: Processed message IDs cleared');\n \n // 5. Enhanced decoy channels cleanup\n if (this.decoyChannels) {\n for (const [channelName, timer] of this.decoyTimers) {\n if (timer) clearTimeout(timer);\n }\n this.decoyChannels.clear();\n this.decoyTimers.clear();\n this._secureLog('info', '\uD83E\uDDF9 Enhanced Emergency: Decoy channels cleared');\n }\n \n // 6. Enhanced fake traffic cleanup\n if (this.fakeTrafficTimer) {\n clearTimeout(this.fakeTrafficTimer);\n this.fakeTrafficTimer = null;\n }\n if (this._fakeTrafficMessages) {\n this._fakeTrafficMessages.length = 0;\n this._secureLog('info', '\uD83E\uDDF9 Enhanced Emergency: Fake traffic messages cleared');\n }\n \n // 7. Clear chunk queue\n this.chunkQueue.length = 0;\n this._secureLog('info', '\uD83E\uDDF9 Emergency: Chunk queue cleared');\n \n // 8. Clear packet buffer\n if (this.packetBuffer) {\n this.packetBuffer.clear();\n this._secureLog('info', '\uD83E\uDDF9 Emergency: Packet buffer cleared');\n }\n \n // 9. Enhanced memory cleanup with quantum-resistant patterns\n this._secureMemoryManager.isCleaning = true;\n this._secureMemoryManager.cleanupQueue.length = 0;\n this._secureMemoryManager.memoryStats.lastCleanup = Date.now();\n \n // Force multiple garbage collection cycles\n if (typeof window.gc === 'function') {\n try {\n // Multiple GC cycles for thorough cleanup\n for (let i = 0; i < 3; i++) {\n window.gc();\n this._secureLog('info', `\uD83E\uDDF9 Enhanced Emergency: Garbage collection cycle ${i + 1}/3`);\n // Small delay between cycles\n if (i < 2) {\n const start = Date.now();\n while (Date.now() - start < 10) {\n // Busy wait for 10ms\n }\n }\n }\n } catch (e) {\n // Ignore GC errors\n }\n }\n \n this._secureMemoryManager.isCleaning = false;\n \n this._secureLog('info', '\u2705 Enhanced emergency cleanup completed successfully');\n \n } catch (error) {\n this._secureLog('error', '\u274C Enhanced emergency cleanup failed', {\n errorType: error?.constructor?.name || 'Unknown',\n message: error?.message || 'Unknown error'\n });\n \n // Rollback mechanism (simplified)\n this._secureMemoryManager.isCleaning = false;\n }\n }\n\n /**\n * Validate emergency cleanup success\n * @param {Object} originalState - Original state before cleanup\n * @returns {Object} Validation results\n */\n _validateEmergencyCleanup(originalState) {\n const currentState = {\n messageQueueSize: this.messageQueue.length,\n processedIdsSize: this.processedMessageIds.size,\n packetBufferSize: this.packetBuffer ? this.packetBuffer.size : 0,\n ivTrackingSize: this._ivTrackingSystem ? this._ivTrackingSystem.usedIVs.size : 0,\n decoyChannelsSize: this.decoyChannels ? this.decoyChannels.size : 0\n };\n \n const validation = {\n messageQueueCleared: currentState.messageQueueSize === 0,\n processedIdsCleared: currentState.processedIdsSize === 0,\n packetBufferCleared: currentState.packetBufferSize === 0,\n ivTrackingCleared: currentState.ivTrackingSize === 0,\n decoyChannelsCleared: currentState.decoyChannelsSize === 0,\n allCleared: (\n currentState.messageQueueSize === 0 &&\n currentState.processedIdsSize === 0 &&\n currentState.packetBufferSize === 0 &&\n currentState.ivTrackingSize === 0 &&\n currentState.decoyChannelsSize === 0\n )\n };\n \n return validation;\n }\n\n /**\n * Cleanup resources based on age and usage\n */\n _cleanupResources() {\n const now = Date.now();\n \n // Clean old processed message IDs (keep only last hour)\n if (this.processedMessageIds.size > this._emergencyThresholds.processedMessageIds) {\n this.processedMessageIds.clear();\n this._secureLog('info', '\uD83E\uDDF9 Old processed message IDs cleared');\n }\n \n // Clean old IVs\n if (this._ivTrackingSystem) {\n this._cleanupOldIVs();\n }\n \n // Clean old keys\n this.cleanupOldKeys();\n \n // Clean rate limiter\n if (window.EnhancedSecureCryptoUtils && window.EnhancedSecureCryptoUtils.rateLimiter) {\n window.EnhancedSecureCryptoUtils.rateLimiter.cleanup();\n }\n \n this._secureLog('info', '\uD83E\uDDF9 Resource cleanup completed');\n }\n\n /**\n * Monitor key security (replaces _startKeySecurityMonitoring)\n */\n _monitorKeySecurity() {\n if (this._keyStorageStats.activeKeys > 10) {\n this._secureLog('warn', '\u26A0\uFE0F High number of active keys detected. Consider rotation.');\n }\n \n if (Date.now() - (this._keyStorageStats.lastRotation || 0) > 3600000) {\n this._rotateKeys();\n }\n }\n\n /**\n * Send heartbeat message (called by unified scheduler)\n */\n _sendHeartbeat() {\n try {\n if (this.isConnected() && this.dataChannel && this.dataChannel.readyState === 'open') {\n this.dataChannel.send(JSON.stringify({ \n type: EnhancedSecureWebRTCManager.MESSAGE_TYPES.HEARTBEAT, \n timestamp: Date.now() \n }));\n \n this._heartbeatConfig.lastHeartbeat = Date.now();\n this._secureLog('debug', '\uD83D\uDC93 Heartbeat sent');\n }\n } catch (error) {\n this._secureLog('error', '\u274C Heartbeat failed:', { \n errorType: error?.constructor?.name || 'Unknown',\n message: error?.message || 'Unknown error'\n });\n }\n }\n\n /**\n * Comprehensive input validation to prevent DoS and injection attacks\n * @param {any} data - Data to validate\n * @param {string} context - Context for validation (e.g., 'sendMessage', 'sendSecureMessage')\n * @returns {Object} Validation result with isValid and sanitizedData\n */\n _validateInputData(data, context = 'unknown') {\n const validationResult = {\n isValid: false,\n sanitizedData: null,\n errors: [],\n warnings: []\n };\n\n try {\n // 1. Basic type validation\n if (data === null || data === undefined) {\n validationResult.errors.push('Data cannot be null or undefined');\n return validationResult;\n }\n\n // 2. Size validation for strings\n if (typeof data === 'string') {\n if (data.length > this._inputValidationLimits.maxStringLength) {\n validationResult.errors.push(`String too long: ${data.length} > ${this._inputValidationLimits.maxStringLength}`);\n return validationResult;\n }\n\n // 3. Malicious pattern detection for strings\n for (const pattern of this._maliciousPatterns) {\n if (pattern.test(data)) {\n validationResult.errors.push(`Malicious pattern detected: ${pattern.source}`);\n this._secureLog('warn', '\uD83D\uDEA8 Malicious pattern detected in input', {\n context: context,\n pattern: pattern.source,\n dataLength: data.length\n });\n return validationResult;\n }\n }\n\n // 4. Sanitize string data\n validationResult.sanitizedData = this._sanitizeInputString(data);\n validationResult.isValid = true;\n return validationResult;\n }\n\n // 5. Object validation\n if (typeof data === 'object') {\n // Check for circular references\n const seen = new WeakSet();\n const checkCircular = (obj, path = '') => {\n if (obj === null || typeof obj !== 'object') return;\n \n if (seen.has(obj)) {\n validationResult.errors.push(`Circular reference detected at path: ${path}`);\n return;\n }\n \n seen.add(obj);\n \n // Check object depth\n if (path.split('.').length > this._inputValidationLimits.maxObjectDepth) {\n validationResult.errors.push(`Object too deep: ${path.split('.').length} > ${this._inputValidationLimits.maxObjectDepth}`);\n return;\n }\n\n // Check array length\n if (Array.isArray(obj) && obj.length > this._inputValidationLimits.maxArrayLength) {\n validationResult.errors.push(`Array too long: ${obj.length} > ${this._inputValidationLimits.maxArrayLength}`);\n return;\n }\n\n // Recursively check all properties\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n checkCircular(obj[key], path ? `${path}.${key}` : key);\n }\n }\n };\n\n checkCircular(data);\n \n if (validationResult.errors.length > 0) {\n return validationResult;\n }\n\n // 6. Check total object size\n const objectSize = this._calculateObjectSize(data);\n if (objectSize > this._inputValidationLimits.maxMessageSize) {\n validationResult.errors.push(`Object too large: ${objectSize} bytes > ${this._inputValidationLimits.maxMessageSize} bytes`);\n return validationResult;\n }\n\n // 7. Sanitize object data\n validationResult.sanitizedData = this._sanitizeInputObject(data);\n validationResult.isValid = true;\n return validationResult;\n }\n\n // 8. ArrayBuffer validation\n if (data instanceof ArrayBuffer) {\n if (data.byteLength > this._inputValidationLimits.maxMessageSize) {\n validationResult.errors.push(`ArrayBuffer too large: ${data.byteLength} bytes > ${this._inputValidationLimits.maxMessageSize} bytes`);\n return validationResult;\n }\n \n validationResult.sanitizedData = data;\n validationResult.isValid = true;\n return validationResult;\n }\n\n // 9. Other types are not allowed\n validationResult.errors.push(`Unsupported data type: ${typeof data}`);\n return validationResult;\n\n } catch (error) {\n validationResult.errors.push(`Validation error: ${error.message}`);\n this._secureLog('error', '\u274C Input validation failed', {\n context: context,\n errorType: error?.constructor?.name || 'Unknown',\n message: error?.message || 'Unknown error'\n });\n return validationResult;\n }\n }\n\n /**\n * Calculate approximate object size in bytes\n * @param {any} obj - Object to calculate size for\n * @returns {number} Size in bytes\n */\n _calculateObjectSize(obj) {\n try {\n const jsonString = JSON.stringify(obj);\n return new TextEncoder().encode(jsonString).length;\n } catch (error) {\n // If JSON.stringify fails, estimate size\n return 1024 * 1024; // Assume 1MB to be safe\n }\n }\n\n /**\n * Sanitize string data for input validation\n * @param {string} str - String to sanitize\n * @returns {string} Sanitized string\n */\n _sanitizeInputString(str) {\n if (typeof str !== 'string') return str;\n \n // Remove null bytes\n str = str.replace(/\\0/g, '');\n \n // Normalize whitespace\n str = str.replace(/\\s+/g, ' ');\n \n // Trim\n str = str.trim();\n \n return str;\n }\n\n /**\n * Sanitize object data for input validation\n * @param {any} obj - Object to sanitize\n * @returns {any} Sanitized object\n */\n _sanitizeInputObject(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n \n if (Array.isArray(obj)) {\n return obj.map(item => this._sanitizeInputObject(item));\n }\n \n const sanitized = {};\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n const value = obj[key];\n if (typeof value === 'string') {\n sanitized[key] = this._sanitizeInputString(value);\n } else if (typeof value === 'object') {\n sanitized[key] = this._sanitizeInputObject(value);\n } else {\n sanitized[key] = value;\n }\n }\n }\n \n return sanitized;\n }\n\n /**\n * Rate limiting for message sending\n * @param {string} context - Context for rate limiting\n * @returns {boolean} true if rate limit allows\n */\n _checkRateLimit(context = 'message') {\n const now = Date.now();\n \n // Initialize rate limiter if not exists\n if (!this._rateLimiter) {\n this._rateLimiter = {\n messageCount: 0,\n lastReset: now,\n burstCount: 0,\n lastBurstReset: now\n };\n }\n \n // Reset counters if needed\n if (now - this._rateLimiter.lastReset > 60000) { // 1 minute\n this._rateLimiter.messageCount = 0;\n this._rateLimiter.lastReset = now;\n }\n \n if (now - this._rateLimiter.lastBurstReset > 1000) { // 1 second\n this._rateLimiter.burstCount = 0;\n this._rateLimiter.lastBurstReset = now;\n }\n \n // Check burst limit\n if (this._rateLimiter.burstCount >= this._inputValidationLimits.rateLimitBurstSize) {\n this._secureLog('warn', '\u26A0\uFE0F Rate limit burst exceeded', { context });\n return false;\n }\n \n // Check overall rate limit\n if (this._rateLimiter.messageCount >= this._inputValidationLimits.rateLimitMessagesPerMinute) {\n this._secureLog('warn', '\u26A0\uFE0F Rate limit exceeded', { context });\n return false;\n }\n \n // Increment counters\n this._rateLimiter.messageCount++;\n this._rateLimiter.burstCount++;\n \n return true;\n }\n\n // ============================================\n // SECURE KEY STORAGE MANAGEMENT\n // ============================================\n\n /**\n * Initializes the secure key storage\n */\n _initializeSecureKeyStorage() {\n // Initialize with the new class\n this._secureKeyStorage = new SecureKeyStorage();\n \n // Keep the stats structure for compatibility\n this._keyStorageStats = {\n totalKeys: 0,\n activeKeys: 0,\n lastAccess: null,\n lastRotation: null,\n };\n \n this._secureLog('info', '\uD83D\uDD10 Enhanced secure key storage initialized');\n }\n\n // Helper: ensure file transfer system is ready (lazy init on receiver)\n async _ensureFileTransferReady() {\n try {\n // If already initialized \u2014 done\n if (this.fileTransferSystem) {\n return true;\n }\n // Requires an open data channel and a verified connection\n if (!this.dataChannel || this.dataChannel.readyState !== 'open') {\n throw new Error('Data channel not open');\n }\n if (!this.isVerified) {\n throw new Error('Connection not verified');\n }\n // Initialization\n this.initializeFileTransfer();\n \n // \u041A\u0420\u0418\u0422\u0418\u0427\u0415\u0421\u041A\u041E\u0415 \u0418\u0421\u041F\u0420\u0410\u0412\u041B\u0415\u041D\u0418\u0415: \u0416\u0434\u0435\u043C \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u0441 \u0442\u0430\u0439\u043C\u0430\u0443\u0442\u043E\u043C\n let attempts = 0;\n const maxAttempts = 50; // 5 \u0441\u0435\u043A\u0443\u043D\u0434 \u043C\u0430\u043A\u0441\u0438\u043C\u0443\u043C\n while (!this.fileTransferSystem && attempts < maxAttempts) {\n await new Promise(r => setTimeout(r, 100));\n attempts++;\n }\n \n if (!this.fileTransferSystem) {\n throw new Error('File transfer system initialization timeout');\n }\n \n return true;\n } catch (e) {\n this._secureLog('error', '\u274C _ensureFileTransferReady failed', { \n errorType: e?.constructor?.name || 'Unknown',\n hasMessage: !!e?.message \n });\n return false;\n }\n }\n\n _getSecureKey(keyId) {\n return this._secureKeyStorage.retrieveKey(keyId);\n }\n\n async _setSecureKey(keyId, key) {\n if (!(key instanceof CryptoKey)) {\n this._secureLog('error', '\u274C Attempt to store non-CryptoKey');\n return false;\n }\n \n const success = await this._secureKeyStorage.storeKey(keyId, key, {\n version: this.currentKeyVersion,\n type: key.algorithm.name\n });\n \n if (success) {\n this._secureLog('info', `\uD83D\uDD11 Key ${keyId} stored securely with encryption`);\n }\n \n return success;\n }\n\n /**\n * Validates a key value\n * @param {CryptoKey} key - Key to validate\n * @returns {boolean} true if the key is valid\n */\n _validateKeyValue(key) {\n return key instanceof CryptoKey &&\n key.algorithm &&\n key.usages &&\n key.usages.length > 0;\n }\n\n _secureWipeKeys() {\n this._secureKeyStorage.secureWipeAll();\n this._secureLog('info', '\uD83E\uDDF9 All keys securely wiped and encrypted storage cleared');\n }\n\n /**\n * Validates key storage state\n * @returns {boolean} true if the storage is ready\n */\n _validateKeyStorage() {\n return this._secureKeyStorage instanceof SecureKeyStorage;\n }\n\n /**\n * Returns secure key storage statistics\n * @returns {object} Storage metrics\n */\n _getKeyStorageStats() {\n const stats = this._secureKeyStorage.getStorageStats();\n return {\n totalKeysCount: stats.totalKeys,\n activeKeysCount: stats.totalKeys,\n hasLastAccess: stats.metadata.some(m => m.lastAccessed),\n hasLastRotation: !!this._keyStorageStats.lastRotation,\n storageType: 'SecureKeyStorage',\n timestamp: Date.now()\n };\n }\n\n /**\n * Performs key rotation in storage\n */\n _rotateKeys() {\n const oldKeys = Array.from(this._secureKeyStorage.keys());\n this._secureKeyStorage.clear();\n this._keyStorageStats.lastRotation = Date.now();\n this._keyStorageStats.activeKeys = 0;\n this._secureLog('info', `\uD83D\uDD04 Key rotation completed. ${oldKeys.length} keys rotated`);\n }\n\n /**\n * Emergency key wipe (e.g., upon detecting a threat)\n */\n _emergencyKeyWipe() {\n this._secureWipeKeys();\n this._secureLog('error', '\uD83D\uDEA8 EMERGENCY: All keys wiped due to security threat');\n }\n\n /**\n * Starts key security monitoring\n * @deprecated Use unified scheduler instead\n */\n _startKeySecurityMonitoring() {\n // Functionality moved to unified scheduler\n this._secureLog('info', '\uD83D\uDD27 Key security monitoring moved to unified scheduler');\n }\n\n\n // ============================================\n // HELPER METHODS\n // ============================================\n /**\n * Constant-time key validation to prevent timing attacks\n * @param {CryptoKey} key - Key to validate\n * @returns {boolean} true if key is valid\n */\n _validateKeyConstantTime(key) {\n // Constant-time validation to prevent timing attacks\n let isValid = 0;\n \n // Check if key is CryptoKey instance (constant-time)\n try {\n const isCryptoKey = key instanceof CryptoKey;\n isValid += isCryptoKey ? 1 : 0;\n } catch {\n isValid += 0;\n }\n \n // Check algorithm (constant-time)\n try {\n const hasAlgorithm = !!(key && key.algorithm);\n isValid += hasAlgorithm ? 1 : 0;\n } catch {\n isValid += 0;\n }\n \n // Check type (constant-time)\n try {\n const hasType = !!(key && key.type);\n isValid += hasType ? 1 : 0;\n } catch {\n isValid += 0;\n }\n \n // Check extractable property (constant-time)\n try {\n const hasExtractable = key && key.extractable !== undefined;\n isValid += hasExtractable ? 1 : 0;\n } catch {\n isValid += 0;\n }\n \n // All checks must pass\n return isValid === 4;\n }\n\n /**\n * Constant-time key pair validation\n * @param {Object} keyPair - Key pair to validate\n * @returns {boolean} true if key pair is valid\n */\n _validateKeyPairConstantTime(keyPair) {\n if (!keyPair || typeof keyPair !== 'object') return false;\n \n const privateKeyValid = this._validateKeyConstantTime(keyPair.privateKey);\n const publicKeyValid = this._validateKeyConstantTime(keyPair.publicKey);\n \n // Constant-time AND operation\n return privateKeyValid && publicKeyValid;\n }\n\n /**\n * Enhanced secure logging system initialization\n */\n _initializeSecureLogging() {\n // Logging levels\n this._logLevels = {\n error: 0,\n warn: 1, \n info: 2,\n debug: 3,\n trace: 4\n };\n \n // Ultra-strict levels for production\n this._currentLogLevel = this._isProductionMode ? \n this._logLevels.error : // In production, ONLY critical errors\n this._logLevels.info; // In development, up to info\n \n // Reduced log limits to prevent data accumulation\n this._logCounts = new Map();\n this._maxLogCount = this._isProductionMode ? 5 : 50; // Reduced limits\n \n // Hard resource limits to prevent memory leaks\n this._resourceLimits = {\n maxLogEntries: this._isProductionMode ? 100 : 1000,\n maxMessageQueue: 1000,\n maxIVHistory: 10000,\n maxProcessedMessageIds: 5000,\n maxDecoyChannels: 100,\n maxFakeTrafficMessages: 500,\n maxChunkQueue: 200,\n maxPacketBuffer: 1000\n };\n \n // Emergency cleanup thresholds\n this._emergencyThresholds = {\n logEntries: this._resourceLimits.maxLogEntries * 0.8, // 80%\n messageQueue: this._resourceLimits.maxMessageQueue * 0.8,\n ivHistory: this._resourceLimits.maxIVHistory * 0.8,\n processedMessageIds: this._resourceLimits.maxProcessedMessageIds * 0.8\n };\n \n // Input validation limits to prevent DoS attacks\n this._inputValidationLimits = {\n maxStringLength: 100000, // 100KB for strings\n maxObjectDepth: 10, // Maximum object nesting depth\n maxArrayLength: 1000, // Maximum array length\n maxMessageSize: 1024 * 1024, // 1MB total message size\n maxConcurrentMessages: 10, // Maximum concurrent message processing\n rateLimitMessagesPerMinute: 60, // Rate limiting\n rateLimitBurstSize: 10 // Burst size for rate limiting\n };\n \n // Malicious pattern detection\n this._maliciousPatterns = [\n /)<[^<]*)*<\\/script>/gi, // Script tags\n /javascript:/gi, // JavaScript protocol\n /data:text\\/html/gi, // Data URLs with HTML\n /on\\w+\\s*=/gi, // Event handlers\n /eval\\s*\\(/gi, // eval() calls\n /document\\./gi, // Document object access\n /window\\./gi, // Window object access\n /localStorage/gi, // LocalStorage access\n /sessionStorage/gi, // SessionStorage access\n /fetch\\s*\\(/gi, // Fetch API calls\n /XMLHttpRequest/gi, // XHR calls\n /import\\s*\\(/gi, // Dynamic imports\n /require\\s*\\(/gi, // Require calls\n /process\\./gi, // Process object access\n /global/gi, // Global object access\n /__proto__/gi, // Prototype pollution\n /constructor/gi, // Constructor access\n /prototype/gi, // Prototype access\n /toString\\s*\\(/gi, // toString calls\n /valueOf\\s*\\(/gi // valueOf calls\n ];\n\n // Comprehensive blacklist with all sensitive patterns\n this._absoluteBlacklist = new Set([\n // Cryptographic keys\n 'encryptionKey', 'macKey', 'metadataKey', 'privateKey', 'publicKey',\n 'ecdhKeyPair', 'ecdsaKeyPair', 'peerPublicKey', 'nestedEncryptionKey',\n \n // Authentication and session data\n 'verificationCode', 'sessionSalt', 'keyFingerprint', 'sessionId',\n 'authChallenge', 'authProof', 'authToken', 'sessionToken',\n \n // Credentials and secrets\n 'password', 'token', 'secret', 'credential', 'signature',\n 'apiKey', 'accessKey', 'secretKey', 'privateKey',\n \n // Cryptographic materials\n 'hash', 'digest', 'nonce', 'iv', 'cipher', 'seed',\n 'entropy', 'random', 'salt', 'fingerprint',\n \n // JWT and session data\n 'jwt', 'bearer', 'refreshToken', 'accessToken',\n \n // File transfer sensitive data\n 'fileHash', 'fileSignature', 'transferKey', 'chunkKey'\n ]);\n\n // Minimal whitelist with strict validation\n this._safeFieldsWhitelist = new Set([\n // Basic status fields\n 'timestamp', 'type', 'status', 'state', 'level',\n 'isConnected', 'isVerified', 'isInitiator', 'version',\n \n // Counters and metrics (safe)\n 'count', 'total', 'active', 'inactive', 'success', 'failure',\n \n // Connection states (safe)\n 'readyState', 'connectionState', 'iceConnectionState',\n \n // Feature counts (safe)\n 'activeFeaturesCount', 'totalFeatures', 'stage',\n \n // Error types (safe)\n 'errorType', 'errorCode', 'phase', 'attempt'\n ]);\n \n // Initialize security monitoring\n this._initializeLogSecurityMonitoring();\n \n this._secureLog('info', `\uD83D\uDD27 Enhanced secure logging initialized (Production: ${this._isProductionMode})`);\n }\n\n /**\n * Initialize security monitoring for logging system\n */\n _initializeLogSecurityMonitoring() {\n // Security monitoring moved to unified scheduler\n this._logSecurityViolations = 0;\n this._maxLogSecurityViolations = 3;\n }\n\n /**\n * Audit logging system security\n */\n _auditLoggingSystemSecurity() {\n let violations = 0;\n \n // Check for excessive log counts (potential data leakage)\n for (const [key, count] of this._logCounts.entries()) {\n if (count > this._maxLogCount * 2) {\n violations++;\n this._originalConsole?.error?.(`\uD83D\uDEA8 LOG SECURITY: Excessive log count detected: ${key}`);\n }\n }\n \n // Check for blacklisted patterns in recent logs\n const recentLogs = Array.from(this._logCounts.keys());\n for (const logKey of recentLogs) {\n if (this._containsSensitiveContent(logKey)) {\n violations++;\n this._originalConsole?.error?.(`\uD83D\uDEA8 LOG SECURITY: Sensitive content in log key: ${logKey}`);\n }\n }\n \n // Emergency shutdown if too many violations\n this._logSecurityViolations += violations;\n if (this._logSecurityViolations >= this._maxLogSecurityViolations) {\n this._emergencyDisableLogging();\n this._originalConsole?.error?.('\uD83D\uDEA8 CRITICAL: Logging system disabled due to security violations');\n }\n }\n\n _secureLogShim(...args) {\n try {\n // Validate arguments array\n if (!Array.isArray(args) || args.length === 0) {\n return;\n }\n \n // Proper destructuring with fallback\n const message = args[0];\n const restArgs = args.slice(1);\n \n // Handle different argument patterns\n if (restArgs.length === 0) {\n this._secureLog('info', String(message || ''));\n return;\n }\n \n if (restArgs.length === 1) {\n this._secureLog('info', String(message || ''), restArgs[0]);\n return;\n }\n \n // Proper object structure for multiple args\n this._secureLog('info', String(message || ''), { \n additionalArgs: restArgs,\n argCount: restArgs.length \n });\n } catch (error) {\n // Better error handling - fallback to original console if available\n try {\n if (this._originalConsole?.log) {\n this._originalConsole.log(...args);\n }\n } catch (fallbackError) {\n // Silent failure to prevent execution disruption\n }\n }\n }\n\n /**\n * Setup own logger without touching global console\n */\n _setupOwnLogger() {\n // Create own logger without touching global console\n this.logger = {\n log: (message, data) => this._secureLog('info', message, data),\n info: (message, data) => this._secureLog('info', message, data),\n warn: (message, data) => this._secureLog('warn', message, data),\n error: (message, data) => this._secureLog('error', message, data),\n debug: (message, data) => this._secureLog('debug', message, data)\n };\n \n // In development, log to console; in production, use secure logging only\n if (EnhancedSecureWebRTCManager.DEBUG_MODE) {\n this._secureLog('info', '\uD83D\uDD12 Own logger created - development mode');\n } else {\n this._secureLog('info', '\uD83D\uDD12 Own logger created - production mode');\n }\n }\n /**\n * Production logging - use own logger with minimal output\n */\n _setupProductionLogging() {\n // In production, own logger becomes minimal\n if (this._isProductionMode) {\n this.logger = {\n log: () => {}, // No-op in production\n info: () => {}, // No-op in production\n warn: (message, data) => this._secureLog('warn', message, data),\n error: (message, data) => this._secureLog('error', message, data),\n debug: () => {} // No-op in production\n };\n \n this._secureLog('info', '\uD83D\uDD12 Production logging mode activated');\n }\n }\n /**\n * Secure logging with enhanced data protection\n * @param {string} level - Log level (error, warn, info, debug, trace)\n * @param {string} message - Message\n * @param {object} data - Optional payload (will be sanitized)\n */\n _secureLog(level, message, data = null) {\n // Pre-sanitization audit to prevent data leakage\n if (data && !this._auditLogMessage(message, data)) {\n // Log the attempt but block the actual data\n this._originalConsole?.error?.('\uD83D\uDEA8 SECURITY: Logging blocked due to potential data leakage');\n return;\n }\n \n // Check log level\n if (this._logLevels[level] > this._currentLogLevel) {\n return;\n }\n \n // Prevent log spam with better key generation\n const logKey = `${level}:${message.substring(0, 50)}`;\n const currentCount = this._logCounts.get(logKey) || 0;\n \n if (currentCount >= this._maxLogCount) {\n return;\n }\n \n this._logCounts.set(logKey, currentCount + 1);\n \n // Enhanced sanitization with multiple passes\n let sanitizedData = null;\n if (data) {\n // First pass: basic sanitization\n sanitizedData = this._sanitizeLogData(data);\n \n // Second pass: check if sanitized data still contains sensitive content\n if (this._containsSensitiveContent(JSON.stringify(sanitizedData))) {\n this._originalConsole?.error?.('\uD83D\uDEA8 SECURITY: Sanitized data still contains sensitive content - blocking log');\n return;\n }\n }\n \n // Production mode security - only log essential errors\n if (this._isProductionMode) {\n if (level === 'error') {\n // In production, only log error messages without sensitive data\n const safeMessage = this._sanitizeString(message);\n this._originalConsole?.error?.(safeMessage);\n }\n // Block all other log levels in production\n return;\n }\n \n // Development mode: full logging with sanitized data\n const logMethod = this._originalConsole?.[level] || this._originalConsole?.log;\n if (sanitizedData) {\n logMethod(message, sanitizedData);\n } else {\n logMethod(message);\n }\n }\n /**\n * Enhanced sanitization for log data with multiple security layers\n */\n _sanitizeLogData(data) {\n // Pre-check for sensitive content before processing\n if (typeof data === 'string') {\n return this._sanitizeString(data);\n }\n \n if (!data || typeof data !== 'object') {\n return data;\n }\n \n const sanitized = {};\n \n for (const [key, value] of Object.entries(data)) {\n const lowerKey = key.toLowerCase();\n \n // Enhanced blacklist with more comprehensive patterns\n const blacklistPatterns = [\n 'key', 'secret', 'token', 'password', 'credential', 'auth',\n 'fingerprint', 'salt', 'signature', 'private', 'encryption',\n 'mac', 'metadata', 'session', 'jwt', 'bearer', 'hash',\n 'digest', 'nonce', 'iv', 'cipher', 'seed', 'entropy'\n ];\n \n const isBlacklisted = this._absoluteBlacklist.has(key) || \n blacklistPatterns.some(pattern => lowerKey.includes(pattern));\n \n if (isBlacklisted) {\n sanitized[key] = '[SENSITIVE_DATA_BLOCKED]';\n continue;\n }\n \n // Enhanced whitelist with strict validation\n if (this._safeFieldsWhitelist.has(key)) {\n // Even whitelisted fields get sanitized if they contain sensitive data\n if (typeof value === 'string') {\n sanitized[key] = this._sanitizeString(value);\n } else {\n sanitized[key] = value;\n }\n continue;\n }\n \n // Enhanced type handling with security checks\n if (typeof value === 'boolean' || typeof value === 'number') {\n sanitized[key] = value;\n } else if (typeof value === 'string') {\n sanitized[key] = this._sanitizeString(value);\n } else if (value instanceof ArrayBuffer || value instanceof Uint8Array) {\n // Don't reveal actual byte lengths for security\n sanitized[key] = `[${value.constructor.name}( bytes)]`;\n } else if (value && typeof value === 'object') {\n // Recursive sanitization with depth limit and security check\n try {\n sanitized[key] = this._sanitizeLogData(value);\n } catch (error) {\n sanitized[key] = '[RECURSIVE_SANITIZATION_FAILED]';\n }\n } else {\n sanitized[key] = `[${typeof value}]`;\n }\n }\n \n // Final security check on sanitized data\n const sanitizedString = JSON.stringify(sanitized);\n if (this._containsSensitiveContent(sanitizedString)) {\n return { error: 'SANITIZATION_FAILED_SENSITIVE_CONTENT_DETECTED' };\n }\n \n return sanitized;\n }\n /**\n * Enhanced sanitization for strings with comprehensive pattern detection\n */\n _sanitizeString(str) {\n if (typeof str !== 'string' || str.length === 0) {\n return str;\n }\n \n // Comprehensive sensitive pattern detection\n const sensitivePatterns = [\n // Hex patterns (various lengths)\n /[a-f0-9]{16,}/i, // 16+ hex chars (covers short keys)\n /[a-f0-9]{8,}/i, // 8+ hex chars (covers shorter keys)\n \n // Base64 patterns (comprehensive)\n /[A-Za-z0-9+/]{16,}={0,2}/, // Base64 with padding\n /[A-Za-z0-9+/]{12,}/, // Base64 without padding\n /[A-Za-z0-9+/=]{10,}/, // Base64-like patterns\n \n // Base58 patterns (Bitcoin-style)\n /[1-9A-HJ-NP-Za-km-z]{16,}/, // Base58 strings\n \n // Base32 patterns\n /[A-Z2-7]{16,}={0,6}/, // Base32 with padding\n /[A-Z2-7]{12,}/, // Base32 without padding\n \n // Custom encoding patterns\n /[A-Za-z0-9\\-_]{16,}/, // URL-safe base64 variants\n /[A-Za-z0-9\\.\\-_]{16,}/, // JWT-like patterns\n \n // Long alphanumeric strings (potential keys)\n /\\b[A-Za-z0-9]{12,}\\b/, // 12+ alphanumeric chars\n /\\b[A-Za-z0-9]{8,}\\b/, // 8+ alphanumeric chars\n \n // PEM key patterns\n /BEGIN\\s+(PRIVATE|PUBLIC|RSA|DSA|EC)\\s+KEY/i,\n /END\\s+(PRIVATE|PUBLIC|RSA|DSA|EC)\\s+KEY/i,\n \n // JWT patterns\n /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,\n \n // API key patterns\n /(api[_-]?key|token|secret|password|credential)[\\s]*[:=][\\s]*[A-Za-z0-9\\-_]{8,}/i,\n \n // UUID patterns\n /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i,\n \n // Credit cards and SSN (existing patterns)\n /\\b\\d{4}[\\s-]?\\d{4}[\\s-]?\\d{4}[\\s-]?\\d{4}\\b/,\n /\\b\\d{3}-\\d{2}-\\d{4}\\b/,\n \n // Email patterns (more restrictive)\n /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}/,\n \n // Crypto-specific patterns\n /(fingerprint|hash|digest|signature)[\\s]*[:=][\\s]*[A-Za-z0-9\\-_]{8,}/i,\n /(encryption|mac|metadata)[\\s]*key[\\s]*[:=][\\s]*[A-Za-z0-9\\-_]{8,}/i,\n \n // Session and auth patterns\n /(session|auth|jwt|bearer)[\\s]*[:=][\\s]*[A-Za-z0-9\\-_]{8,}/i,\n ];\n \n // Check for sensitive patterns with early return\n for (const pattern of sensitivePatterns) {\n if (pattern.test(str)) {\n // Always fully hide sensitive data\n return '[SENSITIVE_DATA_REDACTED]';\n }\n }\n \n // Check for suspicious entropy (high randomness indicates keys)\n if (this._hasHighEntropy(str)) {\n return '[HIGH_ENTROPY_DATA_REDACTED]';\n }\n \n // Check for suspicious character distributions\n if (this._hasSuspiciousDistribution(str)) {\n return '[SUSPICIOUS_DATA_REDACTED]';\n }\n \n // For regular strings \u2014 limit length more aggressively\n if (str.length > 50) {\n return str.substring(0, 20) + '...[TRUNCATED]';\n }\n \n return str;\n }\n /**\n * Enhanced sensitive content detection\n */\n _containsSensitiveContent(str) {\n if (typeof str !== 'string') return false;\n \n // Use the same comprehensive patterns as _sanitizeString\n const sensitivePatterns = [\n /[a-f0-9]{16,}/i,\n /[A-Za-z0-9+/]{16,}={0,2}/,\n /[1-9A-HJ-NP-Za-km-z]{16,}/,\n /[A-Z2-7]{16,}={0,6}/,\n /\\b[A-Za-z0-9]{12,}\\b/,\n /BEGIN\\s+(PRIVATE|PUBLIC|RSA|DSA|EC)\\s+KEY/i,\n /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,\n /(api[_-]?key|token|secret|password|credential)[\\s]*[:=][\\s]*[A-Za-z0-9\\-_]{8,}/i,\n ];\n \n return sensitivePatterns.some(pattern => pattern.test(str)) ||\n this._hasHighEntropy(str) ||\n this._hasSuspiciousDistribution(str);\n }\n\n /**\n * Check for high entropy strings (likely cryptographic keys)\n */\n _hasHighEntropy(str) {\n if (str.length < 8) return false;\n \n // Calculate character frequency\n const charCount = {};\n for (const char of str) {\n charCount[char] = (charCount[char] || 0) + 1;\n }\n \n // Calculate Shannon entropy\n const length = str.length;\n let entropy = 0;\n \n for (const count of Object.values(charCount)) {\n const probability = count / length;\n entropy -= probability * Math.log2(probability);\n }\n \n // High entropy (>4.5 bits per character) suggests cryptographic data\n return entropy > 4.5;\n }\n\n /**\n * Check for suspicious character distributions\n */\n _hasSuspiciousDistribution(str) {\n if (str.length < 8) return false;\n \n // Check for uniform distribution of hex characters\n const hexChars = str.match(/[a-f0-9]/gi) || [];\n if (hexChars.length >= str.length * 0.8) {\n // If 80%+ are hex chars, likely a key\n return true;\n }\n \n // Check for base64-like distribution\n const base64Chars = str.match(/[A-Za-z0-9+/=]/g) || [];\n if (base64Chars.length >= str.length * 0.9) {\n // If 90%+ are base64 chars, likely encoded data\n return true;\n }\n \n // Check for very low character diversity (suggests random data)\n const uniqueChars = new Set(str).size;\n const diversityRatio = uniqueChars / str.length;\n \n // If diversity is too high (>0.8) for the length, likely random data\n if (diversityRatio > 0.8 && str.length > 16) {\n return true;\n }\n \n return false;\n }\n\n\n // ============================================\n // SECURE LOGGING SYSTEM\n // ============================================\n \n /**\n * Detects production mode\n */\n _detectProductionMode() {\n // Check various production mode indicators\n return (\n // Standard env variables\n (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production') ||\n // No debug flags\n (!this._debugMode) ||\n // Production domains\n (window.location.hostname && !window.location.hostname.includes('localhost') && \n !window.location.hostname.includes('127.0.0.1') && \n !window.location.hostname.includes('.local')) ||\n // Minified code (heuristic check)\n (typeof window.webpackHotUpdate === 'undefined' && !window.location.search.includes('debug'))\n );\n }\n // ============================================\n // FIXED SECURE GLOBAL API\n // ============================================\n \n /**\n * Sets up a secure global API with limited access\n */\n _setupSecureGlobalAPI() {\n // Log that we're starting API setup\n this._secureLog('info', '\uD83D\uDD12 Starting secure global API setup');\n \n // Create simple public API with safety checks\n const secureAPI = {};\n \n // Only bind methods that exist\n if (typeof this.sendMessage === 'function') {\n secureAPI.sendMessage = this.sendMessage.bind(this);\n }\n \n // Create simple getConnectionStatus method\n secureAPI.getConnectionStatus = () => ({\n isConnected: this.isConnected ? this.isConnected() : false,\n isVerified: this.isVerified || false,\n connectionState: this.peerConnection?.connectionState || 'disconnected'\n });\n \n // Create simple getSecurityStatus method\n secureAPI.getSecurityStatus = () => ({\n securityLevel: this.currentSecurityLevel || 'basic',\n stage: 'initialized',\n activeFeaturesCount: Object.values(this.securityFeatures || {}).filter(Boolean).length\n });\n \n if (typeof this.sendFile === 'function') {\n secureAPI.sendFile = this.sendFile.bind(this);\n }\n \n // Create simple getFileTransferStatus method\n secureAPI.getFileTransferStatus = () => ({\n initialized: !!this.fileTransferSystem,\n status: 'ready',\n activeTransfers: 0,\n receivingTransfers: 0\n });\n \n if (typeof this.disconnect === 'function') {\n secureAPI.disconnect = this.disconnect.bind(this);\n }\n \n // Create simple API object with safety checks\n const safeGlobalAPI = {\n ...secureAPI, // Spread only existing methods\n getConfiguration: () => ({\n fakeTraffic: this._config.fakeTraffic.enabled,\n decoyChannels: this._config.decoyChannels.enabled,\n packetPadding: this._config.packetPadding.enabled,\n antiFingerprinting: this._config.antiFingerprinting.enabled\n }),\n emergency: {}\n };\n \n // Only add emergency methods that exist\n if (typeof this._emergencyUnlockAllMutexes === 'function') {\n safeGlobalAPI.emergency.unlockAllMutexes = this._emergencyUnlockAllMutexes.bind(this);\n }\n \n if (typeof this._emergencyRecoverMutexSystem === 'function') {\n safeGlobalAPI.emergency.recoverMutexSystem = this._emergencyRecoverMutexSystem.bind(this);\n }\n \n if (typeof this._emergencyDisableLogging === 'function') {\n safeGlobalAPI.emergency.disableLogging = this._emergencyDisableLogging.bind(this);\n }\n \n if (typeof this._resetLoggingSystem === 'function') {\n safeGlobalAPI.emergency.resetLogging = this._resetLoggingSystem.bind(this);\n }\n \n // Add file transfer system status\n safeGlobalAPI.getFileTransferSystemStatus = () => ({\n initialized: !!this.fileTransferSystem,\n status: 'ready',\n activeTransfers: 0,\n receivingTransfers: 0\n });\n \n // Log available methods for debugging\n this._secureLog('info', '\uD83D\uDD12 API methods available', {\n sendMessage: !!secureAPI.sendMessage,\n getConnectionStatus: !!secureAPI.getConnectionStatus,\n getSecurityStatus: !!secureAPI.getSecurityStatus,\n sendFile: !!secureAPI.sendFile,\n getFileTransferStatus: !!secureAPI.getFileTransferStatus,\n disconnect: !!secureAPI.disconnect,\n getConfiguration: !!safeGlobalAPI.getConfiguration,\n emergencyMethods: Object.keys(safeGlobalAPI.emergency).length\n });\n\n // Apply Object.freeze to prevent modification\n Object.freeze(safeGlobalAPI);\n Object.freeze(safeGlobalAPI.emergency);\n\n // Export API once without monitoring\n this._createProtectedGlobalAPI(safeGlobalAPI);\n \n // Setup minimal protection\n this._setupMinimalGlobalProtection();\n \n // Log that API setup is complete\n this._secureLog('info', '\uD83D\uDD12 Secure global API setup completed successfully');\n }\n /**\n * Create simple global API export\n */\n _createProtectedGlobalAPI(safeGlobalAPI) {\n // Log that we're creating protected global API\n this._secureLog('info', '\uD83D\uDD12 Creating protected global API');\n \n // Simple API export without proxy or monitoring\n if (!window.secureBitChat) {\n this._exportAPI(safeGlobalAPI);\n } else {\n this._secureLog('warn', '\u26A0\uFE0F Global API already exists, skipping setup');\n }\n }\n \n /**\n * Simple API export without monitoring\n */\n _exportAPI(apiObject) {\n // Log that we're exporting API\n this._secureLog('info', '\uD83D\uDD12 Exporting API to window.secureBitChat');\n \n // Check if important methods are available\n if (!this._importantMethods || !this._importantMethods.defineProperty) {\n this._secureLog('error', '\u274C Important methods not available for API export, using fallback');\n // Fallback to direct Object.defineProperty\n Object.defineProperty(window, 'secureBitChat', {\n value: apiObject,\n writable: false,\n configurable: false,\n enumerable: true\n });\n } else {\n // One-time export with immutable properties\n this._importantMethods.defineProperty(window, 'secureBitChat', {\n value: apiObject,\n writable: false,\n configurable: false,\n enumerable: true\n });\n }\n \n this._secureLog('info', '\uD83D\uDD12 Secure API exported to window.secureBitChat');\n }\n \n /**\n * Setup minimal global protection\n */\n _setupMinimalGlobalProtection() {\n // Simple protection without monitoring (methods already stored)\n this._protectGlobalAPI();\n \n this._secureLog('info', '\uD83D\uDD12 Minimal global protection activated');\n }\n \n /**\n * Store important methods in closure for local use\n */\n _storeImportantMethods() {\n // Store references to important methods locally\n this._importantMethods = {\n defineProperty: Object.defineProperty,\n getOwnPropertyDescriptor: Object.getOwnPropertyDescriptor,\n freeze: Object.freeze,\n consoleLog: console.log,\n consoleError: console.error,\n consoleWarn: console.warn\n };\n \n this._secureLog('info', '\uD83D\uDD12 Important methods stored locally', {\n defineProperty: !!this._importantMethods.defineProperty,\n getOwnPropertyDescriptor: !!this._importantMethods.getOwnPropertyDescriptor,\n freeze: !!this._importantMethods.freeze\n });\n }\n\n /**\n * Simple protection without monitoring\n */\n _setupSimpleProtection() {\n this._secureLog('info', '\uD83D\uDD12 Simple protection activated - no monitoring');\n }\n\n /**\n * No global exposure prevention needed\n */\n _preventGlobalExposure() {\n this._secureLog('info', '\uD83D\uDD12 No global exposure prevention - using secure API export only');\n }\n /**\n * API integrity check - only at initialization\n */\n _verifyAPIIntegrity() {\n try {\n if (!window.secureBitChat) {\n this._secureLog('error', '\u274C SECURITY ALERT: Secure API has been removed!');\n return false;\n }\n \n const requiredMethods = ['sendMessage', 'getConnectionStatus', 'disconnect'];\n const missingMethods = requiredMethods.filter(method => \n typeof window.secureBitChat[method] !== 'function'\n );\n \n if (missingMethods.length > 0) {\n this._secureLog('error', '\u274C SECURITY ALERT: API tampering detected, missing methods:', { errorType: missingMethods?.constructor?.name || 'Unknown' });\n return false;\n }\n \n return true;\n } catch (error) {\n this._secureLog('error', '\u274C SECURITY ALERT: API integrity check failed:', { errorType: error?.constructor?.name || 'Unknown' });\n return false;\n }\n }\n // ============================================\n // ADDITIONAL SECURITY METHODS\n // ============================================\n \n /**\n * Simple global exposure check - only at initialization\n */\n _auditGlobalExposure() {\n // Only check once at initialization, no periodic scanning\n this._secureLog('info', '\uD83D\uDD12 Global exposure check completed at initialization');\n return [];\n }\n \n /**\n * No periodic security audits - only at initialization\n */\n _startSecurityAudit() {\n // Only audit once at initialization, no periodic checks\n this._secureLog('info', '\uD83D\uDD12 Security audit completed at initialization - no periodic monitoring');\n }\n \n /**\n * Simple global API protection\n */\n _protectGlobalAPI() {\n if (!window.secureBitChat) {\n this._secureLog('warn', '\u26A0\uFE0F Global API not found during protection setup');\n return;\n }\n\n try {\n // Validate API integrity once\n if (this._validateAPIIntegrityOnce()) {\n this._secureLog('info', '\uD83D\uDD12 Global API protection verified');\n }\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to verify global API protection', { \n errorType: error.constructor.name,\n errorMessage: error.message\n });\n }\n }\n \n /**\n * Validate API integrity once at initialization\n */\n _validateAPIIntegrityOnce() {\n try {\n // Check if API is properly configured\n if (!this._importantMethods || !this._importantMethods.getOwnPropertyDescriptor) {\n // Fallback to direct Object.getOwnPropertyDescriptor\n const descriptor = Object.getOwnPropertyDescriptor(window, 'secureBitChat');\n \n if (!descriptor || descriptor.configurable) {\n throw new Error('secureBitChat must not be reconfigurable!');\n }\n } else {\n const descriptor = this._importantMethods.getOwnPropertyDescriptor(window, 'secureBitChat');\n \n if (!descriptor || descriptor.configurable) {\n throw new Error('secureBitChat must not be reconfigurable!');\n }\n }\n \n this._secureLog('info', '\u2705 API integrity validated');\n return true;\n \n } catch (error) {\n this._secureLog('error', '\u274C API integrity validation failed', {\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n return false;\n }\n }\n \n /**\n * Secure memory wipe for sensitive data\n */\n _secureWipeMemory(data, context = 'unknown') {\n if (!data) return;\n \n try {\n // Different handling for different data types\n if (data instanceof ArrayBuffer) {\n this._secureWipeArrayBuffer(data, context);\n } else if (data instanceof Uint8Array) {\n this._secureWipeUint8Array(data, context);\n } else if (Array.isArray(data)) {\n this._secureWipeArray(data, context);\n } else if (typeof data === 'string') {\n this._secureWipeString(data, context);\n } else if (data instanceof CryptoKey) {\n this._secureWipeCryptoKey(data, context);\n } else if (typeof data === 'object') {\n this._secureWipeObject(data, context);\n }\n \n this._secureMemoryManager.memoryStats.totalCleanups++;\n \n } catch (error) {\n this._secureMemoryManager.memoryStats.failedCleanups++;\n this._secureLog('error', '\u274C Secure memory wipe failed', {\n context: context,\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n }\n }\n \n /**\n * Secure wipe for ArrayBuffer\n */\n _secureWipeArrayBuffer(buffer, context) {\n if (!buffer || buffer.byteLength === 0) return;\n \n try {\n const view = new Uint8Array(buffer);\n \n // Overwrite with random data first\n crypto.getRandomValues(view);\n \n // Overwrite with zeros\n view.fill(0);\n \n // Overwrite with ones\n view.fill(255);\n \n // Final zero overwrite\n view.fill(0);\n \n this._secureLog('debug', '\uD83D\uDD12 ArrayBuffer securely wiped', {\n context: context,\n size: buffer.byteLength\n });\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to wipe ArrayBuffer', {\n context: context,\n errorType: error.constructor.name\n });\n }\n }\n \n /**\n * Secure wipe for Uint8Array\n */\n _secureWipeUint8Array(array, context) {\n if (!array || array.length === 0) return;\n \n try {\n // Overwrite with random data first\n crypto.getRandomValues(array);\n \n // Overwrite with zeros\n array.fill(0);\n \n // Overwrite with ones\n array.fill(255);\n \n // Final zero overwrite\n array.fill(0);\n \n this._secureLog('debug', '\uD83D\uDD12 Uint8Array securely wiped', {\n context: context,\n size: array.length\n });\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to wipe Uint8Array', {\n context: context,\n errorType: error.constructor.name\n });\n }\n }\n \n /**\n * Secure wipe for arrays\n */\n _secureWipeArray(array, context) {\n if (!Array.isArray(array) || array.length === 0) return;\n \n try {\n // Recursively wipe each element\n array.forEach((item, index) => {\n if (item !== null && item !== undefined) {\n this._secureWipeMemory(item, `${context}[${index}]`);\n }\n });\n \n // Fill with nulls\n array.fill(null);\n \n this._secureLog('debug', '\uD83D\uDD12 Array securely wiped', {\n context: context,\n size: array.length\n });\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to wipe array', {\n context: context,\n errorType: error.constructor.name\n });\n }\n }\n \n /**\n * No string wiping - strings are immutable in JS\n */\n _secureWipeString(str, context) {\n // Strings are immutable in JavaScript, no need to wipe\n // Just remove the reference\n this._secureLog('debug', '\uD83D\uDD12 String reference removed (strings are immutable)', {\n context: context,\n length: str ? str.length : 0\n });\n }\n \n /**\n * CryptoKey cleanup - store in WeakMap for proper GC\n */\n _secureWipeCryptoKey(key, context) {\n if (!key || !(key instanceof CryptoKey)) return;\n \n try {\n // Store in WeakMap for proper garbage collection\n if (!this._cryptoKeyStorage) {\n this._cryptoKeyStorage = new WeakMap();\n }\n \n // Store reference for cleanup tracking\n this._cryptoKeyStorage.set(key, {\n context: context,\n timestamp: Date.now(),\n type: key.type\n });\n \n this._secureLog('debug', '\uD83D\uDD12 CryptoKey stored in WeakMap for cleanup', {\n context: context,\n type: key.type\n });\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to store CryptoKey for cleanup', {\n context: context,\n errorType: error.constructor.name\n });\n }\n }\n \n /**\n * Secure wipe for objects\n */\n _secureWipeObject(obj, context) {\n if (!obj || typeof obj !== 'object') return;\n \n try {\n // Recursively wipe all properties\n for (const [key, value] of Object.entries(obj)) {\n if (value !== null && value !== undefined) {\n this._secureWipeMemory(value, `${context}.${key}`);\n }\n // Set property to null\n obj[key] = null;\n }\n \n this._secureLog('debug', '\uD83D\uDD12 Object securely wiped', {\n context: context,\n properties: Object.keys(obj).length\n });\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to wipe object', {\n context: context,\n errorType: error.constructor.name\n });\n }\n }\n \n /**\n * Secure cleanup of cryptographic materials\n */\n _secureCleanupCryptographicMaterials() {\n try {\n // Secure wipe of key pairs\n if (this.ecdhKeyPair) {\n this._secureWipeMemory(this.ecdhKeyPair, 'ecdhKeyPair');\n this.ecdhKeyPair = null;\n }\n \n if (this.ecdsaKeyPair) {\n this._secureWipeMemory(this.ecdsaKeyPair, 'ecdsaKeyPair');\n this.ecdsaKeyPair = null;\n }\n \n // Secure wipe of derived keys\n if (this.encryptionKey) {\n this._secureWipeMemory(this.encryptionKey, 'encryptionKey');\n this.encryptionKey = null;\n }\n \n if (this.macKey) {\n this._secureWipeMemory(this.macKey, 'macKey');\n this.macKey = null;\n }\n \n if (this.metadataKey) {\n this._secureWipeMemory(this.metadataKey, 'metadataKey');\n this.metadataKey = null;\n }\n \n if (this.nestedEncryptionKey) {\n this._secureWipeMemory(this.nestedEncryptionKey, 'nestedEncryptionKey');\n this.nestedEncryptionKey = null;\n }\n \n // Secure wipe of session data\n if (this.sessionSalt) {\n this._secureWipeMemory(this.sessionSalt, 'sessionSalt');\n this.sessionSalt = null;\n }\n \n if (this.sessionId) {\n this._secureWipeMemory(this.sessionId, 'sessionId');\n this.sessionId = null;\n }\n \n if (this.verificationCode) {\n this._secureWipeMemory(this.verificationCode, 'verificationCode');\n this.verificationCode = null;\n }\n \n if (this.peerPublicKey) {\n this._secureWipeMemory(this.peerPublicKey, 'peerPublicKey');\n this.peerPublicKey = null;\n }\n \n if (this.keyFingerprint) {\n this._secureWipeMemory(this.keyFingerprint, 'keyFingerprint');\n this.keyFingerprint = null;\n }\n \n if (this.connectionId) {\n this._secureWipeMemory(this.connectionId, 'connectionId');\n this.connectionId = null;\n }\n \n this._secureLog('info', '\uD83D\uDD12 Cryptographic materials securely cleaned up');\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to cleanup cryptographic materials', {\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n }\n }\n \n /**\n * Force garbage collection if available\n */\n _forceGarbageCollection() {\n try {\n // Try to force garbage collection if available\n if (typeof window.gc === 'function') {\n window.gc();\n this._secureLog('debug', '\uD83D\uDD12 Garbage collection forced');\n } else if (typeof global.gc === 'function') {\n global.gc();\n this._secureLog('debug', '\uD83D\uDD12 Garbage collection forced (global)');\n } else {\n this._secureLog('debug', '\u26A0\uFE0F Garbage collection not available');\n }\n } catch (error) {\n this._secureLog('error', '\u274C Failed to force garbage collection', {\n errorType: error.constructor.name\n });\n }\n }\n \n /**\n * Perform periodic memory cleanup\n */\n _performPeriodicMemoryCleanup() {\n try {\n this._secureMemoryManager.isCleaning = true;\n \n // Clean up any remaining sensitive data\n this._secureCleanupCryptographicMaterials();\n \n // Clean up message queue if it's too large\n if (this.messageQueue && this.messageQueue.length > 100) {\n const excessMessages = this.messageQueue.splice(0, this.messageQueue.length - 50);\n excessMessages.forEach((message, index) => {\n this._secureWipeMemory(message, `periodicCleanup[${index}]`);\n });\n }\n \n // Clean up processed message IDs if too many\n if (this.processedMessageIds && this.processedMessageIds.size > 1000) {\n this.processedMessageIds.clear();\n }\n \n // Force garbage collection\n this._forceGarbageCollection();\n \n this._secureLog('debug', '\uD83D\uDD12 Periodic memory cleanup completed');\n \n } catch (error) {\n this._secureLog('error', '\u274C Error during periodic memory cleanup', {\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n } finally {\n this._secureMemoryManager.isCleaning = false;\n }\n }\n \n /**\n * Create secure error message without information disclosure\n */\n _createSecureErrorMessage(originalError, context = 'unknown') {\n try {\n // Categorize error for appropriate handling\n const category = this._categorizeError(originalError);\n \n // Generate safe error message based on category\n const safeMessage = this._getSafeErrorMessage(category, context);\n \n // Log detailed error internally for debugging\n this._secureLog('error', 'Internal error occurred', {\n category: category,\n context: context,\n errorType: originalError?.constructor?.name || 'Unknown',\n timestamp: Date.now()\n });\n \n // Track error frequency\n this._trackErrorFrequency(category);\n \n return safeMessage;\n \n } catch (error) {\n // Fallback to generic error if error handling fails\n this._secureLog('error', 'Error handling failed', {\n originalError: originalError?.message || 'Unknown',\n handlingError: error.message\n });\n return 'An unexpected error occurred';\n }\n }\n \n /**\n * Categorize error for appropriate handling\n */\n _categorizeError(error) {\n if (!error || !error.message) {\n return this._secureErrorHandler.errorCategories.UNKNOWN;\n }\n \n const message = error.message.toLowerCase();\n \n // Cryptographic errors\n if (message.includes('crypto') || \n message.includes('key') || \n message.includes('encrypt') || \n message.includes('decrypt') ||\n message.includes('sign') ||\n message.includes('verify') ||\n message.includes('ecdh') ||\n message.includes('ecdsa')) {\n return this._secureErrorHandler.errorCategories.CRYPTOGRAPHIC;\n }\n \n // Network errors\n if (message.includes('network') || \n message.includes('connection') || \n message.includes('timeout') ||\n message.includes('webrtc') ||\n message.includes('peer')) {\n return this._secureErrorHandler.errorCategories.NETWORK;\n }\n \n // Validation errors\n if (message.includes('invalid') || \n message.includes('validation') || \n message.includes('format') ||\n message.includes('type')) {\n return this._secureErrorHandler.errorCategories.VALIDATION;\n }\n \n // System errors\n if (message.includes('system') || \n message.includes('internal') || \n message.includes('memory') ||\n message.includes('resource')) {\n return this._secureErrorHandler.errorCategories.SYSTEM;\n }\n \n return this._secureErrorHandler.errorCategories.UNKNOWN;\n }\n \n /**\n * Get safe error message based on category\n */\n _getSafeErrorMessage(category, context) {\n const safeMessages = {\n [this._secureErrorHandler.errorCategories.CRYPTOGRAPHIC]: {\n 'key_generation': 'Security initialization failed',\n 'key_import': 'Security verification failed',\n 'key_derivation': 'Security setup failed',\n 'encryption': 'Message security failed',\n 'decryption': 'Message verification failed',\n 'signature': 'Authentication failed',\n 'default': 'Security operation failed'\n },\n [this._secureErrorHandler.errorCategories.NETWORK]: {\n 'connection': 'Connection failed',\n 'timeout': 'Connection timeout',\n 'peer': 'Peer connection failed',\n 'webrtc': 'Communication failed',\n 'default': 'Network operation failed'\n },\n [this._secureErrorHandler.errorCategories.VALIDATION]: {\n 'format': 'Invalid data format',\n 'type': 'Invalid data type',\n 'structure': 'Invalid data structure',\n 'default': 'Validation failed'\n },\n [this._secureErrorHandler.errorCategories.SYSTEM]: {\n 'memory': 'System resource error',\n 'resource': 'System resource unavailable',\n 'internal': 'Internal system error',\n 'default': 'System operation failed'\n },\n [this._secureErrorHandler.errorCategories.UNKNOWN]: {\n 'default': 'An unexpected error occurred'\n }\n };\n \n const categoryMessages = safeMessages[category] || safeMessages[this._secureErrorHandler.errorCategories.UNKNOWN];\n \n // Determine specific context for more precise message\n let specificContext = 'default';\n if (context.includes('key') || context.includes('crypto')) {\n specificContext = category === this._secureErrorHandler.errorCategories.CRYPTOGRAPHIC ? 'key_generation' : 'default';\n } else if (context.includes('connection') || context.includes('peer')) {\n specificContext = category === this._secureErrorHandler.errorCategories.NETWORK ? 'connection' : 'default';\n } else if (context.includes('validation') || context.includes('format')) {\n specificContext = category === this._secureErrorHandler.errorCategories.VALIDATION ? 'format' : 'default';\n }\n \n return categoryMessages[specificContext] || categoryMessages.default;\n }\n \n /**\n * Track error frequency for security monitoring\n */\n _trackErrorFrequency(category) {\n const now = Date.now();\n \n // Clean old error counts\n if (now - this._secureErrorHandler.lastErrorTime > 60000) { // 1 minute\n this._secureErrorHandler.errorCounts.clear();\n }\n \n // Increment error count\n const currentCount = this._secureErrorHandler.errorCounts.get(category) || 0;\n this._secureErrorHandler.errorCounts.set(category, currentCount + 1);\n this._secureErrorHandler.lastErrorTime = now;\n \n // Check if we're exceeding error threshold\n const totalErrors = Array.from(this._secureErrorHandler.errorCounts.values()).reduce((sum, count) => sum + count, 0);\n \n if (totalErrors > this._secureErrorHandler.errorThreshold) {\n this._secureErrorHandler.isInErrorMode = true;\n this._secureLog('warn', '\u26A0\uFE0F High error frequency detected - entering error mode', {\n totalErrors: totalErrors,\n threshold: this._secureErrorHandler.errorThreshold\n });\n }\n }\n \n /**\n * Throw secure error without information disclosure\n */\n _throwSecureError(originalError, context = 'unknown') {\n const secureMessage = this._createSecureErrorMessage(originalError, context);\n throw new Error(secureMessage);\n }\n \n /**\n * Get error handling statistics\n */\n _getErrorHandlingStats() {\n return {\n errorCounts: Object.fromEntries(this._secureErrorHandler.errorCounts),\n isInErrorMode: this._secureErrorHandler.isInErrorMode,\n lastErrorTime: this._secureErrorHandler.lastErrorTime,\n errorThreshold: this._secureErrorHandler.errorThreshold\n };\n }\n \n /**\n * Reset error handling system\n */\n _resetErrorHandlingSystem() {\n this._secureErrorHandler.errorCounts.clear();\n this._secureErrorHandler.isInErrorMode = false;\n this._secureErrorHandler.lastErrorTime = 0;\n \n this._secureLog('info', '\uD83D\uDD04 Error handling system reset');\n }\n \n /**\n * Get memory management statistics\n */\n _getMemoryManagementStats() {\n return {\n totalCleanups: this._secureMemoryManager.memoryStats.totalCleanups,\n failedCleanups: this._secureMemoryManager.memoryStats.failedCleanups,\n lastCleanup: this._secureMemoryManager.memoryStats.lastCleanup,\n isCleaning: this._secureMemoryManager.isCleaning,\n queueLength: this._secureMemoryManager.cleanupQueue.length\n };\n }\n \n /**\n * Validate API integrity and security\n */\n _validateAPIIntegrity() {\n try {\n // Check if API exists\n if (!window.secureBitChat) {\n this._secureLog('error', '\u274C Global API not found during integrity validation');\n return false;\n }\n \n // Validate required methods exist\n const requiredMethods = ['sendMessage', 'getConnectionStatus', 'getSecurityStatus', 'sendFile', 'disconnect'];\n const missingMethods = requiredMethods.filter(method => \n !window.secureBitChat[method] || typeof window.secureBitChat[method] !== 'function'\n );\n \n if (missingMethods.length > 0) {\n this._secureLog('error', '\u274C Global API integrity validation failed - missing methods', {\n missingMethods: missingMethods\n });\n return false;\n }\n \n // Test method binding integrity\n const testContext = { test: true };\n const boundMethods = requiredMethods.map(method => {\n try {\n return window.secureBitChat[method].bind(testContext);\n } catch (error) {\n return null;\n }\n });\n \n const unboundMethods = boundMethods.filter(method => method === null);\n if (unboundMethods.length > 0) {\n this._secureLog('error', '\u274C Global API integrity validation failed - method binding issues', {\n unboundMethods: unboundMethods.length\n });\n return false;\n }\n \n // Test API immutability\n try {\n const testProp = '_integrity_test_' + Date.now();\n Object.defineProperty(window.secureBitChat, testProp, {\n value: 'test',\n writable: true,\n configurable: true\n });\n \n this._secureLog('error', '\u274C Global API integrity validation failed - API is mutable');\n delete window.secureBitChat[testProp];\n return false;\n \n } catch (immutabilityError) {\n // This is expected - API should be immutable\n this._secureLog('debug', '\u2705 Global API immutability verified');\n }\n \n this._secureLog('info', '\u2705 Global API integrity validation passed');\n return true;\n \n } catch (error) {\n this._secureLog('error', '\u274C Global API integrity validation failed', {\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n return false;\n }\n }\n\n _validateCryptographicSecurity() {\n // Check if basic security features are available\n const criticalFeatures = ['hasRateLimiting'];\n const missingCritical = criticalFeatures.filter(feature => !this.securityFeatures[feature]);\n \n if (missingCritical.length > 0) {\n this._secureLog('error', '\uD83D\uDEA8 CRITICAL: Missing critical rate limiting feature', {\n missing: missingCritical,\n currentFeatures: this.securityFeatures,\n action: 'Rate limiting will be forced enabled'\n });\n\n missingCritical.forEach(feature => {\n this.securityFeatures[feature] = true;\n this._secureLog('warn', `\u26A0\uFE0F Forced enable critical: ${feature} = true`);\n });\n }\n\n // Log current security state\n const availableFeatures = Object.keys(this.securityFeatures).filter(f => this.securityFeatures[f]);\n const encryptionFeatures = ['hasEncryption', 'hasECDH', 'hasECDSA'].filter(f => this.securityFeatures[f]);\n \n this._secureLog('info', '\u2705 Cryptographic security validation passed', {\n criticalFeatures: criticalFeatures.length,\n availableFeatures: availableFeatures.length,\n encryptionFeatures: encryptionFeatures.length,\n totalSecurityFeatures: availableFeatures.length,\n note: 'Encryption features will be enabled after key generation',\n currentState: {\n hasEncryption: this.securityFeatures.hasEncryption,\n hasECDH: this.securityFeatures.hasECDH,\n hasECDSA: this.securityFeatures.hasECDSA,\n hasRateLimiting: this.securityFeatures.hasRateLimiting\n }\n });\n \n return true;\n }\n\n _syncSecurityFeaturesWithTariff() {\n if (!this.sessionManager || !this.sessionManager.isFeatureAllowedForSession) {\n this._secureLog('warn', '\u26A0\uFE0F Session manager not available, using safe default security features');\n\n // Keep existing features, only add new ones\n // Don't override hasEncryption and hasECDH if they're already true\n if (this.securityFeatures.hasEncryption === undefined) {\n this.securityFeatures.hasEncryption = false; // Will be set to true only after key generation\n }\n if (this.securityFeatures.hasECDH === undefined) {\n this.securityFeatures.hasECDH = false; // Will be set to true only after ECDH key generation\n }\n if (this.securityFeatures.hasECDSA === undefined) {\n this.securityFeatures.hasECDSA = false; // Will be set to true only after ECDSA key generation\n }\n if (this.securityFeatures.hasMutualAuth === undefined) {\n this.securityFeatures.hasMutualAuth = false; // Will be set to true only after mutual auth\n }\n if (this.securityFeatures.hasMetadataProtection === undefined) {\n this.securityFeatures.hasMetadataProtection = false;\n }\n if (this.securityFeatures.hasEnhancedReplayProtection === undefined) {\n this.securityFeatures.hasEnhancedReplayProtection = false;\n }\n if (this.securityFeatures.hasNonExtractableKeys === undefined) {\n this.securityFeatures.hasNonExtractableKeys = false;\n }\n if (this.securityFeatures.hasRateLimiting === undefined) {\n this.securityFeatures.hasRateLimiting = true; // Basic rate limiting always available\n }\n if (this.securityFeatures.hasEnhancedValidation === undefined) {\n this.securityFeatures.hasEnhancedValidation = false;\n }\n if (this.securityFeatures.hasPFS === undefined) {\n this.securityFeatures.hasPFS = false;\n }\n if (this.securityFeatures.hasNestedEncryption === undefined) {\n this.securityFeatures.hasNestedEncryption = false;\n }\n if (this.securityFeatures.hasPacketPadding === undefined) {\n this.securityFeatures.hasPacketPadding = false;\n }\n if (this.securityFeatures.hasPacketReordering === undefined) {\n this.securityFeatures.hasPacketReordering = false;\n }\n if (this.securityFeatures.hasAntiFingerprinting === undefined) {\n this.securityFeatures.hasAntiFingerprinting = false;\n }\n if (this.securityFeatures.hasFakeTraffic === undefined) {\n this.securityFeatures.hasFakeTraffic = false;\n }\n if (this.securityFeatures.hasDecoyChannels === undefined) {\n this.securityFeatures.hasDecoyChannels = false;\n }\n if (this.securityFeatures.hasMessageChunking === undefined) {\n this.securityFeatures.hasMessageChunking = false;\n }\n \n this._secureLog('info', '\u2705 Safe default security features applied (features will be enabled as they become available)');\n return;\n }\n\n let sessionType = 'demo'; \n\n if (this.sessionManager.isFeatureAllowedForSession('premium', 'hasFakeTraffic')) {\n sessionType = 'premium';\n } else if (this.sessionManager.isFeatureAllowedForSession('basic', 'hasECDSA')) {\n sessionType = 'basic';\n }\n \n this._secureLog('info', '\uD83D\uDD12 Syncing security features with tariff plan', { sessionType });\n\n const allFeatures = [\n 'hasEncryption', 'hasECDH', 'hasECDSA', 'hasMutualAuth',\n 'hasMetadataProtection', 'hasEnhancedReplayProtection',\n 'hasNonExtractableKeys', 'hasRateLimiting', 'hasEnhancedValidation', 'hasPFS',\n 'hasNestedEncryption', 'hasPacketPadding', 'hasPacketReordering',\n 'hasAntiFingerprinting', 'hasFakeTraffic', 'hasDecoyChannels', 'hasMessageChunking'\n ];\n \n allFeatures.forEach(feature => {\n const isAllowed = this.sessionManager.isFeatureAllowedForSession(sessionType, feature);\n \n if (this.securityFeatures[feature] !== isAllowed) {\n this._secureLog('info', `\uD83D\uDD04 Syncing ${feature}: ${this.securityFeatures[feature]} \u2192 ${isAllowed}`);\n this.securityFeatures[feature] = isAllowed;\n }\n });\n\n if (this.onStatusChange) {\n this.onStatusChange('security_synced', {\n type: 'tariff_sync',\n sessionType: sessionType,\n features: this.securityFeatures,\n message: `Security features synchronized with ${sessionType} tariff plan`\n });\n }\n \n this._secureLog('info', '\u2705 Security features synchronized with tariff plan', {\n sessionType,\n enabledFeatures: Object.keys(this.securityFeatures).filter(f => this.securityFeatures[f]).length,\n totalFeatures: Object.keys(this.securityFeatures).length\n });\n }\n \n /**\n * Emergency shutdown for critical issues\n */\n _emergencyShutdown(reason = 'Security breach') {\n this._secureLog('error', '\u274C EMERGENCY SHUTDOWN: ${reason}');\n \n try {\n // Clear critical data\n this.encryptionKey = null;\n this.macKey = null;\n this.metadataKey = null;\n this.verificationCode = null;\n this.keyFingerprint = null;\n this.connectionId = null;\n \n // Close connections\n if (this.dataChannel) {\n this.dataChannel.close();\n this.dataChannel = null;\n }\n if (this.peerConnection) {\n this.peerConnection.close();\n this.peerConnection = null;\n }\n \n // Clear buffers\n this.messageQueue = [];\n this.processedMessageIds.clear();\n this.packetBuffer.clear();\n \n // Notify UI\n if (this.onStatusChange) {\n this.onStatusChange('security_breach');\n }\n \n this._secureLog('info', '\uD83D\uDD12 Emergency shutdown completed');\n \n } catch (error) {\n this._secureLog('error', '\u274C Error during emergency shutdown:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }\n _finalizeSecureInitialization() {\n this._startKeySecurityMonitoring();\n \n // Verify API integrity\n if (!this._verifyAPIIntegrity()) {\n this._secureLog('error', '\u274C Security initialization failed');\n return;\n }\n\n this._startSecurityMonitoring();\n \n // Start periodic log cleanup\n setInterval(() => {\n this._cleanupLogs();\n }, 300000);\n \n this._secureLog('info', '\u2705 Secure WebRTC Manager initialization completed');\n this._secureLog('info', '\uD83D\uDD12 Global exposure protection: Monitoring only, no automatic removal');\n }\n /**\n * Start security monitoring\n * @deprecated Use unified scheduler instead\n */\n _startSecurityMonitoring() {\n // All security monitoring moved to unified scheduler\n this._secureLog('info', '\uD83D\uDD27 Security monitoring moved to unified scheduler');\n }\n /**\n * Validates connection readiness for sending data\n * @param {boolean} throwError - whether to throw on not ready\n * @returns {boolean} true if connection is ready\n */\n _validateConnection(throwError = true) {\n const isDataChannelReady = this.dataChannel && this.dataChannel.readyState === 'open';\n const isConnectionVerified = this.isVerified;\n const isValid = isDataChannelReady && isConnectionVerified;\n \n if (!isValid && throwError) {\n if (!isDataChannelReady) {\n throw new Error('Data channel not ready');\n }\n if (!isConnectionVerified) {\n throw new Error('Connection not verified');\n }\n }\n \n return isValid;\n }\n\n /**\n * Hard gate for traffic blocking without verification\n * This method enforces that NO traffic (including system messages and file transfers)\n * can pass through without proper cryptographic verification\n */\n _enforceVerificationGate(operation = 'unknown', throwError = true) {\n if (!this.isVerified) {\n const errorMessage = `SECURITY VIOLATION: ${operation} blocked - connection not cryptographically verified`;\n this._secureLog('error', errorMessage, {\n operation: operation,\n isVerified: this.isVerified,\n hasKeys: !!(this.encryptionKey && this.macKey),\n timestamp: Date.now()\n });\n \n if (throwError) {\n throw new Error(errorMessage);\n }\n return false;\n }\n return true;\n }\n\n /**\n * Safe method to set isVerified only after cryptographic verification\n * This is the ONLY method that should set isVerified = true\n */\n _setVerifiedStatus(verified, verificationMethod = 'unknown', verificationData = null) {\n if (verified) {\n // Validate that we have proper cryptographic verification\n if (!this.encryptionKey || !this.macKey) {\n throw new Error('Cannot set verified=true without encryption keys');\n }\n \n if (!verificationMethod || verificationMethod === 'unknown') {\n throw new Error('Cannot set verified=true without specifying verification method');\n }\n \n // Log the verification for audit trail\n this._secureLog('info', 'Connection verified through cryptographic verification', {\n verificationMethod: verificationMethod,\n hasEncryptionKey: !!this.encryptionKey,\n hasMacKey: !!this.macKey,\n keyFingerprint: this.keyFingerprint,\n timestamp: Date.now(),\n verificationData: verificationData ? 'provided' : 'none'\n });\n }\n \n this.isVerified = verified;\n \n if (verified) {\n this.onStatusChange('connected');\n } else {\n this.onStatusChange('disconnected');\n }\n }\n\n /**\n * Create AAD (Additional Authenticated Data) for file messages\n * This binds file messages to the current session and prevents replay attacks\n */\n _createFileMessageAAD(messageType, messageData = null) {\n // Verify that _createMessageAAD method is available\n if (typeof this._createMessageAAD !== 'function') {\n throw new Error('_createMessageAAD method is not available in _createFileMessageAAD. Manager may not be fully initialized.');\n }\n // Use the unified AAD creation method with file message flag\n return this._createMessageAAD(messageType, messageData, true);\n }\n\n /**\n * Validate AAD for file messages\n * This ensures file messages are bound to the correct session\n */\n _validateFileMessageAAD(aadString, expectedMessageType = null) {\n try {\n const aad = JSON.parse(aadString);\n \n // Validate session binding\n if (aad.sessionId !== (this.currentSession?.sessionId || 'unknown')) {\n throw new Error('AAD sessionId mismatch - possible replay attack');\n }\n \n if (aad.keyFingerprint !== (this.keyFingerprint || 'unknown')) {\n throw new Error('AAD keyFingerprint mismatch - possible key substitution attack');\n }\n \n // Validate message type if specified\n if (expectedMessageType && aad.messageType !== expectedMessageType) {\n throw new Error(`AAD messageType mismatch - expected ${expectedMessageType}, got ${aad.messageType}`);\n }\n \n // Validate timestamp (prevent very old messages)\n const now = Date.now();\n const messageAge = now - aad.timestamp;\n if (messageAge > 300000) { // 5 minutes\n throw new Error('AAD timestamp too old - possible replay attack');\n }\n \n return aad;\n } catch (error) {\n this._secureLog('error', 'AAD validation failed', { error: error.message, aadString });\n throw new Error(`AAD validation failed: ${error.message}`);\n }\n }\n\n /**\n * Extract DTLS fingerprint from SDP\n * This is essential for MITM protection\n */\n _extractDTLSFingerprintFromSDP(sdp) {\n try {\n if (!sdp || typeof sdp !== 'string') {\n throw new Error('Invalid SDP provided');\n }\n\n // Look for a=fingerprint lines in SDP with more flexible regex\n const fingerprintRegex = /a=fingerprint:([a-zA-Z0-9-]+)\\s+([A-Fa-f0-9:]+)/g;\n const fingerprints = [];\n let match;\n\n while ((match = fingerprintRegex.exec(sdp)) !== null) {\n fingerprints.push({\n algorithm: match[1].toLowerCase(),\n fingerprint: match[2].toLowerCase().replace(/:/g, '')\n });\n }\n\n if (fingerprints.length === 0) {\n // Try alternative fingerprint format\n const altFingerprintRegex = /fingerprint\\s*=\\s*([a-zA-Z0-9-]+)\\s+([A-Fa-f0-9:]+)/gi;\n while ((match = altFingerprintRegex.exec(sdp)) !== null) {\n fingerprints.push({\n algorithm: match[1].toLowerCase(),\n fingerprint: match[2].toLowerCase().replace(/:/g, '')\n });\n }\n }\n\n if (fingerprints.length === 0) {\n this._secureLog('warn', 'No DTLS fingerprints found in SDP - this may be normal for some WebRTC implementations', {\n sdpLength: sdp.length,\n sdpPreview: sdp.substring(0, 200) + '...'\n });\n throw new Error('No DTLS fingerprints found in SDP');\n }\n\n // Prefer SHA-256 fingerprints\n const sha256Fingerprint = fingerprints.find(fp => fp.algorithm === 'sha-256');\n if (sha256Fingerprint) {\n return sha256Fingerprint.fingerprint;\n }\n\n // Fallback to first available fingerprint\n return fingerprints[0].fingerprint;\n } catch (error) {\n this._secureLog('error', 'Failed to extract DTLS fingerprint from SDP', { \n error: error.message,\n sdpLength: sdp?.length || 0\n });\n throw new Error(`DTLS fingerprint extraction failed: ${error.message}`);\n }\n }\n\n /**\n * Validate DTLS fingerprint against expected value\n * This prevents MITM attacks by ensuring the remote peer has the expected certificate\n */\n _validateDTLSFingerprint(receivedFingerprint, expectedFingerprint, context = 'unknown') {\n try {\n if (!receivedFingerprint || !expectedFingerprint) {\n throw new Error('Missing fingerprint for validation');\n }\n\n // Normalize fingerprints (remove colons, convert to lowercase)\n const normalizedReceived = receivedFingerprint.toLowerCase().replace(/:/g, '');\n const normalizedExpected = expectedFingerprint.toLowerCase().replace(/:/g, '');\n\n if (normalizedReceived !== normalizedExpected) {\n this._secureLog('error', 'DTLS fingerprint mismatch - possible MITM attack', {\n context: context,\n received: normalizedReceived,\n expected: normalizedExpected,\n timestamp: Date.now()\n });\n \n throw new Error(`DTLS fingerprint mismatch - possible MITM attack in ${context}`);\n }\n\n this._secureLog('info', 'DTLS fingerprint validation successful', {\n context: context,\n fingerprint: normalizedReceived,\n timestamp: Date.now()\n });\n\n return true;\n } catch (error) {\n this._secureLog('error', 'DTLS fingerprint validation failed', { \n error: error.message, \n context: context \n });\n throw error;\n }\n }\n\n /**\n * Compute SAS (Short Authentication String) for MITM protection\n * Uses HKDF with DTLS fingerprints to generate a stable 7-digit verification code\n * @param {ArrayBuffer|Uint8Array} keyMaterialRaw - Shared secret or key fingerprint data\n * @param {string} localFP - Local DTLS fingerprint\n * @param {string} remoteFP - Remote DTLS fingerprint\n * @returns {Promise} 7-digit SAS code\n */\n async _computeSAS(keyMaterialRaw, localFP, remoteFP) {\n try {\n console.log('_computeSAS called with parameters:', {\n keyMaterialRaw: keyMaterialRaw ? `${keyMaterialRaw.constructor.name} (${keyMaterialRaw.length || keyMaterialRaw.byteLength} bytes)` : 'null/undefined',\n localFP: localFP ? `${localFP.substring(0, 20)}...` : 'null/undefined',\n remoteFP: remoteFP ? `${remoteFP.substring(0, 20)}...` : 'null/undefined'\n });\n \n if (!keyMaterialRaw || !localFP || !remoteFP) {\n const missing = [];\n if (!keyMaterialRaw) missing.push('keyMaterialRaw');\n if (!localFP) missing.push('localFP');\n if (!remoteFP) missing.push('remoteFP');\n throw new Error(`Missing required parameters for SAS computation: ${missing.join(', ')}`);\n }\n\n const enc = new TextEncoder();\n\n const salt = enc.encode(\n 'webrtc-sas|' + [localFP, remoteFP].sort().join('|')\n );\n\n let keyBuffer;\n if (keyMaterialRaw instanceof ArrayBuffer) {\n keyBuffer = keyMaterialRaw;\n } else if (keyMaterialRaw instanceof Uint8Array) {\n keyBuffer = keyMaterialRaw.buffer;\n } else if (typeof keyMaterialRaw === 'string') {\n // \u0415\u0441\u043B\u0438 \u044D\u0442\u043E \u0441\u0442\u0440\u043E\u043A\u0430 (\u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440, keyFingerprint), \u0434\u0435\u043A\u043E\u0434\u0438\u0440\u0443\u0435\u043C \u0435\u0451\n // \u041F\u0440\u0435\u0434\u043F\u043E\u043B\u0430\u0433\u0430\u0435\u043C, \u0447\u0442\u043E \u044D\u0442\u043E hex \u0441\u0442\u0440\u043E\u043A\u0430\n const hexString = keyMaterialRaw.replace(/:/g, '').replace(/\\s/g, '');\n const bytes = new Uint8Array(hexString.length / 2);\n for (let i = 0; i < hexString.length; i += 2) {\n bytes[i / 2] = parseInt(hexString.substr(i, 2), 16);\n }\n keyBuffer = bytes.buffer;\n } else {\n throw new Error('Invalid keyMaterialRaw type');\n }\n\n // \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u043C HKDF(SHA-256) \u0447\u0442\u043E\u0431\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C \u0441\u0442\u0430\u0431\u0438\u043B\u044C\u043D\u044B\u0435 64 \u0431\u0438\u0442\u0430 \u044D\u043D\u0442\u0440\u043E\u043F\u0438\u0438 \u0434\u043B\u044F \u043A\u043E\u0434\u0430\n const key = await crypto.subtle.importKey(\n 'raw',\n keyBuffer,\n 'HKDF',\n false,\n ['deriveBits']\n );\n\n const info = enc.encode('p2p-sas-v1');\n const bits = await crypto.subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt, info },\n key,\n 64 // 64 \u0431\u0438\u0442\u0430 \u0434\u043E\u0441\u0442\u0430\u0442\u043E\u0447\u043D\u043E \u0434\u043B\u044F 6\u20137 \u0437\u043D\u0430\u043A\u043E\u0432\n );\n\n const dv = new DataView(bits);\n const n = (dv.getUint32(0) ^ dv.getUint32(4)) >>> 0;\n const sasCode = String(n % 10_000_000).padStart(7, '0'); \n\n console.log('\uD83C\uDFAF _computeSAS computed code:', sasCode, '(type:', typeof sasCode, ')');\n\n this._secureLog('info', 'SAS code computed successfully', {\n localFP: localFP.substring(0, 16) + '...',\n remoteFP: remoteFP.substring(0, 16) + '...',\n sasLength: sasCode.length,\n timestamp: Date.now()\n });\n\n return sasCode;\n } catch (error) {\n this._secureLog('error', 'SAS computation failed', {\n error: error.message,\n keyMaterialType: typeof keyMaterialRaw,\n hasLocalFP: !!localFP,\n hasRemoteFP: !!remoteFP,\n timestamp: Date.now()\n });\n throw new Error(`SAS computation failed: ${error.message}`);\n }\n }\n\n /**\n * UTILITY: Decode hex keyFingerprint to Uint8Array for SAS computation\n * @param {string} hexString - Hex encoded keyFingerprint (e.g., \"aa:bb:cc:dd\")\n * @returns {Uint8Array} Decoded bytes\n */\n _decodeKeyFingerprint(hexString) {\n try {\n if (!hexString || typeof hexString !== 'string') {\n throw new Error('Invalid hex string provided');\n }\n\n // Use the utility from EnhancedSecureCryptoUtils\n return window.EnhancedSecureCryptoUtils.hexToUint8Array(hexString);\n } catch (error) {\n this._secureLog('error', 'Key fingerprint decoding failed', {\n error: error.message,\n inputType: typeof hexString,\n inputLength: hexString?.length || 0\n });\n throw new Error(`Key fingerprint decoding failed: ${error.message}`);\n }\n }\n\n /**\n * Emergency key wipe on fingerprint mismatch\n * This ensures no sensitive data remains if MITM is detected\n */\n _emergencyWipeOnFingerprintMismatch(reason = 'DTLS fingerprint mismatch') {\n try {\n this._secureLog('error', '\uD83D\uDEA8 EMERGENCY: Initiating security wipe due to fingerprint mismatch', {\n reason: reason,\n timestamp: Date.now()\n });\n\n // Wipe all cryptographic materials\n this._secureWipeKeys();\n this._secureWipeMemory(this.encryptionKey, 'emergency_wipe');\n this._secureWipeMemory(this.macKey, 'emergency_wipe');\n this._secureWipeMemory(this.metadataKey, 'emergency_wipe');\n \n // Wipe ephemeral keys for PFS\n this._wipeEphemeralKeys();\n \n // Hard wipe old keys for PFS\n this._hardWipeOldKeys();\n\n // Reset verification status\n this.isVerified = null;\n this.verificationCode = null;\n this.keyFingerprint = null;\n this.connectionId = null;\n this.expectedDTLSFingerprint = null;\n\n // Disconnect immediately\n this.disconnect();\n\n // Notify UI about security breach\n this.deliverMessageToUI('\uD83D\uDEA8 SECURITY BREACH: Connection terminated due to fingerprint mismatch. Possible MITM attack detected!', 'system');\n\n } catch (error) {\n this._secureLog('error', 'Failed to perform emergency wipe', { error: error.message });\n }\n }\n\n /**\n * Set expected DTLS fingerprint via out-of-band channel\n * This should be called after receiving the fingerprint through a secure channel\n * (e.g., QR code, voice call, in-person exchange, etc.)\n */\n setExpectedDTLSFingerprint(fingerprint, source = 'out_of_band') {\n try {\n if (!fingerprint || typeof fingerprint !== 'string') {\n throw new Error('Invalid fingerprint provided');\n }\n\n // Normalize fingerprint\n const normalizedFingerprint = fingerprint.toLowerCase().replace(/:/g, '');\n\n // Validate fingerprint format (should be hex string)\n if (!/^[a-f0-9]{40,64}$/.test(normalizedFingerprint)) {\n throw new Error('Invalid fingerprint format - must be hex string');\n }\n\n this.expectedDTLSFingerprint = normalizedFingerprint;\n\n this._secureLog('info', 'Expected DTLS fingerprint set via out-of-band channel', {\n source: source,\n fingerprint: normalizedFingerprint,\n timestamp: Date.now()\n });\n\n this.deliverMessageToUI(`\u2705 DTLS fingerprint set via ${source}. MITM protection enabled.`, 'system');\n\n } catch (error) {\n this._secureLog('error', 'Failed to set expected DTLS fingerprint', { error: error.message });\n throw error;\n }\n }\n\n /**\n * Get current DTLS fingerprint for out-of-band verification\n * This should be shared through a secure channel (QR code, voice, etc.)\n */\n getCurrentDTLSFingerprint() {\n try {\n if (!this.expectedDTLSFingerprint) {\n throw new Error('No DTLS fingerprint available - connection not established');\n }\n\n return this.expectedDTLSFingerprint;\n } catch (error) {\n this._secureLog('error', 'Failed to get current DTLS fingerprint', { error: error.message });\n throw error;\n }\n }\n\n /**\n * DEBUGGING: Temporarily disable strict DTLS validation\n * This should only be used for debugging connection issues\n */\n disableStrictDTLSValidation() {\n this.strictDTLSValidation = false;\n this._secureLog('warn', '\u26A0\uFE0F Strict DTLS validation disabled - security reduced', {\n timestamp: Date.now()\n });\n this.deliverMessageToUI('\u26A0\uFE0F DTLS validation disabled for debugging', 'system');\n }\n\n /**\n * SECURITY: Re-enable strict DTLS validation\n */\n enableStrictDTLSValidation() {\n this.strictDTLSValidation = true;\n this._secureLog('info', '\u2705 Strict DTLS validation re-enabled', {\n timestamp: Date.now()\n });\n this.deliverMessageToUI('\u2705 DTLS validation re-enabled', 'system');\n }\n\n /**\n * Generate ephemeral ECDH keys for Perfect Forward Secrecy\n * This ensures each session has unique, non-persistent keys\n */\n async _generateEphemeralECDHKeys() {\n try {\n this._secureLog('info', '\uD83D\uDD11 Generating ephemeral ECDH keys for PFS', {\n sessionStartTime: this.sessionStartTime,\n timestamp: Date.now()\n });\n\n // Generate new ephemeral ECDH key pair\n const ephemeralKeyPair = await window.EnhancedSecureCryptoUtils.generateECDHKeyPair();\n \n if (!ephemeralKeyPair || !this._validateKeyPairConstantTime(ephemeralKeyPair)) {\n throw new Error('Ephemeral ECDH key pair validation failed');\n }\n\n // Store ephemeral keys with session binding\n const sessionId = this.currentSession?.sessionId || `session_${Date.now()}`;\n this.ephemeralKeyPairs.set(sessionId, {\n keyPair: ephemeralKeyPair,\n timestamp: Date.now(),\n sessionId: sessionId\n });\n\n this._secureLog('info', '\u2705 Ephemeral ECDH keys generated for PFS', {\n sessionId: sessionId,\n timestamp: Date.now()\n });\n\n return ephemeralKeyPair;\n } catch (error) {\n this._secureLog('error', '\u274C Failed to generate ephemeral ECDH keys', { error: error.message });\n throw new Error(`Ephemeral key generation failed: ${error.message}`);\n }\n }\n\n /**\n * Hard wipe old keys for real PFS\n * This prevents retrospective decryption attacks\n */\n _hardWipeOldKeys() {\n try {\n this._secureLog('info', '\uD83E\uDDF9 Performing hard wipe of old keys for PFS', {\n oldKeysCount: this.oldKeys.size,\n timestamp: Date.now()\n });\n\n // Hard wipe all old keys\n for (const [version, keySet] of this.oldKeys.entries()) {\n if (keySet.encryptionKey) {\n this._secureWipeMemory(keySet.encryptionKey, 'pfs_key_wipe');\n }\n if (keySet.macKey) {\n this._secureWipeMemory(keySet.macKey, 'pfs_key_wipe');\n }\n if (keySet.metadataKey) {\n this._secureWipeMemory(keySet.metadataKey, 'pfs_key_wipe');\n }\n \n // Clear references\n keySet.encryptionKey = null;\n keySet.macKey = null;\n keySet.metadataKey = null;\n keySet.keyFingerprint = null;\n }\n\n // Clear the oldKeys map completely\n this.oldKeys.clear();\n\n // Force garbage collection if available\n if (typeof window.gc === 'function') {\n window.gc();\n }\n\n this._secureLog('info', '\u2705 Hard wipe of old keys completed for PFS', {\n timestamp: Date.now()\n });\n\n } catch (error) {\n this._secureLog('error', '\u274C Failed to perform hard wipe of old keys', { error: error.message });\n }\n }\n\n /**\n * Wipe ephemeral keys when session ends\n * This ensures session-specific keys are destroyed\n */\n _wipeEphemeralKeys() {\n try {\n this._secureLog('info', '\uD83E\uDDF9 Wiping ephemeral keys for PFS', {\n ephemeralKeysCount: this.ephemeralKeyPairs.size,\n timestamp: Date.now()\n });\n\n // Wipe all ephemeral key pairs\n for (const [sessionId, keyData] of this.ephemeralKeyPairs.entries()) {\n if (keyData.keyPair?.privateKey) {\n this._secureWipeMemory(keyData.keyPair.privateKey, 'ephemeral_key_wipe');\n }\n if (keyData.keyPair?.publicKey) {\n this._secureWipeMemory(keyData.keyPair.publicKey, 'ephemeral_key_wipe');\n }\n \n // Clear references\n keyData.keyPair = null;\n keyData.timestamp = null;\n keyData.sessionId = null;\n }\n\n // Clear the ephemeral keys map\n this.ephemeralKeyPairs.clear();\n\n // Force garbage collection if available\n if (typeof window.gc === 'function') {\n window.gc();\n }\n\n this._secureLog('info', '\u2705 Ephemeral keys wiped for PFS', {\n timestamp: Date.now()\n });\n\n } catch (error) {\n this._secureLog('error', '\u274C Failed to wipe ephemeral keys', { error: error.message });\n }\n }\n\n /**\n * Encrypt file messages with AAD\n * This ensures file messages are properly authenticated and bound to session\n */\n async _encryptFileMessage(messageData, aad) {\n try {\n if (!this.encryptionKey) {\n throw new Error('No encryption key available for file message');\n }\n\n // Convert message to string if it's an object\n const messageString = typeof messageData === 'string' ? messageData : JSON.stringify(messageData);\n \n // Encrypt with AAD using AES-GCM\n const encryptedData = await window.EnhancedSecureCryptoUtils.encryptDataWithAAD(\n messageString, \n this.encryptionKey, \n aad\n );\n \n // Create encrypted message wrapper\n const encryptedMessage = {\n type: 'encrypted_file_message',\n encryptedData: encryptedData,\n aad: aad,\n timestamp: Date.now(),\n keyFingerprint: this.keyFingerprint\n };\n \n return JSON.stringify(encryptedMessage);\n } catch (error) {\n this._secureLog('error', 'Failed to encrypt file message', { error: error.message });\n throw new Error(`File message encryption failed: ${error.message}`);\n }\n }\n\n /**\n * Decrypt file messages with AAD validation\n * This ensures file messages are properly authenticated and bound to session\n */\n async _decryptFileMessage(encryptedMessageString) {\n try {\n const encryptedMessage = JSON.parse(encryptedMessageString);\n \n if (encryptedMessage.type !== 'encrypted_file_message') {\n throw new Error('Invalid encrypted file message type');\n }\n \n // Validate key fingerprint\n if (encryptedMessage.keyFingerprint !== this.keyFingerprint) {\n throw new Error('Key fingerprint mismatch in encrypted file message');\n }\n \n // Validate AAD with sequence number\n const aad = this._validateMessageAAD(encryptedMessage.aad, 'file_message');\n \n if (!this.encryptionKey) {\n throw new Error('No encryption key available for file message decryption');\n }\n \n // Decrypt with AAD validation\n const decryptedData = await window.EnhancedSecureCryptoUtils.decryptDataWithAAD(\n encryptedMessage.encryptedData,\n this.encryptionKey,\n encryptedMessage.aad\n );\n \n return {\n decryptedData: decryptedData,\n aad: aad\n };\n } catch (error) {\n this._secureLog('error', 'Failed to decrypt file message', { error: error.message });\n throw new Error(`File message decryption failed: ${error.message}`);\n }\n }\n\n /**\n * Validates encryption keys readiness\n * @param {boolean} throwError - whether to throw on not ready\n * @returns {boolean} true if keys are ready\n */\n _validateEncryptionKeys(throwError = true) {\n const hasAllKeys = !!(this.encryptionKey && this.macKey && this.metadataKey);\n \n if (!hasAllKeys && throwError) {\n throw new Error('Encryption keys not initialized');\n }\n \n return hasAllKeys;\n }\n\n /**\n * Checks whether a message is a file-transfer message\n * @param {string|object} data - message payload\n * @returns {boolean} true if it's a file message\n */\n _isFileMessage(data) {\n if (typeof data === 'string') {\n try {\n const parsed = JSON.parse(data);\n return parsed.type && parsed.type.startsWith('file_');\n } catch {\n return false;\n }\n }\n \n if (typeof data === 'object' && data.type) {\n return data.type.startsWith('file_');\n }\n \n return false;\n }\n\n /**\n * Checks whether a message is a system message\n * @param {string|object} data - message payload \n * @returns {boolean} true if it's a system message\n */\n _isSystemMessage(data) {\n const systemTypes = [\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.HEARTBEAT,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_RESPONSE,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_CONFIRMED,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_BOTH_CONFIRMED,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.PEER_DISCONNECT,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.SECURITY_UPGRADE,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.KEY_ROTATION_SIGNAL,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.KEY_ROTATION_READY\n ];\n\n if (typeof data === 'string') {\n try {\n const parsed = JSON.parse(data);\n return systemTypes.includes(parsed.type);\n } catch {\n return false;\n }\n }\n \n if (typeof data === 'object' && data.type) {\n return systemTypes.includes(data.type);\n }\n \n return false;\n }\n\n /**\n * Checks whether a message is fake traffic\n * @param {any} data - message payload\n * @returns {boolean} true if it's a fake message\n */\n _isFakeMessage(data) {\n if (typeof data === 'string') {\n try {\n const parsed = JSON.parse(data);\n return parsed.type === EnhancedSecureWebRTCManager.MESSAGE_TYPES.FAKE || \n parsed.isFakeTraffic === true;\n } catch {\n return false;\n }\n }\n \n if (typeof data === 'object' && data !== null) {\n return data.type === EnhancedSecureWebRTCManager.MESSAGE_TYPES.FAKE || \n data.isFakeTraffic === true;\n }\n \n return false;\n }\n\n /**\n * Safely executes an operation with error handling\n * @param {Function} operation - operation to execute\n * @param {string} errorMessage - error message to log\n * @param {any} fallback - default value on error\n * @returns {any} operation result or fallback\n */\n _withErrorHandling(operation, errorMessage, fallback = null) {\n try {\n return operation();\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('error', '\u274C ${errorMessage}:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n return fallback;\n }\n }\n\n /**\n * Safely executes an async operation with error handling\n * @param {Function} operation - async operation\n * @param {string} errorMessage - error message to log\n * @param {any} fallback - default value on error\n * @returns {Promise} operation result or fallback\n */\n async _withAsyncErrorHandling(operation, errorMessage, fallback = null) {\n try {\n return await operation();\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('error', '\u274C ${errorMessage}:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n return fallback;\n }\n }\n\n /**\n * Checks rate limits\n * @returns {boolean} true if allowed to proceed\n */\n _checkRateLimit() {\n return window.EnhancedSecureCryptoUtils.rateLimiter.checkConnectionRate(this.rateLimiterId);\n }\n\n /**\n * Extracts message type from data\n * @param {string|object} data - message data\n * @returns {string|null} message type or null\n */\n _getMessageType(data) {\n if (typeof data === 'string') {\n try {\n const parsed = JSON.parse(data);\n return parsed.type || null;\n } catch {\n return null;\n }\n }\n \n if (typeof data === 'object' && data !== null) {\n return data.type || null;\n }\n \n return null;\n }\n\n /**\n * Resets notification flags for a new connection\n */\n _resetNotificationFlags() {\n this.lastSecurityLevelNotification = null;\n this.verificationNotificationSent = false;\n this.verificationInitiationSent = false;\n this.disconnectNotificationSent = false;\n this.reconnectionFailedNotificationSent = false;\n this.peerDisconnectNotificationSent = false;\n this.connectionClosedNotificationSent = false;\n this.fakeTrafficDisabledNotificationSent = false;\n this.advancedFeaturesDisabledNotificationSent = false;\n this.securityUpgradeNotificationSent = false;\n this.lastSecurityUpgradeStage = null;\n this.securityCalculationNotificationSent = false;\n this.lastSecurityCalculationLevel = null;\n }\n\n /**\n * Checks whether a message was filtered out\n * @param {any} result - processing result\n * @returns {boolean} true if filtered\n */\n _isFilteredMessage(result) {\n const filteredResults = Object.values(EnhancedSecureWebRTCManager.FILTERED_RESULTS);\n return filteredResults.includes(result);\n }\n /**\n * Enhanced log cleanup with security checks\n */\n _cleanupLogs() {\n // More aggressive cleanup to prevent data accumulation\n if (this._logCounts.size > 500) {\n this._logCounts.clear();\n this._secureLog('debug', '\uD83E\uDDF9 Log counts cleared due to size limit');\n }\n \n // Clean up old log entries to prevent memory leaks\n const now = Date.now();\n const maxAge = 300000; // 5 minutes\n \n // Check for suspicious log patterns\n let suspiciousCount = 0;\n for (const [key, count] of this._logCounts.entries()) {\n if (count > 10) {\n suspiciousCount++;\n }\n }\n \n // Emergency cleanup if too many suspicious patterns\n if (suspiciousCount > 20) {\n this._logCounts.clear();\n this._secureLog('warn', '\uD83D\uDEA8 Emergency log cleanup due to suspicious patterns');\n }\n \n // Reset security violation counter if system is stable\n if (this._logSecurityViolations > 0 && suspiciousCount < 5) {\n this._logSecurityViolations = Math.max(0, this._logSecurityViolations - 1);\n }\n \n // Clean up old IVs periodically\n if (!this._lastIVCleanupTime || Date.now() - this._lastIVCleanupTime > 300000) { // Every 5 minutes\n this._cleanupOldIVs();\n this._lastIVCleanupTime = Date.now();\n }\n \n // Periodic secure memory cleanup\n if (!this._secureMemoryManager.memoryStats.lastCleanup || \n Date.now() - this._secureMemoryManager.memoryStats.lastCleanup > 600000) { // Every 10 minutes\n this._performPeriodicMemoryCleanup();\n this._secureMemoryManager.memoryStats.lastCleanup = Date.now();\n }\n }\n /**\n * Secure logging stats with sensitive data protection\n */\n _getLoggingStats() {\n // Only return safe statistics\n const stats = {\n isProductionMode: this._isProductionMode,\n debugMode: this._debugMode,\n currentLogLevel: this._currentLogLevel,\n logCountsSize: this._logCounts.size,\n maxLogCount: this._maxLogCount,\n securityViolations: this._logSecurityViolations || 0,\n maxSecurityViolations: this._maxLogSecurityViolations || 3,\n systemStatus: this._currentLogLevel === -1 ? 'DISABLED' : 'ACTIVE'\n };\n \n // Sanitize any potentially sensitive data\n const sanitizedStats = {};\n for (const [key, value] of Object.entries(stats)) {\n if (typeof value === 'string' && this._containsSensitiveContent(value)) {\n sanitizedStats[key] = '[SENSITIVE_DATA_REDACTED]';\n } else {\n sanitizedStats[key] = value;\n }\n }\n \n return sanitizedStats;\n }\n /**\n * Enhanced emergency logging disable with cleanup\n */\n _emergencyDisableLogging() {\n // Immediately disable all logging levels\n this._currentLogLevel = -1;\n \n // Clear all log data to prevent memory leaks\n this._logCounts.clear();\n \n // Clear any cached sensitive data\n if (this._logSecurityViolations) {\n this._logSecurityViolations = 0;\n }\n \n // Override _secureLog to a secure no-op\n this._secureLog = () => {\n // Only allow emergency console errors\n if (arguments[0] === 'error' && this._originalConsole?.error) {\n this._originalConsole.error('\uD83D\uDEA8 SECURITY: Logging system disabled - potential data exposure prevented');\n }\n };\n \n // Store original functions before overriding\n this._originalSanitizeString = this._sanitizeString;\n this._originalSanitizeLogData = this._sanitizeLogData;\n this._originalAuditLogMessage = this._auditLogMessage;\n this._originalContainsSensitiveContent = this._containsSensitiveContent;\n \n // Override all logging methods to prevent bypass\n this._sanitizeString = () => '[LOGGING_DISABLED]';\n this._sanitizeLogData = () => ({ error: 'LOGGING_DISABLED' });\n this._auditLogMessage = () => false;\n this._containsSensitiveContent = () => true; // Block everything\n \n // Force garbage collection if available\n if (typeof window.gc === 'function') {\n try {\n window.gc();\n } catch (e) {\n // Ignore GC errors\n }\n }\n \n // Notify about the emergency shutdown\n this._originalConsole?.error?.('\uD83D\uDEA8 CRITICAL: Secure logging system disabled due to potential data exposure');\n }\n\n /**\n * Reset logging system after emergency shutdown\n * Use this function to restore normal logging functionality\n */\n _resetLoggingSystem() {\n this._secureLog('info', '\uD83D\uDD27 Resetting logging system after emergency shutdown');\n \n // Restore original sanitize functions\n this._sanitizeString = this._originalSanitizeString || ((str) => str);\n this._sanitizeLogData = this._originalSanitizeLogData || ((data) => data);\n this._auditLogMessage = this._originalAuditLogMessage || (() => true);\n this._containsSensitiveContent = this._originalContainsSensitiveContent || (() => false);\n \n // Reset security violation counters\n this._logSecurityViolations = 0;\n \n this._secureLog('info', '\u2705 Logging system reset successfully');\n }\n /**\n * Enhanced audit function for log message security\n */\n _auditLogMessage(message, data) {\n if (!data || typeof data !== 'object') return true;\n \n // Convert to string and check for sensitive content\n const dataString = JSON.stringify(data);\n \n // Check message itself for sensitive content\n if (this._containsSensitiveContent(message)) {\n this._emergencyDisableLogging();\n this._originalConsole?.error?.('\uD83D\uDEA8 SECURITY BREACH: Sensitive content detected in log message');\n return false;\n }\n \n // Check data string for sensitive content\n if (this._containsSensitiveContent(dataString)) {\n this._emergencyDisableLogging();\n this._originalConsole?.error?.('\uD83D\uDEA8 SECURITY BREACH: Sensitive content detected in log data');\n return false;\n }\n \n // Enhanced dangerous pattern detection\n const dangerousPatterns = [\n 'secret', 'token', 'password', 'credential', 'auth',\n 'fingerprint', 'salt', 'signature', 'private_key', 'api_key', 'private',\n 'encryption', 'mac', 'metadata', 'session', 'jwt', 'bearer',\n 'key', 'hash', 'digest', 'nonce', 'iv', 'cipher'\n ];\n \n const dataStringLower = dataString.toLowerCase();\n \n for (const pattern of dangerousPatterns) {\n if (dataStringLower.includes(pattern) && !this._safeFieldsWhitelist.has(pattern)) {\n this._emergencyDisableLogging();\n this._originalConsole?.error?.(`\uD83D\uDEA8 SECURITY BREACH: Dangerous pattern detected in log: ${pattern}`);\n return false;\n }\n }\n \n // Check for high entropy values in data\n for (const [key, value] of Object.entries(data)) {\n if (typeof value === 'string' && this._hasHighEntropy(value)) {\n this._emergencyDisableLogging();\n this._originalConsole?.error?.(`\uD83D\uDEA8 SECURITY BREACH: High entropy value detected in log field: ${key}`);\n return false;\n }\n }\n \n return true;\n }\n\n initializeFileTransfer() {\n try {\n this._secureLog('info', '\uD83D\uDD27 Initializing Enhanced Secure File Transfer system...');\n\n if (this.fileTransferSystem) {\n this._secureLog('info', '\u2705 File transfer system already initialized');\n return;\n }\n \n // Step-by-step readiness check\n const channelReady = !!(this.dataChannel && this.dataChannel.readyState === 'open');\n if (!channelReady) {\n this._secureLog('warn', '\u26A0\uFE0F Data channel not open, deferring file transfer initialization');\n if (this.dataChannel) {\n const initHandler = () => {\n this._secureLog('info', '\uD83D\uDD04 DataChannel opened, initializing file transfer...');\n this.initializeFileTransfer();\n };\n this.dataChannel.addEventListener('open', initHandler, { once: true });\n }\n return;\n }\n\n if (!this.isVerified) {\n this._secureLog('warn', '\u26A0\uFE0F Connection not verified yet, deferring file transfer initialization');\n setTimeout(() => this.initializeFileTransfer(), 500);\n return;\n }\n \n // FIX: Clean up previous system if present\n if (this.fileTransferSystem) {\n this._secureLog('info', '\uD83E\uDDF9 Cleaning up existing file transfer system');\n this.fileTransferSystem.cleanup();\n this.fileTransferSystem = null;\n }\n \n // Ensure encryption keys are present\n if (!this.encryptionKey || !this.macKey) {\n this._secureLog('warn', '\u26A0\uFE0F Encryption keys not ready, deferring file transfer initialization');\n setTimeout(() => this.initializeFileTransfer(), 1000);\n return;\n }\n \n // IMPORTANT: callback order: (onProgress, onComplete, onError, onFileReceived)\n const safeOnComplete = (summary) => {\n // Sender: finalize transfer, no Blob handling\n try {\n this._secureLog('info', '\uD83C\uDFC1 Sender transfer summary', { summary });\n // Optionally forward as progress/UI event\n if (this.onFileProgress) {\n this.onFileProgress({ type: 'complete', ...summary });\n }\n } catch (e) {\n this._secureLog('warn', '\u26A0\uFE0F onComplete handler failed:', { details: e.message });\n }\n };\n\n this.fileTransferSystem = new EnhancedSecureFileTransfer(\n this,\n this.onFileProgress || null,\n safeOnComplete,\n this.onFileError || null,\n this.onFileReceived || null\n );\n \n this._fileTransferActive = true;\n \n this._secureLog('info', '\u2705 Enhanced Secure File Transfer system initialized successfully');\n \n // Verify the system is ready\n const status = this.fileTransferSystem.getSystemStatus();\n this._secureLog('info', '\uD83D\uDD0D File transfer system status after init', { status });\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to initialize file transfer system', { errorType: error.constructor.name });\n this.fileTransferSystem = null;\n this._fileTransferActive = false;\n }\n }\n\n // ============================================\n // ENHANCED SECURITY INITIALIZATION\n // ============================================\n\n async initializeEnhancedSecurity() {\n try {\n // Generate nested encryption key\n await this.generateNestedEncryptionKey();\n \n // Initialize decoy channels\n if (this.decoyChannelConfig.enabled) {\n this.initializeDecoyChannels();\n }\n \n // Start fake traffic generation\n if (this.fakeTrafficConfig.enabled) {\n this.startFakeTrafficGeneration();\n }\n\n } catch (error) {\n this._secureLog('error', '\u274C Failed to initialize enhanced security', { errorType: error.constructor.name });\n }\n }\n \n // Generate fingerprint mask for anti-fingerprinting with enhanced randomization\n generateFingerprintMask() {\n // Enhanced randomization to prevent side-channel attacks\n const cryptoRandom = crypto.getRandomValues(new Uint8Array(128));\n \n const mask = {\n timingOffset: cryptoRandom[0] % 1000 + cryptoRandom[1] % 500, // 0-1500ms\n sizeVariation: (cryptoRandom[2] % 50 + 75) / 100, // 0.75 to 1.25\n noisePattern: Array.from(crypto.getRandomValues(new Uint8Array(64))), // Increased size\n headerVariations: [\n 'X-Client-Version', 'X-Session-ID', 'X-Request-ID', 'X-Timestamp', 'X-Signature',\n 'X-Secure', 'X-Encrypted', 'X-Protected', 'X-Safe', 'X-Anonymous', 'X-Private'\n ],\n noiseIntensity: cryptoRandom[3] % 100 + 50, // 50-150%\n sizeMultiplier: (cryptoRandom[4] % 50 + 75) / 100, // 0.75-1.25\n timingVariation: cryptoRandom[5] % 1000 + 100 // 100-1100ms\n };\n return mask;\n }\n\n // Security configuration for session type\n configureSecurityForSession(sessionType, securityLevel) {\n this._secureLog('info', `\uD83D\uDD27 Configuring security for ${sessionType} session (${securityLevel} level)`);\n \n this.currentSessionType = sessionType;\n this.currentSecurityLevel = securityLevel;\n \n if (window.sessionManager && window.sessionManager.isFeatureAllowedForSession) {\n this.sessionConstraints = {};\n \n Object.keys(this.securityFeatures).forEach(feature => {\n this.sessionConstraints[feature] = window.sessionManager.isFeatureAllowedForSession(sessionType, feature);\n });\n \n this.applySessionConstraints();\n \n this._secureLog('info', `\u2705 Security configured for ${sessionType}`, { constraints: this.sessionConstraints });\n\n if (!this._validateCryptographicSecurity()) {\n this._secureLog('error', '\uD83D\uDEA8 CRITICAL: Cryptographic security validation failed after session configuration');\n\n if (this.onStatusChange) {\n this.onStatusChange('security_breach', {\n type: 'crypto_security_failure',\n sessionType: sessionType,\n message: 'Cryptographic security validation failed after session configuration'\n });\n }\n }\n \n this.notifySecurityLevel();\n \n setTimeout(() => {\n this.calculateAndReportSecurityLevel();\n }, EnhancedSecureWebRTCManager.TIMEOUTS.SECURITY_CALC_DELAY);\n \n } else {\n this._secureLog('warn', '\u26A0\uFE0F Session manager not available, using default security');\n }\n }\n\n // Applying session restrictions\n applySessionConstraints() {\n if (!this.sessionConstraints) return;\n\n // Applying restrictions to security features\n Object.keys(this.sessionConstraints).forEach(feature => {\n const allowed = this.sessionConstraints[feature];\n \n if (!allowed && this.securityFeatures[feature]) {\n this._secureLog('info', `\uD83D\uDD12 Disabling ${feature} for ${this.currentSessionType} session`);\n this.securityFeatures[feature] = false;\n \n // Disabling linked configurations\n switch (feature) {\n case 'hasFakeTraffic':\n this.fakeTrafficConfig.enabled = false;\n this.stopFakeTrafficGeneration();\n break;\n case 'hasDecoyChannels':\n this.decoyChannelConfig.enabled = false;\n this.cleanupDecoyChannels();\n break;\n case 'hasPacketReordering':\n this.reorderingConfig.enabled = false;\n this.packetBuffer.clear();\n break;\n case 'hasAntiFingerprinting':\n this.antiFingerprintingConfig.enabled = false;\n break;\n case 'hasMessageChunking':\n this.chunkingConfig.enabled = false;\n break;\n }\n } else if (allowed && !this.securityFeatures[feature]) {\n this._secureLog('info', `\uD83D\uDD13 Enabling ${feature} for ${this.currentSessionType} session`);\n this.securityFeatures[feature] = true;\n \n // Enable linked configurations\n switch (feature) {\n case 'hasFakeTraffic':\n this.fakeTrafficConfig.enabled = true;\n if (this.isConnected()) {\n this.startFakeTrafficGeneration();\n }\n break;\n case 'hasDecoyChannels':\n this.decoyChannelConfig.enabled = true;\n if (this.isConnected()) {\n this.initializeDecoyChannels();\n }\n break;\n case 'hasPacketReordering':\n this.reorderingConfig.enabled = true;\n break;\n case 'hasAntiFingerprinting':\n this.antiFingerprintingConfig.enabled = true;\n break;\n case 'hasMessageChunking':\n this.chunkingConfig.enabled = true;\n break;\n }\n }\n });\n }\n deliverMessageToUI(message, type = 'received') {\n try {\n // Add debug logs\n this._secureLog('debug', '\uD83D\uDCE4 deliverMessageToUI called', {\n message: message,\n type: type,\n messageType: typeof message,\n hasOnMessage: !!this.onMessage\n });\n \n // Filter out file-transfer and system messages\n if (typeof message === 'object' && message.type) {\n const blockedTypes = [\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_TRANSFER_START,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_TRANSFER_RESPONSE,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_CHUNK,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.CHUNK_CONFIRMATION,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_TRANSFER_COMPLETE,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_TRANSFER_ERROR,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.HEARTBEAT,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_RESPONSE,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_CONFIRMED,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_BOTH_CONFIRMED,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.PEER_DISCONNECT,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.KEY_ROTATION_SIGNAL,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.KEY_ROTATION_READY,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.SECURITY_UPGRADE\n ];\n if (blockedTypes.includes(message.type)) {\n if (this._debugMode) {\n this._secureLog('warn', `\uD83D\uDED1 Blocked system/file message from UI: ${message.type}`);\n }\n return; // do not show in chat\n }\n }\n\n // Additional check for string messages containing JSON\n if (typeof message === 'string' && message.trim().startsWith('{')) {\n try {\n const parsedMessage = JSON.parse(message);\n if (parsedMessage.type) {\n const blockedTypes = [\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_TRANSFER_START,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_TRANSFER_RESPONSE,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_CHUNK,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.CHUNK_CONFIRMATION,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_TRANSFER_COMPLETE,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.FILE_TRANSFER_ERROR,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.HEARTBEAT,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_RESPONSE,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_CONFIRMED,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.VERIFICATION_BOTH_CONFIRMED,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.PEER_DISCONNECT,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.KEY_ROTATION_SIGNAL,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.KEY_ROTATION_READY,\n EnhancedSecureWebRTCManager.MESSAGE_TYPES.SECURITY_UPGRADE\n ];\n if (blockedTypes.includes(parsedMessage.type)) {\n if (this._debugMode) {\n this._secureLog('warn', `\uD83D\uDED1 Blocked system/file message from UI (string): ${parsedMessage.type}`);\n }\n return; // do not show in chat\n }\n }\n } catch (parseError) {\n // Not JSON \u2014 fine for plain text messages\n }\n }\n\n if (this.onMessage) {\n this._secureLog('debug', '\uD83D\uDCE4 Calling this.onMessage callback', { message, type });\n this.onMessage(message, type);\n } else {\n this._secureLog('warn', '\u26A0\uFE0F this.onMessage callback is null or undefined');\n }\n } catch (err) {\n this._secureLog('error', '\u274C Failed to deliver message to UI:', { errorType: err?.constructor?.name || 'Unknown' });\n }\n }\n\n\n // Security Level Notification\n notifySecurityLevel() {\n // Avoid duplicate notifications for the same security level\n if (this.lastSecurityLevelNotification === this.currentSecurityLevel) {\n return; // prevent duplication\n }\n \n this.lastSecurityLevelNotification = this.currentSecurityLevel;\n \n const levelMessages = {\n 'basic': '\uD83D\uDD12 Basic Security Active - Demo session with essential protection',\n 'enhanced': '\uD83D\uDD10 Enhanced Security Active - Paid session with advanced protection',\n 'maximum': '\uD83D\uDEE1\uFE0F Maximum Security Active - Premium session with complete protection'\n };\n\n const message = levelMessages[this.currentSecurityLevel] || levelMessages['basic'];\n \n if (this.onMessage) {\n this.deliverMessageToUI(message, 'system');\n }\n\n // Showing details of functions for paid sessions\n if (this.currentSecurityLevel !== 'basic' && this.onMessage) {\n const activeFeatures = Object.entries(this.securityFeatures)\n .filter(([key, value]) => value === true)\n .map(([key]) => key.replace('has', '').replace(/([A-Z])/g, ' $1').trim().toLowerCase())\n .slice(0, 5); \n\n this.deliverMessageToUI(`\uD83D\uDD27 Active: ${activeFeatures.join(', ')}...`, 'system');\n }\n }\n\n // Cleaning decoy channels\n cleanupDecoyChannels() {\n // Stopping decoy traffic\n for (const [channelName, timer] of this.decoyTimers.entries()) {\n clearTimeout(timer);\n }\n this.decoyTimers.clear();\n \n // Closing decoy channels\n for (const [channelName, channel] of this.decoyChannels.entries()) {\n if (channel.readyState === 'open') {\n channel.close();\n }\n }\n this.decoyChannels.clear();\n \n this._secureLog('info', '\uD83E\uDDF9 Decoy channels cleaned up');\n }\n\n // ============================================\n // 1. NESTED ENCRYPTION LAYER\n // ============================================\n\n async generateNestedEncryptionKey() {\n try {\n // Generate additional encryption key for nested encryption\n this.nestedEncryptionKey = await crypto.subtle.generateKey(\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt', 'decrypt']\n );\n \n // Generate random IV for nested encryption\n // No need for base IV or counter - each encryption gets fresh random IV\n // This ensures maximum entropy and prevents IV reuse attacks\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to generate nested encryption key:', { errorType: error?.constructor?.name || 'Unknown' });\n throw error;\n }\n }\n\n async applyNestedEncryption(data) {\n if (!this.nestedEncryptionKey || !this.securityFeatures.hasNestedEncryption) {\n return data;\n }\n\n try {\n // Generate cryptographically secure IV with reuse prevention\n const uniqueIV = this._generateSecureIV(\n EnhancedSecureWebRTCManager.SIZES.NESTED_ENCRYPTION_IV_SIZE, \n 'nestedEncryption'\n );\n \n // Encrypt data with nested layer\n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: uniqueIV },\n this.nestedEncryptionKey,\n data\n );\n \n // Combine IV and encrypted data\n const result = new Uint8Array(EnhancedSecureWebRTCManager.SIZES.NESTED_ENCRYPTION_IV_SIZE + encrypted.byteLength);\n result.set(uniqueIV, 0);\n result.set(new Uint8Array(encrypted), EnhancedSecureWebRTCManager.SIZES.NESTED_ENCRYPTION_IV_SIZE);\n \n this._secureLog('debug', '\u2705 Nested encryption applied with secure IV', {\n ivSize: uniqueIV.length,\n dataSize: data.byteLength,\n encryptedSize: encrypted.byteLength\n });\n \n return result.buffer;\n } catch (error) {\n this._secureLog('error', '\u274C Nested encryption failed:', { \n errorType: error?.constructor?.name || 'Unknown',\n errorMessage: error?.message || 'Unknown error'\n });\n \n // If IV generation failed due to emergency mode, disable nested encryption\n if (error.message.includes('emergency mode')) {\n this.securityFeatures.hasNestedEncryption = false;\n this._secureLog('warn', '\u26A0\uFE0F Nested encryption disabled due to IV emergency mode');\n }\n \n return data; // Fallback to original data\n }\n }\n\n async removeNestedEncryption(data) {\n if (!this.nestedEncryptionKey || !this.securityFeatures.hasNestedEncryption) {\n return data;\n }\n\n // Check that the data is actually encrypted with proper IV size\n if (!(data instanceof ArrayBuffer) || data.byteLength < EnhancedSecureWebRTCManager.SIZES.NESTED_ENCRYPTION_IV_SIZE + 16) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCDD Data not encrypted or too short for nested decryption (need IV + minimum encrypted data)');\n }\n return data;\n }\n\n try {\n const dataArray = new Uint8Array(data);\n const iv = dataArray.slice(0, EnhancedSecureWebRTCManager.SIZES.NESTED_ENCRYPTION_IV_SIZE);\n const encryptedData = dataArray.slice(EnhancedSecureWebRTCManager.SIZES.NESTED_ENCRYPTION_IV_SIZE);\n \n // Check that there is data to decrypt\n if (encryptedData.length === 0) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCDD No encrypted data found');\n }\n return data;\n }\n \n // Decrypt nested layer\n const decrypted = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: iv },\n this.nestedEncryptionKey,\n encryptedData\n );\n \n return decrypted;\n } catch (error) {\n // FIX: Better error handling\n if (error.name === 'OperationError') {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCDD Data not encrypted with nested encryption, skipping...');\n }\n } else {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Nested decryption failed:', { details: error.message });\n }\n }\n return data; // Fallback to original data\n }\n }\n\n // ============================================\n // 2. PACKET PADDING\n // ============================================\n\n applyPacketPadding(data) {\n if (!this.securityFeatures.hasPacketPadding) {\n return data;\n }\n\n try {\n const originalSize = data.byteLength;\n let paddingSize;\n \n if (this.paddingConfig.useRandomPadding) {\n // Generate random padding size\n paddingSize = Math.floor(Math.random() * \n (this.paddingConfig.maxPadding - this.paddingConfig.minPadding + 1)) + \n this.paddingConfig.minPadding;\n } else {\n // Use fixed padding size\n paddingSize = this.paddingConfig.minPadding;\n }\n \n // Generate random padding data\n const padding = crypto.getRandomValues(new Uint8Array(paddingSize));\n \n // Create padded message\n const paddedData = new Uint8Array(originalSize + paddingSize + 4);\n \n // Add original size (4 bytes)\n const sizeView = new DataView(paddedData.buffer, 0, 4);\n sizeView.setUint32(0, originalSize, false);\n \n // Add original data\n paddedData.set(new Uint8Array(data), 4);\n \n // Add padding\n paddedData.set(padding, 4 + originalSize);\n \n return paddedData.buffer;\n } catch (error) {\n this._secureLog('error', '\u274C Packet padding failed:', { errorType: error?.constructor?.name || 'Unknown' });\n return data; // Fallback to original data\n }\n }\n\n removePacketPadding(data) {\n if (!this.securityFeatures.hasPacketPadding) {\n return data;\n }\n\n try {\n const dataArray = new Uint8Array(data);\n \n // Check for minimum data length (4 bytes for size + minimum 1 byte of data)\n if (dataArray.length < 5) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Data too short for packet padding removal, skipping');\n }\n return data;\n }\n \n // Extract original size (first 4 bytes)\n const sizeView = new DataView(dataArray.buffer, 0, 4);\n const originalSize = sizeView.getUint32(0, false);\n \n // Checking the reasonableness of the size\n if (originalSize <= 0 || originalSize > dataArray.length - 4) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Invalid packet padding size, skipping removal');\n }\n return data;\n }\n \n // Extract original data\n const originalData = dataArray.slice(4, 4 + originalSize);\n \n return originalData.buffer;\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('error', '\u274C Packet padding removal failed:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n return data; // Fallback to original data\n }\n }\n\n // ============================================\n // 3. FAKE TRAFFIC GENERATION\n // ============================================\n\n startFakeTrafficGeneration() {\n if (!this.fakeTrafficConfig.enabled || !this.isConnected()) {\n return;\n }\n\n // Prevent multiple fake traffic generators\n if (this.fakeTrafficTimer) {\n this._secureLog('warn', '\u26A0\uFE0F Fake traffic generation already running');\n return;\n }\n\n const sendFakeMessage = async () => {\n if (!this.isConnected()) {\n this.stopFakeTrafficGeneration();\n return;\n }\n\n try {\n const fakeMessage = this.generateFakeMessage();\n await this.sendFakeMessage(fakeMessage);\n \n // FIX: Increase intervals to reduce load\n const nextInterval = this.fakeTrafficConfig.randomDecoyIntervals ? \n Math.random() * (this.fakeTrafficConfig.maxInterval - this.fakeTrafficConfig.minInterval) + \n this.fakeTrafficConfig.minInterval :\n this.fakeTrafficConfig.minInterval;\n \n // Minimum interval 15 seconds for stability\n const safeInterval = Math.max(nextInterval, EnhancedSecureWebRTCManager.TIMEOUTS.FAKE_TRAFFIC_MIN_INTERVAL);\n \n this.fakeTrafficTimer = setTimeout(sendFakeMessage, safeInterval);\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('error', '\u274C Fake traffic generation failed:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n this.stopFakeTrafficGeneration();\n }\n };\n\n // Start fake traffic generation with longer initial delay\n const initialDelay = Math.random() * this.fakeTrafficConfig.maxInterval + EnhancedSecureWebRTCManager.TIMEOUTS.DECOY_INITIAL_DELAY; // Add 5 seconds minimum\n this.fakeTrafficTimer = setTimeout(sendFakeMessage, initialDelay);\n }\n\n stopFakeTrafficGeneration() {\n if (this.fakeTrafficTimer) {\n clearTimeout(this.fakeTrafficTimer);\n this.fakeTrafficTimer = null;\n }\n }\n\n generateFakeMessage() {\n const pattern = this.fakeTrafficConfig.patterns[\n Math.floor(Math.random() * this.fakeTrafficConfig.patterns.length)\n ];\n \n const size = Math.floor(Math.random() * \n (this.fakeTrafficConfig.maxSize - this.fakeTrafficConfig.minSize + 1)) + \n this.fakeTrafficConfig.minSize;\n \n const fakeData = crypto.getRandomValues(new Uint8Array(size));\n \n return {\n type: EnhancedSecureWebRTCManager.MESSAGE_TYPES.FAKE, \n pattern: pattern,\n data: Array.from(fakeData).map(b => b.toString(16).padStart(2, '0')).join(''),\n timestamp: Date.now(),\n size: size,\n isFakeTraffic: true, \n source: 'fake_traffic_generator',\n fakeId: crypto.getRandomValues(new Uint32Array(1))[0].toString(36) \n };\n }\n\n // ============================================\n // EMERGENCY SHUT-OFF OF ADVANCED FUNCTIONS\n // ============================================\n\n emergencyDisableAdvancedFeatures() {\n this._secureLog('error', '\uD83D\uDEA8 Emergency disabling advanced security features due to errors');\n \n // Disable problematic functions\n this.securityFeatures.hasNestedEncryption = false;\n this.securityFeatures.hasPacketReordering = false;\n this.securityFeatures.hasAntiFingerprinting = false;\n \n // Disable configurations\n this.reorderingConfig.enabled = false;\n this.antiFingerprintingConfig.enabled = false;\n \n // Clear the buffers\n this.packetBuffer.clear();\n \n // Stopping fake traffic\n this.emergencyDisableFakeTraffic();\n \n this._secureLog('info', '\u2705 Advanced features disabled, keeping basic encryption');\n \n // Check that advanced-features-disabled notification wasn't already sent\n if (!this.advancedFeaturesDisabledNotificationSent) {\n this.advancedFeaturesDisabledNotificationSent = true;\n if (this.onMessage) {\n this.deliverMessageToUI('\uD83D\uDEA8 Advanced security features temporarily disabled due to compatibility issues', 'system');\n }\n }\n }\n\n async sendFakeMessage(fakeMessage) {\n if (!this._validateConnection(false)) {\n return;\n }\n\n try {\n this._secureLog('debug', '\uD83C\uDFAD Sending fake message', {\n hasPattern: !!fakeMessage.pattern,\n sizeRange: fakeMessage.size > 100 ? 'large' : 'small'\n });\n \n const fakeData = JSON.stringify({\n ...fakeMessage,\n type: EnhancedSecureWebRTCManager.MESSAGE_TYPES.FAKE, \n isFakeTraffic: true, \n timestamp: Date.now()\n });\n \n const fakeBuffer = new TextEncoder().encode(fakeData);\n const encryptedFake = await this.applySecurityLayers(fakeBuffer, true);\n this.dataChannel.send(encryptedFake);\n \n this._secureLog('debug', '\uD83C\uDFAD Fake message sent successfully', {\n pattern: fakeMessage.pattern\n });\n } catch (error) {\n this._secureLog('error', '\u274C Failed to send fake message', {\n error: error.message\n });\n }\n }\n\ncheckFakeTrafficStatus() {\n const status = {\n fakeTrafficEnabled: this.securityFeatures.hasFakeTraffic,\n fakeTrafficConfigEnabled: this.fakeTrafficConfig.enabled,\n timerActive: !!this.fakeTrafficTimer,\n patterns: this.fakeTrafficConfig.patterns,\n intervals: {\n min: this.fakeTrafficConfig.minInterval,\n max: this.fakeTrafficConfig.maxInterval\n }\n };\n \n if (this._debugMode) {\n this._secureLog('info', '\uD83C\uDFAD Fake Traffic Status', { status });\n }\n return status;\n }\nemergencyDisableFakeTraffic() {\n if (this._debugMode) {\n this._secureLog('error', '\uD83D\uDEA8 Emergency disabling fake traffic');\n }\n \n this.securityFeatures.hasFakeTraffic = false;\n this.fakeTrafficConfig.enabled = false;\n this.stopFakeTrafficGeneration();\n \n if (this._debugMode) {\n this._secureLog('info', '\u2705 Fake traffic disabled');\n }\n \n // Check that fake-traffic-disabled notification wasn't already sent\n if (!this.fakeTrafficDisabledNotificationSent) {\n this.fakeTrafficDisabledNotificationSent = true;\n if (this.onMessage) {\n this.deliverMessageToUI('\uD83D\uDEA8 Fake traffic emergency disabled', 'system');\n }\n }\n }\n async _applySecurityLayersWithoutMutex(data, isFakeMessage = false) {\n try {\n let processedData = data;\n \n if (isFakeMessage) {\n if (this.encryptionKey && typeof processedData === 'string') {\n processedData = await window.EnhancedSecureCryptoUtils.encryptData(processedData, this.encryptionKey);\n }\n return processedData;\n }\n \n // Nested Encryption (if enabled)\n if (this.securityFeatures.hasNestedEncryption && this.nestedEncryptionKey && processedData instanceof ArrayBuffer) {\n processedData = await this.applyNestedEncryption(processedData);\n }\n \n // Packet Reordering (if enabled)\n if (this.securityFeatures.hasPacketReordering && this.reorderingConfig?.enabled && processedData instanceof ArrayBuffer) {\n processedData = this.applyPacketReordering(processedData);\n }\n \n // Packet Padding (if enabled)\n if (this.securityFeatures.hasPacketPadding && processedData instanceof ArrayBuffer) {\n processedData = this.applyPacketPadding(processedData);\n }\n \n // Anti-Fingerprinting (if enabled)\n if (this.securityFeatures.hasAntiFingerprinting && processedData instanceof ArrayBuffer) {\n processedData = this.applyAntiFingerprinting(processedData);\n }\n \n // Final encryption (if keys are present)\n if (this.encryptionKey && typeof processedData === 'string') {\n processedData = await window.EnhancedSecureCryptoUtils.encryptData(processedData, this.encryptionKey);\n }\n \n return processedData;\n \n } catch (error) {\n this._secureLog('error', '\u274C Error in applySecurityLayersWithoutMutex:', { errorType: error?.constructor?.name || 'Unknown' });\n return data; // Return original data on error\n }\n}\n // ============================================\n // 4. MESSAGE CHUNKING\n // ============================================\n\n async processChunkedMessage(chunkData) {\n try {\n if (!this.chunkingConfig.addChunkHeaders) {\n // No headers, treat as regular message\n return this.processMessage(chunkData);\n }\n\n const chunkArray = new Uint8Array(chunkData);\n if (chunkArray.length < 16) {\n // Too small to be a chunk with header\n return this.processMessage(chunkData);\n }\n\n // Extract chunk header\n const headerView = new DataView(chunkArray.buffer, 0, 16);\n const messageId = headerView.getUint32(0, false);\n const chunkIndex = headerView.getUint32(4, false);\n const totalChunks = headerView.getUint32(8, false);\n const chunkSize = headerView.getUint32(12, false);\n\n // Extract chunk data\n const chunk = chunkArray.slice(16, 16 + chunkSize);\n\n // Store chunk in buffer\n if (!this.chunkQueue[messageId]) {\n this.chunkQueue[messageId] = {\n chunks: new Array(totalChunks),\n received: 0,\n timestamp: Date.now()\n };\n }\n\n const messageBuffer = this.chunkQueue[messageId];\n messageBuffer.chunks[chunkIndex] = chunk;\n messageBuffer.received++;\n\n this._secureLog('debug', `\uD83D\uDCE6 Received chunk ${chunkIndex + 1}/${totalChunks} for message ${messageId}`);\n\n // Check if all chunks received\n if (messageBuffer.received === totalChunks) {\n // Combine all chunks\n const totalSize = messageBuffer.chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const combinedData = new Uint8Array(totalSize);\n \n let offset = 0;\n for (const chunk of messageBuffer.chunks) {\n combinedData.set(chunk, offset);\n offset += chunk.length;\n }\n\n // Process complete message\n await this.processMessage(combinedData.buffer);\n \n // Clean up\n delete this.chunkQueue[messageId];\n \n this._secureLog('info', `\uD83D\uDCE6 Chunked message ${messageId} reassembled and processed`);\n }\n } catch (error) {\n this._secureLog('error', '\u274C Chunked message processing failed:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }\n\n // ============================================\n // 5. DECOY CHANNELS\n // ============================================\n\n initializeDecoyChannels() {\n if (!this.decoyChannelConfig.enabled || !this.peerConnection) {\n return;\n }\n\n // Prevent multiple initializations\n if (this.decoyChannels.size > 0) {\n this._secureLog('warn', '\u26A0\uFE0F Decoy channels already initialized, skipping...');\n return;\n }\n\n try {\n const numDecoyChannels = Math.min(\n this.decoyChannelConfig.maxDecoyChannels,\n this.decoyChannelConfig.decoyChannelNames.length\n );\n\n for (let i = 0; i < numDecoyChannels; i++) {\n const channelName = this.decoyChannelConfig.decoyChannelNames[i];\n const decoyChannel = this.peerConnection.createDataChannel(channelName, {\n ordered: Math.random() > 0.5,\n maxRetransmits: Math.floor(Math.random() * 3)\n });\n\n this.setupDecoyChannel(decoyChannel, channelName);\n this.decoyChannels.set(channelName, decoyChannel);\n }\n\n if (this._debugMode) {\n this._secureLog('info', `\uD83C\uDFAD Initialized ${numDecoyChannels} decoy channels`);\n }\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('error', '\u274C Failed to initialize decoy channels:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }\n }\n\n setupDecoyChannel(channel, channelName) {\n channel.onopen = () => {\n if (this._debugMode) {\n this._secureLog('debug', `\uD83C\uDFAD Decoy channel \"${channelName}\" opened`);\n }\n this.startDecoyTraffic(channel, channelName);\n };\n\n channel.onmessage = (event) => {\n if (this._debugMode) {\n this._secureLog('debug', `\uD83C\uDFAD Received decoy message on \"${channelName}\": ${event.data?.length || 'undefined'} bytes`);\n }\n };\n\n channel.onclose = () => {\n if (this._debugMode) {\n this._secureLog('debug', `\uD83C\uDFAD Decoy channel \"${channelName}\" closed`);\n }\n this.stopDecoyTraffic(channelName);\n };\n\n channel.onerror = (error) => {\n if (this._debugMode) {\n this._secureLog('error', `\u274C Decoy channel \"${channelName}\" error`, { error: error.message });\n }\n };\n }\n\n startDecoyTraffic(channel, channelName) {\n const sendDecoyData = async () => {\n if (channel.readyState !== 'open') {\n return;\n }\n\n try {\n const decoyData = this.generateDecoyData(channelName);\n channel.send(decoyData);\n \n const interval = this.decoyChannelConfig.randomDecoyIntervals ?\n Math.random() * 15000 + 10000 : \n 20000; \n \n this.decoyTimers.set(channelName, setTimeout(() => sendDecoyData(), interval));\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('error', `\u274C Failed to send decoy data on \"${channelName}\"`, { error: error.message });\n }\n }\n };\n\n const initialDelay = Math.random() * 10000 + 5000; \n this.decoyTimers.set(channelName, setTimeout(() => sendDecoyData(), initialDelay));\n }\n\n stopDecoyTraffic(channelName) {\n const timer = this.decoyTimers.get(channelName);\n if (timer) {\n clearTimeout(timer);\n this.decoyTimers.delete(channelName);\n }\n }\n\n generateDecoyData(channelName) {\n const decoyTypes = {\n 'sync': () => JSON.stringify({\n type: 'sync',\n timestamp: Date.now(),\n sequence: Math.floor(Math.random() * 1000),\n data: Array.from(crypto.getRandomValues(new Uint8Array(32)))\n .map(b => b.toString(16).padStart(2, '0')).join('')\n }),\n 'status': () => JSON.stringify({\n type: 'status',\n status: ['online', 'away', 'busy'][Math.floor(Math.random() * 3)],\n uptime: Math.floor(Math.random() * 3600),\n data: Array.from(crypto.getRandomValues(new Uint8Array(16)))\n .map(b => b.toString(16).padStart(2, '0')).join('')\n }),\n 'heartbeat': () => JSON.stringify({\n type: 'heartbeat',\n timestamp: Date.now(),\n data: Array.from(crypto.getRandomValues(new Uint8Array(24)))\n .map(b => b.toString(16).padStart(2, '0')).join('')\n }),\n 'metrics': () => JSON.stringify({\n type: 'metrics',\n cpu: Math.random() * 100,\n memory: Math.random() * 100,\n network: Math.random() * 1000,\n data: Array.from(crypto.getRandomValues(new Uint8Array(20)))\n .map(b => b.toString(16).padStart(2, '0')).join('')\n }),\n 'debug': () => JSON.stringify({\n type: 'debug',\n level: ['info', 'warn', 'error'][Math.floor(Math.random() * 3)],\n message: 'Debug message',\n data: Array.from(crypto.getRandomValues(new Uint8Array(28)))\n .map(b => b.toString(16).padStart(2, '0')).join('')\n })\n };\n\n return decoyTypes[channelName] ? decoyTypes[channelName]() : \n Array.from(crypto.getRandomValues(new Uint8Array(64)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n }\n\n // ============================================\n // 6. PACKET REORDERING PROTECTION\n // ============================================\n\n addReorderingHeaders(data) {\n if (!this.reorderingConfig.enabled) {\n return data;\n }\n\n try {\n const dataArray = new Uint8Array(data);\n const headerSize = this.reorderingConfig.useTimestamps ? 12 : 8;\n const header = new ArrayBuffer(headerSize);\n const headerView = new DataView(header);\n\n // Add sequence number\n if (this.reorderingConfig.useSequenceNumbers) {\n headerView.setUint32(0, this.sequenceNumber++, false);\n }\n\n // Add timestamp\n if (this.reorderingConfig.useTimestamps) {\n headerView.setUint32(4, Date.now(), false);\n }\n\n // Add data size\n headerView.setUint32(this.reorderingConfig.useTimestamps ? 8 : 4, dataArray.length, false);\n\n // Combine header and data\n const result = new Uint8Array(headerSize + dataArray.length);\n result.set(new Uint8Array(header), 0);\n result.set(dataArray, headerSize);\n\n return result.buffer;\n } catch (error) {\n this._secureLog('error', '\u274C Failed to add reordering headers:', { errorType: error?.constructor?.name || 'Unknown' });\n return data;\n }\n }\n\n async processReorderedPacket(data) {\n if (!this.reorderingConfig.enabled) {\n return this.processMessage(data);\n }\n\n try {\n const dataArray = new Uint8Array(data);\n const headerSize = this.reorderingConfig.useTimestamps ? 12 : 8;\n\n if (dataArray.length < headerSize) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Data too short for reordering headers, processing directly');\n }\n return this.processMessage(data);\n }\n\n const headerView = new DataView(dataArray.buffer, 0, headerSize);\n let sequence = 0;\n let timestamp = 0;\n let dataSize = 0;\n\n if (this.reorderingConfig.useSequenceNumbers) {\n sequence = headerView.getUint32(0, false);\n }\n\n if (this.reorderingConfig.useTimestamps) {\n timestamp = headerView.getUint32(4, false);\n }\n\n dataSize = headerView.getUint32(this.reorderingConfig.useTimestamps ? 8 : 4, false);\n\n if (dataSize > dataArray.length - headerSize || dataSize <= 0) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Invalid reordered packet data size, processing directly');\n }\n return this.processMessage(data);\n }\n\n const actualData = dataArray.slice(headerSize, headerSize + dataSize);\n\n try {\n const textData = new TextDecoder().decode(actualData);\n const content = JSON.parse(textData);\n if (content.type === 'fake' || content.isFakeTraffic === true) {\n if (this._debugMode) {\n this._secureLog('warn', `\uD83C\uDFAD BLOCKED: Reordered fake message: ${content.pattern || 'unknown'}`);\n }\n return; \n }\n } catch (e) {\n\n }\n\n this.packetBuffer.set(sequence, {\n data: actualData.buffer,\n timestamp: timestamp || Date.now()\n });\n\n await this.processOrderedPackets();\n\n } catch (error) {\n this._secureLog('error', '\u274C Failed to process reordered packet:', { errorType: error?.constructor?.name || 'Unknown' });\n return this.processMessage(data);\n }\n}\n\n// ============================================\n// IMPROVED PROCESSORDEREDPACKETS with filtering\n// ============================================\n\nasync processOrderedPackets() {\n const now = Date.now();\n const timeout = this.reorderingConfig.reorderTimeout;\n\n while (true) {\n const nextSequence = this.lastProcessedSequence + 1;\n const packet = this.packetBuffer.get(nextSequence);\n\n if (!packet) {\n const oldestPacket = this.findOldestPacket();\n if (oldestPacket && (now - oldestPacket.timestamp) > timeout) {\n this._secureLog('warn', '\u26A0\uFE0F Packet ${oldestPacket.sequence} timed out, processing out of order');\n \n try {\n const textData = new TextDecoder().decode(oldestPacket.data);\n const content = JSON.parse(textData);\n if (content.type === 'fake' || content.isFakeTraffic === true) {\n this._secureLog('warn', `\uD83C\uDFAD BLOCKED: Timed out fake message: ${content.pattern || 'unknown'}`);\n this.packetBuffer.delete(oldestPacket.sequence);\n this.lastProcessedSequence = oldestPacket.sequence;\n continue; \n }\n } catch (e) {\n }\n \n await this.processMessage(oldestPacket.data);\n this.packetBuffer.delete(oldestPacket.sequence);\n this.lastProcessedSequence = oldestPacket.sequence;\n } else {\n break; \n }\n } else {\n try {\n const textData = new TextDecoder().decode(packet.data);\n const content = JSON.parse(textData);\n if (content.type === 'fake' || content.isFakeTraffic === true) {\n this._secureLog('warn', `\uD83C\uDFAD BLOCKED: Ordered fake message: ${content.pattern || 'unknown'}`);\n this.packetBuffer.delete(nextSequence);\n this.lastProcessedSequence = nextSequence;\n continue; \n }\n } catch (e) {\n }\n \n await this.processMessage(packet.data);\n this.packetBuffer.delete(nextSequence);\n this.lastProcessedSequence = nextSequence;\n }\n }\n\n this.cleanupOldPackets(now, timeout);\n}\n\n\n findOldestPacket() {\n let oldest = null;\n for (const [sequence, packet] of this.packetBuffer.entries()) {\n if (!oldest || packet.timestamp < oldest.timestamp) {\n oldest = { sequence, ...packet };\n }\n }\n return oldest;\n }\n\n cleanupOldPackets(now, timeout) {\n for (const [sequence, packet] of this.packetBuffer.entries()) {\n if ((now - packet.timestamp) > timeout) {\n this._secureLog('warn', '\u26A0\uFE0F \uD83D\uDDD1\uFE0F Removing timed out packet ${sequence}');\n this.packetBuffer.delete(sequence);\n }\n }\n }\n\n // ============================================\n // 7. ANTI-FINGERPRINTING\n // ============================================\n\n applyAntiFingerprinting(data) {\n if (!this.antiFingerprintingConfig.enabled) {\n return data;\n }\n\n try {\n let processedData = data;\n\n // Add random noise\n if (this.antiFingerprintingConfig.addNoise) {\n processedData = this.addNoise(processedData);\n }\n\n // Randomize sizes\n if (this.antiFingerprintingConfig.randomizeSizes) {\n processedData = this.randomizeSize(processedData);\n }\n\n // Mask patterns\n if (this.antiFingerprintingConfig.maskPatterns) {\n processedData = this.maskPatterns(processedData);\n }\n\n // Add random headers\n if (this.antiFingerprintingConfig.useRandomHeaders) {\n processedData = this.addRandomHeaders(processedData);\n }\n\n return processedData;\n } catch (error) {\n this._secureLog('error', '\u274C Anti-fingerprinting failed:', { errorType: error?.constructor?.name || 'Unknown' });\n return data;\n }\n }\n\n addNoise(data) {\n const dataArray = new Uint8Array(data);\n const noiseSize = Math.floor(Math.random() * 32) + 8; // 8-40 bytes\n const noise = crypto.getRandomValues(new Uint8Array(noiseSize));\n \n const result = new Uint8Array(dataArray.length + noiseSize);\n result.set(dataArray, 0);\n result.set(noise, dataArray.length);\n \n return result.buffer;\n }\n\n randomizeSize(data) {\n const dataArray = new Uint8Array(data);\n const variation = this.fingerprintMask.sizeVariation;\n const targetSize = Math.floor(dataArray.length * variation);\n \n if (targetSize > dataArray.length) {\n // Add padding to increase size\n const padding = crypto.getRandomValues(new Uint8Array(targetSize - dataArray.length));\n const result = new Uint8Array(targetSize);\n result.set(dataArray, 0);\n result.set(padding, dataArray.length);\n return result.buffer;\n } else if (targetSize < dataArray.length) {\n // Truncate to decrease size\n return dataArray.slice(0, targetSize).buffer;\n }\n \n return data;\n }\n\n maskPatterns(data) {\n const dataArray = new Uint8Array(data);\n const result = new Uint8Array(dataArray.length);\n \n // Apply XOR with noise pattern\n for (let i = 0; i < dataArray.length; i++) {\n const noiseByte = this.fingerprintMask.noisePattern[i % this.fingerprintMask.noisePattern.length];\n result[i] = dataArray[i] ^ noiseByte;\n }\n \n return result.buffer;\n }\n\n addRandomHeaders(data) {\n const dataArray = new Uint8Array(data);\n const headerCount = Math.floor(Math.random() * 3) + 1; // 1-3 headers\n let totalHeaderSize = 0;\n \n // Calculate total header size\n for (let i = 0; i < headerCount; i++) {\n totalHeaderSize += 4 + Math.floor(Math.random() * 16) + 4; // size + data + checksum\n }\n \n const result = new Uint8Array(totalHeaderSize + dataArray.length);\n let offset = 0;\n \n // Add random headers\n for (let i = 0; i < headerCount; i++) {\n const headerName = this.fingerprintMask.headerVariations[\n Math.floor(Math.random() * this.fingerprintMask.headerVariations.length)\n ];\n const headerData = crypto.getRandomValues(new Uint8Array(Math.floor(Math.random() * 16) + 4));\n \n // Header structure: [size:4][name:4][data:variable][checksum:4]\n const headerView = new DataView(result.buffer, offset);\n headerView.setUint32(0, headerData.length + 8, false); // Total header size\n headerView.setUint32(4, this.hashString(headerName), false); // Name hash\n \n result.set(headerData, offset + 8);\n \n // Add checksum\n const checksum = this.calculateChecksum(result.slice(offset, offset + 8 + headerData.length));\n const checksumView = new DataView(result.buffer, offset + 8 + headerData.length);\n checksumView.setUint32(0, checksum, false);\n \n offset += 8 + headerData.length + 4;\n }\n \n // Add original data\n result.set(dataArray, offset);\n \n return result.buffer;\n }\n\n hashString(str) {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash;\n }\n return Math.abs(hash);\n }\n\n calculateChecksum(data) {\n let checksum = 0;\n for (let i = 0; i < data.length; i++) {\n checksum = (checksum + data[i]) & 0xFFFFFFFF;\n }\n return checksum;\n }\n\n // ============================================\n // ENHANCED MESSAGE SENDING AND RECEIVING\n // ============================================\n\n async removeSecurityLayers(data) {\n try {\n const status = this.getSecurityStatus();\n if (this._debugMode) {\n this._secureLog('debug', `\uD83D\uDD0D removeSecurityLayers (Stage ${status.stage})`, {\n dataType: typeof data,\n dataLength: data?.length || data?.byteLength || 0,\n activeFeatures: status.activeFeaturesCount\n });\n }\n\n if (!data) {\n this._secureLog('warn', '\u26A0\uFE0F Received empty data');\n return null;\n }\n\n let processedData = data;\n\n // IMPORTANT: Early check for fake messages\n if (typeof data === 'string') {\n try {\n const jsonData = JSON.parse(data);\n \n // PRIORITY ONE: Filtering out fake messages\n if (jsonData.type === 'fake') {\n if (this._debugMode) {\n this._secureLog('debug', `\uD83C\uDFAD Fake message filtered out: ${jsonData.pattern} (size: ${jsonData.size})`);\n }\n return 'FAKE_MESSAGE_FILTERED'; \n }\n \n // System messages \u2014 do NOT return for re-processing\n if (jsonData.type && ['heartbeat', 'verification', 'verification_response', 'peer_disconnect', 'key_rotation_signal', 'key_rotation_ready', 'security_upgrade'].includes(jsonData.type)) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDD27 System message detected, blocking from chat', { type: jsonData.type });\n }\n return 'SYSTEM_MESSAGE_FILTERED';\n }\n \n // File transfer messages \u2014 do NOT return for display\n if (jsonData.type && ['file_transfer_start', 'file_transfer_response', 'file_chunk', 'chunk_confirmation', 'file_transfer_complete', 'file_transfer_error'].includes(jsonData.type)) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCC1 File transfer message detected, blocking from chat', { type: jsonData.type });\n }\n return 'FILE_MESSAGE_FILTERED';\n }\n \n // Regular text messages - extract the actual message text\n if (jsonData.type === 'message') {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCDD Regular message detected, extracting text', { data: jsonData.data });\n }\n return jsonData.data; // Return the actual message text, not the JSON\n }\n \n // Enhanced messages\n if (jsonData.type === 'enhanced_message' && jsonData.data) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDD10 Enhanced message detected, decrypting...');\n }\n \n if (!this.encryptionKey || !this.macKey || !this.metadataKey) {\n this._secureLog('error', '\u274C Missing encryption keys');\n return null;\n }\n \n const decryptedResult = await window.EnhancedSecureCryptoUtils.decryptMessage(\n jsonData.data,\n this.encryptionKey,\n this.macKey,\n this.metadataKey\n );\n \n if (this._debugMode) {\n this._secureLog('debug', '\u2705 Enhanced message decrypted, extracting...');\n this._secureLog('debug', '\uD83D\uDD0D decryptedResult', {\n type: typeof decryptedResult,\n hasMessage: !!decryptedResult?.message,\n messageType: typeof decryptedResult?.message,\n messageLength: decryptedResult?.message?.length || 0,\n messageSample: decryptedResult?.message?.substring(0, 50) || 'no message'\n });\n }\n \n // CHECKING FOR FAKE MESSAGES AFTER DECRYPTION\n try {\n const decryptedContent = JSON.parse(decryptedResult.message);\n if (decryptedContent.type === 'fake' || decryptedContent.isFakeTraffic === true) {\n if (this._debugMode) {\n this._secureLog('warn', `\uD83C\uDFAD BLOCKED: Encrypted fake message: ${decryptedContent.pattern || 'unknown'}`);\n }\n return 'FAKE_MESSAGE_FILTERED';\n }\n } catch (e) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCDD Decrypted content is not JSON, treating as plain text message');\n }\n }\n \n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCE4 Returning decrypted message', { message: decryptedResult.message?.substring(0, 50) });\n }\n return decryptedResult.message;\n }\n \n // Regular messages\n if (jsonData.type === 'message' && jsonData.data) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCDD Regular message detected, extracting data');\n }\n return jsonData.data; // Return the actual message text\n }\n \n // If it's a regular message with type 'message', let it continue processing\n if (jsonData.type === 'message') {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCDD Regular message detected, returning for display');\n }\n return data; // Return the original JSON string for processing\n }\n \n // If it's not a special type, return the original data for display\n if (!jsonData.type || (jsonData.type !== 'fake' && !['heartbeat', 'verification', 'verification_response', 'peer_disconnect', 'key_rotation_signal', 'key_rotation_ready', 'enhanced_message', 'security_upgrade', 'file_transfer_start', 'file_transfer_response', 'file_chunk', 'chunk_confirmation', 'file_transfer_complete', 'file_transfer_error'].includes(jsonData.type))) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCDD Regular message detected, returning for display');\n }\n return data;\n }\n } catch (e) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDCC4 Not JSON, processing as raw data');\n }\n // If it's not JSON, it might be a plain text message - return as-is\n return data;\n }\n }\n\n // Standard Decryption\n if (this.encryptionKey && typeof processedData === 'string' && processedData.length > 50) {\n try {\n const base64Regex = /^[A-Za-z0-9+/=]+$/;\n if (base64Regex.test(processedData.trim())) {\n if (this._debugMode) {\n this._secureLog('debug', '\uD83D\uDD13 Applying standard decryption...');\n }\n processedData = await window.EnhancedSecureCryptoUtils.decryptData(processedData, this.encryptionKey);\n if (this._debugMode) {\n this._secureLog('debug', '\u2705 Standard decryption successful');\n }\n \n // CHECKING FOR FAKE MESSAGES AFTER LEGACY DECRYPTION\n if (typeof processedData === 'string') {\n try {\n const legacyContent = JSON.parse(processedData);\n if (legacyContent.type === 'fake' || legacyContent.isFakeTraffic === true) {\n if (this._debugMode) {\n this._secureLog('warn', `\uD83C\uDFAD BLOCKED: Legacy fake message: ${legacyContent.pattern || 'unknown'}`);\n }\n return 'FAKE_MESSAGE_FILTERED';\n }\n } catch (e) {\n \n }\n processedData = new TextEncoder().encode(processedData).buffer;\n }\n }\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Standard decryption failed:', { details: error.message });\n }\n return data; \n }\n }\n\n if (this.securityFeatures.hasNestedEncryption && \n this.nestedEncryptionKey && \n processedData instanceof ArrayBuffer &&\n processedData.byteLength > 12) { \n \n try {\n processedData = await this.removeNestedEncryption(processedData);\n \n if (processedData instanceof ArrayBuffer) {\n try {\n const textData = new TextDecoder().decode(processedData);\n const nestedContent = JSON.parse(textData);\n if (nestedContent.type === 'fake' || nestedContent.isFakeTraffic === true) {\n if (this._debugMode) {\n this._secureLog('warn', `\uD83C\uDFAD BLOCKED: Nested fake message: ${nestedContent.pattern || 'unknown'}`);\n }\n return 'FAKE_MESSAGE_FILTERED';\n }\n } catch (e) {\n \n }\n }\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Nested decryption failed - skipping this layer:', { details: error.message });\n }\n }\n }\n\n if (this.securityFeatures.hasPacketReordering && \n this.reorderingConfig.enabled && \n processedData instanceof ArrayBuffer) {\n try {\n const headerSize = this.reorderingConfig.useTimestamps ? 12 : 8;\n if (processedData.byteLength > headerSize) {\n return await this.processReorderedPacket(processedData);\n }\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Reordering processing failed - using direct processing:', { details: error.message });\n }\n }\n }\n\n // Packet Padding Removal\n if (this.securityFeatures.hasPacketPadding && processedData instanceof ArrayBuffer) {\n try {\n processedData = this.removePacketPadding(processedData);\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Padding removal failed:', { details: error.message });\n }\n }\n }\n\n // Anti-Fingerprinting Removal\n if (this.securityFeatures.hasAntiFingerprinting && processedData instanceof ArrayBuffer) {\n try {\n processedData = this.removeAntiFingerprinting(processedData);\n } catch (error) {\n if (this._debugMode) {\n this._secureLog('warn', '\u26A0\uFE0F Anti-fingerprinting removal failed:', { details: error.message });\n }\n }\n }\n\n // Final transformation\n if (processedData instanceof ArrayBuffer) {\n processedData = new TextDecoder().decode(processedData);\n }\n\n if (typeof processedData === 'string') {\n try {\n const finalContent = JSON.parse(processedData);\n if (finalContent.type === 'fake' || finalContent.isFakeTraffic === true) {\n if (this._debugMode) {\n this._secureLog('warn', `\uD83C\uDFAD BLOCKED: Final check fake message: ${finalContent.pattern || 'unknown'}`);\n }\n return 'FAKE_MESSAGE_FILTERED';\n }\n } catch (e) {\n }\n }\n\n return processedData;\n\n } catch (error) {\n this._secureLog('error', '\u274C Critical error in removeSecurityLayers:', { errorType: error?.constructor?.name || 'Unknown' });\n return data;\n }\n}\n\n removeAntiFingerprinting(data) {\n // This is a simplified version - in practice, you'd need to reverse all operations\n // For now, we'll just return the data as-is since the operations are mostly additive\n return data;\n }\n\n async applySecurityLayers(data, isFakeMessage = false) {\n try {\n let processedData = data;\n \n if (isFakeMessage) {\n if (this.encryptionKey && typeof processedData === 'string') {\n processedData = await window.EnhancedSecureCryptoUtils.encryptData(processedData, this.encryptionKey);\n }\n return processedData;\n }\n \n if (this.securityFeatures.hasNestedEncryption && this.nestedEncryptionKey && processedData instanceof ArrayBuffer) {\n processedData = await this.applyNestedEncryption(processedData);\n }\n \n if (this.securityFeatures.hasPacketReordering && this.reorderingConfig?.enabled && processedData instanceof ArrayBuffer) {\n processedData = this.applyPacketReordering(processedData);\n }\n \n if (this.securityFeatures.hasPacketPadding && processedData instanceof ArrayBuffer) {\n processedData = this.applyPacketPadding(processedData);\n }\n \n if (this.securityFeatures.hasAntiFingerprinting && processedData instanceof ArrayBuffer) {\n processedData = this.applyAntiFingerprinting(processedData);\n }\n \n if (this.encryptionKey && typeof processedData === 'string') {\n processedData = await window.EnhancedSecureCryptoUtils.encryptData(processedData, this.encryptionKey);\n }\n \n return processedData;\n \n } catch (error) {\n this._secureLog('error', '\u274C Error in applySecurityLayers:', { errorType: error?.constructor?.name || 'Unknown' });\n return data;\n }\n }\n\n async sendMessage(data) {\n // Comprehensive input validation\n const validation = this._validateInputData(data, 'sendMessage');\n if (!validation.isValid) {\n const errorMessage = `Input validation failed: ${validation.errors.join(', ')}`;\n this._secureLog('error', '\u274C Input validation failed in sendMessage', {\n errors: validation.errors,\n dataType: typeof data,\n dataLength: data?.length || data?.byteLength || 0\n });\n throw new Error(errorMessage);\n }\n\n // Rate limiting check\n if (!this._checkRateLimit('sendMessage')) {\n throw new Error('Rate limit exceeded for message sending');\n }\n\n // Enforce verification gate\n this._enforceVerificationGate('sendMessage');\n\n // Connection validation\n if (!this.dataChannel || this.dataChannel.readyState !== 'open') {\n throw new Error('Data channel not ready');\n }\n\n try {\n this._secureLog('debug', 'sendMessage called', {\n hasDataChannel: !!this.dataChannel,\n dataChannelReady: this.dataChannel?.readyState === 'open',\n isInitiator: this.isInitiator,\n isVerified: this.isVerified,\n connectionReady: this.peerConnection?.connectionState === 'connected'\n });\n\n this._secureLog('debug', '\uD83D\uDD0D sendMessage DEBUG', {\n dataType: typeof validation.sanitizedData,\n isString: typeof validation.sanitizedData === 'string',\n isArrayBuffer: validation.sanitizedData instanceof ArrayBuffer,\n dataLength: validation.sanitizedData?.length || validation.sanitizedData?.byteLength || 0,\n });\n\n // CRITICAL SECURITY FIX: File messages MUST be encrypted\n // No more bypassing encryption for file_* messages\n if (typeof validation.sanitizedData === 'string') {\n try {\n const parsed = JSON.parse(validation.sanitizedData);\n \n if (parsed.type && parsed.type.startsWith('file_')) {\n this._secureLog('debug', '\uD83D\uDCC1 File message detected - applying full encryption with AAD', { type: parsed.type });\n \n // Create AAD for file message\n const aad = this._createFileMessageAAD(parsed.type, parsed.data);\n \n // Encrypt file message with AAD\n const encryptedData = await this._encryptFileMessage(validation.sanitizedData, aad);\n \n this.dataChannel.send(encryptedData);\n return true;\n }\n } catch (jsonError) {\n // Not JSON \u2014 continue normal handling\n }\n }\n\n // For regular text messages, send via secure path with AAD\n if (typeof validation.sanitizedData === 'string') {\n // Verify that _createMessageAAD method is available\n if (typeof this._createMessageAAD !== 'function') {\n throw new Error('_createMessageAAD method is not available. Manager may not be fully initialized.');\n }\n \n // Create AAD with sequence number for anti-replay protection\n const aad = this._createMessageAAD('message', { content: validation.sanitizedData });\n \n return await this.sendSecureMessage({ \n type: 'message', \n data: validation.sanitizedData, \n timestamp: Date.now(),\n aad: aad // Include AAD for sequence number validation\n });\n }\n\n // For binary data, apply security layers with a limited mutex\n this._secureLog('debug', '\uD83D\uDD10 Applying security layers to non-string data');\n const securedData = await this._applySecurityLayersWithLimitedMutex(validation.sanitizedData, false);\n this.dataChannel.send(securedData);\n \n return true;\n } catch (error) {\n this._secureLog('error', '\u274C Failed to send message', { \n error: error.message,\n errorType: error.constructor.name\n });\n throw error;\n }\n }\n\n // FIX: New method applying security layers with limited mutex use\n async _applySecurityLayersWithLimitedMutex(data, isFakeMessage = false) {\n // Use mutex ONLY for cryptographic operations\n return this._withMutex('cryptoOperation', async (operationId) => {\n try {\n let processedData = data;\n \n if (isFakeMessage) {\n if (this.encryptionKey && typeof processedData === 'string') {\n processedData = await window.EnhancedSecureCryptoUtils.encryptData(processedData, this.encryptionKey);\n }\n return processedData;\n }\n \n if (this.securityFeatures.hasNestedEncryption && this.nestedEncryptionKey && processedData instanceof ArrayBuffer) {\n processedData = await this.applyNestedEncryption(processedData);\n }\n \n if (this.securityFeatures.hasPacketReordering && this.reorderingConfig?.enabled && processedData instanceof ArrayBuffer) {\n processedData = this.applyPacketReordering(processedData);\n }\n \n if (this.securityFeatures.hasPacketPadding && processedData instanceof ArrayBuffer) {\n processedData = this.applyPacketPadding(processedData);\n }\n \n if (this.securityFeatures.hasAntiFingerprinting && processedData instanceof ArrayBuffer) {\n processedData = this.applyAntiFingerprinting(processedData);\n }\n \n if (this.encryptionKey && typeof processedData === 'string') {\n processedData = await window.EnhancedSecureCryptoUtils.encryptData(processedData, this.encryptionKey);\n }\n \n return processedData;\n \n } catch (error) {\n this._secureLog('error', '\u274C Error in applySecurityLayers:', { errorType: error?.constructor?.name || 'Unknown' });\n return data;\n }\n }, 3000); // Short timeout for crypto operations\n}\n\n async sendSystemMessage(messageData) {\n // Block system messages without verification\n // Exception: Allow verification-related system messages\n const isVerificationMessage = messageData.type === 'verification_request' || \n messageData.type === 'verification_response' ||\n messageData.type === 'verification_required';\n \n if (!isVerificationMessage) {\n this._enforceVerificationGate('sendSystemMessage', false);\n }\n \n if (!this.dataChannel || this.dataChannel.readyState !== 'open') {\n this._secureLog('warn', '\u26A0\uFE0F Cannot send system message - data channel not ready');\n return false;\n }\n\n try {\n const systemMessage = JSON.stringify({\n type: messageData.type,\n data: messageData,\n timestamp: Date.now()\n });\n\n this._secureLog('debug', '\uD83D\uDD27 Sending system message', { type: messageData.type });\n this.dataChannel.send(systemMessage);\n return true;\n } catch (error) {\n this._secureLog('error', '\u274C Failed to send system message:', { errorType: error?.constructor?.name || 'Unknown' });\n return false;\n }\n }\n\n // FIX 1: Simplified mutex system for message processing\nasync processMessage(data) {\n try {\n this._secureLog('debug', '\uFFFD\uFFFD Processing message', {\n dataType: typeof data,\n isArrayBuffer: data instanceof ArrayBuffer,\n hasData: !!(data?.length || data?.byteLength)\n });\n \n // CRITICAL: Early check for file messages WITHOUT mutex\n if (typeof data === 'string') {\n try {\n const parsed = JSON.parse(data);\n\n // ============================================\n // FILE MESSAGES \u2014 PRIORITY 1 (WITHOUT MUTEX)\n // ============================================\n \n const fileMessageTypes = [\n 'file_transfer_start',\n 'file_transfer_response',\n 'file_chunk', \n 'chunk_confirmation',\n 'file_transfer_complete',\n 'file_transfer_error'\n ];\n\n // CRITICAL SECURITY FIX: Check for encrypted file messages first\n if (parsed.type === 'encrypted_file_message') {\n this._secureLog('debug', '\uD83D\uDCC1 Encrypted file message detected in processMessage');\n \n try {\n // Decrypt and validate file message\n const { decryptedData, aad } = await this._decryptFileMessage(data);\n \n // Parse decrypted data\n const decryptedParsed = JSON.parse(decryptedData);\n \n this._secureLog('debug', '\uD83D\uDCC1 File message decrypted successfully', { \n type: decryptedParsed.type,\n aadMessageType: aad.messageType \n });\n \n // Process decrypted file message\n if (this.fileTransferSystem && typeof this.fileTransferSystem.handleFileMessage === 'function') {\n await this.fileTransferSystem.handleFileMessage(decryptedParsed);\n return;\n }\n } catch (error) {\n this._secureLog('error', '\u274C Failed to decrypt file message', { error: error.message });\n return; // Drop invalid file message\n }\n }\n \n // Legacy unencrypted file messages - should not happen in secure mode\n if (parsed.type && fileMessageTypes.includes(parsed.type)) {\n this._secureLog('warn', '\u26A0\uFE0F Unencrypted file message detected - this should not happen in secure mode', { type: parsed.type });\n \n // Drop unencrypted file messages for security\n this._secureLog('error', '\u274C Dropping unencrypted file message for security', { type: parsed.type });\n return;\n }\n \n // ============================================\n // ENHANCED MESSAGES WITH AAD VALIDATION (WITHOUT MUTEX)\n // ============================================\n \n if (parsed.type === 'enhanced_message') {\n this._secureLog('debug', '\uD83D\uDD10 Enhanced message detected in processMessage');\n \n try {\n // Decrypt enhanced message\n const decryptedData = await window.EnhancedSecureCryptoUtils.decryptMessage(\n parsed.data,\n this.encryptionKey,\n this.macKey,\n this.metadataKey\n );\n \n // Parse decrypted data\n const decryptedParsed = JSON.parse(decryptedData.data);\n \n // Validate AAD with sequence number\n if (decryptedData.metadata && decryptedData.metadata.sequenceNumber !== undefined) {\n if (!this._validateIncomingSequenceNumber(decryptedData.metadata.sequenceNumber, 'enhanced_message')) {\n this._secureLog('warn', '\u26A0\uFE0F Enhanced message sequence number validation failed - possible replay attack', {\n received: decryptedData.metadata.sequenceNumber,\n expected: this.expectedSequenceNumber\n });\n return; // Drop message with invalid sequence number\n }\n }\n \n // Process decrypted message\n if (decryptedParsed.type === 'message' && this.onMessage && decryptedParsed.data) {\n this.deliverMessageToUI(decryptedParsed.data, 'received');\n }\n \n return;\n } catch (error) {\n this._secureLog('error', '\u274C Failed to decrypt enhanced message', { error: error.message });\n return; // Drop invalid enhanced message\n }\n }\n \n // ============================================\n // REGULAR USER MESSAGES (WITHOUT MUTEX)\n // ============================================\n \n if (parsed.type === 'message') {\n this._secureLog('debug', '\uD83D\uDCDD Regular user message detected in processMessage');\n if (this.onMessage && parsed.data) {\n this.deliverMessageToUI(parsed.data, 'received');\n }\n return;\n }\n \n // ============================================\n // SYSTEM MESSAGES (WITHOUT MUTEX)\n // ============================================\n \n if (parsed.type && ['heartbeat', 'verification', 'verification_response', 'verification_confirmed', 'verification_both_confirmed', 'peer_disconnect', 'security_upgrade'].includes(parsed.type)) {\n this.handleSystemMessage(parsed);\n return;\n }\n \n // ============================================\n // FAKE MESSAGES (WITHOUT MUTEX)\n // ============================================\n \n if (parsed.type === 'fake') {\n this._secureLog('warn', '\uD83C\uDFAD Fake message blocked in processMessage', { pattern: parsed.pattern });\n return;\n }\n \n } catch (jsonError) {\n // Not JSON \u2014 treat as text WITHOUT mutex\n if (this.onMessage) {\n this.deliverMessageToUI(data, 'received');\n }\n return;\n }\n }\n\n // ============================================\n // ENCRYPTED DATA PROCESSING (WITH MUTEX ONLY FOR CRYPTO)\n // ============================================\n \n // If here \u2014 apply security layers with limited mutex\n const originalData = await this._processEncryptedDataWithLimitedMutex(data);\n\n // Check processing result\n if (originalData === 'FAKE_MESSAGE_FILTERED' || \n originalData === 'FILE_MESSAGE_FILTERED' || \n originalData === 'SYSTEM_MESSAGE_FILTERED') {\n return;\n }\n \n if (!originalData) {\n this._secureLog('warn', '\u26A0\uFE0F No data returned from removeSecurityLayers');\n return;\n }\n\n // Handle result after removeSecurityLayers\n let messageText;\n \n if (typeof originalData === 'string') {\n try {\n const message = JSON.parse(originalData);\n \n // SECOND CHECK FOR FILE MESSAGES AFTER DECRYPTION\n if (message.type && fileMessageTypes.includes(message.type)) {\n this._secureLog('debug', '\uD83D\uDCC1 File message detected after decryption', { type: message.type });\n if (this.fileTransferSystem) {\n await this.fileTransferSystem.handleFileMessage(message);\n }\n return;\n }\n \n if (message.type && ['heartbeat', 'verification', 'verification_response', 'verification_confirmed', 'verification_both_confirmed', 'peer_disconnect', 'security_upgrade'].includes(message.type)) {\n this.handleSystemMessage(message);\n return;\n }\n \n if (message.type === 'fake') {\n this._secureLog('warn', `\uD83C\uDFAD Post-decryption fake message blocked: ${message.pattern}`);\n return;\n }\n \n // Regular messages\n if (message.type === 'message' && message.data) {\n messageText = message.data;\n } else {\n messageText = originalData;\n }\n } catch (e) {\n messageText = originalData;\n }\n } else if (originalData instanceof ArrayBuffer) {\n messageText = new TextDecoder().decode(originalData);\n } else if (originalData && typeof originalData === 'object' && originalData.message) {\n messageText = originalData.message;\n } else {\n this._secureLog('warn', '\u26A0\uFE0F Unexpected data type after processing:', { details: typeof originalData });\n return;\n }\n\n // Final check for fake and file messages\n if (messageText && messageText.trim().startsWith('{')) {\n try {\n const finalCheck = JSON.parse(messageText);\n if (finalCheck.type === 'fake') {\n this._secureLog('warn', `\uD83C\uDFAD Final fake message check blocked: ${finalCheck.pattern}`);\n return;\n }\n \n // Additional check for file and system messages\n const blockedTypes = [\n 'file_transfer_start', 'file_transfer_response', 'file_chunk', \n 'chunk_confirmation', 'file_transfer_complete', 'file_transfer_error',\n 'heartbeat', 'verification', 'verification_response', \n 'peer_disconnect', 'key_rotation_signal', 'key_rotation_ready', 'security_upgrade'\n ];\n \n if (finalCheck.type && blockedTypes.includes(finalCheck.type)) {\n this._secureLog('warn', `\uD83D\uDCC1 Final system/file message check blocked: ${finalCheck.type}`);\n return;\n }\n } catch (e) {\n // Not JSON \u2014 fine for plain text\n }\n }\n\n // Deliver message to the UI\n if (this.onMessage && messageText) {\n this._secureLog('debug', '\uD83D\uDCE4 Calling message handler with', { message: messageText.substring(0, 100) });\n this.deliverMessageToUI(messageText, 'received');\n }\n\n } catch (error) {\n this._secureLog('error', '\u274C Failed to process message:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n}\n\n // FIX: New method with limited mutex when processing encrypted data\n async _processEncryptedDataWithLimitedMutex(data) {\n // Use mutex ONLY for cryptographic operations\n return this._withMutex('cryptoOperation', async (operationId) => {\n this._secureLog('debug', '\uD83D\uDD10 Processing encrypted data with limited mutex', {\n operationId: operationId,\n dataType: typeof data\n });\n \n try {\n // Apply security layers\n const originalData = await this.removeSecurityLayers(data);\n return originalData;\n \n } catch (error) {\n this._secureLog('error', '\u274C Error processing encrypted data', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n return data; // Return original data on error\n }\n }, 2000); // Short timeout for crypto operations\n }\n\n notifySecurityUpdate() {\n try {\n this._secureLog('debug', '\uD83D\uDD12 Notifying about security level update', {\n isConnected: this.isConnected(),\n isVerified: this.isVerified,\n hasKeys: !!(this.encryptionKey && this.macKey && this.metadataKey),\n hasLastCalculation: !!this.lastSecurityCalculation\n });\n \n // Send an event about security level update\n document.dispatchEvent(new CustomEvent('security-level-updated', {\n detail: { \n timestamp: Date.now(), \n manager: 'webrtc',\n webrtcManager: this,\n isConnected: this.isConnected(),\n isVerified: this.isVerified,\n hasKeys: !!(this.encryptionKey && this.macKey && this.metadataKey),\n lastCalculation: this.lastSecurityCalculation\n }\n }));\n \n // FIX: Force header refresh with correct manager\n setTimeout(() => {\n // Removed global callback - use event system instead\n // if (window.forceHeaderSecurityUpdate) {\n // window.forceHeaderSecurityUpdate(this);\n // }\n }, 100);\n \n // FIX: Direct update if there is a calculation\n if (this.lastSecurityCalculation) {\n document.dispatchEvent(new CustomEvent('real-security-calculated', {\n detail: {\n securityData: this.lastSecurityCalculation,\n webrtcManager: this,\n timestamp: Date.now()\n }\n }));\n }\n \n } catch (error) {\n this._secureLog('error', '\u274C Error in notifySecurityUpdate', {\n error: error.message\n });\n }\n }\n\n handleSystemMessage(message) {\n this._secureLog('debug', '\uD83D\uDD27 Handling system message:', { type: message.type });\n \n switch (message.type) {\n case 'heartbeat':\n this.handleHeartbeat();\n break;\n case 'verification':\n this.handleVerificationRequest(message.data);\n break;\n case 'verification_response':\n this.handleVerificationResponse(message.data);\n break;\n case 'sas_code':\n this.handleSASCode(message.data);\n break;\n case 'verification_confirmed':\n this.handleVerificationConfirmed(message.data);\n break;\n case 'verification_both_confirmed':\n this.handleVerificationBothConfirmed(message.data);\n break;\n case 'peer_disconnect':\n this.handlePeerDisconnectNotification(message);\n break;\n case 'key_rotation_signal':\n this._secureLog('debug', '\uD83D\uDD04 Key rotation signal received (ignored for stability)');\n break;\n case 'key_rotation_ready':\n this._secureLog('debug', '\uD83D\uDD04 Key rotation ready signal received (ignored for stability)');\n break;\n case 'security_upgrade':\n this._secureLog('debug', '\uD83D\uDD12 Security upgrade notification received:', { type: message.type });\n // Security upgrade messages are handled internally, not displayed to user\n // to prevent duplicate system messages\n break;\n default:\n this._secureLog('debug', '\uD83D\uDD27 Unknown system message type:', { type: message.type });\n }\n }\n\n // ============================================\n // FUNCTION MANAGEMENT METHODS\n // ============================================\n\n // Method to enable Stage 2 functions\n enableStage2Security() {\n if (this.sessionConstraints?.hasPacketReordering) {\n this.securityFeatures.hasPacketReordering = true;\n this.reorderingConfig.enabled = true;\n }\n \n if (this.sessionConstraints?.hasAntiFingerprinting) {\n this.securityFeatures.hasAntiFingerprinting = true;\n this.antiFingerprintingConfig.enabled = true;\n if (this.currentSecurityLevel === 'enhanced') {\n this.antiFingerprintingConfig.randomizeSizes = false;\n this.antiFingerprintingConfig.maskPatterns = false;\n this.antiFingerprintingConfig.useRandomHeaders = false;\n }\n }\n \n this.notifySecurityUpgrade(2);\n setTimeout(() => {\n this.calculateAndReportSecurityLevel();\n }, 500);\n }\n\n // Method to enable Stage 3 features (traffic obfuscation)\n enableStage3Security() {\n if (this.currentSecurityLevel !== 'maximum') {\n this._secureLog('info', '\uD83D\uDD12 Stage 3 features only available for premium sessions');\n return;\n }\n \n if (this.sessionConstraints?.hasMessageChunking) {\n this.securityFeatures.hasMessageChunking = true;\n this.chunkingConfig.enabled = true;\n }\n \n if (this.sessionConstraints?.hasFakeTraffic) {\n this.securityFeatures.hasFakeTraffic = true;\n this.fakeTrafficConfig.enabled = true;\n this.startFakeTrafficGeneration();\n }\n \n this.notifySecurityUpgrade(3);\n setTimeout(() => {\n this.calculateAndReportSecurityLevel();\n }, 500);\n }\n\n // Method for enabling Stage 4 functions (maximum safety)\n enableStage4Security() {\n if (this.currentSecurityLevel !== 'maximum') {\n this._secureLog('info', '\uD83D\uDD12 Stage 4 features only available for premium sessions');\n return;\n }\n \n if (this.sessionConstraints?.hasDecoyChannels && this.isConnected() && this.isVerified) {\n this.securityFeatures.hasDecoyChannels = true;\n this.decoyChannelConfig.enabled = true;\n \n try {\n this.initializeDecoyChannels();\n } catch (error) {\n this._secureLog('warn', '\u26A0\uFE0F Decoy channels initialization failed:', { details: error.message });\n this.securityFeatures.hasDecoyChannels = false;\n this.decoyChannelConfig.enabled = false;\n }\n }\n \n // Full anti-fingerprinting for maximum sessions\n if (this.sessionConstraints?.hasAntiFingerprinting) {\n this.antiFingerprintingConfig.randomizeSizes = true;\n this.antiFingerprintingConfig.maskPatterns = true;\n this.antiFingerprintingConfig.useRandomHeaders = false; \n }\n \n this.notifySecurityUpgrade(4);\n setTimeout(() => {\n this.calculateAndReportSecurityLevel();\n }, 500);\n }\n\n forceSecurityUpdate() {\n setTimeout(() => {\n this.calculateAndReportSecurityLevel();\n this.notifySecurityUpdate();\n }, 100);\n }\n\n // Method for getting security status\n getSecurityStatus() {\n const activeFeatures = Object.entries(this.securityFeatures)\n .filter(([key, value]) => value === true)\n .map(([key]) => key);\n \n const stage = this.currentSecurityLevel === 'basic' ? 1 : \n this.currentSecurityLevel === 'enhanced' ? 2 :\n this.currentSecurityLevel === 'maximum' ? 4 : 1;\n \n return {\n stage: stage,\n sessionType: this.currentSessionType,\n securityLevel: this.currentSecurityLevel,\n activeFeatures: activeFeatures,\n totalFeatures: Object.keys(this.securityFeatures).length,\n activeFeaturesCount: activeFeatures.length,\n activeFeaturesNames: activeFeatures,\n sessionConstraints: this.sessionConstraints\n };\n }\n\n // Method to notify UI about security update\n notifySecurityUpgrade(stage) {\n const stageNames = {\n 1: 'Basic Enhanced',\n 2: 'Medium Security', \n 3: 'High Security',\n 4: 'Maximum Security'\n };\n \n const message = `\uD83D\uDD12 Security upgraded to Stage ${stage}: ${stageNames[stage]}`;\n \n // Avoid duplicate security-upgrade notifications\n if (!this.securityUpgradeNotificationSent || this.lastSecurityUpgradeStage !== stage) {\n this.securityUpgradeNotificationSent = true;\n this.lastSecurityUpgradeStage = stage;\n \n // Notify local UI via onMessage\n if (this.onMessage) {\n this.deliverMessageToUI(message, 'system');\n }\n }\n\n // Send security upgrade notification to peer via WebRTC\n if (this.dataChannel && this.dataChannel.readyState === 'open') {\n try {\n const securityNotification = {\n type: 'security_upgrade',\n stage: stage,\n stageName: stageNames[stage],\n message: message,\n timestamp: Date.now()\n };\n \n this._secureLog('debug', '\uD83D\uDD12 Sending security upgrade notification to peer:', { type: securityNotification.type, stage: securityNotification.stage });\n this.dataChannel.send(JSON.stringify(securityNotification));\n } catch (error) {\n this._secureLog('warn', '\u26A0\uFE0F Failed to send security upgrade notification to peer:', { details: error.message });\n }\n }\n\n const status = this.getSecurityStatus();\n }\n\n async calculateAndReportSecurityLevel() {\n try {\n if (!window.EnhancedSecureCryptoUtils) {\n this._secureLog('warn', '\u26A0\uFE0F EnhancedSecureCryptoUtils not available for security calculation');\n return null;\n }\n\n if (!this.isConnected() || !this.isVerified || !this.encryptionKey || !this.macKey) {\n this._secureLog('debug', '\u26A0\uFE0F WebRTC not ready for security calculation', {\n connected: this.isConnected(),\n verified: this.isVerified,\n hasEncryptionKey: !!this.encryptionKey,\n hasMacKey: !!this.macKey\n });\n return null;\n }\n\n this._secureLog('debug', '\uD83D\uDD0D Calculating real security level', {\n managerState: 'ready',\n hasAllKeys: !!(this.encryptionKey && this.macKey && this.metadataKey)\n });\n \n const securityData = await window.EnhancedSecureCryptoUtils.calculateSecurityLevel(this);\n \n this._secureLog('info', '\uD83D\uDD10 Real security level calculated', {\n hasSecurityLevel: !!securityData.level,\n scoreRange: securityData.score > 80 ? 'high' : securityData.score > 50 ? 'medium' : 'low',\n checksRatio: `${securityData.passedChecks}/${securityData.totalChecks}`,\n isRealCalculation: securityData.isRealData\n });\n\n this.lastSecurityCalculation = securityData;\n\n document.dispatchEvent(new CustomEvent('real-security-calculated', {\n detail: {\n securityData: securityData,\n webrtcManager: this,\n timestamp: Date.now(),\n source: 'calculateAndReportSecurityLevel'\n }\n }));\n\n if (securityData.isRealData && this.onMessage) {\n if (!this.securityCalculationNotificationSent || this.lastSecurityCalculationLevel !== securityData.level) {\n this.securityCalculationNotificationSent = true;\n this.lastSecurityCalculationLevel = securityData.level;\n \n const message = `\uD83D\uDD12 Security Level: ${securityData.level} (${securityData.score}%) - ${securityData.passedChecks}/${securityData.totalChecks} checks passed`;\n this.deliverMessageToUI(message, 'system');\n }\n }\n \n return securityData;\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to calculate real security level', {\n errorType: error.constructor.name\n });\n return null;\n }\n }\n\n // ============================================\n // AUTOMATIC STEP-BY-STEP SWITCHING ON\n // ============================================\n\n // Method for automatic feature enablement with stability check\n async autoEnableSecurityFeatures() {\n if (this.currentSessionType === 'demo') {\n this._secureLog('info', '\uD83D\uDD12 Demo session - keeping basic security only');\n await this.calculateAndReportSecurityLevel();\n this.notifySecurityUpgrade(1);\n return;\n }\n\n const checkStability = () => {\n const isStable = this.isConnected() && \n this.isVerified && \n this.connectionAttempts === 0 && \n this.messageQueue.length === 0 &&\n this.peerConnection?.connectionState === 'connected';\n return isStable;\n };\n \n this._secureLog('info', `\uD83D\uDD12 ${this.currentSessionType} session - starting graduated security activation`);\n await this.calculateAndReportSecurityLevel();\n this.notifySecurityUpgrade(1);\n \n if (this.currentSecurityLevel === 'enhanced' || this.currentSecurityLevel === 'maximum') {\n setTimeout(async () => {\n if (checkStability()) {\n console.log('\u2705 Activating Stage 2 for paid session');\n this.enableStage2Security();\n await this.calculateAndReportSecurityLevel(); \n \n // For maximum sessions, turn on Stage 3 and 4\n if (this.currentSecurityLevel === 'maximum') {\n setTimeout(async () => {\n if (checkStability()) {\n console.log('\u2705 Activating Stage 3 for premium session');\n this.enableStage3Security();\n await this.calculateAndReportSecurityLevel();\n \n setTimeout(async () => {\n if (checkStability()) {\n console.log('\u2705 Activating Stage 4 for premium session');\n this.enableStage4Security();\n await this.calculateAndReportSecurityLevel();\n }\n }, 20000);\n }\n }, 15000);\n }\n }\n }, 10000);\n }\n }\n\n // ============================================\n // CONNECTION MANAGEMENT WITH ENHANCED SECURITY\n // ============================================\n\n async establishConnection() {\n try {\n // Initialize enhanced security features\n await this.initializeEnhancedSecurity();\n \n // Start fake traffic generation\n if (this.fakeTrafficConfig.enabled) {\n this.startFakeTrafficGeneration();\n }\n \n // Initialize decoy channels\n if (this.decoyChannelConfig.enabled) {\n this.initializeDecoyChannels();\n }\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to establish enhanced connection:', { errorType: error?.constructor?.name || 'Unknown' });\n // Do not close the connection on setup errors \u2014 just log and continue\n this.onStatusChange('disconnected');\n throw error;\n }\n }\n\n disconnect() {\n try {\n console.log('\uD83D\uDD0C Disconnecting WebRTC Manager...');\n \n // Cleanup file transfer system\n if (this.fileTransferSystem) {\n console.log('\uD83E\uDDF9 Cleaning up file transfer system during disconnect...');\n this.fileTransferSystem.cleanup();\n this.fileTransferSystem = null;\n }\n \n // Stop fake traffic generation\n this.stopFakeTrafficGeneration();\n \n // Stop decoy traffic\n for (const [channelName, timer] of this.decoyTimers.entries()) {\n clearTimeout(timer);\n }\n this.decoyTimers.clear();\n \n // Close decoy channels\n for (const [channelName, channel] of this.decoyChannels.entries()) {\n if (channel.readyState === 'open') {\n channel.close();\n }\n }\n this.decoyChannels.clear();\n \n // Clean up packet buffer\n this.packetBuffer.clear();\n \n // Clean up chunk queue\n this.chunkQueue = [];\n \n // Wipe ephemeral keys for PFS on disconnect\n this._wipeEphemeralKeys();\n \n // Hard wipe old keys for PFS\n this._hardWipeOldKeys();\n\n // Clear verification states\n this._clearVerificationStates();\n\n } catch (error) {\n this._secureLog('error', '\u274C Error during enhanced disconnect:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }\n\n /**\n * Clear all verification states and data\n * Called when verification is rejected or connection is terminated\n */\n _clearVerificationStates() {\n try {\n console.log('\uD83E\uDDF9 Clearing verification states...');\n \n // Clear verification states\n this.localVerificationConfirmed = false;\n this.remoteVerificationConfirmed = false;\n this.bothVerificationsConfirmed = false;\n this.isVerified = false;\n this.verificationCode = null;\n this.pendingSASCode = null;\n \n // Clear key fingerprint and connection data\n this.keyFingerprint = null;\n this.expectedDTLSFingerprint = null;\n this.connectionId = null;\n \n // Clear processed message IDs\n this.processedMessageIds.clear();\n \n // Reset notification flags\n this.verificationNotificationSent = false;\n this.verificationInitiationSent = false;\n \n console.log('\u2705 Verification states cleared successfully');\n \n } catch (error) {\n this._secureLog('error', '\u274C Error clearing verification states:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }\n\n // Start periodic cleanup for rate limiting and security\n startPeriodicCleanup() {\n // Cleanup moved to unified scheduler\n this._secureLog('info', '\uD83D\uDD27 Periodic cleanup moved to unified scheduler');\n }\n\n // Calculate current security level with real verification\n async calculateSecurityLevel() {\n return await window.EnhancedSecureCryptoUtils.calculateSecurityLevel(this);\n }\n\n // PFS: Check if key rotation is needed\n shouldRotateKeys() {\n if (!this.isConnected() || !this.isVerified) {\n return false;\n }\n \n const now = Date.now();\n const timeSinceLastRotation = now - this.lastKeyRotation;\n \n // Rotate keys every 5 minutes or after 100 messages\n return timeSinceLastRotation > this.keyRotationInterval || \n this.messageCounter % 100 === 0;\n }\n\n // PFS: Rotate encryption keys for Perfect Forward Secrecy\n async rotateKeys() {\n return this._withMutex('keyOperation', async (operationId) => {\n this._secureLog('info', '\uD83D\uDD04 Starting key rotation with mutex', {\n operationId: operationId\n });\n \n // Validate state inside the critical section\n if (!this.isConnected() || !this.isVerified) {\n this._secureLog('warn', '\u26A0\uFE0F Key rotation aborted - connection not ready', {\n operationId: operationId,\n isConnected: this.isConnected(),\n isVerified: this.isVerified\n });\n return false;\n }\n \n // Ensure rotation is not already in progress\n if (this._keySystemState.isRotating) {\n this._secureLog('warn', '\u26A0\uFE0F Key rotation already in progress', {\n operationId: operationId\n });\n return false;\n }\n \n try {\n // Set rotation flag\n this._keySystemState.isRotating = true;\n this._keySystemState.lastOperation = 'rotation';\n this._keySystemState.lastOperationTime = Date.now();\n \n // Send rotation signal to peer\n const rotationSignal = {\n type: 'key_rotation_signal',\n newVersion: this.currentKeyVersion + 1,\n timestamp: Date.now(),\n operationId: operationId\n };\n \n if (this.dataChannel && this.dataChannel.readyState === 'open') {\n this.dataChannel.send(JSON.stringify(rotationSignal));\n } else {\n throw new Error('Data channel not ready for key rotation');\n }\n \n // Perform hard wipe of old keys for real PFS\n this._hardWipeOldKeys();\n \n // Wait for peer confirmation\n return new Promise((resolve) => {\n this.pendingRotation = {\n newVersion: this.currentKeyVersion + 1,\n operationId: operationId,\n resolve: resolve,\n timeout: setTimeout(() => {\n this._secureLog('error', '\u26A0\uFE0F Key rotation timeout', {\n operationId: operationId\n });\n this._keySystemState.isRotating = false;\n this.pendingRotation = null;\n resolve(false);\n }, 10000) // 10 seconds timeout\n };\n });\n \n } catch (error) {\n this._secureLog('error', '\u274C Key rotation failed in critical section', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n this._keySystemState.isRotating = false;\n return false;\n }\n }, 10000); // 10 seconds timeout for the entire operation\n }\n\n // Real PFS - Clean up old keys with hard wipe\n cleanupOldKeys() {\n const now = Date.now();\n const maxKeyAge = EnhancedSecureWebRTCManager.LIMITS.MAX_KEY_AGE; // 15 minutes - keys older than this are deleted\n \n let wipedKeysCount = 0;\n \n for (const [version, keySet] of this.oldKeys.entries()) {\n if (now - keySet.timestamp > maxKeyAge) {\n // Hard wipe old keys before deletion\n if (keySet.encryptionKey) {\n this._secureWipeMemory(keySet.encryptionKey, 'pfs_cleanup_wipe');\n }\n if (keySet.macKey) {\n this._secureWipeMemory(keySet.macKey, 'pfs_cleanup_wipe');\n }\n if (keySet.metadataKey) {\n this._secureWipeMemory(keySet.metadataKey, 'pfs_cleanup_wipe');\n }\n \n // Clear references\n keySet.encryptionKey = null;\n keySet.macKey = null;\n keySet.metadataKey = null;\n keySet.keyFingerprint = null;\n \n this.oldKeys.delete(version);\n wipedKeysCount++;\n \n this._secureLog('info', '\uD83E\uDDF9 Old PFS keys hard wiped and cleaned up', {\n version: version,\n age: Math.round((now - keySet.timestamp) / 1000) + 's',\n timestamp: Date.now()\n });\n }\n }\n \n if (wipedKeysCount > 0) {\n this._secureLog('info', `\u2705 PFS cleanup completed: ${wipedKeysCount} keys hard wiped`, {\n timestamp: Date.now()\n });\n }\n }\n\n // PFS: Get keys for specific version (for decryption)\n getKeysForVersion(version) {\n // First, we check the old keys (including version 0).\n const oldKeySet = this.oldKeys.get(version);\n if (oldKeySet && oldKeySet.encryptionKey && oldKeySet.macKey && oldKeySet.metadataKey) {\n return {\n encryptionKey: oldKeySet.encryptionKey,\n macKey: oldKeySet.macKey,\n metadataKey: oldKeySet.metadataKey\n };\n }\n \n // If this is the current version, return the current keys.\n if (version === this.currentKeyVersion) {\n if (this.encryptionKey && this.macKey && this.metadataKey) {\n return {\n encryptionKey: this.encryptionKey,\n macKey: this.macKey,\n metadataKey: this.metadataKey\n };\n }\n }\n \n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'No valid keys found for version', {\n requestedVersion: version,\n currentVersion: this.currentKeyVersion,\n availableVersions: Array.from(this.oldKeys.keys())\n });\n \n return null;\n }\n\n createPeerConnection() {\n const config = {\n iceServers: [\n { urls: 'stun:stun.l.google.com:19302' },\n { urls: 'stun:stun1.l.google.com:19302' },\n { urls: 'stun:stun2.l.google.com:19302' },\n { urls: 'stun:stun3.l.google.com:19302' },\n { urls: 'stun:stun4.l.google.com:19302' }\n ],\n iceCandidatePoolSize: 10,\n bundlePolicy: 'balanced'\n };\n\n this.peerConnection = new RTCPeerConnection(config);\n\n this.peerConnection.onconnectionstatechange = () => {\n const state = this.peerConnection.connectionState;\n console.log('Connection state:', state);\n \n if (state === 'connected' && !this.isVerified) {\n this.onStatusChange('verifying');\n } else if (state === 'connected' && this.isVerified) {\n this.onStatusChange('connected');\n } else if (state === 'disconnected' || state === 'closed') {\n // If this is an intentional disconnect, clear immediately.\n if (this.intentionalDisconnect) {\n this.onStatusChange('disconnected');\n setTimeout(() => this.disconnect(), 100);\n } else {\n this.onStatusChange('disconnected');\n // Clear verification states on unexpected disconnect\n this._clearVerificationStates();\n }\n } else if (state === 'failed') {\n // Do not auto-reconnect to avoid closing the session on errors\n this.onStatusChange('disconnected');\n\n } else {\n this.onStatusChange(state);\n }\n };\n\n this.peerConnection.ondatachannel = (event) => {\n console.log('\uD83D\uDD17 Data channel received:', {\n channelLabel: event.channel.label,\n channelState: event.channel.readyState,\n isInitiator: this.isInitiator,\n channelId: event.channel.id,\n protocol: event.channel.protocol\n });\n \n // CRITICAL: Store the received data channel\n if (event.channel.label === 'securechat') {\n console.log('\uD83D\uDD17 MAIN DATA CHANNEL RECEIVED (answerer side)');\n this.dataChannel = event.channel;\n this.setupDataChannel(event.channel);\n } else {\n console.log('\uD83D\uDD17 ADDITIONAL DATA CHANNEL RECEIVED:', event.channel.label);\n // Handle additional channels (heartbeat, etc.)\n if (event.channel.label === 'heartbeat') {\n this.heartbeatChannel = event.channel;\n }\n }\n };\n }\n\n setupDataChannel(channel) {\n console.log('\uD83D\uDD17 setupDataChannel called:', {\n channelLabel: channel.label,\n channelState: channel.readyState,\n isInitiator: this.isInitiator,\n isVerified: this.isVerified\n });\n\n this.dataChannel = channel;\n\n this.dataChannel.onopen = async () => {\n console.log('\uD83D\uDD17 Data channel opened:', {\n isInitiator: this.isInitiator,\n isVerified: this.isVerified,\n dataChannelState: this.dataChannel.readyState,\n dataChannelLabel: this.dataChannel.label\n });\n // Configure backpressure for large transfers\n try {\n if (this.dataChannel && typeof this.dataChannel.bufferedAmountLowThreshold === 'number') {\n // 1 MB threshold for bufferedamountlow event\n this.dataChannel.bufferedAmountLowThreshold = 1024 * 1024;\n }\n } catch (e) {\n // ignore\n }\n \n try {\n await this.establishConnection();\n\n this.initializeFileTransfer();\n \n } catch (error) {\n this._secureLog('error', '\u274C Error in establishConnection:', { errorType: error?.constructor?.name || 'Unknown' });\n // Continue despite errors\n }\n \n // CRITICAL: Send pending SAS code if available\n if (this.pendingSASCode && this.dataChannel && this.dataChannel.readyState === 'open') {\n try {\n const sasPayload = {\n type: 'sas_code',\n data: {\n code: this.pendingSASCode,\n timestamp: Date.now(),\n verificationMethod: 'SAS',\n securityLevel: 'MITM_PROTECTION_REQUIRED'\n }\n };\n console.log('\uD83D\uDCE4 Sending pending SAS code to Answer side:', this.pendingSASCode);\n this.dataChannel.send(JSON.stringify(sasPayload));\n this.pendingSASCode = null; // Clear after sending\n } catch (error) {\n console.error('Failed to send pending SAS code to Answer side:', error);\n }\n } else if (this.pendingSASCode) {\n console.log('\u26A0\uFE0F Cannot send SAS code - dataChannel not ready:', {\n hasDataChannel: !!this.dataChannel,\n readyState: this.dataChannel?.readyState,\n pendingSASCode: this.pendingSASCode\n });\n }\n \n if (this.isVerified) {\n this.onStatusChange('connected');\n this.processMessageQueue();\n \n setTimeout(async () => {\n await this.calculateAndReportSecurityLevel();\n this.autoEnableSecurityFeatures();\n this.notifySecurityUpdate();\n }, 500);\n } else {\n this.onStatusChange('verifying');\n this.initiateVerification();\n }\n this.startHeartbeat();\n };\n\n this.dataChannel.onclose = () => {\n if (!this.intentionalDisconnect) {\n this.onStatusChange('disconnected');\n // Clear verification states on data channel close\n this._clearVerificationStates();\n \n if (!this.connectionClosedNotificationSent) {\n this.connectionClosedNotificationSent = true;\n this.deliverMessageToUI('\uD83D\uDD0C Enhanced secure connection closed. Check connection status.', 'system');\n }\n } else {\n this.onStatusChange('disconnected');\n // Clear verification states on intentional disconnect\n this._clearVerificationStates();\n \n if (!this.connectionClosedNotificationSent) {\n this.connectionClosedNotificationSent = true;\n this.deliverMessageToUI('\uD83D\uDD0C Enhanced secure connection closed', 'system');\n }\n }\n \n // Wipe ephemeral keys when session ends for PFS\n this._wipeEphemeralKeys();\n \n this.stopHeartbeat();\n this.isVerified = false;\n };\n\n // FIX 2: Remove mutex entirely from message processing path\n this.dataChannel.onmessage = async (event) => {\n try {\n console.log('\uD83D\uDCE8 Raw message received:', {\n dataType: typeof event.data,\n dataLength: event.data?.length || event.data?.byteLength || 0,\n isString: typeof event.data === 'string'\n });\n\n // IMPORTANT: Process ALL messages WITHOUT mutex\n if (typeof event.data === 'string') {\n try {\n const parsed = JSON.parse(event.data);\n console.log('\uD83D\uDCE8 Parsed message:', {\n type: parsed.type,\n hasData: !!parsed.data,\n timestamp: parsed.timestamp\n });\n \n // ============================================\n // CRITICAL: FILE MESSAGES (WITHOUT MUTEX)\n // ============================================\n \n const fileMessageTypes = [\n 'file_transfer_start',\n 'file_transfer_response', \n 'file_chunk',\n 'chunk_confirmation',\n 'file_transfer_complete',\n 'file_transfer_error'\n ];\n \n if (parsed.type && fileMessageTypes.includes(parsed.type)) {\n console.log('\uD83D\uDCC1 File message intercepted at WebRTC level:', parsed.type);\n\n if (!this.fileTransferSystem) {\n try {\n if (this.isVerified && this.dataChannel && this.dataChannel.readyState === 'open') {\n this.initializeFileTransfer();\n\n let attempts = 0;\n const maxAttempts = 30;\n while (!this.fileTransferSystem && attempts < maxAttempts) {\n await new Promise(resolve => setTimeout(resolve, 100));\n attempts++;\n }\n }\n } catch (initError) {\n this._secureLog('error', '\u274C Failed to initialize file transfer system for receiver:', { errorType: initError?.constructor?.name || 'Unknown' });\n }\n }\n\n if (this.fileTransferSystem) {\n console.log('\uD83D\uDCC1 Forwarding to local file transfer system:', parsed.type);\n await this.fileTransferSystem.handleFileMessage(parsed);\n return;\n }\n // Attempt lazy initialization on receiver side\n this._secureLog('warn', '\u26A0\uFE0F File transfer system not ready, attempting lazy init...');\n try {\n await this._ensureFileTransferReady();\n if (this.fileTransferSystem) {\n await this.fileTransferSystem.handleFileMessage(parsed);\n return;\n }\n } catch (e) {\n this._secureLog('error', '\u274C Lazy init of file transfer failed:', { errorType: e?.message || e?.constructor?.name || 'Unknown' });\n }\n this._secureLog('error', '\u274C No file transfer system available for:', { errorType: parsed.type?.constructor?.name || 'Unknown' });\n return; // IMPORTANT: Do not process further\n }\n \n // ============================================\n // SYSTEM MESSAGES (WITHOUT MUTEX)\n // ============================================\n \n if (parsed.type && ['heartbeat', 'verification', 'verification_response', 'verification_confirmed', 'verification_both_confirmed', 'sas_code', 'peer_disconnect', 'security_upgrade'].includes(parsed.type)) {\n console.log('\uD83D\uDD27 System message detected:', parsed.type);\n this.handleSystemMessage(parsed);\n return;\n }\n \n // ============================================\n // REGULAR USER MESSAGES (WITHOUT MUTEX)\n // ============================================\n \n if (parsed.type === 'message' && parsed.data) {\n console.log('\uD83D\uDCDD User message detected:', parsed.data.substring(0, 50));\n if (this.onMessage) {\n this.deliverMessageToUI(parsed.data, 'received');\n }\n return;\n }\n \n // ============================================\n // ENHANCED MESSAGES (WITHOUT MUTEX)\n // ============================================\n \n if (parsed.type === 'enhanced_message' && parsed.data) {\n console.log('\uD83D\uDD10 Enhanced message detected, processing...');\n await this._processEnhancedMessageWithoutMutex(parsed);\n return;\n }\n \n // ============================================\n // FAKE MESSAGES (WITHOUT MUTEX)\n // ============================================\n \n if (parsed.type === 'fake') {\n console.log('\uD83C\uDFAD Fake message blocked:', parsed.pattern);\n return;\n }\n \n // ============================================\n // UNKNOWN MESSAGE TYPES\n // ============================================\n \n console.log('\u2753 Unknown message type:', parsed.type);\n \n } catch (jsonError) {\n // Not JSON \u2014 treat as regular text message\n console.log('\uD83D\uDCC4 Non-JSON message detected, treating as text');\n if (this.onMessage) {\n this.deliverMessageToUI(event.data, 'received');\n }\n return;\n }\n } else if (event.data instanceof ArrayBuffer) {\n // Binary data \u2014 process WITHOUT mutex\n console.log('\uD83D\uDD22 Binary data received, processing...');\n await this._processBinaryDataWithoutMutex(event.data);\n } else {\n console.log('\u2753 Unknown data type:', typeof event.data);\n }\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to process message in onmessage:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n };\n }\n // FIX 4: New method for processing binary data WITHOUT mutex\n async _processBinaryDataWithoutMutex(data) {\n try {\n console.log('\uD83D\uDD22 Processing binary data without mutex...');\n \n // Apply security layers WITHOUT mutex\n let processedData = data;\n \n // Nested Encryption Removal (if enabled)\n if (this.securityFeatures.hasNestedEncryption && \n this.nestedEncryptionKey && \n processedData instanceof ArrayBuffer &&\n processedData.byteLength > 12) {\n \n try {\n processedData = await this.removeNestedEncryption(processedData);\n } catch (error) {\n this._secureLog('warn', '\u26A0\uFE0F Nested decryption failed, continuing with original data');\n }\n }\n \n // Packet Padding Removal (if enabled)\n if (this.securityFeatures.hasPacketPadding && processedData instanceof ArrayBuffer) {\n try {\n processedData = this.removePacketPadding(processedData);\n } catch (error) {\n this._secureLog('warn', '\u26A0\uFE0F Packet padding removal failed, continuing with original data');\n }\n }\n \n // Anti-Fingerprinting Removal (if enabled)\n if (this.securityFeatures.hasAntiFingerprinting && processedData instanceof ArrayBuffer) {\n try {\n processedData = this.removeAntiFingerprinting(processedData);\n } catch (error) {\n this._secureLog('warn', '\u26A0\uFE0F Anti-fingerprinting removal failed, continuing with original data');\n }\n }\n \n // Convert to text\n if (processedData instanceof ArrayBuffer) {\n const textData = new TextDecoder().decode(processedData);\n \n // Check for fake messages\n try {\n const content = JSON.parse(textData);\n if (content.type === 'fake' || content.isFakeTraffic === true) {\n console.log(`\uD83C\uDFAD BLOCKED: Binary fake message: ${content.pattern || 'unknown'}`);\n return;\n }\n } catch (e) {\n // Not JSON \u2014 fine for plain text\n }\n \n // Deliver message to user\n if (this.onMessage) {\n this.deliverMessageToUI(textData, 'received');\n }\n }\n \n } catch (error) {\n this._secureLog('error', '\u274C Error processing binary data:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }\n // FIX 3: New method for processing enhanced messages WITHOUT mutex\n async _processEnhancedMessageWithoutMutex(parsedMessage) {\n try {\n console.log('\uD83D\uDD10 Processing enhanced message without mutex...');\n \n if (!this.encryptionKey || !this.macKey || !this.metadataKey) {\n this._secureLog('error', '\u274C Missing encryption keys for enhanced message');\n return;\n }\n \n const decryptedResult = await window.EnhancedSecureCryptoUtils.decryptMessage(\n parsedMessage.data,\n this.encryptionKey,\n this.macKey,\n this.metadataKey\n );\n \n if (decryptedResult && decryptedResult.message) {\n console.log('\u2705 Enhanced message decrypted successfully');\n \n // Try parsing JSON and showing nested text if it's a chat message\n try {\n const decryptedContent = JSON.parse(decryptedResult.message);\n if (decryptedContent.type === 'fake' || decryptedContent.isFakeTraffic === true) {\n console.log(`\uFFFD\uFFFD BLOCKED: Encrypted fake message: ${decryptedContent.pattern || 'unknown'}`);\n return;\n }\n if (decryptedContent && decryptedContent.type === 'message' && typeof decryptedContent.data === 'string') {\n if (this.onMessage) {\n this.deliverMessageToUI(decryptedContent.data, 'received');\n }\n return;\n }\n } catch (e) {\n // Not JSON \u2014 fine for plain text\n }\n \n // Otherwise pass as-is\n if (this.onMessage) {\n this.deliverMessageToUI(decryptedResult.message, 'received');\n }\n } else {\n this._secureLog('warn', '\u26A0\uFE0F No message content in decrypted result');\n }\n \n } catch (error) {\n this._secureLog('error', '\u274C Error processing enhanced message:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }\n /**\n * Creates a unique ID for an operation\n */\n _generateOperationId() {\n return `op_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n /**\n * Atomic mutex acquisition with enhanced race condition protection\n */\n async _acquireMutex(mutexName, operationId, timeout = 5000) {\n // Build correct mutex property name\n const mutexPropertyName = `_${mutexName}Mutex`;\n const mutex = this[mutexPropertyName];\n \n if (!mutex) {\n this._secureLog('error', `\u274C Unknown mutex: ${mutexName}`, {\n mutexPropertyName: mutexPropertyName,\n availableMutexes: this._getAvailableMutexes(),\n operationId: operationId\n });\n throw new Error(`Unknown mutex: ${mutexName}. Available: ${this._getAvailableMutexes().join(', ')}`);\n }\n \n // Validate operation ID\n if (!operationId || typeof operationId !== 'string') {\n throw new Error('Invalid operation ID for mutex acquisition');\n }\n \n return new Promise((resolve, reject) => {\n // Atomic lock attempt with immediate state check\n const attemptLock = () => {\n // Check if mutex is already locked by this operation\n if (mutex.lockId === operationId) {\n this._secureLog('warn', `\u26A0\uFE0F Mutex '${mutexName}' already locked by same operation`, {\n operationId: operationId\n });\n resolve();\n return;\n }\n \n // Atomic check and lock operation\n if (!mutex.locked) {\n // Set lock state atomically\n mutex.locked = true;\n mutex.lockId = operationId;\n mutex.lockTime = Date.now();\n \n this._secureLog('debug', `\uD83D\uDD12 Mutex '${mutexName}' acquired atomically`, {\n operationId: operationId,\n lockTime: mutex.lockTime\n });\n \n // Set timeout for automatic release with enhanced validation\n mutex.lockTimeout = setTimeout(() => {\n // Enhanced timeout handling with state validation\n this._handleMutexTimeout(mutexName, operationId, timeout);\n }, timeout);\n \n resolve();\n } else {\n // Add to queue with timeout\n const queueItem = { \n resolve, \n reject, \n operationId,\n timestamp: Date.now(),\n timeout: setTimeout(() => {\n // Remove from queue on timeout\n const index = mutex.queue.findIndex(item => item.operationId === operationId);\n if (index !== -1) {\n mutex.queue.splice(index, 1);\n reject(new Error(`Mutex acquisition timeout for '${mutexName}'`));\n }\n }, timeout)\n };\n \n mutex.queue.push(queueItem);\n \n this._secureLog('debug', `\u23F3 Operation queued for mutex '${mutexName}'`, {\n operationId: operationId,\n queueLength: mutex.queue.length,\n currentLockId: mutex.lockId\n });\n }\n };\n \n // Execute lock attempt immediately\n attemptLock();\n });\n }\n\n /**\n * Enhanced mutex release with strict validation and error handling\n */\n _releaseMutex(mutexName, operationId) {\n // Validate input parameters\n if (!mutexName || typeof mutexName !== 'string') {\n throw new Error('Invalid mutex name provided for release');\n }\n \n if (!operationId || typeof operationId !== 'string') {\n throw new Error('Invalid operation ID provided for mutex release');\n }\n \n // Build correct mutex property name\n const mutexPropertyName = `_${mutexName}Mutex`;\n const mutex = this[mutexPropertyName];\n \n if (!mutex) {\n this._secureLog('error', `\u274C Unknown mutex for release: ${mutexName}`, {\n mutexPropertyName: mutexPropertyName,\n availableMutexes: this._getAvailableMutexes(),\n operationId: operationId\n });\n throw new Error(`Unknown mutex for release: ${mutexName}`);\n }\n \n // Strict validation of lock ownership\n if (mutex.lockId !== operationId) {\n this._secureLog('error', `\u274C CRITICAL: Invalid mutex release attempt - potential race condition`, {\n mutexName: mutexName,\n expectedLockId: mutex.lockId,\n providedOperationId: operationId,\n mutexState: {\n locked: mutex.locked,\n lockTime: mutex.lockTime,\n queueLength: mutex.queue.length\n }\n });\n \n // Throw error instead of silent failure\n throw new Error(`Invalid mutex release attempt for '${mutexName}': expected '${mutex.lockId}', got '${operationId}'`);\n }\n \n // Validate mutex is actually locked\n if (!mutex.locked) {\n this._secureLog('error', `\u274C CRITICAL: Attempting to release unlocked mutex`, {\n mutexName: mutexName,\n operationId: operationId,\n mutexState: {\n locked: mutex.locked,\n lockId: mutex.lockId,\n lockTime: mutex.lockTime\n }\n });\n throw new Error(`Attempting to release unlocked mutex: ${mutexName}`);\n }\n \n try {\n // Clear timeout first\n if (mutex.lockTimeout) {\n clearTimeout(mutex.lockTimeout);\n mutex.lockTimeout = null;\n }\n \n // Calculate lock duration for monitoring\n const lockDuration = mutex.lockTime ? Date.now() - mutex.lockTime : 0;\n \n // Atomic release with state validation\n mutex.locked = false;\n mutex.lockId = null;\n mutex.lockTime = null;\n \n this._secureLog('debug', `\uD83D\uDD13 Mutex released successfully: ${mutexName}`, {\n operationId: operationId,\n lockDuration: lockDuration,\n queueLength: mutex.queue.length\n });\n \n // Process next in queue with enhanced error handling\n this._processNextInQueue(mutexName);\n \n } catch (error) {\n // If queue processing fails, ensure mutex is still released\n this._secureLog('error', `\u274C Error during mutex release queue processing`, {\n mutexName: mutexName,\n operationId: operationId,\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n \n // Ensure mutex is released even if queue processing fails\n mutex.locked = false;\n mutex.lockId = null;\n mutex.lockTime = null;\n mutex.lockTimeout = null;\n \n throw error;\n }\n }\n\n /**\n * Enhanced queue processing with comprehensive error handling\n */\n _processNextInQueue(mutexName) {\n const mutex = this[`_${mutexName}Mutex`];\n \n if (!mutex) {\n this._secureLog('error', `\u274C Mutex not found for queue processing: ${mutexName}`);\n return;\n }\n \n if (mutex.queue.length === 0) {\n return;\n }\n \n // Validate mutex state before processing queue\n if (mutex.locked) {\n this._secureLog('warn', `\u26A0\uFE0F Mutex '${mutexName}' is still locked, skipping queue processing`, {\n lockId: mutex.lockId,\n queueLength: mutex.queue.length\n });\n return;\n }\n \n // Get next item from queue atomically with validation\n const nextItem = mutex.queue.shift();\n \n if (!nextItem) {\n this._secureLog('warn', `\u26A0\uFE0F Empty queue item for mutex '${mutexName}'`);\n return;\n }\n \n // Validate queue item structure\n if (!nextItem.operationId || !nextItem.resolve || !nextItem.reject) {\n this._secureLog('error', `\u274C Invalid queue item structure for mutex '${mutexName}'`, {\n hasOperationId: !!nextItem.operationId,\n hasResolve: !!nextItem.resolve,\n hasReject: !!nextItem.reject\n });\n return;\n }\n \n try {\n // Clear timeout for this item\n if (nextItem.timeout) {\n clearTimeout(nextItem.timeout);\n }\n \n // Attempt to acquire lock for next item\n this._secureLog('debug', `\uD83D\uDD04 Processing next operation in queue for mutex '${mutexName}'`, {\n operationId: nextItem.operationId,\n queueRemaining: mutex.queue.length,\n timestamp: Date.now()\n });\n \n // Retry lock acquisition for queued operation with enhanced error handling\n setTimeout(async () => {\n try {\n await this._acquireMutex(mutexName, nextItem.operationId, 5000);\n \n this._secureLog('debug', `\u2705 Queued operation acquired mutex '${mutexName}'`, {\n operationId: nextItem.operationId,\n acquisitionTime: Date.now()\n });\n \n nextItem.resolve();\n \n } catch (error) {\n this._secureLog('error', `\u274C Queued operation failed to acquire mutex '${mutexName}'`, {\n operationId: nextItem.operationId,\n errorType: error.constructor.name,\n errorMessage: error.message,\n timestamp: Date.now()\n });\n \n // Reject with detailed error information\n nextItem.reject(new Error(`Queue processing failed for '${mutexName}': ${error.message}`));\n \n // Continue processing queue even if one item fails\n setTimeout(() => {\n this._processNextInQueue(mutexName);\n }, 50);\n }\n }, 10); // Small delay to prevent immediate re-acquisition\n \n } catch (error) {\n this._secureLog('error', `\u274C Critical error during queue processing for mutex '${mutexName}'`, {\n operationId: nextItem.operationId,\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n \n // Reject the operation and continue processing\n try {\n nextItem.reject(new Error(`Queue processing critical error: ${error.message}`));\n } catch (rejectError) {\n this._secureLog('error', `\u274C Failed to reject queue item`, {\n originalError: error.message,\n rejectError: rejectError.message\n });\n }\n \n // Continue processing remaining queue items\n setTimeout(() => {\n this._processNextInQueue(mutexName);\n }, 100);\n }\n }\n\n _getAvailableMutexes() {\n const mutexes = [];\n const propertyNames = Object.getOwnPropertyNames(this);\n \n for (const prop of propertyNames) {\n if (prop.endsWith('Mutex') && prop.startsWith('_')) {\n // Extract mutex name without prefix/suffix\n const mutexName = prop.slice(1, -5); // Remove '_' prefix and 'Mutex' suffix\n mutexes.push(mutexName);\n }\n }\n \n return mutexes;\n }\n\n /**\n * Enhanced mutex execution with atomic operations\n */\n async _withMutex(mutexName, operation, timeout = 5000) {\n const operationId = this._generateOperationId();\n \n // Validate mutex system before operation\n if (!this._validateMutexSystem()) {\n this._secureLog('error', '\u274C Mutex system not properly initialized', {\n operationId: operationId,\n mutexName: mutexName\n });\n throw new Error('Mutex system not properly initialized. Call _initializeMutexSystem() first.');\n }\n \n // Get mutex reference with validation\n const mutex = this[`_${mutexName}Mutex`];\n if (!mutex) {\n throw new Error(`Mutex '${mutexName}' not found`);\n }\n \n let mutexAcquired = false;\n \n try {\n // Atomic mutex acquisition with timeout\n await this._acquireMutex(mutexName, operationId, timeout);\n mutexAcquired = true;\n \n // Increment operation counter atomically\n const counterKey = `${mutexName}Operations`;\n if (this._operationCounters && this._operationCounters[counterKey] !== undefined) {\n this._operationCounters[counterKey]++;\n }\n \n // Execute operation with enhanced error handling\n const result = await operation(operationId);\n \n // Validate result before returning\n if (result === undefined && operation.name !== 'cleanup') {\n this._secureLog('warn', '\u26A0\uFE0F Mutex operation returned undefined result', {\n operationId: operationId,\n mutexName: mutexName,\n operationName: operation.name\n });\n }\n \n return result;\n \n } catch (error) {\n // Enhanced error logging with context\n this._secureLog('error', '\u274C Error in mutex operation', {\n operationId: operationId,\n mutexName: mutexName,\n errorType: error.constructor.name,\n errorMessage: error.message,\n mutexAcquired: mutexAcquired,\n mutexState: mutex ? {\n locked: mutex.locked,\n lockId: mutex.lockId,\n queueLength: mutex.queue.length\n } : 'null'\n });\n \n // If this is a key operation error, trigger emergency recovery\n if (mutexName === 'keyOperation') {\n this._handleKeyOperationError(error, operationId);\n }\n \n // Trigger emergency unlock for critical mutex errors\n if (error.message.includes('timeout') || error.message.includes('race condition')) {\n this._emergencyUnlockAllMutexes('errorHandler');\n }\n \n throw error;\n } finally {\n // Always release mutex in finally block with validation\n if (mutexAcquired) {\n try {\n await this._releaseMutex(mutexName, operationId);\n \n // Verify mutex was properly released\n if (mutex.locked && mutex.lockId === operationId) {\n this._secureLog('error', '\u274C Mutex release verification failed', {\n operationId: operationId,\n mutexName: mutexName\n });\n // Force release as fallback\n mutex.locked = false;\n mutex.lockId = null;\n mutex.lockTimeout = null;\n }\n \n } catch (releaseError) {\n this._secureLog('error', '\u274C Error releasing mutex in finally block', {\n operationId: operationId,\n mutexName: mutexName,\n releaseErrorType: releaseError.constructor.name,\n releaseErrorMessage: releaseError.message\n });\n \n // Force release on error\n mutex.locked = false;\n mutex.lockId = null;\n mutex.lockTimeout = null;\n }\n }\n }\n }\n\n _validateMutexSystem() {\n const requiredMutexes = ['keyOperation', 'cryptoOperation', 'connectionOperation'];\n \n for (const mutexName of requiredMutexes) {\n const mutexPropertyName = `_${mutexName}Mutex`;\n const mutex = this[mutexPropertyName];\n \n if (!mutex || typeof mutex !== 'object') {\n this._secureLog('error', `\u274C Missing or invalid mutex: ${mutexName}`, {\n mutexPropertyName: mutexPropertyName,\n mutexType: typeof mutex\n });\n return false;\n }\n \n // Validate mutex structure\n const requiredProps = ['locked', 'queue', 'lockId', 'lockTimeout'];\n for (const prop of requiredProps) {\n if (!(prop in mutex)) {\n this._secureLog('error', `\u274C Mutex ${mutexName} missing property: ${prop}`);\n return false;\n }\n }\n }\n \n return true;\n }\n\n /**\n * Enhanced emergency recovery of the mutex system\n */\n _emergencyRecoverMutexSystem() {\n this._secureLog('warn', '\uD83D\uDEA8 Emergency mutex system recovery initiated');\n \n try {\n // Emergency unlock all mutexes first\n this._emergencyUnlockAllMutexes('emergencyRecovery');\n \n // Force re-initialize the system\n this._initializeMutexSystem();\n \n // Validate recovery success\n if (!this._validateMutexSystem()) {\n throw new Error('Mutex system validation failed after recovery');\n }\n \n this._secureLog('info', '\u2705 Mutex system recovered successfully with validation');\n return true;\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to recover mutex system', {\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n \n // Last resort - force re-initialization\n try {\n this._initializeMutexSystem();\n this._secureLog('warn', '\u26A0\uFE0F Forced mutex system re-initialization completed');\n return true;\n } catch (reinitError) {\n this._secureLog('error', '\u274C CRITICAL: Forced re-initialization also failed', {\n originalError: error.message,\n reinitError: reinitError.message\n });\n return false;\n }\n }\n }\n\n /**\n * Atomic key generation with race condition protection\n */\n async _generateEncryptionKeys() {\n return this._withMutex('keyOperation', async (operationId) => {\n this._secureLog('info', '\uD83D\uDD11 Generating encryption keys with atomic mutex', {\n operationId: operationId\n });\n \n // Atomic state check and update using mutex lock\n const currentState = this._keySystemState;\n \n // Atomic check - if already initializing, wait or fail\n if (currentState.isInitializing) {\n this._secureLog('warn', '\u26A0\uFE0F Key generation already in progress, waiting for completion', {\n operationId: operationId,\n lastOperation: currentState.lastOperation,\n lastOperationTime: currentState.lastOperationTime\n });\n \n // Wait for existing operation to complete\n let waitAttempts = 0;\n const maxWaitAttempts = 50; // 5 seconds max wait\n \n while (currentState.isInitializing && waitAttempts < maxWaitAttempts) {\n await new Promise(resolve => setTimeout(resolve, 100));\n waitAttempts++;\n }\n \n if (currentState.isInitializing) {\n throw new Error('Key generation timeout - operation still in progress after 5 seconds');\n }\n }\n \n // Atomic state update within mutex protection\n try {\n // Set state atomically within mutex\n currentState.isInitializing = true;\n currentState.lastOperation = 'generation';\n currentState.lastOperationTime = Date.now();\n currentState.operationId = operationId;\n \n this._secureLog('debug', '\uD83D\uDD12 Atomic key generation state set', {\n operationId: operationId,\n timestamp: currentState.lastOperationTime\n });\n \n // Generate keys with individual error handling\n let ecdhKeyPair = null;\n let ecdsaKeyPair = null;\n \n // Generate ephemeral ECDH keys for PFS\n try {\n ecdhKeyPair = await this._generateEphemeralECDHKeys();\n \n // Validate ECDH keys immediately\n if (!ecdhKeyPair || !ecdhKeyPair.privateKey || !ecdhKeyPair.publicKey) {\n throw new Error('Ephemeral ECDH key pair validation failed');\n }\n \n // Constant-time validation for key types\n if (!this._validateKeyPairConstantTime(ecdhKeyPair)) {\n throw new Error('Ephemeral ECDH keys are not valid CryptoKey instances');\n }\n \n this._secureLog('debug', '\u2705 Ephemeral ECDH keys generated and validated for PFS', {\n operationId: operationId,\n privateKeyType: ecdhKeyPair.privateKey.algorithm?.name,\n publicKeyType: ecdhKeyPair.publicKey.algorithm?.name,\n isEphemeral: true\n });\n \n } catch (ecdhError) {\n this._secureLog('error', '\u274C Ephemeral ECDH key generation failed', {\n operationId: operationId,\n errorType: ecdhError.constructor.name\n });\n this._throwSecureError(ecdhError, 'ephemeral_ecdh_key_generation');\n }\n \n // Generate ECDSA keys with retry mechanism\n try {\n ecdsaKeyPair = await window.EnhancedSecureCryptoUtils.generateECDSAKeyPair();\n \n // Validate ECDSA keys immediately\n if (!ecdsaKeyPair || !ecdsaKeyPair.privateKey || !ecdsaKeyPair.publicKey) {\n throw new Error('ECDSA key pair validation failed');\n }\n \n // Constant-time validation for key types\n if (!this._validateKeyPairConstantTime(ecdsaKeyPair)) {\n throw new Error('ECDSA keys are not valid CryptoKey instances');\n }\n \n this._secureLog('debug', '\u2705 ECDSA keys generated and validated', {\n operationId: operationId,\n privateKeyType: ecdsaKeyPair.privateKey.algorithm?.name,\n publicKeyType: ecdsaKeyPair.publicKey.algorithm?.name\n });\n \n } catch (ecdsaError) {\n this._secureLog('error', '\u274C ECDSA key generation failed', {\n operationId: operationId,\n errorType: ecdsaError.constructor.name\n });\n this._throwSecureError(ecdsaError, 'ecdsa_key_generation');\n }\n \n // Final validation of both key pairs\n if (!ecdhKeyPair || !ecdsaKeyPair) {\n throw new Error('One or both key pairs failed to generate');\n }\n \n // Enable security features after successful key generation\n this._enableSecurityFeaturesAfterKeyGeneration(ecdhKeyPair, ecdsaKeyPair);\n \n this._secureLog('info', '\u2705 Encryption keys generated successfully with atomic protection', {\n operationId: operationId,\n hasECDHKeys: !!(ecdhKeyPair?.privateKey && ecdhKeyPair?.publicKey),\n hasECDSAKeys: !!(ecdsaKeyPair?.privateKey && ecdsaKeyPair?.publicKey),\n generationTime: Date.now() - currentState.lastOperationTime\n });\n \n return { ecdhKeyPair, ecdsaKeyPair };\n \n } catch (error) {\n // Ensure state is reset on any error\n this._secureLog('error', '\u274C Key generation failed, resetting state', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n throw error;\n } finally {\n // Always reset state in finally block\n currentState.isInitializing = false;\n currentState.operationId = null;\n \n this._secureLog('debug', '\uD83D\uDD13 Key generation state reset', {\n operationId: operationId\n });\n }\n });\n }\n\n /**\n * Enable security features after successful key generation\n */\n _enableSecurityFeaturesAfterKeyGeneration(ecdhKeyPair, ecdsaKeyPair) {\n try {\n // Enable encryption features based on available keys\n if (ecdhKeyPair && ecdhKeyPair.privateKey && ecdhKeyPair.publicKey) {\n this.securityFeatures.hasEncryption = true;\n this.securityFeatures.hasECDH = true;\n this._secureLog('info', '\uD83D\uDD12 ECDH encryption features enabled');\n }\n \n if (ecdsaKeyPair && ecdsaKeyPair.privateKey && ecdsaKeyPair.publicKey) {\n this.securityFeatures.hasECDSA = true;\n this._secureLog('info', '\uD83D\uDD12 ECDSA signature features enabled');\n }\n \n // Enable additional features that depend on encryption\n if (this.securityFeatures.hasEncryption) {\n this.securityFeatures.hasMetadataProtection = true;\n this.securityFeatures.hasEnhancedReplayProtection = true;\n this.securityFeatures.hasNonExtractableKeys = true;\n this._secureLog('info', '\uD83D\uDD12 Additional encryption-dependent features enabled');\n }\n \n // Enable PFS after ephemeral key generation\n if (ecdhKeyPair && this.ephemeralKeyPairs.size > 0) {\n this.securityFeatures.hasPFS = true;\n this._secureLog('info', '\uD83D\uDD12 Perfect Forward Secrecy enabled with ephemeral keys');\n }\n \n this._secureLog('info', '\uD83D\uDD12 Security features updated after key generation', {\n hasEncryption: this.securityFeatures.hasEncryption,\n hasECDH: this.securityFeatures.hasECDH,\n hasECDSA: this.securityFeatures.hasECDSA,\n hasMetadataProtection: this.securityFeatures.hasMetadataProtection,\n hasEnhancedReplayProtection: this.securityFeatures.hasEnhancedReplayProtection,\n hasNonExtractableKeys: this.securityFeatures.hasNonExtractableKeys,\n hasPFS: this.securityFeatures.hasPFS\n });\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to enable security features after key generation', {\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n }\n }\n\n /**\n * Enhanced emergency mutex unlocking with authorization and validation\n */\n _emergencyUnlockAllMutexes(callerContext = 'unknown') {\n // Validate caller authorization\n const authorizedCallers = [\n 'keyOperation', 'cryptoOperation', 'connectionOperation',\n 'emergencyRecovery', 'systemShutdown', 'errorHandler'\n ];\n \n if (!authorizedCallers.includes(callerContext)) {\n this._secureLog('error', `\uD83D\uDEA8 UNAUTHORIZED emergency mutex unlock attempt`, {\n callerContext: callerContext,\n authorizedCallers: authorizedCallers,\n timestamp: Date.now()\n });\n throw new Error(`Unauthorized emergency mutex unlock attempt by: ${callerContext}`);\n }\n \n const mutexes = ['keyOperation', 'cryptoOperation', 'connectionOperation'];\n \n this._secureLog('error', '\uD83D\uDEA8 EMERGENCY: Unlocking all mutexes with authorization and state cleanup', {\n callerContext: callerContext,\n timestamp: Date.now()\n });\n \n let unlockedCount = 0;\n let errorCount = 0;\n \n mutexes.forEach(mutexName => {\n const mutex = this[`_${mutexName}Mutex`];\n if (mutex) {\n try {\n // Clear timeout first\n if (mutex.lockTimeout) {\n clearTimeout(mutex.lockTimeout);\n }\n \n // Log mutex state before emergency unlock\n const previousState = {\n locked: mutex.locked,\n lockId: mutex.lockId,\n lockTime: mutex.lockTime,\n queueLength: mutex.queue.length\n };\n \n // Reset mutex state atomically\n mutex.locked = false;\n mutex.lockId = null;\n mutex.lockTimeout = null;\n mutex.lockTime = null;\n \n // Clear queue with proper error handling and logging\n let queueRejectCount = 0;\n mutex.queue.forEach(item => {\n try {\n if (item.reject && typeof item.reject === 'function') {\n item.reject(new Error(`Emergency mutex unlock for ${mutexName} by ${callerContext}`));\n queueRejectCount++;\n }\n } catch (rejectError) {\n this._secureLog('warn', `\u26A0\uFE0F Failed to reject queue item during emergency unlock`, {\n mutexName: mutexName,\n errorType: rejectError.constructor.name\n });\n }\n });\n \n // Clear queue array\n mutex.queue = [];\n \n unlockedCount++;\n \n this._secureLog('debug', `\uD83D\uDD13 Emergency unlocked mutex: ${mutexName}`, {\n previousState: previousState,\n queueRejectCount: queueRejectCount,\n callerContext: callerContext\n });\n \n } catch (error) {\n errorCount++;\n this._secureLog('error', `\u274C Error during emergency unlock of mutex: ${mutexName}`, {\n errorType: error.constructor.name,\n errorMessage: error.message,\n callerContext: callerContext\n });\n }\n }\n });\n \n // Reset key system state with validation\n if (this._keySystemState) {\n try {\n const previousKeyState = { ...this._keySystemState };\n \n this._keySystemState.isInitializing = false;\n this._keySystemState.isRotating = false;\n this._keySystemState.isDestroying = false;\n this._keySystemState.operationId = null;\n this._keySystemState.concurrentOperations = 0;\n \n this._secureLog('debug', `\uD83D\uDD13 Emergency reset key system state`, {\n previousState: previousKeyState,\n callerContext: callerContext\n });\n \n } catch (error) {\n this._secureLog('error', `\u274C Error resetting key system state during emergency unlock`, {\n errorType: error.constructor.name,\n errorMessage: error.message,\n callerContext: callerContext\n });\n }\n }\n \n // Log emergency unlock summary\n this._secureLog('info', `\uD83D\uDEA8 Emergency mutex unlock completed`, {\n callerContext: callerContext,\n unlockedCount: unlockedCount,\n errorCount: errorCount,\n totalMutexes: mutexes.length,\n timestamp: Date.now()\n });\n \n // Trigger system validation after emergency unlock\n setTimeout(() => {\n this._validateMutexSystemAfterEmergencyUnlock();\n }, 100);\n }\n\n /**\n * Handle key operation errors with recovery mechanisms\n */\n _handleKeyOperationError(error, operationId) {\n this._secureLog('error', '\uD83D\uDEA8 Key operation error detected, initiating recovery', {\n operationId: operationId,\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n \n // Reset key system state immediately\n if (this._keySystemState) {\n this._keySystemState.isInitializing = false;\n this._keySystemState.isRotating = false;\n this._keySystemState.isDestroying = false;\n this._keySystemState.operationId = null;\n }\n \n // Clear any partial key data\n this.ecdhKeyPair = null;\n this.ecdsaKeyPair = null;\n this.encryptionKey = null;\n this.macKey = null;\n this.metadataKey = null;\n \n // Trigger emergency recovery if needed\n if (error.message.includes('timeout') || error.message.includes('race condition')) {\n this._secureLog('warn', '\u26A0\uFE0F Race condition or timeout detected, triggering emergency recovery');\n this._emergencyRecoverMutexSystem();\n }\n }\n\n /**\n * Generate cryptographically secure IV with reuse prevention\n */\n _generateSecureIV(ivSize = 12, context = 'general') {\n // Check if we're in emergency mode\n if (this._ivTrackingSystem.emergencyMode) {\n this._secureLog('error', '\uD83D\uDEA8 CRITICAL: IV generation blocked - emergency mode active due to IV reuse');\n throw new Error('IV generation blocked - emergency mode active');\n }\n \n let attempts = 0;\n const maxAttempts = 100; // Prevent infinite loops\n \n while (attempts < maxAttempts) {\n attempts++;\n \n // Generate fresh IV with crypto.getRandomValues\n const iv = crypto.getRandomValues(new Uint8Array(ivSize));\n \n // Convert IV to string for tracking\n const ivString = Array.from(iv).map(b => b.toString(16).padStart(2, '0')).join('');\n \n // Check for IV reuse\n if (this._ivTrackingSystem.usedIVs.has(ivString)) {\n this._ivTrackingSystem.collisionCount++;\n this._secureLog('error', `\uD83D\uDEA8 CRITICAL: IV reuse detected!`, {\n context: context,\n attempt: attempts,\n collisionCount: this._ivTrackingSystem.collisionCount,\n ivString: ivString.substring(0, 16) + '...' // Log partial IV for debugging\n });\n \n // If too many collisions, trigger emergency mode\n if (this._ivTrackingSystem.collisionCount > 5) {\n this._ivTrackingSystem.emergencyMode = true;\n this._secureLog('error', '\uD83D\uDEA8 CRITICAL: Emergency mode activated due to excessive IV reuse');\n throw new Error('Emergency mode: Excessive IV reuse detected');\n }\n \n continue; // Try again\n }\n \n // Validate IV entropy\n if (!this._validateIVEntropy(iv)) {\n this._ivTrackingSystem.entropyValidation.entropyFailures++;\n this._secureLog('warn', `\u26A0\uFE0F Low entropy IV detected`, {\n context: context,\n attempt: attempts,\n entropyFailures: this._ivTrackingSystem.entropyValidation.entropyFailures\n });\n \n // If too many entropy failures, trigger emergency mode\n if (this._ivTrackingSystem.entropyValidation.entropyFailures > 10) {\n this._ivTrackingSystem.emergencyMode = true;\n this._secureLog('error', '\uD83D\uDEA8 CRITICAL: Emergency mode activated due to low entropy IVs');\n throw new Error('Emergency mode: Low entropy IVs detected');\n }\n \n continue; // Try again\n }\n \n // Track IV usage\n this._ivTrackingSystem.usedIVs.add(ivString);\n this._ivTrackingSystem.ivHistory.set(ivString, {\n timestamp: Date.now(),\n context: context,\n attempt: attempts\n });\n \n // Track per-session IVs\n if (this.sessionId) {\n if (!this._ivTrackingSystem.sessionIVs.has(this.sessionId)) {\n this._ivTrackingSystem.sessionIVs.set(this.sessionId, new Set());\n }\n this._ivTrackingSystem.sessionIVs.get(this.sessionId).add(ivString);\n }\n \n // Validate RNG periodically\n this._validateRNGQuality();\n \n this._secureLog('debug', `\u2705 Secure IV generated`, {\n context: context,\n attempt: attempts,\n ivSize: ivSize,\n totalIVs: this._ivTrackingSystem.usedIVs.size\n });\n \n return iv;\n }\n \n // If we can't generate a unique IV after max attempts\n this._secureLog('error', `\u274C Failed to generate unique IV after ${maxAttempts} attempts`, {\n context: context,\n totalIVs: this._ivTrackingSystem.usedIVs.size\n });\n throw new Error(`Failed to generate unique IV after ${maxAttempts} attempts`);\n }\n \n /**\n * Validate IV entropy to detect weak RNG\n */\n _validateIVEntropy(iv) {\n this._ivTrackingSystem.entropyValidation.entropyTests++;\n \n // Calculate byte distribution\n const byteCounts = new Array(256).fill(0);\n for (let i = 0; i < iv.length; i++) {\n byteCounts[iv[i]]++;\n }\n \n // Multi-dimensional entropy analysis\n const entropyResults = {\n shannon: 0,\n min: 0,\n collision: 0,\n compression: 0,\n quantum: 0\n };\n \n // 1. Shannon entropy calculation\n let shannonEntropy = 0;\n const totalBytes = iv.length;\n \n for (let i = 0; i < 256; i++) {\n if (byteCounts[i] > 0) {\n const probability = byteCounts[i] / totalBytes;\n shannonEntropy -= probability * Math.log2(probability);\n }\n }\n entropyResults.shannon = shannonEntropy;\n \n // 2. Min-entropy calculation (worst-case scenario)\n const maxCount = Math.max(...byteCounts);\n const maxProbability = maxCount / totalBytes;\n entropyResults.min = -Math.log2(maxProbability);\n \n // 3. Collision entropy calculation\n let collisionSum = 0;\n for (let i = 0; i < 256; i++) {\n if (byteCounts[i] > 0) {\n const probability = byteCounts[i] / totalBytes;\n collisionSum += probability * probability;\n }\n }\n entropyResults.collision = -Math.log2(collisionSum);\n \n // 4. Compression-based entropy estimation\n const ivString = Array.from(iv).map(b => String.fromCharCode(b)).join('');\n const compressedLength = this._estimateCompressedLength(ivString);\n entropyResults.compression = (1 - compressedLength / totalBytes) * 8;\n \n // 5. Quantum-resistant entropy analysis\n entropyResults.quantum = this._calculateQuantumResistantEntropy(iv);\n \n // Enhanced suspicious pattern detection\n const hasSuspiciousPatterns = this._detectAdvancedSuspiciousPatterns(iv);\n \n // Multi-criteria validation\n const minEntropyThreshold = this._ivTrackingSystem.entropyValidation.minEntropy;\n const isValid = (\n entropyResults.shannon >= minEntropyThreshold &&\n entropyResults.min >= minEntropyThreshold * 0.8 &&\n entropyResults.collision >= minEntropyThreshold * 0.9 &&\n entropyResults.compression >= minEntropyThreshold * 0.7 &&\n entropyResults.quantum >= minEntropyThreshold * 0.6 &&\n !hasSuspiciousPatterns\n );\n \n if (!isValid) {\n this._secureLog('warn', `\u26A0\uFE0F Enhanced IV entropy validation failed`, {\n shannon: entropyResults.shannon.toFixed(2),\n min: entropyResults.min.toFixed(2),\n collision: entropyResults.collision.toFixed(2),\n compression: entropyResults.compression.toFixed(2),\n quantum: entropyResults.quantum.toFixed(2),\n minThreshold: minEntropyThreshold,\n hasSuspiciousPatterns: hasSuspiciousPatterns\n });\n }\n \n return isValid;\n }\n \n /**\n * Estimate compressed length for entropy calculation\n * @param {string} data - Data to estimate compression\n * @returns {number} Estimated compressed length\n */\n _estimateCompressedLength(data) {\n // Simple LZ77-like compression estimation\n let compressedLength = 0;\n let i = 0;\n \n while (i < data.length) {\n let matchLength = 0;\n let matchDistance = 0;\n \n // Look for repeated patterns\n for (let j = Math.max(0, i - 255); j < i; j++) {\n let k = 0;\n while (i + k < data.length && data[i + k] === data[j + k] && k < 255) {\n k++;\n }\n if (k > matchLength) {\n matchLength = k;\n matchDistance = i - j;\n }\n }\n \n if (matchLength >= 3) {\n compressedLength += 3; // Distance + length + literal\n i += matchLength;\n } else {\n compressedLength += 1;\n i += 1;\n }\n }\n \n return compressedLength;\n }\n\n /**\n * Calculate quantum-resistant entropy\n * @param {Uint8Array} data - Data to analyze\n * @returns {number} Quantum-resistant entropy score\n */\n _calculateQuantumResistantEntropy(data) {\n // Quantum-resistant entropy analysis\n let quantumScore = 0;\n \n // 1. Check for quantum-vulnerable patterns\n const hasQuantumVulnerablePatterns = this._detectQuantumVulnerablePatterns(data);\n if (hasQuantumVulnerablePatterns) {\n quantumScore -= 2;\n }\n \n // 2. Analyze bit distribution\n const bitDistribution = this._analyzeBitDistribution(data);\n quantumScore += bitDistribution.score;\n \n // 3. Check for periodicity\n const periodicity = this._detectPeriodicity(data);\n quantumScore -= periodicity * 0.5;\n \n // 4. Normalize to 0-8 range\n return Math.max(0, Math.min(8, quantumScore));\n }\n\n /**\n * Detect quantum-vulnerable patterns\n * @param {Uint8Array} data - Data to analyze\n * @returns {boolean} true if quantum-vulnerable patterns found\n */\n _detectQuantumVulnerablePatterns(data) {\n // Check for patterns vulnerable to quantum attacks\n const patterns = [\n [0, 0, 0, 0, 0, 0, 0, 0], // All zeros\n [255, 255, 255, 255, 255, 255, 255, 255], // All ones\n [0, 1, 0, 1, 0, 1, 0, 1], // Alternating\n [1, 0, 1, 0, 1, 0, 1, 0] // Alternating reverse\n ];\n \n for (const pattern of patterns) {\n for (let i = 0; i <= data.length - pattern.length; i++) {\n let match = true;\n for (let j = 0; j < pattern.length; j++) {\n if (data[i + j] !== pattern[j]) {\n match = false;\n break;\n }\n }\n if (match) return true;\n }\n }\n \n return false;\n }\n\n /**\n * Analyze bit distribution\n * @param {Uint8Array} data - Data to analyze\n * @returns {Object} Bit distribution analysis\n */\n _analyzeBitDistribution(data) {\n let ones = 0;\n let totalBits = data.length * 8;\n \n for (const byte of data) {\n ones += (byte >>> 0).toString(2).split('1').length - 1;\n }\n \n const zeroRatio = (totalBits - ones) / totalBits;\n const oneRatio = ones / totalBits;\n \n // Ideal distribution is 50/50\n const deviation = Math.abs(0.5 - oneRatio);\n const score = Math.max(0, 8 - deviation * 16);\n \n return { score, zeroRatio, oneRatio, deviation };\n }\n\n /**\n * Detect periodicity in data\n * @param {Uint8Array} data - Data to analyze\n * @returns {number} Periodicity score (0-1)\n */\n _detectPeriodicity(data) {\n if (data.length < 16) return 0;\n \n let maxPeriodicity = 0;\n \n // Check for periods from 2 to data.length/2\n for (let period = 2; period <= data.length / 2; period++) {\n let matches = 0;\n let totalChecks = 0;\n \n for (let i = 0; i < data.length - period; i++) {\n if (data[i] === data[i + period]) {\n matches++;\n }\n totalChecks++;\n }\n \n if (totalChecks > 0) {\n const periodicity = matches / totalChecks;\n maxPeriodicity = Math.max(maxPeriodicity, periodicity);\n }\n }\n \n return maxPeriodicity;\n }\n\n /**\n * Enhanced suspicious pattern detection\n * @param {Uint8Array} iv - IV to check\n * @returns {boolean} true if suspicious patterns found\n */\n _detectAdvancedSuspiciousPatterns(iv) {\n // Enhanced pattern detection with quantum-resistant analysis\n const patterns = [\n // Sequential patterns\n [0, 1, 2, 3, 4, 5, 6, 7],\n [255, 254, 253, 252, 251, 250, 249, 248],\n \n // Repeated patterns\n [0, 0, 0, 0, 0, 0, 0, 0],\n [255, 255, 255, 255, 255, 255, 255, 255],\n \n // Alternating patterns\n [0, 255, 0, 255, 0, 255, 0, 255],\n [255, 0, 255, 0, 255, 0, 255, 0]\n ];\n \n for (const pattern of patterns) {\n for (let i = 0; i <= iv.length - pattern.length; i++) {\n let match = true;\n for (let j = 0; j < pattern.length; j++) {\n if (iv[i + j] !== pattern[j]) {\n match = false;\n break;\n }\n }\n if (match) return true;\n }\n }\n \n // Check for low entropy regions\n const entropyMap = this._calculateLocalEntropy(iv);\n const lowEntropyRegions = entropyMap.filter(e => e < 3.0).length;\n \n return lowEntropyRegions > iv.length * 0.3; // More than 30% low entropy\n }\n\n /**\n * Calculate local entropy for pattern detection\n * @param {Uint8Array} data - Data to analyze\n * @returns {Array} Array of local entropy values\n */\n _calculateLocalEntropy(data) {\n const windowSize = 8;\n const entropyMap = [];\n \n for (let i = 0; i <= data.length - windowSize; i++) {\n const window = data.slice(i, i + windowSize);\n const charCount = {};\n \n for (const byte of window) {\n charCount[byte] = (charCount[byte] || 0) + 1;\n }\n \n let entropy = 0;\n for (const count of Object.values(charCount)) {\n const probability = count / windowSize;\n entropy -= probability * Math.log2(probability);\n }\n \n entropyMap.push(entropy);\n }\n \n return entropyMap;\n }\n\n /**\n * Detect suspicious patterns in IVs\n */\n _detectSuspiciousIVPatterns(iv) {\n // Check for all zeros or all ones\n const allZeros = iv.every(byte => byte === 0);\n const allOnes = iv.every(byte => byte === 255);\n \n if (allZeros || allOnes) {\n return true;\n }\n \n // Check for sequential patterns\n let sequentialCount = 0;\n for (let i = 1; i < iv.length; i++) {\n if (iv[i] === iv[i-1] + 1 || iv[i] === iv[i-1] - 1) {\n sequentialCount++;\n } else {\n sequentialCount = 0;\n }\n \n if (sequentialCount >= 3) {\n return true; // Suspicious sequential pattern\n }\n }\n \n // Check for repeated patterns\n for (let patternLength = 2; patternLength <= Math.floor(iv.length / 2); patternLength++) {\n for (let start = 0; start <= iv.length - patternLength * 2; start++) {\n const pattern1 = iv.slice(start, start + patternLength);\n const pattern2 = iv.slice(start + patternLength, start + patternLength * 2);\n \n if (pattern1.every((byte, index) => byte === pattern2[index])) {\n return true; // Repeated pattern detected\n }\n }\n }\n \n return false;\n }\n \n /**\n * Clean up old IVs with strict limits\n */\n _cleanupOldIVs() {\n const now = Date.now();\n const maxAge = 1800000; // Reduced to 30 minutes for better security\n let cleanedCount = 0;\n const cleanupBatch = [];\n \n // Aggressive cleanup with quantum-resistant patterns\n // Enforce maximum IV history size with batch processing\n if (this._ivTrackingSystem.ivHistory.size > this._ivTrackingSystem.maxIVHistorySize) {\n const ivArray = Array.from(this._ivTrackingSystem.ivHistory.entries());\n const toRemove = ivArray.slice(0, ivArray.length - this._ivTrackingSystem.maxIVHistorySize);\n \n for (const [ivString] of toRemove) {\n cleanupBatch.push(ivString);\n cleanedCount++;\n \n // Process in batches to prevent memory spikes\n if (cleanupBatch.length >= 100) {\n this._processCleanupBatch(cleanupBatch);\n cleanupBatch.length = 0;\n }\n }\n }\n \n // Clean up old IVs from history by age with enhanced security\n for (const [ivString, metadata] of this._ivTrackingSystem.ivHistory.entries()) {\n if (now - metadata.timestamp > maxAge) {\n cleanupBatch.push(ivString);\n cleanedCount++;\n \n // Process in batches to prevent memory spikes\n if (cleanupBatch.length >= 100) {\n this._processCleanupBatch(cleanupBatch);\n cleanupBatch.length = 0;\n }\n }\n }\n \n // Process remaining batch\n if (cleanupBatch.length > 0) {\n this._processCleanupBatch(cleanupBatch);\n }\n \n // Enhanced session IV cleanup with entropy preservation\n for (const [sessionId, sessionIVs] of this._ivTrackingSystem.sessionIVs.entries()) {\n if (sessionIVs.size > this._ivTrackingSystem.maxSessionIVs) {\n const ivArray = Array.from(sessionIVs);\n const toRemove = ivArray.slice(0, ivArray.length - this._ivTrackingSystem.maxSessionIVs);\n \n for (const ivString of toRemove) {\n sessionIVs.delete(ivString);\n this._ivTrackingSystem.usedIVs.delete(ivString);\n this._ivTrackingSystem.ivHistory.delete(ivString);\n cleanedCount++;\n }\n }\n }\n \n // Force garbage collection if available and significant cleanup occurred\n if (typeof window.gc === 'function' && cleanedCount > 50) {\n try {\n window.gc();\n } catch (e) {\n // Ignore GC errors\n }\n }\n \n if (cleanedCount > 0) {\n this._secureLog('debug', `\uD83E\uDDF9 Enhanced cleanup: ${cleanedCount} old IVs removed`, {\n cleanedCount: cleanedCount,\n remainingIVs: this._ivTrackingSystem.usedIVs.size,\n remainingHistory: this._ivTrackingSystem.ivHistory.size,\n memoryPressure: this._calculateMemoryPressure()\n });\n }\n }\n \n /**\n * Process cleanup batch with constant-time operations\n * @param {Array} batch - Batch of items to clean up\n */\n _processCleanupBatch(batch) {\n // Constant-time batch processing\n for (const item of batch) {\n this._ivTrackingSystem.usedIVs.delete(item);\n this._ivTrackingSystem.ivHistory.delete(item);\n }\n }\n\n /**\n * Calculate memory pressure for adaptive cleanup\n * @returns {number} Memory pressure score (0-100)\n */\n _calculateMemoryPressure() {\n const totalIVs = this._ivTrackingSystem.usedIVs.size;\n const maxAllowed = this._resourceLimits.maxIVHistory;\n \n return Math.min(100, Math.floor((totalIVs / maxAllowed) * 100));\n }\n\n /**\n * Get IV tracking system statistics\n */\n _getIVTrackingStats() {\n return {\n totalIVs: this._ivTrackingSystem.usedIVs.size,\n collisionCount: this._ivTrackingSystem.collisionCount,\n entropyTests: this._ivTrackingSystem.entropyValidation.entropyTests,\n entropyFailures: this._ivTrackingSystem.entropyValidation.entropyFailures,\n rngTests: this._ivTrackingSystem.rngValidation.testsPerformed,\n weakRngDetected: this._ivTrackingSystem.rngValidation.weakRngDetected,\n emergencyMode: this._ivTrackingSystem.emergencyMode,\n sessionCount: this._ivTrackingSystem.sessionIVs.size,\n lastCleanup: this._lastIVCleanupTime || 0\n };\n }\n \n /**\n * Reset IV tracking system (for testing or emergency recovery)\n */\n _resetIVTrackingSystem() {\n this._secureLog('warn', '\uD83D\uDD04 Resetting IV tracking system');\n \n this._ivTrackingSystem.usedIVs.clear();\n this._ivTrackingSystem.ivHistory.clear();\n this._ivTrackingSystem.sessionIVs.clear();\n this._ivTrackingSystem.collisionCount = 0;\n this._ivTrackingSystem.entropyValidation.entropyTests = 0;\n this._ivTrackingSystem.entropyValidation.entropyFailures = 0;\n this._ivTrackingSystem.rngValidation.testsPerformed = 0;\n this._ivTrackingSystem.rngValidation.weakRngDetected = false;\n this._ivTrackingSystem.emergencyMode = false;\n \n this._secureLog('info', '\u2705 IV tracking system reset completed');\n }\n \n /**\n * Validate RNG quality\n */\n _validateRNGQuality() {\n const now = Date.now();\n \n // Validate RNG every 1000 IV generations\n if (this._ivTrackingSystem.rngValidation.testsPerformed % 1000 === 0) {\n try {\n // Generate test IVs and validate\n const testIVs = [];\n for (let i = 0; i < 100; i++) {\n testIVs.push(crypto.getRandomValues(new Uint8Array(12)));\n }\n \n // Check for duplicates in test set\n const testIVStrings = testIVs.map(iv => Array.from(iv).map(b => b.toString(16).padStart(2, '0')).join(''));\n const uniqueTestIVs = new Set(testIVStrings);\n \n if (uniqueTestIVs.size < 95) { // Allow some tolerance\n this._ivTrackingSystem.rngValidation.weakRngDetected = true;\n this._secureLog('error', '\uD83D\uDEA8 CRITICAL: Weak RNG detected in validation test', {\n uniqueIVs: uniqueTestIVs.size,\n totalTests: testIVs.length\n });\n }\n \n this._ivTrackingSystem.rngValidation.lastValidation = now;\n \n } catch (error) {\n this._secureLog('error', '\u274C RNG validation failed', {\n errorType: error.constructor.name\n });\n }\n }\n \n this._ivTrackingSystem.rngValidation.testsPerformed++;\n }\n \n /**\n * Handle mutex timeout with enhanced state validation\n */\n _handleMutexTimeout(mutexName, operationId, timeout) {\n const mutex = this[`_${mutexName}Mutex`];\n \n if (!mutex) {\n this._secureLog('error', `\u274C Mutex '${mutexName}' not found during timeout handling`);\n return;\n }\n \n // Validate timeout conditions\n if (mutex.lockId !== operationId) {\n this._secureLog('warn', `\u26A0\uFE0F Timeout for different operation ID on mutex '${mutexName}'`, {\n expectedOperationId: operationId,\n actualLockId: mutex.lockId,\n locked: mutex.locked\n });\n return;\n }\n \n if (!mutex.locked) {\n this._secureLog('warn', `\u26A0\uFE0F Timeout for already unlocked mutex '${mutexName}'`, {\n operationId: operationId\n });\n return;\n }\n \n try {\n // Calculate lock duration for monitoring\n const lockDuration = mutex.lockTime ? Date.now() - mutex.lockTime : 0;\n \n this._secureLog('warn', `\u26A0\uFE0F Mutex '${mutexName}' auto-released due to timeout`, {\n operationId: operationId,\n lockDuration: lockDuration,\n timeout: timeout,\n queueLength: mutex.queue.length\n });\n \n // Atomic release with state validation\n mutex.locked = false;\n mutex.lockId = null;\n mutex.lockTimeout = null;\n mutex.lockTime = null;\n \n // Process next in queue with error handling\n setTimeout(() => {\n try {\n this._processNextInQueue(mutexName);\n } catch (queueError) {\n this._secureLog('error', `\u274C Error processing queue after timeout for mutex '${mutexName}'`, {\n errorType: queueError.constructor.name,\n errorMessage: queueError.message\n });\n }\n }, 10);\n \n } catch (error) {\n this._secureLog('error', `\u274C Critical error during mutex timeout handling for '${mutexName}'`, {\n operationId: operationId,\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n \n // Force emergency unlock if timeout handling fails\n try {\n this._emergencyUnlockAllMutexes('timeoutHandler');\n } catch (emergencyError) {\n this._secureLog('error', `\u274C Emergency unlock failed during timeout handling`, {\n originalError: error.message,\n emergencyError: emergencyError.message\n });\n }\n }\n }\n\n /**\n * Validate mutex system after emergency unlock\n */\n _validateMutexSystemAfterEmergencyUnlock() {\n const mutexes = ['keyOperation', 'cryptoOperation', 'connectionOperation'];\n let validationErrors = 0;\n \n this._secureLog('info', '\uD83D\uDD0D Validating mutex system after emergency unlock');\n \n mutexes.forEach(mutexName => {\n const mutex = this[`_${mutexName}Mutex`];\n \n if (!mutex) {\n validationErrors++;\n this._secureLog('error', `\u274C Mutex '${mutexName}' not found after emergency unlock`);\n return;\n }\n \n // Validate mutex state consistency\n if (mutex.locked) {\n validationErrors++;\n this._secureLog('error', `\u274C Mutex '${mutexName}' still locked after emergency unlock`, {\n lockId: mutex.lockId,\n lockTime: mutex.lockTime\n });\n }\n \n if (mutex.lockId !== null) {\n validationErrors++;\n this._secureLog('error', `\u274C Mutex '${mutexName}' still has lock ID after emergency unlock`, {\n lockId: mutex.lockId\n });\n }\n \n if (mutex.lockTimeout !== null) {\n validationErrors++;\n this._secureLog('error', `\u274C Mutex '${mutexName}' still has timeout after emergency unlock`);\n }\n \n if (mutex.queue.length > 0) {\n validationErrors++;\n this._secureLog('error', `\u274C Mutex '${mutexName}' still has queue items after emergency unlock`, {\n queueLength: mutex.queue.length\n });\n }\n });\n \n // Validate key system state\n if (this._keySystemState) {\n if (this._keySystemState.isInitializing || \n this._keySystemState.isRotating || \n this._keySystemState.isDestroying) {\n validationErrors++;\n this._secureLog('error', `\u274C Key system state not properly reset after emergency unlock`, {\n isInitializing: this._keySystemState.isInitializing,\n isRotating: this._keySystemState.isRotating,\n isDestroying: this._keySystemState.isDestroying\n });\n }\n }\n \n if (validationErrors === 0) {\n this._secureLog('info', '\u2705 Mutex system validation passed after emergency unlock');\n } else {\n this._secureLog('error', `\u274C Mutex system validation failed after emergency unlock`, {\n validationErrors: validationErrors\n });\n \n // Force re-initialization if validation fails\n setTimeout(() => {\n this._emergencyRecoverMutexSystem();\n }, 1000);\n }\n }\n /**\n * NEW: Diagnostics of the mutex system state\n */\n _getMutexSystemDiagnostics() {\n const diagnostics = {\n timestamp: Date.now(),\n systemValid: this._validateMutexSystem(),\n mutexes: {},\n counters: { ...this._operationCounters },\n keySystemState: { ...this._keySystemState }\n };\n \n const mutexNames = ['keyOperation', 'cryptoOperation', 'connectionOperation'];\n \n mutexNames.forEach(mutexName => {\n const mutexPropertyName = `_${mutexName}Mutex`;\n const mutex = this[mutexPropertyName];\n \n if (mutex) {\n diagnostics.mutexes[mutexName] = {\n locked: mutex.locked,\n lockId: mutex.lockId,\n queueLength: mutex.queue.length,\n hasTimeout: !!mutex.lockTimeout\n };\n } else {\n diagnostics.mutexes[mutexName] = { error: 'not_found' };\n }\n });\n \n return diagnostics;\n }\n\n /**\n * FULLY FIXED createSecureOffer()\n * With race-condition protection and improved security\n */\n async createSecureOffer() {\n console.log('\uD83C\uDFAF createSecureOffer called');\n return this._withMutex('connectionOperation', async (operationId) => {\n this._secureLog('info', '\uD83D\uDCE4 Creating secure offer with mutex', {\n operationId: operationId,\n connectionAttempts: this.connectionAttempts,\n currentState: this.peerConnection?.connectionState || 'none'\n });\n \n try {\n // ============================================\n // PHASE 1: INITIALIZATION AND VALIDATION\n // ============================================\n console.log('\uD83C\uDFAF PHASE 1: Initialization and validation');\n \n // Reset notification flags for a new connection\n this._resetNotificationFlags();\n \n // Rate limiting check\n if (!this._checkRateLimit()) {\n throw new Error('Connection rate limit exceeded. Please wait before trying again.');\n }\n \n // Reset attempt counters\n this.connectionAttempts = 0;\n \n // Generate session salt (64 bytes for v4.0)\n this.sessionSalt = window.EnhancedSecureCryptoUtils.generateSalt();\n console.log('\uD83C\uDFAF PHASE 1 completed: Session salt generated');\n \n this._secureLog('debug', '\uD83E\uDDC2 Session salt generated', {\n operationId: operationId,\n saltLength: this.sessionSalt.length,\n isValidSalt: Array.isArray(this.sessionSalt) && this.sessionSalt.length === 64\n });\n \n // ============================================\n // PHASE 2: SECURE KEY GENERATION\n // ============================================\n console.log('\uD83C\uDFAF PHASE 2: Secure key generation');\n \n // Secure key generation via mutex\n const keyPairs = await this._generateEncryptionKeys();\n this.ecdhKeyPair = keyPairs.ecdhKeyPair;\n this.ecdsaKeyPair = keyPairs.ecdsaKeyPair;\n \n // Validate generated keys\n if (!this.ecdhKeyPair?.privateKey || !this.ecdhKeyPair?.publicKey) {\n throw new Error('Failed to generate valid ECDH key pair');\n }\n \n if (!this.ecdsaKeyPair?.privateKey || !this.ecdsaKeyPair?.publicKey) {\n throw new Error('Failed to generate valid ECDSA key pair');\n }\n \n // ============================================\n // PHASE 3: MITM PROTECTION AND FINGERPRINTING\n // ============================================\n console.log('\uD83C\uDFAF PHASE 3: MITM protection and fingerprinting');\n \n // MITM Protection: Compute unique key fingerprints\n const ecdhFingerprint = await window.EnhancedSecureCryptoUtils.calculateKeyFingerprint(\n await crypto.subtle.exportKey('spki', this.ecdhKeyPair.publicKey)\n );\n const ecdsaFingerprint = await window.EnhancedSecureCryptoUtils.calculateKeyFingerprint(\n await crypto.subtle.exportKey('spki', this.ecdsaKeyPair.publicKey)\n );\n \n // Validate fingerprints\n if (!ecdhFingerprint || !ecdsaFingerprint) {\n throw new Error('Failed to generate key fingerprints');\n }\n \n this._secureLog('info', 'Generated unique key pairs for MITM protection', {\n operationId: operationId,\n hasECDHFingerprint: !!ecdhFingerprint,\n hasECDSAFingerprint: !!ecdsaFingerprint,\n fingerprintLength: ecdhFingerprint.length,\n timestamp: Date.now()\n });\n \n // ============================================\n // PHASE 4: EXPORT SIGNED KEYS\n // ============================================\n console.log('\uD83C\uDFAF PHASE 4: Export signed keys');\n \n // Export keys with digital signatures\n const ecdhPublicKeyData = await window.EnhancedSecureCryptoUtils.exportPublicKeyWithSignature(\n this.ecdhKeyPair.publicKey,\n this.ecdsaKeyPair.privateKey,\n 'ECDH'\n );\n \n const ecdsaPublicKeyData = await window.EnhancedSecureCryptoUtils.exportPublicKeyWithSignature(\n this.ecdsaKeyPair.publicKey,\n this.ecdsaKeyPair.privateKey,\n 'ECDSA'\n );\n\n \n if (!ecdhPublicKeyData || typeof ecdhPublicKeyData !== 'object') {\n this._secureLog('error', 'CRITICAL: ECDH key export failed - invalid object structure', { operationId });\n throw new Error('CRITICAL SECURITY FAILURE: ECDH key export validation failed - hard abort required');\n }\n \n if (!ecdhPublicKeyData.keyData || !ecdhPublicKeyData.signature) {\n this._secureLog('error', 'CRITICAL: ECDH key export incomplete - missing keyData or signature', { \n operationId,\n hasKeyData: !!ecdhPublicKeyData.keyData,\n hasSignature: !!ecdhPublicKeyData.signature \n });\n throw new Error('CRITICAL SECURITY FAILURE: ECDH key export incomplete - hard abort required');\n }\n \n if (!ecdsaPublicKeyData || typeof ecdsaPublicKeyData !== 'object') {\n this._secureLog('error', 'CRITICAL: ECDSA key export failed - invalid object structure', { operationId });\n throw new Error('CRITICAL SECURITY FAILURE: ECDSA key export validation failed - hard abort required');\n }\n \n if (!ecdsaPublicKeyData.keyData || !ecdsaPublicKeyData.signature) {\n this._secureLog('error', 'CRITICAL: ECDSA key export incomplete - missing keyData or signature', { \n operationId,\n hasKeyData: !!ecdsaPublicKeyData.keyData,\n hasSignature: !!ecdsaPublicKeyData.signature \n });\n throw new Error('CRITICAL SECURITY FAILURE: ECDSA key export incomplete - hard abort required');\n }\n \n // ============================================\n // PHASE 5: UPDATE SECURITY FEATURES\n // ============================================\n console.log('\uD83C\uDFAF PHASE 5: Update security features');\n \n // Atomic update of security features\n this._updateSecurityFeatures({\n hasEncryption: true,\n hasECDH: true,\n hasECDSA: true,\n hasMutualAuth: true,\n hasMetadataProtection: true,\n hasEnhancedReplayProtection: true,\n hasNonExtractableKeys: true,\n hasRateLimiting: true,\n hasEnhancedValidation: true,\n hasPFS: true\n });\n \n // ============================================\n // PHASE 6: INITIALIZE PEER CONNECTION\n // ============================================\n console.log('\uD83C\uDFAF PHASE 6: Initialize peer connection');\n \n this.isInitiator = true;\n this.onStatusChange('connecting');\n \n // Create peer connection\n this.createPeerConnection();\n \n // Create main data channel\n this.dataChannel = this.peerConnection.createDataChannel('securechat', {\n ordered: true\n });\n \n // Setup data channel\n this.setupDataChannel(this.dataChannel);\n \n this._secureLog('debug', '\uD83D\uDD17 Data channel created', {\n operationId: operationId,\n channelLabel: this.dataChannel.label,\n channelOrdered: this.dataChannel.ordered\n });\n \n // ============================================\n // PHASE 7: CREATE SDP OFFER\n // ============================================\n console.log('\uD83C\uDFAF PHASE 7: Create SDP offer');\n \n // Create WebRTC offer\n console.log('\uD83C\uDFAF Creating WebRTC offer...');\n const offer = await this.peerConnection.createOffer({\n offerToReceiveAudio: false,\n offerToReceiveVideo: false\n });\n console.log('\uD83C\uDFAF WebRTC offer created successfully');\n \n // Set local description\n console.log('\uD83C\uDFAF Setting local description...');\n await this.peerConnection.setLocalDescription(offer);\n console.log('\uD83C\uDFAF Local description set successfully');\n \n // Extract and store our DTLS fingerprint for out-of-band verification\n console.log('\uD83C\uDFAF Extracting DTLS fingerprint...');\n try {\n const ourFingerprint = this._extractDTLSFingerprintFromSDP(offer.sdp);\n this.expectedDTLSFingerprint = ourFingerprint;\n console.log('\uD83C\uDFAF DTLS fingerprint extracted successfully');\n \n this._secureLog('info', 'Generated DTLS fingerprint for out-of-band verification', {\n fingerprint: ourFingerprint,\n context: 'offer_creation'\n });\n \n // Notify UI that fingerprint is ready for out-of-band verification\n this.deliverMessageToUI(`\uD83D\uDD10 DTLS fingerprint ready for verification: ${ourFingerprint}`, 'system');\n } catch (error) {\n this._secureLog('error', 'Failed to extract DTLS fingerprint from offer', { error: error.message });\n // Continue without fingerprint validation (fallback mode)\n }\n \n // Await ICE gathering\n await this.waitForIceGathering();\n \n this._secureLog('debug', '\uD83E\uDDCA ICE gathering completed', {\n operationId: operationId,\n iceGatheringState: this.peerConnection.iceGatheringState,\n connectionState: this.peerConnection.connectionState\n });\n \n // ============================================\n // PHASE 8: GENERATE SAS FOR OUT-OF-BAND VERIFICATION\n // ============================================\n console.log('\uD83C\uDFAF PHASE 8: Generate SAS for out-of-band verification');\n\n this.verificationCode = window.EnhancedSecureCryptoUtils.generateVerificationCode();\n console.log('\uD83C\uDFAF Placeholder verification code generated:', this.verificationCode);\n \n // Validate verification code\n if (!this.verificationCode || this.verificationCode.length < EnhancedSecureWebRTCManager.SIZES.VERIFICATION_CODE_MIN_LENGTH) {\n throw new Error('Failed to generate valid verification code');\n }\n \n // ============================================\n // PHASE 9: MUTUAL AUTHENTICATION CHALLENGE\n // ============================================\n console.log('\uD83C\uDFAF PHASE 9: Mutual authentication challenge');\n \n // Generate challenge for mutual authentication\n const authChallenge = window.EnhancedSecureCryptoUtils.generateMutualAuthChallenge();\n \n if (!authChallenge) {\n throw new Error('Failed to generate mutual authentication challenge');\n }\n \n // ============================================\n // PHASE 10: SESSION ID FOR MITM PROTECTION\n // ============================================\n console.log('\uD83C\uDFAF PHASE 10: Session ID for MITM protection');\n \n // MITM Protection: Generate session-specific ID\n this.sessionId = Array.from(crypto.getRandomValues(new Uint8Array(EnhancedSecureWebRTCManager.SIZES.SESSION_ID_LENGTH)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n \n // Validate session ID\n if (!this.sessionId || this.sessionId.length !== (EnhancedSecureWebRTCManager.SIZES.SESSION_ID_LENGTH * 2)) {\n throw new Error('Failed to generate valid session ID');\n }\n \n // Generate connection ID for AAD\n this.connectionId = Array.from(crypto.getRandomValues(new Uint8Array(8)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n \n // ============================================\n // PHASE 11: SECURITY LEVEL CALCULATION\n // ============================================\n console.log('\uD83C\uDFAF PHASE 11: Security level calculation');\n \n // Preliminary security level calculation\n let securityLevel;\n try {\n securityLevel = await this.calculateSecurityLevel();\n } catch (error) {\n this._secureLog('warn', '\u26A0\uFE0F Security level calculation failed, using fallback', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n \n // Fallback value\n securityLevel = {\n level: 'enhanced',\n score: 75,\n passedChecks: 10,\n totalChecks: 15,\n isRealData: false\n };\n }\n \n // ============================================\n // PHASE 12: CREATE OFFER PACKAGE\n // ============================================\n console.log('\uD83C\uDFAF PHASE 12: Create offer package');\n \n const currentTimestamp = Date.now();\n console.log('\uD83C\uDFAF Creating offer package object...');\n \n const offerPackage = {\n // Core information\n type: 'enhanced_secure_offer',\n sdp: this.peerConnection.localDescription.sdp,\n version: '4.0',\n timestamp: currentTimestamp,\n \n // Cryptographic keys\n ecdhPublicKey: ecdhPublicKeyData,\n ecdsaPublicKey: ecdsaPublicKeyData,\n \n // Session data\n salt: this.sessionSalt,\n sessionId: this.sessionId,\n connectionId: this.connectionId,\n \n // Authentication\n verificationCode: this.verificationCode,\n authChallenge: authChallenge,\n \n // Security metadata\n securityLevel: securityLevel,\n \n // Additional fields for validation\n keyFingerprints: {\n ecdh: ecdhFingerprint.substring(0, 16), // First 16 chars for validation\n ecdsa: ecdsaFingerprint.substring(0, 16)\n },\n \n // Optional capabilities info\n capabilities: {\n supportsFileTransfer: true,\n supportsEnhancedSecurity: true,\n supportsKeyRotation: true,\n supportsFakeTraffic: this.fakeTrafficConfig.enabled,\n supportsDecoyChannels: this.decoyChannelConfig.enabled\n }\n };\n console.log('\uD83C\uDFAF Offer package object created successfully');\n \n // ============================================\n // PHASE 13: VALIDATE OFFER PACKAGE\n // ============================================\n console.log('\uD83C\uDFAF PHASE 13: Validate offer package');\n \n // Final validation of the generated package\n console.log('\uD83C\uDFAF Validating offer package...');\n try {\n const validationResult = this.validateEnhancedOfferData(offerPackage);\n console.log('\uD83C\uDFAF Validation result:', validationResult);\n if (!validationResult) {\n console.log('\uD83C\uDFAF Offer package validation FAILED');\n throw new Error('Generated offer package failed validation');\n }\n console.log('\uD83C\uDFAF Offer package validation PASSED');\n } catch (validationError) {\n console.log('\uD83C\uDFAF Validation ERROR:', validationError.message);\n throw new Error(`Offer package validation error: ${validationError.message}`);\n }\n \n // ============================================\n // PHASE 14: LOGGING AND EVENTS\n // ============================================\n console.log('\uD83C\uDFAF PHASE 14: Logging and events');\n \n this._secureLog('info', 'Enhanced secure offer created successfully', {\n operationId: operationId,\n version: offerPackage.version,\n hasECDSA: true,\n hasMutualAuth: true,\n hasSessionId: !!offerPackage.sessionId,\n securityLevel: securityLevel.level,\n timestamp: currentTimestamp,\n capabilitiesCount: Object.keys(offerPackage.capabilities).length\n });\n \n // Dispatch event about new connection\n document.dispatchEvent(new CustomEvent('new-connection', {\n detail: { \n type: 'offer',\n timestamp: currentTimestamp,\n securityLevel: securityLevel.level,\n operationId: operationId\n }\n }));\n \n // ============================================\n // PHASE 15: RETURN RESULT\n // ============================================\n console.log('\uD83C\uDFAF PHASE 15: Return result');\n \n console.log('\uD83C\uDFAF createSecureOffer completed successfully, returning offerPackage');\n return offerPackage;\n \n } catch (error) {\n // ============================================\n // ERROR HANDLING\n // ============================================\n \n this._secureLog('error', '\u274C Enhanced secure offer creation failed in critical section', {\n operationId: operationId,\n errorType: error.constructor.name,\n errorMessage: error.message,\n phase: this._determineErrorPhase(error),\n connectionAttempts: this.connectionAttempts\n });\n \n // Cleanup state on error\n this._cleanupFailedOfferCreation();\n \n // Update status\n this.onStatusChange('disconnected');\n \n // Re-throw for upper-level handling\n throw error;\n }\n }, 15000); // 15 seconds timeout for the entire offer creation\n }\n\n /**\n * HELPER: Determine the phase where the error occurred\n */\n _determineErrorPhase(error) {\n const message = error.message.toLowerCase();\n \n if (message.includes('rate limit')) return 'rate_limiting';\n if (message.includes('key pair') || message.includes('generate')) return 'key_generation';\n if (message.includes('fingerprint')) return 'fingerprinting';\n if (message.includes('export') || message.includes('signature')) return 'key_export';\n if (message.includes('peer connection')) return 'webrtc_setup';\n if (message.includes('offer') || message.includes('sdp')) return 'sdp_creation';\n if (message.includes('verification')) return 'verification_setup';\n if (message.includes('session')) return 'session_setup';\n if (message.includes('validation')) return 'package_validation';\n \n return 'unknown';\n }\n\n /**\n * Secure cleanup state after failed offer creation\n */\n _cleanupFailedOfferCreation() {\n try {\n // Secure wipe of cryptographic materials\n this._secureCleanupCryptographicMaterials();\n \n // Close peer connection if it was created\n if (this.peerConnection) {\n this.peerConnection.close();\n this.peerConnection = null;\n }\n \n // Clear data channel\n if (this.dataChannel) {\n this.dataChannel.close();\n this.dataChannel = null;\n }\n \n // Reset flags\n this.isInitiator = false;\n this.isVerified = false;\n \n // Reset security features to baseline\n this._updateSecurityFeatures({\n hasEncryption: false,\n hasECDH: false,\n hasECDSA: false,\n hasMutualAuth: false,\n hasMetadataProtection: false,\n hasEnhancedReplayProtection: false,\n hasNonExtractableKeys: false,\n hasEnhancedValidation: false,\n hasPFS: false\n });\n \n // Force garbage collection\n this._forceGarbageCollection();\n \n this._secureLog('debug', '\uD83D\uDD12 Failed offer creation cleanup completed with secure memory wipe');\n \n } catch (cleanupError) {\n this._secureLog('error', '\u274C Error during offer creation cleanup', {\n errorType: cleanupError.constructor.name,\n errorMessage: cleanupError.message\n });\n }\n }\n\n /**\n * HELPER: Atomic update of security features (if not added yet)\n */\n _updateSecurityFeatures(updates) {\n const oldFeatures = { ...this.securityFeatures };\n \n try {\n Object.assign(this.securityFeatures, updates);\n \n this._secureLog('debug', '\uD83D\uDD27 Security features updated', {\n updatedCount: Object.keys(updates).length,\n totalFeatures: Object.keys(this.securityFeatures).length\n });\n \n } catch (error) {\n // Roll back on error\n this.securityFeatures = oldFeatures;\n this._secureLog('error', '\u274C Security features update failed, rolled back', {\n errorType: error.constructor.name\n });\n throw error;\n }\n }\n\n /**\n * FULLY FIXED METHOD createSecureAnswer()\n * With race-condition protection and enhanced security\n */\n async createSecureAnswer(offerData) {\n console.log('\uD83C\uDFAF createSecureAnswer called with offerData:', offerData ? 'present' : 'null');\n return this._withMutex('connectionOperation', async (operationId) => {\n this._secureLog('info', '\uD83D\uDCE8 Creating secure answer with mutex', {\n operationId: operationId,\n hasOfferData: !!offerData,\n offerType: offerData?.type,\n offerVersion: offerData?.version,\n offerTimestamp: offerData?.timestamp\n });\n \n try {\n // ============================================\n // PHASE 1: PRE-VALIDATION OF OFFER\n // ============================================\n \n // Reset notification flags for a new connection\n this._resetNotificationFlags();\n \n this._secureLog('debug', 'Starting enhanced offer validation', {\n operationId: operationId,\n hasOfferData: !!offerData,\n offerType: offerData?.type,\n hasECDHKey: !!offerData?.ecdhPublicKey,\n hasECDSAKey: !!offerData?.ecdsaPublicKey,\n hasSalt: !!offerData?.salt\n });\n \n // Strict input validation\n if (!this.validateEnhancedOfferData(offerData)) {\n throw new Error('Invalid connection data format - failed enhanced validation');\n }\n \n // Rate limiting check\n if (!window.EnhancedSecureCryptoUtils.rateLimiter.checkConnectionRate(this.rateLimiterId)) {\n throw new Error('Connection rate limit exceeded. Please wait before trying again.');\n }\n \n // ============================================\n // PHASE 2: SECURITY AND ANTI-REPLAY PROTECTION\n // ============================================\n \n // MITM Protection: Validate offer data structure\n if (!offerData.timestamp || !offerData.version) {\n throw new Error('Missing required security fields in offer data \u2013 possible MITM attack');\n }\n \n // Replay attack protection (window reduced to 5 minutes)\n const offerAge = Date.now() - offerData.timestamp;\n const MAX_OFFER_AGE = 300000; // 5 minutes instead of 1 hour\n \n if (offerAge > MAX_OFFER_AGE) {\n this._secureLog('error', 'Offer data is too old - possible replay attack', {\n operationId: operationId,\n offerAge: Math.round(offerAge / 1000),\n maxAllowedAge: Math.round(MAX_OFFER_AGE / 1000),\n timestamp: offerData.timestamp\n });\n \n // Notify the main code about the replay attack\n if (this.onAnswerError) {\n this.onAnswerError('replay_attack', 'Offer data is too old \u2013 possible replay attack');\n }\n \n throw new Error('Offer data is too old \u2013 possible replay attack');\n }\n \n // Protocol version compatibility check\n if (offerData.version !== '4.0') {\n this._secureLog('warn', 'Protocol version mismatch detected', {\n operationId: operationId,\n expectedVersion: '4.0',\n receivedVersion: offerData.version\n });\n \n // For backward compatibility with v3.0, a fallback can be added\n if (offerData.version !== '3.0') {\n throw new Error(`Unsupported protocol version: ${offerData.version}`);\n }\n }\n \n // ============================================\n // PHASE 3: EXTRACT AND VALIDATE SESSION SALT\n // ============================================\n \n // Set session salt from offer\n this.sessionSalt = offerData.salt;\n \n // Validate session salt\n if (!Array.isArray(this.sessionSalt)) {\n throw new Error('Invalid session salt format - must be array');\n }\n \n const expectedSaltLength = offerData.version === '4.0' ? 64 : 32;\n if (this.sessionSalt.length !== expectedSaltLength) {\n throw new Error(`Invalid session salt length: expected ${expectedSaltLength}, got ${this.sessionSalt.length}`);\n }\n \n // MITM Protection: Check salt integrity\n const saltFingerprint = await window.EnhancedSecureCryptoUtils.calculateKeyFingerprint(this.sessionSalt);\n \n this._secureLog('info', 'Session salt validated successfully', {\n operationId: operationId,\n saltLength: this.sessionSalt.length,\n saltFingerprint: saltFingerprint.substring(0, 8)\n });\n \n // ============================================\n // PHASE 4: SECURE GENERATION OF OUR KEYS\n // ============================================\n \n // Secure generation of our keys via mutex\n const keyPairs = await this._generateEncryptionKeys();\n this.ecdhKeyPair = keyPairs.ecdhKeyPair;\n this.ecdsaKeyPair = keyPairs.ecdsaKeyPair;\n \n // Additional validation of generated keys\n if (!(this.ecdhKeyPair?.privateKey instanceof CryptoKey)) {\n this._secureLog('error', 'Local ECDH private key is not a CryptoKey', {\n operationId: operationId,\n hasKeyPair: !!this.ecdhKeyPair,\n privateKeyType: typeof this.ecdhKeyPair?.privateKey,\n privateKeyAlgorithm: this.ecdhKeyPair?.privateKey?.algorithm?.name\n });\n throw new Error('Local ECDH private key is not a valid CryptoKey');\n }\n \n // ============================================\n // PHASE 5: IMPORT AND VERIFY PEER KEYS\n // ============================================\n \n // Import peer ECDSA public key for signature verification\n let peerECDSAPublicKey;\n \n try {\n peerECDSAPublicKey = await crypto.subtle.importKey(\n 'spki',\n new Uint8Array(offerData.ecdsaPublicKey.keyData),\n {\n name: 'ECDSA',\n namedCurve: 'P-384'\n },\n false,\n ['verify']\n );\n } catch (error) {\n this._throwSecureError(error, 'ecdsa_key_import');\n }\n \n // ============================================\n // PHASE 6: IMPORT AND VERIFY ECDH KEY\n // ============================================\n \n // Import and verify ECDH public key using verified ECDSA key\n let peerECDHPublicKey;\n \n try {\n peerECDHPublicKey = await window.EnhancedSecureCryptoUtils.importSignedPublicKey(\n offerData.ecdhPublicKey,\n peerECDSAPublicKey,\n 'ECDH'\n );\n } catch (error) {\n this._secureLog('error', 'Failed to import signed ECDH public key', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n this._throwSecureError(error, 'ecdh_key_import');\n }\n \n // Final validation of ECDH key\n if (!(peerECDHPublicKey instanceof CryptoKey)) {\n this._secureLog('error', 'Peer ECDH public key is not a CryptoKey', {\n operationId: operationId,\n publicKeyType: typeof peerECDHPublicKey,\n publicKeyAlgorithm: peerECDHPublicKey?.algorithm?.name\n });\n throw new Error('Peer ECDH public key is not a valid CryptoKey');\n }\n \n // Save peer key for PFS rotation\n this.peerPublicKey = peerECDHPublicKey;\n \n // ============================================\n // PHASE 7: DERIVE SHARED ENCRYPTION KEYS\n // ============================================\n \n // Derive shared keys with metadata protection\n let derivedKeys;\n \n try {\n derivedKeys = await window.EnhancedSecureCryptoUtils.deriveSharedKeys(\n this.ecdhKeyPair.privateKey,\n peerECDHPublicKey,\n this.sessionSalt\n );\n } catch (error) {\n this._secureLog('error', 'Failed to derive shared keys', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n this._throwSecureError(error, 'key_derivation');\n }\n \n // Securely set keys via helper\n await this._setEncryptionKeys(\n derivedKeys.encryptionKey,\n derivedKeys.macKey,\n derivedKeys.metadataKey,\n derivedKeys.fingerprint\n );\n \n // Additional validation of installed keys\n if (!(this.encryptionKey instanceof CryptoKey) || \n !(this.macKey instanceof CryptoKey) || \n !(this.metadataKey instanceof CryptoKey)) {\n \n this._secureLog('error', 'Invalid key types after derivation', {\n operationId: operationId,\n encryptionKeyType: typeof this.encryptionKey,\n macKeyType: typeof this.macKey,\n metadataKeyType: typeof this.metadataKey\n });\n throw new Error('Invalid key types after derivation');\n }\n \n // Set verification code from offer\n this.verificationCode = offerData.verificationCode;\n \n this._secureLog('info', 'Encryption keys derived and set successfully', {\n operationId: operationId,\n hasEncryptionKey: !!this.encryptionKey,\n hasMacKey: !!this.macKey,\n hasMetadataKey: !!this.metadataKey,\n hasKeyFingerprint: !!this.keyFingerprint,\n mitmProtection: 'enabled',\n signatureVerified: true\n });\n \n // ============================================\n // PHASE 8: UPDATE SECURITY FEATURES\n // ============================================\n \n // Atomic update of security features\n this._updateSecurityFeatures({\n hasEncryption: true,\n hasECDH: true,\n hasECDSA: true,\n hasMutualAuth: true,\n hasMetadataProtection: true,\n hasEnhancedReplayProtection: true,\n hasNonExtractableKeys: true,\n hasRateLimiting: true,\n hasEnhancedValidation: true,\n hasPFS: true\n });\n \n // PFS: Initialize key version tracking\n this.currentKeyVersion = 0;\n this.lastKeyRotation = Date.now();\n this.keyVersions.set(0, {\n salt: this.sessionSalt,\n timestamp: this.lastKeyRotation,\n messageCount: 0\n });\n \n // ============================================\n // PHASE 9: CREATE AUTHENTICATION PROOF\n // ============================================\n \n // Create proof for mutual authentication\n let authProof;\n \n if (offerData.authChallenge) {\n try {\n authProof = await window.EnhancedSecureCryptoUtils.createAuthProof(\n offerData.authChallenge,\n this.ecdsaKeyPair.privateKey,\n this.ecdsaKeyPair.publicKey\n );\n } catch (error) {\n this._secureLog('error', 'Failed to create authentication proof', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n this._throwSecureError(error, 'authentication_proof_creation');\n }\n } else {\n this._secureLog('warn', 'No auth challenge in offer - mutual auth disabled', {\n operationId: operationId\n });\n }\n \n // ============================================\n // PHASE 10: INITIALIZE WEBRTC\n // ============================================\n \n this.isInitiator = false;\n this.onStatusChange('connecting');\n \n // DEBUG: Check keyFingerprint before calling onKeyExchange\n console.log('Before onKeyExchange - keyFingerprint:', this.keyFingerprint);\n this.onKeyExchange(this.keyFingerprint);\n \n // Create peer connection first\n this.createPeerConnection();\n \n // Validate DTLS fingerprint before setting remote description\n if (this.strictDTLSValidation) {\n try {\n const receivedFingerprint = this._extractDTLSFingerprintFromSDP(offerData.sdp);\n \n if (this.expectedDTLSFingerprint) {\n this._validateDTLSFingerprint(receivedFingerprint, this.expectedDTLSFingerprint, 'offer_validation');\n } else {\n // Store fingerprint for future validation (first connection)\n this.expectedDTLSFingerprint = receivedFingerprint;\n this._secureLog('info', 'Stored DTLS fingerprint for future validation', {\n fingerprint: receivedFingerprint,\n context: 'first_connection'\n });\n }\n } catch (error) {\n this._secureLog('warn', 'DTLS fingerprint validation failed - continuing in fallback mode', { \n error: error.message,\n context: 'offer_validation'\n });\n // Continue without strict fingerprint validation for first connection\n // This allows the connection to proceed while maintaining security awareness\n }\n } else {\n this._secureLog('info', 'DTLS fingerprint validation disabled - proceeding without validation');\n }\n\n // Set remote description from offer\n try {\n this._secureLog('debug', 'Setting remote description from offer', {\n operationId: operationId,\n sdpLength: offerData.sdp?.length || 0\n });\n \n await this.peerConnection.setRemoteDescription(new RTCSessionDescription({\n type: 'offer',\n sdp: offerData.sdp\n }));\n \n this._secureLog('debug', 'Remote description set successfully', {\n operationId: operationId,\n signalingState: this.peerConnection.signalingState\n });\n } catch (error) {\n this._secureLog('error', 'Failed to set remote description', { \n error: error.message,\n operationId: operationId\n });\n this._throwSecureError(error, 'webrtc_remote_description');\n }\n \n this._secureLog('debug', '\uD83D\uDD17 Remote description set successfully', {\n operationId: operationId,\n connectionState: this.peerConnection.connectionState,\n signalingState: this.peerConnection.signalingState\n });\n \n // ============================================\n // PHASE 11: CREATE SDP ANSWER\n // ============================================\n \n // Create WebRTC answer\n let answer;\n \n try {\n answer = await this.peerConnection.createAnswer({\n offerToReceiveAudio: false,\n offerToReceiveVideo: false\n });\n } catch (error) {\n this._throwSecureError(error, 'webrtc_create_answer');\n }\n \n // Set local description\n try {\n await this.peerConnection.setLocalDescription(answer);\n } catch (error) {\n this._throwSecureError(error, 'webrtc_local_description');\n }\n \n // Extract and store our DTLS fingerprint for out-of-band verification\n try {\n const ourFingerprint = this._extractDTLSFingerprintFromSDP(answer.sdp);\n this.expectedDTLSFingerprint = ourFingerprint;\n \n this._secureLog('info', 'Generated DTLS fingerprint for out-of-band verification', {\n fingerprint: ourFingerprint,\n context: 'answer_creation'\n });\n \n // Notify UI that fingerprint is ready for out-of-band verification\n this.deliverMessageToUI(`\uD83D\uDD10 DTLS fingerprint ready for verification: ${ourFingerprint}`, 'system');\n } catch (error) {\n this._secureLog('error', 'Failed to extract DTLS fingerprint from answer', { error: error.message });\n // Continue without fingerprint validation (fallback mode)\n }\n \n \n // Await ICE gathering\n await this.waitForIceGathering();\n \n this._secureLog('debug', '\uD83E\uDDCA ICE gathering completed for answer', {\n operationId: operationId,\n iceGatheringState: this.peerConnection.iceGatheringState,\n connectionState: this.peerConnection.connectionState\n });\n \n // ============================================\n // PHASE 12: EXPORT OUR KEYS\n // ============================================\n \n // Export our keys with signatures\n const ecdhPublicKeyData = await window.EnhancedSecureCryptoUtils.exportPublicKeyWithSignature(\n this.ecdhKeyPair.publicKey,\n this.ecdsaKeyPair.privateKey,\n 'ECDH'\n );\n \n const ecdsaPublicKeyData = await window.EnhancedSecureCryptoUtils.exportPublicKeyWithSignature(\n this.ecdsaKeyPair.publicKey,\n this.ecdsaKeyPair.privateKey,\n 'ECDSA'\n );\n \n if (!ecdhPublicKeyData || typeof ecdhPublicKeyData !== 'object') {\n this._secureLog('error', 'CRITICAL: ECDH key export failed - invalid object structure', { operationId });\n throw new Error('CRITICAL SECURITY FAILURE: ECDH key export validation failed - hard abort required');\n }\n \n if (!ecdhPublicKeyData.keyData || !ecdhPublicKeyData.signature) {\n this._secureLog('error', 'CRITICAL: ECDH key export incomplete - missing keyData or signature', { \n operationId,\n hasKeyData: !!ecdhPublicKeyData.keyData,\n hasSignature: !!ecdhPublicKeyData.signature \n });\n throw new Error('CRITICAL SECURITY FAILURE: ECDH key export incomplete - hard abort required');\n }\n \n if (!ecdsaPublicKeyData || typeof ecdsaPublicKeyData !== 'object') {\n this._secureLog('error', 'CRITICAL: ECDSA key export failed - invalid object structure', { operationId });\n throw new Error('CRITICAL SECURITY FAILURE: ECDSA key export validation failed - hard abort required');\n }\n \n if (!ecdsaPublicKeyData.keyData || !ecdsaPublicKeyData.signature) {\n this._secureLog('error', 'CRITICAL: ECDSA key export incomplete - missing keyData or signature', { \n operationId,\n hasKeyData: !!ecdsaPublicKeyData.keyData,\n hasSignature: !!ecdsaPublicKeyData.signature \n });\n throw new Error('CRITICAL SECURITY FAILURE: ECDSA key export incomplete - hard abort required');\n }\n \n // ============================================\n // PHASE 13: SECURITY LEVEL CALCULATION\n // ============================================\n \n // Calculate security level\n let securityLevel;\n \n try {\n securityLevel = await this.calculateSecurityLevel();\n } catch (error) {\n this._secureLog('warn', '\u26A0\uFE0F Security level calculation failed, using fallback', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n \n // Fallback value\n securityLevel = {\n level: 'enhanced',\n score: 80,\n passedChecks: 12,\n totalChecks: 15,\n isRealData: false\n };\n }\n \n // ============================================\n // PHASE 14: CREATE ANSWER PACKAGE\n // ============================================\n \n const currentTimestamp = Date.now();\n \n const answerPackage = {\n // Core information\n type: 'enhanced_secure_answer',\n sdp: this.peerConnection.localDescription.sdp,\n version: '4.0',\n timestamp: currentTimestamp,\n \n // Cryptographic keys\n ecdhPublicKey: ecdhPublicKeyData,\n ecdsaPublicKey: ecdsaPublicKeyData,\n \n // Authentication\n authProof: authProof,\n \n // Security metadata\n securityLevel: securityLevel,\n \n // Additional security fields\n sessionConfirmation: {\n saltFingerprint: saltFingerprint.substring(0, 16),\n keyDerivationSuccess: true,\n mutualAuthEnabled: !!authProof\n },\n \n // Answerer capabilities\n capabilities: {\n supportsFileTransfer: true,\n supportsEnhancedSecurity: true,\n supportsKeyRotation: true,\n supportsFakeTraffic: this.fakeTrafficConfig.enabled,\n supportsDecoyChannels: this.decoyChannelConfig.enabled,\n protocolVersion: '4.0'\n }\n };\n \n // ============================================\n // PHASE 15: VALIDATION AND LOGGING\n // ============================================\n \n // Final validation of the answer package\n if (!answerPackage.sdp || !answerPackage.ecdhPublicKey || !answerPackage.ecdsaPublicKey) {\n throw new Error('Generated answer package is incomplete');\n }\n \n this._secureLog('info', 'Enhanced secure answer created successfully', {\n operationId: operationId,\n version: answerPackage.version,\n hasECDSA: true,\n hasMutualAuth: !!authProof,\n hasSessionConfirmation: !!answerPackage.sessionConfirmation,\n securityLevel: securityLevel.level,\n timestamp: currentTimestamp,\n processingTime: currentTimestamp - offerData.timestamp\n });\n \n // Dispatch event about new connection\n document.dispatchEvent(new CustomEvent('new-connection', {\n detail: { \n type: 'answer',\n timestamp: currentTimestamp,\n securityLevel: securityLevel.level,\n operationId: operationId\n }\n }));\n \n // ============================================\n // PHASE 16: SCHEDULE SECURITY CALCULATIONS\n // ============================================\n \n // Plan security calculation after connection\n setTimeout(async () => {\n try {\n const realSecurityData = await this.calculateAndReportSecurityLevel();\n if (realSecurityData) {\n this.notifySecurityUpdate();\n this._secureLog('info', '\u2705 Post-connection security level calculated', {\n operationId: operationId,\n level: realSecurityData.level\n });\n }\n } catch (error) {\n this._secureLog('error', '\u274C Error calculating post-connection security', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n }\n }, 1000);\n \n // Retry if the first calculation fails\n setTimeout(async () => {\n if (!this.lastSecurityCalculation || this.lastSecurityCalculation.score < 50) {\n this._secureLog('info', '\uD83D\uDD04 Retrying security calculation', {\n operationId: operationId\n });\n await this.calculateAndReportSecurityLevel();\n this.notifySecurityUpdate();\n }\n }, 3000);\n \n // Final security update\n this.notifySecurityUpdate();\n \n // ============================================\n // PHASE 17: RETURN RESULT\n // ============================================\n \n return answerPackage;\n \n } catch (error) {\n // ============================================\n // ERROR HANDLING\n // ============================================\n \n this._secureLog('error', '\u274C Enhanced secure answer creation failed in critical section', {\n operationId: operationId,\n errorType: error.constructor.name,\n errorMessage: error.message,\n phase: this._determineAnswerErrorPhase(error),\n offerAge: offerData?.timestamp ? Date.now() - offerData.timestamp : 'unknown'\n });\n \n // Cleanup state on error\n this._cleanupFailedAnswerCreation();\n \n // Update status\n this.onStatusChange('disconnected');\n \n // Special handling of security errors\n if (this.onAnswerError) {\n if (error.message.includes('too old') || error.message.includes('replay')) {\n this.onAnswerError('replay_attack', error.message);\n } else if (error.message.includes('MITM') || error.message.includes('signature')) {\n this.onAnswerError('security_violation', error.message);\n } else if (error.message.includes('validation') || error.message.includes('format')) {\n this.onAnswerError('invalid_format', error.message);\n } else {\n this.onAnswerError('general_error', error.message);\n }\n }\n \n // Re-throw for upper-level handling\n throw error;\n }\n }, 20000); // 20 seconds timeout for the entire answer creation (longer than offer)\n }\n\n /**\n * HELPER: Determine error phase for answer\n */\n _determineAnswerErrorPhase(error) {\n const message = error.message.toLowerCase();\n \n if (message.includes('validation') || message.includes('format')) return 'offer_validation';\n if (message.includes('rate limit')) return 'rate_limiting';\n if (message.includes('replay') || message.includes('too old')) return 'replay_protection';\n if (message.includes('salt')) return 'salt_validation';\n if (message.includes('key pair') || message.includes('generate')) return 'key_generation';\n if (message.includes('import') || message.includes('ecdsa') || message.includes('ecdh')) return 'key_import';\n if (message.includes('signature') || message.includes('mitm')) return 'signature_verification';\n if (message.includes('derive') || message.includes('shared')) return 'key_derivation';\n if (message.includes('auth') || message.includes('proof')) return 'authentication';\n if (message.includes('remote description') || message.includes('local description')) return 'webrtc_setup';\n if (message.includes('answer') || message.includes('sdp')) return 'sdp_creation';\n if (message.includes('export')) return 'key_export';\n if (message.includes('security level')) return 'security_calculation';\n \n return 'unknown';\n }\n\n /**\n * HELPER: Cleanup state after failed answer creation\n */\n /**\n * Secure cleanup state after failed answer creation\n */\n _cleanupFailedAnswerCreation() {\n try {\n // Secure wipe of cryptographic materials\n this._secureCleanupCryptographicMaterials();\n \n // Secure wipe of PFS key versions\n this.currentKeyVersion = 0;\n this.keyVersions.clear();\n this.oldKeys.clear();\n \n // Close peer connection if created\n if (this.peerConnection) {\n this.peerConnection.close();\n this.peerConnection = null;\n }\n \n // Clear data channel\n if (this.dataChannel) {\n this.dataChannel.close();\n this.dataChannel = null;\n }\n \n // Reset flags and counters\n this.isInitiator = false;\n this.isVerified = false;\n this.sequenceNumber = 0;\n this.expectedSequenceNumber = 0;\n this.messageCounter = 0;\n this.processedMessageIds.clear();\n this.replayWindow.clear(); // Clear replay window\n \n // Reset security features to baseline\n this._updateSecurityFeatures({\n hasEncryption: false,\n hasECDH: false,\n hasECDSA: false,\n hasMutualAuth: false,\n hasMetadataProtection: false,\n hasEnhancedReplayProtection: false,\n hasNonExtractableKeys: false,\n hasEnhancedValidation: false,\n hasPFS: false\n });\n \n // Force garbage collection\n this._forceGarbageCollection();\n \n this._secureLog('debug', '\uD83D\uDD12 Failed answer creation cleanup completed with secure memory wipe');\n \n } catch (cleanupError) {\n this._secureLog('error', '\u274C Error during answer creation cleanup', {\n errorType: cleanupError.constructor.name,\n errorMessage: cleanupError.message\n });\n }\n }\n\n /**\n * HELPER: Securely set encryption keys (if not set yet)\n */\n async _setEncryptionKeys(encryptionKey, macKey, metadataKey, keyFingerprint) {\n return this._withMutex('keyOperation', async (operationId) => {\n this._secureLog('info', '\uD83D\uDD10 Setting encryption keys with mutex', {\n operationId: operationId\n });\n \n // Validate all keys before setting\n if (!(encryptionKey instanceof CryptoKey) ||\n !(macKey instanceof CryptoKey) ||\n !(metadataKey instanceof CryptoKey)) {\n throw new Error('Invalid key types provided');\n }\n \n if (!keyFingerprint || typeof keyFingerprint !== 'string') {\n throw new Error('Invalid key fingerprint provided');\n }\n \n // Atomically set all keys\n const oldKeys = {\n encryptionKey: this.encryptionKey,\n macKey: this.macKey,\n metadataKey: this.metadataKey,\n keyFingerprint: this.keyFingerprint\n };\n \n try {\n this.encryptionKey = encryptionKey;\n this.macKey = macKey;\n this.metadataKey = metadataKey;\n this.keyFingerprint = keyFingerprint;\n \n // Reset counters\n this.sequenceNumber = 0;\n this.expectedSequenceNumber = 0;\n this.messageCounter = 0;\n this.processedMessageIds.clear();\n this.replayWindow.clear(); // Clear replay window\n \n this._secureLog('info', '\u2705 Encryption keys set successfully', {\n operationId: operationId,\n hasAllKeys: !!(this.encryptionKey && this.macKey && this.metadataKey),\n hasFingerprint: !!this.keyFingerprint\n });\n \n return true;\n \n } catch (error) {\n // Roll back on error\n this.encryptionKey = oldKeys.encryptionKey;\n this.macKey = oldKeys.macKey;\n this.metadataKey = oldKeys.metadataKey;\n this.keyFingerprint = oldKeys.keyFingerprint;\n \n this._secureLog('error', '\u274C Key setting failed, rolled back', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n \n throw error;\n }\n });\n }\n\n async handleSecureAnswer(answerData) {\n console.log('\uD83C\uDFAF handleSecureAnswer called with answerData:', answerData ? 'present' : 'null');\n try {\n \n if (!answerData || typeof answerData !== 'object' || Array.isArray(answerData)) {\n this._secureLog('error', 'CRITICAL: Invalid answer data structure', { \n hasAnswerData: !!answerData,\n answerDataType: typeof answerData,\n isArray: Array.isArray(answerData)\n });\n throw new Error('CRITICAL SECURITY FAILURE: Answer data must be a non-null object');\n }\n \n if (answerData.type !== 'enhanced_secure_answer' || !answerData.sdp) {\n this._secureLog('error', 'CRITICAL: Invalid answer format', { \n type: answerData.type,\n hasSdp: !!answerData.sdp\n });\n throw new Error('CRITICAL SECURITY FAILURE: Invalid answer format - hard abort required');\n }\n\n // CRITICAL: Strict validation of ECDH public key structure\n if (!answerData.ecdhPublicKey || typeof answerData.ecdhPublicKey !== 'object' || Array.isArray(answerData.ecdhPublicKey)) {\n this._secureLog('error', 'CRITICAL: Invalid ECDH public key structure in answer', { \n hasEcdhKey: !!answerData.ecdhPublicKey,\n ecdhKeyType: typeof answerData.ecdhPublicKey,\n isArray: Array.isArray(answerData.ecdhPublicKey)\n });\n throw new Error('CRITICAL SECURITY FAILURE: Missing or invalid ECDH public key structure');\n }\n \n if (!answerData.ecdhPublicKey.keyData || !answerData.ecdhPublicKey.signature) {\n this._secureLog('error', 'CRITICAL: ECDH key missing keyData or signature in answer', { \n hasKeyData: !!answerData.ecdhPublicKey.keyData,\n hasSignature: !!answerData.ecdhPublicKey.signature\n });\n throw new Error('CRITICAL SECURITY FAILURE: ECDH key missing keyData or signature');\n }\n\n // CRITICAL: Strict validation of ECDSA public key structure\n if (!answerData.ecdsaPublicKey || typeof answerData.ecdsaPublicKey !== 'object' || Array.isArray(answerData.ecdsaPublicKey)) {\n this._secureLog('error', 'CRITICAL: Invalid ECDSA public key structure in answer', { \n hasEcdsaKey: !!answerData.ecdsaPublicKey,\n ecdsaKeyType: typeof answerData.ecdsaPublicKey,\n isArray: Array.isArray(answerData.ecdsaPublicKey)\n });\n throw new Error('CRITICAL SECURITY FAILURE: Missing or invalid ECDSA public key structure');\n }\n \n if (!answerData.ecdsaPublicKey.keyData || !answerData.ecdsaPublicKey.signature) {\n this._secureLog('error', 'CRITICAL: ECDSA key missing keyData or signature in answer', { \n hasKeyData: !!answerData.ecdsaPublicKey.keyData,\n hasSignature: !!answerData.ecdsaPublicKey.signature\n });\n throw new Error('CRITICAL SECURITY FAILURE: ECDSA key missing keyData or signature');\n }\n\n // Additional MITM protection: Validate answer data structure\n if (!answerData.timestamp || !answerData.version) {\n throw new Error('Missing required fields in response data \u2013 possible MITM attack');\n }\n\n // MITM Protection: Verify session ID if present (for enhanced security)\n if (answerData.sessionId && this.sessionId && answerData.sessionId !== this.sessionId) {\n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'Session ID mismatch detected - possible MITM attack', {\n expectedSessionId: this.sessionId,\n receivedSessionId: answerData.sessionId\n });\n throw new Error('Session ID mismatch \u2013 possible MITM attack');\n }\n\n // Check for replay attacks (reject answers older than 1 hour)\n const answerAge = Date.now() - answerData.timestamp;\n if (answerAge > 3600000) { // 1 hour in milliseconds\n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'Answer data is too old - possible replay attack', {\n answerAge: answerAge,\n timestamp: answerData.timestamp\n });\n \n // Notify the main code about the replay attack error\n if (this.onAnswerError) {\n this.onAnswerError('replay_attack', 'Response data is too old \u2013 possible replay attack');\n }\n \n throw new Error('Response data is too old \u2013 possible replay attack');\n }\n\n // Check protocol version compatibility\n if (answerData.version !== '4.0') {\n window.EnhancedSecureCryptoUtils.secureLog.log('warn', 'Incompatible protocol version in answer', {\n expectedVersion: '4.0',\n receivedVersion: answerData.version\n });\n }\n\n // Import ECDSA public key for verification (self-signed)\n const peerECDSAPublicKey = await crypto.subtle.importKey(\n 'spki',\n new Uint8Array(answerData.ecdsaPublicKey.keyData),\n {\n name: 'ECDSA',\n namedCurve: 'P-384'\n },\n false,\n ['verify']\n );\n\n\n // Now import and verify the ECDH public key using the verified ECDSA key\n const peerPublicKey = await window.EnhancedSecureCryptoUtils.importPublicKeyFromSignedPackage(\n answerData.ecdhPublicKey,\n peerECDSAPublicKey\n );\n \n // Additional MITM protection: Verify session salt integrity\n if (!this.sessionSalt || this.sessionSalt.length !== 64) {\n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'Invalid session salt detected - possible session hijacking', {\n saltLength: this.sessionSalt ? this.sessionSalt.length : 0\n });\n throw new Error('Invalid session salt \u2013 possible session hijacking attempt');\n }\n\n // Verify that the session salt hasn't been tampered with\n const expectedSaltHash = await window.EnhancedSecureCryptoUtils.calculateKeyFingerprint(this.sessionSalt);\n window.EnhancedSecureCryptoUtils.secureLog.log('info', 'Session salt integrity verified', {\n saltFingerprint: expectedSaltHash.substring(0, 8)\n });\n\n // Additional validation: Ensure all keys are CryptoKey instances before derivation\n if (!(this.ecdhKeyPair?.privateKey instanceof CryptoKey)) {\n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'Local ECDH private key is not a CryptoKey in handleSecureAnswer', {\n hasKeyPair: !!this.ecdhKeyPair,\n privateKeyType: typeof this.ecdhKeyPair?.privateKey,\n privateKeyAlgorithm: this.ecdhKeyPair?.privateKey?.algorithm?.name\n });\n throw new Error('Local ECDH private key is not a CryptoKey');\n }\n \n if (!(peerPublicKey instanceof CryptoKey)) {\n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'Peer ECDH public key is not a CryptoKey in handleSecureAnswer', {\n publicKeyType: typeof peerPublicKey,\n publicKeyAlgorithm: peerPublicKey?.algorithm?.name\n });\n throw new Error('Peer ECDH public key is not a CryptoKey');\n }\n\n // Store peer's public key for PFS key rotation\n this.peerPublicKey = peerPublicKey;\n \n // Initialize connection ID if not already set\n if (!this.connectionId) {\n this.connectionId = Array.from(crypto.getRandomValues(new Uint8Array(8)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n }\n\n \n const derivedKeys = await window.EnhancedSecureCryptoUtils.deriveSharedKeys(\n this.ecdhKeyPair.privateKey,\n peerPublicKey,\n this.sessionSalt\n );\n \n this.encryptionKey = derivedKeys.encryptionKey;\n this.macKey = derivedKeys.macKey;\n this.metadataKey = derivedKeys.metadataKey;\n this.keyFingerprint = derivedKeys.fingerprint;\n this.sequenceNumber = 0;\n this.expectedSequenceNumber = 0;\n this.messageCounter = 0;\n this.processedMessageIds.clear();\n this.replayWindow.clear(); // Clear replay window\n // Validate that all keys are properly set\n if (!(this.encryptionKey instanceof CryptoKey) || \n !(this.macKey instanceof CryptoKey) || \n !(this.metadataKey instanceof CryptoKey)) {\n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'Invalid key types after derivation in handleSecureAnswer', {\n encryptionKeyType: typeof this.encryptionKey,\n macKeyType: typeof this.macKey,\n metadataKeyType: typeof this.metadataKey,\n encryptionKeyAlgorithm: this.encryptionKey?.algorithm?.name,\n macKeyAlgorithm: this.macKey?.algorithm?.name,\n metadataKeyAlgorithm: this.metadataKey?.algorithm?.name\n });\n throw new Error('Invalid key types after export');\n }\n \n this._secureLog('info', 'Encryption keys set in handleSecureAnswer', {\n hasEncryptionKey: !!this.encryptionKey,\n hasMacKey: !!this.macKey,\n hasMetadataKey: !!this.metadataKey,\n hasKeyFingerprint: !!this.keyFingerprint,\n mitmProtection: 'enabled',\n signatureVerified: true\n });\n \n // Update security features for initiator after successful key exchange\n this.securityFeatures.hasMutualAuth = true;\n this.securityFeatures.hasMetadataProtection = true;\n this.securityFeatures.hasEnhancedReplayProtection = true;\n this.securityFeatures.hasPFS = true;\n \n // PFS: Initialize key version tracking\n this.currentKeyVersion = 0;\n this.lastKeyRotation = Date.now();\n this.keyVersions.set(0, {\n salt: this.sessionSalt,\n timestamp: this.lastKeyRotation,\n messageCount: 0\n });\n \n this.onKeyExchange(this.keyFingerprint);\n\n // Compute SAS for MITM protection (Offer side - Answer handler)\n try {\n console.log('Starting SAS computation for Offer side (Answer handler)');\n const remoteFP = this._extractDTLSFingerprintFromSDP(answerData.sdp); // \u0443\u0436\u0435 \u0435\u0441\u0442\u044C \u0432 \u043A\u043E\u0434\u0435\n const localFP = this.expectedDTLSFingerprint; // \u0442\u044B \u0435\u0433\u043E \u0441\u043E\u0445\u0440\u0430\u043D\u044F\u0435\u0448\u044C \u043F\u0440\u0438 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0438 \u043E\u0444\u0444\u0435\u0440\u0430/\u043E\u0442\u0432\u0435\u0442\u0430\n const keyBytes = this._decodeKeyFingerprint(this.keyFingerprint); // \u0443\u0442\u0438\u043B\u0438\u0442\u0430 \u0434\u0435\u043A\u043E\u0434\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F\n console.log('SAS computation parameters:', { \n remoteFP: remoteFP ? remoteFP.substring(0, 16) + '...' : 'null/undefined', \n localFP: localFP ? localFP.substring(0, 16) + '...' : 'null/undefined', \n keyBytesLength: keyBytes ? keyBytes.length : 'null/undefined',\n keyBytesType: keyBytes ? keyBytes.constructor.name : 'null/undefined'\n });\n\n this.verificationCode = await this._computeSAS(keyBytes, localFP, remoteFP);\n this.onStatusChange?.('verifying'); // \u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u043C SAS \u0438 \u0436\u0434\u0451\u043C \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F\n this.onVerificationRequired(this.verificationCode);\n \n // CRITICAL: Store SAS code to send when data channel opens\n this.pendingSASCode = this.verificationCode;\n console.log('\uD83D\uDCE4 SAS code ready to send when data channel opens:', this.verificationCode);\n \n this._secureLog('info', 'SAS verification code generated for MITM protection (Offer side)', {\n sasCode: this.verificationCode,\n localFP: localFP.substring(0, 16) + '...',\n remoteFP: remoteFP.substring(0, 16) + '...',\n timestamp: Date.now()\n });\n } catch (sasError) {\n console.error('SAS computation failed in handleSecureAnswer (Offer side):', sasError);\n this._secureLog('error', 'SAS computation failed in handleSecureAnswer (Offer side)', {\n error: sasError.message,\n stack: sasError.stack,\n timestamp: Date.now()\n });\n }\n\n // Validate DTLS fingerprint before setting remote description\n if (this.strictDTLSValidation) {\n try {\n const receivedFingerprint = this._extractDTLSFingerprintFromSDP(answerData.sdp);\n \n if (this.expectedDTLSFingerprint) {\n this._validateDTLSFingerprint(receivedFingerprint, this.expectedDTLSFingerprint, 'answer_validation');\n } else {\n // Store fingerprint for future validation (first connection)\n this.expectedDTLSFingerprint = receivedFingerprint;\n this._secureLog('info', 'Stored DTLS fingerprint for future validation', {\n fingerprint: receivedFingerprint,\n context: 'first_connection'\n });\n }\n } catch (error) {\n this._secureLog('warn', 'DTLS fingerprint validation failed - continuing in fallback mode', { \n error: error.message,\n context: 'answer_validation'\n });\n\n }\n } else {\n this._secureLog('info', 'DTLS fingerprint validation disabled - proceeding without validation');\n }\n\n this._secureLog('debug', 'Setting remote description from answer', {\n sdpLength: answerData.sdp?.length || 0\n });\n \n await this.peerConnection.setRemoteDescription({\n type: 'answer',\n sdp: answerData.sdp\n });\n \n this._secureLog('debug', 'Remote description set successfully from answer', {\n signalingState: this.peerConnection.signalingState\n });\n \n console.log('Enhanced secure connection established');\n\n setTimeout(async () => {\n try {\n const securityData = await this.calculateAndReportSecurityLevel();\n if (securityData) {\n console.log('\u2705 Security level calculated after connection:', securityData.level);\n this.notifySecurityUpdate();\n }\n } catch (error) {\n this._secureLog('error', '\u274C Error calculating security after connection:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }, 1000);\n setTimeout(async () => {\n if (!this.lastSecurityCalculation || this.lastSecurityCalculation.score < 50) {\n console.log('\uD83D\uDD04 Retrying security calculation...');\n await this.calculateAndReportSecurityLevel();\n this.notifySecurityUpdate();\n }\n }, 3000);\n this.notifySecurityUpdate();\n } catch (error) {\n this._secureLog('error', 'Enhanced secure answer handling failed', {\n errorType: error.constructor.name\n });\n this.onStatusChange('failed');\n\n if (this.onAnswerError) {\n if (error.message.includes('too old') || error.message.includes('\u0441\u043B\u0438\u0448\u043A\u043E\u043C \u0441\u0442\u0430\u0440\u044B\u0435')) {\n this.onAnswerError('replay_attack', error.message);\n } else if (error.message.includes('MITM') || error.message.includes('signature') || error.message.includes('\u043F\u043E\u0434\u043F\u0438\u0441\u044C')) {\n this.onAnswerError('security_violation', error.message);\n } else {\n this.onAnswerError('general_error', error.message);\n }\n }\n \n throw error;\n }\n }\n\n forceSecurityUpdate() {\n console.log('\uD83D\uDD04 Force security update requested');\n setTimeout(async () => {\n try {\n const securityData = await this.calculateAndReportSecurityLevel();\n if (securityData) {\n this.notifySecurityUpdate();\n console.log('\u2705 Force security update completed');\n }\n } catch (error) {\n this._secureLog('error', '\u274C Force security update failed:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }, 100);\n }\n\n initiateVerification() {\n \n if (this.isInitiator) {\n // Ensure verification initiation notice wasn't already sent\n if (!this.verificationInitiationSent) {\n this.verificationInitiationSent = true;\n this.deliverMessageToUI('\uD83D\uDD10 CRITICAL: Compare verification code with peer out-of-band (voice/video/in-person) to prevent MITM attack!', 'system');\n this.deliverMessageToUI(`\uD83D\uDD10 Your verification code: ${this.verificationCode}`, 'system');\n this.deliverMessageToUI('\uD83D\uDD10 Ask peer to confirm this exact code before allowing traffic!', 'system');\n }\n } else {\n // Answer side: Wait for SAS code from Offer side\n console.log('\uD83D\uDCE5 Answer side: Waiting for SAS code from Offer side');\n this.deliverMessageToUI('\uD83D\uDCE5 Waiting for verification code from peer...', 'system');\n }\n }\n\n confirmVerification() {\n \n try {\n console.log('\uD83D\uDCE4 confirmVerification - sending local confirmation');\n \n // Mark local verification as confirmed\n this.localVerificationConfirmed = true;\n \n // Send confirmation to peer\n const confirmationPayload = {\n type: 'verification_confirmed',\n data: {\n timestamp: Date.now(),\n verificationMethod: 'SAS',\n securityLevel: 'MITM_PROTECTION_REQUIRED'\n }\n };\n \n console.log('\uD83D\uDCE4 Sending verification confirmation:', confirmationPayload);\n this.dataChannel.send(JSON.stringify(confirmationPayload));\n \n // Notify UI about state change\n if (this.onVerificationStateChange) {\n this.onVerificationStateChange({\n localConfirmed: this.localVerificationConfirmed,\n remoteConfirmed: this.remoteVerificationConfirmed,\n bothConfirmed: this.bothVerificationsConfirmed\n });\n }\n \n // Check if both parties have confirmed\n this._checkBothVerificationsConfirmed();\n \n // Notify UI about local confirmation\n this.deliverMessageToUI('\u2705 You confirmed the verification code. Waiting for peer confirmation...', 'system');\n \n this.processMessageQueue();\n } catch (error) {\n this._secureLog('error', '\u274C SAS verification failed:', { errorType: error?.constructor?.name || 'Unknown' });\n this.deliverMessageToUI('\u274C SAS verification failed', 'system');\n }\n }\n\n _checkBothVerificationsConfirmed() {\n // Check if both parties have confirmed verification\n if (this.localVerificationConfirmed && this.remoteVerificationConfirmed && !this.bothVerificationsConfirmed) {\n console.log('\uD83C\uDF89 Both parties confirmed verification!');\n this.bothVerificationsConfirmed = true;\n \n // Notify both parties that verification is complete\n const bothConfirmedPayload = {\n type: 'verification_both_confirmed',\n data: {\n timestamp: Date.now(),\n verificationMethod: 'SAS',\n securityLevel: 'MITM_PROTECTION_COMPLETE'\n }\n };\n \n console.log('\uD83D\uDCE4 Sending both confirmed notification:', bothConfirmedPayload);\n this.dataChannel.send(JSON.stringify(bothConfirmedPayload));\n \n // Notify UI about state change\n if (this.onVerificationStateChange) {\n this.onVerificationStateChange({\n localConfirmed: this.localVerificationConfirmed,\n remoteConfirmed: this.remoteVerificationConfirmed,\n bothConfirmed: this.bothVerificationsConfirmed\n });\n }\n \n // Set verified status and open chat after 2 second delay\n this.deliverMessageToUI('\uD83C\uDF89 Both parties confirmed! Opening secure chat in 2 seconds...', 'system');\n \n setTimeout(() => {\n this._setVerifiedStatus(true, 'MUTUAL_SAS_CONFIRMED', { \n code: this.verificationCode,\n timestamp: Date.now()\n });\n this._enforceVerificationGate('mutual_confirmed', false);\n this.onStatusChange?.('verified');\n }, 2000);\n }\n }\n\n handleVerificationConfirmed(data) {\n // Handle peer's verification confirmation\n console.log('\uD83D\uDCE5 Received verification confirmation from peer');\n this.remoteVerificationConfirmed = true;\n \n // Notify UI about peer confirmation\n this.deliverMessageToUI('\u2705 Peer confirmed the verification code. Waiting for your confirmation...', 'system');\n \n // Notify UI about state change\n if (this.onVerificationStateChange) {\n this.onVerificationStateChange({\n localConfirmed: this.localVerificationConfirmed,\n remoteConfirmed: this.remoteVerificationConfirmed,\n bothConfirmed: this.bothVerificationsConfirmed\n });\n }\n \n // Check if both parties have confirmed\n this._checkBothVerificationsConfirmed();\n }\n\n handleVerificationBothConfirmed(data) {\n // Handle notification that both parties have confirmed\n console.log('\uD83D\uDCE5 Received both confirmed notification from peer');\n this.bothVerificationsConfirmed = true;\n \n // Notify UI about state change\n if (this.onVerificationStateChange) {\n this.onVerificationStateChange({\n localConfirmed: this.localVerificationConfirmed,\n remoteConfirmed: this.remoteVerificationConfirmed,\n bothConfirmed: this.bothVerificationsConfirmed\n });\n }\n \n // Set verified status and open chat after 2 second delay\n this.deliverMessageToUI('\uD83C\uDF89 Both parties confirmed! Opening secure chat in 2 seconds...', 'system');\n \n setTimeout(() => {\n this._setVerifiedStatus(true, 'MUTUAL_SAS_CONFIRMED', { \n code: this.verificationCode,\n timestamp: Date.now()\n });\n this._enforceVerificationGate('mutual_confirmed', false);\n this.onStatusChange?.('verified');\n }, 2000);\n }\n\n handleVerificationRequest(data) {\n \n console.log('\uD83D\uDD0D handleVerificationRequest called with:');\n console.log(' - receivedCode:', data.code, '(type:', typeof data.code, ')');\n console.log(' - expectedCode:', this.verificationCode, '(type:', typeof this.verificationCode, ')');\n console.log(' - codesMatch:', data.code === this.verificationCode);\n console.log(' - data object:', data);\n \n if (data.code === this.verificationCode) {\n // \u2705 SAS verification successful - MITM protection confirmed\n const responsePayload = {\n type: 'verification_response',\n data: {\n ok: true,\n timestamp: Date.now(),\n verificationMethod: 'SAS', // Indicate SAS was used\n securityLevel: 'MITM_PROTECTED'\n }\n };\n this.dataChannel.send(JSON.stringify(responsePayload));\n \n // Ensure verification success notice wasn't already sent\n if (!this.verificationNotificationSent) {\n this.verificationNotificationSent = true;\n this.deliverMessageToUI('\u2705 SAS verification successful! MITM protection confirmed. Channel is now secure!', 'system');\n }\n \n this.processMessageQueue();\n } else {\n // \u274C SAS verification failed - possible MITM attack\n console.log('\u274C SAS verification failed - codes do not match, disconnecting');\n const responsePayload = {\n type: 'verification_response',\n data: {\n ok: false,\n timestamp: Date.now(),\n reason: 'code_mismatch'\n }\n };\n this.dataChannel.send(JSON.stringify(responsePayload));\n \n this._secureLog('error', 'SAS verification failed - possible MITM attack', {\n receivedCode: data.code,\n expectedCode: this.verificationCode,\n timestamp: Date.now()\n });\n \n this.deliverMessageToUI('\u274C SAS verification failed! Possible MITM attack detected. Connection aborted for safety!', 'system');\n this.disconnect();\n }\n }\n\n handleSASCode(data) {\n \n console.log('\uD83D\uDCE5 Received SAS code from Offer side:', data.code);\n \n this.verificationCode = data.code;\n this.onStatusChange?.('verifying'); // \u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u043C SAS \u0438 \u0436\u0434\u0451\u043C \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F\n this.onVerificationRequired(this.verificationCode);\n \n this._secureLog('info', 'SAS code received from Offer side', {\n sasCode: this.verificationCode,\n timestamp: Date.now()\n });\n }\n\n handleVerificationResponse(data) {\n \n if (data.ok === true) {\n \n // Log successful mutual SAS verification\n this._secureLog('info', 'Mutual SAS verification completed - MITM protection active', {\n verificationMethod: data.verificationMethod || 'SAS',\n securityLevel: data.securityLevel || 'MITM_PROTECTED',\n timestamp: Date.now()\n });\n \n // Ensure verification success notice wasn't already sent\n if (!this.verificationNotificationSent) {\n this.verificationNotificationSent = true;\n this.deliverMessageToUI('\u2705 Mutual SAS verification complete! MITM protection active. Channel is now secure!', 'system');\n }\n \n this.processMessageQueue();\n } else {\n // \u274C Peer verification failed - connection not secure\n this._secureLog('error', 'Peer SAS verification failed - connection not secure', {\n responseData: data,\n timestamp: Date.now()\n });\n \n this.deliverMessageToUI('\u274C Peer verification failed! Connection not secure!', 'system');\n this.disconnect();\n }\n }\n\n validateOfferData(offerData) {\n return offerData &&\n offerData.type === 'enhanced_secure_offer' &&\n offerData.sdp &&\n offerData.publicKey &&\n offerData.salt &&\n offerData.verificationCode &&\n Array.isArray(offerData.publicKey) &&\n Array.isArray(offerData.salt) &&\n offerData.salt.length === 32;\n }\n\n validateEnhancedOfferData(offerData) {\n console.log('\uD83C\uDFAF validateEnhancedOfferData called with:', offerData ? 'valid object' : 'null/undefined');\n try {\n // CRITICAL: Strict type checking to prevent syntax errors\n if (!offerData || typeof offerData !== 'object' || Array.isArray(offerData)) {\n this._secureLog('error', 'CRITICAL: Invalid offer data structure', { \n hasOfferData: !!offerData,\n offerDataType: typeof offerData,\n isArray: Array.isArray(offerData)\n });\n throw new Error('CRITICAL SECURITY FAILURE: Offer data must be a non-null object');\n }\n\n // Basic required fields for all versions\n const basicFields = ['type', 'sdp'];\n for (const field of basicFields) {\n if (!offerData[field]) {\n throw new Error(`Missing required field: ${field}`);\n }\n }\n\n // Validate offer type (support both v3.0 and v4.0 formats)\n if (!['enhanced_secure_offer', 'secure_offer'].includes(offerData.type)) {\n throw new Error('Invalid offer type');\n }\n\n // Check if this is v4.0 format with enhanced features\n const isV4Format = offerData.version === '4.0' && offerData.ecdhPublicKey && offerData.ecdsaPublicKey;\n \n if (isV4Format) {\n // v4.0 enhanced validation\n const v4RequiredFields = [\n 'ecdhPublicKey', 'ecdsaPublicKey', 'salt', 'verificationCode',\n 'authChallenge', 'timestamp', 'version', 'securityLevel'\n ];\n\n for (const field of v4RequiredFields) {\n if (!offerData[field]) {\n throw new Error(`Missing v4.0 field: ${field}`);\n }\n }\n\n // Validate salt (must be 64 bytes for v4.0)\n if (!Array.isArray(offerData.salt) || offerData.salt.length !== 64) {\n throw new Error('Salt must be exactly 64 bytes for v4.0');\n }\n\n // Validate timestamp (not older than 1 hour)\n const offerAge = Date.now() - offerData.timestamp;\n if (offerAge > 3600000) {\n throw new Error('Offer is too old (older than 1 hour)');\n }\n\n // CRITICAL: Strict validation of key structures to prevent syntax errors\n if (!offerData.ecdhPublicKey || typeof offerData.ecdhPublicKey !== 'object' || Array.isArray(offerData.ecdhPublicKey)) {\n this._secureLog('error', 'CRITICAL: Invalid ECDH public key structure', { \n hasEcdhKey: !!offerData.ecdhPublicKey,\n ecdhKeyType: typeof offerData.ecdhPublicKey,\n isArray: Array.isArray(offerData.ecdhPublicKey)\n });\n throw new Error('CRITICAL SECURITY FAILURE: Invalid ECDH public key structure - hard abort required');\n }\n\n if (!offerData.ecdsaPublicKey || typeof offerData.ecdsaPublicKey !== 'object' || Array.isArray(offerData.ecdsaPublicKey)) {\n this._secureLog('error', 'CRITICAL: Invalid ECDSA public key structure', { \n hasEcdsaKey: !!offerData.ecdsaPublicKey,\n ecdsaKeyType: typeof offerData.ecdsaPublicKey,\n isArray: Array.isArray(offerData.ecdsaPublicKey)\n });\n throw new Error('CRITICAL SECURITY FAILURE: Invalid ECDSA public key structure - hard abort required');\n }\n\n // CRITICAL: Validate key internal structure to prevent syntax errors\n if (!offerData.ecdhPublicKey.keyData || !offerData.ecdhPublicKey.signature) {\n this._secureLog('error', 'CRITICAL: ECDH key missing keyData or signature', { \n hasKeyData: !!offerData.ecdhPublicKey.keyData,\n hasSignature: !!offerData.ecdhPublicKey.signature\n });\n throw new Error('CRITICAL SECURITY FAILURE: ECDH key missing keyData or signature');\n }\n\n if (!offerData.ecdsaPublicKey.keyData || !offerData.ecdsaPublicKey.signature) {\n this._secureLog('error', 'CRITICAL: ECDSA key missing keyData or signature', { \n hasKeyData: !!offerData.ecdsaPublicKey.keyData,\n hasSignature: !!offerData.ecdsaPublicKey.signature\n });\n throw new Error('CRITICAL SECURITY FAILURE: ECDSA key missing keyData or signature');\n }\n\n if (typeof offerData.verificationCode !== 'string' || offerData.verificationCode.length < 6) {\n throw new Error('Invalid SAS verification code format - MITM protection required');\n }\n\n this._secureLog('info', 'v4.0 offer validation passed', {\n version: offerData.version,\n hasSecurityLevel: !!offerData.securityLevel?.level,\n offerAge: Math.round(offerAge / 1000) + 's'\n });\n } else {\n // v3.0 backward compatibility validation\n // NOTE: v3.0 has limited security - SAS verification is still critical\n const v3RequiredFields = ['publicKey', 'salt', 'verificationCode'];\n for (const field of v3RequiredFields) {\n if (!offerData[field]) {\n throw new Error(`Missing v3.0 field: ${field}`);\n }\n }\n\n // Validate salt (32 bytes for v3.0)\n if (!Array.isArray(offerData.salt) || offerData.salt.length !== 32) {\n throw new Error('Salt must be exactly 32 bytes for v3.0');\n }\n\n // Validate public key\n if (!Array.isArray(offerData.publicKey)) {\n throw new Error('Invalid public key format for v3.0');\n }\n\n window.EnhancedSecureCryptoUtils.secureLog.log('info', 'v3.0 offer validation passed (backward compatibility)', {\n version: 'v3.0',\n legacy: true\n });\n }\n\n // Validate SDP structure (basic check for all versions)\n if (typeof offerData.sdp !== 'string' || !offerData.sdp.includes('v=0')) {\n throw new Error('Invalid SDP structure');\n }\n\n console.log('\uD83C\uDFAF validateEnhancedOfferData completed successfully');\n return true;\n } catch (error) {\n console.log('\uD83C\uDFAF validateEnhancedOfferData ERROR:', error.message);\n this._secureLog('error', 'CRITICAL: Security validation failed - hard abort required', {\n error: error.message,\n errorType: error.constructor.name,\n timestamp: Date.now()\n });\n\n throw new Error(`CRITICAL SECURITY VALIDATION FAILURE: ${error.message}`);\n }\n }\n\n async sendSecureMessage(message) {\n // Comprehensive input validation\n const validation = this._validateInputData(message, 'sendSecureMessage');\n if (!validation.isValid) {\n const errorMessage = `Input validation failed: ${validation.errors.join(', ')}`;\n this._secureLog('error', '\u274C Input validation failed in sendSecureMessage', {\n errors: validation.errors,\n messageType: typeof message\n });\n throw new Error(errorMessage);\n }\n\n // Rate limiting check\n if (!this._checkRateLimit('sendSecureMessage')) {\n throw new Error('Rate limit exceeded for secure message sending');\n }\n\n // Enforce verification gate\n this._enforceVerificationGate('sendSecureMessage');\n\n // Quick readiness check WITHOUT mutex\n if (!this.isConnected()) {\n if (validation.sanitizedData && typeof validation.sanitizedData === 'object' && validation.sanitizedData.type && validation.sanitizedData.type.startsWith('file_')) {\n throw new Error('Connection not ready for file transfer. Please ensure the connection is established and verified.');\n }\n this.messageQueue.push(validation.sanitizedData);\n throw new Error('Connection not ready. Message queued for sending.');\n }\n \n // Use mutex ONLY for cryptographic operations\n return this._withMutex('cryptoOperation', async (operationId) => {\n // Re-check inside critical section\n if (!this.isConnected() || !this.isVerified) {\n throw new Error('Connection lost during message preparation');\n }\n \n // Validate keys inside critical section\n if (!this.encryptionKey || !this.macKey || !this.metadataKey) {\n throw new Error('Encryption keys not initialized');\n }\n \n // Additional rate limiting check\n if (!window.EnhancedSecureCryptoUtils.rateLimiter.checkMessageRate(this.rateLimiterId)) {\n throw new Error('Message rate limit exceeded (60 messages per minute)');\n }\n \n try {\n // Accept strings and objects; stringify objects\n const textToSend = typeof validation.sanitizedData === 'string' ? validation.sanitizedData : JSON.stringify(validation.sanitizedData);\n const sanitizedMessage = window.EnhancedSecureCryptoUtils.sanitizeMessage(textToSend);\n const messageId = `msg_${Date.now()}_${this.messageCounter++}`;\n \n // Create AAD with sequence number for anti-replay protection\n if (typeof this._createMessageAAD !== 'function') {\n throw new Error('_createMessageAAD method is not available in sendSecureMessage. Manager may not be fully initialized.');\n }\n const aad = message.aad || this._createMessageAAD('enhanced_message', { content: sanitizedMessage });\n \n // Use enhanced encryption with AAD and sequence number\n const encryptedData = await window.EnhancedSecureCryptoUtils.encryptMessage(\n sanitizedMessage,\n this.encryptionKey,\n this.macKey,\n this.metadataKey,\n messageId,\n JSON.parse(aad).sequenceNumber // Use sequence number from AAD\n );\n \n const payload = {\n type: 'enhanced_message',\n data: encryptedData,\n keyVersion: this.currentKeyVersion,\n version: '4.0'\n };\n \n this.dataChannel.send(JSON.stringify(payload));\n // Locally display only plain strings to avoid UI duplication\n if (typeof validation.sanitizedData === 'string') {\n this.deliverMessageToUI(validation.sanitizedData, 'sent');\n }\n \n this._secureLog('debug', '\uD83D\uDCE4 Secure message sent successfully', {\n operationId: operationId,\n messageLength: sanitizedMessage.length,\n keyVersion: this.currentKeyVersion\n });\n \n } catch (error) {\n this._secureLog('error', '\u274C Secure message sending failed', {\n operationId: operationId,\n errorType: error.constructor.name\n });\n throw error;\n }\n }, 2000); // Reduced timeout for crypto operations\n }\n\n processMessageQueue() {\n while (this.messageQueue.length > 0 && this.isConnected() && this.isVerified) {\n const message = this.messageQueue.shift();\n this.sendSecureMessage(message).catch(console.error);\n }\n }\n\n startHeartbeat() {\n // Heartbeat moved to unified scheduler with connection validation\n this._secureLog('info', '\uD83D\uDD27 Heartbeat moved to unified scheduler');\n \n // Store heartbeat configuration for scheduler\n this._heartbeatConfig = {\n enabled: true,\n interval: EnhancedSecureWebRTCManager.TIMEOUTS.HEARTBEAT_INTERVAL,\n lastHeartbeat: 0\n };\n }\n\n stopHeartbeat() {\n // Heartbeat stopped via unified scheduler\n if (this._heartbeatConfig) {\n this._heartbeatConfig.enabled = false;\n }\n }\n\n /**\n * Stop all active timers and cleanup scheduler\n */\n _stopAllTimers() {\n this._secureLog('info', '\uD83D\uDD27 Stopping all timers and cleanup scheduler');\n \n // Stop maintenance scheduler\n if (this._maintenanceScheduler) {\n clearInterval(this._maintenanceScheduler);\n this._maintenanceScheduler = null;\n }\n \n // Stop heartbeat\n if (this._heartbeatConfig) {\n this._heartbeatConfig.enabled = false;\n }\n \n // Clear all timer references\n if (this._activeTimers) {\n this._activeTimers.forEach(timer => {\n if (timer) clearInterval(timer);\n });\n this._activeTimers.clear();\n }\n \n this._secureLog('info', '\u2705 All timers stopped successfully');\n }\n\n handleHeartbeat() {\n console.log('Heartbeat received - connection alive');\n }\n\n waitForIceGathering() {\n return new Promise((resolve) => {\n if (this.peerConnection.iceGatheringState === 'complete') {\n resolve();\n return;\n }\n\n const checkState = () => {\n if (this.peerConnection && this.peerConnection.iceGatheringState === 'complete') {\n this.peerConnection.removeEventListener('icegatheringstatechange', checkState);\n resolve();\n }\n };\n \n this.peerConnection.addEventListener('icegatheringstatechange', checkState);\n \n setTimeout(() => {\n if (this.peerConnection) {\n this.peerConnection.removeEventListener('icegatheringstatechange', checkState);\n }\n resolve();\n }, EnhancedSecureWebRTCManager.TIMEOUTS.ICE_GATHERING_TIMEOUT);\n });\n }\n\n retryConnection() {\n console.log(`Retrying connection (attempt ${this.connectionAttempts}/${this.maxConnectionAttempts})`);\n this.onStatusChange('retrying');\n }\n\n isConnected() {\n const hasDataChannel = !!this.dataChannel;\n const dataChannelState = this.dataChannel?.readyState;\n const isDataChannelOpen = dataChannelState === 'open';\n const isVerified = this.isVerified;\n const connectionState = this.peerConnection?.connectionState;\n \n return this.dataChannel && this.dataChannel.readyState === 'open' && this.isVerified;\n }\n\n getConnectionInfo() {\n return {\n fingerprint: this.keyFingerprint,\n isConnected: this.isConnected(),\n isVerified: this.isVerified,\n connectionState: this.peerConnection?.connectionState,\n iceConnectionState: this.peerConnection?.iceConnectionState,\n verificationCode: this.verificationCode\n };\n }\n\n disconnect() {\n // Stop all timers first\n this._stopAllTimers();\n \n if (this.fileTransferSystem) {\n this.fileTransferSystem.cleanup();\n }\n this.intentionalDisconnect = true;\n \n window.EnhancedSecureCryptoUtils.secureLog.log('info', 'Starting intentional disconnect');\n\n this.sendDisconnectNotification();\n\n setTimeout(() => {\n this.sendDisconnectNotification(); \n }, 100);\n\n document.dispatchEvent(new CustomEvent('peer-disconnect', {\n detail: { \n reason: 'user_disconnect',\n timestamp: Date.now()\n }\n }));\n }\n \n handleUnexpectedDisconnect() {\n this.sendDisconnectNotification();\n this.isVerified = false;\n \n // Ensure disconnect notification wasn't already sent\n if (!this.disconnectNotificationSent) {\n this.disconnectNotificationSent = true;\n this.deliverMessageToUI('\uD83D\uDD0C Connection lost. Attempting to reconnect...', 'system');\n }\n \n // Cleanup file transfer system on unexpected disconnect\n if (this.fileTransferSystem) {\n console.log('\uD83E\uDDF9 Cleaning up file transfer system on unexpected disconnect...');\n this.fileTransferSystem.cleanup();\n this.fileTransferSystem = null;\n }\n \n document.dispatchEvent(new CustomEvent('peer-disconnect', {\n detail: { \n reason: 'connection_lost',\n timestamp: Date.now()\n }\n }));\n\n }\n \n sendDisconnectNotification() {\n try {\n if (this.dataChannel && this.dataChannel.readyState === 'open') {\n const notification = {\n type: 'peer_disconnect',\n timestamp: Date.now(),\n reason: this.intentionalDisconnect ? 'user_disconnect' : 'connection_lost'\n };\n\n for (let i = 0; i < 3; i++) {\n try {\n this.dataChannel.send(JSON.stringify(notification));\n window.EnhancedSecureCryptoUtils.secureLog.log('info', 'Disconnect notification sent', {\n reason: notification.reason,\n attempt: i + 1\n });\n break;\n } catch (sendError) {\n if (i === 2) { \n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'Failed to send disconnect notification', {\n error: sendError.message\n });\n }\n }\n }\n }\n } catch (error) {\n window.EnhancedSecureCryptoUtils.secureLog.log('error', 'Could not send disconnect notification', {\n error: error.message\n });\n }\n }\n \n attemptReconnection() {\n // Ensure reconnection-failed notification wasn't already sent\n if (!this.reconnectionFailedNotificationSent) {\n this.reconnectionFailedNotificationSent = true;\n this.deliverMessageToUI('\u274C Unable to reconnect. A new connection is required.', 'system');\n }\n\n }\n \n handlePeerDisconnectNotification(data) {\n const reason = data.reason || 'unknown';\n const reasonText = reason === 'user_disconnect' ? 'manually disconnected.' : 'connection lost.';\n \n // Ensure peer-disconnect notification wasn't already sent\n if (!this.peerDisconnectNotificationSent) {\n this.peerDisconnectNotificationSent = true;\n this.deliverMessageToUI(`\uD83D\uDC4B Peer ${reasonText}`, 'system');\n }\n \n this.onStatusChange('peer_disconnected');\n \n this.intentionalDisconnect = false;\n this.isVerified = false;\n this.stopHeartbeat();\n \n this.onKeyExchange(''); \n this.onVerificationRequired(''); \n\n document.dispatchEvent(new CustomEvent('peer-disconnect', {\n detail: { \n reason: reason,\n timestamp: Date.now()\n }\n }));\n\n setTimeout(() => {\n this.disconnect();\n }, 2000);\n \n window.EnhancedSecureCryptoUtils.secureLog.log('info', 'Peer disconnect notification processed', {\n reason: reason\n });\n }\n \n /**\n * Secure disconnect with complete memory cleanup\n */\n disconnect() {\n this.stopHeartbeat();\n this.isVerified = false;\n this.processedMessageIds.clear();\n this.messageCounter = 0;\n \n // Secure cleanup of cryptographic materials\n this._secureCleanupCryptographicMaterials();\n \n // Secure wipe of PFS key versions\n this.keyVersions.clear();\n this.oldKeys.clear();\n this.currentKeyVersion = 0;\n this.lastKeyRotation = Date.now();\n \n // Reset message counters\n this.sequenceNumber = 0;\n this.expectedSequenceNumber = 0;\n this.replayWindow.clear(); // Clear replay window\n \n // Reset security features\n this.securityFeatures = {\n hasEncryption: true,\n hasECDH: true,\n hasECDSA: true, \n hasMutualAuth: true, \n hasMetadataProtection: true, \n hasEnhancedReplayProtection: true, \n hasNonExtractableKeys: true, \n hasRateLimiting: true, \n hasEnhancedValidation: true, \n hasPFS: true \n };\n \n // Close connections\n if (this.dataChannel) {\n this.dataChannel.close();\n this.dataChannel = null;\n }\n if (this.peerConnection) {\n this.peerConnection.close();\n this.peerConnection = null;\n }\n \n // Secure wipe of message queue\n if (this.messageQueue && this.messageQueue.length > 0) {\n this.messageQueue.forEach((message, index) => {\n this._secureWipeMemory(message, `messageQueue[${index}]`);\n });\n this.messageQueue = [];\n }\n \n // Force garbage collection\n this._forceGarbageCollection();\n \n document.dispatchEvent(new CustomEvent('connection-cleaned', {\n detail: { \n timestamp: Date.now(),\n reason: this.intentionalDisconnect ? 'user_cleanup' : 'automatic_cleanup'\n }\n }));\n\n // Notify UI about complete cleanup\n this.onStatusChange('disconnected');\n this.onKeyExchange('');\n this.onVerificationRequired('');\n \n this._secureLog('info', '\uD83D\uDD12 Connection securely cleaned up with complete memory wipe');\n \n // Reset the intentional disconnect flag\n this.intentionalDisconnect = false;\n }\n // Public method to send files\n async sendFile(file) {\n // Enforce verification gate for file transfers\n this._enforceVerificationGate('sendFile');\n \n if (!this.isConnected()) {\n throw new Error('Connection not ready for file transfer. Please ensure the connection is established.');\n }\n\n if (!this.fileTransferSystem) {\n console.log('\uD83D\uDD04 File transfer system not initialized, attempting to initialize...');\n this.initializeFileTransfer();\n \n // Allow time for initialization\n await new Promise(resolve => setTimeout(resolve, 500));\n \n if (!this.fileTransferSystem) {\n throw new Error('File transfer system could not be initialized. Please try reconnecting.');\n }\n }\n\n // Verify key readiness\n if (!this.encryptionKey || !this.macKey) {\n throw new Error('Encryption keys not ready. Please wait for connection to be fully established.');\n }\n\n // Debug logging for file transfer system\n console.log('\uD83D\uDD0D Debug: File transfer system in sendFile:', {\n hasFileTransferSystem: !!this.fileTransferSystem,\n fileTransferSystemType: this.fileTransferSystem.constructor?.name,\n hasWebrtcManager: !!this.fileTransferSystem.webrtcManager,\n webrtcManagerType: this.fileTransferSystem.webrtcManager?.constructor?.name\n });\n\n try {\n console.log('\uD83D\uDE80 Starting file transfer for:', file.name, `(${(file.size / 1024 / 1024).toFixed(2)} MB)`);\n const fileId = await this.fileTransferSystem.sendFile(file);\n console.log('\u2705 File transfer initiated successfully with ID:', fileId);\n return fileId;\n } catch (error) {\n this._secureLog('error', '\u274C File transfer error:', { errorType: error?.constructor?.name || 'Unknown' });\n \n // Re-throw with a clearer message\n if (error.message.includes('Connection not ready')) {\n throw new Error('Connection not ready for file transfer. Check connection status.');\n } else if (error.message.includes('Encryption keys not initialized')) {\n throw new Error('Encryption keys not initialized. Try reconnecting.');\n } else if (error.message.includes('Transfer timeout')) {\n throw new Error('File transfer timeout. Check connection and try again.');\n } else {\n throw error;\n }\n }\n }\n\n // Get active file transfers\n getFileTransfers() {\n if (!this.fileTransferSystem) {\n return { sending: [], receiving: [] };\n }\n \n try {\n // Check available methods in file transfer system\n let sending = [];\n let receiving = [];\n \n if (typeof this.fileTransferSystem.getActiveTransfers === 'function') {\n sending = this.fileTransferSystem.getActiveTransfers();\n } else {\n this._secureLog('warn', '\u26A0\uFE0F getActiveTransfers method not available in file transfer system');\n }\n \n if (typeof this.fileTransferSystem.getReceivingTransfers === 'function') {\n receiving = this.fileTransferSystem.getReceivingTransfers();\n } else {\n this._secureLog('warn', '\u26A0\uFE0F getReceivingTransfers method not available in file transfer system');\n }\n \n return {\n sending: sending || [],\n receiving: receiving || []\n };\n } catch (error) {\n this._secureLog('error', '\u274C Error getting file transfers:', { errorType: error?.constructor?.name || 'Unknown' });\n return { sending: [], receiving: [] };\n }\n }\n\n // Get file transfer system status\n getFileTransferStatus() {\n if (!this.fileTransferSystem) {\n return {\n initialized: false,\n status: 'not_initialized',\n message: 'File transfer system not initialized'\n };\n }\n \n const activeTransfers = this.fileTransferSystem.getActiveTransfers();\n const receivingTransfers = this.fileTransferSystem.getReceivingTransfers();\n \n return {\n initialized: true,\n status: 'ready',\n activeTransfers: activeTransfers.length,\n receivingTransfers: receivingTransfers.length,\n totalTransfers: activeTransfers.length + receivingTransfers.length\n };\n }\n\n // Cancel file transfer\n cancelFileTransfer(fileId) {\n if (!this.fileTransferSystem) return false;\n return this.fileTransferSystem.cancelTransfer(fileId);\n }\n\n // Force cleanup of file transfer system\n cleanupFileTransferSystem() {\n if (this.fileTransferSystem) {\n console.log('\uD83E\uDDF9 Force cleaning up file transfer system...');\n this.fileTransferSystem.cleanup();\n this.fileTransferSystem = null;\n return true;\n }\n return false;\n }\n\n // Reinitialize file transfer system\n reinitializeFileTransfer() {\n try {\n console.log('\uD83D\uDD04 Reinitializing file transfer system...');\n if (this.fileTransferSystem) {\n this.fileTransferSystem.cleanup();\n }\n this.initializeFileTransfer();\n return true;\n } catch (error) {\n this._secureLog('error', '\u274C Failed to reinitialize file transfer system:', { errorType: error?.constructor?.name || 'Unknown' });\n return false;\n }\n }\n\n // Set file transfer callbacks\n setFileTransferCallbacks(onProgress, onReceived, onError) {\n this.onFileProgress = onProgress;\n this.onFileReceived = onReceived;\n this.onFileError = onError;\n \n console.log('\uD83D\uDD27 File transfer callbacks set:', {\n hasProgress: !!onProgress,\n hasReceived: !!onReceived,\n hasError: !!onError\n });\n \n // Reinitialize file transfer system if it exists to update callbacks\n if (this.fileTransferSystem) {\n console.log('\uD83D\uDD04 Reinitializing file transfer system with new callbacks...');\n this.initializeFileTransfer();\n }\n }\n\n // ============================================\n // SESSION ACTIVATION HANDLING\n // ============================================\n\n async handleSessionActivation(sessionData) {\n try {\n console.log('\uD83D\uDD10 Handling session activation:', sessionData);\n \n // Update session state\n this.currentSession = sessionData;\n this.sessionManager = sessionData.sessionManager;\n \n // FIX: More lenient checks for activation\n const hasKeys = !!(this.encryptionKey && this.macKey);\n const hasSession = !!(this.sessionManager && (this.sessionManager.hasActiveSession?.() || sessionData.sessionId));\n \n console.log('\uD83D\uDD0D Session activation status:', {\n hasKeys: hasKeys,\n hasSession: hasSession,\n sessionType: sessionData.sessionType,\n isDemo: sessionData.isDemo\n });\n \n // Force connection status if there is an active session\n if (hasSession) {\n console.log('\uD83D\uDD13 Session activated - forcing connection status to connected');\n this.onStatusChange('connected');\n \n console.log('\u26A0\uFE0F Session activated but NOT verified - cryptographic verification still required');\n }\n\n setTimeout(() => {\n try {\n this.initializeFileTransfer();\n } catch (error) {\n this._secureLog('warn', '\u26A0\uFE0F File transfer initialization failed during session activation:', { details: error.message });\n }\n }, 1000);\n \n console.log('\u2705 Session activation handled successfully');\n \n if (this.fileTransferSystem && this.isConnected()) {\n console.log('\uD83D\uDD04 Synchronizing file transfer keys after session activation...');\n \n if (typeof this.fileTransferSystem.onSessionUpdate === 'function') {\n this.fileTransferSystem.onSessionUpdate({\n keyFingerprint: this.keyFingerprint,\n sessionSalt: this.sessionSalt,\n hasMacKey: !!this.macKey\n });\n }\n }\n \n } catch (error) {\n this._secureLog('error', '\u274C Failed to handle session activation:', { errorType: error?.constructor?.name || 'Unknown' });\n }\n }\n // Method to check readiness of file transfers\ncheckFileTransferReadiness() {\n const status = {\n hasFileTransferSystem: !!this.fileTransferSystem,\n hasDataChannel: !!this.dataChannel,\n dataChannelState: this.dataChannel?.readyState,\n isConnected: this.isConnected(),\n isVerified: this.isVerified,\n hasEncryptionKey: !!this.encryptionKey,\n hasMacKey: !!this.macKey,\n ready: false\n };\n \n status.ready = status.hasFileTransferSystem && \n status.hasDataChannel && \n status.dataChannelState === 'open' && \n status.isConnected && \n status.isVerified;\n \n console.log('\uD83D\uDD0D File transfer readiness check:', status);\n return status;\n }\n\n // Method to force re-initialize file transfer system\n forceReinitializeFileTransfer() {\n try {\n console.log('\uD83D\uDD04 Force reinitializing file transfer system...');\n \n if (this.fileTransferSystem) {\n this.fileTransferSystem.cleanup();\n this.fileTransferSystem = null;\n }\n \n // Small delay before reinitialization\n setTimeout(() => {\n this.initializeFileTransfer();\n }, 500);\n \n return true;\n } catch (error) {\n this._secureLog('error', '\u274C Failed to force reinitialize file transfer:', { errorType: error?.constructor?.name || 'Unknown' });\n return false;\n }\n }\n\n // Method to get diagnostic information\n getFileTransferDiagnostics() {\n const diagnostics = {\n timestamp: new Date().toISOString(),\n webrtcManager: {\n hasDataChannel: !!this.dataChannel,\n dataChannelState: this.dataChannel?.readyState,\n isConnected: this.isConnected(),\n isVerified: this.isVerified,\n isInitiator: this.isInitiator,\n hasEncryptionKey: !!this.encryptionKey,\n hasMacKey: !!this.macKey,\n hasMetadataKey: !!this.metadataKey,\n hasKeyFingerprint: !!this.keyFingerprint,\n hasSessionSalt: !!this.sessionSalt\n },\n fileTransferSystem: null,\n globalState: {\n fileTransferActive: this._fileTransferActive || false,\n hasFileTransferSystem: !!this.fileTransferSystem,\n fileTransferSystemType: this.fileTransferSystem ? 'EnhancedSecureFileTransfer' : 'none'\n }\n };\n \n if (this.fileTransferSystem) {\n try {\n diagnostics.fileTransferSystem = this.fileTransferSystem.getSystemStatus();\n } catch (error) {\n diagnostics.fileTransferSystem = { error: error.message };\n }\n }\n \n return diagnostics;\n }\n\n getSupportedFileTypes() {\n if (!this.fileTransferSystem) {\n return { error: 'File transfer system not initialized' };\n }\n \n try {\n return this.fileTransferSystem.getSupportedFileTypes();\n } catch (error) {\n return { error: error.message };\n }\n }\n\n validateFile(file) {\n if (!this.fileTransferSystem) {\n return { \n isValid: false, \n errors: ['File transfer system not initialized'],\n fileType: null,\n fileSize: file?.size || 0,\n formattedSize: '0 B'\n };\n }\n \n try {\n return this.fileTransferSystem.validateFile(file);\n } catch (error) {\n return { \n isValid: false, \n errors: [error.message],\n fileType: null,\n fileSize: file?.size || 0,\n formattedSize: '0 B'\n };\n }\n }\n\n getFileTypeInfo() {\n if (!this.fileTransferSystem) {\n return { error: 'File transfer system not initialized' };\n }\n \n try {\n return this.fileTransferSystem.getFileTypeInfo();\n } catch (error) {\n return { error: error.message };\n }\n }\n\n async forceInitializeFileTransfer(options = {}) {\n const abortController = new AbortController();\n const { signal = abortController.signal, timeout = 6000 } = options;\n\n if (signal && signal !== abortController.signal) {\n signal.addEventListener('abort', () => abortController.abort());\n }\n try {\n if (!this.isVerified) {\n throw new Error('Connection not verified');\n }\n \n if (!this.dataChannel || this.dataChannel.readyState !== 'open') {\n throw new Error('Data channel not open');\n }\n \n if (!this.encryptionKey || !this.macKey) {\n throw new Error('Encryption keys not ready');\n }\n\n if (this.fileTransferSystem) {\n this.fileTransferSystem.cleanup();\n this.fileTransferSystem = null;\n }\n\n this.initializeFileTransfer();\n\n let attempts = 0;\n const maxAttempts = 50;\n const checkInterval = 100; \n const maxWaitTime = maxAttempts * checkInterval; \n\n const initializationPromise = new Promise((resolve, reject) => {\n const checkInitialization = () => {\n if (abortController.signal.aborted) {\n reject(new Error('Operation cancelled'));\n return;\n }\n \n if (this.fileTransferSystem) {\n resolve(true);\n return;\n }\n \n if (attempts >= maxAttempts) {\n reject(new Error(`Initialization timeout after ${maxWaitTime}ms`));\n return;\n }\n \n attempts++;\n setTimeout(checkInitialization, checkInterval);\n };\n \n checkInitialization();\n });\n\n await Promise.race([\n initializationPromise,\n new Promise((_, reject) => \n setTimeout(() => reject(new Error(`Global timeout after ${timeout}ms`)), timeout)\n )\n ]);\n \n if (this.fileTransferSystem) {\n return true;\n } else {\n throw new Error('Force initialization timeout');\n }\n \n } catch (error) {\n if (error.name === 'AbortError' || error.message.includes('cancelled')) {\n this._secureLog('info', '\u23F9\uFE0F File transfer initialization cancelled by user');\n return { cancelled: true };\n }\n \n this._secureLog('error', '\u274C Force file transfer initialization failed:', { \n errorType: error?.constructor?.name || 'Unknown',\n message: error.message,\n attempts: attempts\n });\n return { error: error.message, attempts: attempts };\n }\n }\n\n cancelFileTransferInitialization() {\n try {\n if (this.fileTransferSystem) {\n this.fileTransferSystem.cleanup();\n this.fileTransferSystem = null;\n this._fileTransferActive = false;\n this._secureLog('info', '\u23F9\uFE0F File transfer initialization cancelled');\n return true;\n }\n return false;\n } catch (error) {\n this._secureLog('error', '\u274C Failed to cancel file transfer initialization:', { \n errorType: error?.constructor?.name || 'Unknown' \n });\n return false;\n }\n }\n \n getFileTransferSystemStatus() {\n if (!this.fileTransferSystem) {\n return { available: false, status: 'not_initialized' };\n }\n \n try {\n const status = this.fileTransferSystem.getSystemStatus();\n return {\n available: true,\n status: status.status || 'unknown',\n activeTransfers: status.activeTransfers || 0,\n receivingTransfers: status.receivingTransfers || 0,\n systemType: 'EnhancedSecureFileTransfer'\n };\n } catch (error) {\n this._secureLog('error', '\u274C Failed to get file transfer system status:', { \n errorType: error?.constructor?.name || 'Unknown' \n });\n return { available: false, status: 'error', error: error.message };\n }\n }\n\n _validateNestedEncryptionSecurity() {\n if (this.securityFeatures.hasNestedEncryption && this.nestedEncryptionKey) {\n // Test secure IV generation with reuse prevention\n try {\n const testIV1 = this._generateSecureIV(EnhancedSecureWebRTCManager.SIZES.NESTED_ENCRYPTION_IV_SIZE, 'securityTest1');\n const testIV2 = this._generateSecureIV(EnhancedSecureWebRTCManager.SIZES.NESTED_ENCRYPTION_IV_SIZE, 'securityTest2');\n \n // Verify IVs are different and properly tracked\n if (testIV1.every((byte, index) => byte === testIV2[index])) {\n this._secureLog('error', '\u274C CRITICAL: Nested encryption security validation failed - IVs are identical!');\n return false;\n }\n \n // Verify IV tracking system is working\n const stats = this._getIVTrackingStats();\n if (stats.totalIVs < 2) {\n this._secureLog('error', '\u274C CRITICAL: IV tracking system not working properly');\n return false;\n }\n \n this._secureLog('info', '\u2705 Nested encryption security validation passed - secure IV generation working');\n return true;\n } catch (error) {\n this._secureLog('error', '\u274C CRITICAL: Nested encryption security validation failed:', {\n errorType: error.constructor.name,\n errorMessage: error.message\n });\n return false;\n }\n }\n return true;\n }\n}\n\nclass SecureKeyStorage {\n constructor() {\n // Use WeakMap for automatic garbage collection of unused keys\n this._keyStore = new WeakMap();\n this._keyMetadata = new Map(); // Metadata doesn't need WeakMap\n this._keyReferences = new Map(); // Strong references for active keys\n \n // Master encryption key for storage encryption\n this._storageMasterKey = null;\n this._initializeStorageMaster();\n\n setTimeout(() => {\n if (!this.validateStorageIntegrity()) {\n console.error('\u274C CRITICAL: Key storage integrity check failed');\n }\n }, 100);\n \n }\n\n async _initializeStorageMaster() {\n // Generate a master key for encrypting stored keys\n this._storageMasterKey = await crypto.subtle.generateKey(\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt', 'decrypt']\n );\n }\n\n async storeKey(keyId, cryptoKey, metadata = {}) {\n if (!(cryptoKey instanceof CryptoKey)) {\n throw new Error('Only CryptoKey objects can be stored');\n }\n\n try {\n // For non-extractable keys, we can only store a reference\n if (!cryptoKey.extractable) {\n // Store the key reference directly without encryption\n this._keyReferences.set(keyId, cryptoKey);\n this._keyMetadata.set(keyId, {\n ...metadata,\n created: Date.now(),\n lastAccessed: Date.now(),\n extractable: false,\n encrypted: false // Mark as not encrypted\n });\n return true;\n }\n\n // For extractable keys, proceed with encryption\n const keyData = await crypto.subtle.exportKey('jwk', cryptoKey);\n const encryptedKeyData = await this._encryptKeyData(keyData);\n \n // Validate that extractable keys are properly encrypted\n if (!encryptedKeyData || encryptedKeyData.byteLength === 0) {\n throw new Error('Failed to encrypt extractable key data');\n }\n\n // Create a storage object\n const storageObject = {\n id: keyId,\n encryptedData: encryptedKeyData,\n algorithm: cryptoKey.algorithm,\n usages: cryptoKey.usages,\n extractable: cryptoKey.extractable,\n type: cryptoKey.type,\n timestamp: Date.now()\n };\n\n // Use WeakMap with the CryptoKey as the key\n this._keyStore.set(cryptoKey, storageObject);\n \n // Store reference for retrieval by ID\n this._keyReferences.set(keyId, cryptoKey);\n \n // Store metadata separately\n this._keyMetadata.set(keyId, {\n ...metadata,\n created: Date.now(),\n lastAccessed: Date.now(),\n extractable: true,\n encrypted: true // Mark extractable keys as encrypted\n });\n\n return true;\n } catch (error) {\n console.error('Failed to store key securely:', error);\n return false;\n }\n }\n\n async retrieveKey(keyId) {\n const metadata = this._keyMetadata.get(keyId);\n if (!metadata) {\n return null;\n }\n\n // Update access time\n metadata.lastAccessed = Date.now();\n\n // For non-encrypted keys (non-extractable), return directly\n if (!metadata.encrypted) {\n // Only non-extractable keys should be non-encrypted\n if (metadata.extractable === false) {\n return this._keyReferences.get(keyId);\n } else {\n // This should never happen - extractable keys must be encrypted\n this._secureLog('error', '\u274C SECURITY VIOLATION: Extractable key marked as non-encrypted', {\n keyId,\n extractable: metadata.extractable,\n encrypted: metadata.encrypted\n });\n return null;\n }\n }\n\n // For encrypted keys, decrypt and recreate\n try {\n const cryptoKey = this._keyReferences.get(keyId);\n const storedData = this._keyStore.get(cryptoKey);\n \n if (!storedData) {\n return null;\n }\n\n // Decrypt the key data\n const decryptedKeyData = await this._decryptKeyData(storedData.encryptedData);\n \n // Recreate the CryptoKey\n const recreatedKey = await crypto.subtle.importKey(\n 'jwk',\n decryptedKeyData,\n storedData.algorithm,\n storedData.extractable,\n storedData.usages\n );\n \n return recreatedKey;\n } catch (error) {\n console.error('Failed to retrieve key:', error);\n return null;\n }\n }\n\n async _encryptKeyData(keyData) {\n const dataToEncrypt = typeof keyData === 'object' \n ? JSON.stringify(keyData) \n : keyData;\n \n const encoder = new TextEncoder();\n const data = encoder.encode(dataToEncrypt);\n \n const iv = crypto.getRandomValues(new Uint8Array(12));\n \n const encryptedData = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n this._storageMasterKey,\n data\n );\n\n // Return IV + encrypted data\n const result = new Uint8Array(iv.length + encryptedData.byteLength);\n result.set(iv, 0);\n result.set(new Uint8Array(encryptedData), iv.length);\n \n return result;\n }\n\n async _decryptKeyData(encryptedData) {\n const iv = encryptedData.slice(0, 12);\n const data = encryptedData.slice(12);\n \n const decryptedData = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv },\n this._storageMasterKey,\n data\n );\n\n const decoder = new TextDecoder();\n const jsonString = decoder.decode(decryptedData);\n \n try {\n return JSON.parse(jsonString);\n } catch {\n return decryptedData;\n }\n }\n\n secureWipe(keyId) {\n const cryptoKey = this._keyReferences.get(keyId);\n \n if (cryptoKey) {\n // Remove from WeakMap (will be GC'd)\n this._keyStore.delete(cryptoKey);\n // Remove strong reference\n this._keyReferences.delete(keyId);\n // Remove metadata\n this._keyMetadata.delete(keyId);\n }\n\n // Overwrite memory locations if possible\n if (typeof window.gc === 'function') {\n window.gc();\n }\n }\n\n secureWipeAll() {\n // Clear all references\n this._keyReferences.clear();\n this._keyMetadata.clear();\n \n // WeakMap entries will be garbage collected\n this._keyStore = new WeakMap();\n \n // Force garbage collection if available\n if (typeof window.gc === 'function') {\n window.gc();\n }\n }\n\n // Validate storage integrity\n validateStorageIntegrity() {\n const violations = [];\n \n for (const [keyId, metadata] of this._keyMetadata.entries()) {\n // Check: extractable keys must be encrypted\n if (metadata.extractable === true && metadata.encrypted !== true) {\n violations.push({\n keyId,\n type: 'EXTRACTABLE_KEY_NOT_ENCRYPTED',\n metadata\n });\n }\n \n // Check: non-extractable keys should not be encrypted\n if (metadata.extractable === false && metadata.encrypted === true) {\n violations.push({\n keyId,\n type: 'NON_EXTRACTABLE_KEY_ENCRYPTED',\n metadata\n });\n }\n }\n \n if (violations.length > 0) {\n console.error('\u274C Storage integrity violations detected:', violations);\n return false;\n }\n \n return true;\n }\n\n getStorageStats() {\n return {\n totalKeys: this._keyReferences.size,\n metadata: Array.from(this._keyMetadata.entries()).map(([id, meta]) => ({\n id,\n created: meta.created,\n lastAccessed: meta.lastAccessed,\n age: Date.now() - meta.created\n }))\n };\n }\n\n // Method _generateNextSequenceNumber moved to constructor area for early availability\n\n /**\n * Validate incoming message sequence number\n * This prevents replay attacks and ensures message ordering\n */\n _validateIncomingSequenceNumber(receivedSeq, context = 'unknown') {\n try {\n if (!this.replayProtectionEnabled) {\n return true; // Skip validation if disabled\n }\n\n // Check if sequence number is within acceptable range\n if (receivedSeq < this.expectedSequenceNumber - this.replayWindowSize) {\n this._secureLog('warn', '\u26A0\uFE0F Sequence number too old - possible replay attack', {\n received: receivedSeq,\n expected: this.expectedSequenceNumber,\n context: context,\n timestamp: Date.now()\n });\n return false;\n }\n\n // Check if sequence number is too far ahead (DoS protection)\n if (receivedSeq > this.expectedSequenceNumber + this.maxSequenceGap) {\n this._secureLog('warn', '\u26A0\uFE0F Sequence number gap too large - possible DoS attack', {\n received: receivedSeq,\n expected: this.expectedSequenceNumber,\n gap: receivedSeq - this.expectedSequenceNumber,\n context: context,\n timestamp: Date.now()\n });\n return false;\n }\n\n // Check if sequence number is already in replay window\n if (this.replayWindow.has(receivedSeq)) {\n this._secureLog('warn', '\u26A0\uFE0F Duplicate sequence number detected - replay attack', {\n received: receivedSeq,\n context: context,\n timestamp: Date.now()\n });\n return false;\n }\n\n // Add to replay window\n this.replayWindow.add(receivedSeq);\n \n // Maintain sliding window size\n if (this.replayWindow.size > this.replayWindowSize) {\n const oldestSeq = Math.min(...this.replayWindow);\n this.replayWindow.delete(oldestSeq);\n }\n\n // Update expected sequence number if this is the next expected\n if (receivedSeq === this.expectedSequenceNumber) {\n this.expectedSequenceNumber++;\n \n // Clean up replay window entries that are no longer needed\n while (this.replayWindow.has(this.expectedSequenceNumber - this.replayWindowSize - 1)) {\n this.replayWindow.delete(this.expectedSequenceNumber - this.replayWindowSize - 1);\n }\n }\n\n this._secureLog('debug', '\u2705 Sequence number validation successful', {\n received: receivedSeq,\n expected: this.expectedSequenceNumber,\n context: context,\n timestamp: Date.now()\n });\n\n return true;\n } catch (error) {\n this._secureLog('error', '\u274C Sequence number validation failed', {\n error: error.message,\n context: context,\n timestamp: Date.now()\n });\n return false;\n }\n }\n\n // Method _createMessageAAD moved to constructor area for early availability\n\n /**\n * Validate message AAD with sequence number\n * This ensures message integrity and prevents replay attacks\n */\n _validateMessageAAD(aadString, expectedMessageType = null) {\n try {\n const aad = JSON.parse(aadString);\n \n // Validate session binding\n if (aad.sessionId !== (this.currentSession?.sessionId || 'unknown')) {\n throw new Error('AAD sessionId mismatch - possible replay attack');\n }\n \n if (aad.keyFingerprint !== (this.keyFingerprint || 'unknown')) {\n throw new Error('AAD keyFingerprint mismatch - possible key substitution attack');\n }\n \n // Validate sequence number\n if (!this._validateIncomingSequenceNumber(aad.sequenceNumber, aad.messageType)) {\n throw new Error('Sequence number validation failed - possible replay or DoS attack');\n }\n \n // Validate message type if specified\n if (expectedMessageType && aad.messageType !== expectedMessageType) {\n throw new Error(`AAD messageType mismatch - expected ${expectedMessageType}, got ${aad.messageType}`);\n }\n \n return aad;\n } catch (error) {\n this._secureLog('error', 'AAD validation failed', { error: error.message, aadString });\n throw new Error(`AAD validation failed: ${error.message}`);\n }\n }\n\n /**\n * Get anti-replay protection status\n * This shows the current state of replay protection\n */\n getAntiReplayStatus() {\n const status = {\n replayProtectionEnabled: this.replayProtectionEnabled,\n replayWindowSize: this.replayWindowSize,\n currentReplayWindowSize: this.replayWindow.size,\n sequenceNumber: this.sequenceNumber,\n expectedSequenceNumber: this.expectedSequenceNumber,\n maxSequenceGap: this.maxSequenceGap,\n replayWindowEntries: Array.from(this.replayWindow).sort((a, b) => a - b)\n };\n\n this._secureLog('info', 'Anti-replay status retrieved', status);\n return status;\n }\n\n /**\n * Configure anti-replay protection\n * This allows fine-tuning of replay protection parameters\n */\n configureAntiReplayProtection(config) {\n try {\n if (config.windowSize !== undefined) {\n if (config.windowSize < 16 || config.windowSize > 1024) {\n throw new Error('Replay window size must be between 16 and 1024');\n }\n this.replayWindowSize = config.windowSize;\n }\n\n if (config.maxGap !== undefined) {\n if (config.maxGap < 10 || config.maxGap > 1000) {\n throw new Error('Max sequence gap must be between 10 and 1000');\n }\n this.maxSequenceGap = config.maxGap;\n }\n\n if (config.enabled !== undefined) {\n this.replayProtectionEnabled = config.enabled;\n }\n\n this._secureLog('info', 'Anti-replay protection configured', config);\n return true;\n } catch (error) {\n this._secureLog('error', 'Failed to configure anti-replay protection', { error: error.message });\n return false;\n }\n }\n\n\n}\n\nexport { EnhancedSecureWebRTCManager };", "class PayPerSessionManager {\n constructor(config = {}) {\n this.sessionPrices = {\n demo: { sats: 0, hours: 0.1, usd: 0.00, securityLevel: 'basic' }, \n basic: { sats: 5000, hours: 1, usd: 2.00, securityLevel: 'enhanced' },\n premium: { sats: 20000, hours: 6, usd: 8.00, securityLevel: 'maximum' }\n };\n \n this.currentSession = null;\n this.sessionTimer = null;\n this.onSessionExpired = null;\n this.staticLightningAddress = \"dullpastry62@walletofsatoshi.com\";\n \n // Storage of used preimage to prevent reuse\n this.usedPreimages = new Set();\n this.preimageCleanupInterval = null;\n \n // FIXED DEMO mode: Stricter control\n this.demoSessions = new Map(); \n this.maxDemoSessionsPerUser = 3; \n this.demoCooldownPeriod = 24 * 60 * 60 * 1000; \n this.demoSessionCooldown = 1 * 60 * 1000; \n this.demoSessionMaxDuration = 6 * 60 * 1000; \n \n // NEW: Global tracking of active demo sessions\n this.activeDemoSessions = new Set(); \n this.maxGlobalDemoSessions = 10; \n \n // NEW: Tracking of terminated sessions to prevent rapid reconnection\n this.completedDemoSessions = new Map(); \n this.minTimeBetweenCompletedSessions = 15 * 60 * 1000; \n\n // Minimum cost for paid sessions (protection against micropayment attacks)\n this.minimumPaymentSats = 1000;\n \n this.verificationConfig = {\n method: config.method || 'lnbits',\n apiUrl: config.apiUrl || 'https://demo.lnbits.com',\n apiKey: config.apiKey || 'a7226682253f4dd7bdb2d9487a9a59f8', \n walletId: config.walletId || '649903697b03457d8b12c4eae7b2fab9',\n isDemo: config.isDemo !== undefined ? config.isDemo : true,\n demoTimeout: 30000, \n retryAttempts: 3,\n invoiceExpiryMinutes: 15\n };\n \n // Rate limiting for API requests\n this.lastApiCall = 0;\n this.apiCallMinInterval = 1000; \n \n // Run periodic tasks\n this.startPreimageCleanup();\n this.startDemoSessionCleanup();\n this.startActiveDemoSessionCleanup();\n \n this.globalDemoCounter = 0;\n this.memoryStorage = new Map();\n this.currentTabId = null;\n this.tabHeartbeatInterval = null;\n this.initializePersistentStorage();\n this.performEnhancedCleanup();\n const multiTabCheck = this.checkMultiTabProtection();\n if (!multiTabCheck.allowed) {\n console.warn('\u274C Multi-tab protection triggered:', multiTabCheck.message);\n }\n \n console.log('\uD83D\uDCB0 PayPerSessionManager initialized with TIERED security levels');\n \n setInterval(() => {\n this.savePersistentData();\n }, 30000);\n this.notifySecurityUpdate = () => {\n document.dispatchEvent(new CustomEvent('security-level-updated', {\n detail: { timestamp: Date.now(), manager: 'webrtc' }\n }));\n };\n console.log('\uD83D\uDCB0 PayPerSessionManager initialized with ENHANCED secure demo mode and auto-save');\n }\n\n getSecurityLevelForSession(sessionType) {\n const pricing = this.sessionPrices[sessionType];\n if (!pricing) return 'basic';\n \n return pricing.securityLevel || 'basic';\n }\n\n // Check if the function is allowed for the given session type\n isFeatureAllowedForSession(sessionType, feature) {\n const securityLevel = this.getSecurityLevelForSession(sessionType);\n \n const featureMatrix = {\n 'basic': {\n // DEMO \u0441\u0435\u0441\u0441\u0438\u0438 - \u0442\u043E\u043B\u044C\u043A\u043E \u0431\u0430\u0437\u043E\u0432\u044B\u0435 \u0444\u0443\u043D\u043A\u0446\u0438\u0438\n hasEncryption: true,\n hasECDH: true,\n hasECDSA: false,\n hasMutualAuth: false,\n hasMetadataProtection: false,\n hasEnhancedReplayProtection: false,\n hasNonExtractableKeys: false,\n hasRateLimiting: true,\n hasEnhancedValidation: false,\n hasPFS: false,\n \n // Advanced features are DISABLED for demo\n hasNestedEncryption: false,\n hasPacketPadding: false,\n hasPacketReordering: false,\n hasAntiFingerprinting: false,\n hasFakeTraffic: false,\n hasDecoyChannels: false,\n hasMessageChunking: false\n },\n 'enhanced': {\n // BASIC paid sessions - improved security\n hasEncryption: true,\n hasECDH: true,\n hasECDSA: true,\n hasMutualAuth: true,\n hasMetadataProtection: true,\n hasEnhancedReplayProtection: true,\n hasNonExtractableKeys: true,\n hasRateLimiting: true,\n hasEnhancedValidation: true,\n hasPFS: true,\n \n // Partially enabled advanced features\n hasNestedEncryption: true,\n hasPacketPadding: true,\n hasPacketReordering: false, \n hasAntiFingerprinting: false,\n hasFakeTraffic: false, \n hasDecoyChannels: false,\n hasMessageChunking: false\n },\n 'maximum': {\n // PREMIUM sessions - all functions included\n hasEncryption: true,\n hasECDH: true,\n hasECDSA: true,\n hasMutualAuth: true,\n hasMetadataProtection: true,\n hasEnhancedReplayProtection: true,\n hasNonExtractableKeys: true,\n hasRateLimiting: true,\n hasEnhancedValidation: true,\n hasPFS: true,\n \n // ALL advanced features\n hasNestedEncryption: true,\n hasPacketPadding: true,\n hasPacketReordering: true,\n hasAntiFingerprinting: true,\n hasFakeTraffic: true,\n hasDecoyChannels: true,\n hasMessageChunking: true\n }\n };\n\n return featureMatrix[securityLevel]?.[feature] || false;\n }\n\n // ============================================\n // FIXED DEMO MODE: Improved controls and management\n // ============================================\n\n startActiveDemoSessionCleanup() {\n setInterval(() => {\n const now = Date.now();\n let cleanedCount = 0;\n \n for (const preimage of this.activeDemoSessions) {\n const demoTimestamp = this.extractDemoTimestamp(preimage);\n if (demoTimestamp && (now - demoTimestamp) > this.demoSessionMaxDuration) {\n this.activeDemoSessions.delete(preimage);\n cleanedCount++;\n }\n }\n \n if (cleanedCount > 0) {\n console.log(`\uD83E\uDDF9 Cleaned ${cleanedCount} expired active demo sessions`);\n }\n }, 30000); \n }\n \n\n startDemoSessionCleanup() {\n setInterval(() => {\n const now = Date.now();\n const maxAge = 25 * 60 * 60 * 1000; \n \n let cleanedCount = 0;\n for (const [identifier, data] of this.demoSessions.entries()) {\n if (now - data.lastUsed > maxAge) {\n this.demoSessions.delete(identifier);\n cleanedCount++;\n }\n \n if (data.sessions) {\n const originalCount = data.sessions.length;\n data.sessions = data.sessions.filter(session => \n now - session.timestamp < maxAge\n );\n \n if (data.sessions.length === 0 && now - data.lastUsed > maxAge) {\n this.demoSessions.delete(identifier);\n cleanedCount++;\n }\n }\n }\n \n for (const [identifier, sessions] of this.completedDemoSessions.entries()) {\n const filteredSessions = sessions.filter(session => \n now - session.endTime < maxAge\n );\n \n if (filteredSessions.length === 0) {\n this.completedDemoSessions.delete(identifier);\n } else {\n this.completedDemoSessions.set(identifier, filteredSessions);\n }\n }\n \n if (cleanedCount > 0) {\n console.log(`\uD83E\uDDF9 Cleaned ${cleanedCount} old demo session records`);\n }\n }, 60 * 60 * 1000); \n }\n\n // IMPROVED user fingerprint generation\n generateAdvancedUserFingerprint() {\n try {\n const basicComponents = [\n navigator.userAgent || '',\n navigator.language || '',\n screen.width + 'x' + screen.height,\n Intl.DateTimeFormat().resolvedOptions().timeZone || '',\n navigator.hardwareConcurrency || 0,\n navigator.deviceMemory || 0,\n navigator.platform || '',\n navigator.cookieEnabled ? '1' : '0',\n window.screen.colorDepth || 0,\n window.screen.pixelDepth || 0,\n navigator.maxTouchPoints || 0,\n navigator.onLine ? '1' : '0'\n ];\n\n const hardwareComponents = [];\n \n // WebGL fingerprint \n try {\n const canvas = document.createElement('canvas');\n const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');\n if (gl) {\n const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');\n if (debugInfo) {\n hardwareComponents.push(gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) || '');\n hardwareComponents.push(gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) || '');\n }\n hardwareComponents.push(gl.getParameter(gl.VERSION) || '');\n hardwareComponents.push(gl.getParameter(gl.SHADING_LANGUAGE_VERSION) || '');\n }\n } catch (e) {\n hardwareComponents.push('webgl_error');\n }\n\n // Canvas print \n try {\n const canvas = document.createElement('canvas');\n canvas.width = 200;\n canvas.height = 50;\n const ctx = canvas.getContext('2d');\n ctx.textBaseline = 'top';\n ctx.font = '14px Arial';\n ctx.fillText('SecureBit Demo Fingerprint \uD83D\uDD12', 2, 2);\n ctx.fillStyle = 'rgba(255,0,0,0.5)';\n ctx.fillRect(50, 10, 20, 20);\n hardwareComponents.push(canvas.toDataURL());\n } catch (e) {\n hardwareComponents.push('canvas_error');\n }\n\n // Audio fingerprint \n try {\n const audioContext = new (window.AudioContext || window.webkitAudioContext)();\n const oscillator = audioContext.createOscillator();\n const analyser = audioContext.createAnalyser();\n const gain = audioContext.createGain();\n \n oscillator.connect(analyser);\n analyser.connect(gain);\n gain.connect(audioContext.destination);\n \n oscillator.frequency.setValueAtTime(1000, audioContext.currentTime);\n gain.gain.setValueAtTime(0, audioContext.currentTime);\n \n hardwareComponents.push(audioContext.sampleRate.toString());\n hardwareComponents.push(audioContext.state);\n hardwareComponents.push(analyser.frequencyBinCount.toString());\n \n audioContext.close();\n } catch (e) {\n hardwareComponents.push('audio_error');\n }\n\n // CPU Performance \n const cpuBenchmark = this.performCPUBenchmark();\n hardwareComponents.push(cpuBenchmark);\n\n const allComponents = [...basicComponents, ...hardwareComponents];\n\n let primaryHash = 0;\n let secondaryHash = 0;\n let tertiaryHash = 0;\n \n const primaryStr = allComponents.slice(0, 8).join('|');\n const secondaryStr = allComponents.slice(8, 16).join('|');\n const tertiaryStr = allComponents.slice(16).join('|');\n \n for (let i = 0; i < primaryStr.length; i++) {\n const char = primaryStr.charCodeAt(i);\n primaryHash = ((primaryHash << 7) - primaryHash) + char;\n primaryHash = primaryHash & primaryHash;\n }\n\n for (let i = 0; i < secondaryStr.length; i++) {\n const char = secondaryStr.charCodeAt(i);\n secondaryHash = ((secondaryHash << 11) - secondaryHash) + char;\n secondaryHash = secondaryHash & secondaryHash;\n }\n \n for (let i = 0; i < tertiaryStr.length; i++) {\n const char = tertiaryStr.charCodeAt(i);\n tertiaryHash = ((tertiaryHash << 13) - tertiaryHash) + char;\n tertiaryHash = tertiaryHash & tertiaryHash;\n }\n \n const combined = `${Math.abs(primaryHash).toString(36)}_${Math.abs(secondaryHash).toString(36)}_${Math.abs(tertiaryHash).toString(36)}`;\n \n console.log('\uD83D\uDD12 Enhanced fingerprint generated:', {\n components: allComponents.length,\n primaryLength: primaryStr.length,\n secondaryLength: secondaryStr.length,\n tertiaryLength: tertiaryStr.length,\n fingerprintLength: combined.length\n });\n \n return combined;\n \n } catch (error) {\n console.warn('Failed to generate enhanced fingerprint:', error);\n return 'fallback_' + Date.now().toString(36) + '_' + Math.random().toString(36).substr(2, 9);\n }\n }\n\n performCPUBenchmark() {\n const start = performance.now();\n let result = 0;\n \n for (let i = 0; i < 100000; i++) {\n result += Math.sin(i) * Math.cos(i);\n }\n \n const end = performance.now();\n const duration = Math.round(end - start);\n \n if (duration < 5) return 'fast_cpu';\n if (duration < 15) return 'medium_cpu';\n if (duration < 30) return 'slow_cpu';\n return 'very_slow_cpu';\n }\n\n initializePersistentStorage() {\n this.storageKeys = {\n demoSessions: 'sb_demo_sessions_v2',\n completedSessions: 'sb_completed_sessions_v2',\n globalCounter: 'sb_global_demo_counter_v2',\n lastCleanup: 'sb_last_cleanup_v2',\n hardwareFingerprint: 'sb_hw_fingerprint_v2'\n };\n \n this.loadPersistentData();\n }\n\n loadPersistentData() {\n try {\n const savedDemoSessions = this.getFromStorage(this.storageKeys.demoSessions);\n if (savedDemoSessions) {\n const parsed = JSON.parse(savedDemoSessions);\n for (const [key, value] of Object.entries(parsed)) {\n this.demoSessions.set(key, value);\n }\n }\n \n const savedCompletedSessions = this.getFromStorage(this.storageKeys.completedSessions);\n if (savedCompletedSessions) {\n const parsed = JSON.parse(savedCompletedSessions);\n for (const [key, value] of Object.entries(parsed)) {\n this.completedDemoSessions.set(key, value);\n }\n }\n \n const savedGlobalCounter = this.getFromStorage(this.storageKeys.globalCounter);\n if (savedGlobalCounter) {\n this.globalDemoCounter = parseInt(savedGlobalCounter) || 0;\n } else {\n this.globalDemoCounter = 0;\n }\n \n console.log('\uD83D\uDCCA Persistent data loaded:', {\n demoSessions: this.demoSessions.size,\n completedSessions: this.completedDemoSessions.size,\n globalCounter: this.globalDemoCounter\n });\n \n } catch (error) {\n console.warn('Failed to load persistent data:', error);\n this.globalDemoCounter = 0;\n }\n }\n\n savePersistentData() {\n try {\n const demoSessionsObj = Object.fromEntries(this.demoSessions);\n this.setToStorage(this.storageKeys.demoSessions, JSON.stringify(demoSessionsObj));\n \n const completedSessionsObj = Object.fromEntries(this.completedDemoSessions);\n this.setToStorage(this.storageKeys.completedSessions, JSON.stringify(completedSessionsObj));\n \n this.setToStorage(this.storageKeys.globalCounter, this.globalDemoCounter.toString());\n \n this.setToStorage(this.storageKeys.lastCleanup, Date.now().toString());\n \n } catch (error) {\n console.warn('Failed to save persistent data:', error);\n }\n }\n\n getFromStorage(key) {\n try {\n if (typeof localStorage !== 'undefined') {\n const value = localStorage.getItem(key);\n if (value) return value;\n }\n } catch (e) {}\n \n try {\n if (typeof sessionStorage !== 'undefined') {\n const value = sessionStorage.getItem(key);\n if (value) return value;\n }\n } catch (e) {}\n \n try {\n if ('caches' in window) {\n }\n } catch (e) {}\n \n return null;\n }\n\n setToStorage(key, value) {\n try {\n if (typeof localStorage !== 'undefined') {\n localStorage.setItem(key, value);\n }\n } catch (e) {}\n \n try {\n if (typeof sessionStorage !== 'undefined') {\n sessionStorage.setItem(key, value);\n }\n } catch (e) {}\n \n if (!this.memoryStorage) this.memoryStorage = new Map();\n this.memoryStorage.set(key, value);\n }\n\n checkAntiResetProtection(userFingerprint) {\n if (!this.globalDemoCounter) {\n this.globalDemoCounter = 0;\n }\n \n const hardwareFingerprint = this.getHardwareFingerprint();\n \n const savedHardwareFingerprint = this.getFromStorage(this.storageKeys.hardwareFingerprint);\n \n if (savedHardwareFingerprint && savedHardwareFingerprint !== hardwareFingerprint) {\n console.warn('\uD83D\uDEA8 Hardware fingerprint mismatch detected - possible reset attempt');\n \n this.globalDemoCounter += 5;\n this.savePersistentData();\n \n return {\n isValid: false,\n reason: 'hardware_mismatch',\n penalty: 5\n };\n }\n \n this.setToStorage(this.storageKeys.hardwareFingerprint, hardwareFingerprint);\n \n if (this.globalDemoCounter >= 10) {\n return {\n isValid: false,\n reason: 'global_limit_exceeded',\n globalCount: this.globalDemoCounter\n };\n }\n \n return {\n isValid: true,\n globalCount: this.globalDemoCounter\n };\n }\n\n getHardwareFingerprint() {\n const components = [];\n\n components.push(navigator.hardwareConcurrency || 0);\n components.push(navigator.deviceMemory || 0);\n \n try {\n const canvas = document.createElement('canvas');\n const gl = canvas.getContext('webgl');\n if (gl) {\n const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');\n if (debugInfo) {\n components.push(gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) || '');\n components.push(gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) || '');\n }\n }\n } catch (e) {\n components.push('webgl_unavailable');\n }\n \n components.push(screen.width);\n components.push(screen.height);\n components.push(screen.colorDepth);\n\n components.push(Intl.DateTimeFormat().resolvedOptions().timeZone);\n \n let hash = 0;\n const str = components.join('|');\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash;\n }\n \n return Math.abs(hash).toString(36);\n }\n\n registerEnhancedDemoSessionUsage(userFingerprint, preimage) {\n const session = this.registerDemoSessionUsage(userFingerprint, preimage);\n \n this.savePersistentData();\n\n console.log('\uD83D\uDCCA Enhanced demo session registered:', {\n userFingerprint: userFingerprint.substring(0, 12),\n globalCount: this.globalDemoCounter,\n sessionId: session.sessionId,\n timestamp: new Date().toISOString()\n });\n \n return session;\n }\n\n // COMPLETELY REWRITTEN demo session limits check\n checkEnhancedDemoSessionLimits(userFingerprint) {\n const antiResetCheck = this.checkAntiResetProtection(userFingerprint);\n if (!antiResetCheck.isValid) {\n return {\n allowed: false,\n reason: antiResetCheck.reason,\n message: this.getAntiResetMessage(antiResetCheck),\n globalCount: antiResetCheck.globalCount,\n penalty: antiResetCheck.penalty\n };\n }\n \n const regularCheck = this.checkDemoSessionLimits(userFingerprint);\n \n if (regularCheck.allowed) {\n this.globalDemoCounter++;\n this.savePersistentData();\n }\n \n return {\n ...regularCheck,\n globalCount: this.globalDemoCounter\n };\n }\n\n\n\n getAntiResetMessage(antiResetCheck) {\n switch (antiResetCheck.reason) {\n case 'hardware_mismatch':\n return 'An attempt to reset restrictions was detected. Access to demo mode is temporarily restricted.';\n case 'global_limit_exceeded':\n return `Global demo session limit exceeded (${antiResetCheck.globalCount}/10). A paid session is required to continue.`;\n default:\n return 'Access to demo mode is restricted for security reasons.';\n }\n }\n\n\n\n // FIXED demo session usage registration\n registerDemoSessionUsage(userFingerprint, preimage) {\n const now = Date.now();\n const userData = this.demoSessions.get(userFingerprint) || {\n count: 0,\n lastUsed: 0,\n sessions: [],\n firstUsed: now\n };\n \n userData.count++;\n userData.lastUsed = now;\n \n // Add a new session with preimage for tracking\n const newSession = {\n timestamp: now,\n sessionId: crypto.getRandomValues(new Uint32Array(1))[0].toString(36),\n duration: this.demoSessionMaxDuration,\n preimage: preimage, \n status: 'active'\n };\n \n userData.sessions.push(newSession);\n \n // Clear old sessions (only those older than 24 hours)\n userData.sessions = userData.sessions.filter(session => \n now - session.timestamp < this.demoCooldownPeriod\n );\n \n // NEW: Add to global set of active sessions\n this.activeDemoSessions.add(preimage);\n \n this.demoSessions.set(userFingerprint, userData);\n \n console.log(`\uD83D\uDCCA Demo session registered for user ${userFingerprint.substring(0, 12)} (${userData.sessions.length}/${this.maxDemoSessionsPerUser} today)`);\n console.log(`\uD83C\uDF10 Global active demo sessions: ${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}`);\n \n return newSession;\n }\n\n performEnhancedCleanup() {\n const now = Date.now();\n const lastCleanup = parseInt(this.getFromStorage(this.storageKeys.lastCleanup)) || 0;\n \n if (now - lastCleanup < 6 * 60 * 60 * 1000) {\n return;\n }\n \n console.log('\uD83E\uDDF9 Performing enhanced cleanup...');\n \n const maxAge = 25 * 60 * 60 * 1000;\n let cleanedSessions = 0;\n \n for (const [identifier, data] of this.demoSessions.entries()) {\n if (now - data.lastUsed > maxAge) {\n this.demoSessions.delete(identifier);\n cleanedSessions++;\n }\n }\n \n let cleanedCompleted = 0;\n for (const [identifier, sessions] of this.completedDemoSessions.entries()) {\n const filteredSessions = sessions.filter(session => \n now - session.endTime < maxAge\n );\n \n if (filteredSessions.length === 0) {\n this.completedDemoSessions.delete(identifier);\n cleanedCompleted++;\n } else {\n this.completedDemoSessions.set(identifier, filteredSessions);\n }\n }\n \n const weekAgo = 7 * 24 * 60 * 60 * 1000;\n if (now - lastCleanup > weekAgo) {\n this.globalDemoCounter = Math.max(0, this.globalDemoCounter - 3);\n console.log('\uD83D\uDD04 Global demo counter reset (weekly):', this.globalDemoCounter);\n }\n \n this.savePersistentData();\n \n console.log('\u2705 Enhanced cleanup completed:', {\n cleanedSessions,\n cleanedCompleted,\n globalCounter: this.globalDemoCounter\n });\n }\n\n checkMultiTabProtection() {\n const tabId = 'tab_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);\n const activeTabsKey = 'sb_active_tabs';\n \n try {\n const activeTabsStr = this.getFromStorage(activeTabsKey);\n const activeTabs = activeTabsStr ? JSON.parse(activeTabsStr) : [];\n \n const now = Date.now();\n const validTabs = activeTabs.filter(tab => now - tab.timestamp < 30000);\n \n if (validTabs.length >= 2) {\n return {\n allowed: false,\n reason: 'multiple_tabs',\n message: 'Demo mode is only available in one tab at a time..'\n };\n }\n\n validTabs.push({\n tabId: tabId,\n timestamp: now\n });\n \n this.setToStorage(activeTabsKey, JSON.stringify(validTabs));\n this.currentTabId = tabId;\n\n this.startTabHeartbeat();\n \n return {\n allowed: true,\n tabId: tabId\n };\n \n } catch (error) {\n console.warn('Multi-tab protection error:', error);\n return { allowed: true }; \n }\n }\n\n startTabHeartbeat() {\n if (this.tabHeartbeatInterval) {\n clearInterval(this.tabHeartbeatInterval);\n }\n \n this.tabHeartbeatInterval = setInterval(() => {\n this.updateTabHeartbeat();\n }, 10000); \n }\n\n updateTabHeartbeat() {\n if (!this.currentTabId) return;\n \n try {\n const activeTabsKey = 'sb_active_tabs';\n const activeTabsStr = this.getFromStorage(activeTabsKey);\n const activeTabs = activeTabsStr ? JSON.parse(activeTabsStr) : [];\n \n const updatedTabs = activeTabs.map(tab => {\n if (tab.tabId === this.currentTabId) {\n return {\n ...tab,\n timestamp: Date.now()\n };\n }\n return tab;\n });\n \n this.setToStorage(activeTabsKey, JSON.stringify(updatedTabs));\n \n } catch (error) {\n console.warn('Tab heartbeat update failed:', error);\n }\n }\n\n // NEW method: Register demo session completion\n registerDemoSessionCompletion(userFingerprint, sessionDuration, preimage) {\n const now = Date.now();\n \n // Remove from active sessions\n if (preimage) {\n this.activeDemoSessions.delete(preimage);\n }\n \n // Add to completed sessions\n const completedSessions = this.completedDemoSessions.get(userFingerprint) || [];\n completedSessions.push({\n endTime: now,\n duration: sessionDuration,\n preimage: preimage ? preimage.substring(0, 16) + '...' : 'unknown' // \u041B\u043E\u0433\u0438\u0440\u0443\u0435\u043C \u0442\u043E\u043B\u044C\u043A\u043E \u0447\u0430\u0441\u0442\u044C \u0434\u043B\u044F \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E\u0441\u0442\u0438\n });\n \n // Store only the last completed sessions\n const filteredSessions = completedSessions\n .filter(session => now - session.endTime < this.minTimeBetweenCompletedSessions)\n .slice(-5); \n \n this.completedDemoSessions.set(userFingerprint, filteredSessions);\n \n // Update the status in the user's master data\n const userData = this.demoSessions.get(userFingerprint);\n if (userData && userData.sessions) {\n const session = userData.sessions.find(s => s.preimage === preimage);\n if (session) {\n session.status = 'completed';\n session.endTime = now;\n }\n }\n \n console.log(`\u2705 Demo session completed for user ${userFingerprint.substring(0, 12)}`);\n console.log(`\uD83C\uDF10 Global active demo sessions: ${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}`);\n }\n\n // ENHANCED demo preimage generation with additional protection\n generateSecureDemoPreimage() {\n try {\n const timestamp = Date.now();\n const randomBytes = crypto.getRandomValues(new Uint8Array(24));\n const timestampBytes = new Uint8Array(4);\n const versionBytes = new Uint8Array(4);\n \n // Pack the timestamp\n const timestampSeconds = Math.floor(timestamp / 1000);\n timestampBytes[0] = (timestampSeconds >>> 24) & 0xFF;\n timestampBytes[1] = (timestampSeconds >>> 16) & 0xFF;\n timestampBytes[2] = (timestampSeconds >>> 8) & 0xFF;\n timestampBytes[3] = timestampSeconds & 0xFF;\n \n // IMPROVED version marker with additional protection\n versionBytes[0] = 0xDE; \n versionBytes[1] = 0xE0; \n versionBytes[2] = 0x00; \n versionBytes[3] = 0x02; \n \n const combined = new Uint8Array(32);\n combined.set(versionBytes, 0);\n combined.set(timestampBytes, 4);\n combined.set(randomBytes, 8);\n \n const preimage = Array.from(combined).map(b => b.toString(16).padStart(2, '0')).join('');\n \n console.log(`\uD83C\uDFAE Generated SECURE demo preimage v2: ${preimage.substring(0, 16)}...`);\n return preimage;\n \n } catch (error) {\n console.error('Failed to generate demo preimage:', error);\n throw new Error('Failed to generate secure demo preimage');\n }\n }\n\n // UPDATED demo preimage check\n isDemoPreimage(preimage) {\n if (!preimage || typeof preimage !== 'string' || preimage.length !== 64) {\n return false;\n }\n \n // Check the demo marker (support versions 1 and 2)\n const lower = preimage.toLowerCase();\n return lower.startsWith('dee00001') || lower.startsWith('dee00002');\n }\n\n // Extract timestamp from demo preimage\n extractDemoTimestamp(preimage) {\n if (!this.isDemoPreimage(preimage)) {\n return null;\n }\n \n try {\n const timestampHex = preimage.slice(8, 16);\n const timestampSeconds = parseInt(timestampHex, 16);\n return timestampSeconds * 1000;\n } catch (error) {\n console.error('Failed to extract demo timestamp:', error);\n return null;\n }\n }\n\n // ============================================\n // VALIDATION AND CHECKS\n // ============================================\n\n validateSessionType(sessionType) {\n if (!sessionType || typeof sessionType !== 'string') {\n throw new Error('Session type must be a non-empty string');\n }\n \n if (!this.sessionPrices[sessionType]) {\n throw new Error(`Invalid session type: ${sessionType}. Allowed: ${Object.keys(this.sessionPrices).join(', ')}`);\n }\n \n const pricing = this.sessionPrices[sessionType];\n \n if (sessionType === 'demo') {\n return true;\n }\n \n if (pricing.sats < this.minimumPaymentSats) {\n throw new Error(`Session type ${sessionType} below minimum payment threshold (${this.minimumPaymentSats} sats)`);\n }\n \n return true;\n }\n\n calculateEntropy(str) {\n const freq = {};\n for (let char of str) {\n freq[char] = (freq[char] || 0) + 1;\n }\n \n let entropy = 0;\n const length = str.length;\n for (let char in freq) {\n const p = freq[char] / length;\n entropy -= p * Math.log2(p);\n }\n \n return entropy;\n }\n\n // ============================================\n // ENHANCED verification with additional checks\n // ============================================\n\n async verifyCryptographically(preimage, paymentHash) {\n try {\n // Basic validation\n if (!preimage || typeof preimage !== 'string' || preimage.length !== 64) {\n throw new Error('Invalid preimage format');\n }\n \n if (!/^[0-9a-fA-F]{64}$/.test(preimage)) {\n throw new Error('Preimage must be valid hexadecimal');\n }\n \n if (this.isDemoPreimage(preimage)) {\n console.log('\uD83C\uDFAE Demo preimage detected - performing ENHANCED validation...');\n \n // CHECK 1: Preimage duplicates\n if (this.usedPreimages.has(preimage)) {\n throw new Error('Demo preimage already used - replay attack prevented');\n }\n \n // CHECK 2: Global Activity\n if (this.activeDemoSessions.has(preimage)) {\n throw new Error('Demo preimage already active - concurrent usage prevented');\n }\n \n // CHECK 3: Timestamp validation\n const demoTimestamp = this.extractDemoTimestamp(preimage);\n if (!demoTimestamp) {\n throw new Error('Invalid demo preimage timestamp');\n }\n \n const now = Date.now();\n const age = now - demoTimestamp;\n \n // Demo preimage must not be older than 15 minutes\n if (age > 15 * 60 * 1000) {\n throw new Error(`Demo preimage expired (age: ${Math.round(age / (60 * 1000))} minutes)`);\n }\n\n if (age < -2 * 60 * 1000) {\n throw new Error('Demo preimage timestamp from future - possible clock manipulation');\n }\n \n // CHECK 4: FIXED calling limits - use the CORRECT method\n const userFingerprint = this.generateAdvancedUserFingerprint(); \n const limitsCheck = this.checkEnhancedDemoSessionLimits(userFingerprint); \n \n if (!limitsCheck.allowed) {\n throw new Error(`Demo session limits exceeded: ${limitsCheck.message}`);\n }\n \n // FIX: For demo sessions, do NOT add preimage to usedPreimages here,\n // as this will only be done after successful activation\n this.registerEnhancedDemoSessionUsage(userFingerprint, preimage); \n \n console.log('\u2705 Demo preimage ENHANCED validation passed');\n return true;\n }\n \n // For regular preimage - standard checks\n if (this.usedPreimages.has(preimage)) {\n throw new Error('Preimage already used - replay attack prevented');\n }\n \n // Checking entropy\n const entropy = this.calculateEntropy(preimage);\n if (entropy < 3.5) {\n throw new Error(`Preimage has insufficient entropy: ${entropy.toFixed(2)}`);\n }\n \n // Cryptographic verification SHA256(preimage) = paymentHash\n const preimageBytes = new Uint8Array(preimage.match(/.{2}/g).map(byte => parseInt(byte, 16)));\n const hashBuffer = await crypto.subtle.digest('SHA-256', preimageBytes);\n const computedHash = Array.from(new Uint8Array(hashBuffer))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n \n const isValid = computedHash === paymentHash.toLowerCase();\n \n if (isValid) {\n this.usedPreimages.add(preimage);\n console.log('\u2705 Standard preimage cryptographic validation passed');\n }\n \n return isValid;\n \n } catch (error) {\n console.error('\u274C Cryptographic verification failed:', error.message);\n return false;\n }\n }\n\n\n // ============================================\n // LIGHTNING NETWORK INTEGRATION\n // ============================================\n\n // Creating a Lightning invoice\n async createLightningInvoice(sessionType) {\n const pricing = this.sessionPrices[sessionType];\n if (!pricing) throw new Error('Invalid session type');\n\n try {\n console.log(`Creating ${sessionType} invoice for ${pricing.sats} sats...`);\n\n const now = Date.now();\n if (now - this.lastApiCall < this.apiCallMinInterval) {\n throw new Error('API rate limit: please wait before next request');\n }\n this.lastApiCall = now;\n\n const healthCheck = await fetch(`${this.verificationConfig.apiUrl}/api/v1/health`, {\n method: 'GET',\n headers: {\n 'X-Api-Key': this.verificationConfig.apiKey\n },\n signal: AbortSignal.timeout(5000)\n });\n\n if (!healthCheck.ok) {\n throw new Error(`LNbits API unavailable: ${healthCheck.status}`);\n }\n\n const response = await fetch(`${this.verificationConfig.apiUrl}/api/v1/payments`, {\n method: 'POST',\n headers: {\n 'X-Api-Key': this.verificationConfig.apiKey,\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n out: false,\n amount: pricing.sats,\n memo: `SecureBit.chat ${sessionType} session (${pricing.hours}h) - ${Date.now()}`,\n unit: 'sat',\n expiry: this.verificationConfig.invoiceExpiryMinutes * 60\n }),\n signal: AbortSignal.timeout(10000)\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n console.error('LNbits API error response:', errorText);\n throw new Error(`LNbits API error ${response.status}: ${errorText}`);\n }\n\n const data = await response.json();\n \n console.log('\u2705 Lightning invoice created successfully');\n \n return {\n paymentRequest: data.bolt11 || data.payment_request,\n paymentHash: data.payment_hash,\n checkingId: data.checking_id || data.payment_hash,\n amount: data.amount || pricing.sats,\n sessionType: sessionType,\n createdAt: Date.now(),\n expiresAt: Date.now() + (this.verificationConfig.invoiceExpiryMinutes * 60 * 1000),\n description: data.description || data.memo || `SecureBit.chat ${sessionType} session`,\n bolt11: data.bolt11 || data.payment_request,\n memo: data.memo || `SecureBit.chat ${sessionType} session`\n };\n\n } catch (error) {\n console.error('\u274C Lightning invoice creation failed:', error);\n \n if (this.verificationConfig.isDemo && error.message.includes('API')) {\n console.log('\uD83D\uDD04 Creating demo invoice for testing...');\n return this.createDemoInvoice(sessionType);\n }\n \n throw error;\n }\n }\n\n // Creating a demo invoice for testing\n createDemoInvoice(sessionType) {\n const pricing = this.sessionPrices[sessionType];\n const demoHash = Array.from(crypto.getRandomValues(new Uint8Array(32)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n \n return {\n paymentRequest: `lntb${pricing.sats}1p${demoHash.substring(0, 16)}...`,\n paymentHash: demoHash,\n checkingId: demoHash,\n amount: pricing.sats,\n sessionType: sessionType,\n createdAt: Date.now(),\n expiresAt: Date.now() + (5 * 60 * 1000),\n description: `SecureBit.chat ${sessionType} session (DEMO)`,\n isDemo: true\n };\n }\n\n // Checking payment status via LNbits\n async checkPaymentStatus(checkingId) {\n try {\n console.log(`\uD83D\uDD0D Checking payment status for: ${checkingId?.substring(0, 8)}...`);\n\n const now = Date.now();\n if (now - this.lastApiCall < this.apiCallMinInterval) {\n throw new Error('API rate limit exceeded');\n }\n this.lastApiCall = now;\n\n const response = await fetch(`${this.verificationConfig.apiUrl}/api/v1/payments/${checkingId}`, {\n method: 'GET',\n headers: {\n 'X-Api-Key': this.verificationConfig.apiKey,\n 'Content-Type': 'application/json'\n },\n signal: AbortSignal.timeout(10000)\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n console.error('Payment status check failed:', errorText);\n throw new Error(`Payment check failed: ${response.status} - ${errorText}`);\n }\n\n const data = await response.json();\n console.log('\uD83D\uDCCA Payment status retrieved successfully');\n \n return {\n paid: data.paid || false,\n preimage: data.preimage || null,\n details: data.details || {},\n amount: data.amount || 0,\n fee: data.fee || 0,\n timestamp: data.timestamp || Date.now(),\n bolt11: data.bolt11 || null\n };\n\n } catch (error) {\n console.error('\u274C Payment status check error:', error);\n \n if (this.verificationConfig.isDemo && error.message.includes('API')) {\n console.log('\uD83D\uDD04 Returning demo payment status...');\n return {\n paid: false,\n preimage: null,\n details: { demo: true },\n amount: 0,\n fee: 0,\n timestamp: Date.now()\n };\n }\n \n throw error;\n }\n }\n\n // Payment verification via LNbits API\n async verifyPaymentLNbits(preimage, paymentHash) {\n try {\n console.log(`\uD83D\uDD10 Verifying payment via LNbits API...`);\n \n if (!this.verificationConfig.apiUrl || !this.verificationConfig.apiKey) {\n throw new Error('LNbits API configuration missing');\n }\n\n const now = Date.now();\n if (now - this.lastApiCall < this.apiCallMinInterval) {\n throw new Error('API rate limit: please wait before next verification');\n }\n this.lastApiCall = now;\n\n const response = await fetch(`${this.verificationConfig.apiUrl}/api/v1/payments/${paymentHash}`, {\n method: 'GET',\n headers: {\n 'X-Api-Key': this.verificationConfig.apiKey,\n 'Content-Type': 'application/json'\n },\n signal: AbortSignal.timeout(10000)\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n console.error('LNbits verification failed:', errorText);\n throw new Error(`API request failed: ${response.status} - ${errorText}`);\n }\n\n const paymentData = await response.json();\n console.log('\uD83D\uDCCB Payment verification data received from LNbits');\n \n const isPaid = paymentData.paid === true;\n const preimageMatches = paymentData.preimage === preimage;\n const amountValid = paymentData.amount >= this.minimumPaymentSats;\n \n const paymentTimestamp = paymentData.timestamp || paymentData.time || 0;\n const paymentAge = now - (paymentTimestamp * 1000);\n const maxPaymentAge = 24 * 60 * 60 * 1000;\n \n if (paymentAge > maxPaymentAge && paymentTimestamp > 0) {\n throw new Error(`Payment too old: ${Math.round(paymentAge / (60 * 60 * 1000))} hours (max: 24h)`);\n }\n \n if (isPaid && preimageMatches && amountValid) {\n console.log('\u2705 Payment verified successfully via LNbits');\n return {\n verified: true,\n amount: paymentData.amount,\n fee: paymentData.fee || 0,\n timestamp: paymentTimestamp || now,\n method: 'lnbits',\n verificationTime: now,\n paymentAge: paymentAge\n };\n }\n\n console.log('\u274C LNbits payment verification failed:', {\n paid: isPaid,\n preimageMatch: preimageMatches,\n amountValid: amountValid,\n paymentAge: Math.round(paymentAge / (60 * 1000)) + ' minutes'\n });\n \n return {\n verified: false,\n reason: 'Payment verification failed: not paid, preimage mismatch, insufficient amount, or payment too old',\n method: 'lnbits',\n details: {\n paid: isPaid,\n preimageMatch: preimageMatches,\n amountValid: amountValid,\n paymentAge: paymentAge\n }\n };\n \n } catch (error) {\n console.error('\u274C LNbits payment verification failed:', error);\n return {\n verified: false,\n reason: error.message,\n method: 'lnbits',\n error: true\n };\n }\n }\n\n // ============================================\n // BASIC LOGIC OF PAYMENT VERIFICATION\n // ============================================\n\n // The main method of payment verification\n async verifyPayment(preimage, paymentHash) {\n console.log(`\uD83D\uDD10 Starting payment verification...`);\n \n try {\n if (!preimage || !paymentHash) {\n throw new Error('Missing preimage or payment hash');\n }\n \n if (typeof preimage !== 'string' || typeof paymentHash !== 'string') {\n throw new Error('Preimage and payment hash must be strings');\n }\n \n // Special demo preimage processing with ENHANCED checks\n if (this.isDemoPreimage(preimage)) {\n console.log('\uD83C\uDFAE Processing demo session verification...');\n \n // Cryptographic verification already includes all necessary checks\n const cryptoValid = await this.verifyCryptographically(preimage, paymentHash);\n if (!cryptoValid) {\n return { \n verified: false, \n reason: 'Demo preimage verification failed',\n stage: 'crypto'\n };\n }\n \n console.log('\u2705 Demo session verified successfully');\n return { \n verified: true, \n method: 'demo',\n sessionType: 'demo',\n isDemo: true,\n warning: 'Demo session - limited duration (6 minutes)'\n };\n }\n \n // Cryptographic verification for regular preimage\n const cryptoValid = await this.verifyCryptographically(preimage, paymentHash);\n if (!cryptoValid) {\n return { \n verified: false, \n reason: 'Cryptographic verification failed',\n stage: 'crypto'\n };\n }\n\n console.log('\u2705 Cryptographic verification passed');\n\n // Check via Lightning Network (if not demo mode)\n if (!this.verificationConfig.isDemo) {\n switch (this.verificationConfig.method) {\n case 'lnbits':\n const lnbitsResult = await this.verifyPaymentLNbits(preimage, paymentHash);\n if (!lnbitsResult.verified) {\n return {\n verified: false,\n reason: lnbitsResult.reason || 'LNbits verification failed',\n stage: 'lightning',\n details: lnbitsResult.details\n };\n }\n return lnbitsResult;\n \n default:\n console.warn('Unknown verification method, using crypto-only verification');\n return { \n verified: true, \n method: 'crypto-only',\n warning: 'Lightning verification skipped - unknown method'\n };\n }\n } else {\n console.warn('\uD83D\uDEA8 DEMO MODE: Lightning payment verification bypassed - FOR DEVELOPMENT ONLY');\n return { \n verified: true, \n method: 'demo-mode',\n warning: 'DEMO MODE - Lightning verification bypassed'\n };\n }\n \n } catch (error) {\n console.error('\u274C Payment verification failed:', error);\n return { \n verified: false, \n reason: error.message,\n stage: 'error'\n };\n }\n }\n\n // ============================================\n // SESSION MANAGEMENT\n // ============================================\n\n // ============================================\n // REWORKED session activation methods\n // ============================================\n\n async safeActivateSession(sessionType, preimage, paymentHash) {\n try {\n console.log(`\uD83D\uDE80 Attempting to activate ${sessionType} session...`);\n \n if (!sessionType || !preimage || !paymentHash) {\n return { \n success: false, \n reason: 'Missing required parameters: sessionType, preimage, or paymentHash' \n };\n }\n \n try {\n this.validateSessionType(sessionType);\n } catch (error) {\n return { success: false, reason: error.message };\n }\n \n if (this.hasActiveSession()) {\n return { \n success: false, \n reason: 'Active session already exists. Please wait for it to expire or disconnect.' \n };\n }\n \n if (sessionType === 'demo') {\n if (!this.isDemoPreimage(preimage)) {\n return {\n success: false,\n reason: 'Invalid demo preimage format. Please use the generated demo preimage.'\n };\n }\n \n const userFingerprint = this.generateAdvancedUserFingerprint();\n const demoCheck = this.checkEnhancedDemoSessionLimits(userFingerprint);\n \n if (!demoCheck.allowed) {\n console.log(`\u26A0\uFE0F Demo session cooldown active, but allowing activation for development`);\n \n if (demoCheck.reason === 'global_limit_exceeded') {\n return {\n success: false,\n reason: demoCheck.message,\n demoLimited: true,\n timeUntilNext: demoCheck.timeUntilNext,\n remaining: demoCheck.remaining\n };\n }\n \n console.log(`\uD83D\uDD04 Bypassing demo cooldown for development purposes`);\n }\n \n if (this.activeDemoSessions.has(preimage)) {\n if (!this.currentSession || !this.hasActiveSession()) {\n console.log(`\uD83D\uDD04 Demo session with preimage ${preimage.substring(0, 16)}... was interrupted, allowing reactivation`);\n this.activeDemoSessions.delete(preimage);\n } else {\n return {\n success: false,\n reason: 'Demo session with this preimage is already active',\n demoLimited: true\n };\n }\n }\n }\n \n let verificationResult;\n \n if (sessionType === 'demo') {\n console.log('\uD83C\uDFAE Using special demo verification for activation...');\n verificationResult = await this.verifyDemoSessionForActivation(preimage, paymentHash);\n } else {\n verificationResult = await this.verifyPayment(preimage, paymentHash);\n }\n \n if (!verificationResult.verified) {\n return {\n success: false,\n reason: verificationResult.reason,\n stage: verificationResult.stage,\n method: verificationResult.method,\n demoLimited: verificationResult.demoLimited,\n timeUntilNext: verificationResult.timeUntilNext,\n remaining: verificationResult.remaining\n };\n }\n \n // Session activation\n const session = this.activateSession(sessionType, preimage);\n \n console.log(`\u2705 Session activated successfully: ${sessionType} via ${verificationResult.method}`);\n return {\n success: true,\n sessionType: sessionType,\n method: verificationResult.method,\n details: verificationResult,\n timeLeft: this.getTimeLeft(),\n sessionId: session.id,\n warning: verificationResult.warning,\n isDemo: verificationResult.isDemo || false,\n remaining: verificationResult.remaining\n };\n \n } catch (error) {\n console.error('\u274C Session activation failed:', error);\n return {\n success: false,\n reason: error.message,\n method: 'error'\n };\n }\n }\n\n // REWORKED session activation\n activateSession(sessionType, preimage) {\n if (this.hasActiveSession()) {\n return this.currentSession;\n }\n if (this.sessionTimer) {\n clearInterval(this.sessionTimer);\n this.sessionTimer = null;\n }\n\n const pricing = this.sessionPrices[sessionType];\n const now = Date.now();\n \n let duration;\n if (sessionType === 'demo') {\n duration = this.demoSessionMaxDuration;\n } else {\n duration = pricing.hours * 60 * 60 * 1000;\n }\n \n const expiresAt = now + duration;\n const sessionId = Array.from(crypto.getRandomValues(new Uint8Array(16)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n\n this.currentSession = {\n id: sessionId,\n type: sessionType,\n startTime: now,\n expiresAt: expiresAt,\n preimage: preimage,\n isDemo: sessionType === 'demo',\n securityLevel: this.getSecurityLevelForSession(sessionType)\n };\n\n this.startSessionTimer();\n \n if (sessionType === 'demo') {\n setTimeout(() => {\n this.handleDemoSessionExpiry(preimage);\n }, duration);\n }\n \n const durationMinutes = Math.round(duration / (60 * 1000));\n const securityLevel = this.currentSession ? this.currentSession.securityLevel : 'unknown';\n console.log(`\uD83D\uDCC5 Session ${sessionId.substring(0, 8)}... activated for ${durationMinutes} minutes with ${securityLevel} security`);\n \n if (sessionType === 'demo') {\n this.activeDemoSessions.add(preimage);\n this.usedPreimages.add(preimage);\n console.log(`\uD83C\uDF10 Demo session added to active sessions. Total: ${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}`);\n }\n \n // SENDING SECURITY LEVEL INFORMATION TO WebRTC\n const activatedSession = this.currentSession; \n setTimeout(() => {\n if (activatedSession) {\n this.notifySessionActivated(activatedSession);\n }\n // Notify WebRTC manager about session type\n if (window.webrtcManager && window.webrtcManager.configureSecurityForSession && activatedSession) {\n const securityLevel = activatedSession.securityLevel || this.getSecurityLevelForSession(sessionType);\n window.webrtcManager.configureSecurityForSession(sessionType, securityLevel);\n }\n }, 100);\n \n return this.currentSession;\n }\n\n // UPDATED method for getting session information\n getSessionInfo() {\n if (!this.currentSession) {\n return null;\n }\n\n const securityLevel = this.getSecurityLevelForSession(this.currentSession.type);\n const pricing = this.sessionPrices[this.currentSession.type];\n\n return {\n ...this.currentSession,\n securityLevel: securityLevel,\n securityDescription: this.getSecurityDescription(securityLevel),\n pricing: pricing,\n timeLeft: this.getTimeLeft(),\n isConnected: this.hasActiveSession()\n };\n }\n\n getSecurityDescription(level) {\n const descriptions = {\n 'basic': {\n title: 'Basic Security',\n features: [\n 'End-to-end encryption',\n 'Basic key exchange',\n 'Rate limiting',\n 'Message integrity'\n ],\n limitations: [\n 'No advanced obfuscation',\n 'No traffic padding',\n 'No decoy channels'\n ]\n },\n 'enhanced': {\n title: 'Enhanced Security',\n features: [\n 'All basic features',\n 'ECDSA signatures',\n 'Metadata protection',\n 'Perfect forward secrecy',\n 'Nested encryption',\n 'Packet padding'\n ],\n limitations: [\n 'Limited traffic obfuscation',\n 'No fake traffic generation'\n ]\n },\n 'maximum': {\n title: 'Maximum Security',\n features: [\n 'All enhanced features',\n 'Traffic obfuscation',\n 'Fake traffic generation',\n 'Decoy channels',\n 'Anti-fingerprinting',\n 'Message chunking',\n 'Packet reordering protection'\n ],\n limitations: []\n }\n };\n\n return descriptions[level] || descriptions['basic'];\n }\n\n notifySessionActivated(session = null) {\n const targetSession = session || this.currentSession;\n\n if (!targetSession) return;\n if (targetSession.notified) {\n return;\n }\n \n const timeLeft = Math.max(0, targetSession.expiresAt - Date.now());\n const sessionType = targetSession.type;\n \n\n \n if (window.updateSessionTimer) {\n window.updateSessionTimer(timeLeft, sessionType);\n }\n \n document.dispatchEvent(new CustomEvent('session-activated', {\n detail: {\n sessionId: targetSession.id,\n timeLeft: timeLeft,\n sessionType: sessionType,\n isDemo: targetSession.isDemo,\n timestamp: Date.now()\n }\n }));\n \n if (window.forceUpdateHeader) {\n window.forceUpdateHeader(timeLeft, sessionType);\n }\n\n if (window.debugSessionManager) {\n window.debugSessionManager();\n }\n targetSession.notified = true;\n }\n\n handleDemoSessionExpiry(preimage) {\n if (this.currentSession && this.currentSession.preimage === preimage) {\n const userFingerprint = this.generateAdvancedUserFingerprint(); \n const sessionDuration = Date.now() - this.currentSession.startTime;\n \n this.registerDemoSessionCompletion(userFingerprint, sessionDuration, preimage);\n \n console.log(`\u23F0 Demo session auto-expired for preimage ${preimage.substring(0, 16)}...`);\n }\n }\n\n startSessionTimer() {\n if (this.sessionTimer) {\n clearInterval(this.sessionTimer);\n }\n\n this.sessionTimer = setInterval(() => {\n if (!this.hasActiveSession()) {\n this.expireSession();\n }\n }, 60000);\n }\n\n expireSession() {\n if (this.sessionTimer) {\n clearInterval(this.sessionTimer);\n this.sessionTimer = null;\n }\n \n const expiredSession = this.currentSession;\n \n if (expiredSession && expiredSession.isDemo) {\n const userFingerprint = this.generateAdvancedUserFingerprint(); \n const sessionDuration = Date.now() - expiredSession.startTime;\n this.registerDemoSessionCompletion(userFingerprint, sessionDuration, expiredSession.preimage);\n }\n \n this.currentSession = null;\n \n if (expiredSession) {\n console.log(`\u23F0 Session ${expiredSession.id.substring(0, 8)}... expired`);\n }\n \n if (this.onSessionExpired) {\n this.onSessionExpired();\n }\n }\n\n hasActiveSession() {\n if (!this.currentSession) {\n return false;\n }\n \n const isActive = Date.now() < this.currentSession.expiresAt;\n \n return isActive;\n }\n\n getTimeLeft() {\n if (!this.currentSession) return 0;\n return Math.max(0, this.currentSession.expiresAt - Date.now());\n }\n\n forceUpdateTimer() {\n if (this.currentSession) {\n const timeLeft = this.getTimeLeft();\n if (window.DEBUG_MODE && Math.floor(Date.now() / 30000) !== Math.floor((Date.now() - 1000) / 30000)) {\n console.log(`\u23F1\uFE0F Timer updated: ${Math.ceil(timeLeft / 1000)}s left`);\n }\n return timeLeft;\n }\n return 0;\n }\n\n // ============================================\n // DEMO MODE: Custom Methods\n // ============================================\n\n // UPDATED demo session creation\n createDemoSession() {\n const userFingerprint = this.generateAdvancedUserFingerprint(); \n const demoCheck = this.checkEnhancedDemoSessionLimits(userFingerprint); \n \n if (!demoCheck.allowed) {\n return {\n success: false,\n reason: demoCheck.message,\n timeUntilNext: demoCheck.timeUntilNext,\n remaining: demoCheck.remaining,\n blockingReason: demoCheck.reason\n };\n }\n \n // Checking the global limit\n if (this.activeDemoSessions.size >= this.maxGlobalDemoSessions) {\n return {\n success: false,\n reason: `Too many demo sessions active globally (${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}). Please try again later.`,\n blockingReason: 'global_limit',\n globalActive: this.activeDemoSessions.size,\n globalLimit: this.maxGlobalDemoSessions\n };\n }\n \n try {\n const demoPreimage = this.generateSecureDemoPreimage();\n const demoPaymentHash = 'demo_' + Array.from(crypto.getRandomValues(new Uint8Array(16)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n \n return {\n success: true,\n sessionType: 'demo',\n preimage: demoPreimage,\n paymentHash: demoPaymentHash,\n duration: this.sessionPrices.demo.hours,\n durationMinutes: Math.round(this.demoSessionMaxDuration / (60 * 1000)),\n warning: `Demo session - limited to ${Math.round(this.demoSessionMaxDuration / (60 * 1000))} minutes`,\n remaining: demoCheck.remaining - 1,\n globalActive: this.activeDemoSessions.size + 1,\n globalLimit: this.maxGlobalDemoSessions\n };\n } catch (error) {\n console.error('Failed to create demo session:', error);\n return {\n success: false,\n reason: 'Failed to generate demo session. Please try again.',\n remaining: demoCheck.remaining\n };\n }\n }\n\n\n // UPDATED information about demo limits\n getDemoSessionInfo() {\n const userFingerprint = this.generateAdvancedUserFingerprint(); \n const userData = this.demoSessions.get(userFingerprint);\n const now = Date.now();\n \n if (!userData) {\n return {\n available: this.maxDemoSessionsPerUser,\n used: 0,\n total: this.maxDemoSessionsPerUser,\n nextAvailable: 'immediately',\n cooldownMinutes: 0,\n durationMinutes: Math.round(this.demoSessionMaxDuration / (60 * 1000)),\n canUseNow: this.activeDemoSessions.size < this.maxGlobalDemoSessions,\n globalActive: this.activeDemoSessions.size,\n globalLimit: this.maxGlobalDemoSessions,\n debugInfo: 'New user, no restrictions'\n };\n }\n \n // Counting sessions for the last 24 hours\n const sessionsLast24h = userData.sessions.filter(session => \n now - session.timestamp < this.demoCooldownPeriod\n );\n \n const available = Math.max(0, this.maxDemoSessionsPerUser - sessionsLast24h.length);\n \n // We check all possible blockages\n let cooldownMs = 0;\n let nextAvailable = 'immediately';\n let blockingReason = null;\n let debugInfo = '';\n \n // Global limit\n if (this.activeDemoSessions.size >= this.maxGlobalDemoSessions) {\n nextAvailable = 'when global limit decreases';\n blockingReason = 'global_limit';\n debugInfo = `Global limit: ${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}`;\n }\n // Daily limit\n else if (available === 0) {\n const oldestSession = Math.min(...sessionsLast24h.map(s => s.timestamp));\n cooldownMs = this.demoCooldownPeriod - (now - oldestSession);\n nextAvailable = `${Math.ceil(cooldownMs / (60 * 1000))} minutes`;\n blockingReason = 'daily_limit';\n debugInfo = `Daily limit reached: ${sessionsLast24h.length}/${this.maxDemoSessionsPerUser}`;\n }\n // Cooldown between sessions\n else if (userData.lastUsed && (now - userData.lastUsed) < this.demoSessionCooldown) {\n cooldownMs = this.demoSessionCooldown - (now - userData.lastUsed);\n nextAvailable = `${Math.ceil(cooldownMs / (60 * 1000))} minutes`;\n blockingReason = 'session_cooldown';\n const lastUsedMinutes = Math.round((now - userData.lastUsed) / (60 * 1000));\n debugInfo = `Cooldown active: last used ${lastUsedMinutes}min ago, need ${Math.ceil(cooldownMs / (60 * 1000))}min more`;\n }\n // Cooldown after completed session\n else {\n const completedSessions = this.completedDemoSessions.get(userFingerprint) || [];\n const recentCompletedSessions = completedSessions.filter(session =>\n now - session.endTime < this.minTimeBetweenCompletedSessions\n );\n \n if (recentCompletedSessions.length > 0) {\n const lastCompletedSession = Math.max(...recentCompletedSessions.map(s => s.endTime));\n cooldownMs = this.minTimeBetweenCompletedSessions - (now - lastCompletedSession);\n nextAvailable = `${Math.ceil(cooldownMs / (60 * 1000))} minutes`;\n blockingReason = 'completion_cooldown';\n const completedMinutes = Math.round((now - lastCompletedSession) / (60 * 1000));\n debugInfo = `Completion cooldown: last session ended ${completedMinutes}min ago`;\n } else {\n debugInfo = `Ready to use: ${available} sessions available`;\n }\n }\n \n const canUseNow = available > 0 && \n cooldownMs <= 0 && \n this.activeDemoSessions.size < this.maxGlobalDemoSessions;\n \n return {\n available: available,\n used: sessionsLast24h.length,\n total: this.maxDemoSessionsPerUser,\n nextAvailable: nextAvailable,\n cooldownMinutes: Math.ceil(cooldownMs / (60 * 1000)),\n durationMinutes: Math.round(this.demoSessionMaxDuration / (60 * 1000)),\n canUseNow: canUseNow,\n blockingReason: blockingReason,\n globalActive: this.activeDemoSessions.size,\n globalLimit: this.maxGlobalDemoSessions,\n completionCooldownMinutes: Math.round(this.minTimeBetweenCompletedSessions / (60 * 1000)),\n sessionCooldownMinutes: Math.round(this.demoSessionCooldown / (60 * 1000)),\n debugInfo: debugInfo,\n lastUsed: userData.lastUsed ? new Date(userData.lastUsed).toLocaleString() : 'Never'\n };\n }\n\n\n\n // ============================================\n // ADDITIONAL VERIFICATION METHODS\n // ============================================\n\n // Verification method via LND (Lightning Network Daemon)\n async verifyPaymentLND(preimage, paymentHash) {\n try {\n if (!this.verificationConfig.nodeUrl || !this.verificationConfig.macaroon) {\n throw new Error('LND configuration missing');\n }\n\n const response = await fetch(`${this.verificationConfig.nodeUrl}/v1/invoice/${paymentHash}`, {\n method: 'GET',\n headers: {\n 'Grpc-Metadata-macaroon': this.verificationConfig.macaroon,\n 'Content-Type': 'application/json'\n },\n signal: AbortSignal.timeout(10000)\n });\n\n if (!response.ok) {\n throw new Error(`LND API request failed: ${response.status}`);\n }\n\n const invoiceData = await response.json();\n \n if (invoiceData.settled && invoiceData.r_preimage === preimage) {\n return {\n verified: true,\n amount: invoiceData.value,\n method: 'lnd',\n timestamp: Date.now()\n };\n }\n\n return { verified: false, reason: 'LND verification failed', method: 'lnd' };\n } catch (error) {\n console.error('LND payment verification failed:', error);\n return { verified: false, reason: error.message, method: 'lnd' };\n }\n }\n\n // Verification method via CLN (Core Lightning)\n async verifyPaymentCLN(preimage, paymentHash) {\n try {\n if (!this.verificationConfig.nodeUrl) {\n throw new Error('CLN configuration missing');\n }\n\n const response = await fetch(`${this.verificationConfig.nodeUrl}/v1/listinvoices`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n payment_hash: paymentHash\n }),\n signal: AbortSignal.timeout(10000)\n });\n\n if (!response.ok) {\n throw new Error(`CLN API request failed: ${response.status}`);\n }\n\n const data = await response.json();\n \n if (data.invoices && data.invoices.length > 0) {\n const invoice = data.invoices[0];\n if (invoice.status === 'paid' && invoice.payment_preimage === preimage) {\n return {\n verified: true,\n amount: invoice.amount_msat / 1000,\n method: 'cln',\n timestamp: Date.now()\n };\n }\n }\n\n return { verified: false, reason: 'CLN verification failed', method: 'cln' };\n } catch (error) {\n console.error('CLN payment verification failed:', error);\n return { verified: false, reason: error.message, method: 'cln' };\n }\n }\n\n // Verification method via BTCPay Server\n async verifyPaymentBTCPay(preimage, paymentHash) {\n try {\n if (!this.verificationConfig.apiUrl || !this.verificationConfig.apiKey) {\n throw new Error('BTCPay Server configuration missing');\n }\n\n const response = await fetch(`${this.verificationConfig.apiUrl}/api/v1/invoices/${paymentHash}`, {\n method: 'GET',\n headers: {\n 'Authorization': `Bearer ${this.verificationConfig.apiKey}`,\n 'Content-Type': 'application/json'\n },\n signal: AbortSignal.timeout(10000)\n });\n\n if (!response.ok) {\n throw new Error(`BTCPay API request failed: ${response.status}`);\n }\n\n const invoiceData = await response.json();\n \n if (invoiceData.status === 'Settled' && \n invoiceData.payment && \n invoiceData.payment.preimage === preimage) {\n return {\n verified: true,\n amount: invoiceData.amount,\n method: 'btcpay',\n timestamp: Date.now()\n };\n }\n\n return { verified: false, reason: 'BTCPay verification failed', method: 'btcpay' };\n } catch (error) {\n console.error('BTCPay payment verification failed:', error);\n return { verified: false, reason: error.message, method: 'btcpay' };\n }\n }\n\n // ============================================\n // UTILITY METHODS\n // ============================================\n\n // Creating a regular invoice (not a demo)\n createInvoice(sessionType) {\n this.validateSessionType(sessionType);\n const pricing = this.sessionPrices[sessionType];\n\n const randomBytes = crypto.getRandomValues(new Uint8Array(32));\n const timestamp = Date.now();\n const sessionEntropy = crypto.getRandomValues(new Uint8Array(16));\n \n const combinedEntropy = new Uint8Array(48);\n combinedEntropy.set(randomBytes, 0);\n combinedEntropy.set(new Uint8Array(new BigUint64Array([BigInt(timestamp)]).buffer), 32);\n combinedEntropy.set(sessionEntropy, 40);\n \n const paymentHash = Array.from(crypto.getRandomValues(new Uint8Array(32)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n\n return {\n amount: pricing.sats,\n memo: `SecureBit.chat ${sessionType} session (${pricing.hours}h) - ${timestamp}`,\n sessionType: sessionType,\n timestamp: timestamp,\n paymentHash: paymentHash,\n lightningAddress: this.staticLightningAddress,\n entropy: Array.from(sessionEntropy).map(b => b.toString(16).padStart(2, '0')).join(''),\n expiresAt: timestamp + (this.verificationConfig.invoiceExpiryMinutes * 60 * 1000)\n };\n }\n\n // Checking if a session can be activated\n canActivateSession() {\n return !this.hasActiveSession();\n }\n\n // Reset session (if there are security errors)\n resetSession() {\n if (this.sessionTimer) {\n clearInterval(this.sessionTimer);\n this.sessionTimer = null;\n }\n \n const resetSession = this.currentSession;\n \n // IMPORTANT: For demo sessions, we register forced termination\n if (resetSession && resetSession.isDemo) {\n const userFingerprint = this.generateAdvancedUserFingerprint(); \n const sessionDuration = Date.now() - resetSession.startTime;\n this.registerDemoSessionCompletion(userFingerprint, sessionDuration, resetSession.preimage);\n }\n \n this.currentSession = null;\n this.sessionStartTime = null;\n this.sessionEndTime = null;\n \n if (resetSession && resetSession.preimage) {\n this.activeDemoSessions.delete(resetSession.preimage);\n }\n \n document.dispatchEvent(new CustomEvent('session-reset', {\n detail: { \n timestamp: Date.now(),\n reason: 'security_reset'\n }\n }));\n \n setTimeout(() => {\n if (this.currentSession) {\n this.currentSession = null;\n }\n }, 100);\n }\n\n // Cleaning old preimages (every 24 hours)\n startPreimageCleanup() {\n this.preimageCleanupInterval = setInterval(() => {\n if (this.usedPreimages.size > 10000) {\n const oldSize = this.usedPreimages.size;\n this.usedPreimages.clear();\n console.log(`\uD83E\uDDF9 Cleaned ${oldSize} old preimages for memory management`);\n }\n }, 24 * 60 * 60 * 1000);\n }\n\n // Complete manager cleanup\n cleanup() {\n if (this.sessionTimer) {\n clearInterval(this.sessionTimer);\n this.sessionTimer = null;\n }\n if (this.preimageCleanupInterval) {\n clearInterval(this.preimageCleanupInterval);\n this.preimageCleanupInterval = null;\n }\n \n // IMPORTANT: We register the end of the current demo session during cleanup\n if (this.currentSession && this.currentSession.isDemo) {\n const userFingerprint = this.generateAdvancedUserFingerprint(); \n const sessionDuration = Date.now() - this.currentSession.startTime;\n this.registerDemoSessionCompletion(userFingerprint, sessionDuration, this.currentSession.preimage);\n }\n \n this.currentSession = null;\n this.sessionStartTime = null;\n this.sessionEndTime = null;\n \n if (this.currentSession && this.currentSession.preimage) {\n this.activeDemoSessions.delete(this.currentSession.preimage);\n }\n \n document.dispatchEvent(new CustomEvent('session-cleanup', {\n detail: { \n timestamp: Date.now(),\n reason: 'complete_cleanup'\n }\n }));\n \n setTimeout(() => {\n if (this.currentSession) {\n this.currentSession = null;\n }\n }, 100);\n }\n\n getUsageStats() {\n const stats = {\n totalDemoUsers: this.demoSessions.size,\n usedPreimages: this.usedPreimages.size,\n activeDemoSessions: this.activeDemoSessions.size,\n globalDemoLimit: this.maxGlobalDemoSessions,\n currentSession: this.currentSession ? {\n type: this.currentSession.type,\n timeLeft: this.getTimeLeft(),\n isDemo: this.currentSession.isDemo\n } : null,\n config: {\n maxDemoSessions: this.maxDemoSessionsPerUser,\n demoCooldown: this.demoSessionCooldown / (60 * 1000),\n demoMaxDuration: this.demoSessionMaxDuration / (60 * 1000),\n completionCooldown: this.minTimeBetweenCompletedSessions / (60 * 1000)\n }\n };\n \n return stats;\n }\n\n getVerifiedDemoSession() {\n const userFingerprint = this.generateAdvancedUserFingerprint(); \n const userData = this.demoSessions.get(userFingerprint);\n \n console.log('\uD83D\uDD0D Searching for verified demo session:', {\n userFingerprint: userFingerprint.substring(0, 12),\n hasUserData: !!userData,\n sessionsCount: userData?.sessions?.length || 0,\n currentSession: this.currentSession ? {\n type: this.currentSession.type,\n timeLeft: this.getTimeLeft(),\n isActive: this.hasActiveSession()\n } : null\n });\n \n if (!userData || !userData.sessions || userData.sessions.length === 0) {\n console.log('\u274C No user data or sessions found');\n return null;\n }\n\n const lastSession = userData.sessions[userData.sessions.length - 1];\n if (!lastSession || !lastSession.preimage) {\n console.log('\u274C Last session is invalid:', lastSession);\n return null;\n }\n \n if (!this.isDemoPreimage(lastSession.preimage)) {\n console.log('\u274C Last session preimage is not demo format:', lastSession.preimage.substring(0, 16) + '...');\n return null;\n }\n \n if (this.activeDemoSessions.has(lastSession.preimage)) {\n console.log('\u26A0\uFE0F Demo session is already in activeDemoSessions, checking if truly active...');\n if (this.hasActiveSession()) {\n console.log('\u274C Demo session is truly active, cannot reactivate');\n return null;\n } else {\n console.log('\uD83D\uDD04 Demo session was interrupted, can be reactivated');\n }\n }\n \n const verifiedSession = {\n preimage: lastSession.preimage,\n paymentHash: lastSession.paymentHash || 'demo_' + Date.now(),\n sessionType: 'demo',\n timestamp: lastSession.timestamp\n };\n \n console.log('\u2705 Found verified demo session:', {\n preimage: verifiedSession.preimage.substring(0, 16) + '...',\n timestamp: new Date(verifiedSession.timestamp).toLocaleTimeString(),\n canActivate: !this.hasActiveSession()\n });\n \n return verifiedSession;\n }\n\n checkDemoSessionLimits(userFingerprint) {\n const userData = this.demoSessions.get(userFingerprint);\n const now = Date.now();\n \n console.log(`\uD83D\uDD0D Checking demo limits for user ${userFingerprint.substring(0, 12)}...`);\n \n // CHECK 1: Global limit of simultaneous demo sessions\n if (this.activeDemoSessions.size >= this.maxGlobalDemoSessions) {\n console.log(`\u274C Global demo limit reached: ${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}`);\n return {\n allowed: false,\n reason: 'global_limit_exceeded',\n message: `Too many demo sessions active globally (${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}). Please try again later.`,\n remaining: 0,\n debugInfo: `Global sessions: ${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}`\n };\n }\n \n if (!userData) {\n // First demo session for this user\n console.log(`\u2705 First demo session for user ${userFingerprint.substring(0, 12)}`);\n return { \n allowed: true, \n reason: 'first_demo_session',\n remaining: this.maxDemoSessionsPerUser,\n debugInfo: 'First time user'\n };\n }\n \n // CHECK 2: Limit sessions per 24 hours (STRICT check)\n const sessionsLast24h = userData.sessions.filter(session => \n now - session.timestamp < this.demoCooldownPeriod\n );\n \n console.log(`\uD83D\uDCCA Sessions in last 24h for user ${userFingerprint.substring(0, 12)}: ${sessionsLast24h.length}/${this.maxDemoSessionsPerUser}`);\n \n if (sessionsLast24h.length >= this.maxDemoSessionsPerUser) {\n const oldestSession = Math.min(...sessionsLast24h.map(s => s.timestamp));\n const timeUntilNext = this.demoCooldownPeriod - (now - oldestSession);\n \n console.log(`\u274C Daily demo limit exceeded for user ${userFingerprint.substring(0, 12)}`);\n return { \n allowed: false, \n reason: 'daily_limit_exceeded',\n timeUntilNext: timeUntilNext,\n message: `Daily demo limit reached (${this.maxDemoSessionsPerUser}/day). Next session available in ${Math.ceil(timeUntilNext / (60 * 1000))} minutes.`,\n remaining: 0,\n debugInfo: `Used ${sessionsLast24h.length}/${this.maxDemoSessionsPerUser} today`\n };\n }\n \n // CHECK 3: Cooldown between sessions (FIXED LOGIC)\n if (userData.lastUsed && (now - userData.lastUsed) < this.demoSessionCooldown) {\n const timeUntilNext = this.demoSessionCooldown - (now - userData.lastUsed);\n const minutesLeft = Math.ceil(timeUntilNext / (60 * 1000));\n \n console.log(`\u23F0 Cooldown active for user ${userFingerprint.substring(0, 12)}: ${minutesLeft} minutes`);\n \n return { \n allowed: false, \n reason: 'session_cooldown',\n timeUntilNext: timeUntilNext,\n message: `Please wait ${minutesLeft} minutes between demo sessions. This prevents abuse and ensures fair access for all users.`,\n remaining: this.maxDemoSessionsPerUser - sessionsLast24h.length,\n debugInfo: `Cooldown: ${minutesLeft}min left, last used: ${Math.round((now - userData.lastUsed) / (60 * 1000))}min ago`\n };\n }\n \n // CHECK 4: NEW - Check for completed sessions\n const completedSessions = this.completedDemoSessions.get(userFingerprint) || [];\n const recentCompletedSessions = completedSessions.filter(session =>\n now - session.endTime < this.minTimeBetweenCompletedSessions\n );\n \n if (recentCompletedSessions.length > 0) {\n const lastCompletedSession = Math.max(...recentCompletedSessions.map(s => s.endTime));\n const timeUntilNext = this.minTimeBetweenCompletedSessions - (now - lastCompletedSession);\n \n console.log(`\u23F0 Recent session completed, waiting period active for user ${userFingerprint.substring(0, 12)}`);\n return {\n allowed: false,\n reason: 'recent_session_completed',\n timeUntilNext: timeUntilNext,\n message: `Please wait ${Math.ceil(timeUntilNext / (60 * 1000))} minutes after your last session before starting a new one.`,\n remaining: this.maxDemoSessionsPerUser - sessionsLast24h.length,\n debugInfo: `Last session ended ${Math.round((now - lastCompletedSession) / (60 * 1000))}min ago`\n };\n }\n \n console.log(`\u2705 Demo session approved for user ${userFingerprint.substring(0, 12)}`);\n return { \n allowed: true, \n reason: 'within_limits',\n remaining: this.maxDemoSessionsPerUser - sessionsLast24h.length,\n debugInfo: `Available: ${this.maxDemoSessionsPerUser - sessionsLast24h.length}/${this.maxDemoSessionsPerUser}`\n };\n }\n\n createDemoSessionForActivation() {\n const userFingerprint = this.generateAdvancedUserFingerprint(); // \u0418\u0421\u041F\u0420\u0410\u0412\u041B\u0415\u041D\u041E!\n \n if (this.activeDemoSessions.size >= this.maxGlobalDemoSessions) {\n return {\n success: false,\n reason: `Too many demo sessions active globally (${this.activeDemoSessions.size}/${this.maxGlobalDemoSessions}). Please try again later.`,\n blockingReason: 'global_limit'\n };\n }\n \n try {\n const demoPreimage = this.generateSecureDemoPreimage();\n const demoPaymentHash = 'demo_' + Array.from(crypto.getRandomValues(new Uint8Array(16)))\n .map(b => b.toString(16).padStart(2, '0')).join('');\n \n console.log('\uD83D\uDD04 Created demo session for activation:', {\n preimage: demoPreimage.substring(0, 16) + '...',\n paymentHash: demoPaymentHash.substring(0, 16) + '...'\n });\n \n return {\n success: true,\n sessionType: 'demo',\n preimage: demoPreimage,\n paymentHash: demoPaymentHash,\n duration: this.sessionPrices.demo.hours,\n durationMinutes: Math.round(this.demoSessionMaxDuration / (60 * 1000)),\n warning: `Demo session - limited to ${Math.round(this.demoSessionMaxDuration / (60 * 1000))} minutes`,\n globalActive: this.activeDemoSessions.size + 1,\n globalLimit: this.maxGlobalDemoSessions\n };\n } catch (error) {\n console.error('Failed to create demo session for activation:', error);\n return {\n success: false,\n reason: 'Failed to generate demo session for activation. Please try again.'\n };\n }\n }\n\n async verifyDemoSessionForActivation(preimage, paymentHash) {\n console.log('\uD83C\uDFAE Verifying demo session for activation (bypassing limits)...');\n \n try {\n if (!preimage || !paymentHash) {\n throw new Error('Missing preimage or payment hash');\n }\n \n if (typeof preimage !== 'string' || typeof paymentHash !== 'string') {\n throw new Error('Preimage and payment hash must be strings');\n }\n \n if (!this.isDemoPreimage(preimage)) {\n throw new Error('Invalid demo preimage format');\n }\n \n const entropy = this.calculateEntropy(preimage);\n if (entropy < 3.5) {\n throw new Error(`Demo preimage has insufficient entropy: ${entropy.toFixed(2)}`);\n }\n \n if (this.activeDemoSessions.has(preimage)) {\n throw new Error('Demo session with this preimage is already active');\n }\n \n console.log('\u2705 Demo session verified for activation successfully');\n return { \n verified: true, \n method: 'demo-activation',\n sessionType: 'demo',\n isDemo: true,\n warning: 'Demo session - limited duration (6 minutes)'\n };\n \n } catch (error) {\n console.error('\u274C Demo session verification for activation failed:', error);\n return { \n verified: false, \n reason: error.message,\n stage: 'demo-activation'\n };\n }\n }\n}\n\nexport { PayPerSessionManager };", "// SessionTimer Component - v4.02.985 - ECDH + DTLS + SAS\nconst SessionTimer = ({ timeLeft, sessionType, sessionManager, onDisconnect }) => {\n const [currentTime, setCurrentTime] = React.useState(timeLeft || 0);\n const [showExpiredMessage, setShowExpiredMessage] = React.useState(false);\n const [initialized, setInitialized] = React.useState(false);\n const [connectionBroken, setConnectionBroken] = React.useState(false);\n \n\n const [loggedHidden, setLoggedHidden] = React.useState(false);\n\n React.useEffect(() => {\n if (connectionBroken) {\n if (!loggedHidden) {\n console.log('\u23F1\uFE0F SessionTimer initialization skipped - connection broken');\n setLoggedHidden(true);\n }\n return;\n }\n \n let initialTime = 0;\n \n if (sessionManager?.hasActiveSession()) {\n initialTime = sessionManager.getTimeLeft();\n } else if (timeLeft && timeLeft > 0) {\n initialTime = timeLeft;\n }\n\n if (initialTime <= 0) {\n setCurrentTime(0);\n setInitialized(false);\n setLoggedHidden(true);\n return;\n }\n\n if (connectionBroken) {\n setCurrentTime(0);\n setInitialized(false);\n setLoggedHidden(true);\n return;\n }\n setCurrentTime(initialTime);\n setInitialized(true);\n setLoggedHidden(false); \n }, [sessionManager, connectionBroken]);\n\n React.useEffect(() => {\n if (connectionBroken) {\n if (!loggedHidden) {\n setLoggedHidden(true);\n }\n return;\n }\n \n if (timeLeft && timeLeft > 0) {\n setCurrentTime(timeLeft);\n }\n setLoggedHidden(false);\n }, [timeLeft, connectionBroken]);\n\n React.useEffect(() => {\n if (!initialized) {\n return;\n }\n\n if (connectionBroken) {\n if (!loggedHidden) {\n setLoggedHidden(true);\n }\n return;\n }\n\n if (!currentTime || currentTime <= 0 || !sessionManager) {\n return;\n }\n\n const interval = setInterval(() => {\n if (connectionBroken) {\n setCurrentTime(0);\n clearInterval(interval);\n return;\n }\n \n if (sessionManager?.hasActiveSession()) {\n const newTime = sessionManager.getTimeLeft();\n setCurrentTime(newTime);\n\n if (window.DEBUG_MODE && Math.floor(Date.now() / 30000) !== Math.floor((Date.now() - 1000) / 30000)) {\n console.log('\u23F1\uFE0F Timer tick:', Math.floor(newTime / 1000) + 's');\n }\n\n if (newTime <= 0) {\n setShowExpiredMessage(true);\n setTimeout(() => setShowExpiredMessage(false), 5000);\n clearInterval(interval);\n }\n } else {\n setCurrentTime(0);\n clearInterval(interval);\n }\n }, 1000);\n\n return () => {\n clearInterval(interval);\n };\n }, [initialized, currentTime, sessionManager, connectionBroken]);\n\n React.useEffect(() => {\n const handleSessionTimerUpdate = (event) => {\n if (connectionBroken) {\n return;\n }\n \n if (event.detail.timeLeft && event.detail.timeLeft > 0) {\n setCurrentTime(event.detail.timeLeft);\n }\n };\n\n const handleForceHeaderUpdate = (event) => {\n if (connectionBroken) {\n return;\n }\n \n if (sessionManager && sessionManager.hasActiveSession()) {\n const newTime = sessionManager.getTimeLeft();\n setCurrentTime(newTime);\n } else {\n setCurrentTime(event.detail.timeLeft);\n }\n };\n\n const handlePeerDisconnect = (event) => {\n setConnectionBroken(true);\n setCurrentTime(0);\n setShowExpiredMessage(false);\n setLoggedHidden(false);\n };\n\n const handleNewConnection = (event) => {\n setConnectionBroken(false);\n setLoggedHidden(false); \n };\n\n const handleConnectionCleaned = (event) => {\n setConnectionBroken(true);\n setCurrentTime(0);\n setShowExpiredMessage(false);\n setInitialized(false);\n setLoggedHidden(false);\n };\n\n const handleSessionReset = (event) => {\n setConnectionBroken(true);\n setCurrentTime(0);\n setShowExpiredMessage(false);\n setInitialized(false);\n setLoggedHidden(false);\n };\n\n const handleSessionCleanup = (event) => {\n setConnectionBroken(true);\n setCurrentTime(0);\n setShowExpiredMessage(false);\n setInitialized(false);\n setLoggedHidden(false);\n };\n\n const handleDisconnected = (event) => {\n setConnectionBroken(true);\n setCurrentTime(0);\n setShowExpiredMessage(false);\n setInitialized(false);\n setLoggedHidden(false);\n };\n\n document.addEventListener('session-timer-update', handleSessionTimerUpdate);\n document.addEventListener('force-header-update', handleForceHeaderUpdate);\n document.addEventListener('peer-disconnect', handlePeerDisconnect);\n document.addEventListener('new-connection', handleNewConnection);\n document.addEventListener('connection-cleaned', handleConnectionCleaned);\n document.addEventListener('session-reset', handleSessionReset);\n document.addEventListener('session-cleanup', handleSessionCleanup);\n document.addEventListener('disconnected', handleDisconnected);\n\n return () => {\n document.removeEventListener('session-timer-update', handleSessionTimerUpdate);\n document.removeEventListener('force-header-update', handleForceHeaderUpdate);\n document.removeEventListener('peer-disconnect', handlePeerDisconnect);\n document.removeEventListener('new-connection', handleNewConnection);\n document.removeEventListener('connection-cleaned', handleConnectionCleaned);\n document.removeEventListener('session-reset', handleSessionReset);\n document.removeEventListener('session-cleanup', handleSessionCleanup);\n document.removeEventListener('disconnected', handleDisconnected);\n };\n }, [sessionManager]);\n\n if (showExpiredMessage) {\n return React.createElement('div', {\n className: 'session-timer expired flex items-center space-x-2 px-3 py-1.5 rounded-lg animate-pulse',\n style: { background: 'linear-gradient(135deg, rgba(239, 68, 68, 0.2) 0%, rgba(220, 38, 38, 0.2) 100%)' }\n }, [\n React.createElement('i', {\n key: 'icon',\n className: 'fas fa-exclamation-triangle text-red-400'\n }),\n React.createElement('span', {\n key: 'message',\n className: 'text-red-400 text-sm font-medium'\n }, 'Session Expired!')\n ]);\n }\n\n if (!sessionManager) {\n if (!loggedHidden) {\n console.log('\u23F1\uFE0F SessionTimer hidden - no sessionManager');\n setLoggedHidden(true);\n }\n return null;\n }\n\n if (connectionBroken) {\n if (!loggedHidden) {\n console.log('\u23F1\uFE0F SessionTimer hidden - connection broken');\n setLoggedHidden(true);\n }\n return null;\n }\n\n if (!currentTime || currentTime <= 0) {\n if (!loggedHidden) {\n console.log('\u23F1\uFE0F SessionTimer hidden - no time left, currentTime:', currentTime);\n setLoggedHidden(true);\n }\n return null;\n }\n\n if (loggedHidden) {\n setLoggedHidden(false);\n }\n\n const totalMinutes = Math.floor(currentTime / (60 * 1000));\n const totalSeconds = Math.floor(currentTime / 1000);\n \n const isDemo = sessionType === 'demo';\n const isWarning = isDemo ? totalMinutes <= 2 : totalMinutes <= 10;\n const isCritical = isDemo ? totalSeconds <= 60 : totalMinutes <= 5;\n\n const formatTime = (ms) => {\n const hours = Math.floor(ms / (60 * 60 * 1000));\n const minutes = Math.floor((ms % (60 * 60 * 1000)) / (60 * 1000));\n const seconds = Math.floor((ms % (60 * 1000)) / 1000);\n\n if (hours > 0) {\n return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;\n } else {\n return `${minutes}:${seconds.toString().padStart(2, '0')}`;\n }\n };\n\n const getTimerStyle = () => {\n const totalDuration = sessionType === 'demo' ? 6 * 60 * 1000 : 60 * 60 * 1000;\n const timeProgress = (totalDuration - currentTime) / totalDuration;\n \n let backgroundColor, textColor, iconColor, iconClass, shouldPulse;\n \n if (timeProgress <= 0.33) {\n backgroundColor = 'linear-gradient(135deg, rgba(34, 197, 94, 0.15) 0%, rgba(22, 163, 74, 0.15) 100%)';\n textColor = 'text-green-400';\n iconColor = 'text-green-400';\n iconClass = 'fas fa-clock';\n shouldPulse = false;\n } else if (timeProgress <= 0.66) {\n backgroundColor = 'linear-gradient(135deg, rgba(234, 179, 8, 0.15) 0%, rgba(202, 138, 4, 0.15) 100%)';\n textColor = 'text-yellow-400';\n iconColor = 'text-yellow-400';\n iconClass = 'fas fa-clock';\n shouldPulse = false;\n } else {\n backgroundColor = 'linear-gradient(135deg, rgba(239, 68, 68, 0.15) 0%, rgba(220, 38, 38, 0.15) 100%)';\n textColor = 'text-red-400';\n iconColor = 'text-red-400';\n iconClass = 'fas fa-exclamation-triangle';\n shouldPulse = true;\n }\n \n return { backgroundColor, textColor, iconColor, iconClass, shouldPulse };\n };\n\n const timerStyle = getTimerStyle();\n \n const handleTimerClick = () => {\n if (onDisconnect && typeof onDisconnect === 'function') {\n onDisconnect();\n }\n };\n\n return React.createElement('div', {\n className: `session-timer flex items-center space-x-2 px-3 py-1.5 rounded-lg transition-all duration-500 cursor-pointer hover:opacity-80 ${\n isDemo ? 'demo-session' : ''\n } ${timerStyle.shouldPulse ? 'animate-pulse' : ''}`,\n style: { background: timerStyle.backgroundColor },\n onClick: handleTimerClick,\n title: 'Click to disconnect and clear session'\n }, [\n React.createElement('i', {\n key: 'icon',\n className: `${timerStyle.iconClass} ${timerStyle.iconColor}`\n }),\n React.createElement('span', {\n key: 'time',\n className: `text-sm font-mono font-semibold ${timerStyle.textColor}`\n }, formatTime(currentTime)),\n React.createElement('div', {\n key: 'progress',\n className: 'ml-2 w-16 h-1 bg-gray-700 rounded-full overflow-hidden'\n }, [\n React.createElement('div', {\n key: 'progress-bar',\n className: `${timerStyle.textColor.replace('text-', 'bg-')} h-full rounded-full transition-all duration-500`,\n style: { \n width: `${Math.max(0, Math.min(100, (currentTime / (sessionType === 'demo' ? 6 * 60 * 1000 : 60 * 60 * 1000)) * 100))}%`\n }\n })\n ])\n ]);\n};\n\nwindow.SessionTimer = SessionTimer;\n\nwindow.updateSessionTimer = (newTimeLeft, newSessionType) => {\n document.dispatchEvent(new CustomEvent('session-timer-update', {\n detail: { timeLeft: newTimeLeft, sessionType: newSessionType }\n }));\n};\n\n", "const EnhancedMinimalHeader = ({ \n status, \n fingerprint, \n verificationCode, \n onDisconnect, \n isConnected, \n securityLevel, \n sessionManager, \n sessionTimeLeft,\n webrtcManager \n}) => {\n const [currentTimeLeft, setCurrentTimeLeft] = React.useState(sessionTimeLeft || 0);\n const [hasActiveSession, setHasActiveSession] = React.useState(false);\n const [sessionType, setSessionType] = React.useState('unknown');\n const [realSecurityLevel, setRealSecurityLevel] = React.useState(null);\n const [lastSecurityUpdate, setLastSecurityUpdate] = React.useState(0);\n\n // ============================================\n // FIXED SECURITY UPDATE LOGIC\n // ============================================\n \n React.useEffect(() => {\n let isUpdating = false; \n let lastUpdateAttempt = 0; \n \n const updateRealSecurityStatus = async () => {\n const now = Date.now();\n if (now - lastUpdateAttempt < 10000) { \n return;\n }\n\n if (isUpdating) {\n return;\n }\n \n isUpdating = true;\n lastUpdateAttempt = now;\n \n try {\n if (!webrtcManager || !isConnected) {\n return;\n }\n \n const activeWebrtcManager = webrtcManager;\n \n let realSecurityData = null;\n \n if (typeof activeWebrtcManager.getRealSecurityLevel === 'function') {\n realSecurityData = await activeWebrtcManager.getRealSecurityLevel();\n } else if (typeof activeWebrtcManager.calculateAndReportSecurityLevel === 'function') {\n realSecurityData = await activeWebrtcManager.calculateAndReportSecurityLevel();\n } else {\n realSecurityData = await window.EnhancedSecureCryptoUtils.calculateSecurityLevel(activeWebrtcManager);\n }\n \n if (window.DEBUG_MODE) {\n console.log('\uD83D\uDD10 REAL security level calculated:', {\n level: realSecurityData?.level,\n score: realSecurityData?.score,\n passedChecks: realSecurityData?.passedChecks,\n totalChecks: realSecurityData?.totalChecks,\n isRealData: realSecurityData?.isRealData,\n sessionType: realSecurityData?.sessionType,\n maxPossibleScore: realSecurityData?.maxPossibleScore,\n verificationResults: realSecurityData?.verificationResults ? Object.keys(realSecurityData.verificationResults) : []\n });\n }\n \n if (realSecurityData && realSecurityData.isRealData !== false) {\n const currentScore = realSecurityLevel?.score || 0;\n const newScore = realSecurityData.score || 0;\n\n if (currentScore !== newScore || !realSecurityLevel) {\n setRealSecurityLevel(realSecurityData);\n setLastSecurityUpdate(now);\n \n if (window.DEBUG_MODE) {\n console.log('\u2705 Security level updated in header component:', {\n oldScore: currentScore,\n newScore: newScore,\n sessionType: realSecurityData.sessionType\n });\n }\n } else if (window.DEBUG_MODE) {\n console.log('\u2139\uFE0F Security level unchanged, skipping update');\n }\n } else {\n console.warn('\u26A0\uFE0F Security calculation returned invalid data');\n }\n \n } catch (error) {\n console.error('\u274C Error in real security calculation:', error);\n } finally {\n isUpdating = false;\n }\n };\n\n if (isConnected) {\n updateRealSecurityStatus();\n \n if (!realSecurityLevel || realSecurityLevel.score < 50) {\n const retryInterval = setInterval(() => {\n if (!realSecurityLevel || realSecurityLevel.score < 50) {\n updateRealSecurityStatus();\n } else {\n clearInterval(retryInterval);\n }\n }, 5000); \n \n setTimeout(() => clearInterval(retryInterval), 30000);\n }\n }\n\n const interval = setInterval(updateRealSecurityStatus, 30000);\n \n return () => clearInterval(interval);\n }, [webrtcManager, isConnected, lastSecurityUpdate, realSecurityLevel]);\n\n // ============================================\n // FIXED EVENT HANDLERS\n // ============================================\n\n React.useEffect(() => {\n const handleSecurityUpdate = (event) => {\n if (window.DEBUG_MODE) {\n console.log('\uD83D\uDD12 Security level update event received:', event.detail);\n }\n\n setTimeout(() => {\n setLastSecurityUpdate(0);\n }, 100);\n };\n\n const handleRealSecurityCalculated = (event) => {\n if (window.DEBUG_MODE) {\n console.log('\uD83D\uDD10 Real security calculated event:', event.detail);\n }\n \n if (event.detail && event.detail.securityData) {\n setRealSecurityLevel(event.detail.securityData);\n setLastSecurityUpdate(Date.now());\n }\n };\n\n document.addEventListener('security-level-updated', handleSecurityUpdate);\n document.addEventListener('real-security-calculated', handleRealSecurityCalculated);\n \n window.forceHeaderSecurityUpdate = (webrtcManager) => {\n if (window.DEBUG_MODE) {\n console.log('\uD83D\uDD04 Force header security update called');\n }\n \n if (webrtcManager && window.EnhancedSecureCryptoUtils) {\n window.EnhancedSecureCryptoUtils.calculateSecurityLevel(webrtcManager)\n .then(securityData => {\n if (securityData && securityData.isRealData !== false) {\n setRealSecurityLevel(securityData);\n setLastSecurityUpdate(Date.now());\n console.log('\u2705 Header security level force-updated');\n }\n })\n .catch(error => {\n console.error('\u274C Force update failed:', error);\n });\n } else {\n setLastSecurityUpdate(0); \n }\n };\n\n return () => {\n document.removeEventListener('security-level-updated', handleSecurityUpdate);\n document.removeEventListener('real-security-calculated', handleRealSecurityCalculated);\n };\n }, []);\n\n // ============================================\n // REST of the component logic\n // ============================================\n\n React.useEffect(() => {\n const updateSessionInfo = () => {\n if (sessionManager) {\n const isActive = sessionManager.hasActiveSession();\n const timeLeft = sessionManager.getTimeLeft();\n const currentSession = sessionManager.currentSession;\n \n setHasActiveSession(isActive);\n setCurrentTimeLeft(timeLeft);\n setSessionType(currentSession?.type || 'unknown');\n }\n };\n\n updateSessionInfo();\n const interval = setInterval(updateSessionInfo, 1000);\n return () => clearInterval(interval);\n }, [sessionManager]);\n\n React.useEffect(() => {\n if (sessionManager?.hasActiveSession()) {\n setCurrentTimeLeft(sessionManager.getTimeLeft());\n setHasActiveSession(true);\n } else {\n setHasActiveSession(false);\n setRealSecurityLevel(null);\n setLastSecurityUpdate(0);\n setSessionType('unknown');\n }\n }, [sessionManager, sessionTimeLeft]);\n\n React.useEffect(() => {\n const handleForceUpdate = (event) => {\n if (sessionManager) {\n const isActive = sessionManager.hasActiveSession();\n const timeLeft = sessionManager.getTimeLeft();\n const currentSession = sessionManager.currentSession;\n \n setHasActiveSession(isActive);\n setCurrentTimeLeft(timeLeft);\n setSessionType(currentSession?.type || 'unknown');\n }\n };\n\n // Connection cleanup handler (use existing event from module)\n const handleConnectionCleaned = () => {\n if (window.DEBUG_MODE) {\n console.log('\uD83E\uDDF9 Connection cleaned - clearing security data in header');\n }\n\n setRealSecurityLevel(null);\n setLastSecurityUpdate(0);\n\n setHasActiveSession(false);\n setCurrentTimeLeft(0);\n setSessionType('unknown');\n };\n\n const handlePeerDisconnect = () => {\n if (window.DEBUG_MODE) {\n console.log('\uD83D\uDC4B Peer disconnect detected - clearing security data in header');\n }\n\n setRealSecurityLevel(null);\n setLastSecurityUpdate(0);\n };\n\n document.addEventListener('force-header-update', handleForceUpdate);\n document.addEventListener('peer-disconnect', handlePeerDisconnect);\n document.addEventListener('connection-cleaned', handleConnectionCleaned);\n \n return () => {\n document.removeEventListener('force-header-update', handleForceUpdate);\n document.removeEventListener('peer-disconnect', handlePeerDisconnect);\n document.removeEventListener('connection-cleaned', handleConnectionCleaned);\n };\n }, [sessionManager]);\n\n // ============================================\n // SECURITY INDICATOR CLICK HANDLER\n // ============================================\n\n const handleSecurityClick = (event) => {\n // Check if it's a right-click or Ctrl+click to disconnect\n if (event && (event.button === 2 || event.ctrlKey || event.metaKey)) {\n if (onDisconnect && typeof onDisconnect === 'function') {\n onDisconnect();\n return;\n }\n }\n\n if (!realSecurityLevel) {\n alert('Security verification in progress...\\nPlease wait for real-time cryptographic verification to complete.');\n return;\n }\n\n // Detailed information about the REAL security check\n let message = `\uD83D\uDD12 REAL-TIME SECURITY VERIFICATION\\n\\n`;\n message += `Security Level: ${realSecurityLevel.level} (${realSecurityLevel.score}%)\\n`;\n message += `Session Type: ${realSecurityLevel.sessionType || 'demo'}\\n`;\n message += `Verification Time: ${new Date(realSecurityLevel.timestamp).toLocaleTimeString()}\\n`;\n message += `Data Source: ${realSecurityLevel.isRealData ? 'Real Cryptographic Tests' : 'Simulated Data'}\\n\\n`;\n \n if (realSecurityLevel.verificationResults) {\n message += 'DETAILED CRYPTOGRAPHIC TESTS:\\n';\n message += '=' + '='.repeat(40) + '\\n';\n \n const passedTests = Object.entries(realSecurityLevel.verificationResults).filter(([key, result]) => result.passed);\n const failedTests = Object.entries(realSecurityLevel.verificationResults).filter(([key, result]) => !result.passed);\n \n if (passedTests.length > 0) {\n message += '\u2705 PASSED TESTS:\\n';\n passedTests.forEach(([key, result]) => {\n const testName = key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase());\n message += ` ${testName}: ${result.details}\\n`;\n });\n message += '\\n';\n }\n \n if (failedTests.length > 0) {\n message += '\u274C UNAVAILABLE/Failed TESTS:\\n';\n failedTests.forEach(([key, result]) => {\n const testName = key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase());\n message += ` ${testName}: ${result.details}\\n`;\n });\n message += '\\n';\n }\n \n message += `SUMMARY:\\n`;\n message += `Passed: ${realSecurityLevel.passedChecks}/${realSecurityLevel.totalChecks} tests\\n`;\n }\n \n // Add information about what is available in other sessions\n message += `\\n\uD83D\uDCCB WHAT'S AVAILABLE IN OTHER SESSIONS:\\n`;\n message += '=' + '='.repeat(40) + '\\n';\n \n if (realSecurityLevel.sessionType === 'demo') {\n message += `\uD83D\uDD12 BASIC SESSION (5,000 sat - $2.00):\\n`;\n message += ` \u2022 ECDSA Digital Signatures\\n`;\n message += ` \u2022 Metadata Protection\\n`;\n message += ` \u2022 Perfect Forward Secrecy\\n`;\n message += ` \u2022 Nested Encryption\\n`;\n message += ` \u2022 Packet Padding\\n\\n`;\n \n message += `\uD83D\uDE80 PREMIUM SESSION (20,000 sat - $8.00):\\n`;\n message += ` \u2022 All Basic + Enhanced features\\n`;\n message += ` \u2022 Traffic Obfuscation\\n`;\n message += ` \u2022 Fake Traffic Generation\\n`;\n message += ` \u2022 Decoy Channels\\n`;\n message += ` \u2022 Anti-Fingerprinting\\n`;\n message += ` \u2022 Message Chunking\\n`;\n message += ` \u2022 Advanced Replay Protection\\n`;\n } else if (realSecurityLevel.sessionType === 'basic') {\n message += `\uD83D\uDE80 PREMIUM SESSION (20,000 sat - $8.00):\\n`;\n message += ` \u2022 Traffic Obfuscation\\n`;\n message += ` \u2022 Fake Traffic Generation\\n`;\n message += ` \u2022 Decoy Channels\\n`;\n message += ` \u2022 Anti-Fingerprinting\\n`;\n message += ` \u2022 Message Chunking\\n`;\n message += ` \u2022 Advanced Replay Protection\\n`;\n }\n \n message += `\\n${realSecurityLevel.details || 'Real cryptographic verification completed'}`;\n \n if (realSecurityLevel.isRealData) {\n message += '\\n\\n\u2705 This is REAL-TIME verification using actual cryptographic functions.';\n } else {\n message += '\\n\\n\u26A0\uFE0F Warning: This data may be simulated. Connection may not be fully established.';\n }\n \n alert(message);\n };\n\n // ============================================\n // DISPLAY UTILITIES\n // ============================================\n\n const getStatusConfig = () => {\n switch (status) {\n case 'connected':\n return {\n text: 'Connected',\n className: 'status-connected',\n badgeClass: 'bg-green-500/10 text-green-400 border-green-500/20'\n };\n case 'verifying':\n return {\n text: 'Verifying...',\n className: 'status-verifying',\n badgeClass: 'bg-purple-500/10 text-purple-400 border-purple-500/20'\n };\n case 'connecting':\n return {\n text: 'Connecting...',\n className: 'status-connecting',\n badgeClass: 'bg-blue-500/10 text-blue-400 border-blue-500/20'\n };\n case 'retrying':\n return {\n text: 'Retrying...',\n className: 'status-connecting',\n badgeClass: 'bg-yellow-500/10 text-yellow-400 border-yellow-500/20'\n };\n case 'failed':\n return {\n text: 'Error',\n className: 'status-failed',\n badgeClass: 'bg-red-500/10 text-red-400 border-red-500/20'\n };\n case 'reconnecting':\n return {\n text: 'Reconnecting...',\n className: 'status-connecting',\n badgeClass: 'bg-yellow-500/10 text-yellow-400 border-yellow-500/20'\n };\n case 'peer_disconnected':\n return {\n text: 'Peer disconnected',\n className: 'status-failed',\n badgeClass: 'bg-orange-500/10 text-orange-400 border-orange-500/20'\n };\n default:\n return {\n text: 'Not connected',\n className: 'status-disconnected',\n badgeClass: 'bg-gray-500/10 text-gray-400 border-gray-500/20'\n };\n }\n };\n\n const config = getStatusConfig();\n const displaySecurityLevel = realSecurityLevel || securityLevel;\n \n const shouldShowTimer = hasActiveSession && currentTimeLeft > 0 && window.SessionTimer;\n\n // ============================================\n // DATA RELIABILITY INDICATOR\n // ============================================\n\n const getSecurityIndicatorDetails = () => {\n if (!displaySecurityLevel) {\n return {\n tooltip: 'Security verification in progress...',\n isVerified: false,\n dataSource: 'loading'\n };\n }\n \n const isRealData = displaySecurityLevel.isRealData !== false;\n const baseTooltip = `${displaySecurityLevel.level} (${displaySecurityLevel.score}%)`;\n \n if (isRealData) {\n return {\n tooltip: `${baseTooltip} - Real-time verification \u2705\\nRight-click or Ctrl+click to disconnect`,\n isVerified: true,\n dataSource: 'real'\n };\n } else {\n return {\n tooltip: `${baseTooltip} - Estimated (connection establishing...)\\nRight-click or Ctrl+click to disconnect`,\n isVerified: false,\n dataSource: 'estimated'\n };\n }\n };\n\n const securityDetails = getSecurityIndicatorDetails();\n\n // ============================================\n // ADDING global methods for debugging\n // ============================================\n\n React.useEffect(() => {\n window.debugHeaderSecurity = () => {\n console.log('\uD83D\uDD0D Header Security Debug:', {\n realSecurityLevel,\n lastSecurityUpdate,\n isConnected,\n webrtcManagerProp: !!webrtcManager,\n windowWebrtcManager: !!window.webrtcManager,\n cryptoUtils: !!window.EnhancedSecureCryptoUtils,\n displaySecurityLevel: displaySecurityLevel,\n securityDetails: securityDetails\n });\n };\n \n return () => {\n delete window.debugHeaderSecurity;\n };\n }, [realSecurityLevel, lastSecurityUpdate, isConnected, webrtcManager, displaySecurityLevel, securityDetails]);\n\n // ============================================\n // RENDER\n // ============================================\n\n return React.createElement('header', {\n className: 'header-minimal sticky top-0 z-50'\n }, [\n React.createElement('div', {\n key: 'container',\n className: 'max-w-7xl mx-auto px-4 sm:px-6 lg:px-8'\n }, [\n React.createElement('div', {\n key: 'content',\n className: 'flex items-center justify-between h-16'\n }, [\n // Logo and Title\n React.createElement('div', {\n key: 'logo-section',\n className: 'flex items-center space-x-2 sm:space-x-3'\n }, [\n React.createElement('div', {\n key: 'logo',\n className: 'icon-container w-8 h-8 sm:w-10 sm:h-10'\n }, [\n React.createElement('i', {\n className: 'fas fa-shield-halved accent-orange text-sm sm:text-base'\n })\n ]),\n React.createElement('div', {\n key: 'title-section'\n }, [\n React.createElement('h1', {\n key: 'title',\n className: 'text-lg sm:text-xl font-semibold text-primary'\n }, 'SecureBit.chat'),\n React.createElement('p', {\n key: 'subtitle',\n className: 'text-xs sm:text-sm text-muted hidden sm:block'\n }, 'End-to-end freedom v4.02.985')\n ])\n ]),\n\n // Status and Controls - Responsive\n React.createElement('div', {\n key: 'status-section',\n className: 'flex items-center space-x-2 sm:space-x-3'\n }, [\n // Session Timer\n shouldShowTimer && React.createElement(window.SessionTimer, {\n key: 'session-timer',\n timeLeft: currentTimeLeft,\n sessionType: sessionType,\n sessionManager: sessionManager,\n onDisconnect: onDisconnect\n }),\n\n displaySecurityLevel && React.createElement('div', {\n key: 'security-level',\n className: 'hidden md:flex items-center space-x-2 cursor-pointer hover:opacity-80 transition-opacity duration-200',\n onClick: handleSecurityClick,\n onContextMenu: (e) => {\n e.preventDefault();\n if (onDisconnect && typeof onDisconnect === 'function') {\n onDisconnect();\n }\n },\n title: securityDetails.tooltip\n }, [\n React.createElement('div', {\n key: 'security-icon',\n className: `w-6 h-6 rounded-full flex items-center justify-center relative ${\n displaySecurityLevel.color === 'green' ? 'bg-green-500/20' :\n displaySecurityLevel.color === 'orange' ? 'bg-orange-500/20' :\n displaySecurityLevel.color === 'yellow' ? 'bg-yellow-500/20' : 'bg-red-500/20'\n } ${securityDetails.isVerified ? '' : 'animate-pulse'}`\n }, [\n React.createElement('i', {\n className: `fas fa-shield-alt text-xs ${\n displaySecurityLevel.color === 'green' ? 'text-green-400' :\n displaySecurityLevel.color === 'orange' ? 'text-orange-400' :\n displaySecurityLevel.color === 'yellow' ? 'text-yellow-400' : 'text-red-400'\n }`\n })\n ]),\n React.createElement('div', {\n key: 'security-info',\n className: 'flex flex-col'\n }, [\n React.createElement('div', {\n key: 'security-level-text',\n className: 'text-xs font-medium text-primary flex items-center space-x-1'\n }, [\n React.createElement('span', {}, `${displaySecurityLevel.level} (${displaySecurityLevel.score}%)`)\n ]),\n React.createElement('div', {\n key: 'security-details',\n className: 'text-xs text-muted mt-1 hidden lg:block'\n }, securityDetails.dataSource === 'real' ? \n `${displaySecurityLevel.passedChecks || 0}/${displaySecurityLevel.totalChecks || 0} tests` :\n (displaySecurityLevel.details || `Stage ${displaySecurityLevel.stage || 1}`)\n ),\n React.createElement('div', {\n key: 'security-progress',\n className: 'w-16 h-1 bg-gray-600 rounded-full overflow-hidden'\n }, [\n React.createElement('div', {\n key: 'progress-bar',\n className: `h-full transition-all duration-500 ${\n displaySecurityLevel.color === 'green' ? 'bg-green-400' :\n displaySecurityLevel.color === 'orange' ? 'bg-orange-400' :\n displaySecurityLevel.color === 'yellow' ? 'bg-yellow-400' : 'bg-red-400'\n }`,\n style: { width: `${displaySecurityLevel.score}%` }\n })\n ])\n ])\n ]),\n\n // Mobile Security Indicator\n displaySecurityLevel && React.createElement('div', {\n key: 'mobile-security',\n className: 'md:hidden flex items-center'\n }, [\n React.createElement('div', {\n key: 'mobile-security-icon',\n className: `w-8 h-8 rounded-full flex items-center justify-center cursor-pointer hover:opacity-80 transition-opacity duration-200 relative ${\n displaySecurityLevel.color === 'green' ? 'bg-green-500/20' :\n displaySecurityLevel.color === 'orange' ? 'bg-orange-500/20' :\n displaySecurityLevel.color === 'yellow' ? 'bg-yellow-500/20' : 'bg-red-500/20'\n } ${securityDetails.isVerified ? '' : 'animate-pulse'}`,\n title: securityDetails.tooltip,\n onClick: handleSecurityClick,\n onContextMenu: (e) => {\n e.preventDefault();\n if (onDisconnect && typeof onDisconnect === 'function') {\n onDisconnect();\n }\n }\n }, [\n React.createElement('i', {\n className: `fas fa-shield-alt text-sm ${\n displaySecurityLevel.color === 'green' ? 'text-green-400' :\n displaySecurityLevel.color === 'orange' ? 'text-orange-400' :\n displaySecurityLevel.color === 'yellow' ? 'text-yellow-400' : 'text-red-400'\n }`\n })\n ])\n ]),\n\n // Status Badge\n React.createElement('div', {\n key: 'status-badge',\n className: `px-2 sm:px-3 py-1.5 rounded-lg border ${config.badgeClass} flex items-center space-x-1 sm:space-x-2`\n }, [\n React.createElement('span', {\n key: 'status-dot',\n className: `status-dot ${config.className}`\n }),\n React.createElement('span', {\n key: 'status-text',\n className: 'text-xs sm:text-sm font-medium'\n }, config.text)\n ]),\n\n // Disconnect Button\n isConnected && React.createElement('button', {\n key: 'disconnect-btn',\n onClick: onDisconnect,\n className: 'p-1.5 sm:px-3 sm:py-1.5 bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/20 rounded-lg transition-all duration-200 text-sm'\n }, [\n React.createElement('i', {\n className: 'fas fa-power-off sm:mr-2'\n }),\n React.createElement('span', {\n className: 'hidden sm:inline'\n }, 'Disconnect')\n ])\n ])\n ])\n ])\n ]);\n};\n\nwindow.EnhancedMinimalHeader = EnhancedMinimalHeader;\n", "const SessionTypeSelector = ({ onSelectType, onCancel, sessionManager }) => {\n const [selectedType, setSelectedType] = React.useState(null);\n const [demoInfo, setDemoInfo] = React.useState(null);\n const [refreshTimer, setRefreshTimer] = React.useState(null);\n const [lastRefresh, setLastRefresh] = React.useState(Date.now());\n\n // We receive up-to-date information about demo limits\n const updateDemoInfo = React.useCallback(() => {\n if (sessionManager && sessionManager.getDemoSessionInfo) {\n try {\n const info = sessionManager.getDemoSessionInfo();\n if (window.DEBUG_MODE) {\n console.log('\uD83D\uDD04 Demo info updated:', info);\n }\n setDemoInfo(info);\n setLastRefresh(Date.now());\n } catch (error) {\n console.error('Failed to get demo info:', error);\n }\n }\n }, [sessionManager]);\n\n // Update information on load and every 10 seconds\n React.useEffect(() => {\n updateDemoInfo();\n const interval = setInterval(updateDemoInfo, 10000); \n setRefreshTimer(interval);\n return () => {\n if (interval) clearInterval(interval);\n };\n }, [updateDemoInfo]);\n\n // Clear timer on unmount\n React.useEffect(() => {\n return () => {\n if (refreshTimer) {\n clearInterval(refreshTimer);\n }\n };\n }, [refreshTimer]);\n\n const sessionTypes = [\n { \n id: 'demo', \n name: 'Demo', \n duration: '6 minutes', \n price: '0 sat', \n usd: '$0.00', \n popular: false,\n securityLevel: 'Basic',\n securityBadge: 'BASIC',\n securityColor: 'bg-blue-500/20 text-blue-300',\n description: 'Limited testing session with basic security',\n features: [\n 'Basic end-to-end encryption', \n 'Simple key exchange', \n 'Message integrity',\n 'Rate limiting'\n ],\n limitations: [\n 'No advanced security features',\n 'No traffic obfuscation',\n 'No metadata protection'\n ]\n },\n { \n id: 'basic', \n name: 'Basic', \n duration: '1 hour', \n price: '5,000 sat', \n usd: '$2.00',\n securityLevel: 'Enhanced',\n securityBadge: 'ENHANCED',\n securityColor: 'bg-orange-500/20 text-orange-300',\n popular: true,\n description: 'Full featured session with enhanced security',\n features: [\n 'All basic features',\n 'ECDSA digital signatures', \n 'Metadata protection', \n 'Perfect forward secrecy',\n 'Nested encryption',\n 'Packet padding',\n 'Complete ASN.1 validation',\n 'OID and EC point verification',\n 'SPKI structure validation',\n '18-layer security architecture',\n 'ASN.1 Validated'\n ],\n limitations: [\n 'Limited traffic obfuscation',\n 'No fake traffic generation'\n ]\n },\n { \n id: 'premium', \n name: 'Premium', \n duration: '6 hours', \n price: '20,000 sat', \n usd: '$8.00',\n securityLevel: 'Maximum',\n securityBadge: 'MAXIMUM',\n securityColor: 'bg-green-500/20 text-green-300',\n description: 'Extended session with maximum security protection',\n features: [\n 'All enhanced features',\n 'Traffic obfuscation', \n 'Fake traffic generation',\n 'Decoy channels',\n 'Anti-fingerprinting',\n 'Message chunking',\n 'Advanced replay protection',\n 'Complete ASN.1 validation',\n 'OID and EC point verification',\n 'SPKI structure validation',\n '18-layer security architecture',\n 'ASN.1 Validated'\n ],\n limitations: []\n }\n ];\n\n const handleTypeSelect = (typeId) => {\n console.log(`\uD83C\uDFAF Selecting session type: ${typeId}`);\n \n if (typeId === 'demo') {\n if (demoInfo && !demoInfo.canUseNow) {\n let message = `Demo session not available.\\n\\n`;\n \n if (demoInfo.blockingReason === 'global_limit') {\n message += `Reason: Too many global demo sessions active (${demoInfo.globalActive}/${demoInfo.globalLimit})\\n`;\n message += `Please try again in a few minutes.`;\n } else if (demoInfo.blockingReason === 'daily_limit') {\n message += `Reason: Daily limit reached (${demoInfo.used}/${demoInfo.total})\\n`;\n message += `Next available: ${demoInfo.nextAvailable}`;\n } else if (demoInfo.blockingReason === 'session_cooldown') {\n message += `Reason: Cooldown between sessions\\n`;\n message += `Next available: ${demoInfo.nextAvailable}`;\n } else if (demoInfo.blockingReason === 'completion_cooldown') {\n message += `Reason: Wait period after last session\\n`;\n message += `Next available: ${demoInfo.nextAvailable}`;\n } else {\n message += `Next available: ${demoInfo.nextAvailable}`;\n }\n \n alert(message);\n return;\n }\n }\n setSelectedType(typeId);\n };\n\n const formatCooldownTime = (minutes) => {\n if (minutes >= 60) {\n const hours = Math.floor(minutes / 60);\n const remainingMinutes = minutes % 60;\n return `${hours}h ${remainingMinutes}m`;\n }\n return `${minutes}m`;\n };\n\n return React.createElement('div', { className: 'space-y-6' }, [\n React.createElement('div', { key: 'header', className: 'text-center' }, [\n React.createElement('h3', { \n key: 'title', \n className: 'text-xl font-semibold text-white mb-2' \n }, 'Choose Your Session'),\n React.createElement('p', { \n key: 'subtitle', \n className: 'text-gray-300 text-sm' \n }, 'Different security levels for different needs')\n ]),\n \n React.createElement('div', { key: 'types', className: 'space-y-4' }, \n sessionTypes.map(type => {\n const isDemo = type.id === 'demo';\n const isDisabled = isDemo && demoInfo && !demoInfo.canUseNow;\n \n return React.createElement('div', {\n key: type.id,\n onClick: () => !isDisabled && handleTypeSelect(type.id),\n className: `relative card-minimal ${selectedType === type.id ? 'card-minimal--selected' : ''} rounded-lg p-5 border-2 transition-all ${\n selectedType === type.id\n ? 'border-orange-500 bg-orange-500/15 ring-2 ring-orange-400 ring-offset-2 ring-offset-black/30'\n : 'border-gray-600 hover:border-orange-400'\n } ${type.popular && selectedType !== type.id ? 'ring-2 ring-orange-500/30' : ''} ${\n isDisabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'\n }`\n }, [\n // Popular badge\n type.popular && React.createElement('div', { \n key: 'popular-badge', \n className: 'absolute -top-2 right-3 bg-orange-500 text-white text-xs px-3 py-1 rounded-full font-medium' \n }, 'Most Popular'),\n \n React.createElement('div', { key: 'content', className: 'space-y-4' }, [\n // Header with name and security level\n React.createElement('div', { key: 'header', className: 'flex items-start justify-between' }, [\n React.createElement('div', { key: 'title-section' }, [\n React.createElement('div', { key: 'name-row', className: 'flex items-center gap-3 mb-2' }, [\n React.createElement('h4', { \n key: 'name', \n className: 'text-xl font-bold text-white' \n }, type.name),\n isDemo && React.createElement('span', {\n key: 'free-badge',\n className: 'text-xs bg-blue-500/20 text-blue-300 px-2 py-1 rounded-full font-medium'\n }, 'FREE'),\n React.createElement('span', {\n key: 'security-badge',\n className: `text-xs px-2 py-1 rounded-full font-medium ${type.securityColor}`\n }, type.securityBadge)\n ]),\n React.createElement('p', { \n key: 'duration', \n className: 'text-gray-300 font-medium mb-1' \n }, `Duration: ${type.duration}`),\n React.createElement('p', {\n key: 'description',\n className: 'text-sm text-gray-400'\n }, type.description)\n ]),\n React.createElement('div', { key: 'pricing', className: 'text-right' }, [\n React.createElement('div', { \n key: 'sats', \n className: `text-xl font-bold ${isDemo ? 'text-green-400' : 'text-orange-400'}` \n }, type.price),\n React.createElement('div', { \n key: 'usd', \n className: 'text-sm text-gray-400' \n }, type.usd)\n ])\n ]),\n\n // Demo status info\n isDemo && demoInfo && React.createElement('div', {\n key: 'demo-status',\n className: 'p-3 bg-blue-900/20 border border-blue-700/30 rounded-lg'\n }, [\n React.createElement('div', {\n key: 'availability',\n className: `text-sm font-medium ${demoInfo.canUseNow ? 'text-green-400' : 'text-yellow-400'}`\n }, demoInfo.canUseNow ? \n `\u2705 Available (${demoInfo.available}/${demoInfo.total} today)` : \n `\u23F0 Next: ${demoInfo.nextAvailable}`\n ),\n demoInfo.globalActive > 0 && React.createElement('div', {\n key: 'global-status',\n className: 'text-blue-300 text-xs mt-1'\n }, `\uD83C\uDF10 Global: ${demoInfo.globalActive}/${demoInfo.globalLimit} active`)\n ]),\n\n // Security features\n React.createElement('div', { key: 'features-section', className: 'space-y-3' }, [\n React.createElement('div', { key: 'features' }, [\n React.createElement('h5', {\n key: 'features-title',\n className: 'text-sm font-medium text-green-300 mb-2 flex items-center'\n }, [\n React.createElement('i', {\n key: 'shield-icon',\n className: 'fas fa-shield-alt mr-2'\n }),\n 'Security Features'\n ]),\n React.createElement('div', {\n key: 'features-list',\n className: 'grid grid-cols-1 gap-1'\n }, type.features.map((feature, index) => \n React.createElement('div', {\n key: index,\n className: 'flex items-center gap-2 text-xs text-gray-300'\n }, [\n React.createElement('i', {\n key: 'check',\n className: 'fas fa-check text-green-400 w-3'\n }),\n React.createElement('span', {\n key: 'text'\n }, feature)\n ])\n ))\n ]),\n\n // Limitations (if any)\n type.limitations && type.limitations.length > 0 && React.createElement('div', { key: 'limitations' }, [\n React.createElement('h5', {\n key: 'limitations-title',\n className: 'text-sm font-medium text-yellow-300 mb-2 flex items-center'\n }, [\n React.createElement('i', {\n key: 'info-icon',\n className: 'fas fa-info-circle mr-2'\n }),\n 'Limitations'\n ]),\n React.createElement('div', {\n key: 'limitations-list',\n className: 'grid grid-cols-1 gap-1'\n }, type.limitations.map((limitation, index) => \n React.createElement('div', {\n key: index,\n className: 'flex items-center gap-2 text-xs text-gray-400'\n }, [\n React.createElement('i', {\n key: 'minus',\n className: 'fas fa-minus text-yellow-400 w-3'\n }),\n React.createElement('span', {\n key: 'text'\n }, limitation)\n ])\n ))\n ])\n ])\n ])\n ])\n })\n ),\n \n demoInfo && React.createElement('div', { \n key: 'demo-info', \n className: 'bg-gradient-to-r from-blue-900/20 to-purple-900/20 border border-blue-700/50 rounded-lg p-4' \n }, [\n React.createElement('div', { \n key: 'demo-header', \n className: 'flex items-center gap-2 text-blue-300 text-sm font-medium mb-3' \n }, [\n React.createElement('i', {\n key: 'icon',\n className: 'fas fa-info-circle'\n }),\n React.createElement('span', {\n key: 'title'\n }, 'Demo Session Information')\n ]),\n React.createElement('div', { \n key: 'demo-details', \n className: 'grid grid-cols-1 md:grid-cols-2 gap-3 text-blue-200 text-xs' \n }, [\n React.createElement('div', { key: 'limits', className: 'space-y-1' }, [\n React.createElement('div', { key: 'daily' }, `\uD83D\uDCC5 Daily limit: ${demoInfo.total} sessions`),\n React.createElement('div', { key: 'duration' }, `\u23F1\uFE0F Duration: ${demoInfo.durationMinutes} minutes each`),\n React.createElement('div', { key: 'cooldown' }, `\u23F0 Cooldown: ${demoInfo.sessionCooldownMinutes} min between sessions`)\n ]),\n React.createElement('div', { key: 'status', className: 'space-y-1' }, [\n React.createElement('div', { key: 'used' }, `\uD83D\uDCCA Used today: ${demoInfo.used}/${demoInfo.total}`),\n React.createElement('div', { key: 'global' }, `\uD83C\uDF10 Global active: ${demoInfo.globalActive}/${demoInfo.globalLimit}`),\n React.createElement('div', { \n key: 'next', \n className: demoInfo.canUseNow ? 'text-green-300' : 'text-yellow-300' \n }, `\uD83C\uDFAF Status: ${demoInfo.canUseNow ? 'Available now' : demoInfo.nextAvailable}`)\n ])\n ]),\n React.createElement('div', {\n key: 'security-note',\n className: 'mt-3 p-2 bg-yellow-500/10 border border-yellow-500/20 rounded text-yellow-200 text-xs'\n }, '\u26A0\uFE0F Demo sessions use basic security only. Upgrade to paid sessions for enhanced protection.'),\n React.createElement('div', {\n key: 'last-updated',\n className: 'text-xs text-gray-400 mt-2 text-center'\n }, `Last updated: ${new Date(lastRefresh).toLocaleTimeString()}`)\n ]),\n\n // Action buttons\n React.createElement('div', { key: 'buttons', className: 'flex space-x-3' }, [\n React.createElement('button', { \n key: 'continue', \n onClick: () => {\n if (selectedType) {\n console.log(`\uD83D\uDE80 Proceeding with session type: ${selectedType}`);\n onSelectType(selectedType);\n }\n }, \n disabled: !selectedType || (selectedType === 'demo' && demoInfo && !demoInfo.canUseNow), \n className: 'flex-1 lightning-button text-white py-3 px-4 rounded-lg font-medium disabled:opacity-50 disabled:cursor-not-allowed transition-all' \n }, [\n React.createElement('i', { \n key: 'icon',\n className: selectedType === 'demo' ? 'fas fa-play mr-2' : 'fas fa-bolt mr-2' \n }), \n selectedType === 'demo' ? 'Start Demo Session' : 'Continue to Payment'\n ]),\n React.createElement('button', { \n key: 'cancel', \n onClick: onCancel, \n className: 'px-6 py-3 bg-gray-600 hover:bg-gray-500 text-white rounded-lg transition-all' \n }, 'Cancel'),\n \n ])\n ]);\n};\n\nwindow.SessionTypeSelector = SessionTypeSelector;", "const React = window.React;\nconst { useState, useEffect } = React;\n\nconst IntegratedLightningPayment = ({ sessionType, onSuccess, onCancel, paymentManager }) => {\n const [paymentMethod, setPaymentMethod] = useState('webln');\n const [preimage, setPreimage] = useState('');\n const [isProcessing, setIsProcessing] = useState(false);\n const [error, setError] = useState('');\n const [invoice, setInvoice] = useState(null);\n const [paymentStatus, setPaymentStatus] = useState('pending'); // pending, created, paid, expired\n const [qrCodeUrl, setQrCodeUrl] = useState('');\n\n useEffect(() => {\n createInvoice();\n }, [sessionType]);\n\n const createInvoice = async () => {\n if (sessionType === 'free') {\n setPaymentStatus('free');\n return;\n }\n\n setIsProcessing(true);\n setError('');\n\n try {\n \n if (!paymentManager) {\n throw new Error('Payment manager not available. Please check sessionManager initialization.');\n }\n\n const createdInvoice = await paymentManager.createLightningInvoice(sessionType);\n\n if (!createdInvoice) {\n throw new Error('Failed to create invoice');\n }\n\n setInvoice(createdInvoice);\n setPaymentStatus('created');\n\n if (createdInvoice.paymentRequest) {\n try {\n const dataUrl = await window.generateQRCode(createdInvoice.paymentRequest, { size: 300, margin: 2, errorCorrectionLevel: 'M' });\n setQrCodeUrl(dataUrl);\n } catch (e) {\n console.warn('QR local generation failed, showing placeholder');\n const dataUrl = await window.generateQRCode(createdInvoice.paymentRequest, { size: 300 });\n setQrCodeUrl(dataUrl);\n }\n }\n\n } catch (err) {\n console.error('Invoice creation failed:', err);\n setError(`Error creating invoice: ${err.message}`);\n } finally {\n setIsProcessing(false);\n }\n };\n\n const handleWebLNPayment = async () => {\n if (!window.webln) {\n setError('WebLN is not supported. Please use the Alby or Zeus wallet. SecureBit.chat v4.02.442 - ASN.1 Validated requires WebLN for Lightning payments.');\n return;\n }\n\n if (!invoice || !invoice.paymentRequest) {\n setError('Invoice is not ready for payment');\n return;\n }\n\n setIsProcessing(true);\n setError('');\n\n try {\n await window.webln.enable();\n \n const result = await window.webln.sendPayment(invoice.paymentRequest);\n \n if (result.preimage) {\n setPaymentStatus('paid');\n await activateSession(result.preimage);\n } else {\n setError('Payment does not contain preimage');\n }\n } catch (err) {\n console.error('WebLN payment failed:', err);\n setError(`WebLN Error: ${err.message}`);\n } finally {\n setIsProcessing(false);\n }\n };\n\n const handleManualVerification = async () => {\n const trimmedPreimage = preimage.trim();\n \n if (!trimmedPreimage) {\n setError('Enter payment preimage');\n return;\n }\n \n if (trimmedPreimage.length !== 64) {\n setError('The preimage must be exactly 64 characters long.');\n return;\n }\n \n if (!/^[0-9a-fA-F]{64}$/.test(trimmedPreimage)) {\n setError('The preimage must contain only hexadecimal characters (0-9, a-f, A-F).');\n return;\n }\n \n if (trimmedPreimage === '1'.repeat(64) || \n trimmedPreimage === 'a'.repeat(64) || \n trimmedPreimage === 'f'.repeat(64)) {\n setError('The entered preimage is too weak. Please verify the key..');\n return;\n }\n \n setError('');\n setIsProcessing(true);\n\n try {\n await activateSession(trimmedPreimage);\n } catch (err) {\n setError(`Activation error: ${err.message}`);\n } finally {\n setIsProcessing(false);\n }\n };\n\n const activateSession = async (preimageValue) => {\n try {\n \n let result;\n if (paymentManager) {\n const paymentHash = invoice?.paymentHash || 'dummy_hash';\n result = await paymentManager.safeActivateSession(sessionType, preimageValue, paymentHash);\n } else {\n console.warn('Payment manager not available, using fallback');\n // Fallback if paymentManager is unavailable\n result = { success: true, method: 'fallback' };\n }\n\n if (result.success) {\n setPaymentStatus('paid');\n onSuccess(preimageValue, invoice);\n } else {\n console.error('\u274C Session activation failed:', result);\n throw new Error(`Session activation failed: ${result.reason}`);\n }\n\n } catch (err) {\n console.error('\u274C Session activation failed:', err);\n throw err;\n }\n };\n\n const handleFreeSession = async () => {\n setIsProcessing(true);\n try {\n await activateSession('0'.repeat(64));\n } catch (err) {\n setError(`Free session activation error: ${err.message}`);\n } finally {\n setIsProcessing(false);\n }\n };\n\n const copyToClipboard = (text) => {\n navigator.clipboard.writeText(text).then(() => {\n });\n };\n\n const pricing = {\n free: { sats: 1, hours: 1/60 },\n basic: { sats: 500, hours: 1 },\n premium: { sats: 1000, hours: 4 },\n extended: { sats: 2000, hours: 24 }\n }[sessionType];\n\n return React.createElement('div', { className: 'space-y-4 max-w-md mx-auto' }, [\n React.createElement('div', { key: 'header', className: 'text-center' }, [\n React.createElement('h3', { \n key: 'title', \n className: 'text-xl font-semibold text-white mb-2' \n }, sessionType === 'free' ? 'Free session' : 'Lightning payment'),\n React.createElement('div', { \n key: 'amount', \n className: 'text-2xl font-bold text-orange-400' \n }, sessionType === 'free' \n ? '0 sat per minute' \n : `${pricing.sats} \u0441\u0430\u0442 \u0437\u0430 ${pricing.hours}\u0447`\n ),\n sessionType !== 'free' && React.createElement('div', { \n key: 'usd', \n className: 'text-sm text-gray-400 mt-1' \n }, `\u2248 $${(pricing.sats * 0.0004).toFixed(2)} USD`)\n ]),\n\n // Loading State\n isProcessing && paymentStatus === 'pending' && React.createElement('div', { \n key: 'loading', \n className: 'text-center' \n }, [\n React.createElement('div', { \n key: 'spinner', \n className: 'text-orange-400' \n }, [\n React.createElement('i', { className: 'fas fa-spinner fa-spin mr-2' }),\n 'Creating invoice...'\n ])\n ]),\n\n // Free Session\n sessionType === 'free' && React.createElement('div', { \n key: 'free-session', \n className: 'space-y-3' \n }, [\n React.createElement('div', { \n key: 'info', \n className: 'p-3 bg-blue-500/10 border border-blue-500/20 rounded text-blue-300 text-sm' \n }, 'A free 1-minute session will be activated.'),\n React.createElement('button', { \n key: 'start-btn',\n onClick: handleFreeSession,\n disabled: isProcessing,\n className: 'w-full bg-blue-600 hover:bg-blue-500 text-white py-3 px-4 rounded-lg font-medium disabled:opacity-50'\n }, [\n React.createElement('i', { \n key: 'icon',\n className: `fas ${isProcessing ? 'fa-spinner fa-spin' : 'fa-play'} mr-2` \n }),\n isProcessing ? 'Activation...' : 'Start free session'\n ])\n ]),\n\n // Paid Sessions\n sessionType !== 'free' && paymentStatus === 'created' && invoice && React.createElement('div', { \n key: 'paid-session', \n className: 'space-y-4' \n }, [\n // QR Code\n qrCodeUrl && React.createElement('div', { \n key: 'qr-section', \n className: 'text-center' \n }, [\n React.createElement('div', { \n key: 'qr-container', \n className: 'bg-white p-4 rounded-lg inline-block' \n }, [\n React.createElement('img', { \n key: 'qr-img',\n src: qrCodeUrl, \n alt: 'Payment QR Code', \n className: 'w-48 h-48' \n })\n ]),\n React.createElement('div', { \n key: 'qr-hint', \n className: 'text-xs text-gray-400 mt-2' \n }, 'Scan the QR code with any Lightning wallet')\n ]),\n\n // Payment Request\n invoice.paymentRequest && React.createElement('div', { \n key: 'payment-request', \n className: 'space-y-2' \n }, [\n React.createElement('div', { \n key: 'label', \n className: 'text-sm font-medium text-white' \n }, 'Payment Request:'),\n React.createElement('div', { \n key: 'request',\n className: 'p-3 bg-gray-800 rounded border text-xs font-mono text-gray-300 cursor-pointer hover:bg-gray-700',\n onClick: () => copyToClipboard(invoice.paymentRequest)\n }, [\n invoice.paymentRequest.substring(0, 50) + '...',\n React.createElement('i', { key: 'copy-icon', className: 'fas fa-copy ml-2 text-orange-400' })\n ])\n ]),\n\n // WebLN Payment\n React.createElement('div', { \n key: 'webln-section', \n className: 'space-y-3' \n }, [\n React.createElement('h4', { \n key: 'webln-title', \n className: 'text-white font-medium flex items-center' \n }, [\n React.createElement('i', { key: 'bolt-icon', className: 'fas fa-bolt text-orange-400 mr-2' }),\n 'WebLN wallet (Alby, Zeus)'\n ]),\n React.createElement('button', { \n key: 'webln-btn',\n onClick: handleWebLNPayment,\n disabled: isProcessing,\n className: 'w-full bg-orange-600 hover:bg-orange-500 text-white py-3 px-4 rounded-lg font-medium disabled:opacity-50'\n }, [\n React.createElement('i', { \n key: 'webln-icon',\n className: `fas ${isProcessing ? 'fa-spinner fa-spin' : 'fa-bolt'} mr-2` \n }),\n isProcessing ? 'Processing...' : 'Pay via WebLN'\n ])\n ]),\n\n // Manual Payment\n React.createElement('div', { \n key: 'divider', \n className: 'text-center text-gray-400' \n }, 'or'),\n \n React.createElement('div', { \n key: 'manual-section', \n className: 'space-y-3' \n }, [\n React.createElement('h4', { \n key: 'manual-title', \n className: 'text-white font-medium' \n }, 'Manual payment verification'),\n React.createElement('input', { \n key: 'preimage-input',\n type: 'text',\n value: preimage,\n onChange: (e) => setPreimage(e.target.value),\n placeholder: 'Enter the preimage after payment...',\n className: 'w-full p-3 bg-gray-800 border border-gray-600 rounded text-white placeholder-gray-400 text-sm'\n }),\n React.createElement('button', { \n key: 'verify-btn',\n onClick: handleManualVerification,\n disabled: isProcessing,\n className: 'w-full bg-green-600 hover:bg-green-500 text-white py-3 px-4 rounded-lg font-medium disabled:opacity-50'\n }, [\n React.createElement('i', { \n key: 'verify-icon',\n className: `fas ${isProcessing ? 'fa-spinner fa-spin' : 'fa-check'} mr-2` \n }),\n isProcessing ? 'Verification...' : 'Confirm payment'\n ])\n ])\n ]),\n\n // Success State\n paymentStatus === 'paid' && React.createElement('div', { \n key: 'success', \n className: 'text-center p-4 bg-green-500/10 border border-green-500/20 rounded' \n }, [\n React.createElement('i', { key: 'success-icon', className: 'fas fa-check-circle text-green-400 text-2xl mb-2' }),\n React.createElement('div', { key: 'success-text', className: 'text-green-300 font-medium' }, 'Payment confirmed!'),\n React.createElement('div', { key: 'success-subtext', className: 'text-green-400 text-sm' }, 'Session activated')\n ]),\n\n // Error State\n error && React.createElement('div', { \n key: 'error', \n className: 'p-3 bg-red-500/10 border border-red-500/20 rounded text-red-400 text-sm' \n }, [\n React.createElement('i', { key: 'error-icon', className: 'fas fa-exclamation-triangle mr-2' }),\n error,\n error.includes('invoice') && React.createElement('button', { \n key: 'retry-btn',\n onClick: createInvoice,\n className: 'ml-2 text-orange-400 hover:text-orange-300 underline'\n }, 'Try again')\n ]),\n\n // Cancel Button\n React.createElement('button', { \n key: 'cancel-btn',\n onClick: onCancel,\n className: 'w-full bg-gray-600 hover:bg-gray-500 text-white py-2 px-4 rounded'\n }, 'Cancel')\n ]);\n};\n\nwindow.LightningPayment = IntegratedLightningPayment;", "const React = window.React;\nconst { useState, useEffect, useRef } = React;\n\nconst PaymentModal = ({ isOpen, onClose, sessionManager, onSessionPurchased }) => {\n const [step, setStep] = React.useState('select');\n const [selectedType, setSelectedType] = React.useState(null);\n const [invoice, setInvoice] = React.useState(null);\n const [paymentStatus, setPaymentStatus] = React.useState('pending');\n const [error, setError] = React.useState('');\n const [paymentMethod, setPaymentMethod] = React.useState('webln'); \n const [preimageInput, setPreimageInput] = React.useState('');\n const [isProcessing, setIsProcessing] = React.useState(false);\n const [qrCodeUrl, setQrCodeUrl] = React.useState('');\n const [paymentTimer, setPaymentTimer] = React.useState(null);\n const [timeLeft, setTimeLeft] = React.useState(0);\n const [showSecurityDetails, setShowSecurityDetails] = React.useState(false);\n const pollInterval = React.useRef(null);\n\n React.useEffect(() => {\n if (!isOpen) {\n resetModal();\n if (pollInterval.current) {\n clearInterval(pollInterval.current);\n }\n if (paymentTimer) {\n clearInterval(paymentTimer);\n }\n }\n }, [isOpen]);\n\n const resetModal = () => {\n setStep('select');\n setSelectedType(null);\n setInvoice(null);\n setPaymentStatus('pending');\n setError('');\n setPaymentMethod('webln');\n setPreimageInput('');\n setIsProcessing(false);\n setQrCodeUrl('');\n setTimeLeft(0);\n setShowSecurityDetails(false);\n };\n\n const getSecurityFeaturesInfo = (sessionType) => {\n const features = {\n demo: {\n title: 'Demo Session - Basic Security',\n description: 'Limited testing session with basic security features',\n available: [\n '\uD83D\uDD10 Basic end-to-end encryption (AES-GCM 256)',\n '\uD83D\uDD11 Simple key exchange (ECDH P-384)',\n '\u2705 Message integrity verification',\n '\u26A1 Rate limiting protection'\n ],\n unavailable: [\n '\uD83D\uDD10 ECDSA Digital Signatures',\n '\uD83D\uDEE1\uFE0F Metadata Protection',\n '\uD83D\uDD04 Perfect Forward Secrecy',\n '\uD83D\uDD10 Nested Encryption',\n '\uD83D\uDCE6 Packet Padding',\n '\uD83C\uDFAD Traffic Obfuscation',\n '\uD83C\uDFAA Fake Traffic Generation',\n '\uD83D\uDD75\uFE0F Decoy Channels',\n '\uD83D\uDEAB Anti-Fingerprinting',\n '\uD83D\uDCDD Message Chunking',\n '\uD83D\uDD04 Advanced Replay Protection'\n ],\n upgrade: {\n next: 'Basic Session (5,000 sat - $2.00)',\n features: [\n '\uD83D\uDD10 ECDSA Digital Signatures',\n '\uD83D\uDEE1\uFE0F Metadata Protection',\n '\uD83D\uDD04 Perfect Forward Secrecy',\n '\uD83D\uDD10 Nested Encryption',\n '\uD83D\uDCE6 Packet Padding'\n ]\n }\n },\n basic: {\n title: 'Basic Session - Enhanced Security',\n description: 'Full featured session with enhanced security features',\n available: [\n '\uD83D\uDD10 Basic end-to-end encryption (AES-GCM 256)',\n '\uD83D\uDD11 Simple key exchange (ECDH P-384)',\n '\u2705 Message integrity verification',\n '\u26A1 Rate limiting protection',\n '\uD83D\uDD10 ECDSA Digital Signatures',\n '\uD83D\uDEE1\uFE0F Metadata Protection',\n '\uD83D\uDD04 Perfect Forward Secrecy',\n '\uD83D\uDD10 Nested Encryption',\n '\uD83D\uDCE6 Packet Padding',\n '\uD83D\uDD12 Complete ASN.1 validation',\n '\uD83D\uDD0D OID and EC point verification',\n '\uD83C\uDFD7\uFE0F SPKI structure validation',\n '\uD83D\uDEE1\uFE0F 18-layer security architecture'\n ],\n unavailable: [\n '\uD83C\uDFAD Traffic Obfuscation',\n '\uD83C\uDFAA Fake Traffic Generation',\n '\uD83D\uDD75\uFE0F Decoy Channels',\n '\uD83D\uDEAB Anti-Fingerprinting',\n '\uD83D\uDCDD Message Chunking',\n '\uD83D\uDD04 Advanced Replay Protection'\n ],\n upgrade: {\n next: 'Premium Session (20,000 sat - $8.00)',\n features: [\n '\uD83C\uDFAD Traffic Obfuscation',\n '\uD83C\uDFAA Fake Traffic Generation',\n '\uD83D\uDD75\uFE0F Decoy Channels',\n '\uD83D\uDEAB Anti-Fingerprinting',\n '\uD83D\uDCDD Message Chunking',\n '\uD83D\uDD04 Advanced Replay Protection'\n ]\n }\n },\n premium: {\n title: 'Premium Session - Maximum Security',\n description: 'Extended session with maximum security protection',\n available: [\n '\uD83D\uDD10 Basic end-to-end encryption (AES-GCM 256)',\n '\uD83D\uDD11 Simple key exchange (ECDH P-384)',\n '\u2705 Message integrity verification',\n '\u26A1 Rate limiting protection',\n '\uD83D\uDD10 ECDSA Digital Signatures',\n '\uD83D\uDEE1\uFE0F Metadata Protection',\n '\uD83D\uDD04 Perfect Forward Secrecy',\n '\uD83D\uDD10 Nested Encryption',\n '\uD83D\uDCE6 Packet Padding',\n '\uD83C\uDFAD Traffic Obfuscation',\n '\uD83C\uDFAA Fake Traffic Generation',\n '\uD83D\uDD75\uFE0F Decoy Channels',\n '\uD83D\uDEAB Anti-Fingerprinting',\n '\uD83D\uDCDD Message Chunking',\n '\uD83D\uDD04 Advanced Replay Protection',\n '\uD83D\uDD12 Complete ASN.1 validation',\n '\uD83D\uDD0D OID and EC point verification',\n '\uD83C\uDFD7\uFE0F SPKI structure validation',\n '\uD83D\uDEE1\uFE0F 18-layer security architecture',\n '\uD83D\uDE80 ASN.1 Validated'\n ],\n unavailable: [],\n upgrade: {\n next: 'Maximum security achieved!',\n features: ['\uD83C\uDF89 All security features unlocked!']\n }\n }\n };\n \n return features[sessionType] || features.demo;\n };\n\n const handleSelectType = async (type) => {\n setSelectedType(type);\n setError('');\n \n if (type === 'demo') {\n try {\n if (!sessionManager || !sessionManager.createDemoSession) {\n throw new Error('Demo session manager not available');\n }\n \n const demoSession = sessionManager.createDemoSession();\n if (!demoSession.success) {\n throw new Error(demoSession.reason);\n }\n \n setInvoice({ \n sessionType: 'demo',\n amount: 0,\n paymentHash: demoSession.paymentHash,\n memo: `Demo session (${demoSession.durationMinutes} minutes)`,\n createdAt: Date.now(),\n isDemo: true,\n preimage: demoSession.preimage,\n warning: demoSession.warning,\n securityLevel: 'Basic'\n });\n setPaymentStatus('demo');\n } catch (error) {\n setError(`Demo session creation failed: ${error.message}`);\n return;\n }\n } else {\n await createRealInvoice(type);\n }\n setStep('payment');\n };\n\n const createRealInvoice = async (type) => {\n setPaymentStatus('creating');\n setIsProcessing(true);\n setError('');\n\n try {\n console.log(`Creating Lightning invoice for ${type} session...`);\n \n if (!sessionManager) {\n throw new Error('Session manager not initialized');\n }\n\n const createdInvoice = await sessionManager.createLightningInvoice(type);\n \n if (!createdInvoice || !createdInvoice.paymentRequest) {\n throw new Error('Failed to create Lightning invoice');\n }\n\n createdInvoice.securityLevel = sessionManager.getSecurityLevelForSession(type);\n\n setInvoice(createdInvoice);\n setPaymentStatus('created');\n\n try {\n const dataUrl = await window.generateQRCode(createdInvoice.paymentRequest, { size: 300, margin: 2, errorCorrectionLevel: 'M' });\n setQrCodeUrl(dataUrl);\n } catch (e) {\n console.warn('QR local generation failed, showing placeholder');\n const dataUrl = await window.generateQRCode(createdInvoice.paymentRequest, { size: 300 });\n setQrCodeUrl(dataUrl);\n }\n\n const expirationTime = 15 * 60 * 1000;\n setTimeLeft(expirationTime);\n \n const timer = setInterval(() => {\n setTimeLeft(prev => {\n const newTime = prev - 1000;\n if (newTime <= 0) {\n clearInterval(timer);\n setPaymentStatus('expired');\n setError('Payment time has expired. Create a new invoice.');\n return 0;\n }\n return newTime;\n });\n }, 1000);\n setPaymentTimer(timer);\n\n startPaymentPolling(createdInvoice.checkingId);\n\n console.log('\u2705 Lightning invoice created successfully:', createdInvoice);\n\n } catch (err) {\n console.error('\u274C Invoice creation failed:', err);\n setError(`Invoice creation error: ${err.message}`);\n setPaymentStatus('failed');\n } finally {\n setIsProcessing(false);\n }\n };\n\n const startPaymentPolling = (checkingId) => {\n if (pollInterval.current) {\n clearInterval(pollInterval.current);\n }\n\n pollInterval.current = setInterval(async () => {\n try {\n const status = await sessionManager.checkPaymentStatus(checkingId);\n \n if (status.paid && status.preimage) {\n clearInterval(pollInterval.current);\n setPaymentStatus('paid');\n await handlePaymentSuccess(status.preimage);\n }\n } catch (error) {\n console.warn('Payment status check failed:', error);\n }\n }, 3000); \n };\n\n const handleWebLNPayment = async () => {\n if (!window.webln) {\n setError('WebLN is not supported. Please install the Alby or Zeus wallet.');\n return;\n }\n\n if (!invoice || !invoice.paymentRequest) {\n setError('Invoice is not ready for payment.');\n return;\n }\n\n setIsProcessing(true);\n setError('');\n setPaymentStatus('paying');\n\n try {\n await window.webln.enable();\n \n const result = await window.webln.sendPayment(invoice.paymentRequest);\n \n if (result.preimage) {\n setPaymentStatus('paid');\n await handlePaymentSuccess(result.preimage);\n } else {\n throw new Error('Payment does not contain preimage');\n }\n } catch (err) {\n console.error('\u274C WebLN payment failed:', err);\n setError(`WebLN payment error: ${err.message}`);\n setPaymentStatus('created'); \n } finally {\n setIsProcessing(false);\n }\n };\n\n const handleManualVerification = async () => {\n const trimmedPreimage = preimageInput.trim();\n \n if (!trimmedPreimage) {\n setError('Enter payment preimage');\n return;\n }\n \n if (trimmedPreimage.length !== 64) {\n setError('The preimage must be exactly 64 characters long.');\n return;\n }\n \n if (!/^[0-9a-fA-F]{64}$/.test(trimmedPreimage)) {\n setError('The preimage must contain only hexadecimal characters (0-9, a-f, A-F).');\n return;\n }\n \n const dummyPreimages = ['1'.repeat(64), 'a'.repeat(64), 'f'.repeat(64), '0'.repeat(64)];\n if (dummyPreimages.includes(trimmedPreimage) && selectedType !== 'demo') {\n setError('The entered preimage is invalid. Please use the actual preimage from the payment.');\n return;\n }\n \n setIsProcessing(true);\n setError('');\n setPaymentStatus('paying');\n\n try {\n await handlePaymentSuccess(trimmedPreimage);\n } catch (err) {\n setError(err.message);\n setPaymentStatus('created');\n } finally {\n setIsProcessing(false);\n }\n };\n\n const handleDemoSession = async () => {\n setIsProcessing(true);\n setError('');\n \n try {\n if (!invoice?.preimage) {\n throw new Error('Demo preimage not available');\n }\n \n const isValid = await sessionManager.verifyPayment(invoice.preimage, invoice.paymentHash);\n \n if (isValid && isValid.verified) {\n onSessionPurchased({ \n type: 'demo', \n preimage: invoice.preimage,\n paymentHash: invoice.paymentHash,\n amount: 0,\n isDemo: true,\n warning: invoice.warning,\n securityLevel: 'basic'\n });\n \n setTimeout(() => {\n onClose();\n }, 1500);\n } else {\n throw new Error(isValid?.reason || 'Demo session verification failed');\n }\n } catch (err) {\n setError(`Demo session activation error: ${err.message}`);\n } finally {\n setIsProcessing(false);\n }\n };\n\n const handlePaymentSuccess = async (preimage) => {\n try {\n console.log('\uD83D\uDD0D Verifying payment...', { selectedType, preimage });\n \n let isValid;\n if (selectedType === 'demo') {\n return;\n } else {\n isValid = await sessionManager.verifyPayment(preimage, invoice.paymentHash);\n }\n \n if (isValid) {\n if (pollInterval.current) {\n clearInterval(pollInterval.current);\n }\n if (paymentTimer) {\n clearInterval(paymentTimer);\n }\n\n onSessionPurchased({ \n type: selectedType, \n preimage,\n paymentHash: invoice.paymentHash,\n amount: invoice.amount,\n securityLevel: invoice.securityLevel || (selectedType === 'basic' ? 'enhanced' : 'maximum')\n });\n \n setTimeout(() => {\n onClose();\n }, 1500);\n \n } else {\n throw new Error('Payment verification failed. Please check the preimage for correctness or try again.');\n }\n } catch (error) {\n console.error('\u274C Payment verification failed:', error);\n throw error;\n }\n };\n\n const copyToClipboard = async (text) => {\n try {\n await navigator.clipboard.writeText(text);\n } catch (err) {\n console.error('Failed to copy:', err);\n }\n };\n\n const formatTime = (ms) => {\n const minutes = Math.floor(ms / 60000);\n const seconds = Math.floor((ms % 60000) / 1000);\n return `${minutes}:${seconds.toString().padStart(2, '0')}`;\n };\n\n const getSecurityBadgeColor = (level) => {\n switch (level?.toLowerCase()) {\n case 'basic': return 'bg-blue-500/20 text-blue-300 border-blue-500/30';\n case 'enhanced': return 'bg-orange-500/20 text-orange-300 border-orange-500/30';\n case 'maximum': return 'bg-green-500/20 text-green-300 border-green-500/30';\n default: return 'bg-gray-500/20 text-gray-300 border-gray-500/30';\n }\n };\n\n const pricing = sessionManager?.sessionPrices || {\n demo: { sats: 0, hours: 0.1, usd: 0.00 },\n basic: { sats: 5000, hours: 1, usd: 2.00 },\n premium: { sats: 20000, hours: 6, usd: 8.00 }\n };\n\n if (!isOpen) return null;\n\n return React.createElement('div', { \n className: 'fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4' \n }, [\n React.createElement('div', { \n key: 'modal', \n className: 'card-minimal rounded-xl p-6 max-w-lg w-full max-h-[90vh] overflow-y-auto custom-scrollbar' \n }, [\n React.createElement('div', { \n key: 'header', \n className: 'flex items-center justify-between mb-6' \n }, [\n React.createElement('h2', { \n key: 'title', \n className: 'text-xl font-semibold text-primary' \n }, step === 'select' ? 'Select session type' : \n step === 'details' ? 'Security Features Details' : 'Session payment'),\n React.createElement('button', { \n key: 'close',\n onClick: onClose, \n className: 'text-gray-400 hover:text-white transition-colors' \n }, React.createElement('i', { className: 'fas fa-times' }))\n ]),\n\n step === 'select' && window.SessionTypeSelector && React.createElement(window.SessionTypeSelector, { \n key: 'selector', \n onSelectType: handleSelectType, \n onCancel: onClose,\n sessionManager: sessionManager\n }),\n\n step === 'payment' && React.createElement('div', { \n key: 'payment-step', \n className: 'space-y-6' \n }, [\n React.createElement('div', { \n key: 'session-info', \n className: 'text-center p-4 bg-orange-500/10 border border-orange-500/20 rounded-lg' \n }, [\n React.createElement('h3', { \n key: 'session-title', \n className: 'text-lg font-semibold text-orange-400 mb-2' \n }, [\n `${selectedType.charAt(0).toUpperCase() + selectedType.slice(1)} session`,\n invoice?.securityLevel && React.createElement('span', {\n key: 'security-badge',\n className: `text-xs px-2 py-1 rounded-full border ${getSecurityBadgeColor(invoice.securityLevel)}`\n }, invoice.securityLevel.toUpperCase())\n ]),\n React.createElement('div', { \n key: 'session-details', \n className: 'text-sm text-secondary' \n }, [\n React.createElement('div', { key: 'amount' }, `${pricing[selectedType].sats} sat for ${pricing[selectedType].hours}h`),\n pricing[selectedType].usd > 0 && React.createElement('div', { \n key: 'usd', \n className: 'text-gray-400' \n }, `\u2248 ${pricing[selectedType].usd} USD`),\n React.createElement('button', {\n key: 'details-btn',\n onClick: () => setStep('details'),\n className: 'mt-2 text-xs text-blue-400 hover:text-blue-300 underline cursor-pointer'\n }, '\uD83D\uDCCB View Security Details')\n ])\n ]),\n\n timeLeft > 0 && paymentStatus === 'created' && React.createElement('div', { \n key: 'timer', \n className: 'text-center p-3 bg-yellow-500/10 border border-yellow-500/20 rounded' \n }, [\n React.createElement('div', { \n key: 'timer-text', \n className: 'text-yellow-400 font-medium' \n }, `\u23F1\uFE0F Time to pay: ${formatTime(timeLeft)}`)\n ]),\n\n paymentStatus === 'demo' && React.createElement('div', { \n key: 'demo-payment', \n className: 'space-y-4' \n }, [\n React.createElement('div', { \n key: 'demo-info', \n className: 'p-4 bg-green-500/10 border border-green-500/20 rounded text-green-300 text-sm text-center' \n }, [\n React.createElement('div', { key: 'demo-title', className: 'font-medium mb-1' }, '\uD83C\uDFAE Demo Session Available'),\n React.createElement('div', { key: 'demo-details', className: 'text-xs' }, \n `Limited to ${invoice?.durationMinutes || 6} minutes for testing`)\n ]),\n invoice?.warning && React.createElement('div', {\n key: 'demo-warning',\n className: 'p-3 bg-yellow-500/10 border border-yellow-500/20 rounded text-yellow-300 text-xs text-center'\n }, invoice.warning),\n React.createElement('div', {\n key: 'demo-preimage',\n className: 'p-3 bg-gray-800/50 rounded border border-gray-600 text-xs font-mono text-gray-300'\n }, [\n React.createElement('div', { key: 'preimage-label', className: 'text-gray-400 mb-1' }, 'Demo Preimage:'),\n React.createElement('div', { key: 'preimage-value', className: 'break-all' }, \n invoice?.preimage || 'Generating...')\n ]),\n React.createElement('button', { \n key: 'demo-btn',\n onClick: handleDemoSession,\n disabled: isProcessing,\n className: 'w-full bg-green-600 hover:bg-green-500 text-white py-3 px-4 rounded-lg font-medium disabled:opacity-50 disabled:cursor-not-allowed'\n }, [\n React.createElement('i', { \n key: 'demo-icon',\n className: `fas ${isProcessing ? 'fa-spinner fa-spin' : 'fa-play'} mr-2` \n }),\n isProcessing ? 'Activating...' : 'Activate Demo Session'\n ])\n ]),\n\n paymentStatus === 'creating' && React.createElement('div', { \n key: 'creating', \n className: 'text-center p-4' \n }, [\n React.createElement('i', { className: 'fas fa-spinner fa-spin text-orange-400 text-2xl mb-2' }),\n React.createElement('div', { className: 'text-primary' }, 'Creating Lightning invoice...'),\n React.createElement('div', { className: 'text-secondary text-sm mt-1' }, 'Connecting to the Lightning Network...')\n ]),\n\n (paymentStatus === 'created' || paymentStatus === 'paying') && invoice && React.createElement('div', { \n key: 'payment-methods', \n className: 'space-y-6' \n }, [\n qrCodeUrl && React.createElement('div', { \n key: 'qr-section', \n className: 'text-center' \n }, [\n React.createElement('div', { \n key: 'qr-container', \n className: 'bg-white p-4 rounded-lg inline-block' \n }, [\n React.createElement('img', { \n key: 'qr-img',\n src: qrCodeUrl, \n alt: 'Lightning Payment QR Code', \n className: 'w-48 h-48' \n })\n ]),\n React.createElement('div', { \n key: 'qr-hint', \n className: 'text-xs text-gray-400 mt-2' \n }, 'Scan with any Lightning wallet')\n ]),\n\n invoice.paymentRequest && React.createElement('div', { \n key: 'payment-request', \n className: 'space-y-2' \n }, [\n React.createElement('div', { \n key: 'pr-label', \n className: 'text-sm font-medium text-primary' \n }, 'Lightning Payment Request:'),\n React.createElement('div', { \n key: 'pr-container',\n className: 'p-3 bg-gray-800/50 rounded border border-gray-600 text-xs font-mono text-gray-300 cursor-pointer hover:bg-gray-700/50 transition-colors',\n onClick: () => copyToClipboard(invoice.paymentRequest),\n title: 'Click to copy'\n }, [\n invoice.paymentRequest.substring(0, 60) + '...',\n React.createElement('i', { key: 'copy-icon', className: 'fas fa-copy ml-2 text-orange-400' })\n ])\n ]),\n\n // WebLN Payment\n React.createElement('div', { \n key: 'webln-section', \n className: 'space-y-3' \n }, [\n React.createElement('h4', { \n key: 'webln-title', \n className: 'text-primary font-medium flex items-center' \n }, [\n React.createElement('i', { key: 'bolt-icon', className: 'fas fa-bolt text-orange-400 mr-2' }),\n 'WebLN wallet (recommended)'\n ]),\n React.createElement('div', { \n key: 'webln-info', \n className: 'text-xs text-gray-400 mb-2' \n }, 'Alby, Zeus, or other WebLN-compatible wallets'),\n React.createElement('button', { \n key: 'webln-btn',\n onClick: handleWebLNPayment,\n disabled: isProcessing || paymentStatus === 'paying',\n className: 'w-full bg-orange-600 hover:bg-orange-500 text-white py-3 px-4 rounded-lg font-medium disabled:opacity-50 disabled:cursor-not-allowed transition-colors'\n }, [\n React.createElement('i', { \n key: 'webln-icon',\n className: `fas ${isProcessing ? 'fa-spinner fa-spin' : 'fa-bolt'} mr-2` \n }),\n paymentStatus === 'paying' ? 'Processing payment...' : 'Pay via WebLN'\n ])\n ]),\n\n // Divider\n React.createElement('div', { \n key: 'divider', \n className: 'text-center text-gray-400 text-sm' \n }, '\u2014 or \u2014'),\n \n // Manual Verification\n React.createElement('div', { \n key: 'manual-section', \n className: 'space-y-3' \n }, [\n React.createElement('h4', { \n key: 'manual-title', \n className: 'text-primary font-medium' \n }, 'Manual payment confirmation'),\n React.createElement('div', { \n key: 'manual-info', \n className: 'text-xs text-gray-400' \n }, 'Pay the invoice in any wallet and enter the preimage.:'),\n React.createElement('input', { \n key: 'preimage-input',\n type: 'text',\n value: preimageInput,\n onChange: (e) => setPreimageInput(e.target.value),\n placeholder: 'Enter the preimage (64 hex characters)...',\n className: 'w-full p-3 bg-gray-800 border border-gray-600 rounded text-white placeholder-gray-400 text-sm font-mono',\n maxLength: 64\n }),\n React.createElement('button', { \n key: 'verify-btn',\n onClick: handleManualVerification,\n disabled: isProcessing || !preimageInput.trim(),\n className: 'w-full bg-green-600 hover:bg-green-500 text-white py-3 px-4 rounded-lg font-medium disabled:opacity-50 disabled:cursor-not-allowed transition-colors'\n }, [\n React.createElement('i', { \n key: 'verify-icon',\n className: `fas ${isProcessing ? 'fa-spinner fa-spin' : 'fa-check'} mr-2` \n }),\n isProcessing ? 'Checking payment...' : 'Confirm payment'\n ])\n ])\n ]),\n\n // Success State\n paymentStatus === 'paid' && React.createElement('div', { \n key: 'success', \n className: 'text-center p-6 bg-green-500/10 border border-green-500/20 rounded-lg' \n }, [\n React.createElement('i', { key: 'success-icon', className: 'fas fa-check-circle text-green-400 text-3xl mb-3' }),\n React.createElement('div', { key: 'success-title', className: 'text-green-300 font-semibold text-lg mb-1' }, '\u2705 Payment confirmed!'),\n React.createElement('div', { key: 'success-text', className: 'text-green-400 text-sm' }, 'The session will be activated upon connecting to the chat.')\n ]),\n\n // Error State\n error && React.createElement('div', { \n key: 'error', \n className: 'p-4 bg-red-500/10 border border-red-500/20 rounded-lg' \n }, [\n React.createElement('div', { \n key: 'error-content', \n className: 'flex items-start space-x-3' \n }, [\n React.createElement('i', { key: 'error-icon', className: 'fas fa-exclamation-triangle text-red-400 mt-0.5' }),\n React.createElement('div', { key: 'error-text', className: 'flex-1' }, [\n React.createElement('div', { key: 'error-message', className: 'text-red-400 text-sm' }, error),\n (error.includes('invoice') || paymentStatus === 'failed') && React.createElement('button', { \n key: 'retry-btn',\n onClick: () => createRealInvoice(selectedType),\n className: 'mt-2 text-orange-400 hover:text-orange-300 underline text-sm'\n }, 'Create a new invoice')\n ])\n ])\n ]),\n\n paymentStatus !== 'paid' && React.createElement('div', { \n key: 'back-section', \n className: 'pt-4 border-t border-gray-600' \n }, [\n React.createElement('button', { \n key: 'back-btn',\n onClick: () => setStep('select'),\n className: 'w-full bg-gray-600 hover:bg-gray-500 text-white py-2 px-4 rounded transition-colors'\n }, [\n React.createElement('i', { key: 'back-icon', className: 'fas fa-arrow-left mr-2' }),\n 'Choose another session'\n ])\n ])\n ]),\n\n // Security Details Step\n step === 'details' && React.createElement('div', { \n key: 'details-step', \n className: 'space-y-6' \n }, [\n React.createElement('div', { \n key: 'details-header', \n className: 'text-center p-4 bg-blue-500/10 border border-blue-500/20 rounded-lg' \n }, [\n React.createElement('h3', { \n key: 'details-title', \n className: 'text-lg font-semibold text-blue-400 mb-2' \n }, getSecurityFeaturesInfo(selectedType).title),\n React.createElement('p', { \n key: 'details-description', \n className: 'text-sm text-blue-300' \n }, getSecurityFeaturesInfo(selectedType).description)\n ]),\n\n // Available Features\n React.createElement('div', { key: 'available-features' }, [\n React.createElement('h4', {\n key: 'available-title',\n className: 'text-sm font-medium text-green-300 mb-3 flex items-center'\n }, [\n React.createElement('i', {\n key: 'check-icon',\n className: 'fas fa-check-circle mr-2'\n }),\n 'Available Security Features'\n ]),\n React.createElement('div', {\n key: 'available-list',\n className: 'grid grid-cols-1 gap-2'\n }, getSecurityFeaturesInfo(selectedType).available.map((feature, index) => \n React.createElement('div', {\n key: index,\n className: 'flex items-center gap-2 text-sm text-green-300'\n }, [\n React.createElement('i', {\n key: 'check',\n className: 'fas fa-check text-green-400 w-4'\n }),\n React.createElement('span', {\n key: 'text'\n }, feature)\n ])\n ))\n ]),\n\n // Unavailable Features (if any)\n getSecurityFeaturesInfo(selectedType).unavailable.length > 0 && React.createElement('div', { key: 'unavailable-features' }, [\n React.createElement('h4', {\n key: 'unavailable-title',\n className: 'text-sm font-medium text-red-300 mb-3 flex items-center'\n }, [\n React.createElement('i', {\n key: 'minus-icon',\n className: 'fas fa-minus-circle mr-2'\n }),\n 'Not Available in This Session'\n ]),\n React.createElement('div', {\n key: 'unavailable-list',\n className: 'grid grid-cols-1 gap-2'\n }, getSecurityFeaturesInfo(selectedType).unavailable.map((feature, index) => \n React.createElement('div', {\n key: index,\n className: 'flex items-center gap-2 text-sm text-red-300'\n }, [\n React.createElement('i', {\n key: 'minus',\n className: 'fas fa-minus text-red-400 w-4'\n }),\n React.createElement('span', {\n key: 'text'\n }, feature)\n ])\n ))\n ]),\n\n // Upgrade Information\n React.createElement('div', { key: 'upgrade-info' }, [\n React.createElement('h4', {\n key: 'upgrade-title',\n className: 'text-sm font-medium text-blue-300 mb-3 flex items-center'\n }, [\n React.createElement('i', {\n key: 'upgrade-icon',\n className: 'fas fa-arrow-up mr-2'\n }),\n 'Upgrade for More Security'\n ]),\n React.createElement('div', {\n key: 'upgrade-content',\n className: 'p-3 bg-blue-500/10 border border-blue-500/20 rounded-lg'\n }, [\n React.createElement('div', {\n key: 'upgrade-next',\n className: 'text-sm font-medium text-blue-300 mb-2'\n }, getSecurityFeaturesInfo(selectedType).upgrade.next),\n React.createElement('div', {\n key: 'upgrade-features',\n className: 'grid grid-cols-1 gap-1'\n }, getSecurityFeaturesInfo(selectedType).upgrade.features.map((feature, index) => \n React.createElement('div', {\n key: index,\n className: 'flex items-center gap-2 text-xs text-blue-300'\n }, [\n React.createElement('i', {\n key: 'arrow',\n className: 'fas fa-arrow-right text-blue-400 w-3'\n }),\n React.createElement('span', {\n key: 'text'\n }, feature)\n ])\n ))\n ])\n ]),\n\n // Back Button\n React.createElement('div', { \n key: 'details-back-section', \n className: 'pt-4 border-t border-gray-600' \n }, [\n React.createElement('button', { \n key: 'details-back-btn',\n onClick: () => setStep('payment'),\n className: 'w-full bg-gray-600 hover:bg-gray-500 text-white py-2 px-4 rounded transition-colors'\n }, [\n React.createElement('i', { key: 'back-icon', className: 'fas fa-arrow-left mr-2' }),\n 'Back to Payment'\n ])\n ])\n ])\n ])\n ]);\n};\n\nwindow.PaymentModal = PaymentModal;", "const DownloadApps = () => {\r\n const apps = [\r\n { id: 'web', name: 'Web App', subtitle: 'Browser Version', icon: 'fas fa-globe', platform: 'Web', isActive: true, url: 'https://securebitchat.github.io/securebit-chat/', color: 'green' },\r\n { id: 'windows', name: 'Windows', subtitle: 'Desktop App', icon: 'fab fa-windows', platform: 'Desktop', isActive: false, url: '#', color: 'blue' },\r\n { id: 'macos', name: 'macOS', subtitle: 'Desktop App', icon: 'fab fa-apple', platform: 'Desktop', isActive: false, url: '#', color: 'gray' },\r\n { id: 'linux', name: 'Linux', subtitle: 'Desktop App', icon: 'fab fa-linux', platform: 'Desktop', isActive: false, url: '#', color: 'orange' },\r\n { id: 'ios', name: 'iOS', subtitle: 'iPhone & iPad', icon: 'fab fa-apple', platform: 'Mobile', isActive: false, url: 'https://apps.apple.com/app/securebit-chat/', color: 'blue' },\r\n { id: 'android', name: 'Android', subtitle: 'Google Play', icon: 'fab fa-android', platform: 'Mobile', isActive: false, url: 'https://play.google.com/store/apps/details?id=com.securebit.chat', color: 'green' }\r\n ];\r\n\r\n const handleDownload = (app) => {\r\n if (app.isActive) window.open(app.url, '_blank');\r\n };\r\n\r\n const desktopApps = apps.filter(a => a.platform !== 'Mobile');\r\n const mobileApps = apps.filter(a => a.platform === 'Mobile');\r\n\r\n const cardSize = \"w-28 h-28\"; \r\n\r\n return React.createElement('div', { className: \"mt-20 px-6\" }, [\r\n // Header\r\n React.createElement('div', { key: 'header', className: \"text-center max-w-3xl mx-auto mb-12\" }, [\r\n React.createElement('h3', { key: 'title', className: \"text-3xl font-bold text-primary mb-3\" }, 'Download SecureBit.chat'),\r\n React.createElement('p', { key: 'subtitle', className: \"text-secondary text-lg mb-5\" }, 'Stay secure on every device. Choose your platform and start chatting privately.')\r\n ]),\r\n\r\n React.createElement('div', { key: 'desktop-row', className: \"hidden sm:flex justify-center flex-wrap gap-6 mb-6\" },\r\n desktopApps.map(app =>\r\n React.createElement('div', {\r\n key: app.id,\r\n className: `group relative ${cardSize} rounded-2xl overflow-hidden card-minimal cursor-pointer`\r\n }, [\r\n React.createElement('i', {\r\n key: 'bg-icon',\r\n className: `${app.icon} absolute text-[3rem] text-white/10 top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 pointer-events-none transition-all duration-500 group-hover:scale-105`\r\n }),\r\n React.createElement('div', {\r\n key: 'overlay',\r\n className: \"absolute inset-0 bg-black/30 backdrop-blur-md flex flex-col items-center justify-center text-center opacity-0 transition-opacity duration-300 group-hover:opacity-100\"\r\n }, [\r\n React.createElement('h4', { key: 'name', className: `text-sm font-semibold text-primary mb-1` }, app.name),\r\n React.createElement('p', { key: 'subtitle', className: `text-xs text-secondary mb-2` }, app.subtitle),\r\n app.isActive ?\r\n React.createElement('button', {\r\n key: 'btn',\r\n onClick: () => handleDownload(app),\r\n className: `px-2 py-1 rounded-xl bg-emerald-500 text-black font-medium hover:bg-emerald-600 transition-colors text-xs`\r\n }, app.id === \"web\" ? \"Launch\" : \"Download\")\r\n :\r\n React.createElement('span', { key: 'coming', className: \"text-gray-400 font-medium text-xs\" }, \"Coming Soon\")\r\n ])\r\n ])\r\n )\r\n ),\r\n\r\n React.createElement('div', { key: 'mobile-row', className: \"flex justify-center gap-6\" },\r\n mobileApps.map(app =>\r\n React.createElement('div', {\r\n key: app.id,\r\n className: `group relative ${cardSize} rounded-2xl overflow-hidden card-minimal cursor-pointer`\r\n }, [\r\n React.createElement('i', {\r\n key: 'bg-icon',\r\n className: `${app.icon} absolute text-[3rem] text-white/10 top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 pointer-events-none transition-all duration-500 group-hover:scale-105`\r\n }),\r\n React.createElement('div', {\r\n key: 'overlay',\r\n className: \"absolute inset-0 bg-black/30 backdrop-blur-md flex flex-col items-center justify-center text-center opacity-0 transition-opacity duration-300 group-hover:opacity-100\"\r\n }, [\r\n React.createElement('h4', { key: 'name', className: `text-sm font-semibold text-primary mb-1` }, app.name),\r\n React.createElement('p', { key: 'subtitle', className: `text-xs text-secondary mb-2` }, app.subtitle),\r\n app.isActive ?\r\n React.createElement('button', {\r\n key: 'btn',\r\n onClick: () => handleDownload(app),\r\n className: `px-2 py-1 rounded-xl bg-emerald-500 text-black font-medium hover:bg-emerald-600 transition-colors text-xs`\r\n }, \"Download\")\r\n :\r\n React.createElement('span', { key: 'coming', className: \"text-gray-400 font-medium text-xs\" }, \"Coming Soon\")\r\n ])\r\n ])\r\n )\r\n )\r\n ]);\r\n};\r\n\r\nwindow.DownloadApps = DownloadApps;\r\n", "// File Transfer Component for Chat Interface - Fixed Version\r\nconst FileTransferComponent = ({ webrtcManager, isConnected }) => {\r\n const [dragOver, setDragOver] = React.useState(false);\r\n const [transfers, setTransfers] = React.useState({ sending: [], receiving: [] });\r\n const [readyFiles, setReadyFiles] = React.useState([]); // \u0444\u0430\u0439\u043B\u044B, \u0433\u043E\u0442\u043E\u0432\u044B\u0435 \u043A \u0441\u043A\u0430\u0447\u0438\u0432\u0430\u043D\u0438\u044E\r\n const fileInputRef = React.useRef(null);\r\n\r\n // Update transfers periodically\r\n React.useEffect(() => {\r\n if (!isConnected || !webrtcManager) return;\r\n\r\n const updateTransfers = () => {\r\n const currentTransfers = webrtcManager.getFileTransfers();\r\n setTransfers(currentTransfers);\r\n };\r\n\r\n const interval = setInterval(updateTransfers, 500);\r\n return () => clearInterval(interval);\r\n }, [isConnected, webrtcManager]);\r\n\r\n // Setup file transfer callbacks - \u0418\u0421\u041F\u0420\u0410\u0412\u041B\u0415\u041D\u0418\u0415: \u041D\u0415 \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C \u043F\u0440\u043E\u043C\u0435\u0436\u0443\u0442\u043E\u0447\u043D\u044B\u0435 \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u0432 \u0447\u0430\u0442\r\n React.useEffect(() => {\r\n if (!webrtcManager) return;\r\n\r\n webrtcManager.setFileTransferCallbacks(\r\n // Progress callback - \u0422\u041E\u041B\u042C\u041A\u041E \u043E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C UI, \u041D\u0415 \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C \u0432 \u0447\u0430\u0442\r\n (progress) => {\r\n // \u041E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C \u0442\u043E\u043B\u044C\u043A\u043E \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u043E\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435\r\n const currentTransfers = webrtcManager.getFileTransfers();\r\n setTransfers(currentTransfers);\r\n \r\n // \u041D\u0415 \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u0432 \u0447\u0430\u0442!\r\n },\r\n \r\n // File received callback - \u0434\u043E\u0431\u0430\u0432\u043B\u044F\u0435\u043C \u043A\u043D\u043E\u043F\u043A\u0443 \u0441\u043A\u0430\u0447\u0438\u0432\u0430\u043D\u0438\u044F \u0432 UI\r\n (fileData) => {\r\n // \u0414\u043E\u0431\u0430\u0432\u043B\u044F\u0435\u043C \u0432 \u0441\u043F\u0438\u0441\u043E\u043A \u0433\u043E\u0442\u043E\u0432\u044B\u0445 \u043A \u0441\u043A\u0430\u0447\u0438\u0432\u0430\u043D\u0438\u044E\r\n setReadyFiles(prev => {\r\n // \u0438\u0437\u0431\u0435\u0433\u0430\u0435\u043C \u0434\u0443\u0431\u043B\u0435\u0439 \u043F\u043E fileId\r\n if (prev.some(f => f.fileId === fileData.fileId)) return prev;\r\n return [...prev, {\r\n fileId: fileData.fileId,\r\n fileName: fileData.fileName,\r\n fileSize: fileData.fileSize,\r\n mimeType: fileData.mimeType,\r\n getBlob: fileData.getBlob,\r\n getObjectURL: fileData.getObjectURL,\r\n revokeObjectURL: fileData.revokeObjectURL\r\n }];\r\n });\r\n\r\n // \u041E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C \u0441\u043F\u0438\u0441\u043E\u043A \u0430\u043A\u0442\u0438\u0432\u043D\u044B\u0445 \u043F\u0435\u0440\u0435\u0434\u0430\u0447\r\n const currentTransfers = webrtcManager.getFileTransfers();\r\n setTransfers(currentTransfers);\r\n },\r\n \r\n // Error callback\r\n (error) => {\r\n const currentTransfers = webrtcManager.getFileTransfers();\r\n setTransfers(currentTransfers);\r\n \r\n // \u0418\u0421\u041F\u0420\u0410\u0412\u041B\u0415\u041D\u0418\u0415: \u041D\u0415 \u0434\u0443\u0431\u043B\u0438\u0440\u0443\u0435\u043C \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u043E\u0431 \u043E\u0448\u0438\u0431\u043A\u0430\u0445\r\n // \u0423\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u043E\u0431 \u043E\u0448\u0438\u0431\u043A\u0430\u0445 \u0443\u0436\u0435 \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u044F\u044E\u0442\u0441\u044F \u0432 WebRTC \u043C\u0435\u043D\u0435\u0434\u0436\u0435\u0440\u0435\r\n }\r\n );\r\n }, [webrtcManager]);\r\n\r\n const handleFileSelect = async (files) => {\r\n if (!isConnected || !webrtcManager) {\r\n alert('\u0421\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 \u043D\u0435 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u043E. \u0421\u043D\u0430\u0447\u0430\u043B\u0430 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0435 \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435.');\r\n return;\r\n }\r\n\r\n // \u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u0430\u044F \u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0430 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u044F \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\r\n if (!webrtcManager.isConnected() || !webrtcManager.isVerified) {\r\n alert('\u0421\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 \u043D\u0435 \u0433\u043E\u0442\u043E\u0432\u043E \u0434\u043B\u044F \u043F\u0435\u0440\u0435\u0434\u0430\u0447\u0438 \u0444\u0430\u0439\u043B\u043E\u0432. \u0414\u043E\u0436\u0434\u0438\u0442\u0435\u0441\u044C \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438 \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F.');\r\n return;\r\n }\r\n\r\n for (const file of files) {\r\n try {\r\n // \u041A\u0420\u0418\u0422\u0418\u0427\u0415\u0421\u041A\u041E\u0415 \u0418\u0421\u041F\u0420\u0410\u0412\u041B\u0415\u041D\u0418\u0415: \u0412\u0430\u043B\u0438\u0434\u0430\u0446\u0438\u044F \u0444\u0430\u0439\u043B\u0430 \u043F\u0435\u0440\u0435\u0434 \u043E\u0442\u043F\u0440\u0430\u0432\u043A\u043E\u0439\r\n const validation = webrtcManager.validateFile(file);\r\n if (!validation.isValid) {\r\n const errorMessage = validation.errors.join('. ');\r\n alert(`\u0424\u0430\u0439\u043B ${file.name} \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u0435\u043D: ${errorMessage}`);\r\n continue;\r\n }\r\n\r\n await webrtcManager.sendFile(file);\r\n } catch (error) {\r\n // \u0411\u043E\u043B\u0435\u0435 \u043C\u044F\u0433\u043A\u0430\u044F \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430 \u043E\u0448\u0438\u0431\u043E\u043A - \u043D\u0435 \u0437\u0430\u043A\u0440\u044B\u0432\u0430\u0435\u043C \u0441\u0435\u0441\u0441\u0438\u044E\r\n \r\n // \u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u043C \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044E \u043E\u0448\u0438\u0431\u043A\u0443, \u043D\u043E \u043D\u0435 \u0437\u0430\u043A\u0440\u044B\u0432\u0430\u0435\u043C \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435\r\n if (error.message.includes('Connection not ready')) {\r\n alert(`\u0424\u0430\u0439\u043B ${file.name} \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u0435\u043D \u0441\u0435\u0439\u0447\u0430\u0441. \u041F\u0440\u043E\u0432\u0435\u0440\u044C\u0442\u0435 \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 \u0438 \u043F\u043E\u043F\u0440\u043E\u0431\u0443\u0439\u0442\u0435 \u0441\u043D\u043E\u0432\u0430.`);\r\n } else if (error.message.includes('File too large') || error.message.includes('exceeds maximum')) {\r\n alert(`\u0424\u0430\u0439\u043B ${file.name} \u0441\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0439: ${error.message}`);\r\n } else if (error.message.includes('Maximum concurrent transfers')) {\r\n alert(`\u0414\u043E\u0441\u0442\u0438\u0433\u043D\u0443\u0442 \u043B\u0438\u043C\u0438\u0442 \u043E\u0434\u043D\u043E\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0445 \u043F\u0435\u0440\u0435\u0434\u0430\u0447. \u0414\u043E\u0436\u0434\u0438\u0442\u0435\u0441\u044C \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u044F \u0442\u0435\u043A\u0443\u0449\u0438\u0445 \u043F\u0435\u0440\u0435\u0434\u0430\u0447.`);\r\n } else if (error.message.includes('File type not allowed')) {\r\n alert(`\u0422\u0438\u043F \u0444\u0430\u0439\u043B\u0430 ${file.name} \u043D\u0435 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F: ${error.message}`);\r\n } else {\r\n alert(`\u041E\u0448\u0438\u0431\u043A\u0430 \u043E\u0442\u043F\u0440\u0430\u0432\u043A\u0438 \u0444\u0430\u0439\u043B\u0430 ${file.name}: ${error.message}`);\r\n }\r\n }\r\n }\r\n };\r\n\r\n const handleDrop = (e) => {\r\n e.preventDefault();\r\n setDragOver(false);\r\n \r\n const files = Array.from(e.dataTransfer.files);\r\n handleFileSelect(files);\r\n };\r\n\r\n const handleDragOver = (e) => {\r\n e.preventDefault();\r\n setDragOver(true);\r\n };\r\n\r\n const handleDragLeave = (e) => {\r\n e.preventDefault();\r\n setDragOver(false);\r\n };\r\n\r\n const handleFileInputChange = (e) => {\r\n const files = Array.from(e.target.files);\r\n handleFileSelect(files);\r\n e.target.value = ''; // Reset input\r\n };\r\n\r\n const formatFileSize = (bytes) => {\r\n if (bytes === 0) return '0 B';\r\n const k = 1024;\r\n const sizes = ['B', 'KB', 'MB', 'GB'];\r\n const i = Math.floor(Math.log(bytes) / Math.log(k));\r\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\r\n };\r\n\r\n const getStatusIcon = (status) => {\r\n switch (status) {\r\n case 'metadata_sent':\r\n case 'preparing':\r\n return 'fas fa-cog fa-spin';\r\n case 'transmitting':\r\n case 'receiving':\r\n return 'fas fa-exchange-alt fa-pulse';\r\n case 'assembling':\r\n return 'fas fa-puzzle-piece fa-pulse';\r\n case 'completed':\r\n return 'fas fa-check text-green-400';\r\n case 'failed':\r\n return 'fas fa-times text-red-400';\r\n default:\r\n return 'fas fa-circle';\r\n }\r\n };\r\n\r\n const getStatusText = (status) => {\r\n switch (status) {\r\n case 'metadata_sent':\r\n return '\u041F\u043E\u0434\u0433\u043E\u0442\u043E\u0432\u043A\u0430...';\r\n case 'transmitting':\r\n return '\u041E\u0442\u043F\u0440\u0430\u0432\u043A\u0430...';\r\n case 'receiving':\r\n return '\u041F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u0435...';\r\n case 'assembling':\r\n return '\u0421\u0431\u043E\u0440\u043A\u0430 \u0444\u0430\u0439\u043B\u0430...';\r\n case 'completed':\r\n return '\u0417\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u043E';\r\n case 'failed':\r\n return '\u041E\u0448\u0438\u0431\u043A\u0430';\r\n default:\r\n return status;\r\n }\r\n };\r\n\r\n if (!isConnected) {\r\n return React.createElement('div', {\r\n className: \"p-4 text-center text-muted\"\r\n }, '\u041F\u0435\u0440\u0435\u0434\u0430\u0447\u0430 \u0444\u0430\u0439\u043B\u043E\u0432 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430 \u0442\u043E\u043B\u044C\u043A\u043E \u043F\u0440\u0438 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u043D\u043E\u043C \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0438');\r\n }\r\n\r\n // \u041F\u0440\u043E\u0432\u0435\u0440\u044F\u0435\u043C \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435 \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\r\n const isConnectionReady = webrtcManager && webrtcManager.isConnected() && webrtcManager.isVerified;\r\n \r\n if (!isConnectionReady) {\r\n return React.createElement('div', {\r\n className: \"p-4 text-center text-yellow-600\"\r\n }, [\r\n React.createElement('i', {\r\n key: 'icon',\r\n className: 'fas fa-exclamation-triangle mr-2'\r\n }),\r\n '\u0421\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 \u0443\u0441\u0442\u0430\u043D\u0430\u0432\u043B\u0438\u0432\u0430\u0435\u0442\u0441\u044F... \u041F\u0435\u0440\u0435\u0434\u0430\u0447\u0430 \u0444\u0430\u0439\u043B\u043E\u0432 \u0431\u0443\u0434\u0435\u0442 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430 \u043F\u043E\u0441\u043B\u0435 \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438.'\r\n ]);\r\n }\r\n\r\n return React.createElement('div', {\r\n className: \"file-transfer-component\"\r\n }, [\r\n // File Drop Zone\r\n React.createElement('div', {\r\n key: 'drop-zone',\r\n className: `file-drop-zone ${dragOver ? 'drag-over' : ''}`,\r\n onDrop: handleDrop,\r\n onDragOver: handleDragOver,\r\n onDragLeave: handleDragLeave,\r\n onClick: () => fileInputRef.current?.click()\r\n }, [\r\n React.createElement('div', {\r\n key: 'drop-content',\r\n className: \"drop-content\"\r\n }, [\r\n React.createElement('i', {\r\n key: 'icon',\r\n className: 'fas fa-cloud-upload-alt text-2xl mb-2 text-blue-400'\r\n }),\r\n React.createElement('p', {\r\n key: 'text',\r\n className: \"text-primary font-medium\"\r\n }, 'Drag files here or click to select'),\r\n React.createElement('p', {\r\n key: 'subtext',\r\n className: \"text-muted text-sm\"\r\n }, 'Maximum size: 100 MB per file')\r\n ])\r\n ]),\r\n\r\n // Hidden file input\r\n React.createElement('input', {\r\n key: 'file-input',\r\n ref: fileInputRef,\r\n type: 'file',\r\n multiple: true,\r\n className: 'hidden',\r\n onChange: handleFileInputChange\r\n }),\r\n\r\n // Active Transfers\r\n (transfers.sending.length > 0 || transfers.receiving.length > 0) && React.createElement('div', {\r\n key: 'transfers',\r\n className: \"active-transfers mt-4\"\r\n }, [\r\n React.createElement('h4', {\r\n key: 'title',\r\n className: \"text-primary font-medium mb-3 flex items-center\"\r\n }, [\r\n React.createElement('i', {\r\n key: 'icon',\r\n className: 'fas fa-exchange-alt mr-2'\r\n }),\r\n '\u041F\u0435\u0440\u0435\u0434\u0430\u0447\u0430 \u0444\u0430\u0439\u043B\u043E\u0432'\r\n ]),\r\n\r\n // Sending files\r\n ...transfers.sending.map(transfer => \r\n React.createElement('div', {\r\n key: `send-${transfer.fileId}`,\r\n className: \"transfer-item bg-blue-500/10 border border-blue-500/20 rounded-lg p-3 mb-2\"\r\n }, [\r\n React.createElement('div', {\r\n key: 'header',\r\n className: \"flex items-center justify-between mb-2\"\r\n }, [\r\n React.createElement('div', {\r\n key: 'info',\r\n className: \"flex items-center\"\r\n }, [\r\n React.createElement('i', {\r\n key: 'icon',\r\n className: 'fas fa-upload text-blue-400 mr-2'\r\n }),\r\n React.createElement('span', {\r\n key: 'name',\r\n className: \"text-primary font-medium text-sm\"\r\n }, transfer.fileName),\r\n React.createElement('span', {\r\n key: 'size',\r\n className: \"text-muted text-xs ml-2\"\r\n }, formatFileSize(transfer.fileSize))\r\n ]),\r\n React.createElement('button', {\r\n key: 'cancel',\r\n onClick: () => webrtcManager.cancelFileTransfer(transfer.fileId),\r\n className: \"text-red-400 hover:text-red-300 text-xs\"\r\n }, [\r\n React.createElement('i', {\r\n className: 'fas fa-times'\r\n })\r\n ])\r\n ]),\r\n React.createElement('div', {\r\n key: 'progress',\r\n className: \"progress-bar\"\r\n }, [\r\n React.createElement('div', {\r\n key: 'fill',\r\n className: \"progress-fill bg-blue-400\",\r\n style: { width: `${transfer.progress}%` }\r\n }),\r\n React.createElement('div', {\r\n key: 'text',\r\n className: \"progress-text text-xs flex items-center justify-between\"\r\n }, [\r\n React.createElement('span', {\r\n key: 'status',\r\n className: \"flex items-center\"\r\n }, [\r\n React.createElement('i', {\r\n key: 'icon',\r\n className: `${getStatusIcon(transfer.status)} mr-1`\r\n }),\r\n getStatusText(transfer.status)\r\n ]),\r\n React.createElement('span', {\r\n key: 'percent'\r\n }, `${transfer.progress.toFixed(1)}%`)\r\n ])\r\n ])\r\n ])\r\n ),\r\n\r\n // Receiving files\r\n ...transfers.receiving.map(transfer => \r\n React.createElement('div', {\r\n key: `recv-${transfer.fileId}`,\r\n className: \"transfer-item bg-green-500/10 border border-green-500/20 rounded-lg p-3 mb-2\"\r\n }, [\r\n React.createElement('div', {\r\n key: 'header',\r\n className: \"flex items-center justify-between mb-2\"\r\n }, [\r\n React.createElement('div', {\r\n key: 'info',\r\n className: \"flex items-center\"\r\n }, [\r\n React.createElement('i', {\r\n key: 'icon',\r\n className: 'fas fa-download text-green-400 mr-2'\r\n }),\r\n React.createElement('span', {\r\n key: 'name',\r\n className: \"text-primary font-medium text-sm\"\r\n }, transfer.fileName),\r\n React.createElement('span', {\r\n key: 'size',\r\n className: \"text-muted text-xs ml-2\"\r\n }, formatFileSize(transfer.fileSize))\r\n ]),\r\n React.createElement('div', { key: 'actions', className: 'flex items-center space-x-2' }, [\r\n (() => {\r\n const rf = readyFiles.find(f => f.fileId === transfer.fileId);\r\n if (!rf || transfer.status !== 'completed') return null;\r\n return React.createElement('button', {\r\n key: 'download',\r\n className: 'text-green-400 hover:text-green-300 text-xs flex items-center',\r\n onClick: async () => {\r\n try {\r\n const url = await rf.getObjectURL();\r\n const a = document.createElement('a');\r\n a.href = url;\r\n a.download = rf.fileName || 'file';\r\n a.click();\r\n rf.revokeObjectURL(url);\r\n } catch (e) {\r\n alert('Failed to start download: ' + e.message);\r\n }\r\n }\r\n }, [\r\n React.createElement('i', { key: 'i', className: 'fas fa-download mr-1' }),\r\n 'Download'\r\n ]);\r\n })(),\r\n React.createElement('button', {\r\n key: 'cancel',\r\n onClick: () => webrtcManager.cancelFileTransfer(transfer.fileId),\r\n className: \"text-red-400 hover:text-red-300 text-xs\"\r\n }, [\r\n React.createElement('i', {\r\n className: 'fas fa-times'\r\n })\r\n ])\r\n ])\r\n ]),\r\n React.createElement('div', {\r\n key: 'progress',\r\n className: \"progress-bar\"\r\n }, [\r\n React.createElement('div', {\r\n key: 'fill',\r\n className: \"progress-fill bg-green-400\",\r\n style: { width: `${transfer.progress}%` }\r\n }),\r\n React.createElement('div', {\r\n key: 'text',\r\n className: \"progress-text text-xs flex items-center justify-between\"\r\n }, [\r\n React.createElement('span', {\r\n key: 'status',\r\n className: \"flex items-center\"\r\n }, [\r\n React.createElement('i', {\r\n key: 'icon',\r\n className: `${getStatusIcon(transfer.status)} mr-1`\r\n }),\r\n getStatusText(transfer.status)\r\n ]),\r\n React.createElement('span', {\r\n key: 'percent'\r\n }, `${transfer.progress.toFixed(1)}%`)\r\n ])\r\n ])\r\n ])\r\n )\r\n ])\r\n ]);\r\n};\r\n\r\n// Export\r\nwindow.FileTransferComponent = FileTransferComponent;", "import { EnhancedSecureCryptoUtils } from '../crypto/EnhancedSecureCryptoUtils.js';\r\nimport { EnhancedSecureWebRTCManager } from '../network/EnhancedSecureWebRTCManager.js';\r\nimport { PayPerSessionManager } from '../session/PayPerSessionManager.js';\r\nimport { EnhancedSecureFileTransfer } from '../transfer/EnhancedSecureFileTransfer.js';\r\n\r\n// Import UI components (side-effect: they attach themselves to window.*)\r\nimport '../components/ui/SessionTimer.jsx';\r\nimport '../components/ui/Header.jsx';\r\nimport '../components/ui/SessionTypeSelector.jsx';\r\nimport '../components/ui/LightningPayment.jsx';\r\nimport '../components/ui/PaymentModal.jsx';\r\nimport '../components/ui/DownloadApps.jsx';\r\nimport '../components/ui/FileTransfer.jsx';\r\n\r\n// Expose to global for legacy usage inside app code\r\nwindow.EnhancedSecureCryptoUtils = EnhancedSecureCryptoUtils;\r\nwindow.EnhancedSecureWebRTCManager = EnhancedSecureWebRTCManager;\r\nwindow.PayPerSessionManager = PayPerSessionManager;\r\nwindow.EnhancedSecureFileTransfer = EnhancedSecureFileTransfer;\r\n\r\n// Mount application once DOM and modules are ready\r\nconst start = () => {\r\n if (typeof window.initializeApp === 'function') {\r\n window.initializeApp();\r\n } else if (window.DEBUG_MODE) {\r\n console.error('initializeApp is not defined on window');\r\n }\r\n};\r\n\r\nif (document.readyState === 'loading') {\r\n document.addEventListener('DOMContentLoaded', start);\r\n} else {\r\n start();\r\n}\r\n"], + "mappings": ";AAAA,IAAM,4BAAN,MAAM,2BAA0B;AAAA,EAE5B,OAAO,eAAe,oBAAI,QAAQ;AAAA;AAAA;AAAA,EAKlC,OAAO,eAAe,KAAK;AACvB,QAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM;AACzC,aAAO;AAAA,IACX;AAEA,QAAI,MAAM,QAAQ,GAAG,GAAG;AACpB,aAAO,IAAI,IAAI,2BAA0B,cAAc;AAAA,IAC3D;AAEA,UAAM,YAAY,CAAC;AACnB,WAAO,KAAK,GAAG,EAAE,KAAK,EAAE,QAAQ,SAAO;AACnC,gBAAU,GAAG,IAAI,2BAA0B,eAAe,IAAI,GAAG,CAAC;AAAA,IACtE,CAAC;AACD,WAAO;AAAA,EACX;AAAA;AAAA,EAGA,OAAO,gBAAgB,KAAK,eAAe,MAAM,iBAAiB,CAAC,GAAG;AAClE,QAAI,EAAE,eAAe,WAAY,OAAM,IAAI,MAAM,oBAAoB;AACrE,QAAI,gBAAgB,IAAI,WAAW,SAAS,cAAc;AACtD,YAAM,IAAI,MAAM,sBAAsB,YAAY,SAAS,IAAI,WAAW,IAAI,EAAE;AAAA,IACpF;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AQ,IAAI;AAAA,YAC5C,CAAC;AAAA,YACD,MAAM,cAAc,OAAO;AAAA,cACvB,KAAK;AAAA,cACL,WAAW;AAAA,YACf,GAAG;AAAA,cACC,MAAM,cAAc,QAAQ;AAAA,gBACxB,KAAK;AAAA,gBACL,WAAW;AAAA,cACf,GAAG;AAAA,gBACC,MAAM,cAAc,KAAK;AAAA,kBACrB,KAAK;AAAA,kBACL,WAAW,GAAG,cAAc,SAAS,MAAM,CAAC;AAAA,gBAChD,CAAC;AAAA,gBACD,cAAc,SAAS,MAAM;AAAA,cACjC,CAAC;AAAA,cACD,MAAM,cAAc,QAAQ;AAAA,gBACxB,KAAK;AAAA,cACT,GAAG,GAAG,SAAS,SAAS,QAAQ,CAAC,CAAC,GAAG;AAAA,YACzC,CAAC;AAAA,UACL,CAAC;AAAA,QACL,CAAC;AAAA,MACL;AAAA,IACJ,CAAC;AAAA,EACL,CAAC;AACL;AAGA,OAAO,wBAAwB;;;ACvZ/B,OAAO,4BAA4B;AACnC,OAAO,8BAA8B;AACrC,OAAO,uBAAuB;AAC9B,OAAO,6BAA6B;AAGpC,IAAM,QAAQ,MAAM;AAClB,MAAI,OAAO,OAAO,kBAAkB,YAAY;AAC9C,WAAO,cAAc;AAAA,EACvB,WAAW,OAAO,YAAY;AAC5B,YAAQ,MAAM,wCAAwC;AAAA,EACxD;AACF;AAEA,IAAI,SAAS,eAAe,WAAW;AACrC,WAAS,iBAAiB,oBAAoB,KAAK;AACrD,OAAO;AACL,QAAM;AACR;", "names": ["fileMessageTypes", "attempts", "start", "start", "attempts", "chunk", "fileMessageTypes", "window", "start", "cryptoValid", "securityLevel", "webrtcManager", "React", "React", "useState", "useEffect", "error"] } diff --git a/node_modules/.bin/cssesc b/node_modules/.bin/cssesc new file mode 100644 index 0000000..5dd9699 --- /dev/null +++ b/node_modules/.bin/cssesc @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../cssesc/bin/cssesc" "$@" +else + exec node "$basedir/../cssesc/bin/cssesc" "$@" +fi diff --git a/node_modules/.bin/cssesc.cmd b/node_modules/.bin/cssesc.cmd new file mode 100644 index 0000000..b560b42 --- /dev/null +++ b/node_modules/.bin/cssesc.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\cssesc\bin\cssesc" %* diff --git a/node_modules/.bin/cssesc.ps1 b/node_modules/.bin/cssesc.ps1 new file mode 100644 index 0000000..480aa17 --- /dev/null +++ b/node_modules/.bin/cssesc.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../cssesc/bin/cssesc" $args + } else { + & "$basedir/node$exe" "$basedir/../cssesc/bin/cssesc" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../cssesc/bin/cssesc" $args + } else { + & "node$exe" "$basedir/../cssesc/bin/cssesc" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/glob b/node_modules/.bin/glob new file mode 100644 index 0000000..6fbc4bb --- /dev/null +++ b/node_modules/.bin/glob @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../glob/dist/esm/bin.mjs" "$@" +else + exec node "$basedir/../glob/dist/esm/bin.mjs" "$@" +fi diff --git a/node_modules/.bin/glob.cmd b/node_modules/.bin/glob.cmd new file mode 100644 index 0000000..3c1d48a --- /dev/null +++ b/node_modules/.bin/glob.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\glob\dist\esm\bin.mjs" %* diff --git a/node_modules/.bin/glob.ps1 b/node_modules/.bin/glob.ps1 new file mode 100644 index 0000000..71ac2b2 --- /dev/null +++ b/node_modules/.bin/glob.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../glob/dist/esm/bin.mjs" $args + } else { + & "$basedir/node$exe" "$basedir/../glob/dist/esm/bin.mjs" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../glob/dist/esm/bin.mjs" $args + } else { + & "node$exe" "$basedir/../glob/dist/esm/bin.mjs" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/nanoid b/node_modules/.bin/nanoid new file mode 100644 index 0000000..46220bd --- /dev/null +++ b/node_modules/.bin/nanoid @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../nanoid/bin/nanoid.cjs" "$@" +else + exec node "$basedir/../nanoid/bin/nanoid.cjs" "$@" +fi diff --git a/node_modules/.bin/nanoid.cmd b/node_modules/.bin/nanoid.cmd new file mode 100644 index 0000000..9c40107 --- /dev/null +++ b/node_modules/.bin/nanoid.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\nanoid\bin\nanoid.cjs" %* diff --git a/node_modules/.bin/nanoid.ps1 b/node_modules/.bin/nanoid.ps1 new file mode 100644 index 0000000..d8a4d7a --- /dev/null +++ b/node_modules/.bin/nanoid.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args + } else { + & "$basedir/node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args + } else { + & "node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/node-which b/node_modules/.bin/node-which new file mode 100644 index 0000000..b49b03f --- /dev/null +++ b/node_modules/.bin/node-which @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../which/bin/node-which" "$@" +else + exec node "$basedir/../which/bin/node-which" "$@" +fi diff --git a/node_modules/.bin/node-which.cmd b/node_modules/.bin/node-which.cmd new file mode 100644 index 0000000..8738aed --- /dev/null +++ b/node_modules/.bin/node-which.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\which\bin\node-which" %* diff --git a/node_modules/.bin/node-which.ps1 b/node_modules/.bin/node-which.ps1 new file mode 100644 index 0000000..cfb09e8 --- /dev/null +++ b/node_modules/.bin/node-which.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../which/bin/node-which" $args + } else { + & "$basedir/node$exe" "$basedir/../which/bin/node-which" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../which/bin/node-which" $args + } else { + & "node$exe" "$basedir/../which/bin/node-which" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/resolve b/node_modules/.bin/resolve new file mode 100644 index 0000000..c043cba --- /dev/null +++ b/node_modules/.bin/resolve @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../resolve/bin/resolve" "$@" +else + exec node "$basedir/../resolve/bin/resolve" "$@" +fi diff --git a/node_modules/.bin/resolve.cmd b/node_modules/.bin/resolve.cmd new file mode 100644 index 0000000..1a017c4 --- /dev/null +++ b/node_modules/.bin/resolve.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\resolve\bin\resolve" %* diff --git a/node_modules/.bin/resolve.ps1 b/node_modules/.bin/resolve.ps1 new file mode 100644 index 0000000..f22b2d3 --- /dev/null +++ b/node_modules/.bin/resolve.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../resolve/bin/resolve" $args + } else { + & "$basedir/node$exe" "$basedir/../resolve/bin/resolve" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../resolve/bin/resolve" $args + } else { + & "node$exe" "$basedir/../resolve/bin/resolve" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/sucrase b/node_modules/.bin/sucrase new file mode 100644 index 0000000..6c58a2e --- /dev/null +++ b/node_modules/.bin/sucrase @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../sucrase/bin/sucrase" "$@" +else + exec node "$basedir/../sucrase/bin/sucrase" "$@" +fi diff --git a/node_modules/.bin/sucrase-node b/node_modules/.bin/sucrase-node new file mode 100644 index 0000000..fb3bb6c --- /dev/null +++ b/node_modules/.bin/sucrase-node @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../sucrase/bin/sucrase-node" "$@" +else + exec node "$basedir/../sucrase/bin/sucrase-node" "$@" +fi diff --git a/node_modules/.bin/sucrase-node.cmd b/node_modules/.bin/sucrase-node.cmd new file mode 100644 index 0000000..7319f3a --- /dev/null +++ b/node_modules/.bin/sucrase-node.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\sucrase\bin\sucrase-node" %* diff --git a/node_modules/.bin/sucrase-node.ps1 b/node_modules/.bin/sucrase-node.ps1 new file mode 100644 index 0000000..9ec0672 --- /dev/null +++ b/node_modules/.bin/sucrase-node.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../sucrase/bin/sucrase-node" $args + } else { + & "$basedir/node$exe" "$basedir/../sucrase/bin/sucrase-node" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../sucrase/bin/sucrase-node" $args + } else { + & "node$exe" "$basedir/../sucrase/bin/sucrase-node" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/sucrase.cmd b/node_modules/.bin/sucrase.cmd new file mode 100644 index 0000000..3cd8928 --- /dev/null +++ b/node_modules/.bin/sucrase.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\sucrase\bin\sucrase" %* diff --git a/node_modules/.bin/sucrase.ps1 b/node_modules/.bin/sucrase.ps1 new file mode 100644 index 0000000..667bb84 --- /dev/null +++ b/node_modules/.bin/sucrase.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../sucrase/bin/sucrase" $args + } else { + & "$basedir/node$exe" "$basedir/../sucrase/bin/sucrase" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../sucrase/bin/sucrase" $args + } else { + & "node$exe" "$basedir/../sucrase/bin/sucrase" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/tailwind b/node_modules/.bin/tailwind new file mode 100644 index 0000000..e475d32 --- /dev/null +++ b/node_modules/.bin/tailwind @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../tailwindcss/lib/cli.js" "$@" +else + exec node "$basedir/../tailwindcss/lib/cli.js" "$@" +fi diff --git a/node_modules/.bin/tailwind.cmd b/node_modules/.bin/tailwind.cmd new file mode 100644 index 0000000..338176a --- /dev/null +++ b/node_modules/.bin/tailwind.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\tailwindcss\lib\cli.js" %* diff --git a/node_modules/.bin/tailwind.ps1 b/node_modules/.bin/tailwind.ps1 new file mode 100644 index 0000000..5d60bef --- /dev/null +++ b/node_modules/.bin/tailwind.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../tailwindcss/lib/cli.js" $args + } else { + & "$basedir/node$exe" "$basedir/../tailwindcss/lib/cli.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../tailwindcss/lib/cli.js" $args + } else { + & "node$exe" "$basedir/../tailwindcss/lib/cli.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/tailwindcss b/node_modules/.bin/tailwindcss new file mode 100644 index 0000000..e475d32 --- /dev/null +++ b/node_modules/.bin/tailwindcss @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../tailwindcss/lib/cli.js" "$@" +else + exec node "$basedir/../tailwindcss/lib/cli.js" "$@" +fi diff --git a/node_modules/.bin/tailwindcss.cmd b/node_modules/.bin/tailwindcss.cmd new file mode 100644 index 0000000..338176a --- /dev/null +++ b/node_modules/.bin/tailwindcss.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\tailwindcss\lib\cli.js" %* diff --git a/node_modules/.bin/tailwindcss.ps1 b/node_modules/.bin/tailwindcss.ps1 new file mode 100644 index 0000000..5d60bef --- /dev/null +++ b/node_modules/.bin/tailwindcss.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../tailwindcss/lib/cli.js" $args + } else { + & "$basedir/node$exe" "$basedir/../tailwindcss/lib/cli.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../tailwindcss/lib/cli.js" $args + } else { + & "node$exe" "$basedir/../tailwindcss/lib/cli.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/yaml b/node_modules/.bin/yaml new file mode 100644 index 0000000..c68b081 --- /dev/null +++ b/node_modules/.bin/yaml @@ -0,0 +1,16 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir=`cygpath -w "$basedir"` + fi + ;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../yaml/bin.mjs" "$@" +else + exec node "$basedir/../yaml/bin.mjs" "$@" +fi diff --git a/node_modules/.bin/yaml.cmd b/node_modules/.bin/yaml.cmd new file mode 100644 index 0000000..f76090f --- /dev/null +++ b/node_modules/.bin/yaml.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\yaml\bin.mjs" %* diff --git a/node_modules/.bin/yaml.ps1 b/node_modules/.bin/yaml.ps1 new file mode 100644 index 0000000..6820582 --- /dev/null +++ b/node_modules/.bin/yaml.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../yaml/bin.mjs" $args + } else { + & "$basedir/node$exe" "$basedir/../yaml/bin.mjs" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../yaml/bin.mjs" $args + } else { + & "node$exe" "$basedir/../yaml/bin.mjs" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index 5e8bfa0..4d62371 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -1,9 +1,22 @@ { - "name": "public", + "name": "securebit-chat", "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { + "node_modules/@alloc/quick-lru": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", + "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/@esbuild/win32-x64": { "version": "0.25.9", "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.9.tgz", @@ -21,6 +34,197 @@ "node": ">=18" } }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@isaacs/cliui/node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@isaacs/cliui/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.30", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.30.tgz", + "integrity": "sha512-GQ7Nw5G2lTu/BtHTKfXhKHok2WGetd4XYcVKGx00SjAk8GMwgJM3zr6zORiPGuOE+/vkc90KtTosSSvaCjKb2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, "node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", @@ -45,6 +249,77 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "dev": true, + "license": "MIT" + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/arg": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", + "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==", + "dev": true, + "license": "MIT" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/camelcase": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", @@ -54,6 +329,54 @@ "node": ">=6" } }, + "node_modules/camelcase-css": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz", + "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chokidar/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/cliui": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", @@ -83,6 +406,44 @@ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "license": "MIT" }, + "node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "dev": true, + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/decamelize": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", @@ -92,12 +453,33 @@ "node": ">=0.10.0" } }, + "node_modules/didyoumean": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", + "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/dijkstrajs": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", "license": "MIT" }, + "node_modules/dlv": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz", + "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "dev": true, + "license": "MIT" + }, "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -146,6 +528,59 @@ "@esbuild/win32-x64": "0.25.9" } }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-glob/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fastq": { + "version": "1.19.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz", + "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/find-up": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", @@ -159,6 +594,33 @@ "node": ">=8" } }, + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "dev": true, + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", @@ -168,6 +630,92 @@ "node": "6.* || 8.* || >= 10.*" } }, + "node_modules/glob": { + "version": "10.4.5", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", + "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", + "dev": true, + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", + "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", @@ -177,6 +725,72 @@ "node": ">=8" } }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/lilconfig": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", + "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true, + "license": "MIT" + }, "node_modules/locate-path": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", @@ -189,6 +803,124 @@ "node": ">=8" } }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-hash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz", + "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, "node_modules/p-limit": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", @@ -225,6 +957,13 @@ "node": ">=6" } }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -234,6 +973,80 @@ "node": ">=8" } }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pirates": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", + "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, "node_modules/pngjs": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", @@ -243,6 +1056,156 @@ "node": ">=10.13.0" } }, + "node_modules/postcss": { + "version": "8.5.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-import": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz", + "integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.0.0", + "read-cache": "^1.0.0", + "resolve": "^1.1.7" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "postcss": "^8.0.0" + } + }, + "node_modules/postcss-js": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.0.1.tgz", + "integrity": "sha512-dDLF8pEO191hJMtlHFPRa8xsizHaM82MLfNkUHdUtVEV3tgTp5oj+8qbEqYM57SLfc74KSbw//4SeJma2LRVIw==", + "dev": true, + "license": "MIT", + "dependencies": { + "camelcase-css": "^2.0.1" + }, + "engines": { + "node": "^12 || ^14 || >= 16" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + "peerDependencies": { + "postcss": "^8.4.21" + } + }, + "node_modules/postcss-load-config": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-4.0.2.tgz", + "integrity": "sha512-bSVhyJGL00wMVoPUzAVAnbEoWyqRxkjv64tUl427SKnPrENtq6hJwUojroMz2VB+Q1edmi4IfrAPpami5VVgMQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "lilconfig": "^3.0.0", + "yaml": "^2.3.4" + }, + "engines": { + "node": ">= 14" + }, + "peerDependencies": { + "postcss": ">=8.0.9", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "postcss": { + "optional": true + }, + "ts-node": { + "optional": true + } + } + }, + "node_modules/postcss-nested": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz", + "integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.1.1" + }, + "engines": { + "node": ">=12.0" + }, + "peerDependencies": { + "postcss": "^8.2.14" + } + }, + "node_modules/postcss-selector-parser": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz", + "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true, + "license": "MIT" + }, "node_modules/qrcode": { "version": "1.5.4", "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", @@ -260,6 +1223,50 @@ "node": ">=10.13.0" } }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/read-cache": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", + "integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "pify": "^2.3.0" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -275,12 +1282,114 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", "license": "ISC" }, + "node_modules/resolve": { + "version": "1.22.10", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz", + "integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.16.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, "node_modules/set-blocking": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", "license": "ISC" }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", @@ -295,6 +1404,22 @@ "node": ">=8" } }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -307,6 +1432,170 @@ "node": ">=8" } }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/sucrase": { + "version": "3.35.0", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.0.tgz", + "integrity": "sha512-8EbVDiu9iN/nESwxeSxDKe0dunta1GOlHufmSSXxMD2z2/tMZpDMpvXQGsc+ajGo8y2uYUmixaSRUc/QPoQ0GA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "glob": "^10.3.10", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tailwindcss": { + "version": "3.4.17", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz", + "integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==", + "dev": true, + "license": "MIT", + "dependencies": { + "@alloc/quick-lru": "^5.2.0", + "arg": "^5.0.2", + "chokidar": "^3.6.0", + "didyoumean": "^1.2.2", + "dlv": "^1.1.3", + "fast-glob": "^3.3.2", + "glob-parent": "^6.0.2", + "is-glob": "^4.0.3", + "jiti": "^1.21.6", + "lilconfig": "^3.1.3", + "micromatch": "^4.0.8", + "normalize-path": "^3.0.0", + "object-hash": "^3.0.0", + "picocolors": "^1.1.1", + "postcss": "^8.4.47", + "postcss-import": "^15.1.0", + "postcss-js": "^4.0.1", + "postcss-load-config": "^4.0.2", + "postcss-nested": "^6.2.0", + "postcss-selector-parser": "^6.1.2", + "resolve": "^1.22.8", + "sucrase": "^3.35.0" + }, + "bin": { + "tailwind": "lib/cli.js", + "tailwindcss": "lib/cli.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tailwindcss/node_modules/jiti": { + "version": "1.21.7", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.7.tgz", + "integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "bin/jiti.js" + } + }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/which-module": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", @@ -327,12 +1616,44 @@ "node": ">=8" } }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/y18n": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", "license": "ISC" }, + "node_modules/yaml": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.1.tgz", + "integrity": "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + } + }, "node_modules/yargs": { "version": "15.4.1", "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", diff --git a/node_modules/@alloc/quick-lru/index.d.ts b/node_modules/@alloc/quick-lru/index.d.ts new file mode 100644 index 0000000..eb819ba --- /dev/null +++ b/node_modules/@alloc/quick-lru/index.d.ts @@ -0,0 +1,128 @@ +declare namespace QuickLRU { + interface Options { + /** + The maximum number of milliseconds an item should remain in the cache. + + @default Infinity + + By default, `maxAge` will be `Infinity`, which means that items will never expire. + Lazy expiration upon the next write or read call. + + Individual expiration of an item can be specified by the `set(key, value, maxAge)` method. + */ + readonly maxAge?: number; + + /** + The maximum number of items before evicting the least recently used items. + */ + readonly maxSize: number; + + /** + Called right before an item is evicted from the cache. + + Useful for side effects or for items like object URLs that need explicit cleanup (`revokeObjectURL`). + */ + onEviction?: (key: KeyType, value: ValueType) => void; + } +} + +declare class QuickLRU + implements Iterable<[KeyType, ValueType]> { + /** + The stored item count. + */ + readonly size: number; + + /** + Simple ["Least Recently Used" (LRU) cache](https://en.m.wikipedia.org/wiki/Cache_replacement_policies#Least_Recently_Used_.28LRU.29). + + The instance is [`iterable`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols) so you can use it directly in a [`for…of`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of) loop. + + @example + ``` + import QuickLRU = require('quick-lru'); + + const lru = new QuickLRU({maxSize: 1000}); + + lru.set('🦄', '🌈'); + + lru.has('🦄'); + //=> true + + lru.get('🦄'); + //=> '🌈' + ``` + */ + constructor(options: QuickLRU.Options); + + [Symbol.iterator](): IterableIterator<[KeyType, ValueType]>; + + /** + Set an item. Returns the instance. + + Individual expiration of an item can be specified with the `maxAge` option. If not specified, the global `maxAge` value will be used in case it is specified in the constructor, otherwise the item will never expire. + + @returns The list instance. + */ + set(key: KeyType, value: ValueType, options?: {maxAge?: number}): this; + + /** + Get an item. + + @returns The stored item or `undefined`. + */ + get(key: KeyType): ValueType | undefined; + + /** + Check if an item exists. + */ + has(key: KeyType): boolean; + + /** + Get an item without marking it as recently used. + + @returns The stored item or `undefined`. + */ + peek(key: KeyType): ValueType | undefined; + + /** + Delete an item. + + @returns `true` if the item is removed or `false` if the item doesn't exist. + */ + delete(key: KeyType): boolean; + + /** + Delete all items. + */ + clear(): void; + + /** + Update the `maxSize` in-place, discarding items as necessary. Insertion order is mostly preserved, though this is not a strong guarantee. + + Useful for on-the-fly tuning of cache sizes in live systems. + */ + resize(maxSize: number): void; + + /** + Iterable for all the keys. + */ + keys(): IterableIterator; + + /** + Iterable for all the values. + */ + values(): IterableIterator; + + /** + Iterable for all entries, starting with the oldest (ascending in recency). + */ + entriesAscending(): IterableIterator<[KeyType, ValueType]>; + + /** + Iterable for all entries, starting with the newest (descending in recency). + */ + entriesDescending(): IterableIterator<[KeyType, ValueType]>; +} + +export = QuickLRU; diff --git a/node_modules/@alloc/quick-lru/index.js b/node_modules/@alloc/quick-lru/index.js new file mode 100644 index 0000000..7eeced2 --- /dev/null +++ b/node_modules/@alloc/quick-lru/index.js @@ -0,0 +1,263 @@ +'use strict'; + +class QuickLRU { + constructor(options = {}) { + if (!(options.maxSize && options.maxSize > 0)) { + throw new TypeError('`maxSize` must be a number greater than 0'); + } + + if (typeof options.maxAge === 'number' && options.maxAge === 0) { + throw new TypeError('`maxAge` must be a number greater than 0'); + } + + this.maxSize = options.maxSize; + this.maxAge = options.maxAge || Infinity; + this.onEviction = options.onEviction; + this.cache = new Map(); + this.oldCache = new Map(); + this._size = 0; + } + + _emitEvictions(cache) { + if (typeof this.onEviction !== 'function') { + return; + } + + for (const [key, item] of cache) { + this.onEviction(key, item.value); + } + } + + _deleteIfExpired(key, item) { + if (typeof item.expiry === 'number' && item.expiry <= Date.now()) { + if (typeof this.onEviction === 'function') { + this.onEviction(key, item.value); + } + + return this.delete(key); + } + + return false; + } + + _getOrDeleteIfExpired(key, item) { + const deleted = this._deleteIfExpired(key, item); + if (deleted === false) { + return item.value; + } + } + + _getItemValue(key, item) { + return item.expiry ? this._getOrDeleteIfExpired(key, item) : item.value; + } + + _peek(key, cache) { + const item = cache.get(key); + + return this._getItemValue(key, item); + } + + _set(key, value) { + this.cache.set(key, value); + this._size++; + + if (this._size >= this.maxSize) { + this._size = 0; + this._emitEvictions(this.oldCache); + this.oldCache = this.cache; + this.cache = new Map(); + } + } + + _moveToRecent(key, item) { + this.oldCache.delete(key); + this._set(key, item); + } + + * _entriesAscending() { + for (const item of this.oldCache) { + const [key, value] = item; + if (!this.cache.has(key)) { + const deleted = this._deleteIfExpired(key, value); + if (deleted === false) { + yield item; + } + } + } + + for (const item of this.cache) { + const [key, value] = item; + const deleted = this._deleteIfExpired(key, value); + if (deleted === false) { + yield item; + } + } + } + + get(key) { + if (this.cache.has(key)) { + const item = this.cache.get(key); + + return this._getItemValue(key, item); + } + + if (this.oldCache.has(key)) { + const item = this.oldCache.get(key); + if (this._deleteIfExpired(key, item) === false) { + this._moveToRecent(key, item); + return item.value; + } + } + } + + set(key, value, {maxAge = this.maxAge === Infinity ? undefined : Date.now() + this.maxAge} = {}) { + if (this.cache.has(key)) { + this.cache.set(key, { + value, + maxAge + }); + } else { + this._set(key, {value, expiry: maxAge}); + } + } + + has(key) { + if (this.cache.has(key)) { + return !this._deleteIfExpired(key, this.cache.get(key)); + } + + if (this.oldCache.has(key)) { + return !this._deleteIfExpired(key, this.oldCache.get(key)); + } + + return false; + } + + peek(key) { + if (this.cache.has(key)) { + return this._peek(key, this.cache); + } + + if (this.oldCache.has(key)) { + return this._peek(key, this.oldCache); + } + } + + delete(key) { + const deleted = this.cache.delete(key); + if (deleted) { + this._size--; + } + + return this.oldCache.delete(key) || deleted; + } + + clear() { + this.cache.clear(); + this.oldCache.clear(); + this._size = 0; + } + + resize(newSize) { + if (!(newSize && newSize > 0)) { + throw new TypeError('`maxSize` must be a number greater than 0'); + } + + const items = [...this._entriesAscending()]; + const removeCount = items.length - newSize; + if (removeCount < 0) { + this.cache = new Map(items); + this.oldCache = new Map(); + this._size = items.length; + } else { + if (removeCount > 0) { + this._emitEvictions(items.slice(0, removeCount)); + } + + this.oldCache = new Map(items.slice(removeCount)); + this.cache = new Map(); + this._size = 0; + } + + this.maxSize = newSize; + } + + * keys() { + for (const [key] of this) { + yield key; + } + } + + * values() { + for (const [, value] of this) { + yield value; + } + } + + * [Symbol.iterator]() { + for (const item of this.cache) { + const [key, value] = item; + const deleted = this._deleteIfExpired(key, value); + if (deleted === false) { + yield [key, value.value]; + } + } + + for (const item of this.oldCache) { + const [key, value] = item; + if (!this.cache.has(key)) { + const deleted = this._deleteIfExpired(key, value); + if (deleted === false) { + yield [key, value.value]; + } + } + } + } + + * entriesDescending() { + let items = [...this.cache]; + for (let i = items.length - 1; i >= 0; --i) { + const item = items[i]; + const [key, value] = item; + const deleted = this._deleteIfExpired(key, value); + if (deleted === false) { + yield [key, value.value]; + } + } + + items = [...this.oldCache]; + for (let i = items.length - 1; i >= 0; --i) { + const item = items[i]; + const [key, value] = item; + if (!this.cache.has(key)) { + const deleted = this._deleteIfExpired(key, value); + if (deleted === false) { + yield [key, value.value]; + } + } + } + } + + * entriesAscending() { + for (const [key, value] of this._entriesAscending()) { + yield [key, value.value]; + } + } + + get size() { + if (!this._size) { + return this.oldCache.size; + } + + let oldCacheSize = 0; + for (const key of this.oldCache.keys()) { + if (!this.cache.has(key)) { + oldCacheSize++; + } + } + + return Math.min(this._size + oldCacheSize, this.maxSize); + } +} + +module.exports = QuickLRU; diff --git a/node_modules/@alloc/quick-lru/license b/node_modules/@alloc/quick-lru/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/@alloc/quick-lru/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@alloc/quick-lru/package.json b/node_modules/@alloc/quick-lru/package.json new file mode 100644 index 0000000..21f1072 --- /dev/null +++ b/node_modules/@alloc/quick-lru/package.json @@ -0,0 +1,43 @@ +{ + "name": "@alloc/quick-lru", + "version": "5.2.0", + "description": "Simple “Least Recently Used” (LRU) cache", + "license": "MIT", + "repository": "sindresorhus/quick-lru", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && nyc ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "lru", + "quick", + "cache", + "caching", + "least", + "recently", + "used", + "fast", + "map", + "hash", + "buffer" + ], + "devDependencies": { + "ava": "^2.0.0", + "coveralls": "^3.0.3", + "nyc": "^15.0.0", + "tsd": "^0.11.0", + "xo": "^0.26.0" + } +} diff --git a/node_modules/@alloc/quick-lru/readme.md b/node_modules/@alloc/quick-lru/readme.md new file mode 100644 index 0000000..7187ba5 --- /dev/null +++ b/node_modules/@alloc/quick-lru/readme.md @@ -0,0 +1,139 @@ +# quick-lru [![Build Status](https://travis-ci.org/sindresorhus/quick-lru.svg?branch=master)](https://travis-ci.org/sindresorhus/quick-lru) [![Coverage Status](https://coveralls.io/repos/github/sindresorhus/quick-lru/badge.svg?branch=master)](https://coveralls.io/github/sindresorhus/quick-lru?branch=master) + +> Simple [“Least Recently Used” (LRU) cache](https://en.m.wikipedia.org/wiki/Cache_replacement_policies#Least_Recently_Used_.28LRU.29) + +Useful when you need to cache something and limit memory usage. + +Inspired by the [`hashlru` algorithm](https://github.com/dominictarr/hashlru#algorithm), but instead uses [`Map`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map) to support keys of any type, not just strings, and values can be `undefined`. + +## Install + +``` +$ npm install quick-lru +``` + +## Usage + +```js +const QuickLRU = require('quick-lru'); + +const lru = new QuickLRU({maxSize: 1000}); + +lru.set('🦄', '🌈'); + +lru.has('🦄'); +//=> true + +lru.get('🦄'); +//=> '🌈' +``` + +## API + +### new QuickLRU(options?) + +Returns a new instance. + +### options + +Type: `object` + +#### maxSize + +*Required*\ +Type: `number` + +The maximum number of items before evicting the least recently used items. + +#### maxAge + +Type: `number`\ +Default: `Infinity` + +The maximum number of milliseconds an item should remain in cache. +By default maxAge will be Infinity, which means that items will never expire. + +Lazy expiration happens upon the next `write` or `read` call. + +Individual expiration of an item can be specified by the `set(key, value, options)` method. + +#### onEviction + +*Optional*\ +Type: `(key, value) => void` + +Called right before an item is evicted from the cache. + +Useful for side effects or for items like object URLs that need explicit cleanup (`revokeObjectURL`). + +### Instance + +The instance is [`iterable`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols) so you can use it directly in a [`for…of`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of) loop. + +Both `key` and `value` can be of any type. + +#### .set(key, value, options?) + +Set an item. Returns the instance. + +Individual expiration of an item can be specified with the `maxAge` option. If not specified, the global `maxAge` value will be used in case it is specified on the constructor, otherwise the item will never expire. + +#### .get(key) + +Get an item. + +#### .has(key) + +Check if an item exists. + +#### .peek(key) + +Get an item without marking it as recently used. + +#### .delete(key) + +Delete an item. + +Returns `true` if the item is removed or `false` if the item doesn't exist. + +#### .clear() + +Delete all items. + +#### .resize(maxSize) + +Update the `maxSize`, discarding items as necessary. Insertion order is mostly preserved, though this is not a strong guarantee. + +Useful for on-the-fly tuning of cache sizes in live systems. + +#### .keys() + +Iterable for all the keys. + +#### .values() + +Iterable for all the values. + +#### .entriesAscending() + +Iterable for all entries, starting with the oldest (ascending in recency). + +#### .entriesDescending() + +Iterable for all entries, starting with the newest (descending in recency). + +#### .size + +The stored item count. + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/@isaacs/cliui/LICENSE.txt b/node_modules/@isaacs/cliui/LICENSE.txt new file mode 100644 index 0000000..c7e2747 --- /dev/null +++ b/node_modules/@isaacs/cliui/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@isaacs/cliui/README.md b/node_modules/@isaacs/cliui/README.md new file mode 100644 index 0000000..4880642 --- /dev/null +++ b/node_modules/@isaacs/cliui/README.md @@ -0,0 +1,143 @@ +# @isaacs/cliui + +Temporary fork of [cliui](http://npm.im/cliui). + +![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg) +[![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) +[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) +![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui) + +easily create complex multi-column command-line-interfaces. + +## Example + +```js +const ui = require('cliui')() + +ui.div('Usage: $0 [command] [options]') + +ui.div({ + text: 'Options:', + padding: [2, 0, 1, 0] +}) + +ui.div( + { + text: "-f, --file", + width: 20, + padding: [0, 4, 0, 4] + }, + { + text: "the file to load." + + chalk.green("(if this description is long it wraps).") + , + width: 20 + }, + { + text: chalk.red("[required]"), + align: 'right' + } +) + +console.log(ui.toString()) +``` + +## Deno/ESM Support + +As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and +[ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules): + +```typescript +import cliui from "https://deno.land/x/cliui/deno.ts"; + +const ui = cliui({}) + +ui.div('Usage: $0 [command] [options]') + +ui.div({ + text: 'Options:', + padding: [2, 0, 1, 0] +}) + +ui.div({ + text: "-f, --file", + width: 20, + padding: [0, 4, 0, 4] +}) + +console.log(ui.toString()) +``` + + + +## Layout DSL + +cliui exposes a simple layout DSL: + +If you create a single `ui.div`, passing a string rather than an +object: + +* `\n`: characters will be interpreted as new rows. +* `\t`: characters will be interpreted as new columns. +* `\s`: characters will be interpreted as padding. + +**as an example...** + +```js +var ui = require('./')({ + width: 60 +}) + +ui.div( + 'Usage: node ./bin/foo.js\n' + + ' \t provide a regex\n' + + ' \t provide a glob\t [required]' +) + +console.log(ui.toString()) +``` + +**will output:** + +```shell +Usage: node ./bin/foo.js + provide a regex + provide a glob [required] +``` + +## Methods + +```js +cliui = require('cliui') +``` + +### cliui({width: integer}) + +Specify the maximum width of the UI being generated. +If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. + +### cliui({wrap: boolean}) + +Enable or disable the wrapping of text in a column. + +### cliui.div(column, column, column) + +Create a row with any number of columns, a column +can either be a string, or an object with the following +options: + +* **text:** some text to place in the column. +* **width:** the width of a column. +* **align:** alignment, `right` or `center`. +* **padding:** `[top, right, bottom, left]`. +* **border:** should a border be placed around the div? + +### cliui.span(column, column, column) + +Similar to `div`, except the next row will be appended without +a new line being created. + +### cliui.resetOutput() + +Resets the UI elements of the current cliui instance, maintaining the values +set for `width` and `wrap`. diff --git a/node_modules/@isaacs/cliui/build/index.cjs b/node_modules/@isaacs/cliui/build/index.cjs new file mode 100644 index 0000000..aca2b85 --- /dev/null +++ b/node_modules/@isaacs/cliui/build/index.cjs @@ -0,0 +1,317 @@ +'use strict'; + +const align = { + right: alignRight, + center: alignCenter +}; +const top = 0; +const right = 1; +const bottom = 2; +const left = 3; +class UI { + constructor(opts) { + var _a; + this.width = opts.width; + /* c8 ignore start */ + this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true; + /* c8 ignore stop */ + this.rows = []; + } + span(...args) { + const cols = this.div(...args); + cols.span = true; + } + resetOutput() { + this.rows = []; + } + div(...args) { + if (args.length === 0) { + this.div(''); + } + if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') { + return this.applyLayoutDSL(args[0]); + } + const cols = args.map(arg => { + if (typeof arg === 'string') { + return this.colFromString(arg); + } + return arg; + }); + this.rows.push(cols); + return cols; + } + shouldApplyLayoutDSL(...args) { + return args.length === 1 && typeof args[0] === 'string' && + /[\t\n]/.test(args[0]); + } + applyLayoutDSL(str) { + const rows = str.split('\n').map(row => row.split('\t')); + let leftColumnWidth = 0; + // simple heuristic for layout, make sure the + // second column lines up along the left-hand. + // don't allow the first column to take up more + // than 50% of the screen. + rows.forEach(columns => { + if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) { + leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0])); + } + }); + // generate a table: + // replacing ' ' with padding calculations. + // using the algorithmically generated width. + rows.forEach(columns => { + this.div(...columns.map((r, i) => { + return { + text: r.trim(), + padding: this.measurePadding(r), + width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined + }; + })); + }); + return this.rows[this.rows.length - 1]; + } + colFromString(text) { + return { + text, + padding: this.measurePadding(text) + }; + } + measurePadding(str) { + // measure padding without ansi escape codes + const noAnsi = mixin.stripAnsi(str); + return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; + } + toString() { + const lines = []; + this.rows.forEach(row => { + this.rowToString(row, lines); + }); + // don't display any lines with the + // hidden flag set. + return lines + .filter(line => !line.hidden) + .map(line => line.text) + .join('\n'); + } + rowToString(row, lines) { + this.rasterize(row).forEach((rrow, r) => { + let str = ''; + rrow.forEach((col, c) => { + const { width } = row[c]; // the width with padding. + const wrapWidth = this.negatePadding(row[c]); // the width without padding. + let ts = col; // temporary string used during alignment/padding. + if (wrapWidth > mixin.stringWidth(col)) { + ts += ' '.repeat(wrapWidth - mixin.stringWidth(col)); + } + // align the string within its column. + if (row[c].align && row[c].align !== 'left' && this.wrap) { + const fn = align[row[c].align]; + ts = fn(ts, wrapWidth); + if (mixin.stringWidth(ts) < wrapWidth) { + /* c8 ignore start */ + const w = width || 0; + /* c8 ignore stop */ + ts += ' '.repeat(w - mixin.stringWidth(ts) - 1); + } + } + // apply border and padding to string. + const padding = row[c].padding || [0, 0, 0, 0]; + if (padding[left]) { + str += ' '.repeat(padding[left]); + } + str += addBorder(row[c], ts, '| '); + str += ts; + str += addBorder(row[c], ts, ' |'); + if (padding[right]) { + str += ' '.repeat(padding[right]); + } + // if prior row is span, try to render the + // current row on the prior line. + if (r === 0 && lines.length > 0) { + str = this.renderInline(str, lines[lines.length - 1]); + } + }); + // remove trailing whitespace. + lines.push({ + text: str.replace(/ +$/, ''), + span: row.span + }); + }); + return lines; + } + // if the full 'source' can render in + // the target line, do so. + renderInline(source, previousLine) { + const match = source.match(/^ */); + /* c8 ignore start */ + const leadingWhitespace = match ? match[0].length : 0; + /* c8 ignore stop */ + const target = previousLine.text; + const targetTextWidth = mixin.stringWidth(target.trimEnd()); + if (!previousLine.span) { + return source; + } + // if we're not applying wrapping logic, + // just always append to the span. + if (!this.wrap) { + previousLine.hidden = true; + return target + source; + } + if (leadingWhitespace < targetTextWidth) { + return source; + } + previousLine.hidden = true; + return target.trimEnd() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimStart(); + } + rasterize(row) { + const rrows = []; + const widths = this.columnWidths(row); + let wrapped; + // word wrap all columns, and create + // a data-structure that is easy to rasterize. + row.forEach((col, c) => { + // leave room for left and right padding. + col.width = widths[c]; + if (this.wrap) { + wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n'); + } + else { + wrapped = col.text.split('\n'); + } + if (col.border) { + wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.'); + wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'"); + } + // add top and bottom padding. + if (col.padding) { + wrapped.unshift(...new Array(col.padding[top] || 0).fill('')); + wrapped.push(...new Array(col.padding[bottom] || 0).fill('')); + } + wrapped.forEach((str, r) => { + if (!rrows[r]) { + rrows.push([]); + } + const rrow = rrows[r]; + for (let i = 0; i < c; i++) { + if (rrow[i] === undefined) { + rrow.push(''); + } + } + rrow.push(str); + }); + }); + return rrows; + } + negatePadding(col) { + /* c8 ignore start */ + let wrapWidth = col.width || 0; + /* c8 ignore stop */ + if (col.padding) { + wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); + } + if (col.border) { + wrapWidth -= 4; + } + return wrapWidth; + } + columnWidths(row) { + if (!this.wrap) { + return row.map(col => { + return col.width || mixin.stringWidth(col.text); + }); + } + let unset = row.length; + let remainingWidth = this.width; + // column widths can be set in config. + const widths = row.map(col => { + if (col.width) { + unset--; + remainingWidth -= col.width; + return col.width; + } + return undefined; + }); + // any unset widths should be calculated. + /* c8 ignore start */ + const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; + /* c8 ignore stop */ + return widths.map((w, i) => { + if (w === undefined) { + return Math.max(unsetWidth, _minWidth(row[i])); + } + return w; + }); + } +} +function addBorder(col, ts, style) { + if (col.border) { + if (/[.']-+[.']/.test(ts)) { + return ''; + } + if (ts.trim().length !== 0) { + return style; + } + return ' '; + } + return ''; +} +// calculates the minimum width of +// a column, based on padding preferences. +function _minWidth(col) { + const padding = col.padding || []; + const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); + if (col.border) { + return minWidth + 4; + } + return minWidth; +} +function getWindowWidth() { + /* c8 ignore start */ + if (typeof process === 'object' && process.stdout && process.stdout.columns) { + return process.stdout.columns; + } + return 80; +} +/* c8 ignore stop */ +function alignRight(str, width) { + str = str.trim(); + const strWidth = mixin.stringWidth(str); + if (strWidth < width) { + return ' '.repeat(width - strWidth) + str; + } + return str; +} +function alignCenter(str, width) { + str = str.trim(); + const strWidth = mixin.stringWidth(str); + /* c8 ignore start */ + if (strWidth >= width) { + return str; + } + /* c8 ignore stop */ + return ' '.repeat((width - strWidth) >> 1) + str; +} +let mixin; +function cliui(opts, _mixin) { + mixin = _mixin; + return new UI({ + /* c8 ignore start */ + width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), + wrap: opts === null || opts === void 0 ? void 0 : opts.wrap + /* c8 ignore stop */ + }); +} + +// Bootstrap cliui with CommonJS dependencies: +const stringWidth = require('string-width-cjs'); +const stripAnsi = require('strip-ansi-cjs'); +const wrap = require('wrap-ansi-cjs'); +function ui(opts) { + return cliui(opts, { + stringWidth, + stripAnsi, + wrap + }); +} + +module.exports = ui; diff --git a/node_modules/@isaacs/cliui/build/index.d.cts b/node_modules/@isaacs/cliui/build/index.d.cts new file mode 100644 index 0000000..4567f94 --- /dev/null +++ b/node_modules/@isaacs/cliui/build/index.d.cts @@ -0,0 +1,43 @@ +interface UIOptions { + width: number; + wrap?: boolean; + rows?: string[]; +} +interface Column { + text: string; + width?: number; + align?: "right" | "left" | "center"; + padding: number[]; + border?: boolean; +} +interface ColumnArray extends Array { + span: boolean; +} +interface Line { + hidden?: boolean; + text: string; + span?: boolean; +} +declare class UI { + width: number; + wrap: boolean; + rows: ColumnArray[]; + constructor(opts: UIOptions); + span(...args: ColumnArray): void; + resetOutput(): void; + div(...args: (Column | string)[]): ColumnArray; + private shouldApplyLayoutDSL; + private applyLayoutDSL; + private colFromString; + private measurePadding; + toString(): string; + rowToString(row: ColumnArray, lines: Line[]): Line[]; + // if the full 'source' can render in + // the target line, do so. + private renderInline; + private rasterize; + private negatePadding; + private columnWidths; +} +declare function ui(opts: UIOptions): UI; +export { ui as default }; diff --git a/node_modules/@isaacs/cliui/build/lib/index.js b/node_modules/@isaacs/cliui/build/lib/index.js new file mode 100644 index 0000000..587b5ec --- /dev/null +++ b/node_modules/@isaacs/cliui/build/lib/index.js @@ -0,0 +1,302 @@ +'use strict'; +const align = { + right: alignRight, + center: alignCenter +}; +const top = 0; +const right = 1; +const bottom = 2; +const left = 3; +export class UI { + constructor(opts) { + var _a; + this.width = opts.width; + /* c8 ignore start */ + this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true; + /* c8 ignore stop */ + this.rows = []; + } + span(...args) { + const cols = this.div(...args); + cols.span = true; + } + resetOutput() { + this.rows = []; + } + div(...args) { + if (args.length === 0) { + this.div(''); + } + if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') { + return this.applyLayoutDSL(args[0]); + } + const cols = args.map(arg => { + if (typeof arg === 'string') { + return this.colFromString(arg); + } + return arg; + }); + this.rows.push(cols); + return cols; + } + shouldApplyLayoutDSL(...args) { + return args.length === 1 && typeof args[0] === 'string' && + /[\t\n]/.test(args[0]); + } + applyLayoutDSL(str) { + const rows = str.split('\n').map(row => row.split('\t')); + let leftColumnWidth = 0; + // simple heuristic for layout, make sure the + // second column lines up along the left-hand. + // don't allow the first column to take up more + // than 50% of the screen. + rows.forEach(columns => { + if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) { + leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0])); + } + }); + // generate a table: + // replacing ' ' with padding calculations. + // using the algorithmically generated width. + rows.forEach(columns => { + this.div(...columns.map((r, i) => { + return { + text: r.trim(), + padding: this.measurePadding(r), + width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined + }; + })); + }); + return this.rows[this.rows.length - 1]; + } + colFromString(text) { + return { + text, + padding: this.measurePadding(text) + }; + } + measurePadding(str) { + // measure padding without ansi escape codes + const noAnsi = mixin.stripAnsi(str); + return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; + } + toString() { + const lines = []; + this.rows.forEach(row => { + this.rowToString(row, lines); + }); + // don't display any lines with the + // hidden flag set. + return lines + .filter(line => !line.hidden) + .map(line => line.text) + .join('\n'); + } + rowToString(row, lines) { + this.rasterize(row).forEach((rrow, r) => { + let str = ''; + rrow.forEach((col, c) => { + const { width } = row[c]; // the width with padding. + const wrapWidth = this.negatePadding(row[c]); // the width without padding. + let ts = col; // temporary string used during alignment/padding. + if (wrapWidth > mixin.stringWidth(col)) { + ts += ' '.repeat(wrapWidth - mixin.stringWidth(col)); + } + // align the string within its column. + if (row[c].align && row[c].align !== 'left' && this.wrap) { + const fn = align[row[c].align]; + ts = fn(ts, wrapWidth); + if (mixin.stringWidth(ts) < wrapWidth) { + /* c8 ignore start */ + const w = width || 0; + /* c8 ignore stop */ + ts += ' '.repeat(w - mixin.stringWidth(ts) - 1); + } + } + // apply border and padding to string. + const padding = row[c].padding || [0, 0, 0, 0]; + if (padding[left]) { + str += ' '.repeat(padding[left]); + } + str += addBorder(row[c], ts, '| '); + str += ts; + str += addBorder(row[c], ts, ' |'); + if (padding[right]) { + str += ' '.repeat(padding[right]); + } + // if prior row is span, try to render the + // current row on the prior line. + if (r === 0 && lines.length > 0) { + str = this.renderInline(str, lines[lines.length - 1]); + } + }); + // remove trailing whitespace. + lines.push({ + text: str.replace(/ +$/, ''), + span: row.span + }); + }); + return lines; + } + // if the full 'source' can render in + // the target line, do so. + renderInline(source, previousLine) { + const match = source.match(/^ */); + /* c8 ignore start */ + const leadingWhitespace = match ? match[0].length : 0; + /* c8 ignore stop */ + const target = previousLine.text; + const targetTextWidth = mixin.stringWidth(target.trimEnd()); + if (!previousLine.span) { + return source; + } + // if we're not applying wrapping logic, + // just always append to the span. + if (!this.wrap) { + previousLine.hidden = true; + return target + source; + } + if (leadingWhitespace < targetTextWidth) { + return source; + } + previousLine.hidden = true; + return target.trimEnd() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimStart(); + } + rasterize(row) { + const rrows = []; + const widths = this.columnWidths(row); + let wrapped; + // word wrap all columns, and create + // a data-structure that is easy to rasterize. + row.forEach((col, c) => { + // leave room for left and right padding. + col.width = widths[c]; + if (this.wrap) { + wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n'); + } + else { + wrapped = col.text.split('\n'); + } + if (col.border) { + wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.'); + wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'"); + } + // add top and bottom padding. + if (col.padding) { + wrapped.unshift(...new Array(col.padding[top] || 0).fill('')); + wrapped.push(...new Array(col.padding[bottom] || 0).fill('')); + } + wrapped.forEach((str, r) => { + if (!rrows[r]) { + rrows.push([]); + } + const rrow = rrows[r]; + for (let i = 0; i < c; i++) { + if (rrow[i] === undefined) { + rrow.push(''); + } + } + rrow.push(str); + }); + }); + return rrows; + } + negatePadding(col) { + /* c8 ignore start */ + let wrapWidth = col.width || 0; + /* c8 ignore stop */ + if (col.padding) { + wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); + } + if (col.border) { + wrapWidth -= 4; + } + return wrapWidth; + } + columnWidths(row) { + if (!this.wrap) { + return row.map(col => { + return col.width || mixin.stringWidth(col.text); + }); + } + let unset = row.length; + let remainingWidth = this.width; + // column widths can be set in config. + const widths = row.map(col => { + if (col.width) { + unset--; + remainingWidth -= col.width; + return col.width; + } + return undefined; + }); + // any unset widths should be calculated. + /* c8 ignore start */ + const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; + /* c8 ignore stop */ + return widths.map((w, i) => { + if (w === undefined) { + return Math.max(unsetWidth, _minWidth(row[i])); + } + return w; + }); + } +} +function addBorder(col, ts, style) { + if (col.border) { + if (/[.']-+[.']/.test(ts)) { + return ''; + } + if (ts.trim().length !== 0) { + return style; + } + return ' '; + } + return ''; +} +// calculates the minimum width of +// a column, based on padding preferences. +function _minWidth(col) { + const padding = col.padding || []; + const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); + if (col.border) { + return minWidth + 4; + } + return minWidth; +} +function getWindowWidth() { + /* c8 ignore start */ + if (typeof process === 'object' && process.stdout && process.stdout.columns) { + return process.stdout.columns; + } + return 80; +} +/* c8 ignore stop */ +function alignRight(str, width) { + str = str.trim(); + const strWidth = mixin.stringWidth(str); + if (strWidth < width) { + return ' '.repeat(width - strWidth) + str; + } + return str; +} +function alignCenter(str, width) { + str = str.trim(); + const strWidth = mixin.stringWidth(str); + /* c8 ignore start */ + if (strWidth >= width) { + return str; + } + /* c8 ignore stop */ + return ' '.repeat((width - strWidth) >> 1) + str; +} +let mixin; +export function cliui(opts, _mixin) { + mixin = _mixin; + return new UI({ + /* c8 ignore start */ + width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), + wrap: opts === null || opts === void 0 ? void 0 : opts.wrap + /* c8 ignore stop */ + }); +} diff --git a/node_modules/@isaacs/cliui/index.mjs b/node_modules/@isaacs/cliui/index.mjs new file mode 100644 index 0000000..5177519 --- /dev/null +++ b/node_modules/@isaacs/cliui/index.mjs @@ -0,0 +1,14 @@ +// Bootstrap cliui with ESM dependencies: +import { cliui } from './build/lib/index.js' + +import stringWidth from 'string-width' +import stripAnsi from 'strip-ansi' +import wrap from 'wrap-ansi' + +export default function ui (opts) { + return cliui(opts, { + stringWidth, + stripAnsi, + wrap + }) +} diff --git a/node_modules/@isaacs/cliui/node_modules/ansi-regex/index.d.ts b/node_modules/@isaacs/cliui/node_modules/ansi-regex/index.d.ts new file mode 100644 index 0000000..7d562e9 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/ansi-regex/index.d.ts @@ -0,0 +1,33 @@ +export type Options = { + /** + Match only the first ANSI escape. + + @default false + */ + readonly onlyFirst: boolean; +}; + +/** +Regular expression for matching ANSI escape codes. + +@example +``` +import ansiRegex from 'ansi-regex'; + +ansiRegex().test('\u001B[4mcake\u001B[0m'); +//=> true + +ansiRegex().test('cake'); +//=> false + +'\u001B[4mcake\u001B[0m'.match(ansiRegex()); +//=> ['\u001B[4m', '\u001B[0m'] + +'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); +//=> ['\u001B[4m'] + +'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); +//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] +``` +*/ +export default function ansiRegex(options?: Options): RegExp; diff --git a/node_modules/@isaacs/cliui/node_modules/ansi-regex/index.js b/node_modules/@isaacs/cliui/node_modules/ansi-regex/index.js new file mode 100644 index 0000000..2cc5ca2 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/ansi-regex/index.js @@ -0,0 +1,14 @@ +export default function ansiRegex({onlyFirst = false} = {}) { + // Valid string terminator sequences are BEL, ESC\, and 0x9c + const ST = '(?:\\u0007|\\u001B\\u005C|\\u009C)'; + + // OSC sequences only: ESC ] ... ST (non-greedy until the first ST) + const osc = `(?:\\u001B\\][\\s\\S]*?${ST})`; + + // CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :) then final byte + const csi = '[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]'; + + const pattern = `${osc}|${csi}`; + + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +} diff --git a/node_modules/@isaacs/cliui/node_modules/ansi-regex/license b/node_modules/@isaacs/cliui/node_modules/ansi-regex/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/ansi-regex/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@isaacs/cliui/node_modules/ansi-regex/package.json b/node_modules/@isaacs/cliui/node_modules/ansi-regex/package.json new file mode 100644 index 0000000..2efe9eb --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/ansi-regex/package.json @@ -0,0 +1,61 @@ +{ + "name": "ansi-regex", + "version": "6.2.2", + "description": "Regular expression for matching ANSI escape codes", + "license": "MIT", + "repository": "chalk/ansi-regex", + "funding": "https://github.com/chalk/ansi-regex?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": "./index.js", + "types": "./index.d.ts", + "sideEffects": false, + "engines": { + "node": ">=12" + }, + "scripts": { + "test": "xo && ava && tsd", + "view-supported": "node fixtures/view-codes.js" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "text", + "regex", + "regexp", + "re", + "match", + "test", + "find", + "pattern" + ], + "devDependencies": { + "ansi-escapes": "^5.0.0", + "ava": "^3.15.0", + "tsd": "^0.21.0", + "xo": "^0.54.2" + } +} diff --git a/node_modules/@isaacs/cliui/node_modules/ansi-regex/readme.md b/node_modules/@isaacs/cliui/node_modules/ansi-regex/readme.md new file mode 100644 index 0000000..4d3c415 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/ansi-regex/readme.md @@ -0,0 +1,66 @@ +# ansi-regex + +> Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) + +## Install + +```sh +npm install ansi-regex +``` + +## Usage + +```js +import ansiRegex from 'ansi-regex'; + +ansiRegex().test('\u001B[4mcake\u001B[0m'); +//=> true + +ansiRegex().test('cake'); +//=> false + +'\u001B[4mcake\u001B[0m'.match(ansiRegex()); +//=> ['\u001B[4m', '\u001B[0m'] + +'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); +//=> ['\u001B[4m'] + +'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); +//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] +``` + +## API + +### ansiRegex(options?) + +Returns a regex for matching ANSI escape codes. + +#### options + +Type: `object` + +##### onlyFirst + +Type: `boolean`\ +Default: `false` *(Matches any ANSI escape codes in a string)* + +Match only the first ANSI escape. + +## Important + +If you run the regex against untrusted user input in a server context, you should [give it a timeout](https://github.com/sindresorhus/super-regex). + +**I do not consider [ReDoS](https://blog.yossarian.net/2022/12/28/ReDoS-vulnerabilities-and-misaligned-incentives) a valid vulnerability for this package.** + +## FAQ + +### Why do you test for codes not in the ECMA 48 standard? + +Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. + +On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) diff --git a/node_modules/@isaacs/cliui/node_modules/ansi-styles/index.d.ts b/node_modules/@isaacs/cliui/node_modules/ansi-styles/index.d.ts new file mode 100644 index 0000000..ee8bc27 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/ansi-styles/index.d.ts @@ -0,0 +1,236 @@ +export type CSPair = { // eslint-disable-line @typescript-eslint/naming-convention + /** + The ANSI terminal control sequence for starting this style. + */ + readonly open: string; + + /** + The ANSI terminal control sequence for ending this style. + */ + readonly close: string; +}; + +export type ColorBase = { + /** + The ANSI terminal control sequence for ending this color. + */ + readonly close: string; + + ansi(code: number): string; + + ansi256(code: number): string; + + ansi16m(red: number, green: number, blue: number): string; +}; + +export type Modifier = { + /** + Resets the current color chain. + */ + readonly reset: CSPair; + + /** + Make text bold. + */ + readonly bold: CSPair; + + /** + Emitting only a small amount of light. + */ + readonly dim: CSPair; + + /** + Make text italic. (Not widely supported) + */ + readonly italic: CSPair; + + /** + Make text underline. (Not widely supported) + */ + readonly underline: CSPair; + + /** + Make text overline. + + Supported on VTE-based terminals, the GNOME terminal, mintty, and Git Bash. + */ + readonly overline: CSPair; + + /** + Inverse background and foreground colors. + */ + readonly inverse: CSPair; + + /** + Prints the text, but makes it invisible. + */ + readonly hidden: CSPair; + + /** + Puts a horizontal line through the center of the text. (Not widely supported) + */ + readonly strikethrough: CSPair; +}; + +export type ForegroundColor = { + readonly black: CSPair; + readonly red: CSPair; + readonly green: CSPair; + readonly yellow: CSPair; + readonly blue: CSPair; + readonly cyan: CSPair; + readonly magenta: CSPair; + readonly white: CSPair; + + /** + Alias for `blackBright`. + */ + readonly gray: CSPair; + + /** + Alias for `blackBright`. + */ + readonly grey: CSPair; + + readonly blackBright: CSPair; + readonly redBright: CSPair; + readonly greenBright: CSPair; + readonly yellowBright: CSPair; + readonly blueBright: CSPair; + readonly cyanBright: CSPair; + readonly magentaBright: CSPair; + readonly whiteBright: CSPair; +}; + +export type BackgroundColor = { + readonly bgBlack: CSPair; + readonly bgRed: CSPair; + readonly bgGreen: CSPair; + readonly bgYellow: CSPair; + readonly bgBlue: CSPair; + readonly bgCyan: CSPair; + readonly bgMagenta: CSPair; + readonly bgWhite: CSPair; + + /** + Alias for `bgBlackBright`. + */ + readonly bgGray: CSPair; + + /** + Alias for `bgBlackBright`. + */ + readonly bgGrey: CSPair; + + readonly bgBlackBright: CSPair; + readonly bgRedBright: CSPair; + readonly bgGreenBright: CSPair; + readonly bgYellowBright: CSPair; + readonly bgBlueBright: CSPair; + readonly bgCyanBright: CSPair; + readonly bgMagentaBright: CSPair; + readonly bgWhiteBright: CSPair; +}; + +export type ConvertColor = { + /** + Convert from the RGB color space to the ANSI 256 color space. + + @param red - (`0...255`) + @param green - (`0...255`) + @param blue - (`0...255`) + */ + rgbToAnsi256(red: number, green: number, blue: number): number; + + /** + Convert from the RGB HEX color space to the RGB color space. + + @param hex - A hexadecimal string containing RGB data. + */ + hexToRgb(hex: string): [red: number, green: number, blue: number]; + + /** + Convert from the RGB HEX color space to the ANSI 256 color space. + + @param hex - A hexadecimal string containing RGB data. + */ + hexToAnsi256(hex: string): number; + + /** + Convert from the ANSI 256 color space to the ANSI 16 color space. + + @param code - A number representing the ANSI 256 color. + */ + ansi256ToAnsi(code: number): number; + + /** + Convert from the RGB color space to the ANSI 16 color space. + + @param red - (`0...255`) + @param green - (`0...255`) + @param blue - (`0...255`) + */ + rgbToAnsi(red: number, green: number, blue: number): number; + + /** + Convert from the RGB HEX color space to the ANSI 16 color space. + + @param hex - A hexadecimal string containing RGB data. + */ + hexToAnsi(hex: string): number; +}; + +/** +Basic modifier names. +*/ +export type ModifierName = keyof Modifier; + +/** +Basic foreground color names. + +[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) +*/ +export type ForegroundColorName = keyof ForegroundColor; + +/** +Basic background color names. + +[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) +*/ +export type BackgroundColorName = keyof BackgroundColor; + +/** +Basic color names. The combination of foreground and background color names. + +[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support) +*/ +export type ColorName = ForegroundColorName | BackgroundColorName; + +/** +Basic modifier names. +*/ +export const modifierNames: readonly ModifierName[]; + +/** +Basic foreground color names. +*/ +export const foregroundColorNames: readonly ForegroundColorName[]; + +/** +Basic background color names. +*/ +export const backgroundColorNames: readonly BackgroundColorName[]; + +/* +Basic color names. The combination of foreground and background color names. +*/ +export const colorNames: readonly ColorName[]; + +declare const ansiStyles: { + readonly modifier: Modifier; + readonly color: ColorBase & ForegroundColor; + readonly bgColor: ColorBase & BackgroundColor; + readonly codes: ReadonlyMap; +} & ForegroundColor & BackgroundColor & Modifier & ConvertColor; + +export default ansiStyles; diff --git a/node_modules/@isaacs/cliui/node_modules/ansi-styles/index.js b/node_modules/@isaacs/cliui/node_modules/ansi-styles/index.js new file mode 100644 index 0000000..eaa7bed --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/ansi-styles/index.js @@ -0,0 +1,223 @@ +const ANSI_BACKGROUND_OFFSET = 10; + +const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`; + +const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; + +const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; + +const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + overline: [53, 55], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + // Bright color + blackBright: [90, 39], + gray: [90, 39], // Alias of `blackBright` + grey: [90, 39], // Alias of `blackBright` + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39], + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgGray: [100, 49], // Alias of `bgBlackBright` + bgGrey: [100, 49], // Alias of `bgBlackBright` + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49], + }, +}; + +export const modifierNames = Object.keys(styles.modifier); +export const foregroundColorNames = Object.keys(styles.color); +export const backgroundColorNames = Object.keys(styles.bgColor); +export const colorNames = [...foregroundColorNames, ...backgroundColorNames]; + +function assembleStyles() { + const codes = new Map(); + + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m`, + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false, + }); + } + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false, + }); + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = wrapAnsi16(); + styles.color.ansi256 = wrapAnsi256(); + styles.color.ansi16m = wrapAnsi16m(); + styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); + styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); + styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); + + // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js + Object.defineProperties(styles, { + rgbToAnsi256: { + value(red, green, blue) { + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (red === green && green === blue) { + if (red < 8) { + return 16; + } + + if (red > 248) { + return 231; + } + + return Math.round(((red - 8) / 247) * 24) + 232; + } + + return 16 + + (36 * Math.round(red / 255 * 5)) + + (6 * Math.round(green / 255 * 5)) + + Math.round(blue / 255 * 5); + }, + enumerable: false, + }, + hexToRgb: { + value(hex) { + const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); + if (!matches) { + return [0, 0, 0]; + } + + let [colorString] = matches; + + if (colorString.length === 3) { + colorString = [...colorString].map(character => character + character).join(''); + } + + const integer = Number.parseInt(colorString, 16); + + return [ + /* eslint-disable no-bitwise */ + (integer >> 16) & 0xFF, + (integer >> 8) & 0xFF, + integer & 0xFF, + /* eslint-enable no-bitwise */ + ]; + }, + enumerable: false, + }, + hexToAnsi256: { + value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), + enumerable: false, + }, + ansi256ToAnsi: { + value(code) { + if (code < 8) { + return 30 + code; + } + + if (code < 16) { + return 90 + (code - 8); + } + + let red; + let green; + let blue; + + if (code >= 232) { + red = (((code - 232) * 10) + 8) / 255; + green = red; + blue = red; + } else { + code -= 16; + + const remainder = code % 36; + + red = Math.floor(code / 36) / 5; + green = Math.floor(remainder / 6) / 5; + blue = (remainder % 6) / 5; + } + + const value = Math.max(red, green, blue) * 2; + + if (value === 0) { + return 30; + } + + // eslint-disable-next-line no-bitwise + let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); + + if (value === 2) { + result += 60; + } + + return result; + }, + enumerable: false, + }, + rgbToAnsi: { + value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), + enumerable: false, + }, + hexToAnsi: { + value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), + enumerable: false, + }, + }); + + return styles; +} + +const ansiStyles = assembleStyles(); + +export default ansiStyles; diff --git a/node_modules/@isaacs/cliui/node_modules/ansi-styles/license b/node_modules/@isaacs/cliui/node_modules/ansi-styles/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/ansi-styles/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@isaacs/cliui/node_modules/ansi-styles/package.json b/node_modules/@isaacs/cliui/node_modules/ansi-styles/package.json new file mode 100644 index 0000000..16b508f --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/ansi-styles/package.json @@ -0,0 +1,54 @@ +{ + "name": "ansi-styles", + "version": "6.2.3", + "description": "ANSI escape codes for styling strings in the terminal", + "license": "MIT", + "repository": "chalk/ansi-styles", + "funding": "https://github.com/chalk/ansi-styles?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": "./index.js", + "engines": { + "node": ">=12" + }, + "scripts": { + "test": "xo && ava && tsd", + "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "devDependencies": { + "ava": "^6.1.3", + "svg-term-cli": "^2.1.1", + "tsd": "^0.31.1", + "xo": "^0.58.0" + } +} diff --git a/node_modules/@isaacs/cliui/node_modules/ansi-styles/readme.md b/node_modules/@isaacs/cliui/node_modules/ansi-styles/readme.md new file mode 100644 index 0000000..6d04183 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/ansi-styles/readme.md @@ -0,0 +1,173 @@ +# ansi-styles + +> [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal + +You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. + +![](screenshot.png) + +## Install + +```sh +npm install ansi-styles +``` + +## Usage + +```js +import styles from 'ansi-styles'; + +console.log(`${styles.green.open}Hello world!${styles.green.close}`); + + +// Color conversion between 256/truecolor +// NOTE: When converting from truecolor to 256 colors, the original color +// may be degraded to fit the new color palette. This means terminals +// that do not support 16 million colors will best-match the +// original color. +console.log(`${styles.color.ansi(styles.rgbToAnsi(199, 20, 250))}Hello World${styles.color.close}`) +console.log(`${styles.color.ansi256(styles.rgbToAnsi256(199, 20, 250))}Hello World${styles.color.close}`) +console.log(`${styles.color.ansi16m(...styles.hexToRgb('#abcdef'))}Hello World${styles.color.close}`) +``` + +## API + +### `open` and `close` + +Each style has an `open` and `close` property. + +### `modifierNames`, `foregroundColorNames`, `backgroundColorNames`, and `colorNames` + +All supported style strings are exposed as an array of strings for convenience. `colorNames` is the combination of `foregroundColorNames` and `backgroundColorNames`. + +This can be useful if you need to validate input: + +```js +import {modifierNames, foregroundColorNames} from 'ansi-styles'; + +console.log(modifierNames.includes('bold')); +//=> true + +console.log(foregroundColorNames.includes('pink')); +//=> false +``` + +## Styles + +### Modifiers + +- `reset` +- `bold` +- `dim` +- `italic` *(Not widely supported)* +- `underline` +- `overline` *Supported on VTE-based terminals, the GNOME terminal, mintty, and Git Bash.* +- `inverse` +- `hidden` +- `strikethrough` *(Not widely supported)* + +### Colors + +- `black` +- `red` +- `green` +- `yellow` +- `blue` +- `magenta` +- `cyan` +- `white` +- `blackBright` (alias: `gray`, `grey`) +- `redBright` +- `greenBright` +- `yellowBright` +- `blueBright` +- `magentaBright` +- `cyanBright` +- `whiteBright` + +### Background colors + +- `bgBlack` +- `bgRed` +- `bgGreen` +- `bgYellow` +- `bgBlue` +- `bgMagenta` +- `bgCyan` +- `bgWhite` +- `bgBlackBright` (alias: `bgGray`, `bgGrey`) +- `bgRedBright` +- `bgGreenBright` +- `bgYellowBright` +- `bgBlueBright` +- `bgMagentaBright` +- `bgCyanBright` +- `bgWhiteBright` + +## Advanced usage + +By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. + +- `styles.modifier` +- `styles.color` +- `styles.bgColor` + +###### Example + +```js +import styles from 'ansi-styles'; + +console.log(styles.color.green.open); +``` + +Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `styles.codes`, which returns a `Map` with the open codes as keys and close codes as values. + +###### Example + +```js +import styles from 'ansi-styles'; + +console.log(styles.codes.get(36)); +//=> 39 +``` + +## 16 / 256 / 16 million (TrueColor) support + +`ansi-styles` allows converting between various color formats and ANSI escapes, with support for 16, 256 and [16 million colors](https://gist.github.com/XVilka/8346728). + +The following color spaces are supported: + +- `rgb` +- `hex` +- `ansi256` +- `ansi` + +To use these, call the associated conversion function with the intended output, for example: + +```js +import styles from 'ansi-styles'; + +styles.color.ansi(styles.rgbToAnsi(100, 200, 15)); // RGB to 16 color ansi foreground code +styles.bgColor.ansi(styles.hexToAnsi('#C0FFEE')); // HEX to 16 color ansi foreground code + +styles.color.ansi256(styles.rgbToAnsi256(100, 200, 15)); // RGB to 256 color ansi foreground code +styles.bgColor.ansi256(styles.hexToAnsi256('#C0FFEE')); // HEX to 256 color ansi foreground code + +styles.color.ansi16m(100, 200, 15); // RGB to 16 million color foreground code +styles.bgColor.ansi16m(...styles.hexToRgb('#C0FFEE')); // Hex (RGB) to 16 million color foreground code +``` + +## Related + +- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + +## For enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of `ansi-styles` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-ansi-styles?utm_source=npm-ansi-styles&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/LICENSE-MIT.txt b/node_modules/@isaacs/cliui/node_modules/emoji-regex/LICENSE-MIT.txt new file mode 100644 index 0000000..a41e0a7 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/emoji-regex/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/README.md b/node_modules/@isaacs/cliui/node_modules/emoji-regex/README.md new file mode 100644 index 0000000..6d63082 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/emoji-regex/README.md @@ -0,0 +1,137 @@ +# emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=main)](https://travis-ci.org/mathiasbynens/emoji-regex) + +_emoji-regex_ offers a regular expression to match all emoji symbols and sequences (including textual representations of emoji) as per the Unicode Standard. + +This repository contains a script that generates this regular expression based on [Unicode data](https://github.com/node-unicode/node-unicode-data). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. + +## Installation + +Via [npm](https://www.npmjs.com/): + +```bash +npm install emoji-regex +``` + +In [Node.js](https://nodejs.org/): + +```js +const emojiRegex = require('emoji-regex/RGI_Emoji.js'); +// Note: because the regular expression has the global flag set, this module +// exports a function that returns the regex rather than exporting the regular +// expression itself, to make it impossible to (accidentally) mutate the +// original regular expression. + +const text = ` +\u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) +\u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji +\u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) +\u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier +`; + +const regex = emojiRegex(); +let match; +while (match = regex.exec(text)) { + const emoji = match[0]; + console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); +} +``` + +Console output: + +``` +Matched sequence ⌚ — code points: 1 +Matched sequence ⌚ — code points: 1 +Matched sequence ↔️ — code points: 2 +Matched sequence ↔️ — code points: 2 +Matched sequence 👩 — code points: 1 +Matched sequence 👩 — code points: 1 +Matched sequence 👩🏿 — code points: 2 +Matched sequence 👩🏿 — code points: 2 +``` + +## Regular expression flavors + +The package comes with three distinct regular expressions: + +```js +// This is the recommended regular expression to use. It matches all +// emoji recommended for general interchange, as defined via the +// `RGI_Emoji` property in the Unicode Standard. +// https://unicode.org/reports/tr51/#def_rgi_set +// When in doubt, use this! +const emojiRegexRGI = require('emoji-regex/RGI_Emoji.js'); + +// This is the old regular expression, prior to `RGI_Emoji` being +// standardized. In addition to all `RGI_Emoji` sequences, it matches +// some emoji you probably don’t want to match (such as emoji component +// symbols that are not meant to be used separately). +const emojiRegex = require('emoji-regex/index.js'); + +// This regular expression matches even more emoji than the previous +// one, including emoji that render as text instead of icons (i.e. +// emoji that are not `Emoji_Presentation` symbols and that aren’t +// forced to render as emoji by a variation selector). +const emojiRegexText = require('emoji-regex/text.js'); +``` + +Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: + +```js +const emojiRegexRGI = require('emoji-regex/es2015/RGI_Emoji.js'); +const emojiRegex = require('emoji-regex/es2015/index.js'); +const emojiRegexText = require('emoji-regex/es2015/text.js'); +``` + +## For maintainers + +### How to update emoji-regex after new Unicode Standard releases + +1. Update the Unicode data dependency in `package.json` by running the following commands: + + ```sh + # Example: updating from Unicode v12 to Unicode v13. + npm uninstall @unicode/unicode-12.0.0 + npm install @unicode/unicode-13.0.0 --save-dev + ```` + +1. Generate the new output: + + ```sh + npm run build + ``` + +1. Verify that tests still pass: + + ```sh + npm test + ``` + +1. Send a pull request with the changes, and get it reviewed & merged. + +1. On the `main` branch, bump the emoji-regex version number in `package.json`: + + ```sh + npm version patch -m 'Release v%s' + ``` + + Instead of `patch`, use `minor` or `major` [as needed](https://semver.org/). + + Note that this produces a Git commit + tag. + +1. Push the release commit and tag: + + ```sh + git push + ``` + + Our CI then automatically publishes the new release to npm. + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## License + +_emoji-regex_ is available under the [MIT](https://mths.be/mit) license. diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/RGI_Emoji.d.ts b/node_modules/@isaacs/cliui/node_modules/emoji-regex/RGI_Emoji.d.ts new file mode 100644 index 0000000..89a651f --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/emoji-regex/RGI_Emoji.d.ts @@ -0,0 +1,5 @@ +declare module 'emoji-regex/RGI_Emoji' { + function emojiRegex(): RegExp; + + export = emojiRegex; +} diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/RGI_Emoji.js b/node_modules/@isaacs/cliui/node_modules/emoji-regex/RGI_Emoji.js new file mode 100644 index 0000000..3fbe924 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/emoji-regex/RGI_Emoji.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?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BB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB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?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]/g; +}; diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/RGI_Emoji.d.ts b/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/RGI_Emoji.d.ts new file mode 100644 index 0000000..bf0f154 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/RGI_Emoji.d.ts @@ -0,0 +1,5 @@ +declare module 'emoji-regex/es2015/RGI_Emoji' { + function emojiRegex(): RegExp; + + export = emojiRegex; +} diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/RGI_Emoji.js b/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/RGI_Emoji.js new file mode 100644 index 0000000..ecf32f1 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/RGI_Emoji.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = () => { + // https://mths.be/emoji + return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0077}\u{E006C}\u{E0073}|\u{E0073}\u{E0063}\u{E0074}|\u{E0065}\u{E006E}\u{E0067})\u{E007F}|(?:\u{1F9D1}\u{1F3FF}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FE}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FD}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FB}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FC}-\u{1F3FF}]|\u{1F468}(?:\u{1F3FB}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]))?|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u{1F466}\u{1F467}])|\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC})?|(?:\u{1F469}(?:\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}]))|\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]\u200D\u{1F91D}\u200D\u{1F9D1})[\u{1F3FB}-\u{1F3FF}]|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F469}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FE}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FD}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4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{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FC}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F9D1}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F636}\u200D\u{1F32B}|\u{1F3F3}\uFE0F\u200D\u26A7|\u{1F43B}\u200D\u2744|(?:[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u{1F3F4}\u200D\u2620|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F202}\u{1F237}\u{1F321}\u{1F324}-\u{1F32C}\u{1F336}\u{1F37D}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}\u{1F39F}\u{1F3CD}\u{1F3CE}\u{1F3D4}-\u{1F3DF}\u{1F3F5}\u{1F3F7}\u{1F43F}\u{1F4FD}\u{1F549}\u{1F54A}\u{1F56F}\u{1F570}\u{1F573}\u{1F576}-\u{1F579}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}\u{1F6CB}\u{1F6CD}-\u{1F6CF}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6F0}\u{1F6F3}])\uFE0F|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F469}\u200D\u{1F467}|\u{1F469}\u200D\u{1F466}|\u{1F635}\u200D\u{1F4AB}|\u{1F62E}\u200D\u{1F4A8}|\u{1F415}\u200D\u{1F9BA}|\u{1F9D1}(?:\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC}|\u{1F3FB})?|\u{1F469}(?:\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC}|\u{1F3FB})?|\u{1F1FD}\u{1F1F0}|\u{1F1F6}\u{1F1E6}|\u{1F1F4}\u{1F1F2}|\u{1F408}\u200D\u2B1B|\u2764\uFE0F\u200D[\u{1F525}\u{1FA79}]|\u{1F441}\uFE0F|\u{1F3F3}\uFE0F|\u{1F1FF}[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F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]|\u{1F3F4}|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270C\u270D\u{1F574}\u{1F590}][\uFE0F\u{1F3FB}-\u{1F3FF}]|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F408}\u{1F415}\u{1F43B}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F62E}\u{1F635}\u{1F636}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F384}\u{1F386}-\u{1F393}\u{1F3A0}-\u{1F3C1}\u{1F3C5}\u{1F3C6}\u{1F3C8}\u{1F3C9}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F8}-\u{1F407}\u{1F409}-\u{1F414}\u{1F416}-\u{1F43A}\u{1F43C}-\u{1F43E}\u{1F440}\u{1F444}\u{1F445}\u{1F451}-\u{1F465}\u{1F46A}\u{1F479}-\u{1F47B}\u{1F47D}-\u{1F480}\u{1F484}\u{1F488}-\u{1F48E}\u{1F490}\u{1F492}-\u{1F4A9}\u{1F4AB}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F5A4}\u{1F5FB}-\u{1F62D}\u{1F62F}-\u{1F634}\u{1F637}-\u{1F644}\u{1F648}-\u{1F64A}\u{1F680}-\u{1F6A2}\u{1F6A4}-\u{1F6B3}\u{1F6B7}-\u{1F6BF}\u{1F6C1}-\u{1F6C5}\u{1F6D0}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90D}\u{1F90E}\u{1F910}-\u{1F917}\u{1F91D}\u{1F920}-\u{1F925}\u{1F927}-\u{1F92F}\u{1F93A}\u{1F93F}-\u{1F945}\u{1F947}-\u{1F976}\u{1F978}\u{1F97A}-\u{1F9B4}\u{1F9B7}\u{1F9BA}\u{1F9BC}-\u{1F9CB}\u{1F9D0}\u{1F9E0}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]/gu; +}; diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/index.d.ts b/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/index.d.ts new file mode 100644 index 0000000..823dfa6 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/index.d.ts @@ -0,0 +1,5 @@ +declare module 'emoji-regex/es2015' { + function emojiRegex(): RegExp; + + export = emojiRegex; +} diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/index.js b/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/index.js new file mode 100644 index 0000000..1a4fc8d --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/index.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = () => { + // https://mths.be/emoji + return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0077}\u{E006C}\u{E0073}|\u{E0073}\u{E0063}\u{E0074}|\u{E0065}\u{E006E}\u{E0067})\u{E007F}|(?:\u{1F9D1}\u{1F3FF}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FE}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FD}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FB}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FC}-\u{1F3FF}]|\u{1F468}(?:\u{1F3FB}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]))?|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u{1F466}\u{1F467}])|\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC})?|(?:\u{1F469}(?:\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}]))|\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]\u200D\u{1F91D}\u200D\u{1F9D1})[\u{1F3FB}-\u{1F3FF}]|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F469}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u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{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FE}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FD}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FC}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F9D1}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F636}\u200D\u{1F32B}|\u{1F3F3}\uFE0F\u200D\u26A7|\u{1F43B}\u200D\u2744|(?:[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u{1F3F4}\u200D\u2620|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F202}\u{1F237}\u{1F321}\u{1F324}-\u{1F32C}\u{1F336}\u{1F37D}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}\u{1F39F}\u{1F3CD}\u{1F3CE}\u{1F3D4}-\u{1F3DF}\u{1F3F5}\u{1F3F7}\u{1F43F}\u{1F4FD}\u{1F549}\u{1F54A}\u{1F56F}\u{1F570}\u{1F573}\u{1F576}-\u{1F579}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F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|[\u261D\u270C\u270D\u{1F574}\u{1F590}][\uFE0F\u{1F3FB}-\u{1F3FF}]|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F408}\u{1F415}\u{1F43B}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F62E}\u{1F635}\u{1F636}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F384}\u{1F386}-\u{1F393}\u{1F3A0}-\u{1F3C1}\u{1F3C5}\u{1F3C6}\u{1F3C8}\u{1F3C9}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F8}-\u{1F407}\u{1F409}-\u{1F414}\u{1F416}-\u{1F43A}\u{1F43C}-\u{1F43E}\u{1F440}\u{1F444}\u{1F445}\u{1F451}-\u{1F465}\u{1F46A}\u{1F479}-\u{1F47B}\u{1F47D}-\u{1F480}\u{1F484}\u{1F488}-\u{1F48E}\u{1F490}\u{1F492}-\u{1F4A9}\u{1F4AB}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F5A4}\u{1F5FB}-\u{1F62D}\u{1F62F}-\u{1F634}\u{1F637}-\u{1F644}\u{1F648}-\u{1F64A}\u{1F680}-\u{1F6A2}\u{1F6A4}-\u{1F6B3}\u{1F6B7}-\u{1F6BF}\u{1F6C1}-\u{1F6C5}\u{1F6D0}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90D}\u{1F90E}\u{1F910}-\u{1F917}\u{1F91D}\u{1F920}-\u{1F925}\u{1F927}-\u{1F92F}\u{1F93A}\u{1F93F}-\u{1F945}\u{1F947}-\u{1F976}\u{1F978}\u{1F97A}-\u{1F9B4}\u{1F9B7}\u{1F9BA}\u{1F9BC}-\u{1F9CB}\u{1F9D0}\u{1F9E0}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90C}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F978}\u{1F97A}-\u{1F9CB}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90C}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F978}\u{1F97A}-\u{1F9CB}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]\uFE0F|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; +}; diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/text.d.ts b/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/text.d.ts new file mode 100644 index 0000000..ccc2f9a --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/text.d.ts @@ -0,0 +1,5 @@ +declare module 'emoji-regex/es2015/text' { + function emojiRegex(): RegExp; + + export = emojiRegex; +} diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/text.js b/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/text.js new file mode 100644 index 0000000..8e9f985 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/emoji-regex/es2015/text.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = () => { + // https://mths.be/emoji + return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0077}\u{E006C}\u{E0073}|\u{E0073}\u{E0063}\u{E0074}|\u{E0065}\u{E006E}\u{E0067})\u{E007F}|(?:\u{1F9D1}\u{1F3FF}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FE}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FD}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FB}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FC}-\u{1F3FF}]|\u{1F468}(?:\u{1F3FB}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]))?|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u{1F466}\u{1F467}])|\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC})?|(?:\u{1F469}(?:\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}]))|\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]\u200D\u{1F91D}\u200D\u{1F9D1})[\u{1F3FB}-\u{1F3FF}]|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F469}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FE}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FD}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FC}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1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u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F9D1}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F636}\u200D\u{1F32B}|\u{1F3F3}\uFE0F\u200D\u26A7|\u{1F43B}\u200D\u2744|(?:[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u{1F3F4}\u200D\u2620|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F202}\u{1F237}\u{1F321}\u{1F324}-\u{1F32C}\u{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1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270C\u270D\u{1F574}\u{1F590}][\uFE0F\u{1F3FB}-\u{1F3FF}]|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F408}\u{1F415}\u{1F43B}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F62E}\u{1F635}\u{1F636}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F384}\u{1F386}-\u{1F393}\u{1F3A0}-\u{1F3C1}\u{1F3C5}\u{1F3C6}\u{1F3C8}\u{1F3C9}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F8}-\u{1F407}\u{1F409}-\u{1F414}\u{1F416}-\u{1F43A}\u{1F43C}-\u{1F43E}\u{1F440}\u{1F444}\u{1F445}\u{1F451}-\u{1F465}\u{1F46A}\u{1F479}-\u{1F47B}\u{1F47D}-\u{1F480}\u{1F484}\u{1F488}-\u{1F48E}\u{1F490}\u{1F492}-\u{1F4A9}\u{1F4AB}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F5A4}\u{1F5FB}-\u{1F62D}\u{1F62F}-\u{1F634}\u{1F637}-\u{1F644}\u{1F648}-\u{1F64A}\u{1F680}-\u{1F6A2}\u{1F6A4}-\u{1F6B3}\u{1F6B7}-\u{1F6BF}\u{1F6C1}-\u{1F6C5}\u{1F6D0}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90D}\u{1F90E}\u{1F910}-\u{1F917}\u{1F91D}\u{1F920}-\u{1F925}\u{1F927}-\u{1F92F}\u{1F93A}\u{1F93F}-\u{1F945}\u{1F947}-\u{1F976}\u{1F978}\u{1F97A}-\u{1F9B4}\u{1F9B7}\u{1F9BA}\u{1F9BC}-\u{1F9CB}\u{1F9D0}\u{1F9E0}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90C}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F978}\u{1F97A}-\u{1F9CB}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]\uFE0F?/gu; +}; diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/index.d.ts b/node_modules/@isaacs/cliui/node_modules/emoji-regex/index.d.ts new file mode 100644 index 0000000..8f235c9 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/emoji-regex/index.d.ts @@ -0,0 +1,5 @@ +declare module 'emoji-regex' { + function emojiRegex(): RegExp; + + export = emojiRegex; +} diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/index.js b/node_modules/@isaacs/cliui/node_modules/emoji-regex/index.js new file mode 100644 index 0000000..c0490d4 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/emoji-regex/index.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF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\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\u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uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/package.json b/node_modules/@isaacs/cliui/node_modules/emoji-regex/package.json new file mode 100644 index 0000000..eac892a --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/emoji-regex/package.json @@ -0,0 +1,52 @@ +{ + "name": "emoji-regex", + "version": "9.2.2", + "description": "A regular expression to match all Emoji-only symbols as per the Unicode Standard.", + "homepage": "https://mths.be/emoji-regex", + "main": "index.js", + "types": "index.d.ts", + "keywords": [ + "unicode", + "regex", + "regexp", + "regular expressions", + "code points", + "symbols", + "characters", + "emoji" + ], + "license": "MIT", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "repository": { + "type": "git", + "url": "https://github.com/mathiasbynens/emoji-regex.git" + }, + "bugs": "https://github.com/mathiasbynens/emoji-regex/issues", + "files": [ + "LICENSE-MIT.txt", + "index.js", + "index.d.ts", + "RGI_Emoji.js", + "RGI_Emoji.d.ts", + "text.js", + "text.d.ts", + "es2015" + ], + "scripts": { + "build": "rm -rf -- es2015; babel src -d .; NODE_ENV=es2015 babel src es2015_types -D -d ./es2015; node script/inject-sequences.js", + "test": "mocha", + "test:watch": "npm run test -- --watch" + }, + "devDependencies": { + "@babel/cli": "^7.4.4", + "@babel/core": "^7.4.4", + "@babel/plugin-proposal-unicode-property-regex": "^7.4.4", + "@babel/preset-env": "^7.4.4", + "@unicode/unicode-13.0.0": "^1.0.3", + "mocha": "^6.1.4", + "regexgen": "^1.3.0" + } +} diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/text.d.ts b/node_modules/@isaacs/cliui/node_modules/emoji-regex/text.d.ts new file mode 100644 index 0000000..c3a0125 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/emoji-regex/text.d.ts @@ -0,0 +1,5 @@ +declare module 'emoji-regex/text' { + function emojiRegex(): RegExp; + + export = emojiRegex; +} diff --git a/node_modules/@isaacs/cliui/node_modules/emoji-regex/text.js b/node_modules/@isaacs/cliui/node_modules/emoji-regex/text.js new file mode 100644 index 0000000..9bc63ce --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/emoji-regex/text.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\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\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD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83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F?/g; +}; diff --git a/node_modules/@isaacs/cliui/node_modules/string-width/index.d.ts b/node_modules/@isaacs/cliui/node_modules/string-width/index.d.ts new file mode 100644 index 0000000..aed9fdf --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/string-width/index.d.ts @@ -0,0 +1,29 @@ +export interface Options { + /** + Count [ambiguous width characters](https://www.unicode.org/reports/tr11/#Ambiguous) as having narrow width (count of 1) instead of wide width (count of 2). + + @default true + */ + readonly ambiguousIsNarrow: boolean; +} + +/** +Get the visual width of a string - the number of columns required to display it. + +Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + +@example +``` +import stringWidth from 'string-width'; + +stringWidth('a'); +//=> 1 + +stringWidth('古'); +//=> 2 + +stringWidth('\u001B[1m古\u001B[22m'); +//=> 2 +``` +*/ +export default function stringWidth(string: string, options?: Options): number; diff --git a/node_modules/@isaacs/cliui/node_modules/string-width/index.js b/node_modules/@isaacs/cliui/node_modules/string-width/index.js new file mode 100644 index 0000000..9294488 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/string-width/index.js @@ -0,0 +1,54 @@ +import stripAnsi from 'strip-ansi'; +import eastAsianWidth from 'eastasianwidth'; +import emojiRegex from 'emoji-regex'; + +export default function stringWidth(string, options = {}) { + if (typeof string !== 'string' || string.length === 0) { + return 0; + } + + options = { + ambiguousIsNarrow: true, + ...options + }; + + string = stripAnsi(string); + + if (string.length === 0) { + return 0; + } + + string = string.replace(emojiRegex(), ' '); + + const ambiguousCharacterWidth = options.ambiguousIsNarrow ? 1 : 2; + let width = 0; + + for (const character of string) { + const codePoint = character.codePointAt(0); + + // Ignore control characters + if (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) { + continue; + } + + // Ignore combining characters + if (codePoint >= 0x300 && codePoint <= 0x36F) { + continue; + } + + const code = eastAsianWidth.eastAsianWidth(character); + switch (code) { + case 'F': + case 'W': + width += 2; + break; + case 'A': + width += ambiguousCharacterWidth; + break; + default: + width += 1; + } + } + + return width; +} diff --git a/node_modules/@isaacs/cliui/node_modules/string-width/license b/node_modules/@isaacs/cliui/node_modules/string-width/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/string-width/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@isaacs/cliui/node_modules/string-width/package.json b/node_modules/@isaacs/cliui/node_modules/string-width/package.json new file mode 100644 index 0000000..f46d677 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/string-width/package.json @@ -0,0 +1,59 @@ +{ + "name": "string-width", + "version": "5.1.2", + "description": "Get the visual width of a string - the number of columns required to display it", + "license": "MIT", + "repository": "sindresorhus/string-width", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": "./index.js", + "engines": { + "node": ">=12" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "string", + "character", + "unicode", + "width", + "visual", + "column", + "columns", + "fullwidth", + "full-width", + "full", + "ansi", + "escape", + "codes", + "cli", + "command-line", + "terminal", + "console", + "cjk", + "chinese", + "japanese", + "korean", + "fixed-width" + ], + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "devDependencies": { + "ava": "^3.15.0", + "tsd": "^0.14.0", + "xo": "^0.38.2" + } +} diff --git a/node_modules/@isaacs/cliui/node_modules/string-width/readme.md b/node_modules/@isaacs/cliui/node_modules/string-width/readme.md new file mode 100644 index 0000000..52910df --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/string-width/readme.md @@ -0,0 +1,67 @@ +# string-width + +> Get the visual width of a string - the number of columns required to display it + +Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + +Useful to be able to measure the actual width of command-line output. + +## Install + +``` +$ npm install string-width +``` + +## Usage + +```js +import stringWidth from 'string-width'; + +stringWidth('a'); +//=> 1 + +stringWidth('古'); +//=> 2 + +stringWidth('\u001B[1m古\u001B[22m'); +//=> 2 +``` + +## API + +### stringWidth(string, options?) + +#### string + +Type: `string` + +The string to be counted. + +#### options + +Type: `object` + +##### ambiguousIsNarrow + +Type: `boolean`\ +Default: `false` + +Count [ambiguous width characters](https://www.unicode.org/reports/tr11/#Ambiguous) as having narrow width (count of 1) instead of wide width (count of 2). + +## Related + +- [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module +- [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string +- [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/@isaacs/cliui/node_modules/strip-ansi/index.d.ts b/node_modules/@isaacs/cliui/node_modules/strip-ansi/index.d.ts new file mode 100644 index 0000000..44e954d --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/strip-ansi/index.d.ts @@ -0,0 +1,15 @@ +/** +Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string. + +@example +``` +import stripAnsi from 'strip-ansi'; + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` +*/ +export default function stripAnsi(string: string): string; diff --git a/node_modules/@isaacs/cliui/node_modules/strip-ansi/index.js b/node_modules/@isaacs/cliui/node_modules/strip-ansi/index.js new file mode 100644 index 0000000..ba19750 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/strip-ansi/index.js @@ -0,0 +1,14 @@ +import ansiRegex from 'ansi-regex'; + +const regex = ansiRegex(); + +export default function stripAnsi(string) { + if (typeof string !== 'string') { + throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``); + } + + // Even though the regex is global, we don't need to reset the `.lastIndex` + // because unlike `.exec()` and `.test()`, `.replace()` does it automatically + // and doing it manually has a performance penalty. + return string.replace(regex, ''); +} diff --git a/node_modules/@isaacs/cliui/node_modules/strip-ansi/license b/node_modules/@isaacs/cliui/node_modules/strip-ansi/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/strip-ansi/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@isaacs/cliui/node_modules/strip-ansi/package.json b/node_modules/@isaacs/cliui/node_modules/strip-ansi/package.json new file mode 100644 index 0000000..2a59216 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/strip-ansi/package.json @@ -0,0 +1,59 @@ +{ + "name": "strip-ansi", + "version": "7.1.2", + "description": "Strip ANSI escape codes from a string", + "license": "MIT", + "repository": "chalk/strip-ansi", + "funding": "https://github.com/chalk/strip-ansi?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": "./index.js", + "types": "./index.d.ts", + "sideEffects": false, + "engines": { + "node": ">=12" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "strip", + "trim", + "remove", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "devDependencies": { + "ava": "^3.15.0", + "tsd": "^0.17.0", + "xo": "^0.44.0" + } +} diff --git a/node_modules/@isaacs/cliui/node_modules/strip-ansi/readme.md b/node_modules/@isaacs/cliui/node_modules/strip-ansi/readme.md new file mode 100644 index 0000000..109b692 --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/strip-ansi/readme.md @@ -0,0 +1,37 @@ +# strip-ansi + +> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string + +> [!NOTE] +> Node.js has this built-in now with [`stripVTControlCharacters`](https://nodejs.org/api/util.html#utilstripvtcontrolcharactersstr). The benefit of this package is consistent behavior across Node.js versions and faster improvements. The Node.js version is actually based on this package. + +## Install + +```sh +npm install strip-ansi +``` + +## Usage + +```js +import stripAnsi from 'strip-ansi'; + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` + +## Related + +- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module +- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module +- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes +- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) diff --git a/node_modules/@isaacs/cliui/node_modules/wrap-ansi/index.d.ts b/node_modules/@isaacs/cliui/node_modules/wrap-ansi/index.d.ts new file mode 100644 index 0000000..95471ca --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/wrap-ansi/index.d.ts @@ -0,0 +1,41 @@ +export type Options = { + /** + By default the wrap is soft, meaning long words may extend past the column width. Setting this to `true` will make it hard wrap at the column width. + + @default false + */ + readonly hard?: boolean; + + /** + By default, an attempt is made to split words at spaces, ensuring that they don't extend past the configured columns. If wordWrap is `false`, each column will instead be completely filled splitting words as necessary. + + @default true + */ + readonly wordWrap?: boolean; + + /** + Whitespace on all lines is removed by default. Set this option to `false` if you don't want to trim. + + @default true + */ + readonly trim?: boolean; +}; + +/** +Wrap words to the specified column width. + +@param string - String with ANSI escape codes. Like one styled by [`chalk`](https://github.com/chalk/chalk). Newline characters will be normalized to `\n`. +@param columns - Number of columns to wrap the text to. + +@example +``` +import chalk from 'chalk'; +import wrapAnsi from 'wrap-ansi'; + +const input = 'The quick brown ' + chalk.red('fox jumped over ') + + 'the lazy ' + chalk.green('dog and then ran away with the unicorn.'); + +console.log(wrapAnsi(input, 20)); +``` +*/ +export default function wrapAnsi(string: string, columns: number, options?: Options): string; diff --git a/node_modules/@isaacs/cliui/node_modules/wrap-ansi/index.js b/node_modules/@isaacs/cliui/node_modules/wrap-ansi/index.js new file mode 100644 index 0000000..d80c74c --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/wrap-ansi/index.js @@ -0,0 +1,214 @@ +import stringWidth from 'string-width'; +import stripAnsi from 'strip-ansi'; +import ansiStyles from 'ansi-styles'; + +const ESCAPES = new Set([ + '\u001B', + '\u009B', +]); + +const END_CODE = 39; +const ANSI_ESCAPE_BELL = '\u0007'; +const ANSI_CSI = '['; +const ANSI_OSC = ']'; +const ANSI_SGR_TERMINATOR = 'm'; +const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; + +const wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; +const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`; + +// Calculate the length of words split on ' ', ignoring +// the extra characters added by ansi escape codes +const wordLengths = string => string.split(' ').map(character => stringWidth(character)); + +// Wrap a long word across multiple rows +// Ansi escape codes do not count towards length +const wrapWord = (rows, word, columns) => { + const characters = [...word]; + + let isInsideEscape = false; + let isInsideLinkEscape = false; + let visible = stringWidth(stripAnsi(rows[rows.length - 1])); + + for (const [index, character] of characters.entries()) { + const characterLength = stringWidth(character); + + if (visible + characterLength <= columns) { + rows[rows.length - 1] += character; + } else { + rows.push(character); + visible = 0; + } + + if (ESCAPES.has(character)) { + isInsideEscape = true; + isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK); + } + + if (isInsideEscape) { + if (isInsideLinkEscape) { + if (character === ANSI_ESCAPE_BELL) { + isInsideEscape = false; + isInsideLinkEscape = false; + } + } else if (character === ANSI_SGR_TERMINATOR) { + isInsideEscape = false; + } + + continue; + } + + visible += characterLength; + + if (visible === columns && index < characters.length - 1) { + rows.push(''); + visible = 0; + } + } + + // It's possible that the last row we copy over is only + // ansi escape characters, handle this edge-case + if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { + rows[rows.length - 2] += rows.pop(); + } +}; + +// Trims spaces from a string ignoring invisible sequences +const stringVisibleTrimSpacesRight = string => { + const words = string.split(' '); + let last = words.length; + + while (last > 0) { + if (stringWidth(words[last - 1]) > 0) { + break; + } + + last--; + } + + if (last === words.length) { + return string; + } + + return words.slice(0, last).join(' ') + words.slice(last).join(''); +}; + +// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode +// +// 'hard' will never allow a string to take up more than columns characters +// +// 'soft' allows long words to expand past the column length +const exec = (string, columns, options = {}) => { + if (options.trim !== false && string.trim() === '') { + return ''; + } + + let returnValue = ''; + let escapeCode; + let escapeUrl; + + const lengths = wordLengths(string); + let rows = ['']; + + for (const [index, word] of string.split(' ').entries()) { + if (options.trim !== false) { + rows[rows.length - 1] = rows[rows.length - 1].trimStart(); + } + + let rowLength = stringWidth(rows[rows.length - 1]); + + if (index !== 0) { + if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { + // If we start with a new word but the current row length equals the length of the columns, add a new row + rows.push(''); + rowLength = 0; + } + + if (rowLength > 0 || options.trim === false) { + rows[rows.length - 1] += ' '; + rowLength++; + } + } + + // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' + if (options.hard && lengths[index] > columns) { + const remainingColumns = (columns - rowLength); + const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); + const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); + if (breaksStartingNextLine < breaksStartingThisLine) { + rows.push(''); + } + + wrapWord(rows, word, columns); + continue; + } + + if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { + if (options.wordWrap === false && rowLength < columns) { + wrapWord(rows, word, columns); + continue; + } + + rows.push(''); + } + + if (rowLength + lengths[index] > columns && options.wordWrap === false) { + wrapWord(rows, word, columns); + continue; + } + + rows[rows.length - 1] += word; + } + + if (options.trim !== false) { + rows = rows.map(row => stringVisibleTrimSpacesRight(row)); + } + + const pre = [...rows.join('\n')]; + + for (const [index, character] of pre.entries()) { + returnValue += character; + + if (ESCAPES.has(character)) { + const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}}; + if (groups.code !== undefined) { + const code = Number.parseFloat(groups.code); + escapeCode = code === END_CODE ? undefined : code; + } else if (groups.uri !== undefined) { + escapeUrl = groups.uri.length === 0 ? undefined : groups.uri; + } + } + + const code = ansiStyles.codes.get(Number(escapeCode)); + + if (pre[index + 1] === '\n') { + if (escapeUrl) { + returnValue += wrapAnsiHyperlink(''); + } + + if (escapeCode && code) { + returnValue += wrapAnsiCode(code); + } + } else if (character === '\n') { + if (escapeCode && code) { + returnValue += wrapAnsiCode(escapeCode); + } + + if (escapeUrl) { + returnValue += wrapAnsiHyperlink(escapeUrl); + } + } + } + + return returnValue; +}; + +// For each newline, invoke the method separately +export default function wrapAnsi(string, columns, options) { + return String(string) + .normalize() + .replace(/\r\n/g, '\n') + .split('\n') + .map(line => exec(line, columns, options)) + .join('\n'); +} diff --git a/node_modules/@isaacs/cliui/node_modules/wrap-ansi/license b/node_modules/@isaacs/cliui/node_modules/wrap-ansi/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/wrap-ansi/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@isaacs/cliui/node_modules/wrap-ansi/package.json b/node_modules/@isaacs/cliui/node_modules/wrap-ansi/package.json new file mode 100644 index 0000000..198a5db --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/wrap-ansi/package.json @@ -0,0 +1,69 @@ +{ + "name": "wrap-ansi", + "version": "8.1.0", + "description": "Wordwrap a string with ANSI escape codes", + "license": "MIT", + "repository": "chalk/wrap-ansi", + "funding": "https://github.com/chalk/wrap-ansi?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "engines": { + "node": ">=12" + }, + "scripts": { + "test": "xo && nyc ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "wrap", + "break", + "wordwrap", + "wordbreak", + "linewrap", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "devDependencies": { + "ava": "^3.15.0", + "chalk": "^4.1.2", + "coveralls": "^3.1.1", + "has-ansi": "^5.0.1", + "nyc": "^15.1.0", + "tsd": "^0.25.0", + "xo": "^0.44.0" + } +} diff --git a/node_modules/@isaacs/cliui/node_modules/wrap-ansi/readme.md b/node_modules/@isaacs/cliui/node_modules/wrap-ansi/readme.md new file mode 100644 index 0000000..21f6fed --- /dev/null +++ b/node_modules/@isaacs/cliui/node_modules/wrap-ansi/readme.md @@ -0,0 +1,91 @@ +# wrap-ansi + +> Wordwrap a string with [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) + +## Install + +``` +$ npm install wrap-ansi +``` + +## Usage + +```js +import chalk from 'chalk'; +import wrapAnsi from 'wrap-ansi'; + +const input = 'The quick brown ' + chalk.red('fox jumped over ') + + 'the lazy ' + chalk.green('dog and then ran away with the unicorn.'); + +console.log(wrapAnsi(input, 20)); +``` + + + +## API + +### wrapAnsi(string, columns, options?) + +Wrap words to the specified column width. + +#### string + +Type: `string` + +String with ANSI escape codes. Like one styled by [`chalk`](https://github.com/chalk/chalk). Newline characters will be normalized to `\n`. + +#### columns + +Type: `number` + +Number of columns to wrap the text to. + +#### options + +Type: `object` + +##### hard + +Type: `boolean`\ +Default: `false` + +By default the wrap is soft, meaning long words may extend past the column width. Setting this to `true` will make it hard wrap at the column width. + +##### wordWrap + +Type: `boolean`\ +Default: `true` + +By default, an attempt is made to split words at spaces, ensuring that they don't extend past the configured columns. If wordWrap is `false`, each column will instead be completely filled splitting words as necessary. + +##### trim + +Type: `boolean`\ +Default: `true` + +Whitespace on all lines is removed by default. Set this option to `false` if you don't want to trim. + +## Related + +- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes +- [cli-truncate](https://github.com/sindresorhus/cli-truncate) - Truncate a string to a specific width in the terminal +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right +- [jsesc](https://github.com/mathiasbynens/jsesc) - Generate ASCII-only output from Unicode strings. Useful for creating test fixtures. + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) +- [Benjamin Coe](https://github.com/bcoe) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/@isaacs/cliui/package.json b/node_modules/@isaacs/cliui/package.json new file mode 100644 index 0000000..7a95253 --- /dev/null +++ b/node_modules/@isaacs/cliui/package.json @@ -0,0 +1,86 @@ +{ + "name": "@isaacs/cliui", + "version": "8.0.2", + "description": "easily create complex multi-column command-line-interfaces", + "main": "build/index.cjs", + "exports": { + ".": [ + { + "import": "./index.mjs", + "require": "./build/index.cjs" + }, + "./build/index.cjs" + ] + }, + "type": "module", + "module": "./index.mjs", + "scripts": { + "check": "standardx '**/*.ts' && standardx '**/*.js' && standardx '**/*.cjs'", + "fix": "standardx --fix '**/*.ts' && standardx --fix '**/*.js' && standardx --fix '**/*.cjs'", + "pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs", + "test": "c8 mocha ./test/*.cjs", + "test:esm": "c8 mocha ./test/**/*.mjs", + "postest": "check", + "coverage": "c8 report --check-coverage", + "precompile": "rimraf build", + "compile": "tsc", + "postcompile": "npm run build:cjs", + "build:cjs": "rollup -c", + "prepare": "npm run compile" + }, + "repository": "yargs/cliui", + "standard": { + "ignore": [ + "**/example/**" + ], + "globals": [ + "it" + ] + }, + "keywords": [ + "cli", + "command-line", + "layout", + "design", + "console", + "wrap", + "table" + ], + "author": "Ben Coe ", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "devDependencies": { + "@types/node": "^14.0.27", + "@typescript-eslint/eslint-plugin": "^4.0.0", + "@typescript-eslint/parser": "^4.0.0", + "c8": "^7.3.0", + "chai": "^4.2.0", + "chalk": "^4.1.0", + "cross-env": "^7.0.2", + "eslint": "^7.6.0", + "eslint-plugin-import": "^2.22.0", + "eslint-plugin-node": "^11.1.0", + "gts": "^3.0.0", + "mocha": "^10.0.0", + "rimraf": "^3.0.2", + "rollup": "^2.23.1", + "rollup-plugin-ts": "^3.0.2", + "standardx": "^7.0.0", + "typescript": "^4.0.0" + }, + "files": [ + "build", + "index.mjs", + "!*.d.ts" + ], + "engines": { + "node": ">=12" + } +} diff --git a/node_modules/@jridgewell/gen-mapping/LICENSE b/node_modules/@jridgewell/gen-mapping/LICENSE new file mode 100644 index 0000000..1f6ce94 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2024 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@jridgewell/gen-mapping/README.md b/node_modules/@jridgewell/gen-mapping/README.md new file mode 100644 index 0000000..93692b1 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/README.md @@ -0,0 +1,227 @@ +# @jridgewell/gen-mapping + +> Generate source maps + +`gen-mapping` allows you to generate a source map during transpilation or minification. +With a source map, you're able to trace the original location in the source file, either in Chrome's +DevTools or using a library like [`@jridgewell/trace-mapping`][trace-mapping]. + +You may already be familiar with the [`source-map`][source-map] package's `SourceMapGenerator`. This +provides the same `addMapping` and `setSourceContent` API. + +## Installation + +```sh +npm install @jridgewell/gen-mapping +``` + +## Usage + +```typescript +import { GenMapping, addMapping, setSourceContent, toEncodedMap, toDecodedMap } from '@jridgewell/gen-mapping'; + +const map = new GenMapping({ + file: 'output.js', + sourceRoot: 'https://example.com/', +}); + +setSourceContent(map, 'input.js', `function foo() {}`); + +addMapping(map, { + // Lines start at line 1, columns at column 0. + generated: { line: 1, column: 0 }, + source: 'input.js', + original: { line: 1, column: 0 }, +}); + +addMapping(map, { + generated: { line: 1, column: 9 }, + source: 'input.js', + original: { line: 1, column: 9 }, + name: 'foo', +}); + +assert.deepEqual(toDecodedMap(map), { + version: 3, + file: 'output.js', + names: ['foo'], + sourceRoot: 'https://example.com/', + sources: ['input.js'], + sourcesContent: ['function foo() {}'], + mappings: [ + [ [0, 0, 0, 0], [9, 0, 0, 9, 0] ] + ], +}); + +assert.deepEqual(toEncodedMap(map), { + version: 3, + file: 'output.js', + names: ['foo'], + sourceRoot: 'https://example.com/', + sources: ['input.js'], + sourcesContent: ['function foo() {}'], + mappings: 'AAAA,SAASA', +}); +``` + +### Smaller Sourcemaps + +Not everything needs to be added to a sourcemap, and needless markings can cause signficantly +larger file sizes. `gen-mapping` exposes `maybeAddSegment`/`maybeAddMapping` APIs that will +intelligently determine if this marking adds useful information. If not, the marking will be +skipped. + +```typescript +import { maybeAddMapping } from '@jridgewell/gen-mapping'; + +const map = new GenMapping(); + +// Adding a sourceless marking at the beginning of a line isn't useful. +maybeAddMapping(map, { + generated: { line: 1, column: 0 }, +}); + +// Adding a new source marking is useful. +maybeAddMapping(map, { + generated: { line: 1, column: 0 }, + source: 'input.js', + original: { line: 1, column: 0 }, +}); + +// But adding another marking pointing to the exact same original location isn't, even if the +// generated column changed. +maybeAddMapping(map, { + generated: { line: 1, column: 9 }, + source: 'input.js', + original: { line: 1, column: 0 }, +}); + +assert.deepEqual(toEncodedMap(map), { + version: 3, + names: [], + sources: ['input.js'], + sourcesContent: [null], + mappings: 'AAAA', +}); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map +Memory Usage: +gen-mapping: addSegment 5852872 bytes +gen-mapping: addMapping 7716042 bytes +source-map-js 6143250 bytes +source-map-0.6.1 6124102 bytes +source-map-0.8.0 6121173 bytes +Smallest memory usage is gen-mapping: addSegment + +Adding speed: +gen-mapping: addSegment x 441 ops/sec ±2.07% (90 runs sampled) +gen-mapping: addMapping x 350 ops/sec ±2.40% (86 runs sampled) +source-map-js: addMapping x 169 ops/sec ±2.42% (80 runs sampled) +source-map-0.6.1: addMapping x 167 ops/sec ±2.56% (80 runs sampled) +source-map-0.8.0: addMapping x 168 ops/sec ±2.52% (80 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 150,824,370 ops/sec ±0.07% (102 runs sampled) +gen-mapping: encoded output x 663 ops/sec ±0.22% (98 runs sampled) +source-map-js: encoded output x 197 ops/sec ±0.45% (84 runs sampled) +source-map-0.6.1: encoded output x 198 ops/sec ±0.33% (85 runs sampled) +source-map-0.8.0: encoded output x 197 ops/sec ±0.06% (93 runs sampled) +Fastest is gen-mapping: decoded output + + +*** + + +babel.min.js.map +Memory Usage: +gen-mapping: addSegment 37578063 bytes +gen-mapping: addMapping 37212897 bytes +source-map-js 47638527 bytes +source-map-0.6.1 47690503 bytes +source-map-0.8.0 47470188 bytes +Smallest memory usage is gen-mapping: addMapping + +Adding speed: +gen-mapping: addSegment x 31.05 ops/sec ±8.31% (43 runs sampled) +gen-mapping: addMapping x 29.83 ops/sec ±7.36% (51 runs sampled) +source-map-js: addMapping x 20.73 ops/sec ±6.22% (38 runs sampled) +source-map-0.6.1: addMapping x 20.03 ops/sec ±10.51% (38 runs sampled) +source-map-0.8.0: addMapping x 19.30 ops/sec ±8.27% (37 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 381,379,234 ops/sec ±0.29% (96 runs sampled) +gen-mapping: encoded output x 95.15 ops/sec ±2.98% (72 runs sampled) +source-map-js: encoded output x 15.20 ops/sec ±7.41% (33 runs sampled) +source-map-0.6.1: encoded output x 16.36 ops/sec ±10.46% (31 runs sampled) +source-map-0.8.0: encoded output x 16.06 ops/sec ±6.45% (31 runs sampled) +Fastest is gen-mapping: decoded output + + +*** + + +preact.js.map +Memory Usage: +gen-mapping: addSegment 416247 bytes +gen-mapping: addMapping 419824 bytes +source-map-js 1024619 bytes +source-map-0.6.1 1146004 bytes +source-map-0.8.0 1113250 bytes +Smallest memory usage is gen-mapping: addSegment + +Adding speed: +gen-mapping: addSegment x 13,755 ops/sec ±0.15% (98 runs sampled) +gen-mapping: addMapping x 13,013 ops/sec ±0.11% (101 runs sampled) +source-map-js: addMapping x 4,564 ops/sec ±0.21% (98 runs sampled) +source-map-0.6.1: addMapping x 4,562 ops/sec ±0.11% (99 runs sampled) +source-map-0.8.0: addMapping x 4,593 ops/sec ±0.11% (100 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 379,864,020 ops/sec ±0.23% (93 runs sampled) +gen-mapping: encoded output x 14,368 ops/sec ±4.07% (82 runs sampled) +source-map-js: encoded output x 5,261 ops/sec ±0.21% (99 runs sampled) +source-map-0.6.1: encoded output x 5,124 ops/sec ±0.58% (99 runs sampled) +source-map-0.8.0: encoded output x 5,434 ops/sec ±0.33% (96 runs sampled) +Fastest is gen-mapping: decoded output + + +*** + + +react.js.map +Memory Usage: +gen-mapping: addSegment 975096 bytes +gen-mapping: addMapping 1102981 bytes +source-map-js 2918836 bytes +source-map-0.6.1 2885435 bytes +source-map-0.8.0 2874336 bytes +Smallest memory usage is gen-mapping: addSegment + +Adding speed: +gen-mapping: addSegment x 4,772 ops/sec ±0.15% (100 runs sampled) +gen-mapping: addMapping x 4,456 ops/sec ±0.13% (97 runs sampled) +source-map-js: addMapping x 1,618 ops/sec ±0.24% (97 runs sampled) +source-map-0.6.1: addMapping x 1,622 ops/sec ±0.12% (99 runs sampled) +source-map-0.8.0: addMapping x 1,631 ops/sec ±0.12% (100 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 379,107,695 ops/sec ±0.07% (99 runs sampled) +gen-mapping: encoded output x 5,421 ops/sec ±1.60% (89 runs sampled) +source-map-js: encoded output x 2,113 ops/sec ±1.81% (98 runs sampled) +source-map-0.6.1: encoded output x 2,126 ops/sec ±0.10% (100 runs sampled) +source-map-0.8.0: encoded output x 2,176 ops/sec ±0.39% (98 runs sampled) +Fastest is gen-mapping: decoded output +``` + +[source-map]: https://www.npmjs.com/package/source-map +[trace-mapping]: https://github.com/jridgewell/sourcemaps/tree/main/packages/trace-mapping diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs new file mode 100644 index 0000000..bbb0cac --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs @@ -0,0 +1,292 @@ +// src/set-array.ts +var SetArray = class { + constructor() { + this._indexes = { __proto__: null }; + this.array = []; + } +}; +function cast(set) { + return set; +} +function get(setarr, key) { + return cast(setarr)._indexes[key]; +} +function put(setarr, key) { + const index = get(setarr, key); + if (index !== void 0) return index; + const { array, _indexes: indexes } = cast(setarr); + const length = array.push(key); + return indexes[key] = length - 1; +} +function remove(setarr, key) { + const index = get(setarr, key); + if (index === void 0) return; + const { array, _indexes: indexes } = cast(setarr); + for (let i = index + 1; i < array.length; i++) { + const k = array[i]; + array[i - 1] = k; + indexes[k]--; + } + indexes[key] = void 0; + array.pop(); +} + +// src/gen-mapping.ts +import { + encode +} from "@jridgewell/sourcemap-codec"; +import { TraceMap, decodedMappings } from "@jridgewell/trace-mapping"; + +// src/sourcemap-segment.ts +var COLUMN = 0; +var SOURCES_INDEX = 1; +var SOURCE_LINE = 2; +var SOURCE_COLUMN = 3; +var NAMES_INDEX = 4; + +// src/gen-mapping.ts +var NO_NAME = -1; +var GenMapping = class { + constructor({ file, sourceRoot } = {}) { + this._names = new SetArray(); + this._sources = new SetArray(); + this._sourcesContent = []; + this._mappings = []; + this.file = file; + this.sourceRoot = sourceRoot; + this._ignoreList = new SetArray(); + } +}; +function cast2(map) { + return map; +} +function addSegment(map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) { + return addSegmentInternal( + false, + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content + ); +} +function addMapping(map, mapping) { + return addMappingInternal(false, map, mapping); +} +var maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal( + true, + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content + ); +}; +var maybeAddMapping = (map, mapping) => { + return addMappingInternal(true, map, mapping); +}; +function setSourceContent(map, source, content) { + const { + _sources: sources, + _sourcesContent: sourcesContent + // _originalScopes: originalScopes, + } = cast2(map); + const index = put(sources, source); + sourcesContent[index] = content; +} +function setIgnore(map, source, ignore = true) { + const { + _sources: sources, + _sourcesContent: sourcesContent, + _ignoreList: ignoreList + // _originalScopes: originalScopes, + } = cast2(map); + const index = put(sources, source); + if (index === sourcesContent.length) sourcesContent[index] = null; + if (ignore) put(ignoreList, index); + else remove(ignoreList, index); +} +function toDecodedMap(map) { + const { + _mappings: mappings, + _sources: sources, + _sourcesContent: sourcesContent, + _names: names, + _ignoreList: ignoreList + // _originalScopes: originalScopes, + // _generatedRanges: generatedRanges, + } = cast2(map); + removeEmptyFinalLines(mappings); + return { + version: 3, + file: map.file || void 0, + names: names.array, + sourceRoot: map.sourceRoot || void 0, + sources: sources.array, + sourcesContent, + mappings, + // originalScopes, + // generatedRanges, + ignoreList: ignoreList.array + }; +} +function toEncodedMap(map) { + const decoded = toDecodedMap(map); + return Object.assign({}, decoded, { + // originalScopes: decoded.originalScopes.map((os) => encodeOriginalScopes(os)), + // generatedRanges: encodeGeneratedRanges(decoded.generatedRanges as GeneratedRange[]), + mappings: encode(decoded.mappings) + }); +} +function fromMap(input) { + const map = new TraceMap(input); + const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot }); + putAll(cast2(gen)._names, map.names); + putAll(cast2(gen)._sources, map.sources); + cast2(gen)._sourcesContent = map.sourcesContent || map.sources.map(() => null); + cast2(gen)._mappings = decodedMappings(map); + if (map.ignoreList) putAll(cast2(gen)._ignoreList, map.ignoreList); + return gen; +} +function allMappings(map) { + const out = []; + const { _mappings: mappings, _sources: sources, _names: names } = cast2(map); + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generated = { line: i + 1, column: seg[COLUMN] }; + let source = void 0; + let original = void 0; + let name = void 0; + if (seg.length !== 1) { + source = sources.array[seg[SOURCES_INDEX]]; + original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] }; + if (seg.length === 5) name = names.array[seg[NAMES_INDEX]]; + } + out.push({ generated, source, original, name }); + } + } + return out; +} +function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) { + const { + _mappings: mappings, + _sources: sources, + _sourcesContent: sourcesContent, + _names: names + // _originalScopes: originalScopes, + } = cast2(map); + const line = getIndex(mappings, genLine); + const index = getColumnIndex(line, genColumn); + if (!source) { + if (skipable && skipSourceless(line, index)) return; + return insert(line, index, [genColumn]); + } + assert(sourceLine); + assert(sourceColumn); + const sourcesIndex = put(sources, source); + const namesIndex = name ? put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null; + if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { + return; + } + return insert( + line, + index, + name ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] : [genColumn, sourcesIndex, sourceLine, sourceColumn] + ); +} +function assert(_val) { +} +function getIndex(arr, index) { + for (let i = arr.length; i <= index; i++) { + arr[i] = []; + } + return arr[index]; +} +function getColumnIndex(line, genColumn) { + let index = line.length; + for (let i = index - 1; i >= 0; index = i--) { + const current = line[i]; + if (genColumn >= current[COLUMN]) break; + } + return index; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +function removeEmptyFinalLines(mappings) { + const { length } = mappings; + let len = length; + for (let i = len - 1; i >= 0; len = i, i--) { + if (mappings[i].length > 0) break; + } + if (len < length) mappings.length = len; +} +function putAll(setarr, array) { + for (let i = 0; i < array.length; i++) put(setarr, array[i]); +} +function skipSourceless(line, index) { + if (index === 0) return true; + const prev = line[index - 1]; + return prev.length === 1; +} +function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { + if (index === 0) return false; + const prev = line[index - 1]; + if (prev.length === 1) return false; + return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME); +} +function addMappingInternal(skipable, map, mapping) { + const { generated, source, original, name, content } = mapping; + if (!source) { + return addSegmentInternal( + skipable, + map, + generated.line - 1, + generated.column, + null, + null, + null, + null, + null + ); + } + assert(original); + return addSegmentInternal( + skipable, + map, + generated.line - 1, + generated.column, + source, + original.line - 1, + original.column, + name, + content + ); +} +export { + GenMapping, + addMapping, + addSegment, + allMappings, + fromMap, + maybeAddMapping, + maybeAddSegment, + setIgnore, + setSourceContent, + toDecodedMap, + toEncodedMap +}; +//# sourceMappingURL=gen-mapping.mjs.map diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map new file mode 100644 index 0000000..4e37e45 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../src/set-array.ts", "../src/gen-mapping.ts", "../src/sourcemap-segment.ts"], + "mappings": ";AAUO,IAAM,WAAN,MAAoC;AAAA,EAIzC,cAAc;AACZ,SAAK,WAAW,EAAE,WAAW,KAAK;AAClC,SAAK,QAAQ,CAAC;AAAA,EAChB;AACF;AAWA,SAAS,KAAoB,KAAgC;AAC3D,SAAO;AACT;AAKO,SAAS,IAAmB,QAAqB,KAA4B;AAClF,SAAO,KAAK,MAAM,EAAE,SAAS,GAAG;AAClC;AAMO,SAAS,IAAmB,QAAqB,KAAgB;AAEtE,QAAM,QAAQ,IAAI,QAAQ,GAAG;AAC7B,MAAI,UAAU,OAAW,QAAO;AAEhC,QAAM,EAAE,OAAO,UAAU,QAAQ,IAAI,KAAK,MAAM;AAEhD,QAAM,SAAS,MAAM,KAAK,GAAG;AAC7B,SAAQ,QAAQ,GAAG,IAAI,SAAS;AAClC;AAgBO,SAAS,OAAsB,QAAqB,KAAc;AACvE,QAAM,QAAQ,IAAI,QAAQ,GAAG;AAC7B,MAAI,UAAU,OAAW;AAEzB,QAAM,EAAE,OAAO,UAAU,QAAQ,IAAI,KAAK,MAAM;AAChD,WAAS,IAAI,QAAQ,GAAG,IAAI,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WAAS,IAAI,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK;AAC1C,QAAI,SAAS,CAAC,EAAE,SAAS,EAAG;AAAA,EAC9B;AACA,MAAI,MAAM,OAAQ,UAAS,SAAS;AACtC;AAEA,SAAS,OAAkC,QAAqB,OAAY;AAC1E,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,IAAK,KAAI,QAAQ,MAAM,CAAC,CAAC;AAC7D;AAEA,SAAS,eAAe,MAA0B,OAAwB;AAGxE,MAAI,UAAU,EAAG,QAAO;AAExB,QAAM,OAAO,KAAK,QAAQ,CAAC;AAI3B,SAAO,KAAK,WAAW;AACzB;AAEA,SAAS,WACP,MACA,OACA,cACA,YACA,cACA,YACS;AAET,MAAI,UAAU,EAAG,QAAO;AAExB,QAAM,OAAO,KAAK,QAAQ,CAAC;AAG3B,MAAI,KAAK,WAAW,EAAG,QAAO;AAI9B,SACE,iBAAiB,KAAK,aAAa,KACnC,eAAe,KAAK,WAAW,KAC/B,iBAAiB,KAAK,aAAa,KACnC,gBAAgB,KAAK,WAAW,IAAI,KAAK,WAAW,IAAI;AAE5D;AAEA,SAAS,mBACP,UACA,KACA,SAOA;AACA,QAAM,EAAE,WAAW,QAAQ,UAAU,MAAM,QAAQ,IAAI;AACvD,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,UAAU,OAAO;AAAA,MACjB,UAAU;AAAA,MACV;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,SAAY,QAAQ;AACpB,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,UAAU,OAAO;AAAA,IACjB,UAAU;AAAA,IACV;AAAA,IACA,SAAS,OAAO;AAAA,IAChB,SAAS;AAAA,IACT;AAAA,IACA;AAAA,EACF;AACF;", + "names": ["cast"] +} diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js new file mode 100644 index 0000000..cb84af5 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js @@ -0,0 +1,358 @@ +(function (global, factory) { + if (typeof exports === 'object' && typeof module !== 'undefined') { + factory(module, require('@jridgewell/sourcemap-codec'), require('@jridgewell/trace-mapping')); + module.exports = def(module); + } else if (typeof define === 'function' && define.amd) { + define(['module', '@jridgewell/sourcemap-codec', '@jridgewell/trace-mapping'], function(mod) { + factory.apply(this, arguments); + mod.exports = def(mod); + }); + } else { + const mod = { exports: {} }; + factory(mod, global.sourcemapCodec, global.traceMapping); + global = typeof globalThis !== 'undefined' ? globalThis : global || self; + global.genMapping = def(mod); + } + function def(m) { return 'default' in m.exports ? m.exports.default : m.exports; } +})(this, (function (module, require_sourcemapCodec, require_traceMapping) { +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// umd:@jridgewell/sourcemap-codec +var require_sourcemap_codec = __commonJS({ + "umd:@jridgewell/sourcemap-codec"(exports, module2) { + module2.exports = require_sourcemapCodec; + } +}); + +// umd:@jridgewell/trace-mapping +var require_trace_mapping = __commonJS({ + "umd:@jridgewell/trace-mapping"(exports, module2) { + module2.exports = require_traceMapping; + } +}); + +// src/gen-mapping.ts +var gen_mapping_exports = {}; +__export(gen_mapping_exports, { + GenMapping: () => GenMapping, + addMapping: () => addMapping, + addSegment: () => addSegment, + allMappings: () => allMappings, + fromMap: () => fromMap, + maybeAddMapping: () => maybeAddMapping, + maybeAddSegment: () => maybeAddSegment, + setIgnore: () => setIgnore, + setSourceContent: () => setSourceContent, + toDecodedMap: () => toDecodedMap, + toEncodedMap: () => toEncodedMap +}); +module.exports = __toCommonJS(gen_mapping_exports); + +// src/set-array.ts +var SetArray = class { + constructor() { + this._indexes = { __proto__: null }; + this.array = []; + } +}; +function cast(set) { + return set; +} +function get(setarr, key) { + return cast(setarr)._indexes[key]; +} +function put(setarr, key) { + const index = get(setarr, key); + if (index !== void 0) return index; + const { array, _indexes: indexes } = cast(setarr); + const length = array.push(key); + return indexes[key] = length - 1; +} +function remove(setarr, key) { + const index = get(setarr, key); + if (index === void 0) return; + const { array, _indexes: indexes } = cast(setarr); + for (let i = index + 1; i < array.length; i++) { + const k = array[i]; + array[i - 1] = k; + indexes[k]--; + } + indexes[key] = void 0; + array.pop(); +} + +// src/gen-mapping.ts +var import_sourcemap_codec = __toESM(require_sourcemap_codec()); +var import_trace_mapping = __toESM(require_trace_mapping()); + +// src/sourcemap-segment.ts +var COLUMN = 0; +var SOURCES_INDEX = 1; +var SOURCE_LINE = 2; +var SOURCE_COLUMN = 3; +var NAMES_INDEX = 4; + +// src/gen-mapping.ts +var NO_NAME = -1; +var GenMapping = class { + constructor({ file, sourceRoot } = {}) { + this._names = new SetArray(); + this._sources = new SetArray(); + this._sourcesContent = []; + this._mappings = []; + this.file = file; + this.sourceRoot = sourceRoot; + this._ignoreList = new SetArray(); + } +}; +function cast2(map) { + return map; +} +function addSegment(map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) { + return addSegmentInternal( + false, + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content + ); +} +function addMapping(map, mapping) { + return addMappingInternal(false, map, mapping); +} +var maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal( + true, + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content + ); +}; +var maybeAddMapping = (map, mapping) => { + return addMappingInternal(true, map, mapping); +}; +function setSourceContent(map, source, content) { + const { + _sources: sources, + _sourcesContent: sourcesContent + // _originalScopes: originalScopes, + } = cast2(map); + const index = put(sources, source); + sourcesContent[index] = content; +} +function setIgnore(map, source, ignore = true) { + const { + _sources: sources, + _sourcesContent: sourcesContent, + _ignoreList: ignoreList + // _originalScopes: originalScopes, + } = cast2(map); + const index = put(sources, source); + if (index === sourcesContent.length) sourcesContent[index] = null; + if (ignore) put(ignoreList, index); + else remove(ignoreList, index); +} +function toDecodedMap(map) { + const { + _mappings: mappings, + _sources: sources, + _sourcesContent: sourcesContent, + _names: names, + _ignoreList: ignoreList + // _originalScopes: originalScopes, + // _generatedRanges: generatedRanges, + } = cast2(map); + removeEmptyFinalLines(mappings); + return { + version: 3, + file: map.file || void 0, + names: names.array, + sourceRoot: map.sourceRoot || void 0, + sources: sources.array, + sourcesContent, + mappings, + // originalScopes, + // generatedRanges, + ignoreList: ignoreList.array + }; +} +function toEncodedMap(map) { + const decoded = toDecodedMap(map); + return Object.assign({}, decoded, { + // originalScopes: decoded.originalScopes.map((os) => encodeOriginalScopes(os)), + // generatedRanges: encodeGeneratedRanges(decoded.generatedRanges as GeneratedRange[]), + mappings: (0, import_sourcemap_codec.encode)(decoded.mappings) + }); +} +function fromMap(input) { + const map = new import_trace_mapping.TraceMap(input); + const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot }); + putAll(cast2(gen)._names, map.names); + putAll(cast2(gen)._sources, map.sources); + cast2(gen)._sourcesContent = map.sourcesContent || map.sources.map(() => null); + cast2(gen)._mappings = (0, import_trace_mapping.decodedMappings)(map); + if (map.ignoreList) putAll(cast2(gen)._ignoreList, map.ignoreList); + return gen; +} +function allMappings(map) { + const out = []; + const { _mappings: mappings, _sources: sources, _names: names } = cast2(map); + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generated = { line: i + 1, column: seg[COLUMN] }; + let source = void 0; + let original = void 0; + let name = void 0; + if (seg.length !== 1) { + source = sources.array[seg[SOURCES_INDEX]]; + original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] }; + if (seg.length === 5) name = names.array[seg[NAMES_INDEX]]; + } + out.push({ generated, source, original, name }); + } + } + return out; +} +function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) { + const { + _mappings: mappings, + _sources: sources, + _sourcesContent: sourcesContent, + _names: names + // _originalScopes: originalScopes, + } = cast2(map); + const line = getIndex(mappings, genLine); + const index = getColumnIndex(line, genColumn); + if (!source) { + if (skipable && skipSourceless(line, index)) return; + return insert(line, index, [genColumn]); + } + assert(sourceLine); + assert(sourceColumn); + const sourcesIndex = put(sources, source); + const namesIndex = name ? put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null; + if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { + return; + } + return insert( + line, + index, + name ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] : [genColumn, sourcesIndex, sourceLine, sourceColumn] + ); +} +function assert(_val) { +} +function getIndex(arr, index) { + for (let i = arr.length; i <= index; i++) { + arr[i] = []; + } + return arr[index]; +} +function getColumnIndex(line, genColumn) { + let index = line.length; + for (let i = index - 1; i >= 0; index = i--) { + const current = line[i]; + if (genColumn >= current[COLUMN]) break; + } + return index; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +function removeEmptyFinalLines(mappings) { + const { length } = mappings; + let len = length; + for (let i = len - 1; i >= 0; len = i, i--) { + if (mappings[i].length > 0) break; + } + if (len < length) mappings.length = len; +} +function putAll(setarr, array) { + for (let i = 0; i < array.length; i++) put(setarr, array[i]); +} +function skipSourceless(line, index) { + if (index === 0) return true; + const prev = line[index - 1]; + return prev.length === 1; +} +function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { + if (index === 0) return false; + const prev = line[index - 1]; + if (prev.length === 1) return false; + return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME); +} +function addMappingInternal(skipable, map, mapping) { + const { generated, source, original, name, content } = mapping; + if (!source) { + return addSegmentInternal( + skipable, + map, + generated.line - 1, + generated.column, + null, + null, + null, + null, + null + ); + } + assert(original); + return addSegmentInternal( + skipable, + map, + generated.line - 1, + generated.column, + source, + original.line - 1, + original.column, + name, + content + ); +} +})); +//# sourceMappingURL=gen-mapping.umd.js.map diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map new file mode 100644 index 0000000..b13750b --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["umd:@jridgewell/sourcemap-codec", "umd:@jridgewell/trace-mapping", "../src/gen-mapping.ts", "../src/set-array.ts", "../src/sourcemap-segment.ts"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,6CAAAA,SAAA;AAAA,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AAI3B,SAAO,KAAK,WAAW;AACzB;AAEA,SAAS,WACP,MACA,OACA,cACA,YACA,cACA,YACS;AAET,MAAI,UAAU,EAAG,QAAO;AAExB,QAAM,OAAO,KAAK,QAAQ,CAAC;AAG3B,MAAI,KAAK,WAAW,EAAG,QAAO;AAI9B,SACE,iBAAiB,KAAK,aAAa,KACnC,eAAe,KAAK,WAAW,KAC/B,iBAAiB,KAAK,aAAa,KACnC,gBAAgB,KAAK,WAAW,IAAI,KAAK,WAAW,IAAI;AAE5D;AAEA,SAAS,mBACP,UACA,KACA,SAOA;AACA,QAAM,EAAE,WAAW,QAAQ,UAAU,MAAM,QAAQ,IAAI;AACvD,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,UAAU,OAAO;AAAA,MACjB,UAAU;AAAA,MACV;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,SAAY,QAAQ;AACpB,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,UAAU,OAAO;AAAA,IACjB,UAAU;AAAA,IACV;AAAA,IACA,SAAS,OAAO;AAAA,IAChB,SAAS;AAAA,IACT;AAAA,IACA;AAAA,EACF;AACF;", + "names": ["module", "module", "cast"] +} diff --git a/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts b/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts new file mode 100644 index 0000000..9ba936e --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts @@ -0,0 +1,88 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types'; +export type { DecodedSourceMap, EncodedSourceMap, Mapping }; +export type Options = { + file?: string | null; + sourceRoot?: string | null; +}; +/** + * Provides the state to generate a sourcemap. + */ +export declare class GenMapping { + private _names; + private _sources; + private _sourcesContent; + private _mappings; + private _ignoreList; + file: string | null | undefined; + sourceRoot: string | null | undefined; + constructor({ file, sourceRoot }?: Options); +} +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source?: null, sourceLine?: null, sourceColumn?: null, name?: null, content?: null): void; +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name?: null, content?: string | null): void; +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name: string, content?: string | null): void; +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source?: null; + original?: null; + name?: null; + content?: null; +}): void; +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name?: null; + content?: string | null; +}): void; +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name: string; + content?: string | null; +}): void; +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +export declare const maybeAddSegment: typeof addSegment; +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +export declare const maybeAddMapping: typeof addMapping; +/** + * Adds/removes the content of the source file to the source map. + */ +export declare function setSourceContent(map: GenMapping, source: string, content: string | null): void; +export declare function setIgnore(map: GenMapping, source: string, ignore?: boolean): void; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function toDecodedMap(map: GenMapping): DecodedSourceMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function toEncodedMap(map: GenMapping): EncodedSourceMap; +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +export declare function fromMap(input: SourceMapInput): GenMapping; +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +export declare function allMappings(map: GenMapping): Mapping[]; diff --git a/node_modules/@jridgewell/gen-mapping/dist/types/set-array.d.ts b/node_modules/@jridgewell/gen-mapping/dist/types/set-array.d.ts new file mode 100644 index 0000000..6ed4354 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/types/set-array.d.ts @@ -0,0 +1,32 @@ +type Key = string | number | symbol; +/** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +export declare class SetArray { + private _indexes; + array: readonly T[]; + constructor(); +} +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +export declare function get(setarr: SetArray, key: T): number | undefined; +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +export declare function put(setarr: SetArray, key: T): number; +/** + * Pops the last added item out of the SetArray. + */ +export declare function pop(setarr: SetArray): void; +/** + * Removes the key, if it exists in the set. + */ +export declare function remove(setarr: SetArray, key: T): void; +export {}; diff --git a/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts b/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts new file mode 100644 index 0000000..aa19fb5 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts @@ -0,0 +1,12 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +export type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export {}; diff --git a/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts b/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts new file mode 100644 index 0000000..8eb90fb --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts @@ -0,0 +1,43 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +export interface SourceMapV3 { + file?: string | null; + names: readonly string[]; + sourceRoot?: string; + sources: readonly (string | null)[]; + sourcesContent?: readonly (string | null)[]; + version: 3; + ignoreList?: readonly number[]; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: readonly SourceMapSegment[][]; +} +export interface Pos { + line: number; + column: number; +} +export interface OriginalPos extends Pos { + source: string; +} +export interface BindingExpressionRange { + start: Pos; + expression: string; +} +export type Mapping = { + generated: Pos; + source: undefined; + original: undefined; + name: undefined; +} | { + generated: Pos; + source: string; + original: Pos; + name: string; +} | { + generated: Pos; + source: string; + original: Pos; + name: undefined; +}; diff --git a/node_modules/@jridgewell/gen-mapping/package.json b/node_modules/@jridgewell/gen-mapping/package.json new file mode 100644 index 0000000..036f9b7 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/package.json @@ -0,0 +1,67 @@ +{ + "name": "@jridgewell/gen-mapping", + "version": "0.3.13", + "description": "Generate source maps", + "keywords": [ + "source", + "map" + ], + "main": "dist/gen-mapping.umd.js", + "module": "dist/gen-mapping.mjs", + "types": "types/gen-mapping.d.cts", + "files": [ + "dist", + "src", + "types" + ], + "exports": { + ".": [ + { + "import": { + "types": "./types/gen-mapping.d.mts", + "default": "./dist/gen-mapping.mjs" + }, + "default": { + "types": "./types/gen-mapping.d.cts", + "default": "./dist/gen-mapping.umd.js" + } + }, + "./dist/gen-mapping.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:code benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.js", + "build": "run-s -n build:code build:types", + "build:code": "node ../../esbuild.mjs gen-mapping.ts", + "build:types": "run-s build:types:force build:types:emit build:types:mts", + "build:types:force": "rimraf tsconfig.build.tsbuildinfo", + "build:types:emit": "tsc --project tsconfig.build.json", + "build:types:mts": "node ../../mts-types.mjs", + "clean": "run-s -n clean:code clean:types", + "clean:code": "tsc --build --clean tsconfig.build.json", + "clean:types": "rimraf dist types", + "test": "run-s -n test:types test:only test:format", + "test:format": "prettier --check '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:types": "eslint '{src,test}/**/*.ts'", + "lint": "run-s -n lint:types lint:format", + "lint:format": "npm run test:format -- --write", + "lint:types": "npm run test:types -- --fix", + "prepublishOnly": "npm run-s -n build test" + }, + "homepage": "https://github.com/jridgewell/sourcemaps/tree/main/packages/gen-mapping", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemaps.git", + "directory": "packages/gen-mapping" + }, + "author": "Justin Ridgewell ", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } +} diff --git a/node_modules/@jridgewell/gen-mapping/src/gen-mapping.ts b/node_modules/@jridgewell/gen-mapping/src/gen-mapping.ts new file mode 100644 index 0000000..ecc878c --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/src/gen-mapping.ts @@ -0,0 +1,614 @@ +import { SetArray, put, remove } from './set-array'; +import { + encode, + // encodeGeneratedRanges, + // encodeOriginalScopes +} from '@jridgewell/sourcemap-codec'; +import { TraceMap, decodedMappings } from '@jridgewell/trace-mapping'; + +import { + COLUMN, + SOURCES_INDEX, + SOURCE_LINE, + SOURCE_COLUMN, + NAMES_INDEX, +} from './sourcemap-segment'; + +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +// import type { OriginalScope, GeneratedRange } from '@jridgewell/sourcemap-codec'; +import type { SourceMapSegment } from './sourcemap-segment'; +import type { + DecodedSourceMap, + EncodedSourceMap, + Pos, + Mapping, + // BindingExpressionRange, + // OriginalPos, + // OriginalScopeInfo, + // GeneratedRangeInfo, +} from './types'; + +export type { DecodedSourceMap, EncodedSourceMap, Mapping }; + +export type Options = { + file?: string | null; + sourceRoot?: string | null; +}; + +const NO_NAME = -1; + +/** + * Provides the state to generate a sourcemap. + */ +export class GenMapping { + declare private _names: SetArray; + declare private _sources: SetArray; + declare private _sourcesContent: (string | null)[]; + declare private _mappings: SourceMapSegment[][]; + // private declare _originalScopes: OriginalScope[][]; + // private declare _generatedRanges: GeneratedRange[]; + declare private _ignoreList: SetArray; + declare file: string | null | undefined; + declare sourceRoot: string | null | undefined; + + constructor({ file, sourceRoot }: Options = {}) { + this._names = new SetArray(); + this._sources = new SetArray(); + this._sourcesContent = []; + this._mappings = []; + // this._originalScopes = []; + // this._generatedRanges = []; + this.file = file; + this.sourceRoot = sourceRoot; + this._ignoreList = new SetArray(); + } +} + +interface PublicMap { + _names: GenMapping['_names']; + _sources: GenMapping['_sources']; + _sourcesContent: GenMapping['_sourcesContent']; + _mappings: GenMapping['_mappings']; + // _originalScopes: GenMapping['_originalScopes']; + // _generatedRanges: GenMapping['_generatedRanges']; + _ignoreList: GenMapping['_ignoreList']; +} + +/** + * Typescript doesn't allow friend access to private fields, so this just casts the map into a type + * with public access modifiers. + */ +function cast(map: unknown): PublicMap { + return map as any; +} + +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +export function addSegment( + map: GenMapping, + genLine: number, + genColumn: number, + source?: null, + sourceLine?: null, + sourceColumn?: null, + name?: null, + content?: null, +): void; +export function addSegment( + map: GenMapping, + genLine: number, + genColumn: number, + source: string, + sourceLine: number, + sourceColumn: number, + name?: null, + content?: string | null, +): void; +export function addSegment( + map: GenMapping, + genLine: number, + genColumn: number, + source: string, + sourceLine: number, + sourceColumn: number, + name: string, + content?: string | null, +): void; +export function addSegment( + map: GenMapping, + genLine: number, + genColumn: number, + source?: string | null, + sourceLine?: number | null, + sourceColumn?: number | null, + name?: string | null, + content?: string | null, +): void { + return addSegmentInternal( + false, + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content, + ); +} + +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +export function addMapping( + map: GenMapping, + mapping: { + generated: Pos; + source?: null; + original?: null; + name?: null; + content?: null; + }, +): void; +export function addMapping( + map: GenMapping, + mapping: { + generated: Pos; + source: string; + original: Pos; + name?: null; + content?: string | null; + }, +): void; +export function addMapping( + map: GenMapping, + mapping: { + generated: Pos; + source: string; + original: Pos; + name: string; + content?: string | null; + }, +): void; +export function addMapping( + map: GenMapping, + mapping: { + generated: Pos; + source?: string | null; + original?: Pos | null; + name?: string | null; + content?: string | null; + }, +): void { + return addMappingInternal(false, map, mapping as Parameters[2]); +} + +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +export const maybeAddSegment: typeof addSegment = ( + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content, +) => { + return addSegmentInternal( + true, + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content, + ); +}; + +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +export const maybeAddMapping: typeof addMapping = (map, mapping) => { + return addMappingInternal(true, map, mapping as Parameters[2]); +}; + +/** + * Adds/removes the content of the source file to the source map. + */ +export function setSourceContent(map: GenMapping, source: string, content: string | null): void { + const { + _sources: sources, + _sourcesContent: sourcesContent, + // _originalScopes: originalScopes, + } = cast(map); + const index = put(sources, source); + sourcesContent[index] = content; + // if (index === originalScopes.length) originalScopes[index] = []; +} + +export function setIgnore(map: GenMapping, source: string, ignore = true) { + const { + _sources: sources, + _sourcesContent: sourcesContent, + _ignoreList: ignoreList, + // _originalScopes: originalScopes, + } = cast(map); + const index = put(sources, source); + if (index === sourcesContent.length) sourcesContent[index] = null; + // if (index === originalScopes.length) originalScopes[index] = []; + if (ignore) put(ignoreList, index); + else remove(ignoreList, index); +} + +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export function toDecodedMap(map: GenMapping): DecodedSourceMap { + const { + _mappings: mappings, + _sources: sources, + _sourcesContent: sourcesContent, + _names: names, + _ignoreList: ignoreList, + // _originalScopes: originalScopes, + // _generatedRanges: generatedRanges, + } = cast(map); + removeEmptyFinalLines(mappings); + + return { + version: 3, + file: map.file || undefined, + names: names.array, + sourceRoot: map.sourceRoot || undefined, + sources: sources.array, + sourcesContent, + mappings, + // originalScopes, + // generatedRanges, + ignoreList: ignoreList.array, + }; +} + +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export function toEncodedMap(map: GenMapping): EncodedSourceMap { + const decoded = toDecodedMap(map); + return Object.assign({}, decoded, { + // originalScopes: decoded.originalScopes.map((os) => encodeOriginalScopes(os)), + // generatedRanges: encodeGeneratedRanges(decoded.generatedRanges as GeneratedRange[]), + mappings: encode(decoded.mappings as SourceMapSegment[][]), + }); +} + +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +export function fromMap(input: SourceMapInput): GenMapping { + const map = new TraceMap(input); + const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot }); + + putAll(cast(gen)._names, map.names); + putAll(cast(gen)._sources, map.sources as string[]); + cast(gen)._sourcesContent = map.sourcesContent || map.sources.map(() => null); + cast(gen)._mappings = decodedMappings(map) as GenMapping['_mappings']; + // TODO: implement originalScopes/generatedRanges + if (map.ignoreList) putAll(cast(gen)._ignoreList, map.ignoreList); + + return gen; +} + +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +export function allMappings(map: GenMapping): Mapping[] { + const out: Mapping[] = []; + const { _mappings: mappings, _sources: sources, _names: names } = cast(map); + + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + + const generated = { line: i + 1, column: seg[COLUMN] }; + let source: string | undefined = undefined; + let original: Pos | undefined = undefined; + let name: string | undefined = undefined; + + if (seg.length !== 1) { + source = sources.array[seg[SOURCES_INDEX]]; + original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] }; + + if (seg.length === 5) name = names.array[seg[NAMES_INDEX]]; + } + + out.push({ generated, source, original, name } as Mapping); + } + } + + return out; +} + +// This split declaration is only so that terser can elminiate the static initialization block. +function addSegmentInternal( + skipable: boolean, + map: GenMapping, + genLine: number, + genColumn: number, + source: S, + sourceLine: S extends string ? number : null | undefined, + sourceColumn: S extends string ? number : null | undefined, + name: S extends string ? string | null | undefined : null | undefined, + content: S extends string ? string | null | undefined : null | undefined, +): void { + const { + _mappings: mappings, + _sources: sources, + _sourcesContent: sourcesContent, + _names: names, + // _originalScopes: originalScopes, + } = cast(map); + const line = getIndex(mappings, genLine); + const index = getColumnIndex(line, genColumn); + + if (!source) { + if (skipable && skipSourceless(line, index)) return; + return insert(line, index, [genColumn]); + } + + // Sigh, TypeScript can't figure out sourceLine and sourceColumn aren't nullish if source + // isn't nullish. + assert(sourceLine); + assert(sourceColumn); + + const sourcesIndex = put(sources, source); + const namesIndex = name ? put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content ?? null; + // if (sourcesIndex === originalScopes.length) originalScopes[sourcesIndex] = []; + + if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { + return; + } + + return insert( + line, + index, + name + ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] + : [genColumn, sourcesIndex, sourceLine, sourceColumn], + ); +} + +function assert(_val: unknown): asserts _val is T { + // noop. +} + +function getIndex(arr: T[][], index: number): T[] { + for (let i = arr.length; i <= index; i++) { + arr[i] = []; + } + return arr[index]; +} + +function getColumnIndex(line: SourceMapSegment[], genColumn: number): number { + let index = line.length; + for (let i = index - 1; i >= 0; index = i--) { + const current = line[i]; + if (genColumn >= current[COLUMN]) break; + } + return index; +} + +function insert(array: T[], index: number, value: T) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} + +function removeEmptyFinalLines(mappings: SourceMapSegment[][]) { + const { length } = mappings; + let len = length; + for (let i = len - 1; i >= 0; len = i, i--) { + if (mappings[i].length > 0) break; + } + if (len < length) mappings.length = len; +} + +function putAll(setarr: SetArray, array: T[]) { + for (let i = 0; i < array.length; i++) put(setarr, array[i]); +} + +function skipSourceless(line: SourceMapSegment[], index: number): boolean { + // The start of a line is already sourceless, so adding a sourceless segment to the beginning + // doesn't generate any useful information. + if (index === 0) return true; + + const prev = line[index - 1]; + // If the previous segment is also sourceless, then adding another sourceless segment doesn't + // genrate any new information. Else, this segment will end the source/named segment and point to + // a sourceless position, which is useful. + return prev.length === 1; +} + +function skipSource( + line: SourceMapSegment[], + index: number, + sourcesIndex: number, + sourceLine: number, + sourceColumn: number, + namesIndex: number, +): boolean { + // A source/named segment at the start of a line gives position at that genColumn + if (index === 0) return false; + + const prev = line[index - 1]; + + // If the previous segment is sourceless, then we're transitioning to a source. + if (prev.length === 1) return false; + + // If the previous segment maps to the exact same source position, then this segment doesn't + // provide any new position information. + return ( + sourcesIndex === prev[SOURCES_INDEX] && + sourceLine === prev[SOURCE_LINE] && + sourceColumn === prev[SOURCE_COLUMN] && + namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME) + ); +} + +function addMappingInternal( + skipable: boolean, + map: GenMapping, + mapping: { + generated: Pos; + source: S; + original: S extends string ? Pos : null | undefined; + name: S extends string ? string | null | undefined : null | undefined; + content: S extends string ? string | null | undefined : null | undefined; + }, +) { + const { generated, source, original, name, content } = mapping; + if (!source) { + return addSegmentInternal( + skipable, + map, + generated.line - 1, + generated.column, + null, + null, + null, + null, + null, + ); + } + assert(original); + return addSegmentInternal( + skipable, + map, + generated.line - 1, + generated.column, + source as string, + original.line - 1, + original.column, + name, + content, + ); +} + +/* +export function addOriginalScope( + map: GenMapping, + data: { + start: Pos; + end: Pos; + source: string; + kind: string; + name?: string; + variables?: string[]; + }, +): OriginalScopeInfo { + const { start, end, source, kind, name, variables } = data; + const { + _sources: sources, + _sourcesContent: sourcesContent, + _originalScopes: originalScopes, + _names: names, + } = cast(map); + const index = put(sources, source); + if (index === sourcesContent.length) sourcesContent[index] = null; + if (index === originalScopes.length) originalScopes[index] = []; + + const kindIndex = put(names, kind); + const scope: OriginalScope = name + ? [start.line - 1, start.column, end.line - 1, end.column, kindIndex, put(names, name)] + : [start.line - 1, start.column, end.line - 1, end.column, kindIndex]; + if (variables) { + scope.vars = variables.map((v) => put(names, v)); + } + const len = originalScopes[index].push(scope); + return [index, len - 1, variables]; +} +*/ + +// Generated Ranges +/* +export function addGeneratedRange( + map: GenMapping, + data: { + start: Pos; + isScope: boolean; + originalScope?: OriginalScopeInfo; + callsite?: OriginalPos; + }, +): GeneratedRangeInfo { + const { start, isScope, originalScope, callsite } = data; + const { + _originalScopes: originalScopes, + _sources: sources, + _sourcesContent: sourcesContent, + _generatedRanges: generatedRanges, + } = cast(map); + + const range: GeneratedRange = [ + start.line - 1, + start.column, + 0, + 0, + originalScope ? originalScope[0] : -1, + originalScope ? originalScope[1] : -1, + ]; + if (originalScope?.[2]) { + range.bindings = originalScope[2].map(() => [[-1]]); + } + if (callsite) { + const index = put(sources, callsite.source); + if (index === sourcesContent.length) sourcesContent[index] = null; + if (index === originalScopes.length) originalScopes[index] = []; + range.callsite = [index, callsite.line - 1, callsite.column]; + } + if (isScope) range.isScope = true; + generatedRanges.push(range); + + return [range, originalScope?.[2]]; +} + +export function setEndPosition(range: GeneratedRangeInfo, pos: Pos) { + range[0][2] = pos.line - 1; + range[0][3] = pos.column; +} + +export function addBinding( + map: GenMapping, + range: GeneratedRangeInfo, + variable: string, + expression: string | BindingExpressionRange, +) { + const { _names: names } = cast(map); + const bindings = (range[0].bindings ||= []); + const vars = range[1]; + + const index = vars!.indexOf(variable); + const binding = getIndex(bindings, index); + + if (typeof expression === 'string') binding[0] = [put(names, expression)]; + else { + const { start } = expression; + binding.push([put(names, expression.expression), start.line - 1, start.column]); + } +} +*/ diff --git a/node_modules/@jridgewell/gen-mapping/src/set-array.ts b/node_modules/@jridgewell/gen-mapping/src/set-array.ts new file mode 100644 index 0000000..a2a73a5 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/src/set-array.ts @@ -0,0 +1,82 @@ +type Key = string | number | symbol; + +/** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +export class SetArray { + declare private _indexes: Record; + declare array: readonly T[]; + + constructor() { + this._indexes = { __proto__: null } as any; + this.array = []; + } +} + +interface PublicSet { + array: T[]; + _indexes: SetArray['_indexes']; +} + +/** + * Typescript doesn't allow friend access to private fields, so this just casts the set into a type + * with public access modifiers. + */ +function cast(set: SetArray): PublicSet { + return set as any; +} + +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +export function get(setarr: SetArray, key: T): number | undefined { + return cast(setarr)._indexes[key]; +} + +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +export function put(setarr: SetArray, key: T): number { + // The key may or may not be present. If it is present, it's a number. + const index = get(setarr, key); + if (index !== undefined) return index; + + const { array, _indexes: indexes } = cast(setarr); + + const length = array.push(key); + return (indexes[key] = length - 1); +} + +/** + * Pops the last added item out of the SetArray. + */ +export function pop(setarr: SetArray): void { + const { array, _indexes: indexes } = cast(setarr); + if (array.length === 0) return; + + const last = array.pop()!; + indexes[last] = undefined; +} + +/** + * Removes the key, if it exists in the set. + */ +export function remove(setarr: SetArray, key: T): void { + const index = get(setarr, key); + if (index === undefined) return; + + const { array, _indexes: indexes } = cast(setarr); + for (let i = index + 1; i < array.length; i++) { + const k = array[i]; + array[i - 1] = k; + indexes[k]!--; + } + indexes[key] = undefined; + array.pop(); +} diff --git a/node_modules/@jridgewell/gen-mapping/src/sourcemap-segment.ts b/node_modules/@jridgewell/gen-mapping/src/sourcemap-segment.ts new file mode 100644 index 0000000..fb296dd --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/src/sourcemap-segment.ts @@ -0,0 +1,16 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; + +export type SourceMapSegment = + | [GeneratedColumn] + | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] + | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; + +export const COLUMN = 0; +export const SOURCES_INDEX = 1; +export const SOURCE_LINE = 2; +export const SOURCE_COLUMN = 3; +export const NAMES_INDEX = 4; diff --git a/node_modules/@jridgewell/gen-mapping/src/types.ts b/node_modules/@jridgewell/gen-mapping/src/types.ts new file mode 100644 index 0000000..b087f70 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/src/types.ts @@ -0,0 +1,61 @@ +// import type { GeneratedRange, OriginalScope } from '@jridgewell/sourcemap-codec'; +import type { SourceMapSegment } from './sourcemap-segment'; + +export interface SourceMapV3 { + file?: string | null; + names: readonly string[]; + sourceRoot?: string; + sources: readonly (string | null)[]; + sourcesContent?: readonly (string | null)[]; + version: 3; + ignoreList?: readonly number[]; +} + +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; + // originalScopes: string[]; + // generatedRanges: string; +} + +export interface DecodedSourceMap extends SourceMapV3 { + mappings: readonly SourceMapSegment[][]; + // originalScopes: readonly OriginalScope[][]; + // generatedRanges: readonly GeneratedRange[]; +} + +export interface Pos { + line: number; // 1-based + column: number; // 0-based +} + +export interface OriginalPos extends Pos { + source: string; +} + +export interface BindingExpressionRange { + start: Pos; + expression: string; +} + +// export type OriginalScopeInfo = [number, number, string[] | undefined]; +// export type GeneratedRangeInfo = [GeneratedRange, string[] | undefined]; + +export type Mapping = + | { + generated: Pos; + source: undefined; + original: undefined; + name: undefined; + } + | { + generated: Pos; + source: string; + original: Pos; + name: string; + } + | { + generated: Pos; + source: string; + original: Pos; + name: undefined; + }; diff --git a/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.cts b/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.cts new file mode 100644 index 0000000..7618d85 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.cts @@ -0,0 +1,89 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types.cts'; +export type { DecodedSourceMap, EncodedSourceMap, Mapping }; +export type Options = { + file?: string | null; + sourceRoot?: string | null; +}; +/** + * Provides the state to generate a sourcemap. + */ +export declare class GenMapping { + private _names; + private _sources; + private _sourcesContent; + private _mappings; + private _ignoreList; + file: string | null | undefined; + sourceRoot: string | null | undefined; + constructor({ file, sourceRoot }?: Options); +} +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source?: null, sourceLine?: null, sourceColumn?: null, name?: null, content?: null): void; +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name?: null, content?: string | null): void; +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name: string, content?: string | null): void; +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source?: null; + original?: null; + name?: null; + content?: null; +}): void; +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name?: null; + content?: string | null; +}): void; +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name: string; + content?: string | null; +}): void; +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +export declare const maybeAddSegment: typeof addSegment; +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +export declare const maybeAddMapping: typeof addMapping; +/** + * Adds/removes the content of the source file to the source map. + */ +export declare function setSourceContent(map: GenMapping, source: string, content: string | null): void; +export declare function setIgnore(map: GenMapping, source: string, ignore?: boolean): void; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function toDecodedMap(map: GenMapping): DecodedSourceMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function toEncodedMap(map: GenMapping): EncodedSourceMap; +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +export declare function fromMap(input: SourceMapInput): GenMapping; +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +export declare function allMappings(map: GenMapping): Mapping[]; +//# sourceMappingURL=gen-mapping.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.cts.map b/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.cts.map new file mode 100644 index 0000000..8a2b183 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"gen-mapping.d.ts","sourceRoot":"","sources":["../src/gen-mapping.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAGhE,OAAO,KAAK,EACV,gBAAgB,EAChB,gBAAgB,EAChB,G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,QAYvE;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,UAAU,GAAG,gBAAgB,CAwB9D;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,UAAU,GAAG,gBAAgB,CAO9D;AAED;;GAEG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,cAAc,GAAG,UAAU,CAYzD;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,UAAU,GAAG,OAAO,EAAE,CA0BtD"} \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.mts b/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.mts new file mode 100644 index 0000000..bbc0d89 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.mts @@ -0,0 +1,89 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types.mts'; +export type { DecodedSourceMap, EncodedSourceMap, Mapping }; +export type Options = { + file?: string | null; + sourceRoot?: string | null; +}; +/** + * Provides the state to generate a sourcemap. + */ +export declare class GenMapping { + private _names; + private _sources; + private _sourcesContent; + private _mappings; + private _ignoreList; + file: string | null | undefined; + sourceRoot: string | null | undefined; + constructor({ file, sourceRoot }?: Options); +} +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source?: null, sourceLine?: null, sourceColumn?: null, name?: null, content?: null): void; +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name?: null, content?: string | null): void; +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name: string, content?: string | null): void; +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source?: null; + original?: null; + name?: null; + content?: null; +}): void; +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name?: null; + content?: string | null; +}): void; +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name: string; + content?: string | null; +}): void; +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +export declare const maybeAddSegment: typeof addSegment; +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +export declare const maybeAddMapping: typeof addMapping; +/** + * Adds/removes the content of the source file to the source map. + */ +export declare function setSourceContent(map: GenMapping, source: string, content: string | null): void; +export declare function setIgnore(map: GenMapping, source: string, ignore?: boolean): void; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function toDecodedMap(map: GenMapping): DecodedSourceMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function toEncodedMap(map: GenMapping): EncodedSourceMap; +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +export declare function fromMap(input: SourceMapInput): GenMapping; +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +export declare function allMappings(map: GenMapping): Mapping[]; +//# sourceMappingURL=gen-mapping.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.mts.map b/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.mts.map new file mode 100644 index 0000000..8a2b183 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"gen-mapping.d.ts","sourceRoot":"","sources":["../src/gen-mapping.ts"],"names":[],"mappings":"AAgBA,OAAO,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,IAAI,CAS9F;AAED,wBAAgB,SAAS,CAAC,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,UAAO,QAYvE;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,UAAU,GAAG,gBAAgB,CAwB9D;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,UAAU,GAAG,gBAAgB,CAO9D;AAED;;GAEG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,cAAc,GAAG,UAAU,CAYzD;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,UAAU,GAAG,OAAO,EAAE,CA0BtD"} \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/types/set-array.d.cts b/node_modules/@jridgewell/gen-mapping/types/set-array.d.cts new file mode 100644 index 0000000..5d8cda3 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/types/set-array.d.cts @@ -0,0 +1,33 @@ +type Key = string | number | symbol; +/** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +export declare class SetArray { + private _indexes; + array: readonly T[]; + constructor(); +} +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +export declare function get(setarr: SetArray, key: T): number | undefined; +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +export declare function put(setarr: SetArray, key: T): number; +/** + * Pops the last added item out of the SetArray. + */ +export declare function pop(setarr: SetArray): void; +/** + * Removes the key, if it exists in the set. + */ +export declare function remove(setarr: SetArray, key: T): void; +export {}; +//# sourceMappingURL=set-array.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/types/set-array.d.cts.map b/node_modules/@jridgewell/gen-mapping/types/set-array.d.cts.map new file mode 100644 index 0000000..c52b8bc --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/types/set-array.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"set-array.d.ts","sourceRoot":"","sources":["../src/set-array.ts"],"names":[],"mappings":"AAAA,KAAK,GAAG,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;AAEpC;;;;;;;GAOG;AACH,qBAAa,QAAQ,CAAC,CAAC,SAAS,GAAG,GAAG,GAAG;IACvC,QAAgB,QAAQ,CAAgC;IAChD,KAAK,EAAE,SAAS,CAAC,EAAE,CAAC;;CAM7B;AAeD;;GAEG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,MAAM,GAAG,SAAS,CAElF;AAED;;;GAGG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,MAAM,CAStE;AAED;;GAEG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,IAAI,CAM5D;AAED;;GAEG;AACH,wBAAgB,MAAM,CAAC,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,IAAI,CAYvE"} \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/types/set-array.d.mts b/node_modules/@jridgewell/gen-mapping/types/set-array.d.mts new file mode 100644 index 0000000..5d8cda3 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/types/set-array.d.mts @@ -0,0 +1,33 @@ +type Key = string | number | symbol; +/** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +export declare class SetArray { + private _indexes; + array: readonly T[]; + constructor(); +} +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +export declare function get(setarr: SetArray, key: T): number | undefined; +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +export declare function put(setarr: SetArray, key: T): number; +/** + * Pops the last added item out of the SetArray. + */ +export declare function pop(setarr: SetArray): void; +/** + * Removes the key, if it exists in the set. + */ +export declare function remove(setarr: SetArray, key: T): void; +export {}; +//# sourceMappingURL=set-array.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/types/set-array.d.mts.map b/node_modules/@jridgewell/gen-mapping/types/set-array.d.mts.map new file mode 100644 index 0000000..c52b8bc --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/types/set-array.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"set-array.d.ts","sourceRoot":"","sources":["../src/set-array.ts"],"names":[],"mappings":"AAAA,KAAK,GAAG,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;AAEpC;;;;;;;GAOG;AACH,qBAAa,QAAQ,CAAC,CAAC,SAAS,GAAG,GAAG,GAAG;IACvC,QAAgB,QAAQ,CAAgC;IAChD,KAAK,EAAE,SAAS,CAAC,EAAE,CAAC;;CAM7B;AAeD;;GAEG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,MAAM,GAAG,SAAS,CAElF;AAED;;;GAGG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,MAAM,CAStE;AAED;;GAEG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,IAAI,CAM5D;AAED;;GAEG;AACH,wBAAgB,MAAM,CAAC,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,IAAI,CAYvE"} \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.cts b/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.cts new file mode 100644 index 0000000..6886295 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.cts @@ -0,0 +1,13 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +export type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export {}; +//# sourceMappingURL=sourcemap-segment.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.cts.map b/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.cts.map new file mode 100644 index 0000000..23cdc45 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-segment.d.ts","sourceRoot":"","sources":["../src/sourcemap-segment.ts"],"names":[],"mappings":"AAAA,KAAK,eAAe,GAAG,MAAM,CAAC;AAC9B,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AACzB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AAEzB,MAAM,MAAM,gBAAgB,GACxB,CAAC,eAAe,CAAC,GACjB,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,CAAC,GACzD,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC;AAE1E,eAAO,MAAM,MAAM,IAAI,CAAC;AACxB,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC;AAC7B,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.mts b/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.mts new file mode 100644 index 0000000..6886295 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.mts @@ -0,0 +1,13 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +export type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export {}; +//# sourceMappingURL=sourcemap-segment.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.mts.map b/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.mts.map new file mode 100644 index 0000000..23cdc45 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-segment.d.ts","sourceRoot":"","sources":["../src/sourcemap-segment.ts"],"names":[],"mappings":"AAAA,KAAK,eAAe,GAAG,MAAM,CAAC;AAC9B,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AACzB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AAEzB,MAAM,MAAM,gBAAgB,GACxB,CAAC,eAAe,CAAC,GACjB,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,CAAC,GACzD,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC;AAE1E,eAAO,MAAM,MAAM,IAAI,CAAC;AACxB,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC;AAC7B,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/types/types.d.cts b/node_modules/@jridgewell/gen-mapping/types/types.d.cts new file mode 100644 index 0000000..58da00a --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/types/types.d.cts @@ -0,0 +1,44 @@ +import type { SourceMapSegment } from './sourcemap-segment.cts'; +export interface SourceMapV3 { + file?: string | null; + names: readonly string[]; + sourceRoot?: string; + sources: readonly (string | null)[]; + sourcesContent?: readonly (string | null)[]; + version: 3; + ignoreList?: readonly number[]; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: readonly SourceMapSegment[][]; +} +export interface Pos { + line: number; + column: number; +} +export interface OriginalPos extends Pos { + source: string; +} +export interface BindingExpressionRange { + start: Pos; + expression: string; +} +export type Mapping = { + generated: Pos; + source: undefined; + original: undefined; + name: undefined; +} | { + generated: Pos; + source: string; + original: Pos; + name: string; +} | { + generated: Pos; + source: string; + original: Pos; + name: undefined; +}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/types/types.d.cts.map b/node_modules/@jridgewell/gen-mapping/types/types.d.cts.map new file mode 100644 index 0000000..159e734 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/types/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ACE,SAAS,EAAE,GAAG,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,GAAG,CAAC;IACd,IAAI,EAAE,SAAS,CAAC;CACjB,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/types/types.d.mts b/node_modules/@jridgewell/gen-mapping/types/types.d.mts new file mode 100644 index 0000000..e9837eb --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/types/types.d.mts @@ -0,0 +1,44 @@ +import type { SourceMapSegment } from './sourcemap-segment.mts'; +export interface SourceMapV3 { + file?: string | null; + names: readonly string[]; + sourceRoot?: string; + sources: readonly (string | null)[]; + sourcesContent?: readonly (string | null)[]; + version: 3; + ignoreList?: readonly number[]; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: readonly SourceMapSegment[][]; +} +export interface Pos { + line: number; + column: number; +} +export interface OriginalPos extends Pos { + source: string; +} +export interface BindingExpressionRange { + start: Pos; + expression: string; +} +export type Mapping = { + generated: Pos; + source: undefined; + original: undefined; + name: undefined; +} | { + generated: Pos; + source: string; + original: Pos; + name: string; +} | { + generated: Pos; + source: string; + original: Pos; + name: undefined; +}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/types/types.d.mts.map b/node_modules/@jridgewell/gen-mapping/types/types.d.mts.map new file mode 100644 index 0000000..159e734 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/types/types.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE5D,MAAM,WAAW,WAAW;IAC1B,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IACzB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,SAAS,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IACpC,cAAc,CAAC,EAAE,SAAS,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IAC5C,OAAO,EAAE,CAAC,CAAC;IACX,UAAU,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAChC;AAED,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,QAAQ,EAAE,MAAM,CAAC;CAGlB;AAED,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,QAAQ,EAAE,SAAS,gBAAgB,EAAE,EAAE,CAAC;CAGzC;AAED,MAAM,WAAW,GAAG;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,WAAY,SAAQ,GAAG;IACtC,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,sBAAsB;IACrC,KAAK,EAAE,GAAG,CAAC;IACX,UAAU,EAAE,MAAM,CAAC;CACpB;AAKD,MAAM,MAAM,OAAO,GACf;IACE,SAAS,EAAE,GAAG,CAAC;IACf,MAAM,EAAE,SAAS,CAAC;IAClB,QAAQ,EAAE,SAAS,CAAC;IACpB,IAAI,EAAE,SAAS,CAAC;CACjB,GACD;IACE,SAAS,EAAE,GAAG,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,GAAG,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;CACd,GACD;IACE,SAAS,EAAE,GAAG,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,GAAG,CAAC;IACd,IAAI,EAAE,SAAS,CAAC;CACjB,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/LICENSE b/node_modules/@jridgewell/resolve-uri/LICENSE new file mode 100644 index 0000000..0a81b2a --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/LICENSE @@ -0,0 +1,19 @@ +Copyright 2019 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/README.md b/node_modules/@jridgewell/resolve-uri/README.md new file mode 100644 index 0000000..2fe70df --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/README.md @@ -0,0 +1,40 @@ +# @jridgewell/resolve-uri + +> Resolve a URI relative to an optional base URI + +Resolve any combination of absolute URIs, protocol-realtive URIs, absolute paths, or relative paths. + +## Installation + +```sh +npm install @jridgewell/resolve-uri +``` + +## Usage + +```typescript +function resolve(input: string, base?: string): string; +``` + +```js +import resolve from '@jridgewell/resolve-uri'; + +resolve('foo', 'https://example.com'); // => 'https://example.com/foo' +``` + +| Input | Base | Resolution | Explanation | +|-----------------------|-------------------------|--------------------------------|--------------------------------------------------------------| +| `https://example.com` | _any_ | `https://example.com/` | Input is normalized only | +| `//example.com` | `https://base.com/` | `https://example.com/` | Input inherits the base's protocol | +| `//example.com` | _rest_ | `//example.com/` | Input is normalized only | +| `/example` | `https://base.com/` | `https://base.com/example` | Input inherits the base's origin | +| `/example` | `//base.com/` | `//base.com/example` | Input inherits the base's host and remains protocol relative | +| `/example` | _rest_ | `/example` | Input is normalized only | +| `example` | `https://base.com/dir/` | `https://base.com/dir/example` | Input is joined with the base | +| `example` | `https://base.com/file` | `https://base.com/example` | Input is joined with the base without its file | +| `example` | `//base.com/dir/` | `//base.com/dir/example` | Input is joined with the base's last directory | +| `example` | `//base.com/file` | `//base.com/example` | Input is joined with the base without its file | +| `example` | `/base/dir/` | `/base/dir/example` | Input is joined with the base's last directory | +| `example` | `/base/file` | `/base/example` | Input is joined with the base without its file | +| `example` | `base/dir/` | `base/dir/example` | Input is joined with the base's last directory | +| `example` | `base/file` | `base/example` | Input is joined with the base without its file | diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs new file mode 100644 index 0000000..e958e88 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs @@ -0,0 +1,232 @@ +// Matches the scheme of a URL, eg "http://" +const schemeRegex = /^[\w+.-]+:\/\//; +/** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ +const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; +/** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ +const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; +function isAbsoluteUrl(input) { + return schemeRegex.test(input); +} +function isSchemeRelativeUrl(input) { + return input.startsWith('//'); +} +function isAbsolutePath(input) { + return input.startsWith('/'); +} +function isFileUrl(input) { + return input.startsWith('file:'); +} +function isRelative(input) { + return /^[.?#]/.test(input); +} +function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); +} +function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); +} +function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: 7 /* Absolute */, + }; +} +function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = 6 /* SchemeRelative */; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = 5 /* AbsolutePath */; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? 3 /* Query */ + : input.startsWith('#') + ? 2 /* Hash */ + : 4 /* RelativePath */ + : 1 /* Empty */; + return url; +} +function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} +function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } +} +/** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ +function normalizePath(url, type) { + const rel = type <= 4 /* RelativePath */; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; +} +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== 7 /* Absolute */) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case 1 /* Empty */: + url.hash = baseUrl.hash; + // fall through + case 2 /* Hash */: + url.query = baseUrl.query; + // fall through + case 3 /* Query */: + case 4 /* RelativePath */: + mergePaths(url, baseUrl); + // fall through + case 5 /* AbsolutePath */: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case 6 /* SchemeRelative */: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case 2 /* Hash */: + case 3 /* Query */: + return queryHash; + case 4 /* RelativePath */: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case 5 /* AbsolutePath */: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } +} + +export { resolve as default }; +//# sourceMappingURL=resolve-uri.mjs.map diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map new file mode 100644 index 0000000..1de97d0 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.mjs","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nconst enum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":"AAAA;AACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAErC;;;;;;;;;;AAUA,MAAM,QAAQ,GAAG,0EAA0E,CAAC;AAE5F;;;;;;;;;AASA,MAAM,SAAS,GAAG,iEAAiE,CAAC;AAuBpF,SAAS,aAAa,CAAC,KAAa;IAClC,OAAO,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACjC,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAa;IACxC,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAChC,CAAC;AAED,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,SAAS,CAAC,KAAa;IAC9B,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;AACnC,CAAC;AAED,SAAS,UAAU,CAAC,KAAa;IAC/B,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAa;IACrC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC;IACpC,OAAO,OAAO,CACZ,KAAK,CAAC,CAAC,CAAC,EACR,KAAK,CAAC,CAAC,CAAC,IAAI,E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CAAC,CAAC,CAAC;YAE/B,IAAI,CAAC,IAAI;gBAAE,OAAO,SAAS,IAAI,GAAG,CAAC;YAEnC,IAAI,UAAU,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;;;;gBAIlD,OAAO,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;aAChC;YAED,OAAO,IAAI,GAAG,SAAS,CAAC;SACzB;QAED;YACE,OAAO,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;QAE9B;YACE,OAAO,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;KACpF;AACH;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js new file mode 100644 index 0000000..a783049 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js @@ -0,0 +1,240 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.resolveURI = factory()); +})(this, (function () { 'use strict'; + + // Matches the scheme of a URL, eg "http://" + const schemeRegex = /^[\w+.-]+:\/\//; + /** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ + const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; + /** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ + const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; + function isAbsoluteUrl(input) { + return schemeRegex.test(input); + } + function isSchemeRelativeUrl(input) { + return input.startsWith('//'); + } + function isAbsolutePath(input) { + return input.startsWith('/'); + } + function isFileUrl(input) { + return input.startsWith('file:'); + } + function isRelative(input) { + return /^[.?#]/.test(input); + } + function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); + } + function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); + } + function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: 7 /* Absolute */, + }; + } + function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = 6 /* SchemeRelative */; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = 5 /* AbsolutePath */; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? 3 /* Query */ + : input.startsWith('#') + ? 2 /* Hash */ + : 4 /* RelativePath */ + : 1 /* Empty */; + return url; + } + function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } + } + /** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ + function normalizePath(url, type) { + const rel = type <= 4 /* RelativePath */; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; + } + /** + * Attempts to resolve `input` URL/path relative to `base`. + */ + function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== 7 /* Absolute */) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case 1 /* Empty */: + url.hash = baseUrl.hash; + // fall through + case 2 /* Hash */: + url.query = baseUrl.query; + // fall through + case 3 /* Query */: + case 4 /* RelativePath */: + mergePaths(url, baseUrl); + // fall through + case 5 /* AbsolutePath */: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case 6 /* SchemeRelative */: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case 2 /* Hash */: + case 3 /* Query */: + return queryHash; + case 4 /* RelativePath */: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case 5 /* AbsolutePath */: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } + } + + return resolve; + +})); +//# sourceMappingURL=resolve-uri.umd.js.map diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map new file mode 100644 index 0000000..70a37f2 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.umd.js","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nconst enum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":";;;;;;IAAA;IACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;IAErC;;;;;;;;;;IAUA,MAAM,QAAQ,GAAG,0EAA0E,CAAC;IAE5F;;;;;;;;;IASA,MAAM,SAAS,GAAG,iEAAiE,CAAC;IAuBpF,SAAS,aAAa,CAAC,KAAa;QAClC,OAAO,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IAED,SAAS,mBAAmB,CAAC,KAAa;QACxC,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;IAED,SAAS,cAAc,CAAC,KAAa;QACnC,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC;IAED,SAAS,SAAS,CAAC,KAAa;QAC9B,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACnC,CAAC;IAED,SAAS,UAAU,CAAC,KAAa;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;SAChD;QAED,aAAa,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;QAE9B,MAAM,SAAS,GAAG,GAAG,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC;QACvC,QAAQ,SAAS;;;YAIf,kBAAkB;YAClB;gBACE,OAAO,SAAS,CAAC;YAEnB,2BAA2B;;gBAEzB,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;gBAE/B,IAAI,CAAC,IAAI;oBAAE,OAAO,SAAS,IAAI,GAAG,CAAC;gBAEnC,IAAI,UAAU,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;;;;oBAIlD,OAAO,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;iBAChC;gBAED,OAAO,IAAI,GAAG,SAAS,CAAC;aACzB;YAED;gBACE,OAAO,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;YAE9B;gBACE,OAAO,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;SACpF;IACH;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts b/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts new file mode 100644 index 0000000..b7f0b3b --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts @@ -0,0 +1,4 @@ +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/@jridgewell/resolve-uri/package.json b/node_modules/@jridgewell/resolve-uri/package.json new file mode 100644 index 0000000..02a4c51 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/package.json @@ -0,0 +1,69 @@ +{ + "name": "@jridgewell/resolve-uri", + "version": "3.1.2", + "description": "Resolve a URI relative to an optional base URI", + "keywords": [ + "resolve", + "uri", + "url", + "path" + ], + "author": "Justin Ridgewell ", + "license": "MIT", + "repository": "https://github.com/jridgewell/resolve-uri", + "main": "dist/resolve-uri.umd.js", + "module": "dist/resolve-uri.mjs", + "types": "dist/types/resolve-uri.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/resolve-uri.d.ts", + "browser": "./dist/resolve-uri.umd.js", + "require": "./dist/resolve-uri.umd.js", + "import": "./dist/resolve-uri.mjs" + }, + "./dist/resolve-uri.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "prebuild": "rm -rf dist", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build" + }, + "devDependencies": { + "@jridgewell/resolve-uri-latest": "npm:@jridgewell/resolve-uri@*", + "@rollup/plugin-typescript": "8.3.0", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "c8": "7.11.0", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.66.0", + "typescript": "4.5.5" + } +} diff --git a/node_modules/@jridgewell/sourcemap-codec/LICENSE b/node_modules/@jridgewell/sourcemap-codec/LICENSE new file mode 100644 index 0000000..1f6ce94 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/LICENSE @@ -0,0 +1,19 @@ +Copyright 2024 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@jridgewell/sourcemap-codec/README.md b/node_modules/@jridgewell/sourcemap-codec/README.md new file mode 100644 index 0000000..b3e0708 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/README.md @@ -0,0 +1,264 @@ +# @jridgewell/sourcemap-codec + +Encode/decode the `mappings` property of a [sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). + + +## Why? + +Sourcemaps are difficult to generate and manipulate, because the `mappings` property – the part that actually links the generated code back to the original source – is encoded using an obscure method called [Variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity). On top of that, each segment in the mapping contains offsets rather than absolute indices, which means that you can't look at a segment in isolation – you have to understand the whole sourcemap. + +This package makes the process slightly easier. + + +## Installation + +```bash +npm install @jridgewell/sourcemap-codec +``` + + +## Usage + +```js +import { encode, decode } from '@jridgewell/sourcemap-codec'; + +var decoded = decode( ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); + +assert.deepEqual( decoded, [ + // the first line (of the generated code) has no mappings, + // as shown by the starting semi-colon (which separates lines) + [], + + // the second line contains four (comma-separated) segments + [ + // segments are encoded as you'd expect: + // [ generatedCodeColumn, sourceIndex, sourceCodeLine, sourceCodeColumn, nameIndex ] + + // i.e. the first segment begins at column 2, and maps back to the second column + // of the second line (both zero-based) of the 0th source, and uses the 0th + // name in the `map.names` array + [ 2, 0, 2, 2, 0 ], + + // the remaining segments are 4-length rather than 5-length, + // because they don't map a name + [ 4, 0, 2, 4 ], + [ 6, 0, 2, 5 ], + [ 7, 0, 2, 7 ] + ], + + // the final line contains two segments + [ + [ 2, 1, 10, 19 ], + [ 12, 1, 11, 20 ] + ] +]); + +var encoded = encode( decoded ); +assert.equal( encoded, ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); +``` + +## Benchmarks + +``` +node v20.10.0 + +amp.js.map - 45120 segments + +Decode Memory Usage: +local code 5815135 bytes +@jridgewell/sourcemap-codec 1.4.15 5868160 bytes +sourcemap-codec 5492584 bytes +source-map-0.6.1 13569984 bytes +source-map-0.8.0 6390584 bytes +chrome dev tools 8011136 bytes +Smallest memory usage is sourcemap-codec + +Decode speed: +decode: local code x 492 ops/sec ±1.22% (90 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 499 ops/sec ±1.16% (89 runs sampled) +decode: sourcemap-codec x 376 ops/sec ±1.66% (89 runs sampled) +decode: source-map-0.6.1 x 34.99 ops/sec ±0.94% (48 runs sampled) +decode: source-map-0.8.0 x 351 ops/sec ±0.07% (95 runs sampled) +chrome dev tools x 165 ops/sec ±0.91% (86 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 444248 bytes +@jridgewell/sourcemap-codec 1.4.15 623024 bytes +sourcemap-codec 8696280 bytes +source-map-0.6.1 8745176 bytes +source-map-0.8.0 8736624 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 796 ops/sec ±0.11% (97 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 795 ops/sec ±0.25% (98 runs sampled) +encode: sourcemap-codec x 231 ops/sec ±0.83% (86 runs sampled) +encode: source-map-0.6.1 x 166 ops/sec ±0.57% (86 runs sampled) +encode: source-map-0.8.0 x 203 ops/sec ±0.45% (88 runs sampled) +Fastest is encode: local code,encode: @jridgewell/sourcemap-codec 1.4.15 + + +*** + + +babel.min.js.map - 347793 segments + +Decode Memory Usage: +local code 35424960 bytes +@jridgewell/sourcemap-codec 1.4.15 35424696 bytes +sourcemap-codec 36033464 bytes +source-map-0.6.1 62253704 bytes +source-map-0.8.0 43843920 bytes +chrome dev tools 45111400 bytes +Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15 + +Decode speed: +decode: local code x 38.18 ops/sec ±5.44% (52 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 38.36 ops/sec ±5.02% (52 runs sampled) +decode: sourcemap-codec x 34.05 ops/sec ±4.45% (47 runs sampled) +decode: source-map-0.6.1 x 4.31 ops/sec ±2.76% (15 runs sampled) +decode: source-map-0.8.0 x 55.60 ops/sec ±0.13% (73 runs sampled) +chrome dev tools x 16.94 ops/sec ±3.78% (46 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +local code 2606016 bytes +@jridgewell/sourcemap-codec 1.4.15 2626440 bytes +sourcemap-codec 21152576 bytes +source-map-0.6.1 25023928 bytes +source-map-0.8.0 25256448 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 127 ops/sec ±0.18% (83 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 128 ops/sec ±0.26% (83 runs sampled) +encode: sourcemap-codec x 29.31 ops/sec ±2.55% (53 runs sampled) +encode: source-map-0.6.1 x 18.85 ops/sec ±3.19% (36 runs sampled) +encode: source-map-0.8.0 x 19.34 ops/sec ±1.97% (36 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15 + + +*** + + +preact.js.map - 1992 segments + +Decode Memory Usage: +local code 261696 bytes +@jridgewell/sourcemap-codec 1.4.15 244296 bytes +sourcemap-codec 302816 bytes +source-map-0.6.1 939176 bytes +source-map-0.8.0 336 bytes +chrome dev tools 587368 bytes +Smallest memory usage is source-map-0.8.0 + +Decode speed: +decode: local code x 17,782 ops/sec ±0.32% (97 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 17,863 ops/sec ±0.40% (100 runs sampled) +decode: sourcemap-codec x 12,453 ops/sec ±0.27% (101 runs sampled) +decode: source-map-0.6.1 x 1,288 ops/sec ±1.05% (96 runs sampled) +decode: source-map-0.8.0 x 9,289 ops/sec ±0.27% (101 runs sampled) +chrome dev tools x 4,769 ops/sec ±0.18% (100 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 262944 bytes +@jridgewell/sourcemap-codec 1.4.15 25544 bytes +sourcemap-codec 323048 bytes +source-map-0.6.1 507808 bytes +source-map-0.8.0 507480 bytes +Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15 + +Encode speed: +encode: local code x 24,207 ops/sec ±0.79% (95 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 24,288 ops/sec ±0.48% (96 runs sampled) +encode: sourcemap-codec x 6,761 ops/sec ±0.21% (100 runs sampled) +encode: source-map-0.6.1 x 5,374 ops/sec ±0.17% (99 runs sampled) +encode: source-map-0.8.0 x 5,633 ops/sec ±0.32% (99 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15,encode: local code + + +*** + + +react.js.map - 5726 segments + +Decode Memory Usage: +local code 678816 bytes +@jridgewell/sourcemap-codec 1.4.15 678816 bytes +sourcemap-codec 816400 bytes +source-map-0.6.1 2288864 bytes +source-map-0.8.0 721360 bytes +chrome dev tools 1012512 bytes +Smallest memory usage is local code + +Decode speed: +decode: local code x 6,178 ops/sec ±0.19% (98 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 6,261 ops/sec ±0.22% (100 runs sampled) +decode: sourcemap-codec x 4,472 ops/sec ±0.90% (99 runs sampled) +decode: source-map-0.6.1 x 449 ops/sec ±0.31% (95 runs sampled) +decode: source-map-0.8.0 x 3,219 ops/sec ±0.13% (100 runs sampled) +chrome dev tools x 1,743 ops/sec ±0.20% (99 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 140960 bytes +@jridgewell/sourcemap-codec 1.4.15 159808 bytes +sourcemap-codec 969304 bytes +source-map-0.6.1 930520 bytes +source-map-0.8.0 930248 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 8,013 ops/sec ±0.19% (100 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 7,989 ops/sec ±0.20% (101 runs sampled) +encode: sourcemap-codec x 2,472 ops/sec ±0.21% (99 runs sampled) +encode: source-map-0.6.1 x 2,200 ops/sec ±0.17% (99 runs sampled) +encode: source-map-0.8.0 x 2,220 ops/sec ±0.37% (99 runs sampled) +Fastest is encode: local code + + +*** + + +vscode.map - 2141001 segments + +Decode Memory Usage: +local code 198955264 bytes +@jridgewell/sourcemap-codec 1.4.15 199175352 bytes +sourcemap-codec 199102688 bytes +source-map-0.6.1 386323432 bytes +source-map-0.8.0 244116432 bytes +chrome dev tools 293734280 bytes +Smallest memory usage is local code + +Decode speed: +decode: local code x 3.90 ops/sec ±22.21% (15 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 3.95 ops/sec ±23.53% (15 runs sampled) +decode: sourcemap-codec x 3.82 ops/sec ±17.94% (14 runs sampled) +decode: source-map-0.6.1 x 0.61 ops/sec ±7.81% (6 runs sampled) +decode: source-map-0.8.0 x 9.54 ops/sec ±0.28% (28 runs sampled) +chrome dev tools x 2.18 ops/sec ±10.58% (10 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +local code 13509880 bytes +@jridgewell/sourcemap-codec 1.4.15 13537648 bytes +sourcemap-codec 32540104 bytes +source-map-0.6.1 127531040 bytes +source-map-0.8.0 127535312 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 20.10 ops/sec ±0.19% (38 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 20.26 ops/sec ±0.32% (38 runs sampled) +encode: sourcemap-codec x 5.44 ops/sec ±1.64% (18 runs sampled) +encode: source-map-0.6.1 x 2.30 ops/sec ±4.79% (10 runs sampled) +encode: source-map-0.8.0 x 2.46 ops/sec ±6.53% (10 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15 +``` + +# License + +MIT diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs new file mode 100644 index 0000000..532bab3 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs @@ -0,0 +1,423 @@ +// src/vlq.ts +var comma = ",".charCodeAt(0); +var semicolon = ";".charCodeAt(0); +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var intToChar = new Uint8Array(64); +var charToInt = new Uint8Array(128); +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +function decodeInteger(reader, relative) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -2147483648 | -value; + } + return relative + value; +} +function encodeInteger(builder, num, relative) { + let delta = num - relative; + delta = delta < 0 ? -delta << 1 | 1 : delta << 1; + do { + let clamped = delta & 31; + delta >>>= 5; + if (delta > 0) clamped |= 32; + builder.write(intToChar[clamped]); + } while (delta > 0); + return num; +} +function hasMoreVlq(reader, max) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} + +// src/strings.ts +var bufLength = 1024 * 16; +var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + } +} : { + decode(buf) { + let out = ""; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + } +}; +var StringWriter = class { + constructor() { + this.pos = 0; + this.out = ""; + this.buffer = new Uint8Array(bufLength); + } + write(v) { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + flush() { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } +}; +var StringReader = class { + constructor(buffer) { + this.pos = 0; + this.buffer = buffer; + } + next() { + return this.buffer.charCodeAt(this.pos++); + } + peek() { + return this.buffer.charCodeAt(this.pos); + } + indexOf(char) { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +}; + +// src/scopes.ts +var EMPTY = []; +function decodeOriginalScopes(input) { + const { length } = input; + const reader = new StringReader(input); + const scopes = []; + const stack = []; + let line = 0; + for (; reader.pos < length; reader.pos++) { + line = decodeInteger(reader, line); + const column = decodeInteger(reader, 0); + if (!hasMoreVlq(reader, length)) { + const last = stack.pop(); + last[2] = line; + last[3] = column; + continue; + } + const kind = decodeInteger(reader, 0); + const fields = decodeInteger(reader, 0); + const hasName = fields & 1; + const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]; + let vars = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeInteger(reader, 0); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + scopes.push(scope); + stack.push(scope); + } + return scopes; +} +function encodeOriginalScopes(scopes) { + const writer = new StringWriter(); + for (let i = 0; i < scopes.length; ) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + return writer.flush(); +} +function _encodeOriginalScopes(scopes, index, writer, state) { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + if (index > 0) writer.write(comma); + state[0] = encodeInteger(writer, startLine, state[0]); + encodeInteger(writer, startColumn, 0); + encodeInteger(writer, kind, 0); + const fields = scope.length === 6 ? 1 : 0; + encodeInteger(writer, fields, 0); + if (scope.length === 6) encodeInteger(writer, scope[5], 0); + for (const v of vars) { + encodeInteger(writer, v, 0); + } + for (index++; index < scopes.length; ) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + writer.write(comma); + state[0] = encodeInteger(writer, endLine, state[0]); + encodeInteger(writer, endColumn, 0); + return index; +} +function decodeGeneratedRanges(input) { + const { length } = input; + const reader = new StringReader(input); + const ranges = []; + const stack = []; + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + do { + const semi = reader.indexOf(";"); + let genColumn = 0; + for (; reader.pos < semi; reader.pos++) { + genColumn = decodeInteger(reader, genColumn); + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop(); + last[2] = genLine; + last[3] = genColumn; + continue; + } + const fields = decodeInteger(reader, 0); + const hasDefinition = fields & 1; + const hasCallsite = fields & 2; + const hasScope = fields & 4; + let callsite = null; + let bindings = EMPTY; + let range; + if (hasDefinition) { + const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex); + definitionScopeIndex = decodeInteger( + reader, + definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0 + ); + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex]; + } else { + range = [genLine, genColumn, 0, 0]; + } + range.isScope = !!hasScope; + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0); + callsiteColumn = decodeInteger( + reader, + sameSource && prevLine === callsiteLine ? callsiteColumn : 0 + ); + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeInteger(reader, 0); + let expressionRanges; + if (expressionsCount < -1) { + expressionRanges = [[decodeInteger(reader, 0)]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine = decodeInteger(reader, bindingLine); + bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0); + const expression = decodeInteger(reader, 0); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + ranges.push(range); + stack.push(range); + } + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + return ranges; +} +function encodeGeneratedRanges(ranges) { + if (ranges.length === 0) return ""; + const writer = new StringWriter(); + for (let i = 0; i < ranges.length; ) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + return writer.flush(); +} +function _encodeGeneratedRanges(ranges, index, writer, state) { + const range = ranges[index]; + const { + 0: startLine, + 1: startColumn, + 2: endLine, + 3: endColumn, + isScope, + callsite, + bindings + } = range; + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } else if (index > 0) { + writer.write(comma); + } + state[1] = encodeInteger(writer, range[1], state[1]); + const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0); + encodeInteger(writer, fields, 0); + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + state[2] = encodeInteger(writer, sourcesIndex, state[2]); + state[3] = encodeInteger(writer, scopesIndex, state[3]); + } + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } else if (callLine !== state[5]) { + state[6] = 0; + } + state[4] = encodeInteger(writer, sourcesIndex, state[4]); + state[5] = encodeInteger(writer, callLine, state[5]); + state[6] = encodeInteger(writer, callColumn, state[6]); + } + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) encodeInteger(writer, -binding.length, 0); + const expression = binding[0][0]; + encodeInteger(writer, expression, 0); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine); + bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn); + encodeInteger(writer, expRange[0], 0); + } + } + } + for (index++; index < ranges.length; ) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } else { + writer.write(comma); + } + state[1] = encodeInteger(writer, endColumn, state[1]); + return index; +} +function catchupLine(writer, lastLine, line) { + do { + writer.write(semicolon); + } while (++lastLine < line); +} + +// src/sourcemap-codec.ts +function decode(mappings) { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + do { + const semi = reader.indexOf(";"); + const line = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + while (reader.pos < semi) { + let seg; + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + line.push(seg); + reader.pos++; + } + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + return decoded; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) writer.write(semicolon); + if (line.length === 0) continue; + let genColumn = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) writer.write(comma); + genColumn = encodeInteger(writer, segment[0], genColumn); + if (segment.length === 1) continue; + sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); + sourceLine = encodeInteger(writer, segment[2], sourceLine); + sourceColumn = encodeInteger(writer, segment[3], sourceColumn); + if (segment.length === 4) continue; + namesIndex = encodeInteger(writer, segment[4], namesIndex); + } + } + return writer.flush(); +} +export { + decode, + decodeGeneratedRanges, + decodeOriginalScopes, + encode, + encodeGeneratedRanges, + encodeOriginalScopes +}; +//# sourceMappingURL=sourcemap-codec.mjs.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map new file mode 100644 index 0000000..c276844 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../src/vlq.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G,UAAU;AACzD,qBAAe,cAAc,QAAQ,QAAQ,CAAC,GAAG,YAAY;AAE7D,UAAI,QAAQ,WAAW,EAAG;AAC1B,mBAAa,cAAc,QAAQ,QAAQ,CAAC,GAAG,UAAU;AAAA,IAC3D;AAAA,EACF;AAEA,SAAO,OAAO,MAAM;AACtB;", + "names": [] +} diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js new file mode 100644 index 0000000..2d8e459 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js @@ -0,0 +1,464 @@ +(function (global, factory) { + if (typeof exports === 'object' && typeof module !== 'undefined') { + factory(module); + module.exports = def(module); + } else if (typeof define === 'function' && define.amd) { + define(['module'], function(mod) { + factory.apply(this, arguments); + mod.exports = def(mod); + }); + } else { + const mod = { exports: {} }; + factory(mod); + global = typeof globalThis !== 'undefined' ? globalThis : global || self; + global.sourcemapCodec = def(mod); + } + function def(m) { return 'default' in m.exports ? m.exports.default : m.exports; } +})(this, (function (module) { +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/sourcemap-codec.ts +var sourcemap_codec_exports = {}; +__export(sourcemap_codec_exports, { + decode: () => decode, + decodeGeneratedRanges: () => decodeGeneratedRanges, + decodeOriginalScopes: () => decodeOriginalScopes, + encode: () => encode, + encodeGeneratedRanges: () => encodeGeneratedRanges, + encodeOriginalScopes: () => encodeOriginalScopes +}); +module.exports = __toCommonJS(sourcemap_codec_exports); + +// src/vlq.ts +var comma = ",".charCodeAt(0); +var semicolon = ";".charCodeAt(0); +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var intToChar = new Uint8Array(64); +var charToInt = new Uint8Array(128); +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +function decodeInteger(reader, relative) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -2147483648 | -value; + } + return relative + value; +} +function encodeInteger(builder, num, relative) { + let delta = num - relative; + delta = delta < 0 ? -delta << 1 | 1 : delta << 1; + do { + let clamped = delta & 31; + delta >>>= 5; + if (delta > 0) clamped |= 32; + builder.write(intToChar[clamped]); + } while (delta > 0); + return num; +} +function hasMoreVlq(reader, max) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} + +// src/strings.ts +var bufLength = 1024 * 16; +var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + } +} : { + decode(buf) { + let out = ""; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + } +}; +var StringWriter = class { + constructor() { + this.pos = 0; + this.out = ""; + this.buffer = new Uint8Array(bufLength); + } + write(v) { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + flush() { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } +}; +var StringReader = class { + constructor(buffer) { + this.pos = 0; + this.buffer = buffer; + } + next() { + return this.buffer.charCodeAt(this.pos++); + } + peek() { + return this.buffer.charCodeAt(this.pos); + } + indexOf(char) { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +}; + +// src/scopes.ts +var EMPTY = []; +function decodeOriginalScopes(input) { + const { length } = input; + const reader = new StringReader(input); + const scopes = []; + const stack = []; + let line = 0; + for (; reader.pos < length; reader.pos++) { + line = decodeInteger(reader, line); + const column = decodeInteger(reader, 0); + if (!hasMoreVlq(reader, length)) { + const last = stack.pop(); + last[2] = line; + last[3] = column; + continue; + } + const kind = decodeInteger(reader, 0); + const fields = decodeInteger(reader, 0); + const hasName = fields & 1; + const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]; + let vars = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeInteger(reader, 0); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + scopes.push(scope); + stack.push(scope); + } + return scopes; +} +function encodeOriginalScopes(scopes) { + const writer = new StringWriter(); + for (let i = 0; i < scopes.length; ) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + return writer.flush(); +} +function _encodeOriginalScopes(scopes, index, writer, state) { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + if (index > 0) writer.write(comma); + state[0] = encodeInteger(writer, startLine, state[0]); + encodeInteger(writer, startColumn, 0); + encodeInteger(writer, kind, 0); + const fields = scope.length === 6 ? 1 : 0; + encodeInteger(writer, fields, 0); + if (scope.length === 6) encodeInteger(writer, scope[5], 0); + for (const v of vars) { + encodeInteger(writer, v, 0); + } + for (index++; index < scopes.length; ) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + writer.write(comma); + state[0] = encodeInteger(writer, endLine, state[0]); + encodeInteger(writer, endColumn, 0); + return index; +} +function decodeGeneratedRanges(input) { + const { length } = input; + const reader = new StringReader(input); + const ranges = []; + const stack = []; + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + do { + const semi = reader.indexOf(";"); + let genColumn = 0; + for (; reader.pos < semi; reader.pos++) { + genColumn = decodeInteger(reader, genColumn); + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop(); + last[2] = genLine; + last[3] = genColumn; + continue; + } + const fields = decodeInteger(reader, 0); + const hasDefinition = fields & 1; + const hasCallsite = fields & 2; + const hasScope = fields & 4; + let callsite = null; + let bindings = EMPTY; + let range; + if (hasDefinition) { + const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex); + definitionScopeIndex = decodeInteger( + reader, + definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0 + ); + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex]; + } else { + range = [genLine, genColumn, 0, 0]; + } + range.isScope = !!hasScope; + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0); + callsiteColumn = decodeInteger( + reader, + sameSource && prevLine === callsiteLine ? callsiteColumn : 0 + ); + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeInteger(reader, 0); + let expressionRanges; + if (expressionsCount < -1) { + expressionRanges = [[decodeInteger(reader, 0)]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine = decodeInteger(reader, bindingLine); + bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0); + const expression = decodeInteger(reader, 0); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + ranges.push(range); + stack.push(range); + } + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + return ranges; +} +function encodeGeneratedRanges(ranges) { + if (ranges.length === 0) return ""; + const writer = new StringWriter(); + for (let i = 0; i < ranges.length; ) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + return writer.flush(); +} +function _encodeGeneratedRanges(ranges, index, writer, state) { + const range = ranges[index]; + const { + 0: startLine, + 1: startColumn, + 2: endLine, + 3: endColumn, + isScope, + callsite, + bindings + } = range; + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } else if (index > 0) { + writer.write(comma); + } + state[1] = encodeInteger(writer, range[1], state[1]); + const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0); + encodeInteger(writer, fields, 0); + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + state[2] = encodeInteger(writer, sourcesIndex, state[2]); + state[3] = encodeInteger(writer, scopesIndex, state[3]); + } + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } else if (callLine !== state[5]) { + state[6] = 0; + } + state[4] = encodeInteger(writer, sourcesIndex, state[4]); + state[5] = encodeInteger(writer, callLine, state[5]); + state[6] = encodeInteger(writer, callColumn, state[6]); + } + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) encodeInteger(writer, -binding.length, 0); + const expression = binding[0][0]; + encodeInteger(writer, expression, 0); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine); + bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn); + encodeInteger(writer, expRange[0], 0); + } + } + } + for (index++; index < ranges.length; ) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } else { + writer.write(comma); + } + state[1] = encodeInteger(writer, endColumn, state[1]); + return index; +} +function catchupLine(writer, lastLine, line) { + do { + writer.write(semicolon); + } while (++lastLine < line); +} + +// src/sourcemap-codec.ts +function decode(mappings) { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + do { + const semi = reader.indexOf(";"); + const line = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + while (reader.pos < semi) { + let seg; + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + line.push(seg); + reader.pos++; + } + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + return decoded; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) writer.write(semicolon); + if (line.length === 0) continue; + let genColumn = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) writer.write(comma); + genColumn = encodeInteger(writer, segment[0], genColumn); + if (segment.length === 1) continue; + sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); + sourceLine = encodeInteger(writer, segment[2], sourceLine); + sourceColumn = encodeInteger(writer, segment[3], sourceColumn); + if (segment.length === 4) continue; + namesIndex = encodeInteger(writer, segment[4], namesIndex); + } + } + return writer.flush(); +} +})); +//# sourceMappingURL=sourcemap-codec.umd.js.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map new file mode 100644 index 0000000..abc18d2 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../src/sourcemap-codec.ts", "../src/vlq.ts", "../src/strings.ts", "../src/scopes.ts"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,QAAQ,IAAI,WAAW,CAAC;AAC9B,IAAM,YAAY,IAAI,WAAW,CAAC;AAEzC,IAAM,QAAQ;AACd,IAAM,YAAY,IAAI,WAAW,EAAE;AACnC,IAAM,YAAY,IAAI,WAAW,GAAG;AAEpC,SAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,QAAM,IAAI,MAAM,WAAW,CAAC;AAC5B,YAAU,CAAC,IAAI;AACf,YAAU,CAAC,IAAI;AACjB;AAEO,SAAS,cAAc,QAAsB,UAA0B;AAC5E,MAAI,QAAQ;AACZ,MAAI,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M,OAAO;AAAA,EACtB,SAAS,OAAO,OAAO;AAEvB,SAAO;AACT;AAEA,SAAS,KAAK,MAA0B;AACtC,OAAK,KAAK,cAAc;AAC1B;AAEA,SAAS,eAAe,GAAqB,GAA6B;AACxE,SAAO,EAAE,CAAC,IAAI,EAAE,CAAC;AACnB;AAIO,SAAS,OAAO,SAA8C;AACnE,QAAM,SAAS,IAAI,aAAa;AAChC,MAAI,eAAe;AACnB,MAAI,aAAa;AACjB,MAAI,eAAe;AACnB,MAAI,aAAa;AAEjB,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,OAAO,QAAQ,CAAC;AACtB,QAAI,IAAI,EAAG,QAAO,MAAM,SAAS;AACjC,QAAI,KAAK,WAAW,EAAG;AAEvB,QAAI,YAAY;AAEhB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,YAAM,UAAU,KAAK,CAAC;AACtB,UAAI,IAAI,EAAG,QAAO,MAAM,KAAK;AAE7B,kBAAY,cAAc,QAAQ,QAAQ,CAAC,GAAG,SAAS;AAEvD,UAAI,QAAQ,WAAW,EAAG;AAC1B,qBAAe,cAAc,QAAQ,QAAQ,CAAC,GAAG,YAAY;AAC7D,mBAAa,cAAc,QAAQ,QAAQ,CAAC,GAAG,UAAU;AACzD,qBAAe,cAAc,QAAQ,QAAQ,CAAC,GAAG,YAAY;AAE7D,UAAI,QAAQ,WAAW,EAAG;AAC1B,mBAAa,cAAc,QAAQ,QAAQ,CAAC,GAAG,UAAU;AAAA,IAC3D;AAAA,EACF;AAEA,SAAO,OAAO,MAAM;AACtB;", + "names": [] +} diff --git a/node_modules/@jridgewell/sourcemap-codec/package.json b/node_modules/@jridgewell/sourcemap-codec/package.json new file mode 100644 index 0000000..da55137 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/package.json @@ -0,0 +1,63 @@ +{ + "name": "@jridgewell/sourcemap-codec", + "version": "1.5.5", + "description": "Encode/decode sourcemap mappings", + "keywords": [ + "sourcemap", + "vlq" + ], + "main": "dist/sourcemap-codec.umd.js", + "module": "dist/sourcemap-codec.mjs", + "types": "types/sourcemap-codec.d.cts", + "files": [ + "dist", + "src", + "types" + ], + "exports": { + ".": [ + { + "import": { + "types": "./types/sourcemap-codec.d.mts", + "default": "./dist/sourcemap-codec.mjs" + }, + "default": { + "types": "./types/sourcemap-codec.d.cts", + "default": "./dist/sourcemap-codec.umd.js" + } + }, + "./dist/sourcemap-codec.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:code benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.js", + "build": "run-s -n build:code build:types", + "build:code": "node ../../esbuild.mjs sourcemap-codec.ts", + "build:types": "run-s build:types:force build:types:emit build:types:mts", + "build:types:force": "rimraf tsconfig.build.tsbuildinfo", + "build:types:emit": "tsc --project tsconfig.build.json", + "build:types:mts": "node ../../mts-types.mjs", + "clean": "run-s -n clean:code clean:types", + "clean:code": "tsc --build --clean tsconfig.build.json", + "clean:types": "rimraf dist types", + "test": "run-s -n test:types test:only test:format", + "test:format": "prettier --check '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:types": "eslint '{src,test}/**/*.ts'", + "lint": "run-s -n lint:types lint:format", + "lint:format": "npm run test:format -- --write", + "lint:types": "npm run test:types -- --fix", + "prepublishOnly": "npm run-s -n build test" + }, + "homepage": "https://github.com/jridgewell/sourcemaps/tree/main/packages/sourcemap-codec", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemaps.git", + "directory": "packages/sourcemap-codec" + }, + "author": "Justin Ridgewell ", + "license": "MIT" +} diff --git a/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts b/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts new file mode 100644 index 0000000..d194c2f --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts @@ -0,0 +1,345 @@ +import { StringReader, StringWriter } from './strings'; +import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq'; + +const EMPTY: any[] = []; + +type Line = number; +type Column = number; +type Kind = number; +type Name = number; +type Var = number; +type SourcesIndex = number; +type ScopesIndex = number; + +type Mix = (A & O) | (B & O); + +export type OriginalScope = Mix< + [Line, Column, Line, Column, Kind], + [Line, Column, Line, Column, Kind, Name], + { vars: Var[] } +>; + +export type GeneratedRange = Mix< + [Line, Column, Line, Column], + [Line, Column, Line, Column, SourcesIndex, ScopesIndex], + { + callsite: CallSite | null; + bindings: Binding[]; + isScope: boolean; + } +>; +export type CallSite = [SourcesIndex, Line, Column]; +type Binding = BindingExpressionRange[]; +export type BindingExpressionRange = [Name] | [Name, Line, Column]; + +export function decodeOriginalScopes(input: string): OriginalScope[] { + const { length } = input; + const reader = new StringReader(input); + const scopes: OriginalScope[] = []; + const stack: OriginalScope[] = []; + let line = 0; + + for (; reader.pos < length; reader.pos++) { + line = decodeInteger(reader, line); + const column = decodeInteger(reader, 0); + + if (!hasMoreVlq(reader, length)) { + const last = stack.pop()!; + last[2] = line; + last[3] = column; + continue; + } + + const kind = decodeInteger(reader, 0); + const fields = decodeInteger(reader, 0); + const hasName = fields & 0b0001; + + const scope: OriginalScope = ( + hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind] + ) as OriginalScope; + + let vars: Var[] = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeInteger(reader, 0); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + + scopes.push(scope); + stack.push(scope); + } + + return scopes; +} + +export function encodeOriginalScopes(scopes: OriginalScope[]): string { + const writer = new StringWriter(); + + for (let i = 0; i < scopes.length; ) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + + return writer.flush(); +} + +function _encodeOriginalScopes( + scopes: OriginalScope[], + index: number, + writer: StringWriter, + state: [ + number, // GenColumn + ], +): number { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + + if (index > 0) writer.write(comma); + + state[0] = encodeInteger(writer, startLine, state[0]); + encodeInteger(writer, startColumn, 0); + encodeInteger(writer, kind, 0); + + const fields = scope.length === 6 ? 0b0001 : 0; + encodeInteger(writer, fields, 0); + if (scope.length === 6) encodeInteger(writer, scope[5], 0); + + for (const v of vars) { + encodeInteger(writer, v, 0); + } + + for (index++; index < scopes.length; ) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || (l === endLine && c >= endColumn)) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + + writer.write(comma); + state[0] = encodeInteger(writer, endLine, state[0]); + encodeInteger(writer, endColumn, 0); + + return index; +} + +export function decodeGeneratedRanges(input: string): GeneratedRange[] { + const { length } = input; + const reader = new StringReader(input); + const ranges: GeneratedRange[] = []; + const stack: GeneratedRange[] = []; + + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + + do { + const semi = reader.indexOf(';'); + let genColumn = 0; + + for (; reader.pos < semi; reader.pos++) { + genColumn = decodeInteger(reader, genColumn); + + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop()!; + last[2] = genLine; + last[3] = genColumn; + continue; + } + + const fields = decodeInteger(reader, 0); + const hasDefinition = fields & 0b0001; + const hasCallsite = fields & 0b0010; + const hasScope = fields & 0b0100; + + let callsite: CallSite | null = null; + let bindings: Binding[] = EMPTY; + let range: GeneratedRange; + if (hasDefinition) { + const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex); + definitionScopeIndex = decodeInteger( + reader, + definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0, + ); + + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex] as GeneratedRange; + } else { + range = [genLine, genColumn, 0, 0] as GeneratedRange; + } + + range.isScope = !!hasScope; + + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0); + callsiteColumn = decodeInteger( + reader, + sameSource && prevLine === callsiteLine ? callsiteColumn : 0, + ); + + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeInteger(reader, 0); + let expressionRanges: BindingExpressionRange[]; + if (expressionsCount < -1) { + expressionRanges = [[decodeInteger(reader, 0)]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine = decodeInteger(reader, bindingLine); + bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0); + const expression = decodeInteger(reader, 0); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + + ranges.push(range); + stack.push(range); + } + + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + + return ranges; +} + +export function encodeGeneratedRanges(ranges: GeneratedRange[]): string { + if (ranges.length === 0) return ''; + + const writer = new StringWriter(); + + for (let i = 0; i < ranges.length; ) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + + return writer.flush(); +} + +function _encodeGeneratedRanges( + ranges: GeneratedRange[], + index: number, + writer: StringWriter, + state: [ + number, // GenLine + number, // GenColumn + number, // DefSourcesIndex + number, // DefScopesIndex + number, // CallSourcesIndex + number, // CallLine + number, // CallColumn + ], +): number { + const range = ranges[index]; + const { + 0: startLine, + 1: startColumn, + 2: endLine, + 3: endColumn, + isScope, + callsite, + bindings, + } = range; + + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } else if (index > 0) { + writer.write(comma); + } + + state[1] = encodeInteger(writer, range[1], state[1]); + + const fields = + (range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0); + encodeInteger(writer, fields, 0); + + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + state[2] = encodeInteger(writer, sourcesIndex, state[2]); + state[3] = encodeInteger(writer, scopesIndex, state[3]); + } + + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite!; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } else if (callLine !== state[5]) { + state[6] = 0; + } + state[4] = encodeInteger(writer, sourcesIndex, state[4]); + state[5] = encodeInteger(writer, callLine, state[5]); + state[6] = encodeInteger(writer, callColumn, state[6]); + } + + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) encodeInteger(writer, -binding.length, 0); + const expression = binding[0][0]; + encodeInteger(writer, expression, 0); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + bindingStartLine = encodeInteger(writer, expRange[1]!, bindingStartLine); + bindingStartColumn = encodeInteger(writer, expRange[2]!, bindingStartColumn); + encodeInteger(writer, expRange[0]!, 0); + } + } + } + + for (index++; index < ranges.length; ) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || (l === endLine && c >= endColumn)) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } else { + writer.write(comma); + } + state[1] = encodeInteger(writer, endColumn, state[1]); + + return index; +} + +function catchupLine(writer: StringWriter, lastLine: number, line: number) { + do { + writer.write(semicolon); + } while (++lastLine < line); +} diff --git a/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts b/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts new file mode 100644 index 0000000..a81f894 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts @@ -0,0 +1,111 @@ +import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq'; +import { StringWriter, StringReader } from './strings'; + +export { + decodeOriginalScopes, + encodeOriginalScopes, + decodeGeneratedRanges, + encodeGeneratedRanges, +} from './scopes'; +export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes'; + +export type SourceMapSegment = + | [number] + | [number, number, number, number] + | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; + +export function decode(mappings: string): SourceMapMappings { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded: SourceMapMappings = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + + do { + const semi = reader.indexOf(';'); + const line: SourceMapLine = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + + while (reader.pos < semi) { + let seg: SourceMapSegment; + + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + + line.push(seg); + reader.pos++; + } + + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + + return decoded; +} + +function sort(line: SourceMapSegment[]) { + line.sort(sortComparator); +} + +function sortComparator(a: SourceMapSegment, b: SourceMapSegment): number { + return a[0] - b[0]; +} + +export function encode(decoded: SourceMapMappings): string; +export function encode(decoded: Readonly): string; +export function encode(decoded: Readonly): string { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) writer.write(semicolon); + if (line.length === 0) continue; + + let genColumn = 0; + + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) writer.write(comma); + + genColumn = encodeInteger(writer, segment[0], genColumn); + + if (segment.length === 1) continue; + sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); + sourceLine = encodeInteger(writer, segment[2], sourceLine); + sourceColumn = encodeInteger(writer, segment[3], sourceColumn); + + if (segment.length === 4) continue; + namesIndex = encodeInteger(writer, segment[4], namesIndex); + } + } + + return writer.flush(); +} diff --git a/node_modules/@jridgewell/sourcemap-codec/src/strings.ts b/node_modules/@jridgewell/sourcemap-codec/src/strings.ts new file mode 100644 index 0000000..d161965 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/src/strings.ts @@ -0,0 +1,65 @@ +const bufLength = 1024 * 16; + +// Provide a fallback for older environments. +const td = + typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf: Uint8Array): string { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf: Uint8Array): string { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; + +export class StringWriter { + pos = 0; + private out = ''; + private buffer = new Uint8Array(bufLength); + + write(v: number): void { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + + flush(): string { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } +} + +export class StringReader { + pos = 0; + declare private buffer: string; + + constructor(buffer: string) { + this.buffer = buffer; + } + + next(): number { + return this.buffer.charCodeAt(this.pos++); + } + + peek(): number { + return this.buffer.charCodeAt(this.pos); + } + + indexOf(char: string): number { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +} diff --git a/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts b/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts new file mode 100644 index 0000000..a42c681 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts @@ -0,0 +1,55 @@ +import type { StringReader, StringWriter } from './strings'; + +export const comma = ','.charCodeAt(0); +export const semicolon = ';'.charCodeAt(0); + +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const intToChar = new Uint8Array(64); // 64 possible chars. +const charToInt = new Uint8Array(128); // z is 122 in ASCII + +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} + +export function decodeInteger(reader: StringReader, relative: number): number { + let value = 0; + let shift = 0; + let integer = 0; + + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + + const shouldNegate = value & 1; + value >>>= 1; + + if (shouldNegate) { + value = -0x80000000 | -value; + } + + return relative + value; +} + +export function encodeInteger(builder: StringWriter, num: number, relative: number): number { + let delta = num - relative; + + delta = delta < 0 ? (-delta << 1) | 1 : delta << 1; + do { + let clamped = delta & 0b011111; + delta >>>= 5; + if (delta > 0) clamped |= 0b100000; + builder.write(intToChar[clamped]); + } while (delta > 0); + + return num; +} + +export function hasMoreVlq(reader: StringReader, max: number) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} diff --git a/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts new file mode 100644 index 0000000..c583c75 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts @@ -0,0 +1,50 @@ +type Line = number; +type Column = number; +type Kind = number; +type Name = number; +type Var = number; +type SourcesIndex = number; +type ScopesIndex = number; +type Mix = (A & O) | (B & O); +export type OriginalScope = Mix<[ + Line, + Column, + Line, + Column, + Kind +], [ + Line, + Column, + Line, + Column, + Kind, + Name +], { + vars: Var[]; +}>; +export type GeneratedRange = Mix<[ + Line, + Column, + Line, + Column +], [ + Line, + Column, + Line, + Column, + SourcesIndex, + ScopesIndex +], { + callsite: CallSite | null; + bindings: Binding[]; + isScope: boolean; +}>; +export type CallSite = [SourcesIndex, Line, Column]; +type Binding = BindingExpressionRange[]; +export type BindingExpressionRange = [Name] | [Name, Line, Column]; +export declare function decodeOriginalScopes(input: string): OriginalScope[]; +export declare function encodeOriginalScopes(scopes: OriginalScope[]): string; +export declare function decodeGeneratedRanges(input: string): GeneratedRange[]; +export declare function encodeGeneratedRanges(ranges: GeneratedRange[]): string; +export {}; +//# sourceMappingURL=scopes.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts.map b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts.map new file mode 100644 index 0000000..630e647 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../src/scopes.ts"],"names":[],"mappings":"AAKA,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,MAAM,GAAG,MAAM,CAAC;AACrB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,GAAG,GAAG,MAAM,CAAC;AAClB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,WAAW,GAAG,MAAM,CAAC;AAE1B,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAEtC,MAAM,MAAM,aAAa,GAAG,GAAG,CAC7B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;CAAC,EAClC;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,IAAI;CAAC,EACxC;IAAE,IAAI,EAAE,GAAG,EAAE,CAAA;CAAE,CAChB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,GAAG,CAC9B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;CAAC,EAC5B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,YAAY;IAAE,WAAW;CAAC,EACvD;IACE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;CAClB,CACF,CAAC;AACF,MAAM,MAAM,QAAQ,GAAG,CAAC,YAAY,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AACpD,KAAK,OAAO,GAAG,sBAAsB,EAAE,CAAC;AACxC,MAAM,MAAM,sBAAsB,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAEnE,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,CAyCnE;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,CAQpE;AA2CD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,EAAE,CAoGrE;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,CAUtE"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts new file mode 100644 index 0000000..c583c75 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts @@ -0,0 +1,50 @@ +type Line = number; +type Column = number; +type Kind = number; +type Name = number; +type Var = number; +type SourcesIndex = number; +type ScopesIndex = number; +type Mix = (A & O) | (B & O); +export type OriginalScope = Mix<[ + Line, + Column, + Line, + Column, + Kind +], [ + Line, + Column, + Line, + Column, + Kind, + Name +], { + vars: Var[]; +}>; +export type GeneratedRange = Mix<[ + Line, + Column, + Line, + Column +], [ + Line, + Column, + Line, + Column, + SourcesIndex, + ScopesIndex +], { + callsite: CallSite | null; + bindings: Binding[]; + isScope: boolean; +}>; +export type CallSite = [SourcesIndex, Line, Column]; +type Binding = BindingExpressionRange[]; +export type BindingExpressionRange = [Name] | [Name, Line, Column]; +export declare function decodeOriginalScopes(input: string): OriginalScope[]; +export declare function encodeOriginalScopes(scopes: OriginalScope[]): string; +export declare function decodeGeneratedRanges(input: string): GeneratedRange[]; +export declare function encodeGeneratedRanges(ranges: GeneratedRange[]): string; +export {}; +//# sourceMappingURL=scopes.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts.map b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts.map new file mode 100644 index 0000000..630e647 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../src/scopes.ts"],"names":[],"mappings":"AAKA,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,MAAM,GAAG,MAAM,CAAC;AACrB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,GAAG,GAAG,MAAM,CAAC;AAClB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,WAAW,GAAG,MAAM,CAAC;AAE1B,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CA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.cts b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts new file mode 100644 index 0000000..5f35e22 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts @@ -0,0 +1,9 @@ +export { decodeOriginalScopes, encodeOriginalScopes, decodeGeneratedRanges, encodeGeneratedRanges, } from './scopes.cts'; +export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes.cts'; +export type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; +//# sourceMappingURL=sourcemap-codec.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map new file mode 100644 index 0000000..7123d52 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.d.ts","sourceRoot":"","sources":["../src/sourcemap-codec.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,UAAU,CAAC;AAClB,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAEhG,MAAM,MAAM,gBAAgB,GACxB,CAAC,MAAM,CAAC,GACR,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,GAChC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7C,MAAM,MAAM,aAAa,GAAG,gBAAgB,EAAE,CAAC;AAC/C,MAAM,MAAM,iBAAiB,GAAG,aAAa,EAAE,CAAC;AAEhD,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB,CAiD1D;AAUD,wBAAgB,MAAM,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAAC;AAC3D,wBAAgB,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts new file mode 100644 index 0000000..199fb9f --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts @@ -0,0 +1,9 @@ +export { decodeOriginalScopes, encodeOriginalScopes, decodeGeneratedRanges, encodeGeneratedRanges, } from './scopes.mts'; +export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes.mts'; +export type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; +//# sourceMappingURL=sourcemap-codec.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map new file mode 100644 index 0000000..7123d52 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.d.ts","sourceRoot":"","sources":["../src/sourcemap-codec.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,UAAU,CAAC;AAClB,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAEhG,MAAM,MAAM,gBAAgB,GACxB,CAAC,MAAM,CAAC,GACR,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,GAChC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7C,MAAM,MAAM,aAAa,GAAG,gBAAgB,EAAE,CAAC;AAC/C,MAAM,MAAM,iBAAiB,GAAG,aAAa,EAAE,CAAC;AAEhD,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB,CAiD1D;AAUD,wBAAgB,MAAM,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAAC;AAC3D,wBAAgB,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts new file mode 100644 index 0000000..62faceb --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts @@ -0,0 +1,16 @@ +export declare class StringWriter { + pos: number; + private out; + private buffer; + write(v: number): void; + flush(): string; +} +export declare class StringReader { + pos: number; + private buffer; + constructor(buffer: string); + next(): number; + peek(): number; + indexOf(char: string): number; +} +//# sourceMappingURL=strings.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts.map b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts.map new file mode 100644 index 0000000..d3602da --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"strings.d.ts","sourceRoot":"","sources":["../src/strings.ts"],"names":[],"mappings":"AAuBA,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,MAAM,CAA6B;IAE3C,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;IAStB,KAAK,IAAI,MAAM;CAIhB;AAED,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,QAAgB,MAAM,CAAS;gBAEnB,MAAM,EAAE,MAAM;IAI1B,IAAI,IAAI,MAAM;IAId,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAK9B"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts new file mode 100644 index 0000000..62faceb --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts @@ -0,0 +1,16 @@ +export declare class StringWriter { + pos: number; + private out; + private buffer; + write(v: number): void; + flush(): string; +} +export declare class StringReader { + pos: number; + private buffer; + constructor(buffer: string); + next(): number; + peek(): number; + indexOf(char: string): number; +} +//# sourceMappingURL=strings.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map new file mode 100644 index 0000000..d3602da --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"strings.d.ts","sourceRoot":"","sources":["../src/strings.ts"],"names":[],"mappings":"AAuBA,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,MAAM,CAA6B;IAE3C,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;IAStB,KAAK,IAAI,MAAM;CAIhB;AAED,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,QAAgB,MAAM,CAAS;gBAEnB,MAAM,EAAE,MAAM;IAI1B,IAAI,IAAI,MAAM;IAId,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAK9B"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts new file mode 100644 index 0000000..dbd6602 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts @@ -0,0 +1,7 @@ +import type { StringReader, StringWriter } from './strings.cts'; +export declare const comma: number; +export declare const semicolon: number; +export declare function decodeInteger(reader: StringReader, relative: number): number; +export declare function encodeInteger(builder: StringWriter, num: number, relative: number): number; +export declare function hasMoreVlq(reader: StringReader, max: number): boolean; +//# sourceMappingURL=vlq.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map new file mode 100644 index 0000000..6fdc356 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"vlq.d.ts","sourceRoot":"","sources":["../src/vlq.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5D,eAAO,MAAM,KAAK,QAAoB,CAAC;AACvC,eAAO,MAAM,SAAS,QAAoB,CAAC;AAY3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAoB5E;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAY1F;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,WAG3D"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts new file mode 100644 index 0000000..2c739bc --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts @@ -0,0 +1,7 @@ +import type { StringReader, StringWriter } from './strings.mts'; +export declare const comma: number; +export declare const semicolon: number; +export declare function decodeInteger(reader: StringReader, relative: number): number; +export declare function encodeInteger(builder: StringWriter, num: number, relative: number): number; +export declare function hasMoreVlq(reader: StringReader, max: number): boolean; +//# sourceMappingURL=vlq.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map new file mode 100644 index 0000000..6fdc356 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"vlq.d.ts","sourceRoot":"","sources":["../src/vlq.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5D,eAAO,MAAM,KAAK,QAAoB,CAAC;AACvC,eAAO,MAAM,SAAS,QAAoB,CAAC;AAY3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAoB5E;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAY1F;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,WAG3D"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/LICENSE b/node_modules/@jridgewell/trace-mapping/LICENSE new file mode 100644 index 0000000..1f6ce94 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2024 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@jridgewell/trace-mapping/README.md b/node_modules/@jridgewell/trace-mapping/README.md new file mode 100644 index 0000000..9fc0ed0 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/README.md @@ -0,0 +1,348 @@ +# @jridgewell/trace-mapping + +> Trace the original position through a source map + +`trace-mapping` allows you to take the line and column of an output file and trace it to the +original location in the source file through a source map. + +You may already be familiar with the [`source-map`][source-map] package's `SourceMapConsumer`. This +provides the same `originalPositionFor` and `generatedPositionFor` API, without requiring WASM. + +## Installation + +```sh +npm install @jridgewell/trace-mapping +``` + +## Usage + +```typescript +import { + TraceMap, + originalPositionFor, + generatedPositionFor, + sourceContentFor, + isIgnored, +} from '@jridgewell/trace-mapping'; + +const tracer = new TraceMap({ + version: 3, + sources: ['input.js'], + sourcesContent: ['content of input.js'], + names: ['foo'], + mappings: 'KAyCIA', + ignoreList: [], +}); + +// Lines start at line 1, columns at column 0. +const traced = originalPositionFor(tracer, { line: 1, column: 5 }); +assert.deepEqual(traced, { + source: 'input.js', + line: 42, + column: 4, + name: 'foo', +}); + +const content = sourceContentFor(tracer, traced.source); +assert.strictEqual(content, 'content for input.js'); + +const generated = generatedPositionFor(tracer, { + source: 'input.js', + line: 42, + column: 4, +}); +assert.deepEqual(generated, { + line: 1, + column: 5, +}); + +const ignored = isIgnored(tracer, 'input.js'); +assert.equal(ignored, false); +``` + +We also provide a lower level API to get the actual segment that matches our line and column. Unlike +`originalPositionFor`, `traceSegment` uses a 0-base for `line`: + +```typescript +import { traceSegment } from '@jridgewell/trace-mapping'; + +// line is 0-base. +const traced = traceSegment(tracer, /* line */ 0, /* column */ 5); + +// Segments are [outputColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] +// Again, line is 0-base and so is sourceLine +assert.deepEqual(traced, [5, 0, 41, 4, 0]); +``` + +### SectionedSourceMaps + +The sourcemap spec defines a special `sections` field that's designed to handle concatenation of +output code with associated sourcemaps. This type of sourcemap is rarely used (no major build tool +produces it), but if you are hand coding a concatenation you may need it. We provide an `AnyMap` +helper that can receive either a regular sourcemap or a `SectionedSourceMap` and returns a +`TraceMap` instance: + +```typescript +import { AnyMap } from '@jridgewell/trace-mapping'; +const fooOutput = 'foo'; +const barOutput = 'bar'; +const output = [fooOutput, barOutput].join('\n'); + +const sectioned = new AnyMap({ + version: 3, + sections: [ + { + // 0-base line and column + offset: { line: 0, column: 0 }, + // fooOutput's sourcemap + map: { + version: 3, + sources: ['foo.js'], + names: ['foo'], + mappings: 'AAAAA', + }, + }, + { + // barOutput's sourcemap will not affect the first line, only the second + offset: { line: 1, column: 0 }, + map: { + version: 3, + sources: ['bar.js'], + names: ['bar'], + mappings: 'AAAAA', + }, + }, + ], +}); + +const traced = originalPositionFor(sectioned, { + line: 2, + column: 0, +}); + +assert.deepEqual(traced, { + source: 'bar.js', + line: 1, + column: 0, + name: 'bar', +}); +``` + +## Benchmarks + +``` +node v20.10.0 + +amp.js.map - 45120 segments + +Memory Usage: +trace-mapping decoded 414164 bytes +trace-mapping encoded 6274352 bytes +source-map-js 10968904 bytes +source-map-0.6.1 17587160 bytes +source-map-0.8.0 8812155 bytes +Chrome dev tools 8672912 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 205 ops/sec ±0.19% (88 runs sampled) +trace-mapping: encoded JSON input x 405 ops/sec ±1.47% (88 runs sampled) +trace-mapping: decoded Object input x 4,645 ops/sec ±0.15% (98 runs sampled) +trace-mapping: encoded Object input x 458 ops/sec ±1.63% (91 runs sampled) +source-map-js: encoded Object input x 75.48 ops/sec ±1.64% (67 runs sampled) +source-map-0.6.1: encoded Object input x 39.37 ops/sec ±1.44% (53 runs sampled) +Chrome dev tools: encoded Object input x 150 ops/sec ±1.76% (79 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed (random): +trace-mapping: decoded originalPositionFor x 44,946 ops/sec ±0.16% (99 runs sampled) +trace-mapping: encoded originalPositionFor x 37,995 ops/sec ±1.81% (89 runs sampled) +source-map-js: encoded originalPositionFor x 9,230 ops/sec ±1.36% (93 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 8,057 ops/sec ±0.84% (96 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 28,198 ops/sec ±1.12% (91 runs sampled) +Chrome dev tools: encoded originalPositionFor x 46,276 ops/sec ±1.35% (95 runs sampled) +Fastest is Chrome dev tools: encoded originalPositionFor + +Trace speed (ascending): +trace-mapping: decoded originalPositionFor x 204,406 ops/sec ±0.19% (97 runs sampled) +trace-mapping: encoded originalPositionFor x 196,695 ops/sec ±0.24% (99 runs sampled) +source-map-js: encoded originalPositionFor x 11,948 ops/sec ±0.94% (99 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 10,730 ops/sec ±0.36% (100 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 51,427 ops/sec ±0.21% (98 runs sampled) +Chrome dev tools: encoded originalPositionFor x 162,615 ops/sec ±0.18% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +babel.min.js.map - 347793 segments + +Memory Usage: +trace-mapping decoded 18504 bytes +trace-mapping encoded 35428008 bytes +source-map-js 51676808 bytes +source-map-0.6.1 63367136 bytes +source-map-0.8.0 43158400 bytes +Chrome dev tools 50721552 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 17.82 ops/sec ±6.35% (35 runs sampled) +trace-mapping: encoded JSON input x 31.57 ops/sec ±7.50% (43 runs sampled) +trace-mapping: decoded Object input x 867 ops/sec ±0.74% (94 runs sampled) +trace-mapping: encoded Object input x 33.83 ops/sec ±7.66% (46 runs sampled) +source-map-js: encoded Object input x 6.58 ops/sec ±3.31% (20 runs sampled) +source-map-0.6.1: encoded Object input x 4.23 ops/sec ±3.43% (15 runs sampled) +Chrome dev tools: encoded Object input x 22.14 ops/sec ±3.79% (41 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed (random): +trace-mapping: decoded originalPositionFor x 78,234 ops/sec ±1.48% (29 runs sampled) +trace-mapping: encoded originalPositionFor x 60,761 ops/sec ±1.35% (21 runs sampled) +source-map-js: encoded originalPositionFor x 51,448 ops/sec ±2.17% (89 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 47,221 ops/sec ±1.99% (15 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 84,002 ops/sec ±1.45% (27 runs sampled) +Chrome dev tools: encoded originalPositionFor x 106,457 ops/sec ±1.38% (37 runs sampled) +Fastest is Chrome dev tools: encoded originalPositionFor + +Trace speed (ascending): +trace-mapping: decoded originalPositionFor x 930,943 ops/sec ±0.25% (99 runs sampled) +trace-mapping: encoded originalPositionFor x 843,545 ops/sec ±0.34% (97 runs sampled) +source-map-js: encoded originalPositionFor x 114,510 ops/sec ±1.37% (36 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 87,412 ops/sec ±0.72% (92 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 197,709 ops/sec ±0.89% (59 runs sampled) +Chrome dev tools: encoded originalPositionFor x 688,983 ops/sec ±0.33% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +preact.js.map - 1992 segments + +Memory Usage: +trace-mapping decoded 33136 bytes +trace-mapping encoded 254240 bytes +source-map-js 837488 bytes +source-map-0.6.1 961928 bytes +source-map-0.8.0 54384 bytes +Chrome dev tools 709680 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 3,709 ops/sec ±0.13% (99 runs sampled) +trace-mapping: encoded JSON input x 6,447 ops/sec ±0.22% (101 runs sampled) +trace-mapping: decoded Object input x 83,062 ops/sec ±0.23% (100 runs sampled) +trace-mapping: encoded Object input x 14,980 ops/sec ±0.28% (100 runs sampled) +source-map-js: encoded Object input x 2,544 ops/sec ±0.16% (99 runs sampled) +source-map-0.6.1: encoded Object input x 1,221 ops/sec ±0.37% (97 runs sampled) +Chrome dev tools: encoded Object input x 4,241 ops/sec ±0.39% (93 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed (random): +trace-mapping: decoded originalPositionFor x 91,028 ops/sec ±0.14% (94 runs sampled) +trace-mapping: encoded originalPositionFor x 84,348 ops/sec ±0.26% (98 runs sampled) +source-map-js: encoded originalPositionFor x 26,998 ops/sec ±0.23% (98 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 18,049 ops/sec ±0.26% (100 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 41,916 ops/sec ±0.28% (98 runs sampled) +Chrome dev tools: encoded originalPositionFor x 88,616 ops/sec ±0.14% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + +Trace speed (ascending): +trace-mapping: decoded originalPositionFor x 319,960 ops/sec ±0.16% (100 runs sampled) +trace-mapping: encoded originalPositionFor x 302,153 ops/sec ±0.18% (100 runs sampled) +source-map-js: encoded originalPositionFor x 35,574 ops/sec ±0.19% (100 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 19,943 ops/sec ±0.12% (101 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 54,648 ops/sec ±0.20% (99 runs sampled) +Chrome dev tools: encoded originalPositionFor x 278,319 ops/sec ±0.17% (102 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +react.js.map - 5726 segments + +Memory Usage: +trace-mapping decoded 10872 bytes +trace-mapping encoded 681512 bytes +source-map-js 2563944 bytes +source-map-0.6.1 2150864 bytes +source-map-0.8.0 88680 bytes +Chrome dev tools 1149576 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 1,887 ops/sec ±0.28% (99 runs sampled) +trace-mapping: encoded JSON input x 4,749 ops/sec ±0.48% (97 runs sampled) +trace-mapping: decoded Object input x 74,236 ops/sec ±0.11% (99 runs sampled) +trace-mapping: encoded Object input x 5,752 ops/sec ±0.38% (100 runs sampled) +source-map-js: encoded Object input x 806 ops/sec ±0.19% (97 runs sampled) +source-map-0.6.1: encoded Object input x 418 ops/sec ±0.33% (94 runs sampled) +Chrome dev tools: encoded Object input x 1,524 ops/sec ±0.57% (92 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed (random): +trace-mapping: decoded originalPositionFor x 620,201 ops/sec ±0.33% (96 runs sampled) +trace-mapping: encoded originalPositionFor x 579,548 ops/sec ±0.35% (97 runs sampled) +source-map-js: encoded originalPositionFor x 230,983 ops/sec ±0.62% (54 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 158,145 ops/sec ±0.80% (46 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 343,801 ops/sec ±0.55% (96 runs sampled) +Chrome dev tools: encoded originalPositionFor x 659,649 ops/sec ±0.49% (98 runs sampled) +Fastest is Chrome dev tools: encoded originalPositionFor + +Trace speed (ascending): +trace-mapping: decoded originalPositionFor x 2,368,079 ops/sec ±0.32% (98 runs sampled) +trace-mapping: encoded originalPositionFor x 2,134,039 ops/sec ±2.72% (87 runs sampled) +source-map-js: encoded originalPositionFor x 290,120 ops/sec ±2.49% (82 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 187,613 ops/sec ±0.86% (49 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 479,569 ops/sec ±0.65% (96 runs sampled) +Chrome dev tools: encoded originalPositionFor x 2,048,414 ops/sec ±0.24% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +vscode.map - 2141001 segments + +Memory Usage: +trace-mapping decoded 5206584 bytes +trace-mapping encoded 208370336 bytes +source-map-js 278493008 bytes +source-map-0.6.1 391564048 bytes +source-map-0.8.0 257508787 bytes +Chrome dev tools 291053000 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 1.63 ops/sec ±33.88% (9 runs sampled) +trace-mapping: encoded JSON input x 3.29 ops/sec ±36.13% (13 runs sampled) +trace-mapping: decoded Object input x 103 ops/sec ±0.93% (77 runs sampled) +trace-mapping: encoded Object input x 5.42 ops/sec ±28.54% (19 runs sampled) +source-map-js: encoded Object input x 1.07 ops/sec ±13.84% (7 runs sampled) +source-map-0.6.1: encoded Object input x 0.60 ops/sec ±2.43% (6 runs sampled) +Chrome dev tools: encoded Object input x 2.61 ops/sec ±22.00% (11 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed (random): +trace-mapping: decoded originalPositionFor x 257,019 ops/sec ±0.97% (93 runs sampled) +trace-mapping: encoded originalPositionFor x 179,163 ops/sec ±0.83% (92 runs sampled) +source-map-js: encoded originalPositionFor x 73,337 ops/sec ±1.35% (87 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 38,797 ops/sec ±1.66% (88 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 107,758 ops/sec ±1.94% (45 runs sampled) +Chrome dev tools: encoded originalPositionFor x 188,550 ops/sec ±1.85% (79 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + +Trace speed (ascending): +trace-mapping: decoded originalPositionFor x 447,621 ops/sec ±3.64% (94 runs sampled) +trace-mapping: encoded originalPositionFor x 323,698 ops/sec ±5.20% (88 runs sampled) +source-map-js: encoded originalPositionFor x 78,387 ops/sec ±1.69% (89 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 41,016 ops/sec ±3.01% (25 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 124,204 ops/sec ±0.90% (92 runs sampled) +Chrome dev tools: encoded originalPositionFor x 230,087 ops/sec ±2.61% (93 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor +``` + +[source-map]: https://www.npmjs.com/package/source-map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs new file mode 100644 index 0000000..251117c --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs @@ -0,0 +1,504 @@ +// src/trace-mapping.ts +import { encode, decode } from "@jridgewell/sourcemap-codec"; + +// src/resolve.ts +import resolveUri from "@jridgewell/resolve-uri"; + +// src/strip-filename.ts +function stripFilename(path) { + if (!path) return ""; + const index = path.lastIndexOf("/"); + return path.slice(0, index + 1); +} + +// src/resolve.ts +function resolver(mapUrl, sourceRoot) { + const from = stripFilename(mapUrl); + const prefix = sourceRoot ? sourceRoot + "/" : ""; + return (source) => resolveUri(prefix + (source || ""), from); +} + +// src/sourcemap-segment.ts +var COLUMN = 0; +var SOURCES_INDEX = 1; +var SOURCE_LINE = 2; +var SOURCE_COLUMN = 3; +var NAMES_INDEX = 4; +var REV_GENERATED_LINE = 1; +var REV_GENERATED_COLUMN = 2; + +// src/sort.ts +function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) return mappings; + if (!owned) mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} +function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) return i; + } + return mappings.length; +} +function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; +} +function sortSegments(line, owned) { + if (!owned) line = line.slice(); + return line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; +} + +// src/binary-search.ts +var found = false; +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + (high - low >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1 + }; +} +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + low = lastIndex === -1 ? 0 : lastIndex; + } else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return state.lastIndex = binarySearch(haystack, needle, low, high); +} + +// src/by-source.ts +function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) continue; + const sourceIndex2 = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex2]; + const originalLine = originalSource[sourceLine] || (originalSource[sourceLine] = []); + const memo = memos[sourceIndex2]; + let index = upperBound( + originalLine, + sourceColumn, + memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine) + ); + memo.lastIndex = ++index; + insert(originalLine, index, [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +function buildNullArray() { + return { __proto__: null }; +} + +// src/types.ts +function parse(map) { + return typeof map === "string" ? JSON.parse(map) : map; +} + +// src/flatten-map.ts +var FlattenMap = function(map, mapUrl) { + const parsed = parse(map); + if (!("sections" in parsed)) { + return new TraceMap(parsed, mapUrl); + } + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + const ignoreList = []; + recurse( + parsed, + mapUrl, + mappings, + sources, + sourcesContent, + names, + ignoreList, + 0, + 0, + Infinity, + Infinity + ); + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + ignoreList + }; + return presortedDecodedMap(joined); +}; +function recurse(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + addSection( + map, + mapUrl, + mappings, + sources, + sourcesContent, + names, + ignoreList, + lineOffset + offset.line, + columnOffset + offset.column, + sl, + sc + ); + } +} +function addSection(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { + const parsed = parse(input); + if ("sections" in parsed) return recurse(...arguments); + const map = new TraceMap(parsed, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map; + append(sources, resolvedSources); + append(names, map.names); + if (contents) append(sourcesContent, contents); + else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null); + if (ignores) for (let i = 0; i < ignores.length; i++) ignoreList.push(ignores[i] + sourcesOffset); + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + if (lineI > stopLine) return; + const out = getLine(mappings, lineI); + const cOffset = i === 0 ? columnOffset : 0; + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + if (lineI === stopLine && column >= stopColumn) return; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push( + seg.length === 4 ? [column, sourcesIndex, sourceLine, sourceColumn] : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]] + ); + } + } +} +function append(arr, other) { + for (let i = 0; i < other.length; i++) arr.push(other[i]); +} +function getLine(arr, index) { + for (let i = arr.length; i <= index; i++) arr[i] = []; + return arr[index]; +} + +// src/trace-mapping.ts +var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)"; +var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)"; +var LEAST_UPPER_BOUND = -1; +var GREATEST_LOWER_BOUND = 1; +var TraceMap = class { + constructor(map, mapUrl) { + const isString = typeof map === "string"; + if (!isString && map._decodedMemo) return map; + const parsed = parse(map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names || []; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0; + const resolve = resolver(mapUrl, sourceRoot); + this.resolvedSources = sources.map(resolve); + const { mappings } = parsed; + if (typeof mappings === "string") { + this._encoded = mappings; + this._decoded = void 0; + } else if (Array.isArray(mappings)) { + this._encoded = void 0; + this._decoded = maybeSort(mappings, isString); + } else if (parsed.sections) { + throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`); + } else { + throw new Error(`invalid source map: ${JSON.stringify(parsed)}`); + } + this._decodedMemo = memoizedState(); + this._bySources = void 0; + this._bySourceMemos = void 0; + } +}; +function cast(map) { + return map; +} +function encodedMappings(map) { + var _a, _b; + return (_b = (_a = cast(map))._encoded) != null ? _b : _a._encoded = encode(cast(map)._decoded); +} +function decodedMappings(map) { + var _a; + return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded)); +} +function traceSegment(map, line, column) { + const decoded = decodedMappings(map); + if (line >= decoded.length) return null; + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + GREATEST_LOWER_BOUND + ); + return index === -1 ? null : segments[index]; +} +function originalPositionFor(map, needle) { + let { line, column, bias } = needle; + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + if (line >= decoded.length) return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + bias || GREATEST_LOWER_BOUND + ); + if (index === -1) return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping( + resolvedSources[segment[SOURCES_INDEX]], + segment[SOURCE_LINE] + 1, + segment[SOURCE_COLUMN], + segment.length === 5 ? names[segment[NAMES_INDEX]] : null + ); +} +function generatedPositionFor(map, needle) { + const { source, line, column, bias } = needle; + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); +} +function allGeneratedPositionsFor(map, needle) { + const { source, line, column, bias } = needle; + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); +} +function eachMapping(map, cb) { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name + }); + } + } +} +function sourceIndex(map, source) { + const { sources, resolvedSources } = map; + let index = sources.indexOf(source); + if (index === -1) index = resolvedSources.indexOf(source); + return index; +} +function sourceContentFor(map, source) { + const { sourcesContent } = map; + if (sourcesContent == null) return null; + const index = sourceIndex(map, source); + return index === -1 ? null : sourcesContent[index]; +} +function isIgnored(map, source) { + const { ignoreList } = map; + if (ignoreList == null) return false; + const index = sourceIndex(map, source); + return index === -1 ? false : ignoreList.includes(index); +} +function presortedDecodedMap(map, mapUrl) { + const tracer = new TraceMap(clone(map, []), mapUrl); + cast(tracer)._decoded = map.mappings; + return tracer; +} +function decodedMap(map) { + return clone(map, decodedMappings(map)); +} +function encodedMap(map) { + return clone(map, encodedMappings(map)); +} +function clone(map, mappings) { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + ignoreList: map.ignoreList || map.x_google_ignoreList + }; +} +function OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function GMapping(line, column) { + return { line, column }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } else if (bias === LEAST_UPPER_BOUND) index++; + if (index === -1 || index === segments.length) return -1; + return index; +} +function sliceGeneratedPositions(segments, memo, line, column, bias) { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + if (!found && bias === LEAST_UPPER_BOUND) min++; + if (min === -1 || min === segments.length) return []; + const matchedColumn = found ? column : segments[min][COLUMN]; + if (!found) min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; +} +function generatedPosition(map, source, line, column, bias, all) { + var _a; + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex2 = sources.indexOf(source); + if (sourceIndex2 === -1) sourceIndex2 = resolvedSources.indexOf(source); + if (sourceIndex2 === -1) return all ? [] : GMapping(null, null); + const generated = (_a = cast(map))._bySources || (_a._bySources = buildBySources( + decodedMappings(map), + cast(map)._bySourceMemos = sources.map(memoizedState) + )); + const segments = generated[sourceIndex2][line]; + if (segments == null) return all ? [] : GMapping(null, null); + const memo = cast(map)._bySourceMemos[sourceIndex2]; + if (all) return sliceGeneratedPositions(segments, memo, line, column, bias); + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) return GMapping(null, null); + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); +} +export { + FlattenMap as AnyMap, + FlattenMap, + GREATEST_LOWER_BOUND, + LEAST_UPPER_BOUND, + TraceMap, + allGeneratedPositionsFor, + decodedMap, + decodedMappings, + eachMapping, + encodedMap, + encodedMappings, + generatedPositionFor, + isIgnored, + originalPositionFor, + presortedDecodedMap, + sourceContentFor, + traceSegment +}; +//# sourceMappingURL=trace-mapping.mjs.map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map new file mode 100644 index 0000000..a3cdb8f --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../src/trace-mapping.ts", "../src/resolve.ts", "../src/strip-filename.ts", "../src/sourcemap-segment.ts", "../src/sort.ts", "../src/binary-search.ts", "../src/by-source.ts", "../src/types.ts", "../src/flatten-map.ts"], + "mappings": ";AAAA,SAAS,QAAQ,cAAc;;;ACA/B,OAAO,gBAAgB;;;ACGR,SAAR,cAA+B,MAAyC;AAC7E,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,QAAQ,K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,IAC1C,gBAAgB,GAAG;AAAA,IAClB,KAAK,GAAG,EAAE,iBAAiB,QAAQ,IAAI,aAAa;AAAA,EACvD;AAEA,QAAM,WAAW,UAAUA,YAAW,EAAE,IAAI;AAC5C,MAAI,YAAY,KAAM,QAAO,MAAM,CAAC,IAAI,SAAS,MAAM,IAAI;AAE3D,QAAM,OAAO,KAAK,GAAG,EAAE,eAAgBA,YAAW;AAElD,MAAI,IAAK,QAAO,wBAAwB,UAAU,MAAM,MAAM,QAAQ,IAAI;AAE1E,QAAM,QAAQ,qBAAqB,UAAU,MAAM,MAAM,QAAQ,IAAI;AACrE,MAAI,UAAU,GAAI,QAAO,SAAS,MAAM,IAAI;AAE5C,QAAM,UAAU,SAAS,KAAK;AAC9B,SAAO,SAAS,QAAQ,kBAAkB,IAAI,GAAG,QAAQ,oBAAoB,CAAC;AAChF;", + "names": ["sourceIndex", "sourceIndex"] +} diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js new file mode 100644 index 0000000..ec7f478 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js @@ -0,0 +1,570 @@ +(function (global, factory) { + if (typeof exports === 'object' && typeof module !== 'undefined') { + factory(module, require('@jridgewell/resolve-uri'), require('@jridgewell/sourcemap-codec')); + module.exports = def(module); + } else if (typeof define === 'function' && define.amd) { + define(['module', '@jridgewell/resolve-uri', '@jridgewell/sourcemap-codec'], function(mod) { + factory.apply(this, arguments); + mod.exports = def(mod); + }); + } else { + const mod = { exports: {} }; + factory(mod, global.resolveURI, global.sourcemapCodec); + global = typeof globalThis !== 'undefined' ? globalThis : global || self; + global.traceMapping = def(mod); + } + function def(m) { return 'default' in m.exports ? m.exports.default : m.exports; } +})(this, (function (module, require_resolveURI, require_sourcemapCodec) { +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// umd:@jridgewell/sourcemap-codec +var require_sourcemap_codec = __commonJS({ + "umd:@jridgewell/sourcemap-codec"(exports, module2) { + module2.exports = require_sourcemapCodec; + } +}); + +// umd:@jridgewell/resolve-uri +var require_resolve_uri = __commonJS({ + "umd:@jridgewell/resolve-uri"(exports, module2) { + module2.exports = require_resolveURI; + } +}); + +// src/trace-mapping.ts +var trace_mapping_exports = {}; +__export(trace_mapping_exports, { + AnyMap: () => FlattenMap, + FlattenMap: () => FlattenMap, + GREATEST_LOWER_BOUND: () => GREATEST_LOWER_BOUND, + LEAST_UPPER_BOUND: () => LEAST_UPPER_BOUND, + TraceMap: () => TraceMap, + allGeneratedPositionsFor: () => allGeneratedPositionsFor, + decodedMap: () => decodedMap, + decodedMappings: () => decodedMappings, + eachMapping: () => eachMapping, + encodedMap: () => encodedMap, + encodedMappings: () => encodedMappings, + generatedPositionFor: () => generatedPositionFor, + isIgnored: () => isIgnored, + originalPositionFor: () => originalPositionFor, + presortedDecodedMap: () => presortedDecodedMap, + sourceContentFor: () => sourceContentFor, + traceSegment: () => traceSegment +}); +module.exports = __toCommonJS(trace_mapping_exports); +var import_sourcemap_codec = __toESM(require_sourcemap_codec()); + +// src/resolve.ts +var import_resolve_uri = __toESM(require_resolve_uri()); + +// src/strip-filename.ts +function stripFilename(path) { + if (!path) return ""; + const index = path.lastIndexOf("/"); + return path.slice(0, index + 1); +} + +// src/resolve.ts +function resolver(mapUrl, sourceRoot) { + const from = stripFilename(mapUrl); + const prefix = sourceRoot ? sourceRoot + "/" : ""; + return (source) => (0, import_resolve_uri.default)(prefix + (source || ""), from); +} + +// src/sourcemap-segment.ts +var COLUMN = 0; +var SOURCES_INDEX = 1; +var SOURCE_LINE = 2; +var SOURCE_COLUMN = 3; +var NAMES_INDEX = 4; +var REV_GENERATED_LINE = 1; +var REV_GENERATED_COLUMN = 2; + +// src/sort.ts +function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) return mappings; + if (!owned) mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} +function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) return i; + } + return mappings.length; +} +function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; +} +function sortSegments(line, owned) { + if (!owned) line = line.slice(); + return line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; +} + +// src/binary-search.ts +var found = false; +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + (high - low >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1 + }; +} +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + low = lastIndex === -1 ? 0 : lastIndex; + } else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return state.lastIndex = binarySearch(haystack, needle, low, high); +} + +// src/by-source.ts +function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) continue; + const sourceIndex2 = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex2]; + const originalLine = originalSource[sourceLine] || (originalSource[sourceLine] = []); + const memo = memos[sourceIndex2]; + let index = upperBound( + originalLine, + sourceColumn, + memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine) + ); + memo.lastIndex = ++index; + insert(originalLine, index, [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +function buildNullArray() { + return { __proto__: null }; +} + +// src/types.ts +function parse(map) { + return typeof map === "string" ? JSON.parse(map) : map; +} + +// src/flatten-map.ts +var FlattenMap = function(map, mapUrl) { + const parsed = parse(map); + if (!("sections" in parsed)) { + return new TraceMap(parsed, mapUrl); + } + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + const ignoreList = []; + recurse( + parsed, + mapUrl, + mappings, + sources, + sourcesContent, + names, + ignoreList, + 0, + 0, + Infinity, + Infinity + ); + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + ignoreList + }; + return presortedDecodedMap(joined); +}; +function recurse(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + addSection( + map, + mapUrl, + mappings, + sources, + sourcesContent, + names, + ignoreList, + lineOffset + offset.line, + columnOffset + offset.column, + sl, + sc + ); + } +} +function addSection(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { + const parsed = parse(input); + if ("sections" in parsed) return recurse(...arguments); + const map = new TraceMap(parsed, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map; + append(sources, resolvedSources); + append(names, map.names); + if (contents) append(sourcesContent, contents); + else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null); + if (ignores) for (let i = 0; i < ignores.length; i++) ignoreList.push(ignores[i] + sourcesOffset); + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + if (lineI > stopLine) return; + const out = getLine(mappings, lineI); + const cOffset = i === 0 ? columnOffset : 0; + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + if (lineI === stopLine && column >= stopColumn) return; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push( + seg.length === 4 ? [column, sourcesIndex, sourceLine, sourceColumn] : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]] + ); + } + } +} +function append(arr, other) { + for (let i = 0; i < other.length; i++) arr.push(other[i]); +} +function getLine(arr, index) { + for (let i = arr.length; i <= index; i++) arr[i] = []; + return arr[index]; +} + +// src/trace-mapping.ts +var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)"; +var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)"; +var LEAST_UPPER_BOUND = -1; +var GREATEST_LOWER_BOUND = 1; +var TraceMap = class { + constructor(map, mapUrl) { + const isString = typeof map === "string"; + if (!isString && map._decodedMemo) return map; + const parsed = parse(map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names || []; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0; + const resolve = resolver(mapUrl, sourceRoot); + this.resolvedSources = sources.map(resolve); + const { mappings } = parsed; + if (typeof mappings === "string") { + this._encoded = mappings; + this._decoded = void 0; + } else if (Array.isArray(mappings)) { + this._encoded = void 0; + this._decoded = maybeSort(mappings, isString); + } else if (parsed.sections) { + throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`); + } else { + throw new Error(`invalid source map: ${JSON.stringify(parsed)}`); + } + this._decodedMemo = memoizedState(); + this._bySources = void 0; + this._bySourceMemos = void 0; + } +}; +function cast(map) { + return map; +} +function encodedMappings(map) { + var _a, _b; + return (_b = (_a = cast(map))._encoded) != null ? _b : _a._encoded = (0, import_sourcemap_codec.encode)(cast(map)._decoded); +} +function decodedMappings(map) { + var _a; + return (_a = cast(map))._decoded || (_a._decoded = (0, import_sourcemap_codec.decode)(cast(map)._encoded)); +} +function traceSegment(map, line, column) { + const decoded = decodedMappings(map); + if (line >= decoded.length) return null; + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + GREATEST_LOWER_BOUND + ); + return index === -1 ? null : segments[index]; +} +function originalPositionFor(map, needle) { + let { line, column, bias } = needle; + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + if (line >= decoded.length) return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + bias || GREATEST_LOWER_BOUND + ); + if (index === -1) return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping( + resolvedSources[segment[SOURCES_INDEX]], + segment[SOURCE_LINE] + 1, + segment[SOURCE_COLUMN], + segment.length === 5 ? names[segment[NAMES_INDEX]] : null + ); +} +function generatedPositionFor(map, needle) { + const { source, line, column, bias } = needle; + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); +} +function allGeneratedPositionsFor(map, needle) { + const { source, line, column, bias } = needle; + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); +} +function eachMapping(map, cb) { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name + }); + } + } +} +function sourceIndex(map, source) { + const { sources, resolvedSources } = map; + let index = sources.indexOf(source); + if (index === -1) index = resolvedSources.indexOf(source); + return index; +} +function sourceContentFor(map, source) { + const { sourcesContent } = map; + if (sourcesContent == null) return null; + const index = sourceIndex(map, source); + return index === -1 ? null : sourcesContent[index]; +} +function isIgnored(map, source) { + const { ignoreList } = map; + if (ignoreList == null) return false; + const index = sourceIndex(map, source); + return index === -1 ? false : ignoreList.includes(index); +} +function presortedDecodedMap(map, mapUrl) { + const tracer = new TraceMap(clone(map, []), mapUrl); + cast(tracer)._decoded = map.mappings; + return tracer; +} +function decodedMap(map) { + return clone(map, decodedMappings(map)); +} +function encodedMap(map) { + return clone(map, encodedMappings(map)); +} +function clone(map, mappings) { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + ignoreList: map.ignoreList || map.x_google_ignoreList + }; +} +function OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function GMapping(line, column) { + return { line, column }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } else if (bias === LEAST_UPPER_BOUND) index++; + if (index === -1 || index === segments.length) return -1; + return index; +} +function sliceGeneratedPositions(segments, memo, line, column, bias) { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + if (!found && bias === LEAST_UPPER_BOUND) min++; + if (min === -1 || min === segments.length) return []; + const matchedColumn = found ? column : segments[min][COLUMN]; + if (!found) min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; +} +function generatedPosition(map, source, line, column, bias, all) { + var _a; + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex2 = sources.indexOf(source); + if (sourceIndex2 === -1) sourceIndex2 = resolvedSources.indexOf(source); + if (sourceIndex2 === -1) return all ? [] : GMapping(null, null); + const generated = (_a = cast(map))._bySources || (_a._bySources = buildBySources( + decodedMappings(map), + cast(map)._bySourceMemos = sources.map(memoizedState) + )); + const segments = generated[sourceIndex2][line]; + if (segments == null) return all ? [] : GMapping(null, null); + const memo = cast(map)._bySourceMemos[sourceIndex2]; + if (all) return sliceGeneratedPositions(segments, memo, line, column, bias); + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) return GMapping(null, null); + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); +} +})); +//# sourceMappingURL=trace-mapping.umd.js.map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map new file mode 100644 index 0000000..5794325 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["umd:@jridgewell/sourcemap-codec", "umd:@jridgewell/resolve-uri", "../src/trace-mapping.ts", "../src/resolve.ts", "../src/strip-filename.ts", "../src/sourcemap-segment.ts", "../src/sort.ts", "../src/binary-search.ts", "../src/by-source.ts", "../src/types.ts", "../src/flatten-map.ts"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,6CAAAA,SAAA;AAAA,IAAAA,QAAO,UAAU;AAAA;AAAA;;;ACAjB;AAAA,yCAAAC,SAAA;AAAA,IAAAA,QAAO,UAAU;AAAA;AAAA;;;ACAjB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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B,QAAQ,MAAM;AACpE,MAAIA,iBAAgB,GAAI,QAAO,MAAM,CAAC,IAAI,SAAS,MAAM,IAAI;AAE7D,QAAM,aAAa,UAAK,GAAG,GAAE,eAAV,GAAU,aAAe;AAAA,IAC1C,gBAAgB,GAAG;AAAA,IAClB,KAAK,GAAG,EAAE,iBAAiB,QAAQ,IAAI,aAAa;AAAA,EACvD;AAEA,QAAM,WAAW,UAAUA,YAAW,EAAE,IAAI;AAC5C,MAAI,YAAY,KAAM,QAAO,MAAM,CAAC,IAAI,SAAS,MAAM,IAAI;AAE3D,QAAM,OAAO,KAAK,GAAG,EAAE,eAAgBA,YAAW;AAElD,MAAI,IAAK,QAAO,wBAAwB,UAAU,MAAM,MAAM,QAAQ,IAAI;AAE1E,QAAM,QAAQ,qBAAqB,UAAU,MAAM,MAAM,QAAQ,IAAI;AACrE,MAAI,UAAU,GAAI,QAAO,SAAS,MAAM,IAAI;AAE5C,QAAM,UAAU,SAAS,KAAK;AAC9B,SAAO,SAAS,QAAQ,kBAAkB,IAAI,GAAG,QAAQ,oBAAoB,CAAC;AAChF;", + "names": ["module", "module", "resolveUri", "sourceIndex", "sourceIndex"] +} diff --git a/node_modules/@jridgewell/trace-mapping/package.json b/node_modules/@jridgewell/trace-mapping/package.json new file mode 100644 index 0000000..74bb8c3 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/package.json @@ -0,0 +1,67 @@ +{ + "name": "@jridgewell/trace-mapping", + "version": "0.3.30", + "description": "Trace the original position through a source map", + "keywords": [ + "source", + "map" + ], + "main": "dist/trace-mapping.umd.js", + "module": "dist/trace-mapping.mjs", + "types": "types/trace-mapping.d.cts", + "files": [ + "dist", + "src", + "types" + ], + "exports": { + ".": [ + { + "import": { + "types": "./types/trace-mapping.d.mts", + "default": "./dist/trace-mapping.mjs" + }, + "default": { + "types": "./types/trace-mapping.d.cts", + "default": "./dist/trace-mapping.umd.js" + } + }, + "./dist/trace-mapping.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:code benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.js", + "build": "run-s -n build:code build:types", + "build:code": "node ../../esbuild.mjs trace-mapping.ts", + "build:types": "run-s build:types:force build:types:emit build:types:mts", + "build:types:force": "rimraf tsconfig.build.tsbuildinfo", + "build:types:emit": "tsc --project tsconfig.build.json", + "build:types:mts": "node ../../mts-types.mjs", + "clean": "run-s -n clean:code clean:types", + "clean:code": "tsc --build --clean tsconfig.build.json", + "clean:types": "rimraf dist types", + "test": "run-s -n test:types test:only test:format", + "test:format": "prettier --check '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:types": "eslint '{src,test}/**/*.ts'", + "lint": "run-s -n lint:types lint:format", + "lint:format": "npm run test:format -- --write", + "lint:types": "npm run test:types -- --fix", + "prepublishOnly": "npm run-s -n build test" + }, + "homepage": "https://github.com/jridgewell/sourcemaps/tree/main/packages/trace-mapping", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemaps.git", + "directory": "packages/trace-mapping" + }, + "author": "Justin Ridgewell ", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } +} diff --git a/node_modules/@jridgewell/trace-mapping/src/binary-search.ts b/node_modules/@jridgewell/trace-mapping/src/binary-search.ts new file mode 100644 index 0000000..c1144ad --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/binary-search.ts @@ -0,0 +1,115 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment'; +import { COLUMN } from './sourcemap-segment'; + +export type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; + +export let found = false; + +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export function binarySearch( + haystack: SourceMapSegment[] | ReverseSegment[], + needle: number, + low: number, + high: number, +): number { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + + if (cmp === 0) { + found = true; + return mid; + } + + if (cmp < 0) { + low = mid + 1; + } else { + high = mid - 1; + } + } + + found = false; + return low - 1; +} + +export function upperBound( + haystack: SourceMapSegment[] | ReverseSegment[], + needle: number, + index: number, +): number { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} + +export function lowerBound( + haystack: SourceMapSegment[] | ReverseSegment[], + needle: number, + index: number, +): number { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} + +export function memoizedState(): MemoState { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; +} + +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export function memoizedBinarySearch( + haystack: SourceMapSegment[] | ReverseSegment[], + needle: number, + state: MemoState, + key: number, +): number { + const { lastKey, lastNeedle, lastIndex } = state; + + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + + return (state.lastIndex = binarySearch(haystack, needle, low, high)); +} diff --git a/node_modules/@jridgewell/trace-mapping/src/by-source.ts b/node_modules/@jridgewell/trace-mapping/src/by-source.ts new file mode 100644 index 0000000..2af1cf0 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/by-source.ts @@ -0,0 +1,65 @@ +import { COLUMN, SOURCES_INDEX, SOURCE_LINE, SOURCE_COLUMN } from './sourcemap-segment'; +import { memoizedBinarySearch, upperBound } from './binary-search'; + +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment'; +import type { MemoState } from './binary-search'; + +export type Source = { + __proto__: null; + [line: number]: Exclude[]; +}; + +// Rebuilds the original source files, with mappings that are ordered by source line/column instead +// of generated line/column. +export default function buildBySources( + decoded: readonly SourceMapSegment[][], + memos: MemoState[], +): Source[] { + const sources: Source[] = memos.map(buildNullArray); + + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) continue; + + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] ||= []); + const memo = memos[sourceIndex]; + + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + let index = upperBound( + originalLine, + sourceColumn, + memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine), + ); + + memo.lastIndex = ++index; + insert(originalLine, index, [sourceColumn, i, seg[COLUMN]]); + } + } + + return sources; +} + +function insert(array: T[], index: number, value: T) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} + +// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like +// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. +// Numeric properties on objects are magically sorted in ascending order by the engine regardless of +// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending +// order when iterating with for-in. +function buildNullArray(): T { + return { __proto__: null } as T; +} diff --git a/node_modules/@jridgewell/trace-mapping/src/flatten-map.ts b/node_modules/@jridgewell/trace-mapping/src/flatten-map.ts new file mode 100644 index 0000000..61ac40c --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/flatten-map.ts @@ -0,0 +1,192 @@ +import { TraceMap, presortedDecodedMap, decodedMappings } from './trace-mapping'; +import { + COLUMN, + SOURCES_INDEX, + SOURCE_LINE, + SOURCE_COLUMN, + NAMES_INDEX, +} from './sourcemap-segment'; +import { parse } from './types'; + +import type { + DecodedSourceMap, + DecodedSourceMapXInput, + EncodedSourceMapXInput, + SectionedSourceMapXInput, + SectionedSourceMapInput, + SectionXInput, + Ro, +} from './types'; +import type { SourceMapSegment } from './sourcemap-segment'; + +type FlattenMap = { + new (map: Ro, mapUrl?: string | null): TraceMap; + (map: Ro, mapUrl?: string | null): TraceMap; +}; + +export const FlattenMap: FlattenMap = function (map, mapUrl) { + const parsed = parse(map as SectionedSourceMapInput); + + if (!('sections' in parsed)) { + return new TraceMap(parsed as DecodedSourceMapXInput | EncodedSourceMapXInput, mapUrl); + } + + const mappings: SourceMapSegment[][] = []; + const sources: string[] = []; + const sourcesContent: (string | null)[] = []; + const names: string[] = []; + const ignoreList: number[] = []; + + recurse( + parsed, + mapUrl, + mappings, + sources, + sourcesContent, + names, + ignoreList, + 0, + 0, + Infinity, + Infinity, + ); + + const joined: DecodedSourceMap = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + ignoreList, + }; + + return presortedDecodedMap(joined); +} as FlattenMap; + +function recurse( + input: SectionedSourceMapXInput, + mapUrl: string | null | undefined, + mappings: SourceMapSegment[][], + sources: string[], + sourcesContent: (string | null)[], + names: string[], + ignoreList: number[], + lineOffset: number, + columnOffset: number, + stopLine: number, + stopColumn: number, +) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + + addSection( + map, + mapUrl, + mappings, + sources, + sourcesContent, + names, + ignoreList, + lineOffset + offset.line, + columnOffset + offset.column, + sl, + sc, + ); + } +} + +function addSection( + input: SectionXInput['map'], + mapUrl: string | null | undefined, + mappings: SourceMapSegment[][], + sources: string[], + sourcesContent: (string | null)[], + names: string[], + ignoreList: number[], + lineOffset: number, + columnOffset: number, + stopLine: number, + stopColumn: number, +) { + const parsed = parse(input); + if ('sections' in parsed) return recurse(...(arguments as unknown as Parameters)); + + const map = new TraceMap(parsed, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map; + + append(sources, resolvedSources); + append(names, map.names); + + if (contents) append(sourcesContent, contents); + else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null); + + if (ignores) for (let i = 0; i < ignores.length; i++) ignoreList.push(ignores[i] + sourcesOffset); + + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. But it may not have any columns that overstep, so we + // still need to check that we don't overstep lines, too. + if (lineI > stopLine) return; + + // The out line may already exist in mappings (if we're continuing the line started by a + // previous section). Or, we may have jumped ahead several lines to start this section. + const out = getLine(mappings, lineI); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (lineI === stopLine && column >= stopColumn) return; + + if (seg.length === 1) { + out.push([column]); + continue; + } + + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push( + seg.length === 4 + ? [column, sourcesIndex, sourceLine, sourceColumn] + : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]], + ); + } + } +} + +function append(arr: T[], other: T[]) { + for (let i = 0; i < other.length; i++) arr.push(other[i]); +} + +function getLine(arr: T[][], index: number): T[] { + for (let i = arr.length; i <= index; i++) arr[i] = []; + return arr[index]; +} diff --git a/node_modules/@jridgewell/trace-mapping/src/resolve.ts b/node_modules/@jridgewell/trace-mapping/src/resolve.ts new file mode 100644 index 0000000..30bfa3b --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/resolve.ts @@ -0,0 +1,16 @@ +import resolveUri from '@jridgewell/resolve-uri'; +import stripFilename from './strip-filename'; + +type Resolve = (source: string | null) => string; +export default function resolver( + mapUrl: string | null | undefined, + sourceRoot: string | undefined, +): Resolve { + const from = stripFilename(mapUrl); + // The sourceRoot is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + const prefix = sourceRoot ? sourceRoot + '/' : ''; + + return (source) => resolveUri(prefix + (source || ''), from); +} diff --git a/node_modules/@jridgewell/trace-mapping/src/sort.ts b/node_modules/@jridgewell/trace-mapping/src/sort.ts new file mode 100644 index 0000000..61213c8 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/sort.ts @@ -0,0 +1,45 @@ +import { COLUMN } from './sourcemap-segment'; + +import type { SourceMapSegment } from './sourcemap-segment'; + +export default function maybeSort( + mappings: SourceMapSegment[][], + owned: boolean, +): SourceMapSegment[][] { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) return mappings; + + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) mappings = mappings.slice(); + + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} + +function nextUnsortedSegmentLine(mappings: SourceMapSegment[][], start: number): number { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) return i; + } + return mappings.length; +} + +function isSorted(line: SourceMapSegment[]): boolean { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; +} + +function sortSegments(line: SourceMapSegment[], owned: boolean): SourceMapSegment[] { + if (!owned) line = line.slice(); + return line.sort(sortComparator); +} + +function sortComparator(a: SourceMapSegment, b: SourceMapSegment): number { + return a[COLUMN] - b[COLUMN]; +} diff --git a/node_modules/@jridgewell/trace-mapping/src/sourcemap-segment.ts b/node_modules/@jridgewell/trace-mapping/src/sourcemap-segment.ts new file mode 100644 index 0000000..94f1b6a --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/sourcemap-segment.ts @@ -0,0 +1,23 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; + +type GeneratedLine = number; + +export type SourceMapSegment = + | [GeneratedColumn] + | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] + | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; + +export type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; + +export const COLUMN = 0; +export const SOURCES_INDEX = 1; +export const SOURCE_LINE = 2; +export const SOURCE_COLUMN = 3; +export const NAMES_INDEX = 4; + +export const REV_GENERATED_LINE = 1; +export const REV_GENERATED_COLUMN = 2; diff --git a/node_modules/@jridgewell/trace-mapping/src/strip-filename.ts b/node_modules/@jridgewell/trace-mapping/src/strip-filename.ts new file mode 100644 index 0000000..2c88980 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/strip-filename.ts @@ -0,0 +1,8 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export default function stripFilename(path: string | undefined | null): string { + if (!path) return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} diff --git a/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts b/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts new file mode 100644 index 0000000..dea4c6c --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts @@ -0,0 +1,504 @@ +import { encode, decode } from '@jridgewell/sourcemap-codec'; + +import resolver from './resolve'; +import maybeSort from './sort'; +import buildBySources from './by-source'; +import { + memoizedState, + memoizedBinarySearch, + upperBound, + lowerBound, + found as bsFound, +} from './binary-search'; +import { + COLUMN, + SOURCES_INDEX, + SOURCE_LINE, + SOURCE_COLUMN, + NAMES_INDEX, + REV_GENERATED_LINE, + REV_GENERATED_COLUMN, +} from './sourcemap-segment'; +import { parse } from './types'; + +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment'; +import type { + SourceMapV3, + DecodedSourceMap, + EncodedSourceMap, + InvalidOriginalMapping, + OriginalMapping, + InvalidGeneratedMapping, + GeneratedMapping, + SourceMapInput, + Needle, + SourceNeedle, + SourceMap, + EachMapping, + Bias, + XInput, + SectionedSourceMap, + Ro, +} from './types'; +import type { Source } from './by-source'; +import type { MemoState } from './binary-search'; + +export type { SourceMapSegment } from './sourcemap-segment'; +export type { + SourceMap, + DecodedSourceMap, + EncodedSourceMap, + Section, + SectionedSourceMap, + SourceMapV3, + Bias, + EachMapping, + GeneratedMapping, + InvalidGeneratedMapping, + InvalidOriginalMapping, + Needle, + OriginalMapping, + OriginalMapping as Mapping, + SectionedSourceMapInput, + SourceMapInput, + SourceNeedle, + XInput, + EncodedSourceMapXInput, + DecodedSourceMapXInput, + SectionedSourceMapXInput, + SectionXInput, +} from './types'; + +interface PublicMap { + _encoded: TraceMap['_encoded']; + _decoded: TraceMap['_decoded']; + _decodedMemo: TraceMap['_decodedMemo']; + _bySources: TraceMap['_bySources']; + _bySourceMemos: TraceMap['_bySourceMemos']; +} + +const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; +const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; + +export const LEAST_UPPER_BOUND = -1; +export const GREATEST_LOWER_BOUND = 1; + +export { FlattenMap, FlattenMap as AnyMap } from './flatten-map'; + +export class TraceMap implements SourceMap { + declare version: SourceMapV3['version']; + declare file: SourceMapV3['file']; + declare names: SourceMapV3['names']; + declare sourceRoot: SourceMapV3['sourceRoot']; + declare sources: SourceMapV3['sources']; + declare sourcesContent: SourceMapV3['sourcesContent']; + declare ignoreList: SourceMapV3['ignoreList']; + + declare resolvedSources: string[]; + declare private _encoded: string | undefined; + + declare private _decoded: SourceMapSegment[][] | undefined; + declare private _decodedMemo: MemoState; + + declare private _bySources: Source[] | undefined; + declare private _bySourceMemos: MemoState[] | undefined; + + constructor(map: Ro, mapUrl?: string | null) { + const isString = typeof map === 'string'; + if (!isString && (map as unknown as { _decodedMemo: any })._decodedMemo) return map as TraceMap; + + const parsed = parse(map as Exclude); + + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names || []; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + this.ignoreList = parsed.ignoreList || (parsed as XInput).x_google_ignoreList || undefined; + + const resolve = resolver(mapUrl, sourceRoot); + this.resolvedSources = sources.map(resolve); + + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } else if (Array.isArray(mappings)) { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } else if ((parsed as unknown as SectionedSourceMap).sections) { + throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`); + } else { + throw new Error(`invalid source map: ${JSON.stringify(parsed)}`); + } + + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } +} + +/** + * Typescript doesn't allow friend access to private fields, so this just casts the map into a type + * with public access modifiers. + */ +function cast(map: unknown): PublicMap { + return map as any; +} + +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export function encodedMappings(map: TraceMap): EncodedSourceMap['mappings'] { + return (cast(map)._encoded ??= encode(cast(map)._decoded!)); +} + +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export function decodedMappings(map: TraceMap): Readonly { + return (cast(map)._decoded ||= decode(cast(map)._encoded!)); +} + +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export function traceSegment( + map: TraceMap, + line: number, + column: number, +): Readonly | null { + const decoded = decodedMappings(map); + + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) return null; + + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + GREATEST_LOWER_BOUND, + ); + + return index === -1 ? null : segments[index]; +} + +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export function originalPositionFor( + map: TraceMap, + needle: Needle, +): OriginalMapping | InvalidOriginalMapping { + let { line, column, bias } = needle; + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + + const decoded = decodedMappings(map); + + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) return OMapping(null, null, null, null); + + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + bias || GREATEST_LOWER_BOUND, + ); + + if (index === -1) return OMapping(null, null, null, null); + + const segment = segments[index]; + if (segment.length === 1) return OMapping(null, null, null, null); + + const { names, resolvedSources } = map; + return OMapping( + resolvedSources[segment[SOURCES_INDEX]], + segment[SOURCE_LINE] + 1, + segment[SOURCE_COLUMN], + segment.length === 5 ? names[segment[NAMES_INDEX]] : null, + ); +} + +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +export function generatedPositionFor( + map: TraceMap, + needle: SourceNeedle, +): GeneratedMapping | InvalidGeneratedMapping { + const { source, line, column, bias } = needle; + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); +} + +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +export function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[] { + const { source, line, column, bias } = needle; + // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit. + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); +} + +/** + * Iterates each mapping in generated position order. + */ +export function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) name = names[seg[4]]; + + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + } as EachMapping); + } + } +} + +function sourceIndex(map: TraceMap, source: string): number { + const { sources, resolvedSources } = map; + let index = sources.indexOf(source); + if (index === -1) index = resolvedSources.indexOf(source); + return index; +} + +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +export function sourceContentFor(map: TraceMap, source: string): string | null { + const { sourcesContent } = map; + if (sourcesContent == null) return null; + const index = sourceIndex(map, source); + return index === -1 ? null : sourcesContent[index]; +} + +/** + * Determines if the source is marked to ignore by the source map. + */ +export function isIgnored(map: TraceMap, source: string): boolean { + const { ignoreList } = map; + if (ignoreList == null) return false; + const index = sourceIndex(map, source); + return index === -1 ? false : ignoreList.includes(index); +} + +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap { + const tracer = new TraceMap(clone(map, []), mapUrl); + cast(tracer)._decoded = map.mappings; + return tracer; +} + +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export function decodedMap( + map: TraceMap, +): Omit & { mappings: readonly SourceMapSegment[][] } { + return clone(map, decodedMappings(map)); +} + +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export function encodedMap(map: TraceMap): EncodedSourceMap { + return clone(map, encodedMappings(map)); +} + +function clone( + map: TraceMap | DecodedSourceMap, + mappings: T, +): T extends string ? EncodedSourceMap : DecodedSourceMap { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + ignoreList: map.ignoreList || (map as XInput).x_google_ignoreList, + } as any; +} + +function OMapping(source: null, line: null, column: null, name: null): InvalidOriginalMapping; +function OMapping( + source: string, + line: number, + column: number, + name: string | null, +): OriginalMapping; +function OMapping( + source: string | null, + line: number | null, + column: number | null, + name: string | null, +): OriginalMapping | InvalidOriginalMapping { + return { source, line, column, name } as any; +} + +function GMapping(line: null, column: null): InvalidGeneratedMapping; +function GMapping(line: number, column: number): GeneratedMapping; +function GMapping( + line: number | null, + column: number | null, +): GeneratedMapping | InvalidGeneratedMapping { + return { line, column } as any; +} + +function traceSegmentInternal( + segments: SourceMapSegment[], + memo: MemoState, + line: number, + column: number, + bias: Bias, +): number; +function traceSegmentInternal( + segments: ReverseSegment[], + memo: MemoState, + line: number, + column: number, + bias: Bias, +): number; +function traceSegmentInternal( + segments: SourceMapSegment[] | ReverseSegment[], + memo: MemoState, + line: number, + column: number, + bias: Bias, +): number { + let index = memoizedBinarySearch(segments, column, memo, line); + if (bsFound) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } else if (bias === LEAST_UPPER_BOUND) index++; + + if (index === -1 || index === segments.length) return -1; + return index; +} + +function sliceGeneratedPositions( + segments: ReverseSegment[], + memo: MemoState, + line: number, + column: number, + bias: Bias, +): GeneratedMapping[] { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + + // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in + // insertion order) segment that matched. Even if we did respect the bias when tracing, we would + // still need to call `lowerBound()` to find the first segment, which is slower than just looking + // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the + // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to + // match LEAST_UPPER_BOUND. + if (!bsFound && bias === LEAST_UPPER_BOUND) min++; + + if (min === -1 || min === segments.length) return []; + + // We may have found the segment that started at an earlier column. If this is the case, then we + // need to slice all generated segments that match _that_ column, because all such segments span + // to our desired column. + const matchedColumn = bsFound ? column : segments[min][COLUMN]; + + // The binary search is not guaranteed to find the lower bound when a match wasn't found. + if (!bsFound) min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; +} + +function generatedPosition( + map: TraceMap, + source: string, + line: number, + column: number, + bias: Bias, + all: false, +): GeneratedMapping | InvalidGeneratedMapping; +function generatedPosition( + map: TraceMap, + source: string, + line: number, + column: number, + bias: Bias, + all: true, +): GeneratedMapping[]; +function generatedPosition( + map: TraceMap, + source: string, + line: number, + column: number, + bias: Bias, + all: boolean, +): GeneratedMapping | InvalidGeneratedMapping | GeneratedMapping[] { + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) return all ? [] : GMapping(null, null); + + const generated = (cast(map)._bySources ||= buildBySources( + decodedMappings(map), + (cast(map)._bySourceMemos = sources.map(memoizedState)), + )); + + const segments = generated[sourceIndex][line]; + if (segments == null) return all ? [] : GMapping(null, null); + + const memo = cast(map)._bySourceMemos![sourceIndex]; + + if (all) return sliceGeneratedPositions(segments, memo, line, column, bias); + + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) return GMapping(null, null); + + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); +} diff --git a/node_modules/@jridgewell/trace-mapping/src/types.ts b/node_modules/@jridgewell/trace-mapping/src/types.ts new file mode 100644 index 0000000..730a61f --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/types.ts @@ -0,0 +1,114 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap } from './trace-mapping'; + +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + ignoreList?: number[]; +} + +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} + +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} + +export interface Section { + offset: { line: number; column: number }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} + +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} + +export type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; + +export type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; + +export type GeneratedMapping = { + line: number; + column: number; +}; +export type InvalidGeneratedMapping = { + line: null; + column: null; +}; + +export type Bias = typeof GREATEST_LOWER_BOUND | typeof LEAST_UPPER_BOUND; + +export type XInput = { x_google_ignoreList?: SourceMapV3['ignoreList'] }; +export type EncodedSourceMapXInput = EncodedSourceMap & XInput; +export type DecodedSourceMapXInput = DecodedSourceMap & XInput; +export type SectionedSourceMapXInput = Omit & { + sections: SectionXInput[]; +}; +export type SectionXInput = Omit & { + map: SectionedSourceMapInput; +}; + +export type SourceMapInput = string | EncodedSourceMapXInput | DecodedSourceMapXInput | TraceMap; +export type SectionedSourceMapInput = SourceMapInput | SectionedSourceMapXInput; + +export type Needle = { line: number; column: number; bias?: Bias }; +export type SourceNeedle = { source: string; line: number; column: number; bias?: Bias }; + +export type EachMapping = + | { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; + } + | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; + }; + +export abstract class SourceMap { + declare version: SourceMapV3['version']; + declare file: SourceMapV3['file']; + declare names: SourceMapV3['names']; + declare sourceRoot: SourceMapV3['sourceRoot']; + declare sources: SourceMapV3['sources']; + declare sourcesContent: SourceMapV3['sourcesContent']; + declare resolvedSources: SourceMapV3['sources']; + declare ignoreList: SourceMapV3['ignoreList']; +} + +export type Ro = + T extends Array + ? V[] | Readonly | RoArray | Readonly> + : T extends object + ? T | Readonly | RoObject | Readonly> + : T; +type RoArray = Ro[]; +type RoObject = { [K in keyof T]: T[K] | Ro }; + +export function parse(map: T): Exclude { + return typeof map === 'string' ? JSON.parse(map) : (map as Exclude); +} diff --git a/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts b/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts new file mode 100644 index 0000000..b7bb85c --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts @@ -0,0 +1,33 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment.cts'; +export type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; +export declare let found: boolean; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export declare function binarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, low: number, high: number): number; +export declare function upperBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function lowerBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function memoizedState(): MemoState; +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export declare function memoizedBinarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, state: MemoState, key: number): number; +//# sourceMappingURL=binary-search.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts.map new file mode 100644 index 0000000..648e84c --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"binary-search.d.ts","sourceRoot":"","sources":["../src/binary-search.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAG5E,MAAM,MAAM,SAAS,GAAG;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,eAAO,IAAI,KAAK,SAAQ,CAAC;AAEzB;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,GACX,MAAM,CAmBR;AAED,wBAAgB,UAAU,CACxB,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GACZ,MAAM,CAKR;AAED,wBAAgB,UAAU,CACxB,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GACZ,MAAM,CAKR;AAED,wBAAgB,aAAa,IAAI,SAAS,CAMzC;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,SAAS,EAChB,GAAG,EAAE,MAAM,GACV,MAAM,CAsBR"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts b/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts new file mode 100644 index 0000000..19e1e6b --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts @@ -0,0 +1,33 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment.mts'; +export type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; +export declare let found: boolean; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export declare function binarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, low: number, high: number): number; +export declare function upperBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function lowerBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function memoizedState(): MemoState; +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export declare function memoizedBinarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, state: MemoState, key: number): number; +//# sourceMappingURL=binary-search.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts.map new file mode 100644 index 0000000..648e84c --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"binary-search.d.ts","sourceRoot":"","sources":["../src/binary-search.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAG5E,MAAM,MAAM,SAAS,GAAG;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,eAAO,IAAI,KAAK,SAAQ,CAAC;AAEzB;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,GACX,MAAM,CAmBR;AAED,wBAAgB,UAAU,CACxB,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GACZ,MAAM,CAKR;AAED,wBAAgB,UAAU,CACxB,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GACZ,MAAM,CAKR;AAED,wBAAgB,aAAa,IAAI,SAAS,CAMzC;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,SAAS,EAChB,GAAG,EAAE,MAAM,GACV,MAAM,CAsBR"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts b/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts new file mode 100644 index 0000000..d474786 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts @@ -0,0 +1,8 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment.cts'; +import type { MemoState } from './binary-search.cts'; +export type Source = { + __proto__: null; + [line: number]: Exclude[]; +}; +export = function buildBySources(decoded: readonly SourceMapSegment[][], memos: MemoState[]): Source[]; +//# sourceMappingURL=by-source.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts.map new file mode 100644 index 0000000..580fe96 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"by-source.d.ts","sourceRoot":"","sources":["../src/by-source.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEjD,MAAM,MAAM,MAAM,GAAG;IACnB,SAAS,EAAE,IAAI,CAAC;IAChB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;CACrD,CAAC;AAIF,MAAM,CAAC,OAAO,UAAU,cAAc,CACpC,OAAO,EAAE,SAAS,gBAAgB,EAAE,EAAE,EACtC,KAAK,EAAE,SAAS,EAAE,GACjB,MAAM,EAAE,CAgCV"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts b/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts new file mode 100644 index 0000000..d980c33 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts @@ -0,0 +1,8 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment.mts'; +import type { MemoState } from './binary-search.mts'; +export type Source = { + __proto__: null; + [line: number]: Exclude[]; +}; +export default function buildBySources(decoded: readonly SourceMapSegment[][], memos: MemoState[]): Source[]; +//# sourceMappingURL=by-source.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts.map new file mode 100644 index 0000000..580fe96 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"by-source.d.ts","sourceRoot":"","sources":["../src/by-source.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEjD,MAAM,MAAM,MAAM,GAAG;IACnB,SAAS,EAAE,IAAI,CAAC;IAChB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;CACrD,CAAC;AAIF,MAAM,CAAC,OAAO,UAAU,cAAc,CACpC,OAAO,EAAE,SAAS,gBAAgB,EAAE,EAAE,EACtC,KAAK,EAAE,SAAS,EAAE,GACjB,MAAM,EAAE,CAgCV"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts b/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts new file mode 100644 index 0000000..433d849 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts @@ -0,0 +1,9 @@ +import { TraceMap } from './trace-mapping.cts'; +import type { SectionedSourceMapInput, Ro } from './types.cts'; +type FlattenMap = { + new (map: Ro, mapUrl?: string | null): TraceMap; + (map: Ro, mapUrl?: string | null): TraceMap; +}; +export declare const FlattenMap: FlattenMap; +export {}; +//# sourceMappingURL=flatten-map.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts.map new file mode 100644 index 0000000..994b208 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"flatten-map.d.ts","sourceRoot":"","sources":["../src/flatten-map.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAwC,MAAM,iBAAiB,CAAC;AAUjF,OAAO,KAAK,EAKV,uBAAuB,EAEvB,EAAE,EACH,MAAM,SAAS,CAAC;AAGjB,KAAK,UAAU,GAAG;IAChB,KAAK,GAAG,EAAE,EAAE,CAAC,uBAAuB,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,QAAQ,CAAC;IACzE,CAAC,GAAG,EAAE,EAAE,CAAC,uBAAuB,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,QAAQ,CAAC;CACtE,CAAC;AAEF,eAAO,MAAM,UAAU,EAAE,UAsCV,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts b/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts new file mode 100644 index 0000000..444a1be --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts @@ -0,0 +1,9 @@ +import { TraceMap } from './trace-mapping.mts'; +import type { SectionedSourceMapInput, Ro } from './types.mts'; +type FlattenMap = { + new (map: Ro, mapUrl?: string | null): TraceMap; + (map: Ro, mapUrl?: string | null): TraceMap; +}; +export declare const FlattenMap: FlattenMap; +export {}; +//# sourceMappingURL=flatten-map.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts.map new file mode 100644 index 0000000..994b208 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"flatten-map.d.ts","sourceRoot":"","sources":["../src/flatten-map.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAwC,MAAM,iBAAiB,CAAC;AAUjF,OAAO,KAAK,EAKV,uBAAuB,EAEvB,EAAE,EACH,MAAM,SAAS,CAAC;AAGjB,KAAK,UAAU,GAAG;IAChB,KAAK,GAAG,EAAE,EAAE,CAAC,uBAAuB,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,QAAQ,CAAC;IACzE,CAAC,GAAG,EAAE,EAAE,CAAC,uBAAuB,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,QAAQ,CAAC;CACtE,CAAC;AAEF,eAAO,MAAM,UAAU,EAAE,UAsCV,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts b/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts new file mode 100644 index 0000000..62aeedb --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts @@ -0,0 +1,4 @@ +type Resolve = (source: string | null) => string; +export = function resolver(mapUrl: string | null | undefined, sourceRoot: string | undefined): Resolve; +export {}; +//# sourceMappingURL=resolve.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts.map new file mode 100644 index 0000000..9f155ac --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../src/resolve.ts"],"names":[],"mappings":"AAGA,KAAK,OAAO,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,KAAK,MAAM,CAAC;AACjD,MAAM,CAAC,OAAO,UAAU,QAAQ,CAC9B,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EACjC,UAAU,EAAE,MAAM,GAAG,SAAS,GAC7B,OAAO,CAQT"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts b/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts new file mode 100644 index 0000000..e2798a1 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts @@ -0,0 +1,4 @@ +type Resolve = (source: string | null) => string; +export default function resolver(mapUrl: string | null | undefined, sourceRoot: string | undefined): Resolve; +export {}; +//# sourceMappingURL=resolve.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts.map new file mode 100644 index 0000000..9f155ac --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../src/resolve.ts"],"names":[],"mappings":"AAGA,KAAK,OAAO,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,KAAK,MAAM,CAAC;AACjD,MAAM,CAAC,OAAO,UAAU,QAAQ,CAC9B,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EACjC,UAAU,EAAE,MAAM,GAAG,SAAS,GAC7B,OAAO,CAQT"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/sort.d.cts b/node_modules/@jridgewell/trace-mapping/types/sort.d.cts new file mode 100644 index 0000000..b364a6d --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/sort.d.cts @@ -0,0 +1,3 @@ +import type { SourceMapSegment } from './sourcemap-segment.cts'; +export = function maybeSort(mappings: SourceMapSegment[][], owned: boolean): SourceMapSegment[][]; +//# sourceMappingURL=sort.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/sort.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/sort.d.cts.map new file mode 100644 index 0000000..6859515 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/sort.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"sort.d.ts","sourceRoot":"","sources":["../src/sort.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE5D,MAAM,CAAC,OAAO,UAAU,SAAS,CAC/B,QAAQ,EAAE,gBAAgB,EAAE,EAAE,EAC9B,KAAK,EAAE,OAAO,GACb,gBAAgB,EAAE,EAAE,CAYtB"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/sort.d.mts b/node_modules/@jridgewell/trace-mapping/types/sort.d.mts new file mode 100644 index 0000000..ffd1301 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/sort.d.mts @@ -0,0 +1,3 @@ +import type { SourceMapSegment } from './sourcemap-segment.mts'; +export default function maybeSort(mappings: SourceMapSegment[][], owned: boolean): SourceMapSegment[][]; +//# sourceMappingURL=sort.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/sort.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/sort.d.mts.map new file mode 100644 index 0000000..6859515 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/sort.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"sort.d.ts","sourceRoot":"","sources":["../src/sort.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE5D,MAAM,CAAC,OAAO,UAAU,SAAS,CAC/B,QAAQ,EAAE,gBAAgB,EAAE,EAAE,EAC9B,KAAK,EAAE,OAAO,GACb,gBAAgB,EAAE,EAAE,CAYtB"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts b/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts new file mode 100644 index 0000000..8d3cabc --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts @@ -0,0 +1,17 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +type GeneratedLine = number; +export type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export declare const REV_GENERATED_LINE = 1; +export declare const REV_GENERATED_COLUMN = 2; +export {}; +//# sourceMappingURL=sourcemap-segment.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts.map new file mode 100644 index 0000000..0c94a46 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-segment.d.ts","sourceRoot":"","sources":["../src/sourcemap-segment.ts"],"names":[],"mappings":"AAAA,KAAK,eAAe,GAAG,MAAM,CAAC;AAC9B,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AACzB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AAEzB,KAAK,aAAa,GAAG,MAAM,CAAC;AAE5B,MAAM,MAAM,gBAAgB,GACxB,CAAC,eAAe,CAAC,GACjB,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,CAAC,GACzD,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC;AAE1E,MAAM,MAAM,cAAc,GAAG,CAAC,YAAY,EAAE,aAAa,EAAE,eAAe,CAAC,CAAC;AAE5E,eAAO,MAAM,MAAM,IAAI,CAAC;AACxB,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC;AAC7B,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC;AAE7B,eAAO,MAAM,kBAAkB,IAAI,CAAC;AACpC,eAAO,MAAM,oBAAoB,IAAI,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts b/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts new file mode 100644 index 0000000..8d3cabc --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts @@ -0,0 +1,17 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +type GeneratedLine = number; +export type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export declare const REV_GENERATED_LINE = 1; +export declare const REV_GENERATED_COLUMN = 2; +export {}; +//# sourceMappingURL=sourcemap-segment.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts.map new file mode 100644 index 0000000..0c94a46 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-segment.d.ts","sourceRoot":"","sources":["../src/sourcemap-segment.ts"],"names":[],"mappings":"AAAA,KAAK,eAAe,GAAG,MAAM,CAAC;AAC9B,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AACzB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AAEzB,KAAK,aAAa,GAAG,MAAM,CAAC;AAE5B,MAAM,MAAM,gBAAgB,GACxB,CAAC,eAAe,CAAC,GACjB,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,CAAC,GACzD,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC;AAE1E,MAAM,MAAM,cAAc,GAAG,CAAC,YAAY,EAAE,aAAa,EAAE,eAAe,CAAC,CAAC;AAE5E,eAAO,MAAM,MAAM,IAAI,CAAC;AACxB,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC;AAC7B,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC;AAE7B,eAAO,MAAM,kBAAkB,IAAI,CAAC;AACpC,eAAO,MAAM,oBAAoB,IAAI,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts b/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts new file mode 100644 index 0000000..8b3c0e9 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts @@ -0,0 +1,5 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export = function stripFilename(path: string | undefined | null): string; +//# sourceMappingURL=strip-filename.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts.map new file mode 100644 index 0000000..17a25da --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"strip-filename.d.ts","sourceRoot":"","sources":["../src/strip-filename.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,MAAM,CAI7E"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts b/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts new file mode 100644 index 0000000..cbbaee0 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts @@ -0,0 +1,5 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export default function stripFilename(path: string | undefined | null): string; +//# sourceMappingURL=strip-filename.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts.map new file mode 100644 index 0000000..17a25da --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"strip-filename.d.ts","sourceRoot":"","sources":["../src/strip-filename.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,MAAM,CAI7E"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts b/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts new file mode 100644 index 0000000..a40f305 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts @@ -0,0 +1,80 @@ +import type { SourceMapSegment } from './sourcemap-segment.cts'; +import type { SourceMapV3, DecodedSourceMap, EncodedSourceMap, InvalidOriginalMapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, SourceMapInput, Needle, SourceNeedle, SourceMap, EachMapping, Ro } from './types.cts'; +export type { SourceMapSegment } from './sourcemap-segment.cts'; +export type { SourceMap, DecodedSourceMap, EncodedSourceMap, Section, SectionedSourceMap, SourceMapV3, Bias, EachMapping, GeneratedMapping, InvalidGeneratedMapping, InvalidOriginalMapping, Needle, OriginalMapping, OriginalMapping as Mapping, SectionedSourceMapInput, SourceMapInput, SourceNeedle, XInput, EncodedSourceMapXInput, DecodedSourceMapXInput, SectionedSourceMapXInput, SectionXInput, } from './types.cts'; +export declare const LEAST_UPPER_BOUND = -1; +export declare const GREATEST_LOWER_BOUND = 1; +export { FlattenMap, FlattenMap as AnyMap } from './flatten-map.cts'; +export declare class TraceMap implements SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + ignoreList: SourceMapV3['ignoreList']; + resolvedSources: string[]; + private _encoded; + private _decoded; + private _decodedMemo; + private _bySources; + private _bySourceMemos; + constructor(map: Ro, mapUrl?: string | null); +} +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export declare function encodedMappings(map: TraceMap): EncodedSourceMap['mappings']; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export declare function decodedMappings(map: TraceMap): Readonly; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export declare function traceSegment(map: TraceMap, line: number, column: number): Readonly | null; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export declare function originalPositionFor(map: TraceMap, needle: Needle): OriginalMapping | InvalidOriginalMapping; +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +export declare function generatedPositionFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping | InvalidGeneratedMapping; +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +export declare function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[]; +/** + * Iterates each mapping in generated position order. + */ +export declare function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void; +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +export declare function sourceContentFor(map: TraceMap, source: string): string | null; +/** + * Determines if the source is marked to ignore by the source map. + */ +export declare function isIgnored(map: TraceMap, source: string): boolean; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export declare function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function decodedMap(map: TraceMap): Omit & { + mappings: readonly SourceMapSegment[][]; +}; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function encodedMap(map: TraceMap): EncodedSourceMap; +//# sourceMappingURL=trace-mapping.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts.map new file mode 100644 index 0000000..b5a874c --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.d.ts","sourceRoot":"","sources":["../src/trace-mapping.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,gBAAgB,EAAkB,MAAM,qBAAqB,CAAC;AAC5E,OAAO,KAAK,EACV,WAAW,EACX,gBAAgB,EAChB,gBAAgB,EAChB,sBAAsB,EACtB,eAAe,EACf,uBAAuB,EACvB,gBAAgB,EAChB,cAAc,EACd,MAAM,EACN,YAAY,EACZ,SAAS,EACT,WAAW,EAIX,EAAE,EACH,MAAM,SAAS,CAAC;AAIjB,YAAY,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,YAAY,EACV,SAAS,EACT,gBAAgB,EAChB,gBAAgB,EAChB,OAAO,EACP,kBAAkB,EAClB,WAAW,EACX,IAAI,EACJ,WAAW,EACX,gBAAgB,EAChB,uBAAuB,EACvB,sBAAsB,EACtB,MAAM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/types/trace-mapping.d.mts new file mode 100644 index 0000000..bc2ff0f --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts @@ -0,0 +1,80 @@ +import type { SourceMapSegment } from './sourcemap-segment.mts'; +import type { SourceMapV3, DecodedSourceMap, EncodedSourceMap, InvalidOriginalMapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, SourceMapInput, Needle, SourceNeedle, SourceMap, EachMapping, Ro } from './types.mts'; +export type { SourceMapSegment } from './sourcemap-segment.mts'; +export type { SourceMap, DecodedSourceMap, EncodedSourceMap, Section, SectionedSourceMap, SourceMapV3, Bias, EachMapping, GeneratedMapping, InvalidGeneratedMapping, InvalidOriginalMapping, Needle, OriginalMapping, OriginalMapping as Mapping, SectionedSourceMapInput, SourceMapInput, SourceNeedle, XInput, EncodedSourceMapXInput, DecodedSourceMapXInput, SectionedSourceMapXInput, SectionXInput, } from './types.mts'; +export declare const LEAST_UPPER_BOUND = -1; +export declare const GREATEST_LOWER_BOUND = 1; +export { FlattenMap, FlattenMap as AnyMap } from './flatten-map.mts'; +export declare class TraceMap implements SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + ignoreList: SourceMapV3['ignoreList']; + resolvedSources: string[]; + private _encoded; + private _decoded; + private _decodedMemo; + private _bySources; + private _bySourceMemos; + constructor(map: Ro, mapUrl?: string | null); +} +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export declare function encodedMappings(map: TraceMap): EncodedSourceMap['mappings']; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export declare function decodedMappings(map: TraceMap): Readonly; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export declare function traceSegment(map: TraceMap, line: number, column: number): Readonly | null; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export declare function originalPositionFor(map: TraceMap, needle: Needle): OriginalMapping | InvalidOriginalMapping; +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +export declare function generatedPositionFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping | InvalidGeneratedMapping; +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +export declare function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[]; +/** + * Iterates each mapping in generated position order. + */ +export declare function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void; +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +export declare function sourceContentFor(map: TraceMap, source: string): string | null; +/** + * Determines if the source is marked to ignore by the source map. + */ +export declare function isIgnored(map: TraceMap, source: string): boolean; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export declare function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function decodedMap(map: TraceMap): Omit & { + mappings: readonly SourceMapSegment[][]; +}; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function encodedMap(map: TraceMap): EncodedSourceMap; +//# sourceMappingURL=trace-mapping.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts.map new file mode 100644 index 0000000..b5a874c --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.d.ts","sourceRoot":"","sources":["../src/trace-mapping.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,gBAAgB,EAAkB,MAAM,qBAAqB,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,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,gBAAgB,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,QAAQ,CAIpF;AAED;;;GAGG;AACH,wBAAgB,UAAU,CACxB,GAAG,EAAE,QAAQ,GACZ,IAAI,CAAC,gBAAgB,EAAE,UAAU,CAAC,GAAG;IAAE,QAAQ,EAAE,SAAS,gBAAgB,EAAE,EAAE,CAAA;CAAE,CAElF;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,QAAQ,GAAG,gBAAgB,CAE1D"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/types.d.cts b/node_modules/@jridgewell/trace-mapping/types/types.d.cts new file mode 100644 index 0000000..729c2c3 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/types.d.cts @@ -0,0 +1,107 @@ +import type { SourceMapSegment } from './sourcemap-segment.cts'; +import type { GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap } from './trace-mapping.cts'; +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + ignoreList?: number[]; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} +export interface Section { + offset: { + line: number; + column: number; + }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} +export type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; +export type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; +export type GeneratedMapping = { + line: number; + column: number; +}; +export type InvalidGeneratedMapping = { + line: null; + column: null; +}; +export type Bias = typeof GREATEST_LOWER_BOUND | typeof LEAST_UPPER_BOUND; +export type XInput = { + x_google_ignoreList?: SourceMapV3['ignoreList']; +}; +export type EncodedSourceMapXInput = EncodedSourceMap & XInput; +export type DecodedSourceMapXInput = DecodedSourceMap & XInput; +export type SectionedSourceMapXInput = Omit & { + sections: SectionXInput[]; +}; +export type SectionXInput = Omit & { + map: SectionedSourceMapInput; +}; +export type SourceMapInput = string | EncodedSourceMapXInput | DecodedSourceMapXInput | TraceMap; +export type SectionedSourceMapInput = SourceMapInput | SectionedSourceMapXInput; +export type Needle = { + line: number; + column: number; + bias?: Bias; +}; +export type SourceNeedle = { + source: string; + line: number; + column: number; + bias?: Bias; +}; +export type EachMapping = { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; +} | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; +}; +export declare abstract class SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: SourceMapV3['sources']; + ignoreList: SourceMapV3['ignoreList']; +} +export type Ro = T extends Array ? V[] | Readonly | RoArray | Readonly> : T extends object ? T | Readonly | RoObject | Readonly> : T; +type RoArray = Ro[]; +type RoObject = { + [K in keyof T]: T[K] | Ro; +}; +export declare function parse(map: T): Exclude; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/types.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/types.d.cts.map new file mode 100644 index 0000000..9224783 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/types.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEzF,MAAM,WAAW,WAAW;IAC1B,IA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KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAAE,CAAC;AAEvD,wBAAgB,KAAK,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,EAAE,MAAM,CAAC,CAEnD"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/types.d.mts b/node_modules/@jridgewell/trace-mapping/types/types.d.mts new file mode 100644 index 0000000..a26d186 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/types.d.mts @@ -0,0 +1,107 @@ +import type { SourceMapSegment } from './sourcemap-segment.mts'; +import type { GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap } from './trace-mapping.mts'; +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + ignoreList?: number[]; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} +export interface Section { + offset: { + line: number; + column: number; + }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} +export type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; +export type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; +export type GeneratedMapping = { + line: number; + column: number; +}; +export type InvalidGeneratedMapping = { + line: null; + column: null; +}; +export type Bias = typeof GREATEST_LOWER_BOUND | typeof LEAST_UPPER_BOUND; +export type XInput = { + x_google_ignoreList?: SourceMapV3['ignoreList']; +}; +export type EncodedSourceMapXInput = EncodedSourceMap & XInput; +export type DecodedSourceMapXInput = DecodedSourceMap & XInput; +export type SectionedSourceMapXInput = Omit & { + sections: SectionXInput[]; +}; +export type SectionXInput = Omit & { + map: SectionedSourceMapInput; +}; +export type SourceMapInput = string | EncodedSourceMapXInput | DecodedSourceMapXInput | TraceMap; +export type SectionedSourceMapInput = SourceMapInput | SectionedSourceMapXInput; +export type Needle = { + line: number; + column: number; + bias?: Bias; +}; +export type SourceNeedle = { + source: string; + line: number; + column: number; + bias?: Bias; +}; +export type EachMapping = { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; +} | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; +}; +export declare abstract class SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: SourceMapV3['sources']; + ignoreList: SourceMapV3['ignoreList']; +} +export type Ro = T extends Array ? V[] | Readonly | RoArray | Readonly> : T extends object ? T | Readonly | RoObject | Readonly> : T; +type RoArray = Ro[]; +type RoObject = { + [K in keyof T]: T[K] | Ro; +}; +export declare function parse(map: T): Exclude; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/types.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/types.d.mts.map new file mode 100644 index 0000000..9224783 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/types.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEzF,MAAM,WAAW,WAAW;IAC1B,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OA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AAEvD,wBAAgB,KAAK,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,EAAE,MAAM,CAAC,CAEnD"} \ No newline at end of file diff --git a/node_modules/@nodelib/fs.scandir/LICENSE b/node_modules/@nodelib/fs.scandir/LICENSE new file mode 100644 index 0000000..65a9994 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Denis Malinochkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@nodelib/fs.scandir/README.md b/node_modules/@nodelib/fs.scandir/README.md new file mode 100644 index 0000000..e0b218b --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/README.md @@ -0,0 +1,171 @@ +# @nodelib/fs.scandir + +> List files and directories inside the specified directory. + +## :bulb: Highlights + +The package is aimed at obtaining information about entries in the directory. + +* :moneybag: Returns useful information: `name`, `path`, `dirent` and `stats` (optional). +* :gear: On Node.js 10.10+ uses the mechanism without additional calls to determine the entry type. See [`old` and `modern` mode](#old-and-modern-mode). +* :link: Can safely work with broken symbolic links. + +## Install + +```console +npm install @nodelib/fs.scandir +``` + +## Usage + +```ts +import * as fsScandir from '@nodelib/fs.scandir'; + +fsScandir.scandir('path', (error, stats) => { /* … */ }); +``` + +## API + +### .scandir(path, [optionsOrSettings], callback) + +Returns an array of plain objects ([`Entry`](#entry)) with information about entry for provided path with standard callback-style. + +```ts +fsScandir.scandir('path', (error, entries) => { /* … */ }); +fsScandir.scandir('path', {}, (error, entries) => { /* … */ }); +fsScandir.scandir('path', new fsScandir.Settings(), (error, entries) => { /* … */ }); +``` + +### .scandirSync(path, [optionsOrSettings]) + +Returns an array of plain objects ([`Entry`](#entry)) with information about entry for provided path. + +```ts +const entries = fsScandir.scandirSync('path'); +const entries = fsScandir.scandirSync('path', {}); +const entries = fsScandir.scandirSync(('path', new fsScandir.Settings()); +``` + +#### path + +* Required: `true` +* Type: `string | Buffer | URL` + +A path to a file. If a URL is provided, it must use the `file:` protocol. + +#### optionsOrSettings + +* Required: `false` +* Type: `Options | Settings` +* Default: An instance of `Settings` class + +An [`Options`](#options) object or an instance of [`Settings`](#settingsoptions) class. + +> :book: When you pass a plain object, an instance of the `Settings` class will be created automatically. If you plan to call the method frequently, use a pre-created instance of the `Settings` class. + +### Settings([options]) + +A class of full settings of the package. + +```ts +const settings = new fsScandir.Settings({ followSymbolicLinks: false }); + +const entries = fsScandir.scandirSync('path', settings); +``` + +## Entry + +* `name` — The name of the entry (`unknown.txt`). +* `path` — The path of the entry relative to call directory (`root/unknown.txt`). +* `dirent` — An instance of [`fs.Dirent`](./src/types/index.ts) class. On Node.js below 10.10 will be emulated by [`DirentFromStats`](./src/utils/fs.ts) class. +* `stats` (optional) — An instance of `fs.Stats` class. + +For example, the `scandir` call for `tools` directory with one directory inside: + +```ts +{ + dirent: Dirent { name: 'typedoc', /* … */ }, + name: 'typedoc', + path: 'tools/typedoc' +} +``` + +## Options + +### stats + +* Type: `boolean` +* Default: `false` + +Adds an instance of `fs.Stats` class to the [`Entry`](#entry). + +> :book: Always use `fs.readdir` without the `withFileTypes` option. ??TODO?? + +### followSymbolicLinks + +* Type: `boolean` +* Default: `false` + +Follow symbolic links or not. Call `fs.stat` on symbolic link if `true`. + +### `throwErrorOnBrokenSymbolicLink` + +* Type: `boolean` +* Default: `true` + +Throw an error when symbolic link is broken if `true` or safely use `lstat` call if `false`. + +### `pathSegmentSeparator` + +* Type: `string` +* Default: `path.sep` + +By default, this package uses the correct path separator for your OS (`\` on Windows, `/` on Unix-like systems). But you can set this option to any separator character(s) that you want to use instead. + +### `fs` + +* Type: [`FileSystemAdapter`](./src/adapters/fs.ts) +* Default: A default FS methods + +By default, the built-in Node.js module (`fs`) is used to work with the file system. You can replace any method with your own. + +```ts +interface FileSystemAdapter { + lstat?: typeof fs.lstat; + stat?: typeof fs.stat; + lstatSync?: typeof fs.lstatSync; + statSync?: typeof fs.statSync; + readdir?: typeof fs.readdir; + readdirSync?: typeof fs.readdirSync; +} + +const settings = new fsScandir.Settings({ + fs: { lstat: fakeLstat } +}); +``` + +## `old` and `modern` mode + +This package has two modes that are used depending on the environment and parameters of use. + +### old + +* Node.js below `10.10` or when the `stats` option is enabled + +When working in the old mode, the directory is read first (`fs.readdir`), then the type of entries is determined (`fs.lstat` and/or `fs.stat` for symbolic links). + +### modern + +* Node.js 10.10+ and the `stats` option is disabled + +In the modern mode, reading the directory (`fs.readdir` with the `withFileTypes` option) is combined with obtaining information about its entries. An additional call for symbolic links (`fs.stat`) is still present. + +This mode makes fewer calls to the file system. It's faster. + +## Changelog + +See the [Releases section of our GitHub project](https://github.com/nodelib/nodelib/releases) for changelog for each release version. + +## License + +This software is released under the terms of the MIT license. diff --git a/node_modules/@nodelib/fs.scandir/out/adapters/fs.d.ts b/node_modules/@nodelib/fs.scandir/out/adapters/fs.d.ts new file mode 100644 index 0000000..827f1db --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/adapters/fs.d.ts @@ -0,0 +1,20 @@ +import type * as fsStat from '@nodelib/fs.stat'; +import type { Dirent, ErrnoException } from '../types'; +export interface ReaddirAsynchronousMethod { + (filepath: string, options: { + withFileTypes: true; + }, callback: (error: ErrnoException | null, files: Dirent[]) => void): void; + (filepath: string, callback: (error: ErrnoException | null, files: string[]) => void): void; +} +export interface ReaddirSynchronousMethod { + (filepath: string, options: { + withFileTypes: true; + }): Dirent[]; + (filepath: string): string[]; +} +export declare type FileSystemAdapter = fsStat.FileSystemAdapter & { + readdir: ReaddirAsynchronousMethod; + readdirSync: ReaddirSynchronousMethod; +}; +export declare const FILE_SYSTEM_ADAPTER: FileSystemAdapter; +export declare function createFileSystemAdapter(fsMethods?: Partial): FileSystemAdapter; diff --git a/node_modules/@nodelib/fs.scandir/out/adapters/fs.js b/node_modules/@nodelib/fs.scandir/out/adapters/fs.js new file mode 100644 index 0000000..f0fe022 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/adapters/fs.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; +const fs = require("fs"); +exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync +}; +function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); +} +exports.createFileSystemAdapter = createFileSystemAdapter; diff --git a/node_modules/@nodelib/fs.scandir/out/constants.d.ts b/node_modules/@nodelib/fs.scandir/out/constants.d.ts new file mode 100644 index 0000000..33f1749 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/constants.d.ts @@ -0,0 +1,4 @@ +/** + * IS `true` for Node.js 10.10 and greater. + */ +export declare const IS_SUPPORT_READDIR_WITH_FILE_TYPES: boolean; diff --git a/node_modules/@nodelib/fs.scandir/out/constants.js b/node_modules/@nodelib/fs.scandir/out/constants.js new file mode 100644 index 0000000..7e3d441 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/constants.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0; +const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); +if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) { + throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); +} +const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); +const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); +const SUPPORTED_MAJOR_VERSION = 10; +const SUPPORTED_MINOR_VERSION = 10; +const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; +const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; +/** + * IS `true` for Node.js 10.10 and greater. + */ +exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; diff --git a/node_modules/@nodelib/fs.scandir/out/index.d.ts b/node_modules/@nodelib/fs.scandir/out/index.d.ts new file mode 100644 index 0000000..b9da83e --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/index.d.ts @@ -0,0 +1,12 @@ +import type { FileSystemAdapter, ReaddirAsynchronousMethod, ReaddirSynchronousMethod } from './adapters/fs'; +import * as async from './providers/async'; +import Settings, { Options } from './settings'; +import type { Dirent, Entry } from './types'; +declare type AsyncCallback = async.AsyncCallback; +declare function scandir(path: string, callback: AsyncCallback): void; +declare function scandir(path: string, optionsOrSettings: Options | Settings, callback: AsyncCallback): void; +declare namespace scandir { + function __promisify__(path: string, optionsOrSettings?: Options | Settings): Promise; +} +declare function scandirSync(path: string, optionsOrSettings?: Options | Settings): Entry[]; +export { scandir, scandirSync, Settings, AsyncCallback, Dirent, Entry, FileSystemAdapter, ReaddirAsynchronousMethod, ReaddirSynchronousMethod, Options }; diff --git a/node_modules/@nodelib/fs.scandir/out/index.js b/node_modules/@nodelib/fs.scandir/out/index.js new file mode 100644 index 0000000..99c70d3 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/index.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Settings = exports.scandirSync = exports.scandir = void 0; +const async = require("./providers/async"); +const sync = require("./providers/sync"); +const settings_1 = require("./settings"); +exports.Settings = settings_1.default; +function scandir(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + async.read(path, getSettings(), optionsOrSettingsOrCallback); + return; + } + async.read(path, getSettings(optionsOrSettingsOrCallback), callback); +} +exports.scandir = scandir; +function scandirSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync.read(path, settings); +} +exports.scandirSync = scandirSync; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) { + return settingsOrOptions; + } + return new settings_1.default(settingsOrOptions); +} diff --git a/node_modules/@nodelib/fs.scandir/out/providers/async.d.ts b/node_modules/@nodelib/fs.scandir/out/providers/async.d.ts new file mode 100644 index 0000000..5829676 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/providers/async.d.ts @@ -0,0 +1,7 @@ +/// +import type Settings from '../settings'; +import type { Entry } from '../types'; +export declare type AsyncCallback = (error: NodeJS.ErrnoException, entries: Entry[]) => void; +export declare function read(directory: string, settings: Settings, callback: AsyncCallback): void; +export declare function readdirWithFileTypes(directory: string, settings: Settings, callback: AsyncCallback): void; +export declare function readdir(directory: string, settings: Settings, callback: AsyncCallback): void; diff --git a/node_modules/@nodelib/fs.scandir/out/providers/async.js b/node_modules/@nodelib/fs.scandir/out/providers/async.js new file mode 100644 index 0000000..e8e2f0a --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/providers/async.js @@ -0,0 +1,104 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; +const fsStat = require("@nodelib/fs.stat"); +const rpl = require("run-parallel"); +const constants_1 = require("../constants"); +const utils = require("../utils"); +const common = require("./common"); +function read(directory, settings, callback) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + readdirWithFileTypes(directory, settings, callback); + return; + } + readdir(directory, settings, callback); +} +exports.read = read; +function readdirWithFileTypes(directory, settings, callback) { + settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { + if (readdirError !== null) { + callFailureCallback(callback, readdirError); + return; + } + const entries = dirents.map((dirent) => ({ + dirent, + name: dirent.name, + path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + })); + if (!settings.followSymbolicLinks) { + callSuccessCallback(callback, entries); + return; + } + const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); + rpl(tasks, (rplError, rplEntries) => { + if (rplError !== null) { + callFailureCallback(callback, rplError); + return; + } + callSuccessCallback(callback, rplEntries); + }); + }); +} +exports.readdirWithFileTypes = readdirWithFileTypes; +function makeRplTaskEntry(entry, settings) { + return (done) => { + if (!entry.dirent.isSymbolicLink()) { + done(null, entry); + return; + } + settings.fs.stat(entry.path, (statError, stats) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + done(statError); + return; + } + done(null, entry); + return; + } + entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); + done(null, entry); + }); + }; +} +function readdir(directory, settings, callback) { + settings.fs.readdir(directory, (readdirError, names) => { + if (readdirError !== null) { + callFailureCallback(callback, readdirError); + return; + } + const tasks = names.map((name) => { + const path = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); + return (done) => { + fsStat.stat(path, settings.fsStatSettings, (error, stats) => { + if (error !== null) { + done(error); + return; + } + const entry = { + name, + path, + dirent: utils.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + done(null, entry); + }); + }; + }); + rpl(tasks, (rplError, entries) => { + if (rplError !== null) { + callFailureCallback(callback, rplError); + return; + } + callSuccessCallback(callback, entries); + }); + }); +} +exports.readdir = readdir; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, result) { + callback(null, result); +} diff --git a/node_modules/@nodelib/fs.scandir/out/providers/common.d.ts b/node_modules/@nodelib/fs.scandir/out/providers/common.d.ts new file mode 100644 index 0000000..2b4d08b --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/providers/common.d.ts @@ -0,0 +1 @@ +export declare function joinPathSegments(a: string, b: string, separator: string): string; diff --git a/node_modules/@nodelib/fs.scandir/out/providers/common.js b/node_modules/@nodelib/fs.scandir/out/providers/common.js new file mode 100644 index 0000000..8724cb5 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/providers/common.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.joinPathSegments = void 0; +function joinPathSegments(a, b, separator) { + /** + * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). + */ + if (a.endsWith(separator)) { + return a + b; + } + return a + separator + b; +} +exports.joinPathSegments = joinPathSegments; diff --git a/node_modules/@nodelib/fs.scandir/out/providers/sync.d.ts b/node_modules/@nodelib/fs.scandir/out/providers/sync.d.ts new file mode 100644 index 0000000..e05c8f0 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/providers/sync.d.ts @@ -0,0 +1,5 @@ +import type Settings from '../settings'; +import type { Entry } from '../types'; +export declare function read(directory: string, settings: Settings): Entry[]; +export declare function readdirWithFileTypes(directory: string, settings: Settings): Entry[]; +export declare function readdir(directory: string, settings: Settings): Entry[]; diff --git a/node_modules/@nodelib/fs.scandir/out/providers/sync.js b/node_modules/@nodelib/fs.scandir/out/providers/sync.js new file mode 100644 index 0000000..146db34 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/providers/sync.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; +const fsStat = require("@nodelib/fs.stat"); +const constants_1 = require("../constants"); +const utils = require("../utils"); +const common = require("./common"); +function read(directory, settings) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(directory, settings); + } + return readdir(directory, settings); +} +exports.read = read; +function readdirWithFileTypes(directory, settings) { + const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); + return dirents.map((dirent) => { + const entry = { + dirent, + name: dirent.name, + path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + }; + if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { + try { + const stats = settings.fs.statSync(entry.path); + entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); + } + catch (error) { + if (settings.throwErrorOnBrokenSymbolicLink) { + throw error; + } + } + } + return entry; + }); +} +exports.readdirWithFileTypes = readdirWithFileTypes; +function readdir(directory, settings) { + const names = settings.fs.readdirSync(directory); + return names.map((name) => { + const entryPath = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); + const stats = fsStat.statSync(entryPath, settings.fsStatSettings); + const entry = { + name, + path: entryPath, + dirent: utils.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + return entry; + }); +} +exports.readdir = readdir; diff --git a/node_modules/@nodelib/fs.scandir/out/settings.d.ts b/node_modules/@nodelib/fs.scandir/out/settings.d.ts new file mode 100644 index 0000000..a0db115 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/settings.d.ts @@ -0,0 +1,20 @@ +import * as fsStat from '@nodelib/fs.stat'; +import * as fs from './adapters/fs'; +export interface Options { + followSymbolicLinks?: boolean; + fs?: Partial; + pathSegmentSeparator?: string; + stats?: boolean; + throwErrorOnBrokenSymbolicLink?: boolean; +} +export default class Settings { + private readonly _options; + readonly followSymbolicLinks: boolean; + readonly fs: fs.FileSystemAdapter; + readonly pathSegmentSeparator: string; + readonly stats: boolean; + readonly throwErrorOnBrokenSymbolicLink: boolean; + readonly fsStatSettings: fsStat.Settings; + constructor(_options?: Options); + private _getValue; +} diff --git a/node_modules/@nodelib/fs.scandir/out/settings.js b/node_modules/@nodelib/fs.scandir/out/settings.js new file mode 100644 index 0000000..15a3e8c --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/settings.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = require("path"); +const fsStat = require("@nodelib/fs.stat"); +const fs = require("./adapters/fs"); +class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); + this.fs = fs.createFileSystemAdapter(this._options.fs); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); + this.stats = this._getValue(this._options.stats, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + this.fsStatSettings = new fsStat.Settings({ + followSymbolicLink: this.followSymbolicLinks, + fs: this.fs, + throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +exports.default = Settings; diff --git a/node_modules/@nodelib/fs.scandir/out/types/index.d.ts b/node_modules/@nodelib/fs.scandir/out/types/index.d.ts new file mode 100644 index 0000000..f326c5e --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/types/index.d.ts @@ -0,0 +1,20 @@ +/// +import type * as fs from 'fs'; +export interface Entry { + dirent: Dirent; + name: string; + path: string; + stats?: Stats; +} +export declare type Stats = fs.Stats; +export declare type ErrnoException = NodeJS.ErrnoException; +export interface Dirent { + isBlockDevice: () => boolean; + isCharacterDevice: () => boolean; + isDirectory: () => boolean; + isFIFO: () => boolean; + isFile: () => boolean; + isSocket: () => boolean; + isSymbolicLink: () => boolean; + name: string; +} diff --git a/node_modules/@nodelib/fs.scandir/out/types/index.js b/node_modules/@nodelib/fs.scandir/out/types/index.js new file mode 100644 index 0000000..c8ad2e5 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/types/index.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nodelib/fs.scandir/out/utils/fs.d.ts b/node_modules/@nodelib/fs.scandir/out/utils/fs.d.ts new file mode 100644 index 0000000..bb863f1 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/utils/fs.d.ts @@ -0,0 +1,2 @@ +import type { Dirent, Stats } from '../types'; +export declare function createDirentFromStats(name: string, stats: Stats): Dirent; diff --git a/node_modules/@nodelib/fs.scandir/out/utils/fs.js b/node_modules/@nodelib/fs.scandir/out/utils/fs.js new file mode 100644 index 0000000..ace7c74 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/utils/fs.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createDirentFromStats = void 0; +class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } +} +function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); +} +exports.createDirentFromStats = createDirentFromStats; diff --git a/node_modules/@nodelib/fs.scandir/out/utils/index.d.ts b/node_modules/@nodelib/fs.scandir/out/utils/index.d.ts new file mode 100644 index 0000000..1b41954 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/utils/index.d.ts @@ -0,0 +1,2 @@ +import * as fs from './fs'; +export { fs }; diff --git a/node_modules/@nodelib/fs.scandir/out/utils/index.js b/node_modules/@nodelib/fs.scandir/out/utils/index.js new file mode 100644 index 0000000..f5de129 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/out/utils/index.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fs = void 0; +const fs = require("./fs"); +exports.fs = fs; diff --git a/node_modules/@nodelib/fs.scandir/package.json b/node_modules/@nodelib/fs.scandir/package.json new file mode 100644 index 0000000..d3a8924 --- /dev/null +++ b/node_modules/@nodelib/fs.scandir/package.json @@ -0,0 +1,44 @@ +{ + "name": "@nodelib/fs.scandir", + "version": "2.1.5", + "description": "List files and directories inside the specified directory", + "license": "MIT", + "repository": "https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.scandir", + "keywords": [ + "NodeLib", + "fs", + "FileSystem", + "file system", + "scandir", + "readdir", + "dirent" + ], + "engines": { + "node": ">= 8" + }, + "files": [ + "out/**", + "!out/**/*.map", + "!out/**/*.spec.*" + ], + "main": "out/index.js", + "typings": "out/index.d.ts", + "scripts": { + "clean": "rimraf {tsconfig.tsbuildinfo,out}", + "lint": "eslint \"src/**/*.ts\" --cache", + "compile": "tsc -b .", + "compile:watch": "tsc -p . --watch --sourceMap", + "test": "mocha \"out/**/*.spec.js\" -s 0", + "build": "npm run clean && npm run compile && npm run lint && npm test", + "watch": "npm run clean && npm run compile:watch" + }, + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "devDependencies": { + "@nodelib/fs.macchiato": "1.0.4", + "@types/run-parallel": "^1.1.0" + }, + "gitHead": "d6a7960d5281d3dd5f8e2efba49bb552d090f562" +} diff --git a/node_modules/@nodelib/fs.stat/LICENSE b/node_modules/@nodelib/fs.stat/LICENSE new file mode 100644 index 0000000..65a9994 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Denis Malinochkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@nodelib/fs.stat/README.md b/node_modules/@nodelib/fs.stat/README.md new file mode 100644 index 0000000..686f047 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/README.md @@ -0,0 +1,126 @@ +# @nodelib/fs.stat + +> Get the status of a file with some features. + +## :bulb: Highlights + +Wrapper around standard method `fs.lstat` and `fs.stat` with some features. + +* :beginner: Normally follows symbolic link. +* :gear: Can safely work with broken symbolic link. + +## Install + +```console +npm install @nodelib/fs.stat +``` + +## Usage + +```ts +import * as fsStat from '@nodelib/fs.stat'; + +fsStat.stat('path', (error, stats) => { /* … */ }); +``` + +## API + +### .stat(path, [optionsOrSettings], callback) + +Returns an instance of `fs.Stats` class for provided path with standard callback-style. + +```ts +fsStat.stat('path', (error, stats) => { /* … */ }); +fsStat.stat('path', {}, (error, stats) => { /* … */ }); +fsStat.stat('path', new fsStat.Settings(), (error, stats) => { /* … */ }); +``` + +### .statSync(path, [optionsOrSettings]) + +Returns an instance of `fs.Stats` class for provided path. + +```ts +const stats = fsStat.stat('path'); +const stats = fsStat.stat('path', {}); +const stats = fsStat.stat('path', new fsStat.Settings()); +``` + +#### path + +* Required: `true` +* Type: `string | Buffer | URL` + +A path to a file. If a URL is provided, it must use the `file:` protocol. + +#### optionsOrSettings + +* Required: `false` +* Type: `Options | Settings` +* Default: An instance of `Settings` class + +An [`Options`](#options) object or an instance of [`Settings`](#settings) class. + +> :book: When you pass a plain object, an instance of the `Settings` class will be created automatically. If you plan to call the method frequently, use a pre-created instance of the `Settings` class. + +### Settings([options]) + +A class of full settings of the package. + +```ts +const settings = new fsStat.Settings({ followSymbolicLink: false }); + +const stats = fsStat.stat('path', settings); +``` + +## Options + +### `followSymbolicLink` + +* Type: `boolean` +* Default: `true` + +Follow symbolic link or not. Call `fs.stat` on symbolic link if `true`. + +### `markSymbolicLink` + +* Type: `boolean` +* Default: `false` + +Mark symbolic link by setting the return value of `isSymbolicLink` function to always `true` (even after `fs.stat`). + +> :book: Can be used if you want to know what is hidden behind a symbolic link, but still continue to know that it is a symbolic link. + +### `throwErrorOnBrokenSymbolicLink` + +* Type: `boolean` +* Default: `true` + +Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`. + +### `fs` + +* Type: [`FileSystemAdapter`](./src/adapters/fs.ts) +* Default: A default FS methods + +By default, the built-in Node.js module (`fs`) is used to work with the file system. You can replace any method with your own. + +```ts +interface FileSystemAdapter { + lstat?: typeof fs.lstat; + stat?: typeof fs.stat; + lstatSync?: typeof fs.lstatSync; + statSync?: typeof fs.statSync; +} + +const settings = new fsStat.Settings({ + fs: { lstat: fakeLstat } +}); +``` + +## Changelog + +See the [Releases section of our GitHub project](https://github.com/nodelib/nodelib/releases) for changelog for each release version. + +## License + +This software is released under the terms of the MIT license. diff --git a/node_modules/@nodelib/fs.stat/out/adapters/fs.d.ts b/node_modules/@nodelib/fs.stat/out/adapters/fs.d.ts new file mode 100644 index 0000000..3af759c --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/adapters/fs.d.ts @@ -0,0 +1,13 @@ +/// +import * as fs from 'fs'; +import type { ErrnoException } from '../types'; +export declare type StatAsynchronousMethod = (path: string, callback: (error: ErrnoException | null, stats: fs.Stats) => void) => void; +export declare type StatSynchronousMethod = (path: string) => fs.Stats; +export interface FileSystemAdapter { + lstat: StatAsynchronousMethod; + stat: StatAsynchronousMethod; + lstatSync: StatSynchronousMethod; + statSync: StatSynchronousMethod; +} +export declare const FILE_SYSTEM_ADAPTER: FileSystemAdapter; +export declare function createFileSystemAdapter(fsMethods?: Partial): FileSystemAdapter; diff --git a/node_modules/@nodelib/fs.stat/out/adapters/fs.js b/node_modules/@nodelib/fs.stat/out/adapters/fs.js new file mode 100644 index 0000000..8dc08c8 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/adapters/fs.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; +const fs = require("fs"); +exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync +}; +function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); +} +exports.createFileSystemAdapter = createFileSystemAdapter; diff --git a/node_modules/@nodelib/fs.stat/out/index.d.ts b/node_modules/@nodelib/fs.stat/out/index.d.ts new file mode 100644 index 0000000..f95db99 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/index.d.ts @@ -0,0 +1,12 @@ +import type { FileSystemAdapter, StatAsynchronousMethod, StatSynchronousMethod } from './adapters/fs'; +import * as async from './providers/async'; +import Settings, { Options } from './settings'; +import type { Stats } from './types'; +declare type AsyncCallback = async.AsyncCallback; +declare function stat(path: string, callback: AsyncCallback): void; +declare function stat(path: string, optionsOrSettings: Options | Settings, callback: AsyncCallback): void; +declare namespace stat { + function __promisify__(path: string, optionsOrSettings?: Options | Settings): Promise; +} +declare function statSync(path: string, optionsOrSettings?: Options | Settings): Stats; +export { Settings, stat, statSync, AsyncCallback, FileSystemAdapter, StatAsynchronousMethod, StatSynchronousMethod, Options, Stats }; diff --git a/node_modules/@nodelib/fs.stat/out/index.js b/node_modules/@nodelib/fs.stat/out/index.js new file mode 100644 index 0000000..b23f751 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/index.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.statSync = exports.stat = exports.Settings = void 0; +const async = require("./providers/async"); +const sync = require("./providers/sync"); +const settings_1 = require("./settings"); +exports.Settings = settings_1.default; +function stat(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + async.read(path, getSettings(), optionsOrSettingsOrCallback); + return; + } + async.read(path, getSettings(optionsOrSettingsOrCallback), callback); +} +exports.stat = stat; +function statSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync.read(path, settings); +} +exports.statSync = statSync; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) { + return settingsOrOptions; + } + return new settings_1.default(settingsOrOptions); +} diff --git a/node_modules/@nodelib/fs.stat/out/providers/async.d.ts b/node_modules/@nodelib/fs.stat/out/providers/async.d.ts new file mode 100644 index 0000000..85423ce --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/providers/async.d.ts @@ -0,0 +1,4 @@ +import type Settings from '../settings'; +import type { ErrnoException, Stats } from '../types'; +export declare type AsyncCallback = (error: ErrnoException, stats: Stats) => void; +export declare function read(path: string, settings: Settings, callback: AsyncCallback): void; diff --git a/node_modules/@nodelib/fs.stat/out/providers/async.js b/node_modules/@nodelib/fs.stat/out/providers/async.js new file mode 100644 index 0000000..983ff0e --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/providers/async.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.read = void 0; +function read(path, settings, callback) { + settings.fs.lstat(path, (lstatError, lstat) => { + if (lstatError !== null) { + callFailureCallback(callback, lstatError); + return; + } + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + callSuccessCallback(callback, lstat); + return; + } + settings.fs.stat(path, (statError, stat) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + callFailureCallback(callback, statError); + return; + } + callSuccessCallback(callback, lstat); + return; + } + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + callSuccessCallback(callback, stat); + }); + }); +} +exports.read = read; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, result) { + callback(null, result); +} diff --git a/node_modules/@nodelib/fs.stat/out/providers/sync.d.ts b/node_modules/@nodelib/fs.stat/out/providers/sync.d.ts new file mode 100644 index 0000000..428c3d7 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/providers/sync.d.ts @@ -0,0 +1,3 @@ +import type Settings from '../settings'; +import type { Stats } from '../types'; +export declare function read(path: string, settings: Settings): Stats; diff --git a/node_modules/@nodelib/fs.stat/out/providers/sync.js b/node_modules/@nodelib/fs.stat/out/providers/sync.js new file mode 100644 index 0000000..1521c36 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/providers/sync.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.read = void 0; +function read(path, settings) { + const lstat = settings.fs.lstatSync(path); + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + return lstat; + } + try { + const stat = settings.fs.statSync(path); + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + return stat; + } + catch (error) { + if (!settings.throwErrorOnBrokenSymbolicLink) { + return lstat; + } + throw error; + } +} +exports.read = read; diff --git a/node_modules/@nodelib/fs.stat/out/settings.d.ts b/node_modules/@nodelib/fs.stat/out/settings.d.ts new file mode 100644 index 0000000..f4b3d44 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/settings.d.ts @@ -0,0 +1,16 @@ +import * as fs from './adapters/fs'; +export interface Options { + followSymbolicLink?: boolean; + fs?: Partial; + markSymbolicLink?: boolean; + throwErrorOnBrokenSymbolicLink?: boolean; +} +export default class Settings { + private readonly _options; + readonly followSymbolicLink: boolean; + readonly fs: fs.FileSystemAdapter; + readonly markSymbolicLink: boolean; + readonly throwErrorOnBrokenSymbolicLink: boolean; + constructor(_options?: Options); + private _getValue; +} diff --git a/node_modules/@nodelib/fs.stat/out/settings.js b/node_modules/@nodelib/fs.stat/out/settings.js new file mode 100644 index 0000000..111ec09 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/settings.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = require("./adapters/fs"); +class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); + this.fs = fs.createFileSystemAdapter(this._options.fs); + this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +exports.default = Settings; diff --git a/node_modules/@nodelib/fs.stat/out/types/index.d.ts b/node_modules/@nodelib/fs.stat/out/types/index.d.ts new file mode 100644 index 0000000..74c08ed --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/types/index.d.ts @@ -0,0 +1,4 @@ +/// +import type * as fs from 'fs'; +export declare type Stats = fs.Stats; +export declare type ErrnoException = NodeJS.ErrnoException; diff --git a/node_modules/@nodelib/fs.stat/out/types/index.js b/node_modules/@nodelib/fs.stat/out/types/index.js new file mode 100644 index 0000000..c8ad2e5 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/out/types/index.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nodelib/fs.stat/package.json b/node_modules/@nodelib/fs.stat/package.json new file mode 100644 index 0000000..f2540c2 --- /dev/null +++ b/node_modules/@nodelib/fs.stat/package.json @@ -0,0 +1,37 @@ +{ + "name": "@nodelib/fs.stat", + "version": "2.0.5", + "description": "Get the status of a file with some features", + "license": "MIT", + "repository": "https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.stat", + "keywords": [ + "NodeLib", + "fs", + "FileSystem", + "file system", + "stat" + ], + "engines": { + "node": ">= 8" + }, + "files": [ + "out/**", + "!out/**/*.map", + "!out/**/*.spec.*" + ], + "main": "out/index.js", + "typings": "out/index.d.ts", + "scripts": { + "clean": "rimraf {tsconfig.tsbuildinfo,out}", + "lint": "eslint \"src/**/*.ts\" --cache", + "compile": "tsc -b .", + "compile:watch": "tsc -p . --watch --sourceMap", + "test": "mocha \"out/**/*.spec.js\" -s 0", + "build": "npm run clean && npm run compile && npm run lint && npm test", + "watch": "npm run clean && npm run compile:watch" + }, + "devDependencies": { + "@nodelib/fs.macchiato": "1.0.4" + }, + "gitHead": "d6a7960d5281d3dd5f8e2efba49bb552d090f562" +} diff --git a/node_modules/@nodelib/fs.walk/LICENSE b/node_modules/@nodelib/fs.walk/LICENSE new file mode 100644 index 0000000..65a9994 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Denis Malinochkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@nodelib/fs.walk/README.md b/node_modules/@nodelib/fs.walk/README.md new file mode 100644 index 0000000..6ccc08d --- /dev/null +++ b/node_modules/@nodelib/fs.walk/README.md @@ -0,0 +1,215 @@ +# @nodelib/fs.walk + +> A library for efficiently walking a directory recursively. + +## :bulb: Highlights + +* :moneybag: Returns useful information: `name`, `path`, `dirent` and `stats` (optional). +* :rocket: On Node.js 10.10+ uses the mechanism without additional calls to determine the entry type for performance reasons. See [`old` and `modern` mode](https://github.com/nodelib/nodelib/blob/master/packages/fs/fs.scandir/README.md#old-and-modern-mode). +* :gear: Built-in directories/files and error filtering system. +* :link: Can safely work with broken symbolic links. + +## Install + +```console +npm install @nodelib/fs.walk +``` + +## Usage + +```ts +import * as fsWalk from '@nodelib/fs.walk'; + +fsWalk.walk('path', (error, entries) => { /* … */ }); +``` + +## API + +### .walk(path, [optionsOrSettings], callback) + +Reads the directory recursively and asynchronously. Requires a callback function. + +> :book: If you want to use the Promise API, use `util.promisify`. + +```ts +fsWalk.walk('path', (error, entries) => { /* … */ }); +fsWalk.walk('path', {}, (error, entries) => { /* … */ }); +fsWalk.walk('path', new fsWalk.Settings(), (error, entries) => { /* … */ }); +``` + +### .walkStream(path, [optionsOrSettings]) + +Reads the directory recursively and asynchronously. [Readable Stream](https://nodejs.org/dist/latest-v12.x/docs/api/stream.html#stream_readable_streams) is used as a provider. + +```ts +const stream = fsWalk.walkStream('path'); +const stream = fsWalk.walkStream('path', {}); +const stream = fsWalk.walkStream('path', new fsWalk.Settings()); +``` + +### .walkSync(path, [optionsOrSettings]) + +Reads the directory recursively and synchronously. Returns an array of entries. + +```ts +const entries = fsWalk.walkSync('path'); +const entries = fsWalk.walkSync('path', {}); +const entries = fsWalk.walkSync('path', new fsWalk.Settings()); +``` + +#### path + +* Required: `true` +* Type: `string | Buffer | URL` + +A path to a file. If a URL is provided, it must use the `file:` protocol. + +#### optionsOrSettings + +* Required: `false` +* Type: `Options | Settings` +* Default: An instance of `Settings` class + +An [`Options`](#options) object or an instance of [`Settings`](#settings) class. + +> :book: When you pass a plain object, an instance of the `Settings` class will be created automatically. If you plan to call the method frequently, use a pre-created instance of the `Settings` class. + +### Settings([options]) + +A class of full settings of the package. + +```ts +const settings = new fsWalk.Settings({ followSymbolicLinks: true }); + +const entries = fsWalk.walkSync('path', settings); +``` + +## Entry + +* `name` — The name of the entry (`unknown.txt`). +* `path` — The path of the entry relative to call directory (`root/unknown.txt`). +* `dirent` — An instance of [`fs.Dirent`](./src/types/index.ts) class. +* [`stats`] — An instance of `fs.Stats` class. + +## Options + +### basePath + +* Type: `string` +* Default: `undefined` + +By default, all paths are built relative to the root path. You can use this option to set custom root path. + +In the example below we read the files from the `root` directory, but in the results the root path will be `custom`. + +```ts +fsWalk.walkSync('root'); // → ['root/file.txt'] +fsWalk.walkSync('root', { basePath: 'custom' }); // → ['custom/file.txt'] +``` + +### concurrency + +* Type: `number` +* Default: `Infinity` + +The maximum number of concurrent calls to `fs.readdir`. + +> :book: The higher the number, the higher performance and the load on the File System. If you want to read in quiet mode, set the value to `4 * os.cpus().length` (4 is default size of [thread pool work scheduling](http://docs.libuv.org/en/v1.x/threadpool.html#thread-pool-work-scheduling)). + +### deepFilter + +* Type: [`DeepFilterFunction`](./src/settings.ts) +* Default: `undefined` + +A function that indicates whether the directory will be read deep or not. + +```ts +// Skip all directories that starts with `node_modules` +const filter: DeepFilterFunction = (entry) => !entry.path.startsWith('node_modules'); +``` + +### entryFilter + +* Type: [`EntryFilterFunction`](./src/settings.ts) +* Default: `undefined` + +A function that indicates whether the entry will be included to results or not. + +```ts +// Exclude all `.js` files from results +const filter: EntryFilterFunction = (entry) => !entry.name.endsWith('.js'); +``` + +### errorFilter + +* Type: [`ErrorFilterFunction`](./src/settings.ts) +* Default: `undefined` + +A function that allows you to skip errors that occur when reading directories. + +For example, you can skip `ENOENT` errors if required: + +```ts +// Skip all ENOENT errors +const filter: ErrorFilterFunction = (error) => error.code == 'ENOENT'; +``` + +### stats + +* Type: `boolean` +* Default: `false` + +Adds an instance of `fs.Stats` class to the [`Entry`](#entry). + +> :book: Always use `fs.readdir` with additional `fs.lstat/fs.stat` calls to determine the entry type. + +### followSymbolicLinks + +* Type: `boolean` +* Default: `false` + +Follow symbolic links or not. Call `fs.stat` on symbolic link if `true`. + +### `throwErrorOnBrokenSymbolicLink` + +* Type: `boolean` +* Default: `true` + +Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`. + +### `pathSegmentSeparator` + +* Type: `string` +* Default: `path.sep` + +By default, this package uses the correct path separator for your OS (`\` on Windows, `/` on Unix-like systems). But you can set this option to any separator character(s) that you want to use instead. + +### `fs` + +* Type: `FileSystemAdapter` +* Default: A default FS methods + +By default, the built-in Node.js module (`fs`) is used to work with the file system. You can replace any method with your own. + +```ts +interface FileSystemAdapter { + lstat: typeof fs.lstat; + stat: typeof fs.stat; + lstatSync: typeof fs.lstatSync; + statSync: typeof fs.statSync; + readdir: typeof fs.readdir; + readdirSync: typeof fs.readdirSync; +} + +const settings = new fsWalk.Settings({ + fs: { lstat: fakeLstat } +}); +``` + +## Changelog + +See the [Releases section of our GitHub project](https://github.com/nodelib/nodelib/releases) for changelog for each release version. + +## License + +This software is released under the terms of the MIT license. diff --git a/node_modules/@nodelib/fs.walk/out/index.d.ts b/node_modules/@nodelib/fs.walk/out/index.d.ts new file mode 100644 index 0000000..8864c7b --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/index.d.ts @@ -0,0 +1,14 @@ +/// +import type { Readable } from 'stream'; +import type { Dirent, FileSystemAdapter } from '@nodelib/fs.scandir'; +import { AsyncCallback } from './providers/async'; +import Settings, { DeepFilterFunction, EntryFilterFunction, ErrorFilterFunction, Options } from './settings'; +import type { Entry } from './types'; +declare function walk(directory: string, callback: AsyncCallback): void; +declare function walk(directory: string, optionsOrSettings: Options | Settings, callback: AsyncCallback): void; +declare namespace walk { + function __promisify__(directory: string, optionsOrSettings?: Options | Settings): Promise; +} +declare function walkSync(directory: string, optionsOrSettings?: Options | Settings): Entry[]; +declare function walkStream(directory: string, optionsOrSettings?: Options | Settings): Readable; +export { walk, walkSync, walkStream, Settings, AsyncCallback, Dirent, Entry, FileSystemAdapter, Options, DeepFilterFunction, EntryFilterFunction, ErrorFilterFunction }; diff --git a/node_modules/@nodelib/fs.walk/out/index.js b/node_modules/@nodelib/fs.walk/out/index.js new file mode 100644 index 0000000..1520787 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/index.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Settings = exports.walkStream = exports.walkSync = exports.walk = void 0; +const async_1 = require("./providers/async"); +const stream_1 = require("./providers/stream"); +const sync_1 = require("./providers/sync"); +const settings_1 = require("./settings"); +exports.Settings = settings_1.default; +function walk(directory, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + new async_1.default(directory, getSettings()).read(optionsOrSettingsOrCallback); + return; + } + new async_1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); +} +exports.walk = walk; +function walkSync(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new sync_1.default(directory, settings); + return provider.read(); +} +exports.walkSync = walkSync; +function walkStream(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new stream_1.default(directory, settings); + return provider.read(); +} +exports.walkStream = walkStream; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) { + return settingsOrOptions; + } + return new settings_1.default(settingsOrOptions); +} diff --git a/node_modules/@nodelib/fs.walk/out/providers/async.d.ts b/node_modules/@nodelib/fs.walk/out/providers/async.d.ts new file mode 100644 index 0000000..0f6717d --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/providers/async.d.ts @@ -0,0 +1,12 @@ +import AsyncReader from '../readers/async'; +import type Settings from '../settings'; +import type { Entry, Errno } from '../types'; +export declare type AsyncCallback = (error: Errno, entries: Entry[]) => void; +export default class AsyncProvider { + private readonly _root; + private readonly _settings; + protected readonly _reader: AsyncReader; + private readonly _storage; + constructor(_root: string, _settings: Settings); + read(callback: AsyncCallback): void; +} diff --git a/node_modules/@nodelib/fs.walk/out/providers/async.js b/node_modules/@nodelib/fs.walk/out/providers/async.js new file mode 100644 index 0000000..51d3be5 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/providers/async.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const async_1 = require("../readers/async"); +class AsyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1.default(this._root, this._settings); + this._storage = []; + } + read(callback) { + this._reader.onError((error) => { + callFailureCallback(callback, error); + }); + this._reader.onEntry((entry) => { + this._storage.push(entry); + }); + this._reader.onEnd(() => { + callSuccessCallback(callback, this._storage); + }); + this._reader.read(); + } +} +exports.default = AsyncProvider; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, entries) { + callback(null, entries); +} diff --git a/node_modules/@nodelib/fs.walk/out/providers/index.d.ts b/node_modules/@nodelib/fs.walk/out/providers/index.d.ts new file mode 100644 index 0000000..874f60c --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/providers/index.d.ts @@ -0,0 +1,4 @@ +import AsyncProvider from './async'; +import StreamProvider from './stream'; +import SyncProvider from './sync'; +export { AsyncProvider, StreamProvider, SyncProvider }; diff --git a/node_modules/@nodelib/fs.walk/out/providers/index.js b/node_modules/@nodelib/fs.walk/out/providers/index.js new file mode 100644 index 0000000..4c2529c --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/providers/index.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SyncProvider = exports.StreamProvider = exports.AsyncProvider = void 0; +const async_1 = require("./async"); +exports.AsyncProvider = async_1.default; +const stream_1 = require("./stream"); +exports.StreamProvider = stream_1.default; +const sync_1 = require("./sync"); +exports.SyncProvider = sync_1.default; diff --git a/node_modules/@nodelib/fs.walk/out/providers/stream.d.ts b/node_modules/@nodelib/fs.walk/out/providers/stream.d.ts new file mode 100644 index 0000000..294185f --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/providers/stream.d.ts @@ -0,0 +1,12 @@ +/// +import { Readable } from 'stream'; +import AsyncReader from '../readers/async'; +import type Settings from '../settings'; +export default class StreamProvider { + private readonly _root; + private readonly _settings; + protected readonly _reader: AsyncReader; + protected readonly _stream: Readable; + constructor(_root: string, _settings: Settings); + read(): Readable; +} diff --git a/node_modules/@nodelib/fs.walk/out/providers/stream.js b/node_modules/@nodelib/fs.walk/out/providers/stream.js new file mode 100644 index 0000000..51298b0 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/providers/stream.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = require("stream"); +const async_1 = require("../readers/async"); +class StreamProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1.default(this._root, this._settings); + this._stream = new stream_1.Readable({ + objectMode: true, + read: () => { }, + destroy: () => { + if (!this._reader.isDestroyed) { + this._reader.destroy(); + } + } + }); + } + read() { + this._reader.onError((error) => { + this._stream.emit('error', error); + }); + this._reader.onEntry((entry) => { + this._stream.push(entry); + }); + this._reader.onEnd(() => { + this._stream.push(null); + }); + this._reader.read(); + return this._stream; + } +} +exports.default = StreamProvider; diff --git a/node_modules/@nodelib/fs.walk/out/providers/sync.d.ts b/node_modules/@nodelib/fs.walk/out/providers/sync.d.ts new file mode 100644 index 0000000..551c42e --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/providers/sync.d.ts @@ -0,0 +1,10 @@ +import SyncReader from '../readers/sync'; +import type Settings from '../settings'; +import type { Entry } from '../types'; +export default class SyncProvider { + private readonly _root; + private readonly _settings; + protected readonly _reader: SyncReader; + constructor(_root: string, _settings: Settings); + read(): Entry[]; +} diff --git a/node_modules/@nodelib/fs.walk/out/providers/sync.js b/node_modules/@nodelib/fs.walk/out/providers/sync.js new file mode 100644 index 0000000..faab6ca --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/providers/sync.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const sync_1 = require("../readers/sync"); +class SyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new sync_1.default(this._root, this._settings); + } + read() { + return this._reader.read(); + } +} +exports.default = SyncProvider; diff --git a/node_modules/@nodelib/fs.walk/out/readers/async.d.ts b/node_modules/@nodelib/fs.walk/out/readers/async.d.ts new file mode 100644 index 0000000..9acf4e6 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/readers/async.d.ts @@ -0,0 +1,30 @@ +/// +import { EventEmitter } from 'events'; +import * as fsScandir from '@nodelib/fs.scandir'; +import type Settings from '../settings'; +import type { Entry, Errno } from '../types'; +import Reader from './reader'; +declare type EntryEventCallback = (entry: Entry) => void; +declare type ErrorEventCallback = (error: Errno) => void; +declare type EndEventCallback = () => void; +export default class AsyncReader extends Reader { + protected readonly _settings: Settings; + protected readonly _scandir: typeof fsScandir.scandir; + protected readonly _emitter: EventEmitter; + private readonly _queue; + private _isFatalError; + private _isDestroyed; + constructor(_root: string, _settings: Settings); + read(): EventEmitter; + get isDestroyed(): boolean; + destroy(): void; + onEntry(callback: EntryEventCallback): void; + onError(callback: ErrorEventCallback): void; + onEnd(callback: EndEventCallback): void; + private _pushToQueue; + private _worker; + private _handleError; + private _handleEntry; + private _emitEntry; +} +export {}; diff --git a/node_modules/@nodelib/fs.walk/out/readers/async.js b/node_modules/@nodelib/fs.walk/out/readers/async.js new file mode 100644 index 0000000..ebe8dd5 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/readers/async.js @@ -0,0 +1,97 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const events_1 = require("events"); +const fsScandir = require("@nodelib/fs.scandir"); +const fastq = require("fastq"); +const common = require("./common"); +const reader_1 = require("./reader"); +class AsyncReader extends reader_1.default { + constructor(_root, _settings) { + super(_root, _settings); + this._settings = _settings; + this._scandir = fsScandir.scandir; + this._emitter = new events_1.EventEmitter(); + this._queue = fastq(this._worker.bind(this), this._settings.concurrency); + this._isFatalError = false; + this._isDestroyed = false; + this._queue.drain = () => { + if (!this._isFatalError) { + this._emitter.emit('end'); + } + }; + } + read() { + this._isFatalError = false; + this._isDestroyed = false; + setImmediate(() => { + this._pushToQueue(this._root, this._settings.basePath); + }); + return this._emitter; + } + get isDestroyed() { + return this._isDestroyed; + } + destroy() { + if (this._isDestroyed) { + throw new Error('The reader is already destroyed'); + } + this._isDestroyed = true; + this._queue.killAndDrain(); + } + onEntry(callback) { + this._emitter.on('entry', callback); + } + onError(callback) { + this._emitter.once('error', callback); + } + onEnd(callback) { + this._emitter.once('end', callback); + } + _pushToQueue(directory, base) { + const queueItem = { directory, base }; + this._queue.push(queueItem, (error) => { + if (error !== null) { + this._handleError(error); + } + }); + } + _worker(item, done) { + this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { + if (error !== null) { + done(error, undefined); + return; + } + for (const entry of entries) { + this._handleEntry(entry, item.base); + } + done(null, undefined); + }); + } + _handleError(error) { + if (this._isDestroyed || !common.isFatalError(this._settings, error)) { + return; + } + this._isFatalError = true; + this._isDestroyed = true; + this._emitter.emit('error', error); + } + _handleEntry(entry, base) { + if (this._isDestroyed || this._isFatalError) { + return; + } + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common.isAppliedFilter(this._settings.entryFilter, entry)) { + this._emitEntry(entry); + } + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + } + } + _emitEntry(entry) { + this._emitter.emit('entry', entry); + } +} +exports.default = AsyncReader; diff --git a/node_modules/@nodelib/fs.walk/out/readers/common.d.ts b/node_modules/@nodelib/fs.walk/out/readers/common.d.ts new file mode 100644 index 0000000..5985f97 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/readers/common.d.ts @@ -0,0 +1,7 @@ +import type { FilterFunction } from '../settings'; +import type Settings from '../settings'; +import type { Errno } from '../types'; +export declare function isFatalError(settings: Settings, error: Errno): boolean; +export declare function isAppliedFilter(filter: FilterFunction | null, value: T): boolean; +export declare function replacePathSegmentSeparator(filepath: string, separator: string): string; +export declare function joinPathSegments(a: string, b: string, separator: string): string; diff --git a/node_modules/@nodelib/fs.walk/out/readers/common.js b/node_modules/@nodelib/fs.walk/out/readers/common.js new file mode 100644 index 0000000..a93572f --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/readers/common.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.joinPathSegments = exports.replacePathSegmentSeparator = exports.isAppliedFilter = exports.isFatalError = void 0; +function isFatalError(settings, error) { + if (settings.errorFilter === null) { + return true; + } + return !settings.errorFilter(error); +} +exports.isFatalError = isFatalError; +function isAppliedFilter(filter, value) { + return filter === null || filter(value); +} +exports.isAppliedFilter = isAppliedFilter; +function replacePathSegmentSeparator(filepath, separator) { + return filepath.split(/[/\\]/).join(separator); +} +exports.replacePathSegmentSeparator = replacePathSegmentSeparator; +function joinPathSegments(a, b, separator) { + if (a === '') { + return b; + } + /** + * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). + */ + if (a.endsWith(separator)) { + return a + b; + } + return a + separator + b; +} +exports.joinPathSegments = joinPathSegments; diff --git a/node_modules/@nodelib/fs.walk/out/readers/reader.d.ts b/node_modules/@nodelib/fs.walk/out/readers/reader.d.ts new file mode 100644 index 0000000..e1f383b --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/readers/reader.d.ts @@ -0,0 +1,6 @@ +import type Settings from '../settings'; +export default class Reader { + protected readonly _root: string; + protected readonly _settings: Settings; + constructor(_root: string, _settings: Settings); +} diff --git a/node_modules/@nodelib/fs.walk/out/readers/reader.js b/node_modules/@nodelib/fs.walk/out/readers/reader.js new file mode 100644 index 0000000..782f07c --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/readers/reader.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const common = require("./common"); +class Reader { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); + } +} +exports.default = Reader; diff --git a/node_modules/@nodelib/fs.walk/out/readers/sync.d.ts b/node_modules/@nodelib/fs.walk/out/readers/sync.d.ts new file mode 100644 index 0000000..af41033 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/readers/sync.d.ts @@ -0,0 +1,15 @@ +import * as fsScandir from '@nodelib/fs.scandir'; +import type { Entry } from '../types'; +import Reader from './reader'; +export default class SyncReader extends Reader { + protected readonly _scandir: typeof fsScandir.scandirSync; + private readonly _storage; + private readonly _queue; + read(): Entry[]; + private _pushToQueue; + private _handleQueue; + private _handleDirectory; + private _handleError; + private _handleEntry; + private _pushToStorage; +} diff --git a/node_modules/@nodelib/fs.walk/out/readers/sync.js b/node_modules/@nodelib/fs.walk/out/readers/sync.js new file mode 100644 index 0000000..9a8d5a6 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/readers/sync.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const fsScandir = require("@nodelib/fs.scandir"); +const common = require("./common"); +const reader_1 = require("./reader"); +class SyncReader extends reader_1.default { + constructor() { + super(...arguments); + this._scandir = fsScandir.scandirSync; + this._storage = []; + this._queue = new Set(); + } + read() { + this._pushToQueue(this._root, this._settings.basePath); + this._handleQueue(); + return this._storage; + } + _pushToQueue(directory, base) { + this._queue.add({ directory, base }); + } + _handleQueue() { + for (const item of this._queue.values()) { + this._handleDirectory(item.directory, item.base); + } + } + _handleDirectory(directory, base) { + try { + const entries = this._scandir(directory, this._settings.fsScandirSettings); + for (const entry of entries) { + this._handleEntry(entry, base); + } + } + catch (error) { + this._handleError(error); + } + } + _handleError(error) { + if (!common.isFatalError(this._settings, error)) { + return; + } + throw error; + } + _handleEntry(entry, base) { + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common.isAppliedFilter(this._settings.entryFilter, entry)) { + this._pushToStorage(entry); + } + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + } + } + _pushToStorage(entry) { + this._storage.push(entry); + } +} +exports.default = SyncReader; diff --git a/node_modules/@nodelib/fs.walk/out/settings.d.ts b/node_modules/@nodelib/fs.walk/out/settings.d.ts new file mode 100644 index 0000000..d1c4b45 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/settings.d.ts @@ -0,0 +1,30 @@ +import * as fsScandir from '@nodelib/fs.scandir'; +import type { Entry, Errno } from './types'; +export declare type FilterFunction = (value: T) => boolean; +export declare type DeepFilterFunction = FilterFunction; +export declare type EntryFilterFunction = FilterFunction; +export declare type ErrorFilterFunction = FilterFunction; +export interface Options { + basePath?: string; + concurrency?: number; + deepFilter?: DeepFilterFunction; + entryFilter?: EntryFilterFunction; + errorFilter?: ErrorFilterFunction; + followSymbolicLinks?: boolean; + fs?: Partial; + pathSegmentSeparator?: string; + stats?: boolean; + throwErrorOnBrokenSymbolicLink?: boolean; +} +export default class Settings { + private readonly _options; + readonly basePath?: string; + readonly concurrency: number; + readonly deepFilter: DeepFilterFunction | null; + readonly entryFilter: EntryFilterFunction | null; + readonly errorFilter: ErrorFilterFunction | null; + readonly pathSegmentSeparator: string; + readonly fsScandirSettings: fsScandir.Settings; + constructor(_options?: Options); + private _getValue; +} diff --git a/node_modules/@nodelib/fs.walk/out/settings.js b/node_modules/@nodelib/fs.walk/out/settings.js new file mode 100644 index 0000000..d7a85c8 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/settings.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = require("path"); +const fsScandir = require("@nodelib/fs.scandir"); +class Settings { + constructor(_options = {}) { + this._options = _options; + this.basePath = this._getValue(this._options.basePath, undefined); + this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); + this.deepFilter = this._getValue(this._options.deepFilter, null); + this.entryFilter = this._getValue(this._options.entryFilter, null); + this.errorFilter = this._getValue(this._options.errorFilter, null); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); + this.fsScandirSettings = new fsScandir.Settings({ + followSymbolicLinks: this._options.followSymbolicLinks, + fs: this._options.fs, + pathSegmentSeparator: this._options.pathSegmentSeparator, + stats: this._options.stats, + throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +exports.default = Settings; diff --git a/node_modules/@nodelib/fs.walk/out/types/index.d.ts b/node_modules/@nodelib/fs.walk/out/types/index.d.ts new file mode 100644 index 0000000..6ee9bd3 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/types/index.d.ts @@ -0,0 +1,8 @@ +/// +import type * as scandir from '@nodelib/fs.scandir'; +export declare type Entry = scandir.Entry; +export declare type Errno = NodeJS.ErrnoException; +export interface QueueItem { + directory: string; + base?: string; +} diff --git a/node_modules/@nodelib/fs.walk/out/types/index.js b/node_modules/@nodelib/fs.walk/out/types/index.js new file mode 100644 index 0000000..c8ad2e5 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/out/types/index.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nodelib/fs.walk/package.json b/node_modules/@nodelib/fs.walk/package.json new file mode 100644 index 0000000..86bfce4 --- /dev/null +++ b/node_modules/@nodelib/fs.walk/package.json @@ -0,0 +1,44 @@ +{ + "name": "@nodelib/fs.walk", + "version": "1.2.8", + "description": "A library for efficiently walking a directory recursively", + "license": "MIT", + "repository": "https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.walk", + "keywords": [ + "NodeLib", + "fs", + "FileSystem", + "file system", + "walk", + "scanner", + "crawler" + ], + "engines": { + "node": ">= 8" + }, + "files": [ + "out/**", + "!out/**/*.map", + "!out/**/*.spec.*", + "!out/**/tests/**" + ], + "main": "out/index.js", + "typings": "out/index.d.ts", + "scripts": { + "clean": "rimraf {tsconfig.tsbuildinfo,out}", + "lint": "eslint \"src/**/*.ts\" --cache", + "compile": "tsc -b .", + "compile:watch": "tsc -p . --watch --sourceMap", + "test": "mocha \"out/**/*.spec.js\" -s 0", + "build": "npm run clean && npm run compile && npm run lint && npm test", + "watch": "npm run clean && npm run compile:watch" + }, + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "devDependencies": { + "@nodelib/fs.macchiato": "1.0.4" + }, + "gitHead": "1e5bad48565da2b06b8600e744324ea240bf49d8" +} diff --git a/node_modules/@pkgjs/parseargs/.editorconfig b/node_modules/@pkgjs/parseargs/.editorconfig new file mode 100644 index 0000000..b140163 --- /dev/null +++ b/node_modules/@pkgjs/parseargs/.editorconfig @@ -0,0 +1,14 @@ +# EditorConfig is awesome: http://EditorConfig.org + +# top-most EditorConfig file +root = true + +# Copied from Node.js to ease compatibility in PR. +[*] +charset = utf-8 +end_of_line = lf +indent_size = 2 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true +quote_type = single diff --git a/node_modules/@pkgjs/parseargs/CHANGELOG.md b/node_modules/@pkgjs/parseargs/CHANGELOG.md new file mode 100644 index 0000000..2adc7d3 --- /dev/null +++ b/node_modules/@pkgjs/parseargs/CHANGELOG.md @@ -0,0 +1,147 @@ +# Changelog + +## [0.11.0](https://github.com/pkgjs/parseargs/compare/v0.10.0...v0.11.0) (2022-10-08) + + +### Features + +* add `default` option parameter ([#142](https://github.com/pkgjs/parseargs/issues/142)) ([cd20847](https://github.com/pkgjs/parseargs/commit/cd20847a00b2f556aa9c085ac83b942c60868ec1)) + +## [0.10.0](https://github.com/pkgjs/parseargs/compare/v0.9.1...v0.10.0) (2022-07-21) + + +### Features + +* add parsed meta-data to returned properties ([#129](https://github.com/pkgjs/parseargs/issues/129)) ([91bfb4d](https://github.com/pkgjs/parseargs/commit/91bfb4d3f7b6937efab1b27c91c45d1205f1497e)) + +## [0.9.1](https://github.com/pkgjs/parseargs/compare/v0.9.0...v0.9.1) (2022-06-20) + + +### Bug Fixes + +* **runtime:** support node 14+ ([#135](https://github.com/pkgjs/parseargs/issues/135)) ([6a1c5a6](https://github.com/pkgjs/parseargs/commit/6a1c5a6f7cadf2f035e004027e2742e3c4ce554b)) + +## [0.9.0](https://github.com/pkgjs/parseargs/compare/v0.8.0...v0.9.0) (2022-05-23) + + +### ⚠ BREAKING CHANGES + +* drop handling of electron arguments (#121) + +### Code Refactoring + +* drop handling of electron arguments ([#121](https://github.com/pkgjs/parseargs/issues/121)) ([a2ffd53](https://github.com/pkgjs/parseargs/commit/a2ffd537c244a062371522b955acb45a404fc9f2)) + +## [0.8.0](https://github.com/pkgjs/parseargs/compare/v0.7.1...v0.8.0) (2022-05-16) + + +### ⚠ BREAKING CHANGES + +* switch type:string option arguments to greedy, but with error for suspect cases in strict mode (#88) +* positionals now opt-in when strict:true (#116) +* create result.values with null prototype (#111) + +### Features + +* create result.values with null prototype ([#111](https://github.com/pkgjs/parseargs/issues/111)) ([9d539c3](https://github.com/pkgjs/parseargs/commit/9d539c3d57f269c160e74e0656ad4fa84ff92ec2)) +* positionals now opt-in when strict:true ([#116](https://github.com/pkgjs/parseargs/issues/116)) ([3643338](https://github.com/pkgjs/parseargs/commit/364333826b746e8a7dc5505b4b22fd19ac51df3b)) +* switch type:string option arguments to greedy, but with error for suspect cases in strict mode ([#88](https://github.com/pkgjs/parseargs/issues/88)) ([c2b5e72](https://github.com/pkgjs/parseargs/commit/c2b5e72161991dfdc535909f1327cc9b970fe7e8)) + +### [0.7.1](https://github.com/pkgjs/parseargs/compare/v0.7.0...v0.7.1) (2022-04-15) + + +### Bug Fixes + +* resist pollution ([#106](https://github.com/pkgjs/parseargs/issues/106)) ([ecf2dec](https://github.com/pkgjs/parseargs/commit/ecf2dece0a9f2a76d789384d5d71c68ffe64022a)) + +## [0.7.0](https://github.com/pkgjs/parseargs/compare/v0.6.0...v0.7.0) (2022-04-13) + + +### Features + +* Add strict mode to parser ([#74](https://github.com/pkgjs/parseargs/issues/74)) ([8267d02](https://github.com/pkgjs/parseargs/commit/8267d02083a87b8b8a71fcce08348d1e031ea91c)) + +## [0.6.0](https://github.com/pkgjs/parseargs/compare/v0.5.0...v0.6.0) (2022-04-11) + + +### ⚠ BREAKING CHANGES + +* rework results to remove redundant `flags` property and store value true for boolean options (#83) +* switch to existing ERR_INVALID_ARG_VALUE (#97) + +### Code Refactoring + +* rework results to remove redundant `flags` property and store value true for boolean options ([#83](https://github.com/pkgjs/parseargs/issues/83)) ([be153db](https://github.com/pkgjs/parseargs/commit/be153dbed1d488cb7b6e27df92f601ba7337713d)) +* switch to existing ERR_INVALID_ARG_VALUE ([#97](https://github.com/pkgjs/parseargs/issues/97)) ([084a23f](https://github.com/pkgjs/parseargs/commit/084a23f9fde2da030b159edb1c2385f24579ce40)) + +## [0.5.0](https://github.com/pkgjs/parseargs/compare/v0.4.0...v0.5.0) (2022-04-10) + + +### ⚠ BREAKING CHANGES + +* Require type to be specified for each supplied option (#95) + +### Features + +* Require type to be specified for each supplied option ([#95](https://github.com/pkgjs/parseargs/issues/95)) ([02cd018](https://github.com/pkgjs/parseargs/commit/02cd01885b8aaa59f2db8308f2d4479e64340068)) + +## [0.4.0](https://github.com/pkgjs/parseargs/compare/v0.3.0...v0.4.0) (2022-03-12) + + +### ⚠ BREAKING CHANGES + +* parsing, revisit short option groups, add support for combined short and value (#75) +* restructure configuration to take options bag (#63) + +### Code Refactoring + +* parsing, revisit short option groups, add support for combined short and value ([#75](https://github.com/pkgjs/parseargs/issues/75)) ([a92600f](https://github.com/pkgjs/parseargs/commit/a92600fa6c214508ab1e016fa55879a314f541af)) +* restructure configuration to take options bag ([#63](https://github.com/pkgjs/parseargs/issues/63)) ([b412095](https://github.com/pkgjs/parseargs/commit/b4120957d90e809ee8b607b06e747d3e6a6b213e)) + +## [0.3.0](https://github.com/pkgjs/parseargs/compare/v0.2.0...v0.3.0) (2022-02-06) + + +### Features + +* **parser:** support short-option groups ([#59](https://github.com/pkgjs/parseargs/issues/59)) ([882067b](https://github.com/pkgjs/parseargs/commit/882067bc2d7cbc6b796f8e5a079a99bc99d4e6ba)) + +## [0.2.0](https://github.com/pkgjs/parseargs/compare/v0.1.1...v0.2.0) (2022-02-05) + + +### Features + +* basic support for shorts ([#50](https://github.com/pkgjs/parseargs/issues/50)) ([a2f36d7](https://github.com/pkgjs/parseargs/commit/a2f36d7da4145af1c92f76806b7fe2baf6beeceb)) + + +### Bug Fixes + +* always store value for a=b ([#43](https://github.com/pkgjs/parseargs/issues/43)) ([a85e8dc](https://github.com/pkgjs/parseargs/commit/a85e8dc06379fd2696ee195cc625de8fac6aee42)) +* support single dash as positional ([#49](https://github.com/pkgjs/parseargs/issues/49)) ([d795bf8](https://github.com/pkgjs/parseargs/commit/d795bf877d068fd67aec381f30b30b63f97109ad)) + +### [0.1.1](https://github.com/pkgjs/parseargs/compare/v0.1.0...v0.1.1) (2022-01-25) + + +### Bug Fixes + +* only use arrays in results for multiples ([#42](https://github.com/pkgjs/parseargs/issues/42)) ([c357584](https://github.com/pkgjs/parseargs/commit/c357584847912506319ed34a0840080116f4fd65)) + +## 0.1.0 (2022-01-22) + + +### Features + +* expand scenarios covered by default arguments for environments ([#20](https://github.com/pkgjs/parseargs/issues/20)) ([582ada7](https://github.com/pkgjs/parseargs/commit/582ada7be0eca3a73d6e0bd016e7ace43449fa4c)) +* update readme and include contributing guidelines ([8edd6fc](https://github.com/pkgjs/parseargs/commit/8edd6fc863cd705f6fac732724159ebe8065a2b0)) + + +### Bug Fixes + +* do not strip excess leading dashes on long option names ([#21](https://github.com/pkgjs/parseargs/issues/21)) ([f848590](https://github.com/pkgjs/parseargs/commit/f848590ebf3249ed5979ff47e003fa6e1a8ec5c0)) +* name & readme ([3f057c1](https://github.com/pkgjs/parseargs/commit/3f057c1b158a1bdbe878c64b57460c58e56e465f)) +* package.json values ([9bac300](https://github.com/pkgjs/parseargs/commit/9bac300e00cd76c77076bf9e75e44f8929512da9)) +* update readme name ([957d8d9](https://github.com/pkgjs/parseargs/commit/957d8d96e1dcb48297c0a14345d44c0123b2883e)) + + +### Build System + +* first release as minor ([421c6e2](https://github.com/pkgjs/parseargs/commit/421c6e2569a8668ad14fac5a5af5be60479a7571)) diff --git a/node_modules/@pkgjs/parseargs/LICENSE b/node_modules/@pkgjs/parseargs/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/node_modules/@pkgjs/parseargs/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@pkgjs/parseargs/README.md b/node_modules/@pkgjs/parseargs/README.md new file mode 100644 index 0000000..0a04192 --- /dev/null +++ b/node_modules/@pkgjs/parseargs/README.md @@ -0,0 +1,413 @@ + +# parseArgs + +[![Coverage][coverage-image]][coverage-url] + +Polyfill of `util.parseArgs()` + +## `util.parseArgs([config])` + + + +> Stability: 1 - Experimental + +* `config` {Object} Used to provide arguments for parsing and to configure + the parser. `config` supports the following properties: + * `args` {string\[]} array of argument strings. **Default:** `process.argv` + with `execPath` and `filename` removed. + * `options` {Object} Used to describe arguments known to the parser. + Keys of `options` are the long names of options and values are an + {Object} accepting the following properties: + * `type` {string} Type of argument, which must be either `boolean` or `string`. + * `multiple` {boolean} Whether this option can be provided multiple + times. If `true`, all values will be collected in an array. If + `false`, values for the option are last-wins. **Default:** `false`. + * `short` {string} A single character alias for the option. + * `default` {string | boolean | string\[] | boolean\[]} The default option + value when it is not set by args. It must be of the same type as the + the `type` property. When `multiple` is `true`, it must be an array. + * `strict` {boolean} Should an error be thrown when unknown arguments + are encountered, or when arguments are passed that do not match the + `type` configured in `options`. + **Default:** `true`. + * `allowPositionals` {boolean} Whether this command accepts positional + arguments. + **Default:** `false` if `strict` is `true`, otherwise `true`. + * `tokens` {boolean} Return the parsed tokens. This is useful for extending + the built-in behavior, from adding additional checks through to reprocessing + the tokens in different ways. + **Default:** `false`. + +* Returns: {Object} The parsed command line arguments: + * `values` {Object} A mapping of parsed option names with their {string} + or {boolean} values. + * `positionals` {string\[]} Positional arguments. + * `tokens` {Object\[] | undefined} See [parseArgs tokens](#parseargs-tokens) + section. Only returned if `config` includes `tokens: true`. + +Provides a higher level API for command-line argument parsing than interacting +with `process.argv` directly. Takes a specification for the expected arguments +and returns a structured object with the parsed options and positionals. + +```mjs +import { parseArgs } from 'node:util'; +const args = ['-f', '--bar', 'b']; +const options = { + foo: { + type: 'boolean', + short: 'f' + }, + bar: { + type: 'string' + } +}; +const { + values, + positionals +} = parseArgs({ args, options }); +console.log(values, positionals); +// Prints: [Object: null prototype] { foo: true, bar: 'b' } [] +``` + +```cjs +const { parseArgs } = require('node:util'); +const args = ['-f', '--bar', 'b']; +const options = { + foo: { + type: 'boolean', + short: 'f' + }, + bar: { + type: 'string' + } +}; +const { + values, + positionals +} = parseArgs({ args, options }); +console.log(values, positionals); +// Prints: [Object: null prototype] { foo: true, bar: 'b' } [] +``` + +`util.parseArgs` is experimental and behavior may change. Join the +conversation in [pkgjs/parseargs][] to contribute to the design. + +### `parseArgs` `tokens` + +Detailed parse information is available for adding custom behaviours by +specifying `tokens: true` in the configuration. +The returned tokens have properties describing: + +* all tokens + * `kind` {string} One of 'option', 'positional', or 'option-terminator'. + * `index` {number} Index of element in `args` containing token. So the + source argument for a token is `args[token.index]`. +* option tokens + * `name` {string} Long name of option. + * `rawName` {string} How option used in args, like `-f` of `--foo`. + * `value` {string | undefined} Option value specified in args. + Undefined for boolean options. + * `inlineValue` {boolean | undefined} Whether option value specified inline, + like `--foo=bar`. +* positional tokens + * `value` {string} The value of the positional argument in args (i.e. `args[index]`). +* option-terminator token + +The returned tokens are in the order encountered in the input args. Options +that appear more than once in args produce a token for each use. Short option +groups like `-xy` expand to a token for each option. So `-xxx` produces +three tokens. + +For example to use the returned tokens to add support for a negated option +like `--no-color`, the tokens can be reprocessed to change the value stored +for the negated option. + +```mjs +import { parseArgs } from 'node:util'; + +const options = { + 'color': { type: 'boolean' }, + 'no-color': { type: 'boolean' }, + 'logfile': { type: 'string' }, + 'no-logfile': { type: 'boolean' }, +}; +const { values, tokens } = parseArgs({ options, tokens: true }); + +// Reprocess the option tokens and overwrite the returned values. +tokens + .filter((token) => token.kind === 'option') + .forEach((token) => { + if (token.name.startsWith('no-')) { + // Store foo:false for --no-foo + const positiveName = token.name.slice(3); + values[positiveName] = false; + delete values[token.name]; + } else { + // Resave value so last one wins if both --foo and --no-foo. + values[token.name] = token.value ?? true; + } + }); + +const color = values.color; +const logfile = values.logfile ?? 'default.log'; + +console.log({ logfile, color }); +``` + +```cjs +const { parseArgs } = require('node:util'); + +const options = { + 'color': { type: 'boolean' }, + 'no-color': { type: 'boolean' }, + 'logfile': { type: 'string' }, + 'no-logfile': { type: 'boolean' }, +}; +const { values, tokens } = parseArgs({ options, tokens: true }); + +// Reprocess the option tokens and overwrite the returned values. +tokens + .filter((token) => token.kind === 'option') + .forEach((token) => { + if (token.name.startsWith('no-')) { + // Store foo:false for --no-foo + const positiveName = token.name.slice(3); + values[positiveName] = false; + delete values[token.name]; + } else { + // Resave value so last one wins if both --foo and --no-foo. + values[token.name] = token.value ?? true; + } + }); + +const color = values.color; +const logfile = values.logfile ?? 'default.log'; + +console.log({ logfile, color }); +``` + +Example usage showing negated options, and when an option is used +multiple ways then last one wins. + +```console +$ node negate.js +{ logfile: 'default.log', color: undefined } +$ node negate.js --no-logfile --no-color +{ logfile: false, color: false } +$ node negate.js --logfile=test.log --color +{ logfile: 'test.log', color: true } +$ node negate.js --no-logfile --logfile=test.log --color --no-color +{ logfile: 'test.log', color: false } +``` + +----- + + +## Table of Contents +- [`util.parseArgs([config])`](#utilparseargsconfig) +- [Scope](#scope) +- [Version Matchups](#version-matchups) +- [🚀 Getting Started](#-getting-started) +- [🙌 Contributing](#-contributing) +- [💡 `process.mainArgs` Proposal](#-processmainargs-proposal) + - [Implementation:](#implementation) +- [📃 Examples](#-examples) +- [F.A.Qs](#faqs) +- [Links & Resources](#links--resources) + +----- + +## Scope + +It is already possible to build great arg parsing modules on top of what Node.js provides; the prickly API is abstracted away by these modules. Thus, process.parseArgs() is not necessarily intended for library authors; it is intended for developers of simple CLI tools, ad-hoc scripts, deployed Node.js applications, and learning materials. + +It is exceedingly difficult to provide an API which would both be friendly to these Node.js users while being extensible enough for libraries to build upon. We chose to prioritize these use cases because these are currently not well-served by Node.js' API. + +---- + +## Version Matchups + +| Node.js | @pkgjs/parseArgs | +| -- | -- | +| [v18.3.0](https://nodejs.org/docs/latest-v18.x/api/util.html#utilparseargsconfig) | [v0.9.1](https://github.com/pkgjs/parseargs/tree/v0.9.1#utilparseargsconfig) | +| [v16.17.0](https://nodejs.org/dist/latest-v16.x/docs/api/util.html#utilparseargsconfig), [v18.7.0](https://nodejs.org/docs/latest-v18.x/api/util.html#utilparseargsconfig) | [0.10.0](https://github.com/pkgjs/parseargs/tree/v0.10.0#utilparseargsconfig) | + +---- + +## 🚀 Getting Started + +1. **Install dependencies.** + + ```bash + npm install + ``` + +2. **Open the index.js file and start editing!** + +3. **Test your code by calling parseArgs through our test file** + + ```bash + npm test + ``` + +---- + +## 🙌 Contributing + +Any person who wants to contribute to the initiative is welcome! Please first read the [Contributing Guide](CONTRIBUTING.md) + +Additionally, reading the [`Examples w/ Output`](#-examples-w-output) section of this document will be the best way to familiarize yourself with the target expected behavior for parseArgs() once it is fully implemented. + +This package was implemented using [tape](https://www.npmjs.com/package/tape) as its test harness. + +---- + +## 💡 `process.mainArgs` Proposal + +> Note: This can be moved forward independently of the `util.parseArgs()` proposal/work. + +### Implementation: + +```javascript +process.mainArgs = process.argv.slice(process._exec ? 1 : 2) +``` + +---- + +## 📃 Examples + +```js +const { parseArgs } = require('@pkgjs/parseargs'); +``` + +```js +const { parseArgs } = require('@pkgjs/parseargs'); +// specify the options that may be used +const options = { + foo: { type: 'string'}, + bar: { type: 'boolean' }, +}; +const args = ['--foo=a', '--bar']; +const { values, positionals } = parseArgs({ args, options }); +// values = { foo: 'a', bar: true } +// positionals = [] +``` + +```js +const { parseArgs } = require('@pkgjs/parseargs'); +// type:string & multiple +const options = { + foo: { + type: 'string', + multiple: true, + }, +}; +const args = ['--foo=a', '--foo', 'b']; +const { values, positionals } = parseArgs({ args, options }); +// values = { foo: [ 'a', 'b' ] } +// positionals = [] +``` + +```js +const { parseArgs } = require('@pkgjs/parseargs'); +// shorts +const options = { + foo: { + short: 'f', + type: 'boolean' + }, +}; +const args = ['-f', 'b']; +const { values, positionals } = parseArgs({ args, options, allowPositionals: true }); +// values = { foo: true } +// positionals = ['b'] +``` + +```js +const { parseArgs } = require('@pkgjs/parseargs'); +// unconfigured +const options = {}; +const args = ['-f', '--foo=a', '--bar', 'b']; +const { values, positionals } = parseArgs({ strict: false, args, options, allowPositionals: true }); +// values = { f: true, foo: 'a', bar: true } +// positionals = ['b'] +``` + +---- + +## F.A.Qs + +- Is `cmd --foo=bar baz` the same as `cmd baz --foo=bar`? + - yes +- Does the parser execute a function? + - no +- Does the parser execute one of several functions, depending on input? + - no +- Can subcommands take options that are distinct from the main command? + - no +- Does it output generated help when no options match? + - no +- Does it generated short usage? Like: `usage: ls [-ABCFGHLOPRSTUWabcdefghiklmnopqrstuwx1] [file ...]` + - no (no usage/help at all) +- Does the user provide the long usage text? For each option? For the whole command? + - no +- Do subcommands (if implemented) have their own usage output? + - no +- Does usage print if the user runs `cmd --help`? + - no +- Does it set `process.exitCode`? + - no +- Does usage print to stderr or stdout? + - N/A +- Does it check types? (Say, specify that an option is a boolean, number, etc.) + - no +- Can an option have more than one type? (string or false, for example) + - no +- Can the user define a type? (Say, `type: path` to call `path.resolve()` on the argument.) + - no +- Does a `--foo=0o22` mean 0, 22, 18, or "0o22"? + - `"0o22"` +- Does it coerce types? + - no +- Does `--no-foo` coerce to `--foo=false`? For all options? Only boolean options? + - no, it sets `{values:{'no-foo': true}}` +- Is `--foo` the same as `--foo=true`? Only for known booleans? Only at the end? + - no, they are not the same. There is no special handling of `true` as a value so it is just another string. +- Does it read environment variables? Ie, is `FOO=1 cmd` the same as `cmd --foo=1`? + - no +- Do unknown arguments raise an error? Are they parsed? Are they treated as positional arguments? + - no, they are parsed, not treated as positionals +- Does `--` signal the end of options? + - yes +- Is `--` included as a positional? + - no +- Is `program -- foo` the same as `program foo`? + - yes, both store `{positionals:['foo']}` +- Does the API specify whether a `--` was present/relevant? + - no +- Is `-bar` the same as `--bar`? + - no, `-bar` is a short option or options, with expansion logic that follows the + [Utility Syntax Guidelines in POSIX.1-2017](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html). `-bar` expands to `-b`, `-a`, `-r`. +- Is `---foo` the same as `--foo`? + - no + - the first is a long option named `'-foo'` + - the second is a long option named `'foo'` +- Is `-` a positional? ie, `bash some-test.sh | tap -` + - yes + +## Links & Resources + +* [Initial Tooling Issue](https://github.com/nodejs/tooling/issues/19) +* [Initial Proposal](https://github.com/nodejs/node/pull/35015) +* [parseArgs Proposal](https://github.com/nodejs/node/pull/42675) + +[coverage-image]: https://img.shields.io/nycrc/pkgjs/parseargs +[coverage-url]: https://github.com/pkgjs/parseargs/blob/main/.nycrc +[pkgjs/parseargs]: https://github.com/pkgjs/parseargs diff --git a/node_modules/@pkgjs/parseargs/examples/is-default-value.js b/node_modules/@pkgjs/parseargs/examples/is-default-value.js new file mode 100644 index 0000000..0a67972 --- /dev/null +++ b/node_modules/@pkgjs/parseargs/examples/is-default-value.js @@ -0,0 +1,25 @@ +'use strict'; + +// This example shows how to understand if a default value is used or not. + +// 1. const { parseArgs } = require('node:util'); // from node +// 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package +const { parseArgs } = require('..'); // in repo + +const options = { + file: { short: 'f', type: 'string', default: 'FOO' }, +}; + +const { values, tokens } = parseArgs({ options, tokens: true }); + +const isFileDefault = !tokens.some((token) => token.kind === 'option' && + token.name === 'file' +); + +console.log(values); +console.log(`Is the file option [${values.file}] the default value? ${isFileDefault}`); + +// Try the following: +// node is-default-value.js +// node is-default-value.js -f FILE +// node is-default-value.js --file FILE diff --git a/node_modules/@pkgjs/parseargs/examples/limit-long-syntax.js b/node_modules/@pkgjs/parseargs/examples/limit-long-syntax.js new file mode 100644 index 0000000..943e643 --- /dev/null +++ b/node_modules/@pkgjs/parseargs/examples/limit-long-syntax.js @@ -0,0 +1,35 @@ +'use strict'; + +// This is an example of using tokens to add a custom behaviour. +// +// Require the use of `=` for long options and values by blocking +// the use of space separated values. +// So allow `--foo=bar`, and not allow `--foo bar`. +// +// Note: this is not a common behaviour, most CLIs allow both forms. + +// 1. const { parseArgs } = require('node:util'); // from node +// 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package +const { parseArgs } = require('..'); // in repo + +const options = { + file: { short: 'f', type: 'string' }, + log: { type: 'string' }, +}; + +const { values, tokens } = parseArgs({ options, tokens: true }); + +const badToken = tokens.find((token) => token.kind === 'option' && + token.value != null && + token.rawName.startsWith('--') && + !token.inlineValue +); +if (badToken) { + throw new Error(`Option value for '${badToken.rawName}' must be inline, like '${badToken.rawName}=VALUE'`); +} + +console.log(values); + +// Try the following: +// node limit-long-syntax.js -f FILE --log=LOG +// node limit-long-syntax.js --file FILE diff --git a/node_modules/@pkgjs/parseargs/examples/negate.js b/node_modules/@pkgjs/parseargs/examples/negate.js new file mode 100644 index 0000000..b663469 --- /dev/null +++ b/node_modules/@pkgjs/parseargs/examples/negate.js @@ -0,0 +1,43 @@ +'use strict'; + +// This example is used in the documentation. + +// How might I add my own support for --no-foo? + +// 1. const { parseArgs } = require('node:util'); // from node +// 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package +const { parseArgs } = require('..'); // in repo + +const options = { + 'color': { type: 'boolean' }, + 'no-color': { type: 'boolean' }, + 'logfile': { type: 'string' }, + 'no-logfile': { type: 'boolean' }, +}; +const { values, tokens } = parseArgs({ options, tokens: true }); + +// Reprocess the option tokens and overwrite the returned values. +tokens + .filter((token) => token.kind === 'option') + .forEach((token) => { + if (token.name.startsWith('no-')) { + // Store foo:false for --no-foo + const positiveName = token.name.slice(3); + values[positiveName] = false; + delete values[token.name]; + } else { + // Resave value so last one wins if both --foo and --no-foo. + values[token.name] = token.value ?? true; + } + }); + +const color = values.color; +const logfile = values.logfile ?? 'default.log'; + +console.log({ logfile, color }); + +// Try the following: +// node negate.js +// node negate.js --no-logfile --no-color +// negate.js --logfile=test.log --color +// node negate.js --no-logfile --logfile=test.log --color --no-color diff --git a/node_modules/@pkgjs/parseargs/examples/no-repeated-options.js b/node_modules/@pkgjs/parseargs/examples/no-repeated-options.js new file mode 100644 index 0000000..0c32468 --- /dev/null +++ b/node_modules/@pkgjs/parseargs/examples/no-repeated-options.js @@ -0,0 +1,31 @@ +'use strict'; + +// This is an example of using tokens to add a custom behaviour. +// +// Throw an error if an option is used more than once. + +// 1. const { parseArgs } = require('node:util'); // from node +// 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package +const { parseArgs } = require('..'); // in repo + +const options = { + ding: { type: 'boolean', short: 'd' }, + beep: { type: 'boolean', short: 'b' } +}; +const { values, tokens } = parseArgs({ options, tokens: true }); + +const seenBefore = new Set(); +tokens.forEach((token) => { + if (token.kind !== 'option') return; + if (seenBefore.has(token.name)) { + throw new Error(`option '${token.name}' used multiple times`); + } + seenBefore.add(token.name); +}); + +console.log(values); + +// Try the following: +// node no-repeated-options --ding --beep +// node no-repeated-options --beep -b +// node no-repeated-options -ddd diff --git a/node_modules/@pkgjs/parseargs/examples/ordered-options.mjs b/node_modules/@pkgjs/parseargs/examples/ordered-options.mjs new file mode 100644 index 0000000..8ab7367 --- /dev/null +++ b/node_modules/@pkgjs/parseargs/examples/ordered-options.mjs @@ -0,0 +1,41 @@ +// This is an example of using tokens to add a custom behaviour. +// +// This adds a option order check so that --some-unstable-option +// may only be used after --enable-experimental-options +// +// Note: this is not a common behaviour, the order of different options +// does not usually matter. + +import { parseArgs } from '../index.js'; + +function findTokenIndex(tokens, target) { + return tokens.findIndex((token) => token.kind === 'option' && + token.name === target + ); +} + +const experimentalName = 'enable-experimental-options'; +const unstableName = 'some-unstable-option'; + +const options = { + [experimentalName]: { type: 'boolean' }, + [unstableName]: { type: 'boolean' }, +}; + +const { values, tokens } = parseArgs({ options, tokens: true }); + +const experimentalIndex = findTokenIndex(tokens, experimentalName); +const unstableIndex = findTokenIndex(tokens, unstableName); +if (unstableIndex !== -1 && + ((experimentalIndex === -1) || (unstableIndex < experimentalIndex))) { + throw new Error(`'--${experimentalName}' must be specified before '--${unstableName}'`); +} + +console.log(values); + +/* eslint-disable max-len */ +// Try the following: +// node ordered-options.mjs +// node ordered-options.mjs --some-unstable-option +// node ordered-options.mjs --some-unstable-option --enable-experimental-options +// node ordered-options.mjs --enable-experimental-options --some-unstable-option diff --git a/node_modules/@pkgjs/parseargs/examples/simple-hard-coded.js b/node_modules/@pkgjs/parseargs/examples/simple-hard-coded.js new file mode 100644 index 0000000..eff04c2 --- /dev/null +++ b/node_modules/@pkgjs/parseargs/examples/simple-hard-coded.js @@ -0,0 +1,26 @@ +'use strict'; + +// This example is used in the documentation. + +// 1. const { parseArgs } = require('node:util'); // from node +// 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package +const { parseArgs } = require('..'); // in repo + +const args = ['-f', '--bar', 'b']; +const options = { + foo: { + type: 'boolean', + short: 'f' + }, + bar: { + type: 'string' + } +}; +const { + values, + positionals +} = parseArgs({ args, options }); +console.log(values, positionals); + +// Try the following: +// node simple-hard-coded.js diff --git a/node_modules/@pkgjs/parseargs/index.js b/node_modules/@pkgjs/parseargs/index.js new file mode 100644 index 0000000..b1004c7 --- /dev/null +++ b/node_modules/@pkgjs/parseargs/index.js @@ -0,0 +1,396 @@ +'use strict'; + +const { + ArrayPrototypeForEach, + ArrayPrototypeIncludes, + ArrayPrototypeMap, + ArrayPrototypePush, + ArrayPrototypePushApply, + ArrayPrototypeShift, + ArrayPrototypeSlice, + ArrayPrototypeUnshiftApply, + ObjectEntries, + ObjectPrototypeHasOwnProperty: ObjectHasOwn, + StringPrototypeCharAt, + StringPrototypeIndexOf, + StringPrototypeSlice, + StringPrototypeStartsWith, +} = require('./internal/primordials'); + +const { + validateArray, + validateBoolean, + validateBooleanArray, + validateObject, + validateString, + validateStringArray, + validateUnion, +} = require('./internal/validators'); + +const { + kEmptyObject, +} = require('./internal/util'); + +const { + findLongOptionForShort, + isLoneLongOption, + isLoneShortOption, + isLongOptionAndValue, + isOptionValue, + isOptionLikeValue, + isShortOptionAndValue, + isShortOptionGroup, + useDefaultValueOption, + objectGetOwn, + optionsGetOwn, +} = require('./utils'); + +const { + codes: { + ERR_INVALID_ARG_VALUE, + ERR_PARSE_ARGS_INVALID_OPTION_VALUE, + ERR_PARSE_ARGS_UNKNOWN_OPTION, + ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL, + }, +} = require('./internal/errors'); + +function getMainArgs() { + // Work out where to slice process.argv for user supplied arguments. + + // Check node options for scenarios where user CLI args follow executable. + const execArgv = process.execArgv; + if (ArrayPrototypeIncludes(execArgv, '-e') || + ArrayPrototypeIncludes(execArgv, '--eval') || + ArrayPrototypeIncludes(execArgv, '-p') || + ArrayPrototypeIncludes(execArgv, '--print')) { + return ArrayPrototypeSlice(process.argv, 1); + } + + // Normally first two arguments are executable and script, then CLI arguments + return ArrayPrototypeSlice(process.argv, 2); +} + +/** + * In strict mode, throw for possible usage errors like --foo --bar + * + * @param {object} token - from tokens as available from parseArgs + */ +function checkOptionLikeValue(token) { + if (!token.inlineValue && isOptionLikeValue(token.value)) { + // Only show short example if user used short option. + const example = StringPrototypeStartsWith(token.rawName, '--') ? + `'${token.rawName}=-XYZ'` : + `'--${token.name}=-XYZ' or '${token.rawName}-XYZ'`; + const errorMessage = `Option '${token.rawName}' argument is ambiguous. +Did you forget to specify the option argument for '${token.rawName}'? +To specify an option argument starting with a dash use ${example}.`; + throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(errorMessage); + } +} + +/** + * In strict mode, throw for usage errors. + * + * @param {object} config - from config passed to parseArgs + * @param {object} token - from tokens as available from parseArgs + */ +function checkOptionUsage(config, token) { + if (!ObjectHasOwn(config.options, token.name)) { + throw new ERR_PARSE_ARGS_UNKNOWN_OPTION( + token.rawName, config.allowPositionals); + } + + const short = optionsGetOwn(config.options, token.name, 'short'); + const shortAndLong = `${short ? `-${short}, ` : ''}--${token.name}`; + const type = optionsGetOwn(config.options, token.name, 'type'); + if (type === 'string' && typeof token.value !== 'string') { + throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(`Option '${shortAndLong} ' argument missing`); + } + // (Idiomatic test for undefined||null, expecting undefined.) + if (type === 'boolean' && token.value != null) { + throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(`Option '${shortAndLong}' does not take an argument`); + } +} + + +/** + * Store the option value in `values`. + * + * @param {string} longOption - long option name e.g. 'foo' + * @param {string|undefined} optionValue - value from user args + * @param {object} options - option configs, from parseArgs({ options }) + * @param {object} values - option values returned in `values` by parseArgs + */ +function storeOption(longOption, optionValue, options, values) { + if (longOption === '__proto__') { + return; // No. Just no. + } + + // We store based on the option value rather than option type, + // preserving the users intent for author to deal with. + const newValue = optionValue ?? true; + if (optionsGetOwn(options, longOption, 'multiple')) { + // Always store value in array, including for boolean. + // values[longOption] starts out not present, + // first value is added as new array [newValue], + // subsequent values are pushed to existing array. + // (note: values has null prototype, so simpler usage) + if (values[longOption]) { + ArrayPrototypePush(values[longOption], newValue); + } else { + values[longOption] = [newValue]; + } + } else { + values[longOption] = newValue; + } +} + +/** + * Store the default option value in `values`. + * + * @param {string} longOption - long option name e.g. 'foo' + * @param {string + * | boolean + * | string[] + * | boolean[]} optionValue - default value from option config + * @param {object} values - option values returned in `values` by parseArgs + */ +function storeDefaultOption(longOption, optionValue, values) { + if (longOption === '__proto__') { + return; // No. Just no. + } + + values[longOption] = optionValue; +} + +/** + * Process args and turn into identified tokens: + * - option (along with value, if any) + * - positional + * - option-terminator + * + * @param {string[]} args - from parseArgs({ args }) or mainArgs + * @param {object} options - option configs, from parseArgs({ options }) + */ +function argsToTokens(args, options) { + const tokens = []; + let index = -1; + let groupCount = 0; + + const remainingArgs = ArrayPrototypeSlice(args); + while (remainingArgs.length > 0) { + const arg = ArrayPrototypeShift(remainingArgs); + const nextArg = remainingArgs[0]; + if (groupCount > 0) + groupCount--; + else + index++; + + // Check if `arg` is an options terminator. + // Guideline 10 in https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html + if (arg === '--') { + // Everything after a bare '--' is considered a positional argument. + ArrayPrototypePush(tokens, { kind: 'option-terminator', index }); + ArrayPrototypePushApply( + tokens, ArrayPrototypeMap(remainingArgs, (arg) => { + return { kind: 'positional', index: ++index, value: arg }; + }) + ); + break; // Finished processing args, leave while loop. + } + + if (isLoneShortOption(arg)) { + // e.g. '-f' + const shortOption = StringPrototypeCharAt(arg, 1); + const longOption = findLongOptionForShort(shortOption, options); + let value; + let inlineValue; + if (optionsGetOwn(options, longOption, 'type') === 'string' && + isOptionValue(nextArg)) { + // e.g. '-f', 'bar' + value = ArrayPrototypeShift(remainingArgs); + inlineValue = false; + } + ArrayPrototypePush( + tokens, + { kind: 'option', name: longOption, rawName: arg, + index, value, inlineValue }); + if (value != null) ++index; + continue; + } + + if (isShortOptionGroup(arg, options)) { + // Expand -fXzy to -f -X -z -y + const expanded = []; + for (let index = 1; index < arg.length; index++) { + const shortOption = StringPrototypeCharAt(arg, index); + const longOption = findLongOptionForShort(shortOption, options); + if (optionsGetOwn(options, longOption, 'type') !== 'string' || + index === arg.length - 1) { + // Boolean option, or last short in group. Well formed. + ArrayPrototypePush(expanded, `-${shortOption}`); + } else { + // String option in middle. Yuck. + // Expand -abfFILE to -a -b -fFILE + ArrayPrototypePush(expanded, `-${StringPrototypeSlice(arg, index)}`); + break; // finished short group + } + } + ArrayPrototypeUnshiftApply(remainingArgs, expanded); + groupCount = expanded.length; + continue; + } + + if (isShortOptionAndValue(arg, options)) { + // e.g. -fFILE + const shortOption = StringPrototypeCharAt(arg, 1); + const longOption = findLongOptionForShort(shortOption, options); + const value = StringPrototypeSlice(arg, 2); + ArrayPrototypePush( + tokens, + { kind: 'option', name: longOption, rawName: `-${shortOption}`, + index, value, inlineValue: true }); + continue; + } + + if (isLoneLongOption(arg)) { + // e.g. '--foo' + const longOption = StringPrototypeSlice(arg, 2); + let value; + let inlineValue; + if (optionsGetOwn(options, longOption, 'type') === 'string' && + isOptionValue(nextArg)) { + // e.g. '--foo', 'bar' + value = ArrayPrototypeShift(remainingArgs); + inlineValue = false; + } + ArrayPrototypePush( + tokens, + { kind: 'option', name: longOption, rawName: arg, + index, value, inlineValue }); + if (value != null) ++index; + continue; + } + + if (isLongOptionAndValue(arg)) { + // e.g. --foo=bar + const equalIndex = StringPrototypeIndexOf(arg, '='); + const longOption = StringPrototypeSlice(arg, 2, equalIndex); + const value = StringPrototypeSlice(arg, equalIndex + 1); + ArrayPrototypePush( + tokens, + { kind: 'option', name: longOption, rawName: `--${longOption}`, + index, value, inlineValue: true }); + continue; + } + + ArrayPrototypePush(tokens, { kind: 'positional', index, value: arg }); + } + + return tokens; +} + +const parseArgs = (config = kEmptyObject) => { + const args = objectGetOwn(config, 'args') ?? getMainArgs(); + const strict = objectGetOwn(config, 'strict') ?? true; + const allowPositionals = objectGetOwn(config, 'allowPositionals') ?? !strict; + const returnTokens = objectGetOwn(config, 'tokens') ?? false; + const options = objectGetOwn(config, 'options') ?? { __proto__: null }; + // Bundle these up for passing to strict-mode checks. + const parseConfig = { args, strict, options, allowPositionals }; + + // Validate input configuration. + validateArray(args, 'args'); + validateBoolean(strict, 'strict'); + validateBoolean(allowPositionals, 'allowPositionals'); + validateBoolean(returnTokens, 'tokens'); + validateObject(options, 'options'); + ArrayPrototypeForEach( + ObjectEntries(options), + ({ 0: longOption, 1: optionConfig }) => { + validateObject(optionConfig, `options.${longOption}`); + + // type is required + const optionType = objectGetOwn(optionConfig, 'type'); + validateUnion(optionType, `options.${longOption}.type`, ['string', 'boolean']); + + if (ObjectHasOwn(optionConfig, 'short')) { + const shortOption = optionConfig.short; + validateString(shortOption, `options.${longOption}.short`); + if (shortOption.length !== 1) { + throw new ERR_INVALID_ARG_VALUE( + `options.${longOption}.short`, + shortOption, + 'must be a single character' + ); + } + } + + const multipleOption = objectGetOwn(optionConfig, 'multiple'); + if (ObjectHasOwn(optionConfig, 'multiple')) { + validateBoolean(multipleOption, `options.${longOption}.multiple`); + } + + const defaultValue = objectGetOwn(optionConfig, 'default'); + if (defaultValue !== undefined) { + let validator; + switch (optionType) { + case 'string': + validator = multipleOption ? validateStringArray : validateString; + break; + + case 'boolean': + validator = multipleOption ? validateBooleanArray : validateBoolean; + break; + } + validator(defaultValue, `options.${longOption}.default`); + } + } + ); + + // Phase 1: identify tokens + const tokens = argsToTokens(args, options); + + // Phase 2: process tokens into parsed option values and positionals + const result = { + values: { __proto__: null }, + positionals: [], + }; + if (returnTokens) { + result.tokens = tokens; + } + ArrayPrototypeForEach(tokens, (token) => { + if (token.kind === 'option') { + if (strict) { + checkOptionUsage(parseConfig, token); + checkOptionLikeValue(token); + } + storeOption(token.name, token.value, options, result.values); + } else if (token.kind === 'positional') { + if (!allowPositionals) { + throw new ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL(token.value); + } + ArrayPrototypePush(result.positionals, token.value); + } + }); + + // Phase 3: fill in default values for missing args + ArrayPrototypeForEach(ObjectEntries(options), ({ 0: longOption, + 1: optionConfig }) => { + const mustSetDefault = useDefaultValueOption(longOption, + optionConfig, + result.values); + if (mustSetDefault) { + storeDefaultOption(longOption, + objectGetOwn(optionConfig, 'default'), + result.values); + } + }); + + + return result; +}; + +module.exports = { + parseArgs, +}; diff --git a/node_modules/@pkgjs/parseargs/internal/errors.js b/node_modules/@pkgjs/parseargs/internal/errors.js new file mode 100644 index 0000000..e1b237b --- /dev/null +++ b/node_modules/@pkgjs/parseargs/internal/errors.js @@ -0,0 +1,47 @@ +'use strict'; + +class ERR_INVALID_ARG_TYPE extends TypeError { + constructor(name, expected, actual) { + super(`${name} must be ${expected} got ${actual}`); + this.code = 'ERR_INVALID_ARG_TYPE'; + } +} + +class ERR_INVALID_ARG_VALUE extends TypeError { + constructor(arg1, arg2, expected) { + super(`The property ${arg1} ${expected}. Received '${arg2}'`); + this.code = 'ERR_INVALID_ARG_VALUE'; + } +} + +class ERR_PARSE_ARGS_INVALID_OPTION_VALUE extends Error { + constructor(message) { + super(message); + this.code = 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE'; + } +} + +class ERR_PARSE_ARGS_UNKNOWN_OPTION extends Error { + constructor(option, allowPositionals) { + const suggestDashDash = allowPositionals ? `. To specify a positional argument starting with a '-', place it at the end of the command after '--', as in '-- ${JSON.stringify(option)}` : ''; + super(`Unknown option '${option}'${suggestDashDash}`); + this.code = 'ERR_PARSE_ARGS_UNKNOWN_OPTION'; + } +} + +class ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL extends Error { + constructor(positional) { + super(`Unexpected argument '${positional}'. This command does not take positional arguments`); + this.code = 'ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL'; + } +} + +module.exports = { + codes: { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_ARG_VALUE, + ERR_PARSE_ARGS_INVALID_OPTION_VALUE, + ERR_PARSE_ARGS_UNKNOWN_OPTION, + ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL, + } +}; diff --git a/node_modules/@pkgjs/parseargs/internal/primordials.js b/node_modules/@pkgjs/parseargs/internal/primordials.js new file mode 100644 index 0000000..63e23ab --- /dev/null +++ b/node_modules/@pkgjs/parseargs/internal/primordials.js @@ -0,0 +1,393 @@ +/* +This file is copied from https://github.com/nodejs/node/blob/v14.19.3/lib/internal/per_context/primordials.js +under the following license: + +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +*/ + +'use strict'; + +/* eslint-disable node-core/prefer-primordials */ + +// This file subclasses and stores the JS builtins that come from the VM +// so that Node.js's builtin modules do not need to later look these up from +// the global proxy, which can be mutated by users. + +// Use of primordials have sometimes a dramatic impact on performance, please +// benchmark all changes made in performance-sensitive areas of the codebase. +// See: https://github.com/nodejs/node/pull/38248 + +const primordials = {}; + +const { + defineProperty: ReflectDefineProperty, + getOwnPropertyDescriptor: ReflectGetOwnPropertyDescriptor, + ownKeys: ReflectOwnKeys, +} = Reflect; + +// `uncurryThis` is equivalent to `func => Function.prototype.call.bind(func)`. +// It is using `bind.bind(call)` to avoid using `Function.prototype.bind` +// and `Function.prototype.call` after it may have been mutated by users. +const { apply, bind, call } = Function.prototype; +const uncurryThis = bind.bind(call); +primordials.uncurryThis = uncurryThis; + +// `applyBind` is equivalent to `func => Function.prototype.apply.bind(func)`. +// It is using `bind.bind(apply)` to avoid using `Function.prototype.bind` +// and `Function.prototype.apply` after it may have been mutated by users. +const applyBind = bind.bind(apply); +primordials.applyBind = applyBind; + +// Methods that accept a variable number of arguments, and thus it's useful to +// also create `${prefix}${key}Apply`, which uses `Function.prototype.apply`, +// instead of `Function.prototype.call`, and thus doesn't require iterator +// destructuring. +const varargsMethods = [ + // 'ArrayPrototypeConcat' is omitted, because it performs the spread + // on its own for arrays and array-likes with a truthy + // @@isConcatSpreadable symbol property. + 'ArrayOf', + 'ArrayPrototypePush', + 'ArrayPrototypeUnshift', + // 'FunctionPrototypeCall' is omitted, since there's 'ReflectApply' + // and 'FunctionPrototypeApply'. + 'MathHypot', + 'MathMax', + 'MathMin', + 'StringPrototypeConcat', + 'TypedArrayOf', +]; + +function getNewKey(key) { + return typeof key === 'symbol' ? + `Symbol${key.description[7].toUpperCase()}${key.description.slice(8)}` : + `${key[0].toUpperCase()}${key.slice(1)}`; +} + +function copyAccessor(dest, prefix, key, { enumerable, get, set }) { + ReflectDefineProperty(dest, `${prefix}Get${key}`, { + value: uncurryThis(get), + enumerable + }); + if (set !== undefined) { + ReflectDefineProperty(dest, `${prefix}Set${key}`, { + value: uncurryThis(set), + enumerable + }); + } +} + +function copyPropsRenamed(src, dest, prefix) { + for (const key of ReflectOwnKeys(src)) { + const newKey = getNewKey(key); + const desc = ReflectGetOwnPropertyDescriptor(src, key); + if ('get' in desc) { + copyAccessor(dest, prefix, newKey, desc); + } else { + const name = `${prefix}${newKey}`; + ReflectDefineProperty(dest, name, desc); + if (varargsMethods.includes(name)) { + ReflectDefineProperty(dest, `${name}Apply`, { + // `src` is bound as the `this` so that the static `this` points + // to the object it was defined on, + // e.g.: `ArrayOfApply` gets a `this` of `Array`: + value: applyBind(desc.value, src), + }); + } + } + } +} + +function copyPropsRenamedBound(src, dest, prefix) { + for (const key of ReflectOwnKeys(src)) { + const newKey = getNewKey(key); + const desc = ReflectGetOwnPropertyDescriptor(src, key); + if ('get' in desc) { + copyAccessor(dest, prefix, newKey, desc); + } else { + const { value } = desc; + if (typeof value === 'function') { + desc.value = value.bind(src); + } + + const name = `${prefix}${newKey}`; + ReflectDefineProperty(dest, name, desc); + if (varargsMethods.includes(name)) { + ReflectDefineProperty(dest, `${name}Apply`, { + value: applyBind(value, src), + }); + } + } + } +} + +function copyPrototype(src, dest, prefix) { + for (const key of ReflectOwnKeys(src)) { + const newKey = getNewKey(key); + const desc = ReflectGetOwnPropertyDescriptor(src, key); + if ('get' in desc) { + copyAccessor(dest, prefix, newKey, desc); + } else { + const { value } = desc; + if (typeof value === 'function') { + desc.value = uncurryThis(value); + } + + const name = `${prefix}${newKey}`; + ReflectDefineProperty(dest, name, desc); + if (varargsMethods.includes(name)) { + ReflectDefineProperty(dest, `${name}Apply`, { + value: applyBind(value), + }); + } + } + } +} + +// Create copies of configurable value properties of the global object +[ + 'Proxy', + 'globalThis', +].forEach((name) => { + // eslint-disable-next-line no-restricted-globals + primordials[name] = globalThis[name]; +}); + +// Create copies of URI handling functions +[ + decodeURI, + decodeURIComponent, + encodeURI, + encodeURIComponent, +].forEach((fn) => { + primordials[fn.name] = fn; +}); + +// Create copies of the namespace objects +[ + 'JSON', + 'Math', + 'Proxy', + 'Reflect', +].forEach((name) => { + // eslint-disable-next-line no-restricted-globals + copyPropsRenamed(global[name], primordials, name); +}); + +// Create copies of intrinsic objects +[ + 'Array', + 'ArrayBuffer', + 'BigInt', + 'BigInt64Array', + 'BigUint64Array', + 'Boolean', + 'DataView', + 'Date', + 'Error', + 'EvalError', + 'Float32Array', + 'Float64Array', + 'Function', + 'Int16Array', + 'Int32Array', + 'Int8Array', + 'Map', + 'Number', + 'Object', + 'RangeError', + 'ReferenceError', + 'RegExp', + 'Set', + 'String', + 'Symbol', + 'SyntaxError', + 'TypeError', + 'URIError', + 'Uint16Array', + 'Uint32Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'WeakMap', + 'WeakSet', +].forEach((name) => { + // eslint-disable-next-line no-restricted-globals + const original = global[name]; + primordials[name] = original; + copyPropsRenamed(original, primordials, name); + copyPrototype(original.prototype, primordials, `${name}Prototype`); +}); + +// Create copies of intrinsic objects that require a valid `this` to call +// static methods. +// Refs: https://www.ecma-international.org/ecma-262/#sec-promise.all +[ + 'Promise', +].forEach((name) => { + // eslint-disable-next-line no-restricted-globals + const original = global[name]; + primordials[name] = original; + copyPropsRenamedBound(original, primordials, name); + copyPrototype(original.prototype, primordials, `${name}Prototype`); +}); + +// Create copies of abstract intrinsic objects that are not directly exposed +// on the global object. +// Refs: https://tc39.es/ecma262/#sec-%typedarray%-intrinsic-object +[ + { name: 'TypedArray', original: Reflect.getPrototypeOf(Uint8Array) }, + { name: 'ArrayIterator', original: { + prototype: Reflect.getPrototypeOf(Array.prototype[Symbol.iterator]()), + } }, + { name: 'StringIterator', original: { + prototype: Reflect.getPrototypeOf(String.prototype[Symbol.iterator]()), + } }, +].forEach(({ name, original }) => { + primordials[name] = original; + // The static %TypedArray% methods require a valid `this`, but can't be bound, + // as they need a subclass constructor as the receiver: + copyPrototype(original, primordials, name); + copyPrototype(original.prototype, primordials, `${name}Prototype`); +}); + +/* eslint-enable node-core/prefer-primordials */ + +const { + ArrayPrototypeForEach, + FunctionPrototypeCall, + Map, + ObjectFreeze, + ObjectSetPrototypeOf, + Set, + SymbolIterator, + WeakMap, + WeakSet, +} = primordials; + +// Because these functions are used by `makeSafe`, which is exposed +// on the `primordials` object, it's important to use const references +// to the primordials that they use: +const createSafeIterator = (factory, next) => { + class SafeIterator { + constructor(iterable) { + this._iterator = factory(iterable); + } + next() { + return next(this._iterator); + } + [SymbolIterator]() { + return this; + } + } + ObjectSetPrototypeOf(SafeIterator.prototype, null); + ObjectFreeze(SafeIterator.prototype); + ObjectFreeze(SafeIterator); + return SafeIterator; +}; + +primordials.SafeArrayIterator = createSafeIterator( + primordials.ArrayPrototypeSymbolIterator, + primordials.ArrayIteratorPrototypeNext +); +primordials.SafeStringIterator = createSafeIterator( + primordials.StringPrototypeSymbolIterator, + primordials.StringIteratorPrototypeNext +); + +const copyProps = (src, dest) => { + ArrayPrototypeForEach(ReflectOwnKeys(src), (key) => { + if (!ReflectGetOwnPropertyDescriptor(dest, key)) { + ReflectDefineProperty( + dest, + key, + ReflectGetOwnPropertyDescriptor(src, key)); + } + }); +}; + +const makeSafe = (unsafe, safe) => { + if (SymbolIterator in unsafe.prototype) { + const dummy = new unsafe(); + let next; // We can reuse the same `next` method. + + ArrayPrototypeForEach(ReflectOwnKeys(unsafe.prototype), (key) => { + if (!ReflectGetOwnPropertyDescriptor(safe.prototype, key)) { + const desc = ReflectGetOwnPropertyDescriptor(unsafe.prototype, key); + if ( + typeof desc.value === 'function' && + desc.value.length === 0 && + SymbolIterator in (FunctionPrototypeCall(desc.value, dummy) ?? {}) + ) { + const createIterator = uncurryThis(desc.value); + next = next ?? uncurryThis(createIterator(dummy).next); + const SafeIterator = createSafeIterator(createIterator, next); + desc.value = function() { + return new SafeIterator(this); + }; + } + ReflectDefineProperty(safe.prototype, key, desc); + } + }); + } else { + copyProps(unsafe.prototype, safe.prototype); + } + copyProps(unsafe, safe); + + ObjectSetPrototypeOf(safe.prototype, null); + ObjectFreeze(safe.prototype); + ObjectFreeze(safe); + return safe; +}; +primordials.makeSafe = makeSafe; + +// Subclass the constructors because we need to use their prototype +// methods later. +// Defining the `constructor` is necessary here to avoid the default +// constructor which uses the user-mutable `%ArrayIteratorPrototype%.next`. +primordials.SafeMap = makeSafe( + Map, + class SafeMap extends Map { + constructor(i) { super(i); } // eslint-disable-line no-useless-constructor + } +); +primordials.SafeWeakMap = makeSafe( + WeakMap, + class SafeWeakMap extends WeakMap { + constructor(i) { super(i); } // eslint-disable-line no-useless-constructor + } +); +primordials.SafeSet = makeSafe( + Set, + class SafeSet extends Set { + constructor(i) { super(i); } // eslint-disable-line no-useless-constructor + } +); +primordials.SafeWeakSet = makeSafe( + WeakSet, + class SafeWeakSet extends WeakSet { + constructor(i) { super(i); } // eslint-disable-line no-useless-constructor + } +); + +ObjectSetPrototypeOf(primordials, null); +ObjectFreeze(primordials); + +module.exports = primordials; diff --git a/node_modules/@pkgjs/parseargs/internal/util.js b/node_modules/@pkgjs/parseargs/internal/util.js new file mode 100644 index 0000000..b9b8fe5 --- /dev/null +++ b/node_modules/@pkgjs/parseargs/internal/util.js @@ -0,0 +1,14 @@ +'use strict'; + +// This is a placeholder for util.js in node.js land. + +const { + ObjectCreate, + ObjectFreeze, +} = require('./primordials'); + +const kEmptyObject = ObjectFreeze(ObjectCreate(null)); + +module.exports = { + kEmptyObject, +}; diff --git a/node_modules/@pkgjs/parseargs/internal/validators.js b/node_modules/@pkgjs/parseargs/internal/validators.js new file mode 100644 index 0000000..b5ac4fb --- /dev/null +++ b/node_modules/@pkgjs/parseargs/internal/validators.js @@ -0,0 +1,89 @@ +'use strict'; + +// This file is a proxy of the original file located at: +// https://github.com/nodejs/node/blob/main/lib/internal/validators.js +// Every addition or modification to this file must be evaluated +// during the PR review. + +const { + ArrayIsArray, + ArrayPrototypeIncludes, + ArrayPrototypeJoin, +} = require('./primordials'); + +const { + codes: { + ERR_INVALID_ARG_TYPE + } +} = require('./errors'); + +function validateString(value, name) { + if (typeof value !== 'string') { + throw new ERR_INVALID_ARG_TYPE(name, 'String', value); + } +} + +function validateUnion(value, name, union) { + if (!ArrayPrototypeIncludes(union, value)) { + throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value); + } +} + +function validateBoolean(value, name) { + if (typeof value !== 'boolean') { + throw new ERR_INVALID_ARG_TYPE(name, 'Boolean', value); + } +} + +function validateArray(value, name) { + if (!ArrayIsArray(value)) { + throw new ERR_INVALID_ARG_TYPE(name, 'Array', value); + } +} + +function validateStringArray(value, name) { + validateArray(value, name); + for (let i = 0; i < value.length; i++) { + validateString(value[i], `${name}[${i}]`); + } +} + +function validateBooleanArray(value, name) { + validateArray(value, name); + for (let i = 0; i < value.length; i++) { + validateBoolean(value[i], `${name}[${i}]`); + } +} + +/** + * @param {unknown} value + * @param {string} name + * @param {{ + * allowArray?: boolean, + * allowFunction?: boolean, + * nullable?: boolean + * }} [options] + */ +function validateObject(value, name, options) { + const useDefaultOptions = options == null; + const allowArray = useDefaultOptions ? false : options.allowArray; + const allowFunction = useDefaultOptions ? false : options.allowFunction; + const nullable = useDefaultOptions ? false : options.nullable; + if ((!nullable && value === null) || + (!allowArray && ArrayIsArray(value)) || + (typeof value !== 'object' && ( + !allowFunction || typeof value !== 'function' + ))) { + throw new ERR_INVALID_ARG_TYPE(name, 'Object', value); + } +} + +module.exports = { + validateArray, + validateObject, + validateString, + validateStringArray, + validateUnion, + validateBoolean, + validateBooleanArray, +}; diff --git a/node_modules/@pkgjs/parseargs/package.json b/node_modules/@pkgjs/parseargs/package.json new file mode 100644 index 0000000..0bcc05c --- /dev/null +++ b/node_modules/@pkgjs/parseargs/package.json @@ -0,0 +1,36 @@ +{ + "name": "@pkgjs/parseargs", + "version": "0.11.0", + "description": "Polyfill of future proposal for `util.parseArgs()`", + "engines": { + "node": ">=14" + }, + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "scripts": { + "coverage": "c8 --check-coverage tape 'test/*.js'", + "test": "c8 tape 'test/*.js'", + "posttest": "eslint .", + "fix": "npm run posttest -- --fix" + }, + "repository": { + "type": "git", + "url": "git@github.com:pkgjs/parseargs.git" + }, + "keywords": [], + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/pkgjs/parseargs/issues" + }, + "homepage": "https://github.com/pkgjs/parseargs#readme", + "devDependencies": { + "c8": "^7.10.0", + "eslint": "^8.2.0", + "eslint-plugin-node-core": "iansu/eslint-plugin-node-core", + "tape": "^5.2.2" + } +} diff --git a/node_modules/@pkgjs/parseargs/utils.js b/node_modules/@pkgjs/parseargs/utils.js new file mode 100644 index 0000000..d7f420a --- /dev/null +++ b/node_modules/@pkgjs/parseargs/utils.js @@ -0,0 +1,198 @@ +'use strict'; + +const { + ArrayPrototypeFind, + ObjectEntries, + ObjectPrototypeHasOwnProperty: ObjectHasOwn, + StringPrototypeCharAt, + StringPrototypeIncludes, + StringPrototypeStartsWith, +} = require('./internal/primordials'); + +const { + validateObject, +} = require('./internal/validators'); + +// These are internal utilities to make the parsing logic easier to read, and +// add lots of detail for the curious. They are in a separate file to allow +// unit testing, although that is not essential (this could be rolled into +// main file and just tested implicitly via API). +// +// These routines are for internal use, not for export to client. + +/** + * Return the named property, but only if it is an own property. + */ +function objectGetOwn(obj, prop) { + if (ObjectHasOwn(obj, prop)) + return obj[prop]; +} + +/** + * Return the named options property, but only if it is an own property. + */ +function optionsGetOwn(options, longOption, prop) { + if (ObjectHasOwn(options, longOption)) + return objectGetOwn(options[longOption], prop); +} + +/** + * Determines if the argument may be used as an option value. + * @example + * isOptionValue('V') // returns true + * isOptionValue('-v') // returns true (greedy) + * isOptionValue('--foo') // returns true (greedy) + * isOptionValue(undefined) // returns false + */ +function isOptionValue(value) { + if (value == null) return false; + + // Open Group Utility Conventions are that an option-argument + // is the argument after the option, and may start with a dash. + return true; // greedy! +} + +/** + * Detect whether there is possible confusion and user may have omitted + * the option argument, like `--port --verbose` when `port` of type:string. + * In strict mode we throw errors if value is option-like. + */ +function isOptionLikeValue(value) { + if (value == null) return false; + + return value.length > 1 && StringPrototypeCharAt(value, 0) === '-'; +} + +/** + * Determines if `arg` is just a short option. + * @example '-f' + */ +function isLoneShortOption(arg) { + return arg.length === 2 && + StringPrototypeCharAt(arg, 0) === '-' && + StringPrototypeCharAt(arg, 1) !== '-'; +} + +/** + * Determines if `arg` is a lone long option. + * @example + * isLoneLongOption('a') // returns false + * isLoneLongOption('-a') // returns false + * isLoneLongOption('--foo') // returns true + * isLoneLongOption('--foo=bar') // returns false + */ +function isLoneLongOption(arg) { + return arg.length > 2 && + StringPrototypeStartsWith(arg, '--') && + !StringPrototypeIncludes(arg, '=', 3); +} + +/** + * Determines if `arg` is a long option and value in the same argument. + * @example + * isLongOptionAndValue('--foo') // returns false + * isLongOptionAndValue('--foo=bar') // returns true + */ +function isLongOptionAndValue(arg) { + return arg.length > 2 && + StringPrototypeStartsWith(arg, '--') && + StringPrototypeIncludes(arg, '=', 3); +} + +/** + * Determines if `arg` is a short option group. + * + * See Guideline 5 of the [Open Group Utility Conventions](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html). + * One or more options without option-arguments, followed by at most one + * option that takes an option-argument, should be accepted when grouped + * behind one '-' delimiter. + * @example + * isShortOptionGroup('-a', {}) // returns false + * isShortOptionGroup('-ab', {}) // returns true + * // -fb is an option and a value, not a short option group + * isShortOptionGroup('-fb', { + * options: { f: { type: 'string' } } + * }) // returns false + * isShortOptionGroup('-bf', { + * options: { f: { type: 'string' } } + * }) // returns true + * // -bfb is an edge case, return true and caller sorts it out + * isShortOptionGroup('-bfb', { + * options: { f: { type: 'string' } } + * }) // returns true + */ +function isShortOptionGroup(arg, options) { + if (arg.length <= 2) return false; + if (StringPrototypeCharAt(arg, 0) !== '-') return false; + if (StringPrototypeCharAt(arg, 1) === '-') return false; + + const firstShort = StringPrototypeCharAt(arg, 1); + const longOption = findLongOptionForShort(firstShort, options); + return optionsGetOwn(options, longOption, 'type') !== 'string'; +} + +/** + * Determine if arg is a short string option followed by its value. + * @example + * isShortOptionAndValue('-a', {}); // returns false + * isShortOptionAndValue('-ab', {}); // returns false + * isShortOptionAndValue('-fFILE', { + * options: { foo: { short: 'f', type: 'string' }} + * }) // returns true + */ +function isShortOptionAndValue(arg, options) { + validateObject(options, 'options'); + + if (arg.length <= 2) return false; + if (StringPrototypeCharAt(arg, 0) !== '-') return false; + if (StringPrototypeCharAt(arg, 1) === '-') return false; + + const shortOption = StringPrototypeCharAt(arg, 1); + const longOption = findLongOptionForShort(shortOption, options); + return optionsGetOwn(options, longOption, 'type') === 'string'; +} + +/** + * Find the long option associated with a short option. Looks for a configured + * `short` and returns the short option itself if a long option is not found. + * @example + * findLongOptionForShort('a', {}) // returns 'a' + * findLongOptionForShort('b', { + * options: { bar: { short: 'b' } } + * }) // returns 'bar' + */ +function findLongOptionForShort(shortOption, options) { + validateObject(options, 'options'); + const longOptionEntry = ArrayPrototypeFind( + ObjectEntries(options), + ({ 1: optionConfig }) => objectGetOwn(optionConfig, 'short') === shortOption + ); + return longOptionEntry?.[0] ?? shortOption; +} + +/** + * Check if the given option includes a default value + * and that option has not been set by the input args. + * + * @param {string} longOption - long option name e.g. 'foo' + * @param {object} optionConfig - the option configuration properties + * @param {object} values - option values returned in `values` by parseArgs + */ +function useDefaultValueOption(longOption, optionConfig, values) { + return objectGetOwn(optionConfig, 'default') !== undefined && + values[longOption] === undefined; +} + +module.exports = { + findLongOptionForShort, + isLoneLongOption, + isLoneShortOption, + isLongOptionAndValue, + isOptionValue, + isOptionLikeValue, + isShortOptionAndValue, + isShortOptionGroup, + useDefaultValueOption, + objectGetOwn, + optionsGetOwn, +}; diff --git a/node_modules/any-promise/.jshintrc b/node_modules/any-promise/.jshintrc new file mode 100644 index 0000000..979105e --- /dev/null +++ b/node_modules/any-promise/.jshintrc @@ -0,0 +1,4 @@ +{ + "node":true, + "strict":true +} diff --git a/node_modules/any-promise/.npmignore b/node_modules/any-promise/.npmignore new file mode 100644 index 0000000..1354abc --- /dev/null +++ b/node_modules/any-promise/.npmignore @@ -0,0 +1,7 @@ +.git* +test/ +test-browser/ +build/ +.travis.yml +*.swp +Makefile diff --git a/node_modules/any-promise/LICENSE b/node_modules/any-promise/LICENSE new file mode 100644 index 0000000..9187fe5 --- /dev/null +++ b/node_modules/any-promise/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2014-2016 Kevin Beaty + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/any-promise/README.md b/node_modules/any-promise/README.md new file mode 100644 index 0000000..174bea4 --- /dev/null +++ b/node_modules/any-promise/README.md @@ -0,0 +1,161 @@ +## Any Promise + +[![Build Status](https://secure.travis-ci.org/kevinbeaty/any-promise.svg)](http://travis-ci.org/kevinbeaty/any-promise) + +Let your library support any ES 2015 (ES6) compatible `Promise` and leave the choice to application authors. The application can *optionally* register its preferred `Promise` implementation and it will be exported when requiring `any-promise` from library code. + +If no preference is registered, defaults to the global `Promise` for newer Node.js versions. The browser version defaults to the window `Promise`, so polyfill or register as necessary. + +### Usage with global Promise: + +Assuming the global `Promise` is the desired implementation: + +```bash +# Install any libraries depending on any-promise +$ npm install mz +``` + +The installed libraries will use global Promise by default. + +```js +// in library +var Promise = require('any-promise') // the global Promise + +function promiseReturningFunction(){ + return new Promise(function(resolve, reject){...}) +} +``` + +### Usage with registration: + +Assuming `bluebird` is the desired Promise implementation: + +```bash +# Install preferred promise library +$ npm install bluebird +# Install any-promise to allow registration +$ npm install any-promise +# Install any libraries you would like to use depending on any-promise +$ npm install mz +``` + +Register your preference in the application entry point before any other `require` of packages that load `any-promise`: + +```javascript +// top of application index.js or other entry point +require('any-promise/register/bluebird') + +// -or- Equivalent to above, but allows customization of Promise library +require('any-promise/register')('bluebird', {Promise: require('bluebird')}) +``` + +Now that the implementation is registered, you can use any package depending on `any-promise`: + + +```javascript +var fsp = require('mz/fs') // mz/fs will use registered bluebird promises +var Promise = require('any-promise') // the registered bluebird promise +``` + +It is safe to call `register` multiple times, but it must always be with the same implementation. + +Again, registration is *optional*. It should only be called by the application user if overriding the global `Promise` implementation is desired. + +### Optional Application Registration + +As an application author, you can *optionally* register a preferred `Promise` implementation on application startup (before any call to `require('any-promise')`: + +You must register your preference before any call to `require('any-promise')` (by you or required packages), and only one implementation can be registered. Typically, this registration would occur at the top of the application entry point. + + +#### Registration shortcuts + +If you are using a known `Promise` implementation, you can register your preference with a shortcut: + + +```js +require('any-promise/register/bluebird') +// -or- +import 'any-promise/register/q'; +``` + +Shortcut registration is the preferred registration method as it works in the browser and Node.js. It is also convenient for using with `import` and many test runners, that offer a `--require` flag: + +``` +$ ava --require=any-promise/register/bluebird test.js +``` + +Current known implementations include `bluebird`, `q`, `when`, `rsvp`, `es6-promise`, `promise`, `native-promise-only`, `pinkie`, `vow` and `lie`. If you are not using a known implementation, you can use another registration method described below. + + +#### Basic Registration + +As an alternative to registration shortcuts, you can call the `register` function with the preferred `Promise` implementation. The benefit of this approach is that a `Promise` library can be required by name without being a known implementation. This approach does NOT work in the browser. To use `any-promise` in the browser use either registration shortcuts or specify the `Promise` constructor using advanced registration (see below). + +```javascript +require('any-promise/register')('when') +// -or- require('any-promise/register')('any other ES6 compatible library (known or otherwise)') +``` + +This registration method will try to detect the `Promise` constructor from requiring the specified implementation. If you would like to specify your own constructor, see advanced registration. + + +#### Advanced Registration + +To use the browser version, you should either install a polyfill or explicitly register the `Promise` constructor: + +```javascript +require('any-promise/register')('bluebird', {Promise: require('bluebird')}) +``` + +This could also be used for registering a custom `Promise` implementation or subclass. + +Your preference will be registered globally, allowing a single registration even if multiple versions of `any-promise` are installed in the NPM dependency tree or are using multiple bundled JavaScript files in the browser. You can bypass this global registration in options: + + +```javascript +require('../register')('es6-promise', {Promise: require('es6-promise').Promise, global: false}) +``` + +### Library Usage + +To use any `Promise` constructor, simply require it: + +```javascript +var Promise = require('any-promise'); + +return Promise + .all([xf, f, init, coll]) + .then(fn); + + +return new Promise(function(resolve, reject){ + try { + resolve(item); + } catch(e){ + reject(e); + } +}); + +``` + +Except noted below, libraries using `any-promise` should only use [documented](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) functions as there is no guarantee which implementation will be chosen by the application author. Libraries should never call `register`, only the application user should call if desired. + + +#### Advanced Library Usage + +If your library needs to branch code based on the registered implementation, you can retrieve it using `var impl = require('any-promise/implementation')`, where `impl` will be the package name (`"bluebird"`, `"when"`, etc.) if registered, `"global.Promise"` if using the global version on Node.js, or `"window.Promise"` if using the browser version. You should always include a default case, as there is no guarantee what package may be registered. + + +### Support for old Node.js versions + +Node.js versions prior to `v0.12` may have contained buggy versions of the global `Promise`. For this reason, the global `Promise` is not loaded automatically for these old versions. If using `any-promise` in Node.js versions versions `<= v0.12`, the user should register a desired implementation. + +If an implementation is not registered, `any-promise` will attempt to discover an installed `Promise` implementation. If no implementation can be found, an error will be thrown on `require('any-promise')`. While the auto-discovery usually avoids errors, it is non-deterministic. It is recommended that the user always register a preferred implementation for older Node.js versions. + +This auto-discovery is only available for Node.jS versions prior to `v0.12`. Any newer versions will always default to the global `Promise` implementation. + +### Related + +- [any-observable](https://github.com/sindresorhus/any-observable) - `any-promise` for Observables. + diff --git a/node_modules/any-promise/implementation.d.ts b/node_modules/any-promise/implementation.d.ts new file mode 100644 index 0000000..c331a56 --- /dev/null +++ b/node_modules/any-promise/implementation.d.ts @@ -0,0 +1,3 @@ +declare var implementation: string; + +export = implementation; diff --git a/node_modules/any-promise/implementation.js b/node_modules/any-promise/implementation.js new file mode 100644 index 0000000..a45ae94 --- /dev/null +++ b/node_modules/any-promise/implementation.js @@ -0,0 +1 @@ +module.exports = require('./register')().implementation diff --git a/node_modules/any-promise/index.d.ts b/node_modules/any-promise/index.d.ts new file mode 100644 index 0000000..9f646c5 --- /dev/null +++ b/node_modules/any-promise/index.d.ts @@ -0,0 +1,73 @@ +declare class Promise implements Promise.Thenable { + /** + * If you call resolve in the body of the callback passed to the constructor, + * your promise is fulfilled with result object passed to resolve. + * If you call reject your promise is rejected with the object passed to resolve. + * For consistency and debugging (eg stack traces), obj should be an instanceof Error. + * Any errors thrown in the constructor callback will be implicitly passed to reject(). + */ + constructor (callback: (resolve : (value?: R | Promise.Thenable) => void, reject: (error?: any) => void) => void); + + /** + * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. + * + * @param onFulfilled called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects + */ + then (onFulfilled?: (value: R) => U | Promise.Thenable, onRejected?: (error: any) => U | Promise.Thenable): Promise; + then (onFulfilled?: (value: R) => U | Promise.Thenable, onRejected?: (error: any) => void): Promise; + + /** + * Sugar for promise.then(undefined, onRejected) + * + * @param onRejected called when/if "promise" rejects + */ + catch (onRejected?: (error: any) => U | Promise.Thenable): Promise; + + /** + * Make a new promise from the thenable. + * A thenable is promise-like in as far as it has a "then" method. + */ + static resolve (): Promise; + static resolve (value: R | Promise.Thenable): Promise; + + /** + * Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error + */ + static reject (error: any): Promise; + + /** + * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects. + * the array passed to all can be a mixture of promise-like objects and other objects. + * The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value. + */ + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable, T6 | Promise.Thenable, T7 | Promise.Thenable, T8 | Promise.Thenable, T9 | Promise.Thenable, T10 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable, T6 | Promise.Thenable, T7 | Promise.Thenable, T8 | Promise.Thenable, T9 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable, T6 | Promise.Thenable, T7 | Promise.Thenable, T8 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable, T6 | Promise.Thenable, T7 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable, T6 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5, T6]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable , T5 | Promise.Thenable]): Promise<[T1, T2, T3, T4, T5]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable, T4 | Promise.Thenable ]): Promise<[T1, T2, T3, T4]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable, T3 | Promise.Thenable]): Promise<[T1, T2, T3]>; + static all (values: [T1 | Promise.Thenable, T2 | Promise.Thenable]): Promise<[T1, T2]>; + static all (values: [T1 | Promise.Thenable]): Promise<[T1]>; + static all (values: Array>): Promise; + + /** + * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects. + */ + static race (promises: (R | Promise.Thenable)[]): Promise; +} + +declare namespace Promise { + export interface Thenable { + then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; + then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => void): Thenable; + } +} + +export = Promise; diff --git a/node_modules/any-promise/index.js b/node_modules/any-promise/index.js new file mode 100644 index 0000000..74b8548 --- /dev/null +++ b/node_modules/any-promise/index.js @@ -0,0 +1 @@ +module.exports = require('./register')().Promise diff --git a/node_modules/any-promise/loader.js b/node_modules/any-promise/loader.js new file mode 100644 index 0000000..e164914 --- /dev/null +++ b/node_modules/any-promise/loader.js @@ -0,0 +1,78 @@ +"use strict" + // global key for user preferred registration +var REGISTRATION_KEY = '@@any-promise/REGISTRATION', + // Prior registration (preferred or detected) + registered = null + +/** + * Registers the given implementation. An implementation must + * be registered prior to any call to `require("any-promise")`, + * typically on application load. + * + * If called with no arguments, will return registration in + * following priority: + * + * For Node.js: + * + * 1. Previous registration + * 2. global.Promise if node.js version >= 0.12 + * 3. Auto detected promise based on first sucessful require of + * known promise libraries. Note this is a last resort, as the + * loaded library is non-deterministic. node.js >= 0.12 will + * always use global.Promise over this priority list. + * 4. Throws error. + * + * For Browser: + * + * 1. Previous registration + * 2. window.Promise + * 3. Throws error. + * + * Options: + * + * Promise: Desired Promise constructor + * global: Boolean - Should the registration be cached in a global variable to + * allow cross dependency/bundle registration? (default true) + */ +module.exports = function(root, loadImplementation){ + return function register(implementation, opts){ + implementation = implementation || null + opts = opts || {} + // global registration unless explicitly {global: false} in options (default true) + var registerGlobal = opts.global !== false; + + // load any previous global registration + if(registered === null && registerGlobal){ + registered = root[REGISTRATION_KEY] || null + } + + if(registered !== null + && implementation !== null + && registered.implementation !== implementation){ + // Throw error if attempting to redefine implementation + throw new Error('any-promise already defined as "'+registered.implementation+ + '". You can only register an implementation before the first '+ + ' call to require("any-promise") and an implementation cannot be changed') + } + + if(registered === null){ + // use provided implementation + if(implementation !== null && typeof opts.Promise !== 'undefined'){ + registered = { + Promise: opts.Promise, + implementation: implementation + } + } else { + // require implementation if implementation is specified but not provided + registered = loadImplementation(implementation) + } + + if(registerGlobal){ + // register preference globally in case multiple installations + root[REGISTRATION_KEY] = registered + } + } + + return registered + } +} diff --git a/node_modules/any-promise/optional.js b/node_modules/any-promise/optional.js new file mode 100644 index 0000000..f388942 --- /dev/null +++ b/node_modules/any-promise/optional.js @@ -0,0 +1,6 @@ +"use strict"; +try { + module.exports = require('./register')().Promise || null +} catch(e) { + module.exports = null +} diff --git a/node_modules/any-promise/package.json b/node_modules/any-promise/package.json new file mode 100644 index 0000000..5baf14c --- /dev/null +++ b/node_modules/any-promise/package.json @@ -0,0 +1,45 @@ +{ + "name": "any-promise", + "version": "1.3.0", + "description": "Resolve any installed ES6 compatible promise", + "main": "index.js", + "typings": "index.d.ts", + "browser": { + "./register.js": "./register-shim.js" + }, + "scripts": { + "test": "ava" + }, + "repository": { + "type": "git", + "url": "https://github.com/kevinbeaty/any-promise" + }, + "keywords": [ + "promise", + "es6" + ], + "author": "Kevin Beaty", + "license": "MIT", + "bugs": { + "url": "https://github.com/kevinbeaty/any-promise/issues" + }, + "homepage": "http://github.com/kevinbeaty/any-promise", + "dependencies": {}, + "devDependencies": { + "ava": "^0.14.0", + "bluebird": "^3.0.0", + "es6-promise": "^3.0.0", + "is-promise": "^2.0.0", + "lie": "^3.0.0", + "mocha": "^2.0.0", + "native-promise-only": "^0.8.0", + "phantomjs-prebuilt": "^2.0.0", + "pinkie": "^2.0.0", + "promise": "^7.0.0", + "q": "^1.0.0", + "rsvp": "^3.0.0", + "vow": "^0.4.0", + "when": "^3.0.0", + "zuul": "^3.0.0" + } +} diff --git a/node_modules/any-promise/register-shim.js b/node_modules/any-promise/register-shim.js new file mode 100644 index 0000000..9049405 --- /dev/null +++ b/node_modules/any-promise/register-shim.js @@ -0,0 +1,18 @@ +"use strict"; +module.exports = require('./loader')(window, loadImplementation) + +/** + * Browser specific loadImplementation. Always uses `window.Promise` + * + * To register a custom implementation, must register with `Promise` option. + */ +function loadImplementation(){ + if(typeof window.Promise === 'undefined'){ + throw new Error("any-promise browser requires a polyfill or explicit registration"+ + " e.g: require('any-promise/register/bluebird')") + } + return { + Promise: window.Promise, + implementation: 'window.Promise' + } +} diff --git a/node_modules/any-promise/register.d.ts b/node_modules/any-promise/register.d.ts new file mode 100644 index 0000000..97f2fc0 --- /dev/null +++ b/node_modules/any-promise/register.d.ts @@ -0,0 +1,17 @@ +import Promise = require('./index'); + +declare function register (module?: string, options?: register.Options): register.Register; + +declare namespace register { + export interface Register { + Promise: typeof Promise; + implementation: string; + } + + export interface Options { + Promise?: typeof Promise; + global?: boolean + } +} + +export = register; diff --git a/node_modules/any-promise/register.js b/node_modules/any-promise/register.js new file mode 100644 index 0000000..255c6e2 --- /dev/null +++ b/node_modules/any-promise/register.js @@ -0,0 +1,94 @@ +"use strict" +module.exports = require('./loader')(global, loadImplementation); + +/** + * Node.js version of loadImplementation. + * + * Requires the given implementation and returns the registration + * containing {Promise, implementation} + * + * If implementation is undefined or global.Promise, loads it + * Otherwise uses require + */ +function loadImplementation(implementation){ + var impl = null + + if(shouldPreferGlobalPromise(implementation)){ + // if no implementation or env specified use global.Promise + impl = { + Promise: global.Promise, + implementation: 'global.Promise' + } + } else if(implementation){ + // if implementation specified, require it + var lib = require(implementation) + impl = { + Promise: lib.Promise || lib, + implementation: implementation + } + } else { + // try to auto detect implementation. This is non-deterministic + // and should prefer other branches, but this is our last chance + // to load something without throwing error + impl = tryAutoDetect() + } + + if(impl === null){ + throw new Error('Cannot find any-promise implementation nor'+ + ' global.Promise. You must install polyfill or call'+ + ' require("any-promise/register") with your preferred'+ + ' implementation, e.g. require("any-promise/register/bluebird")'+ + ' on application load prior to any require("any-promise").') + } + + return impl +} + +/** + * Determines if the global.Promise should be preferred if an implementation + * has not been registered. + */ +function shouldPreferGlobalPromise(implementation){ + if(implementation){ + return implementation === 'global.Promise' + } else if(typeof global.Promise !== 'undefined'){ + // Load global promise if implementation not specified + // Versions < 0.11 did not have global Promise + // Do not use for version < 0.12 as version 0.11 contained buggy versions + var version = (/v(\d+)\.(\d+)\.(\d+)/).exec(process.version) + return !(version && +version[1] == 0 && +version[2] < 12) + } + + // do not have global.Promise or another implementation was specified + return false +} + +/** + * Look for common libs as last resort there is no guarantee that + * this will return a desired implementation or even be deterministic. + * The priority is also nearly arbitrary. We are only doing this + * for older versions of Node.js <0.12 that do not have a reasonable + * global.Promise implementation and we the user has not registered + * the preference. This preserves the behavior of any-promise <= 0.1 + * and may be deprecated or removed in the future + */ +function tryAutoDetect(){ + var libs = [ + "es6-promise", + "promise", + "native-promise-only", + "bluebird", + "rsvp", + "when", + "q", + "pinkie", + "lie", + "vow"] + var i = 0, len = libs.length + for(; i < len; i++){ + try { + return loadImplementation(libs[i]) + } catch(e){} + } + return null +} diff --git a/node_modules/any-promise/register/bluebird.d.ts b/node_modules/any-promise/register/bluebird.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/bluebird.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/bluebird.js b/node_modules/any-promise/register/bluebird.js new file mode 100644 index 0000000..de0f87e --- /dev/null +++ b/node_modules/any-promise/register/bluebird.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('bluebird', {Promise: require('bluebird')}) diff --git a/node_modules/any-promise/register/es6-promise.d.ts b/node_modules/any-promise/register/es6-promise.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/es6-promise.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/es6-promise.js b/node_modules/any-promise/register/es6-promise.js new file mode 100644 index 0000000..59bd55b --- /dev/null +++ b/node_modules/any-promise/register/es6-promise.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('es6-promise', {Promise: require('es6-promise').Promise}) diff --git a/node_modules/any-promise/register/lie.d.ts b/node_modules/any-promise/register/lie.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/lie.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/lie.js b/node_modules/any-promise/register/lie.js new file mode 100644 index 0000000..7d305ca --- /dev/null +++ b/node_modules/any-promise/register/lie.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('lie', {Promise: require('lie')}) diff --git a/node_modules/any-promise/register/native-promise-only.d.ts b/node_modules/any-promise/register/native-promise-only.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/native-promise-only.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/native-promise-only.js b/node_modules/any-promise/register/native-promise-only.js new file mode 100644 index 0000000..70a5a5e --- /dev/null +++ b/node_modules/any-promise/register/native-promise-only.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('native-promise-only', {Promise: require('native-promise-only')}) diff --git a/node_modules/any-promise/register/pinkie.d.ts b/node_modules/any-promise/register/pinkie.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/pinkie.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/pinkie.js b/node_modules/any-promise/register/pinkie.js new file mode 100644 index 0000000..caaf98a --- /dev/null +++ b/node_modules/any-promise/register/pinkie.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('pinkie', {Promise: require('pinkie')}) diff --git a/node_modules/any-promise/register/promise.d.ts b/node_modules/any-promise/register/promise.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/promise.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/promise.js b/node_modules/any-promise/register/promise.js new file mode 100644 index 0000000..746620d --- /dev/null +++ b/node_modules/any-promise/register/promise.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('promise', {Promise: require('promise')}) diff --git a/node_modules/any-promise/register/q.d.ts b/node_modules/any-promise/register/q.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/q.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/q.js b/node_modules/any-promise/register/q.js new file mode 100644 index 0000000..0fc633a --- /dev/null +++ b/node_modules/any-promise/register/q.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('q', {Promise: require('q').Promise}) diff --git a/node_modules/any-promise/register/rsvp.d.ts b/node_modules/any-promise/register/rsvp.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/rsvp.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/rsvp.js b/node_modules/any-promise/register/rsvp.js new file mode 100644 index 0000000..02b1318 --- /dev/null +++ b/node_modules/any-promise/register/rsvp.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('rsvp', {Promise: require('rsvp').Promise}) diff --git a/node_modules/any-promise/register/vow.d.ts b/node_modules/any-promise/register/vow.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/vow.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/vow.js b/node_modules/any-promise/register/vow.js new file mode 100644 index 0000000..5b6868c --- /dev/null +++ b/node_modules/any-promise/register/vow.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('vow', {Promise: require('vow').Promise}) diff --git a/node_modules/any-promise/register/when.d.ts b/node_modules/any-promise/register/when.d.ts new file mode 100644 index 0000000..336ce12 --- /dev/null +++ b/node_modules/any-promise/register/when.d.ts @@ -0,0 +1 @@ +export {} diff --git a/node_modules/any-promise/register/when.js b/node_modules/any-promise/register/when.js new file mode 100644 index 0000000..d91c13d --- /dev/null +++ b/node_modules/any-promise/register/when.js @@ -0,0 +1,2 @@ +'use strict'; +require('../register')('when', {Promise: require('when').Promise}) diff --git a/node_modules/anymatch/LICENSE b/node_modules/anymatch/LICENSE new file mode 100644 index 0000000..491766c --- /dev/null +++ b/node_modules/anymatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com) + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/anymatch/README.md b/node_modules/anymatch/README.md new file mode 100644 index 0000000..1dd67f5 --- /dev/null +++ b/node_modules/anymatch/README.md @@ -0,0 +1,87 @@ +anymatch [![Build Status](https://travis-ci.org/micromatch/anymatch.svg?branch=master)](https://travis-ci.org/micromatch/anymatch) [![Coverage Status](https://img.shields.io/coveralls/micromatch/anymatch.svg?branch=master)](https://coveralls.io/r/micromatch/anymatch?branch=master) +====== +Javascript module to match a string against a regular expression, glob, string, +or function that takes the string as an argument and returns a truthy or falsy +value. The matcher can also be an array of any or all of these. Useful for +allowing a very flexible user-defined config to define things like file paths. + +__Note: This module has Bash-parity, please be aware that Windows-style backslashes are not supported as separators. See https://github.com/micromatch/micromatch#backslashes for more information.__ + + +Usage +----- +```sh +npm install anymatch +``` + +#### anymatch(matchers, testString, [returnIndex], [options]) +* __matchers__: (_Array|String|RegExp|Function_) +String to be directly matched, string with glob patterns, regular expression +test, function that takes the testString as an argument and returns a truthy +value if it should be matched, or an array of any number and mix of these types. +* __testString__: (_String|Array_) The string to test against the matchers. If +passed as an array, the first element of the array will be used as the +`testString` for non-function matchers, while the entire array will be applied +as the arguments for function matchers. +* __options__: (_Object_ [optional]_) Any of the [picomatch](https://github.com/micromatch/picomatch#options) options. + * __returnIndex__: (_Boolean [optional]_) If true, return the array index of +the first matcher that that testString matched, or -1 if no match, instead of a +boolean result. + +```js +const anymatch = require('anymatch'); + +const matchers = [ 'path/to/file.js', 'path/anyjs/**/*.js', /foo.js$/, string => string.includes('bar') && string.length > 10 ] ; + +anymatch(matchers, 'path/to/file.js'); // true +anymatch(matchers, 'path/anyjs/baz.js'); // true +anymatch(matchers, 'path/to/foo.js'); // true +anymatch(matchers, 'path/to/bar.js'); // true +anymatch(matchers, 'bar.js'); // false + +// returnIndex = true +anymatch(matchers, 'foo.js', {returnIndex: true}); // 2 +anymatch(matchers, 'path/anyjs/foo.js', {returnIndex: true}); // 1 + +// any picomatc + +// using globs to match directories and their children +anymatch('node_modules', 'node_modules'); // true +anymatch('node_modules', 'node_modules/somelib/index.js'); // false +anymatch('node_modules/**', 'node_modules/somelib/index.js'); // true +anymatch('node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // false +anymatch('**/node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // true + +const matcher = anymatch(matchers); +['foo.js', 'bar.js'].filter(matcher); // [ 'foo.js' ] +anymatch master* ❯ + +``` + +#### anymatch(matchers) +You can also pass in only your matcher(s) to get a curried function that has +already been bound to the provided matching criteria. This can be used as an +`Array#filter` callback. + +```js +var matcher = anymatch(matchers); + +matcher('path/to/file.js'); // true +matcher('path/anyjs/baz.js', true); // 1 + +['foo.js', 'bar.js'].filter(matcher); // ['foo.js'] +``` + +Changelog +---------- +[See release notes page on GitHub](https://github.com/micromatch/anymatch/releases) + +- **v3.0:** Removed `startIndex` and `endIndex` arguments. Node 8.x-only. +- **v2.0:** [micromatch](https://github.com/jonschlinkert/micromatch) moves away from minimatch-parity and inline with Bash. This includes handling backslashes differently (see https://github.com/micromatch/micromatch#backslashes for more information). +- **v1.2:** anymatch uses [micromatch](https://github.com/jonschlinkert/micromatch) +for glob pattern matching. Issues with glob pattern matching should be +reported directly to the [micromatch issue tracker](https://github.com/jonschlinkert/micromatch/issues). + +License +------- +[ISC](https://raw.github.com/micromatch/anymatch/master/LICENSE) diff --git a/node_modules/anymatch/index.d.ts b/node_modules/anymatch/index.d.ts new file mode 100644 index 0000000..3ef7eaa --- /dev/null +++ b/node_modules/anymatch/index.d.ts @@ -0,0 +1,20 @@ +type AnymatchFn = (testString: string) => boolean; +type AnymatchPattern = string|RegExp|AnymatchFn; +type AnymatchMatcher = AnymatchPattern|AnymatchPattern[] +type AnymatchTester = { + (testString: string|any[], returnIndex: true): number; + (testString: string|any[]): boolean; +} + +type PicomatchOptions = {dot: boolean}; + +declare const anymatch: { + (matchers: AnymatchMatcher): AnymatchTester; + (matchers: AnymatchMatcher, testString: null, returnIndex: true | PicomatchOptions): AnymatchTester; + (matchers: AnymatchMatcher, testString: string|any[], returnIndex: true | PicomatchOptions): number; + (matchers: AnymatchMatcher, testString: string|any[]): boolean; +} + +export {AnymatchMatcher as Matcher} +export {AnymatchTester as Tester} +export default anymatch diff --git a/node_modules/anymatch/index.js b/node_modules/anymatch/index.js new file mode 100644 index 0000000..8eb73e9 --- /dev/null +++ b/node_modules/anymatch/index.js @@ -0,0 +1,104 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { value: true }); + +const picomatch = require('picomatch'); +const normalizePath = require('normalize-path'); + +/** + * @typedef {(testString: string) => boolean} AnymatchFn + * @typedef {string|RegExp|AnymatchFn} AnymatchPattern + * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher + */ +const BANG = '!'; +const DEFAULT_OPTIONS = {returnIndex: false}; +const arrify = (item) => Array.isArray(item) ? item : [item]; + +/** + * @param {AnymatchPattern} matcher + * @param {object} options + * @returns {AnymatchFn} + */ +const createPattern = (matcher, options) => { + if (typeof matcher === 'function') { + return matcher; + } + if (typeof matcher === 'string') { + const glob = picomatch(matcher, options); + return (string) => matcher === string || glob(string); + } + if (matcher instanceof RegExp) { + return (string) => matcher.test(string); + } + return (string) => false; +}; + +/** + * @param {Array} patterns + * @param {Array} negPatterns + * @param {String|Array} args + * @param {Boolean} returnIndex + * @returns {boolean|number} + */ +const matchPatterns = (patterns, negPatterns, args, returnIndex) => { + const isList = Array.isArray(args); + const _path = isList ? args[0] : args; + if (!isList && typeof _path !== 'string') { + throw new TypeError('anymatch: second argument must be a string: got ' + + Object.prototype.toString.call(_path)) + } + const path = normalizePath(_path, false); + + for (let index = 0; index < negPatterns.length; index++) { + const nglob = negPatterns[index]; + if (nglob(path)) { + return returnIndex ? -1 : false; + } + } + + const applied = isList && [path].concat(args.slice(1)); + for (let index = 0; index < patterns.length; index++) { + const pattern = patterns[index]; + if (isList ? pattern(...applied) : pattern(path)) { + return returnIndex ? index : true; + } + } + + return returnIndex ? -1 : false; +}; + +/** + * @param {AnymatchMatcher} matchers + * @param {Array|string} testString + * @param {object} options + * @returns {boolean|number|Function} + */ +const anymatch = (matchers, testString, options = DEFAULT_OPTIONS) => { + if (matchers == null) { + throw new TypeError('anymatch: specify first argument'); + } + const opts = typeof options === 'boolean' ? {returnIndex: options} : options; + const returnIndex = opts.returnIndex || false; + + // Early cache for matchers. + const mtchers = arrify(matchers); + const negatedGlobs = mtchers + .filter(item => typeof item === 'string' && item.charAt(0) === BANG) + .map(item => item.slice(1)) + .map(item => picomatch(item, opts)); + const patterns = mtchers + .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG)) + .map(matcher => createPattern(matcher, opts)); + + if (testString == null) { + return (testString, ri = false) => { + const returnIndex = typeof ri === 'boolean' ? ri : false; + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); + } + } + + return matchPatterns(patterns, negatedGlobs, testString, returnIndex); +}; + +anymatch.default = anymatch; +module.exports = anymatch; diff --git a/node_modules/anymatch/package.json b/node_modules/anymatch/package.json new file mode 100644 index 0000000..2cb2307 --- /dev/null +++ b/node_modules/anymatch/package.json @@ -0,0 +1,48 @@ +{ + "name": "anymatch", + "version": "3.1.3", + "description": "Matches strings against configurable strings, globs, regular expressions, and/or functions", + "files": [ + "index.js", + "index.d.ts" + ], + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "author": { + "name": "Elan Shanker", + "url": "https://github.com/es128" + }, + "license": "ISC", + "homepage": "https://github.com/micromatch/anymatch", + "repository": { + "type": "git", + "url": "https://github.com/micromatch/anymatch" + }, + "keywords": [ + "match", + "any", + "string", + "file", + "fs", + "list", + "glob", + "regex", + "regexp", + "regular", + "expression", + "function" + ], + "scripts": { + "test": "nyc mocha", + "mocha": "mocha" + }, + "devDependencies": { + "mocha": "^6.1.3", + "nyc": "^14.0.0" + }, + "engines": { + "node": ">= 8" + } +} diff --git a/node_modules/arg/LICENSE.md b/node_modules/arg/LICENSE.md new file mode 100644 index 0000000..b708f87 --- /dev/null +++ b/node_modules/arg/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2021 Vercel, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/arg/README.md b/node_modules/arg/README.md new file mode 100644 index 0000000..6501df5 --- /dev/null +++ b/node_modules/arg/README.md @@ -0,0 +1,317 @@ +# Arg + +`arg` is an unopinionated, no-frills CLI argument parser. + +## Installation + +```bash +npm install arg +``` + +## Usage + +`arg()` takes either 1 or 2 arguments: + +1. Command line specification object (see below) +2. Parse options (_Optional_, defaults to `{permissive: false, argv: process.argv.slice(2), stopAtPositional: false}`) + +It returns an object with any values present on the command-line (missing options are thus +missing from the resulting object). Arg performs no validation/requirement checking - we +leave that up to the application. + +All parameters that aren't consumed by options (commonly referred to as "extra" parameters) +are added to `result._`, which is _always_ an array (even if no extra parameters are passed, +in which case an empty array is returned). + +```javascript +const arg = require('arg'); + +// `options` is an optional parameter +const args = arg( + spec, + (options = { permissive: false, argv: process.argv.slice(2) }) +); +``` + +For example: + +```console +$ node ./hello.js --verbose -vvv --port=1234 -n 'My name' foo bar --tag qux --tag=qix -- --foobar +``` + +```javascript +// hello.js +const arg = require('arg'); + +const args = arg({ + // Types + '--help': Boolean, + '--version': Boolean, + '--verbose': arg.COUNT, // Counts the number of times --verbose is passed + '--port': Number, // --port or --port= + '--name': String, // --name or --name= + '--tag': [String], // --tag or --tag= + + // Aliases + '-v': '--verbose', + '-n': '--name', // -n ; result is stored in --name + '--label': '--name' // --label or --label=; + // result is stored in --name +}); + +console.log(args); +/* +{ + _: ["foo", "bar", "--foobar"], + '--port': 1234, + '--verbose': 4, + '--name': "My name", + '--tag': ["qux", "qix"] +} +*/ +``` + +The values for each key=>value pair is either a type (function or [function]) or a string (indicating an alias). + +- In the case of a function, the string value of the argument's value is passed to it, + and the return value is used as the ultimate value. + +- In the case of an array, the only element _must_ be a type function. Array types indicate + that the argument may be passed multiple times, and as such the resulting value in the returned + object is an array with all of the values that were passed using the specified flag. + +- In the case of a string, an alias is established. If a flag is passed that matches the _key_, + then the _value_ is substituted in its place. + +Type functions are passed three arguments: + +1. The parameter value (always a string) +2. The parameter name (e.g. `--label`) +3. The previous value for the destination (useful for reduce-like operations or for supporting `-v` multiple times, etc.) + +This means the built-in `String`, `Number`, and `Boolean` type constructors "just work" as type functions. + +Note that `Boolean` and `[Boolean]` have special treatment - an option argument is _not_ consumed or passed, but instead `true` is +returned. These options are called "flags". + +For custom handlers that wish to behave as flags, you may pass the function through `arg.flag()`: + +```javascript +const arg = require('arg'); + +const argv = [ + '--foo', + 'bar', + '-ff', + 'baz', + '--foo', + '--foo', + 'qux', + '-fff', + 'qix' +]; + +function myHandler(value, argName, previousValue) { + /* `value` is always `true` */ + return 'na ' + (previousValue || 'batman!'); +} + +const args = arg( + { + '--foo': arg.flag(myHandler), + '-f': '--foo' + }, + { + argv + } +); + +console.log(args); +/* +{ + _: ['bar', 'baz', 'qux', 'qix'], + '--foo': 'na na na na na na na na batman!' +} +*/ +``` + +As well, `arg` supplies a helper argument handler called `arg.COUNT`, which equivalent to a `[Boolean]` argument's `.length` +property - effectively counting the number of times the boolean flag, denoted by the key, is passed on the command line.. +For example, this is how you could implement `ssh`'s multiple levels of verbosity (`-vvvv` being the most verbose). + +```javascript +const arg = require('arg'); + +const argv = ['-AAAA', '-BBBB']; + +const args = arg( + { + '-A': arg.COUNT, + '-B': [Boolean] + }, + { + argv + } +); + +console.log(args); +/* +{ + _: [], + '-A': 4, + '-B': [true, true, true, true] +} +*/ +``` + +### Options + +If a second parameter is specified and is an object, it specifies parsing options to modify the behavior of `arg()`. + +#### `argv` + +If you have already sliced or generated a number of raw arguments to be parsed (as opposed to letting `arg` +slice them from `process.argv`) you may specify them in the `argv` option. + +For example: + +```javascript +const args = arg( + { + '--foo': String + }, + { + argv: ['hello', '--foo', 'world'] + } +); +``` + +results in: + +```javascript +const args = { + _: ['hello'], + '--foo': 'world' +}; +``` + +#### `permissive` + +When `permissive` set to `true`, `arg` will push any unknown arguments +onto the "extra" argument array (`result._`) instead of throwing an error about +an unknown flag. + +For example: + +```javascript +const arg = require('arg'); + +const argv = [ + '--foo', + 'hello', + '--qux', + 'qix', + '--bar', + '12345', + 'hello again' +]; + +const args = arg( + { + '--foo': String, + '--bar': Number + }, + { + argv, + permissive: true + } +); +``` + +results in: + +```javascript +const args = { + _: ['--qux', 'qix', 'hello again'], + '--foo': 'hello', + '--bar': 12345 +}; +``` + +#### `stopAtPositional` + +When `stopAtPositional` is set to `true`, `arg` will halt parsing at the first +positional argument. + +For example: + +```javascript +const arg = require('arg'); + +const argv = ['--foo', 'hello', '--bar']; + +const args = arg( + { + '--foo': Boolean, + '--bar': Boolean + }, + { + argv, + stopAtPositional: true + } +); +``` + +results in: + +```javascript +const args = { + _: ['hello', '--bar'], + '--foo': true +}; +``` + +### Errors + +Some errors that `arg` throws provide a `.code` property in order to aid in recovering from user error, or to +differentiate between user error and developer error (bug). + +##### ARG_UNKNOWN_OPTION + +If an unknown option (not defined in the spec object) is passed, an error with code `ARG_UNKNOWN_OPTION` will be thrown: + +```js +// cli.js +try { + require('arg')({ '--hi': String }); +} catch (err) { + if (err.code === 'ARG_UNKNOWN_OPTION') { + console.log(err.message); + } else { + throw err; + } +} +``` + +```shell +node cli.js --extraneous true +Unknown or unexpected option: --extraneous +``` + +# FAQ + +A few questions and answers that have been asked before: + +### How do I require an argument with `arg`? + +Do the assertion yourself, such as: + +```javascript +const args = arg({ '--name': String }); + +if (!args['--name']) throw new Error('missing required argument: --name'); +``` + +# License + +Released under the [MIT License](LICENSE.md). diff --git a/node_modules/arg/index.d.ts b/node_modules/arg/index.d.ts new file mode 100644 index 0000000..44f9f35 --- /dev/null +++ b/node_modules/arg/index.d.ts @@ -0,0 +1,44 @@ +declare function arg( + spec: T, + options?: arg.Options +): arg.Result; + +declare namespace arg { + export const flagSymbol: unique symbol; + + export function flag(fn: T): T & { [arg.flagSymbol]: true }; + + export const COUNT: Handler & { [arg.flagSymbol]: true }; + + export type Handler = ( + value: string, + name: string, + previousValue?: T + ) => T; + + export class ArgError extends Error { + constructor(message: string, code: string); + + code: string; + } + + export interface Spec { + [key: string]: string | Handler | [Handler]; + } + + export type Result = { _: string[] } & { + [K in keyof T]?: T[K] extends Handler + ? ReturnType + : T[K] extends [Handler] + ? Array> + : never; + }; + + export interface Options { + argv?: string[]; + permissive?: boolean; + stopAtPositional?: boolean; + } +} + +export = arg; diff --git a/node_modules/arg/index.js b/node_modules/arg/index.js new file mode 100644 index 0000000..3f60f4c --- /dev/null +++ b/node_modules/arg/index.js @@ -0,0 +1,195 @@ +const flagSymbol = Symbol('arg flag'); + +class ArgError extends Error { + constructor(msg, code) { + super(msg); + this.name = 'ArgError'; + this.code = code; + + Object.setPrototypeOf(this, ArgError.prototype); + } +} + +function arg( + opts, + { + argv = process.argv.slice(2), + permissive = false, + stopAtPositional = false + } = {} +) { + if (!opts) { + throw new ArgError( + 'argument specification object is required', + 'ARG_CONFIG_NO_SPEC' + ); + } + + const result = { _: [] }; + + const aliases = {}; + const handlers = {}; + + for (const key of Object.keys(opts)) { + if (!key) { + throw new ArgError( + 'argument key cannot be an empty string', + 'ARG_CONFIG_EMPTY_KEY' + ); + } + + if (key[0] !== '-') { + throw new ArgError( + `argument key must start with '-' but found: '${key}'`, + 'ARG_CONFIG_NONOPT_KEY' + ); + } + + if (key.length === 1) { + throw new ArgError( + `argument key must have a name; singular '-' keys are not allowed: ${key}`, + 'ARG_CONFIG_NONAME_KEY' + ); + } + + if (typeof opts[key] === 'string') { + aliases[key] = opts[key]; + continue; + } + + let type = opts[key]; + let isFlag = false; + + if ( + Array.isArray(type) && + type.length === 1 && + typeof type[0] === 'function' + ) { + const [fn] = type; + type = (value, name, prev = []) => { + prev.push(fn(value, name, prev[prev.length - 1])); + return prev; + }; + isFlag = fn === Boolean || fn[flagSymbol] === true; + } else if (typeof type === 'function') { + isFlag = type === Boolean || type[flagSymbol] === true; + } else { + throw new ArgError( + `type missing or not a function or valid array type: ${key}`, + 'ARG_CONFIG_VAD_TYPE' + ); + } + + if (key[1] !== '-' && key.length > 2) { + throw new ArgError( + `short argument keys (with a single hyphen) must have only one character: ${key}`, + 'ARG_CONFIG_SHORTOPT_TOOLONG' + ); + } + + handlers[key] = [type, isFlag]; + } + + for (let i = 0, len = argv.length; i < len; i++) { + const wholeArg = argv[i]; + + if (stopAtPositional && result._.length > 0) { + result._ = result._.concat(argv.slice(i)); + break; + } + + if (wholeArg === '--') { + result._ = result._.concat(argv.slice(i + 1)); + break; + } + + if (wholeArg.length > 1 && wholeArg[0] === '-') { + /* eslint-disable operator-linebreak */ + const separatedArguments = + wholeArg[1] === '-' || wholeArg.length === 2 + ? [wholeArg] + : wholeArg + .slice(1) + .split('') + .map((a) => `-${a}`); + /* eslint-enable operator-linebreak */ + + for (let j = 0; j < separatedArguments.length; j++) { + const arg = separatedArguments[j]; + const [originalArgName, argStr] = + arg[1] === '-' ? arg.split(/=(.*)/, 2) : [arg, undefined]; + + let argName = originalArgName; + while (argName in aliases) { + argName = aliases[argName]; + } + + if (!(argName in handlers)) { + if (permissive) { + result._.push(arg); + continue; + } else { + throw new ArgError( + `unknown or unexpected option: ${originalArgName}`, + 'ARG_UNKNOWN_OPTION' + ); + } + } + + const [type, isFlag] = handlers[argName]; + + if (!isFlag && j + 1 < separatedArguments.length) { + throw new ArgError( + `option requires argument (but was followed by another short argument): ${originalArgName}`, + 'ARG_MISSING_REQUIRED_SHORTARG' + ); + } + + if (isFlag) { + result[argName] = type(true, argName, result[argName]); + } else if (argStr === undefined) { + if ( + argv.length < i + 2 || + (argv[i + 1].length > 1 && + argv[i + 1][0] === '-' && + !( + argv[i + 1].match(/^-?\d*(\.(?=\d))?\d*$/) && + (type === Number || + // eslint-disable-next-line no-undef + (typeof BigInt !== 'undefined' && type === BigInt)) + )) + ) { + const extended = + originalArgName === argName ? '' : ` (alias for ${argName})`; + throw new ArgError( + `option requires argument: ${originalArgName}${extended}`, + 'ARG_MISSING_REQUIRED_LONGARG' + ); + } + + result[argName] = type(argv[i + 1], argName, result[argName]); + ++i; + } else { + result[argName] = type(argStr, argName, result[argName]); + } + } + } else { + result._.push(wholeArg); + } + } + + return result; +} + +arg.flag = (fn) => { + fn[flagSymbol] = true; + return fn; +}; + +// Utility types +arg.COUNT = arg.flag((v, name, existingCount) => (existingCount || 0) + 1); + +// Expose error class +arg.ArgError = ArgError; + +module.exports = arg; diff --git a/node_modules/arg/package.json b/node_modules/arg/package.json new file mode 100644 index 0000000..47368d7 --- /dev/null +++ b/node_modules/arg/package.json @@ -0,0 +1,28 @@ +{ + "name": "arg", + "version": "5.0.2", + "description": "Unopinionated, no-frills CLI argument parser", + "main": "index.js", + "types": "index.d.ts", + "repository": "vercel/arg", + "author": "Josh Junon ", + "license": "MIT", + "files": [ + "index.js", + "index.d.ts" + ], + "scripts": { + "test": "WARN_EXIT=1 jest --coverage -w 2" + }, + "devDependencies": { + "chai": "^4.1.1", + "jest": "^27.0.6", + "prettier": "^2.3.2" + }, + "prettier": { + "arrowParens": "always", + "singleQuote": true, + "tabWidth": 2, + "trailingComma": "none" + } +} diff --git a/node_modules/balanced-match/.github/FUNDING.yml b/node_modules/balanced-match/.github/FUNDING.yml new file mode 100644 index 0000000..cea8b16 --- /dev/null +++ b/node_modules/balanced-match/.github/FUNDING.yml @@ -0,0 +1,2 @@ +tidelift: "npm/balanced-match" +patreon: juliangruber diff --git a/node_modules/balanced-match/LICENSE.md b/node_modules/balanced-match/LICENSE.md new file mode 100644 index 0000000..2cdc8e4 --- /dev/null +++ b/node_modules/balanced-match/LICENSE.md @@ -0,0 +1,21 @@ +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/balanced-match/README.md b/node_modules/balanced-match/README.md new file mode 100644 index 0000000..d2a48b6 --- /dev/null +++ b/node_modules/balanced-match/README.md @@ -0,0 +1,97 @@ +# balanced-match + +Match balanced string pairs, like `{` and `}` or `` and ``. Supports regular expressions as well! + +[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) + +[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) + +## Example + +Get the first matching pair of braces: + +```js +var balanced = require('balanced-match'); + +console.log(balanced('{', '}', 'pre{in{nested}}post')); +console.log(balanced('{', '}', 'pre{first}between{second}post')); +console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); +``` + +The matches are: + +```bash +$ node example.js +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } +{ start: 3, + end: 9, + pre: 'pre', + body: 'first', + post: 'between{second}post' } +{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } +``` + +## API + +### var m = balanced(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +object with those keys: + +* **start** the index of the first match of `a` +* **end** the index of the matching `b` +* **pre** the preamble, `a` and `b` not included +* **body** the match, `a` and `b` not included +* **post** the postscript, `a` and `b` not included + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. + +### var r = balanced.range(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +array with indexes: `[ , ]`. + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install balanced-match +``` + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/balanced-match/index.js b/node_modules/balanced-match/index.js new file mode 100644 index 0000000..c67a646 --- /dev/null +++ b/node_modules/balanced-match/index.js @@ -0,0 +1,62 @@ +'use strict'; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} diff --git a/node_modules/balanced-match/package.json b/node_modules/balanced-match/package.json new file mode 100644 index 0000000..ce6073e --- /dev/null +++ b/node_modules/balanced-match/package.json @@ -0,0 +1,48 @@ +{ + "name": "balanced-match", + "description": "Match balanced character pairs, like \"{\" and \"}\"", + "version": "1.0.2", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/balanced-match.git" + }, + "homepage": "https://github.com/juliangruber/balanced-match", + "main": "index.js", + "scripts": { + "test": "tape test/test.js", + "bench": "matcha test/bench.js" + }, + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "keywords": [ + "match", + "regexp", + "test", + "balanced", + "parse" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/node_modules/binary-extensions/binary-extensions.json b/node_modules/binary-extensions/binary-extensions.json new file mode 100644 index 0000000..ac08048 --- /dev/null +++ b/node_modules/binary-extensions/binary-extensions.json @@ -0,0 +1,263 @@ +[ + "3dm", + "3ds", + "3g2", + "3gp", + "7z", + "a", + "aac", + "adp", + "afdesign", + "afphoto", + "afpub", + "ai", + "aif", + "aiff", + "alz", + "ape", + "apk", + "appimage", + "ar", + "arj", + "asf", + "au", + "avi", + "bak", + "baml", + "bh", + "bin", + "bk", + "bmp", + "btif", + "bz2", + "bzip2", + "cab", + "caf", + "cgm", + "class", + "cmx", + "cpio", + "cr2", + "cur", + "dat", + "dcm", + "deb", + "dex", + "djvu", + "dll", + "dmg", + "dng", + "doc", + "docm", + "docx", + "dot", + "dotm", + "dra", + "DS_Store", + "dsk", + "dts", + "dtshd", + "dvb", + "dwg", + "dxf", + "ecelp4800", + "ecelp7470", + "ecelp9600", + "egg", + "eol", + "eot", + "epub", + "exe", + "f4v", + "fbs", + "fh", + "fla", + "flac", + "flatpak", + "fli", + "flv", + "fpx", + "fst", + "fvt", + "g3", + "gh", + "gif", + "graffle", + "gz", + "gzip", + "h261", + "h263", + "h264", + "icns", + "ico", + "ief", + "img", + "ipa", + "iso", + "jar", + "jpeg", + "jpg", + "jpgv", + "jpm", + "jxr", + "key", + "ktx", + "lha", + "lib", + "lvp", + "lz", + "lzh", + "lzma", + "lzo", + "m3u", + "m4a", + "m4v", + "mar", + "mdi", + "mht", + "mid", + "midi", + "mj2", + "mka", + "mkv", + "mmr", + "mng", + "mobi", + "mov", + "movie", + "mp3", + "mp4", + "mp4a", + "mpeg", + "mpg", + "mpga", + "mxu", + "nef", + "npx", + "numbers", + "nupkg", + "o", + "odp", + "ods", + "odt", + "oga", + "ogg", + "ogv", + "otf", + "ott", + "pages", + "pbm", + "pcx", + "pdb", + "pdf", + "pea", + "pgm", + "pic", + "png", + "pnm", + "pot", + "potm", + "potx", + "ppa", + "ppam", + "ppm", + "pps", + "ppsm", + "ppsx", + "ppt", + "pptm", + "pptx", + "psd", + "pya", + "pyc", + "pyo", + "pyv", + "qt", + "rar", + "ras", + "raw", + "resources", + "rgb", + "rip", + "rlc", + "rmf", + "rmvb", + "rpm", + "rtf", + "rz", + "s3m", + "s7z", + "scpt", + "sgi", + "shar", + "snap", + "sil", + "sketch", + "slk", + "smv", + "snk", + "so", + "stl", + "suo", + "sub", + "swf", + "tar", + "tbz", + "tbz2", + "tga", + "tgz", + "thmx", + "tif", + "tiff", + "tlz", + "ttc", + "ttf", + "txz", + "udf", + "uvh", + "uvi", + "uvm", + "uvp", + "uvs", + "uvu", + "viv", + "vob", + "war", + "wav", + "wax", + "wbmp", + "wdp", + "weba", + "webm", + "webp", + "whl", + "wim", + "wm", + "wma", + "wmv", + "wmx", + "woff", + "woff2", + "wrm", + "wvx", + "xbm", + "xif", + "xla", + "xlam", + "xls", + "xlsb", + "xlsm", + "xlsx", + "xlt", + "xltm", + "xltx", + "xm", + "xmind", + "xpi", + "xpm", + "xwd", + "xz", + "z", + "zip", + "zipx" +] diff --git a/node_modules/binary-extensions/binary-extensions.json.d.ts b/node_modules/binary-extensions/binary-extensions.json.d.ts new file mode 100644 index 0000000..94a248c --- /dev/null +++ b/node_modules/binary-extensions/binary-extensions.json.d.ts @@ -0,0 +1,3 @@ +declare const binaryExtensionsJson: readonly string[]; + +export = binaryExtensionsJson; diff --git a/node_modules/binary-extensions/index.d.ts b/node_modules/binary-extensions/index.d.ts new file mode 100644 index 0000000..f469ac5 --- /dev/null +++ b/node_modules/binary-extensions/index.d.ts @@ -0,0 +1,14 @@ +/** +List of binary file extensions. + +@example +``` +import binaryExtensions = require('binary-extensions'); + +console.log(binaryExtensions); +//=> ['3ds', '3g2', …] +``` +*/ +declare const binaryExtensions: readonly string[]; + +export = binaryExtensions; diff --git a/node_modules/binary-extensions/index.js b/node_modules/binary-extensions/index.js new file mode 100644 index 0000000..d46e468 --- /dev/null +++ b/node_modules/binary-extensions/index.js @@ -0,0 +1 @@ +module.exports = require('./binary-extensions.json'); diff --git a/node_modules/binary-extensions/license b/node_modules/binary-extensions/license new file mode 100644 index 0000000..5493a1a --- /dev/null +++ b/node_modules/binary-extensions/license @@ -0,0 +1,10 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) +Copyright (c) Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/binary-extensions/package.json b/node_modules/binary-extensions/package.json new file mode 100644 index 0000000..4710c33 --- /dev/null +++ b/node_modules/binary-extensions/package.json @@ -0,0 +1,40 @@ +{ + "name": "binary-extensions", + "version": "2.3.0", + "description": "List of binary file extensions", + "license": "MIT", + "repository": "sindresorhus/binary-extensions", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "sideEffects": false, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts", + "binary-extensions.json", + "binary-extensions.json.d.ts" + ], + "keywords": [ + "binary", + "extensions", + "extension", + "file", + "json", + "list", + "array" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/binary-extensions/readme.md b/node_modules/binary-extensions/readme.md new file mode 100644 index 0000000..88519b3 --- /dev/null +++ b/node_modules/binary-extensions/readme.md @@ -0,0 +1,25 @@ +# binary-extensions + +> List of binary file extensions + +The list is just a [JSON file](binary-extensions.json) and can be used anywhere. + +## Install + +```sh +npm install binary-extensions +``` + +## Usage + +```js +const binaryExtensions = require('binary-extensions'); + +console.log(binaryExtensions); +//=> ['3ds', '3g2', …] +``` + +## Related + +- [is-binary-path](https://github.com/sindresorhus/is-binary-path) - Check if a filepath is a binary file +- [text-extensions](https://github.com/sindresorhus/text-extensions) - List of text file extensions diff --git a/node_modules/brace-expansion/.github/FUNDING.yml b/node_modules/brace-expansion/.github/FUNDING.yml new file mode 100644 index 0000000..79d1eaf --- /dev/null +++ b/node_modules/brace-expansion/.github/FUNDING.yml @@ -0,0 +1,2 @@ +tidelift: "npm/brace-expansion" +patreon: juliangruber diff --git a/node_modules/brace-expansion/LICENSE b/node_modules/brace-expansion/LICENSE new file mode 100644 index 0000000..de32266 --- /dev/null +++ b/node_modules/brace-expansion/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Julian Gruber + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/brace-expansion/README.md b/node_modules/brace-expansion/README.md new file mode 100644 index 0000000..e55c583 --- /dev/null +++ b/node_modules/brace-expansion/README.md @@ -0,0 +1,135 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/brace-expansion/index.js b/node_modules/brace-expansion/index.js new file mode 100644 index 0000000..a27f81c --- /dev/null +++ b/node_modules/brace-expansion/index.js @@ -0,0 +1,203 @@ +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m) return [str]; + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + if (/\$$/.test(m.pre)) { + for (var k = 0; k < post.length; k++) { + var expansion = pre+ '{' + m.body + '}' + post[k]; + expansions.push(expansion); + } + } else { + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,(?!,).*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = []; + + for (var j = 0; j < n.length; j++) { + N.push.apply(N, expand(n[j], false)); + } + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + } + + return expansions; +} + diff --git a/node_modules/brace-expansion/package.json b/node_modules/brace-expansion/package.json new file mode 100644 index 0000000..c7eee34 --- /dev/null +++ b/node_modules/brace-expansion/package.json @@ -0,0 +1,49 @@ +{ + "name": "brace-expansion", + "description": "Brace expansion as known from sh/bash", + "version": "2.0.2", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "main": "index.js", + "scripts": { + "test": "tape test/*.js", + "gentest": "bash test/generate.sh", + "bench": "matcha test/perf/bench.js" + }, + "dependencies": { + "balanced-match": "^1.0.0" + }, + "devDependencies": { + "@c4312/matcha": "^1.3.1", + "tape": "^4.6.0" + }, + "keywords": [], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "publishConfig": { + "tag": "2.x" + } +} diff --git a/node_modules/braces/LICENSE b/node_modules/braces/LICENSE new file mode 100644 index 0000000..9af4a67 --- /dev/null +++ b/node_modules/braces/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/braces/README.md b/node_modules/braces/README.md new file mode 100644 index 0000000..f59dd60 --- /dev/null +++ b/node_modules/braces/README.md @@ -0,0 +1,586 @@ +# braces [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/braces.svg?style=flat)](https://www.npmjs.com/package/braces) [![NPM monthly downloads](https://img.shields.io/npm/dm/braces.svg?style=flat)](https://npmjs.org/package/braces) [![NPM total downloads](https://img.shields.io/npm/dt/braces.svg?style=flat)](https://npmjs.org/package/braces) [![Linux Build Status](https://img.shields.io/travis/micromatch/braces.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/braces) + +> Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save braces +``` + +## v3.0.0 Released!! + +See the [changelog](CHANGELOG.md) for details. + +## Why use braces? + +Brace patterns make globs more powerful by adding the ability to match specific ranges and sequences of characters. + +- **Accurate** - complete support for the [Bash 4.3 Brace Expansion](www.gnu.org/software/bash/) specification (passes all of the Bash braces tests) +- **[fast and performant](#benchmarks)** - Starts fast, runs fast and [scales well](#performance) as patterns increase in complexity. +- **Organized code base** - The parser and compiler are easy to maintain and update when edge cases crop up. +- **Well-tested** - Thousands of test assertions, and passes all of the Bash, minimatch, and [brace-expansion](https://github.com/juliangruber/brace-expansion) unit tests (as of the date this was written). +- **Safer** - You shouldn't have to worry about users defining aggressive or malicious brace patterns that can break your application. Braces takes measures to prevent malicious regex that can be used for DDoS attacks (see [catastrophic backtracking](https://www.regular-expressions.info/catastrophic.html)). +- [Supports lists](#lists) - (aka "sets") `a/{b,c}/d` => `['a/b/d', 'a/c/d']` +- [Supports sequences](#sequences) - (aka "ranges") `{01..03}` => `['01', '02', '03']` +- [Supports steps](#steps) - (aka "increments") `{2..10..2}` => `['2', '4', '6', '8', '10']` +- [Supports escaping](#escaping) - To prevent evaluation of special characters. + +## Usage + +The main export is a function that takes one or more brace `patterns` and `options`. + +```js +const braces = require('braces'); +// braces(patterns[, options]); + +console.log(braces(['{01..05}', '{a..e}'])); +//=> ['(0[1-5])', '([a-e])'] + +console.log(braces(['{01..05}', '{a..e}'], { expand: true })); +//=> ['01', '02', '03', '04', '05', 'a', 'b', 'c', 'd', 'e'] +``` + +### Brace Expansion vs. Compilation + +By default, brace patterns are compiled into strings that are optimized for creating regular expressions and matching. + +**Compiled** + +```js +console.log(braces('a/{x,y,z}/b')); +//=> ['a/(x|y|z)/b'] +console.log(braces(['a/{01..20}/b', 'a/{1..5}/b'])); +//=> [ 'a/(0[1-9]|1[0-9]|20)/b', 'a/([1-5])/b' ] +``` + +**Expanded** + +Enable brace expansion by setting the `expand` option to true, or by using [braces.expand()](#expand) (returns an array similar to what you'd expect from Bash, or `echo {1..5}`, or [minimatch](https://github.com/isaacs/minimatch)): + +```js +console.log(braces('a/{x,y,z}/b', { expand: true })); +//=> ['a/x/b', 'a/y/b', 'a/z/b'] + +console.log(braces.expand('{01..10}')); +//=> ['01','02','03','04','05','06','07','08','09','10'] +``` + +### Lists + +Expand lists (like Bash "sets"): + +```js +console.log(braces('a/{foo,bar,baz}/*.js')); +//=> ['a/(foo|bar|baz)/*.js'] + +console.log(braces.expand('a/{foo,bar,baz}/*.js')); +//=> ['a/foo/*.js', 'a/bar/*.js', 'a/baz/*.js'] +``` + +### Sequences + +Expand ranges of characters (like Bash "sequences"): + +```js +console.log(braces.expand('{1..3}')); // ['1', '2', '3'] +console.log(braces.expand('a/{1..3}/b')); // ['a/1/b', 'a/2/b', 'a/3/b'] +console.log(braces('{a..c}', { expand: true })); // ['a', 'b', 'c'] +console.log(braces('foo/{a..c}', { expand: true })); // ['foo/a', 'foo/b', 'foo/c'] + +// supports zero-padded ranges +console.log(braces('a/{01..03}/b')); //=> ['a/(0[1-3])/b'] +console.log(braces('a/{001..300}/b')); //=> ['a/(0{2}[1-9]|0[1-9][0-9]|[12][0-9]{2}|300)/b'] +``` + +See [fill-range](https://github.com/jonschlinkert/fill-range) for all available range-expansion options. + +### Steppped ranges + +Steps, or increments, may be used with ranges: + +```js +console.log(braces.expand('{2..10..2}')); +//=> ['2', '4', '6', '8', '10'] + +console.log(braces('{2..10..2}')); +//=> ['(2|4|6|8|10)'] +``` + +When the [.optimize](#optimize) method is used, or [options.optimize](#optionsoptimize) is set to true, sequences are passed to [to-regex-range](https://github.com/jonschlinkert/to-regex-range) for expansion. + +### Nesting + +Brace patterns may be nested. The results of each expanded string are not sorted, and left to right order is preserved. + +**"Expanded" braces** + +```js +console.log(braces.expand('a{b,c,/{x,y}}/e')); +//=> ['ab/e', 'ac/e', 'a/x/e', 'a/y/e'] + +console.log(braces.expand('a/{x,{1..5},y}/c')); +//=> ['a/x/c', 'a/1/c', 'a/2/c', 'a/3/c', 'a/4/c', 'a/5/c', 'a/y/c'] +``` + +**"Optimized" braces** + +```js +console.log(braces('a{b,c,/{x,y}}/e')); +//=> ['a(b|c|/(x|y))/e'] + +console.log(braces('a/{x,{1..5},y}/c')); +//=> ['a/(x|([1-5])|y)/c'] +``` + +### Escaping + +**Escaping braces** + +A brace pattern will not be expanded or evaluted if _either the opening or closing brace is escaped_: + +```js +console.log(braces.expand('a\\{d,c,b}e')); +//=> ['a{d,c,b}e'] + +console.log(braces.expand('a{d,c,b\\}e')); +//=> ['a{d,c,b}e'] +``` + +**Escaping commas** + +Commas inside braces may also be escaped: + +```js +console.log(braces.expand('a{b\\,c}d')); +//=> ['a{b,c}d'] + +console.log(braces.expand('a{d\\,c,b}e')); +//=> ['ad,ce', 'abe'] +``` + +**Single items** + +Following bash conventions, a brace pattern is also not expanded when it contains a single character: + +```js +console.log(braces.expand('a{b}c')); +//=> ['a{b}c'] +``` + +## Options + +### options.maxLength + +**Type**: `Number` + +**Default**: `10,000` + +**Description**: Limit the length of the input string. Useful when the input string is generated or your application allows users to pass a string, et cetera. + +```js +console.log(braces('a/{b,c}/d', { maxLength: 3 })); //=> throws an error +``` + +### options.expand + +**Type**: `Boolean` + +**Default**: `undefined` + +**Description**: Generate an "expanded" brace pattern (alternatively you can use the `braces.expand()` method, which does the same thing). + +```js +console.log(braces('a/{b,c}/d', { expand: true })); +//=> [ 'a/b/d', 'a/c/d' ] +``` + +### options.nodupes + +**Type**: `Boolean` + +**Default**: `undefined` + +**Description**: Remove duplicates from the returned array. + +### options.rangeLimit + +**Type**: `Number` + +**Default**: `1000` + +**Description**: To prevent malicious patterns from being passed by users, an error is thrown when `braces.expand()` is used or `options.expand` is true and the generated range will exceed the `rangeLimit`. + +You can customize `options.rangeLimit` or set it to `Inifinity` to disable this altogether. + +**Examples** + +```js +// pattern exceeds the "rangeLimit", so it's optimized automatically +console.log(braces.expand('{1..1000}')); +//=> ['([1-9]|[1-9][0-9]{1,2}|1000)'] + +// pattern does not exceed "rangeLimit", so it's NOT optimized +console.log(braces.expand('{1..100}')); +//=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100'] +``` + +### options.transform + +**Type**: `Function` + +**Default**: `undefined` + +**Description**: Customize range expansion. + +**Example: Transforming non-numeric values** + +```js +const alpha = braces.expand('x/{a..e}/y', { + transform(value, index) { + // When non-numeric values are passed, "value" is a character code. + return 'foo/' + String.fromCharCode(value) + '-' + index; + }, +}); +console.log(alpha); +//=> [ 'x/foo/a-0/y', 'x/foo/b-1/y', 'x/foo/c-2/y', 'x/foo/d-3/y', 'x/foo/e-4/y' ] +``` + +**Example: Transforming numeric values** + +```js +const numeric = braces.expand('{1..5}', { + transform(value) { + // when numeric values are passed, "value" is a number + return 'foo/' + value * 2; + }, +}); +console.log(numeric); +//=> [ 'foo/2', 'foo/4', 'foo/6', 'foo/8', 'foo/10' ] +``` + +### options.quantifiers + +**Type**: `Boolean` + +**Default**: `undefined` + +**Description**: In regular expressions, quanitifiers can be used to specify how many times a token can be repeated. For example, `a{1,3}` will match the letter `a` one to three times. + +Unfortunately, regex quantifiers happen to share the same syntax as [Bash lists](#lists) + +The `quantifiers` option tells braces to detect when [regex quantifiers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#quantifiers) are defined in the given pattern, and not to try to expand them as lists. + +**Examples** + +```js +const braces = require('braces'); +console.log(braces('a/b{1,3}/{x,y,z}')); +//=> [ 'a/b(1|3)/(x|y|z)' ] +console.log(braces('a/b{1,3}/{x,y,z}', { quantifiers: true })); +//=> [ 'a/b{1,3}/(x|y|z)' ] +console.log(braces('a/b{1,3}/{x,y,z}', { quantifiers: true, expand: true })); +//=> [ 'a/b{1,3}/x', 'a/b{1,3}/y', 'a/b{1,3}/z' ] +``` + +### options.keepEscaping + +**Type**: `Boolean` + +**Default**: `undefined` + +**Description**: Do not strip backslashes that were used for escaping from the result. + +## What is "brace expansion"? + +Brace expansion is a type of parameter expansion that was made popular by unix shells for generating lists of strings, as well as regex-like matching when used alongside wildcards (globs). + +In addition to "expansion", braces are also used for matching. In other words: + +- [brace expansion](#brace-expansion) is for generating new lists +- [brace matching](#brace-matching) is for filtering existing lists + +
+More about brace expansion (click to expand) + +There are two main types of brace expansion: + +1. **lists**: which are defined using comma-separated values inside curly braces: `{a,b,c}` +2. **sequences**: which are defined using a starting value and an ending value, separated by two dots: `a{1..3}b`. Optionally, a third argument may be passed to define a "step" or increment to use: `a{1..100..10}b`. These are also sometimes referred to as "ranges". + +Here are some example brace patterns to illustrate how they work: + +**Sets** + +``` +{a,b,c} => a b c +{a,b,c}{1,2} => a1 a2 b1 b2 c1 c2 +``` + +**Sequences** + +``` +{1..9} => 1 2 3 4 5 6 7 8 9 +{4..-4} => 4 3 2 1 0 -1 -2 -3 -4 +{1..20..3} => 1 4 7 10 13 16 19 +{a..j} => a b c d e f g h i j +{j..a} => j i h g f e d c b a +{a..z..3} => a d g j m p s v y +``` + +**Combination** + +Sets and sequences can be mixed together or used along with any other strings. + +``` +{a,b,c}{1..3} => a1 a2 a3 b1 b2 b3 c1 c2 c3 +foo/{a,b,c}/bar => foo/a/bar foo/b/bar foo/c/bar +``` + +The fact that braces can be "expanded" from relatively simple patterns makes them ideal for quickly generating test fixtures, file paths, and similar use cases. + +## Brace matching + +In addition to _expansion_, brace patterns are also useful for performing regular-expression-like matching. + +For example, the pattern `foo/{1..3}/bar` would match any of following strings: + +``` +foo/1/bar +foo/2/bar +foo/3/bar +``` + +But not: + +``` +baz/1/qux +baz/2/qux +baz/3/qux +``` + +Braces can also be combined with [glob patterns](https://github.com/jonschlinkert/micromatch) to perform more advanced wildcard matching. For example, the pattern `*/{1..3}/*` would match any of following strings: + +``` +foo/1/bar +foo/2/bar +foo/3/bar +baz/1/qux +baz/2/qux +baz/3/qux +``` + +## Brace matching pitfalls + +Although brace patterns offer a user-friendly way of matching ranges or sets of strings, there are also some major disadvantages and potential risks you should be aware of. + +### tldr + +**"brace bombs"** + +- brace expansion can eat up a huge amount of processing resources +- as brace patterns increase _linearly in size_, the system resources required to expand the pattern increase exponentially +- users can accidentally (or intentially) exhaust your system's resources resulting in the equivalent of a DoS attack (bonus: no programming knowledge is required!) + +For a more detailed explanation with examples, see the [geometric complexity](#geometric-complexity) section. + +### The solution + +Jump to the [performance section](#performance) to see how Braces solves this problem in comparison to other libraries. + +### Geometric complexity + +At minimum, brace patterns with sets limited to two elements have quadradic or `O(n^2)` complexity. But the complexity of the algorithm increases exponentially as the number of sets, _and elements per set_, increases, which is `O(n^c)`. + +For example, the following sets demonstrate quadratic (`O(n^2)`) complexity: + +``` +{1,2}{3,4} => (2X2) => 13 14 23 24 +{1,2}{3,4}{5,6} => (2X2X2) => 135 136 145 146 235 236 245 246 +``` + +But add an element to a set, and we get a n-fold Cartesian product with `O(n^c)` complexity: + +``` +{1,2,3}{4,5,6}{7,8,9} => (3X3X3) => 147 148 149 157 158 159 167 168 169 247 248 + 249 257 258 259 267 268 269 347 348 349 357 + 358 359 367 368 369 +``` + +Now, imagine how this complexity grows given that each element is a n-tuple: + +``` +{1..100}{1..100} => (100X100) => 10,000 elements (38.4 kB) +{1..100}{1..100}{1..100} => (100X100X100) => 1,000,000 elements (5.76 MB) +``` + +Although these examples are clearly contrived, they demonstrate how brace patterns can quickly grow out of control. + +**More information** + +Interested in learning more about brace expansion? + +- [linuxjournal/bash-brace-expansion](http://www.linuxjournal.com/content/bash-brace-expansion) +- [rosettacode/Brace_expansion](https://rosettacode.org/wiki/Brace_expansion) +- [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) + +
+ +## Performance + +Braces is not only screaming fast, it's also more accurate the other brace expansion libraries. + +### Better algorithms + +Fortunately there is a solution to the ["brace bomb" problem](#brace-matching-pitfalls): _don't expand brace patterns into an array when they're used for matching_. + +Instead, convert the pattern into an optimized regular expression. This is easier said than done, and braces is the only library that does this currently. + +**The proof is in the numbers** + +Minimatch gets exponentially slower as patterns increase in complexity, braces does not. The following results were generated using `braces()` and `minimatch.braceExpand()`, respectively. + +| **Pattern** | **braces** | **[minimatch][]** | +| --------------------------- | ------------------- | ---------------------------- | +| `{1..9007199254740991}`[^1] | `298 B` (5ms 459μs) | N/A (freezes) | +| `{1..1000000000000000}` | `41 B` (1ms 15μs) | N/A (freezes) | +| `{1..100000000000000}` | `40 B` (890μs) | N/A (freezes) | +| `{1..10000000000000}` | `39 B` (2ms 49μs) | N/A (freezes) | +| `{1..1000000000000}` | `38 B` (608μs) | N/A (freezes) | +| `{1..100000000000}` | `37 B` (397μs) | N/A (freezes) | +| `{1..10000000000}` | `35 B` (983μs) | N/A (freezes) | +| `{1..1000000000}` | `34 B` (798μs) | N/A (freezes) | +| `{1..100000000}` | `33 B` (733μs) | N/A (freezes) | +| `{1..10000000}` | `32 B` (5ms 632μs) | `78.89 MB` (16s 388ms 569μs) | +| `{1..1000000}` | `31 B` (1ms 381μs) | `6.89 MB` (1s 496ms 887μs) | +| `{1..100000}` | `30 B` (950μs) | `588.89 kB` (146ms 921μs) | +| `{1..10000}` | `29 B` (1ms 114μs) | `48.89 kB` (14ms 187μs) | +| `{1..1000}` | `28 B` (760μs) | `3.89 kB` (1ms 453μs) | +| `{1..100}` | `22 B` (345μs) | `291 B` (196μs) | +| `{1..10}` | `10 B` (533μs) | `20 B` (37μs) | +| `{1..3}` | `7 B` (190μs) | `5 B` (27μs) | + +### Faster algorithms + +When you need expansion, braces is still much faster. + +_(the following results were generated using `braces.expand()` and `minimatch.braceExpand()`, respectively)_ + +| **Pattern** | **braces** | **[minimatch][]** | +| --------------- | --------------------------- | ---------------------------- | +| `{1..10000000}` | `78.89 MB` (2s 698ms 642μs) | `78.89 MB` (18s 601ms 974μs) | +| `{1..1000000}` | `6.89 MB` (458ms 576μs) | `6.89 MB` (1s 491ms 621μs) | +| `{1..100000}` | `588.89 kB` (20ms 728μs) | `588.89 kB` (156ms 919μs) | +| `{1..10000}` | `48.89 kB` (2ms 202μs) | `48.89 kB` (13ms 641μs) | +| `{1..1000}` | `3.89 kB` (1ms 796μs) | `3.89 kB` (1ms 958μs) | +| `{1..100}` | `291 B` (424μs) | `291 B` (211μs) | +| `{1..10}` | `20 B` (487μs) | `20 B` (72μs) | +| `{1..3}` | `5 B` (166μs) | `5 B` (27μs) | + +If you'd like to run these comparisons yourself, see [test/support/generate.js](test/support/generate.js). + +## Benchmarks + +### Running benchmarks + +Install dev dependencies: + +```bash +npm i -d && npm benchmark +``` + +### Latest results + +Braces is more accurate, without sacrificing performance. + +```bash +● expand - range (expanded) + braces x 53,167 ops/sec ±0.12% (102 runs sampled) + minimatch x 11,378 ops/sec ±0.10% (102 runs sampled) +● expand - range (optimized for regex) + braces x 373,442 ops/sec ±0.04% (100 runs sampled) + minimatch x 3,262 ops/sec ±0.18% (100 runs sampled) +● expand - nested ranges (expanded) + braces x 33,921 ops/sec ±0.09% (99 runs sampled) + minimatch x 10,855 ops/sec ±0.28% (100 runs sampled) +● expand - nested ranges (optimized for regex) + braces x 287,479 ops/sec ±0.52% (98 runs sampled) + minimatch x 3,219 ops/sec ±0.28% (101 runs sampled) +● expand - set (expanded) + braces x 238,243 ops/sec ±0.19% (97 runs sampled) + minimatch x 538,268 ops/sec ±0.31% (96 runs sampled) +● expand - set (optimized for regex) + braces x 321,844 ops/sec ±0.10% (97 runs sampled) + minimatch x 140,600 ops/sec ±0.15% (100 runs sampled) +● expand - nested sets (expanded) + braces x 165,371 ops/sec ±0.42% (96 runs sampled) + minimatch x 337,720 ops/sec ±0.28% (100 runs sampled) +● expand - nested sets (optimized for regex) + braces x 242,948 ops/sec ±0.12% (99 runs sampled) + minimatch x 87,403 ops/sec ±0.79% (96 runs sampled) +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Contributors + +| **Commits** | **Contributor** | +| ----------- | ------------------------------------------------------------- | +| 197 | [jonschlinkert](https://github.com/jonschlinkert) | +| 4 | [doowb](https://github.com/doowb) | +| 1 | [es128](https://github.com/es128) | +| 1 | [eush77](https://github.com/eush77) | +| 1 | [hemanth](https://github.com/hemanth) | +| 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | + +### Author + +**Jon Schlinkert** + +- [GitHub Profile](https://github.com/jonschlinkert) +- [Twitter Profile](https://twitter.com/jonschlinkert) +- [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +--- + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._ diff --git a/node_modules/braces/index.js b/node_modules/braces/index.js new file mode 100644 index 0000000..d222c13 --- /dev/null +++ b/node_modules/braces/index.js @@ -0,0 +1,170 @@ +'use strict'; + +const stringify = require('./lib/stringify'); +const compile = require('./lib/compile'); +const expand = require('./lib/expand'); +const parse = require('./lib/parse'); + +/** + * Expand the given pattern or create a regex-compatible string. + * + * ```js + * const braces = require('braces'); + * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] + * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + +const braces = (input, options = {}) => { + let output = []; + + if (Array.isArray(input)) { + for (const pattern of input) { + const result = braces.create(pattern, options); + if (Array.isArray(result)) { + output.push(...result); + } else { + output.push(result); + } + } + } else { + output = [].concat(braces.create(input, options)); + } + + if (options && options.expand === true && options.nodupes === true) { + output = [...new Set(output)]; + } + return output; +}; + +/** + * Parse the given `str` with the given `options`. + * + * ```js + * // braces.parse(pattern, [, options]); + * const ast = braces.parse('a/{b,c}/d'); + * console.log(ast); + * ``` + * @param {String} pattern Brace pattern to parse + * @param {Object} options + * @return {Object} Returns an AST + * @api public + */ + +braces.parse = (input, options = {}) => parse(input, options); + +/** + * Creates a braces string from an AST, or an AST node. + * + * ```js + * const braces = require('braces'); + * let ast = braces.parse('foo/{a,b}/bar'); + * console.log(stringify(ast.nodes[2])); //=> '{a,b}' + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.stringify = (input, options = {}) => { + if (typeof input === 'string') { + return stringify(braces.parse(input, options), options); + } + return stringify(input, options); +}; + +/** + * Compiles a brace pattern into a regex-compatible, optimized string. + * This method is called by the main [braces](#braces) function by default. + * + * ```js + * const braces = require('braces'); + * console.log(braces.compile('a/{b,c}/d')); + * //=> ['a/(b|c)/d'] + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.compile = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + return compile(input, options); +}; + +/** + * Expands a brace pattern into an array. This method is called by the + * main [braces](#braces) function when `options.expand` is true. Before + * using this method it's recommended that you read the [performance notes](#performance)) + * and advantages of using [.compile](#compile) instead. + * + * ```js + * const braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/b/d', 'a/c/d']; + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.expand = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + + let result = expand(input, options); + + // filter out empty strings if specified + if (options.noempty === true) { + result = result.filter(Boolean); + } + + // filter out duplicates if specified + if (options.nodupes === true) { + result = [...new Set(result)]; + } + + return result; +}; + +/** + * Processes a brace pattern and returns either an expanded array + * (if `options.expand` is true), a highly optimized regex-compatible string. + * This method is called by the main [braces](#braces) function. + * + * ```js + * const braces = require('braces'); + * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) + * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.create = (input, options = {}) => { + if (input === '' || input.length < 3) { + return [input]; + } + + return options.expand !== true + ? braces.compile(input, options) + : braces.expand(input, options); +}; + +/** + * Expose "braces" + */ + +module.exports = braces; diff --git a/node_modules/braces/lib/compile.js b/node_modules/braces/lib/compile.js new file mode 100644 index 0000000..dce69be --- /dev/null +++ b/node_modules/braces/lib/compile.js @@ -0,0 +1,60 @@ +'use strict'; + +const fill = require('fill-range'); +const utils = require('./utils'); + +const compile = (ast, options = {}) => { + const walk = (node, parent = {}) => { + const invalidBlock = utils.isInvalidBrace(parent); + const invalidNode = node.invalid === true && options.escapeInvalid === true; + const invalid = invalidBlock === true || invalidNode === true; + const prefix = options.escapeInvalid === true ? '\\' : ''; + let output = ''; + + if (node.isOpen === true) { + return prefix + node.value; + } + + if (node.isClose === true) { + console.log('node.isClose', prefix, node.value); + return prefix + node.value; + } + + if (node.type === 'open') { + return invalid ? prefix + node.value : '('; + } + + if (node.type === 'close') { + return invalid ? prefix + node.value : ')'; + } + + if (node.type === 'comma') { + return node.prev.type === 'comma' ? '' : invalid ? node.value : '|'; + } + + if (node.value) { + return node.value; + } + + if (node.nodes && node.ranges > 0) { + const args = utils.reduce(node.nodes); + const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true }); + + if (range.length !== 0) { + return args.length > 1 && range.length > 1 ? `(${range})` : range; + } + } + + if (node.nodes) { + for (const child of node.nodes) { + output += walk(child, node); + } + } + + return output; + }; + + return walk(ast); +}; + +module.exports = compile; diff --git a/node_modules/braces/lib/constants.js b/node_modules/braces/lib/constants.js new file mode 100644 index 0000000..2bb3b88 --- /dev/null +++ b/node_modules/braces/lib/constants.js @@ -0,0 +1,57 @@ +'use strict'; + +module.exports = { + MAX_LENGTH: 10000, + + // Digits + CHAR_0: '0', /* 0 */ + CHAR_9: '9', /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 'A', /* A */ + CHAR_LOWERCASE_A: 'a', /* a */ + CHAR_UPPERCASE_Z: 'Z', /* Z */ + CHAR_LOWERCASE_Z: 'z', /* z */ + + CHAR_LEFT_PARENTHESES: '(', /* ( */ + CHAR_RIGHT_PARENTHESES: ')', /* ) */ + + CHAR_ASTERISK: '*', /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: '&', /* & */ + CHAR_AT: '@', /* @ */ + CHAR_BACKSLASH: '\\', /* \ */ + CHAR_BACKTICK: '`', /* ` */ + CHAR_CARRIAGE_RETURN: '\r', /* \r */ + CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ + CHAR_COLON: ':', /* : */ + CHAR_COMMA: ',', /* , */ + CHAR_DOLLAR: '$', /* . */ + CHAR_DOT: '.', /* . */ + CHAR_DOUBLE_QUOTE: '"', /* " */ + CHAR_EQUAL: '=', /* = */ + CHAR_EXCLAMATION_MARK: '!', /* ! */ + CHAR_FORM_FEED: '\f', /* \f */ + CHAR_FORWARD_SLASH: '/', /* / */ + CHAR_HASH: '#', /* # */ + CHAR_HYPHEN_MINUS: '-', /* - */ + CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ + CHAR_LEFT_CURLY_BRACE: '{', /* { */ + CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ + CHAR_LINE_FEED: '\n', /* \n */ + CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ + CHAR_PERCENT: '%', /* % */ + CHAR_PLUS: '+', /* + */ + CHAR_QUESTION_MARK: '?', /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ + CHAR_RIGHT_CURLY_BRACE: '}', /* } */ + CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ + CHAR_SEMICOLON: ';', /* ; */ + CHAR_SINGLE_QUOTE: '\'', /* ' */ + CHAR_SPACE: ' ', /* */ + CHAR_TAB: '\t', /* \t */ + CHAR_UNDERSCORE: '_', /* _ */ + CHAR_VERTICAL_LINE: '|', /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ +}; diff --git a/node_modules/braces/lib/expand.js b/node_modules/braces/lib/expand.js new file mode 100644 index 0000000..35b2c41 --- /dev/null +++ b/node_modules/braces/lib/expand.js @@ -0,0 +1,113 @@ +'use strict'; + +const fill = require('fill-range'); +const stringify = require('./stringify'); +const utils = require('./utils'); + +const append = (queue = '', stash = '', enclose = false) => { + const result = []; + + queue = [].concat(queue); + stash = [].concat(stash); + + if (!stash.length) return queue; + if (!queue.length) { + return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash; + } + + for (const item of queue) { + if (Array.isArray(item)) { + for (const value of item) { + result.push(append(value, stash, enclose)); + } + } else { + for (let ele of stash) { + if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); + } + } + } + return utils.flatten(result); +}; + +const expand = (ast, options = {}) => { + const rangeLimit = options.rangeLimit === undefined ? 1000 : options.rangeLimit; + + const walk = (node, parent = {}) => { + node.queue = []; + + let p = parent; + let q = parent.queue; + + while (p.type !== 'brace' && p.type !== 'root' && p.parent) { + p = p.parent; + q = p.queue; + } + + if (node.invalid || node.dollar) { + q.push(append(q.pop(), stringify(node, options))); + return; + } + + if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { + q.push(append(q.pop(), ['{}'])); + return; + } + + if (node.nodes && node.ranges > 0) { + const args = utils.reduce(node.nodes); + + if (utils.exceedsLimit(...args, options.step, rangeLimit)) { + throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); + } + + let range = fill(...args, options); + if (range.length === 0) { + range = stringify(node, options); + } + + q.push(append(q.pop(), range)); + node.nodes = []; + return; + } + + const enclose = utils.encloseBrace(node); + let queue = node.queue; + let block = node; + + while (block.type !== 'brace' && block.type !== 'root' && block.parent) { + block = block.parent; + queue = block.queue; + } + + for (let i = 0; i < node.nodes.length; i++) { + const child = node.nodes[i]; + + if (child.type === 'comma' && node.type === 'brace') { + if (i === 1) queue.push(''); + queue.push(''); + continue; + } + + if (child.type === 'close') { + q.push(append(q.pop(), queue, enclose)); + continue; + } + + if (child.value && child.type !== 'open') { + queue.push(append(queue.pop(), child.value)); + continue; + } + + if (child.nodes) { + walk(child, node); + } + } + + return queue; + }; + + return utils.flatten(walk(ast)); +}; + +module.exports = expand; diff --git a/node_modules/braces/lib/parse.js b/node_modules/braces/lib/parse.js new file mode 100644 index 0000000..3a6988e --- /dev/null +++ b/node_modules/braces/lib/parse.js @@ -0,0 +1,331 @@ +'use strict'; + +const stringify = require('./stringify'); + +/** + * Constants + */ + +const { + MAX_LENGTH, + CHAR_BACKSLASH, /* \ */ + CHAR_BACKTICK, /* ` */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_RIGHT_SQUARE_BRACKET, /* ] */ + CHAR_DOUBLE_QUOTE, /* " */ + CHAR_SINGLE_QUOTE, /* ' */ + CHAR_NO_BREAK_SPACE, + CHAR_ZERO_WIDTH_NOBREAK_SPACE +} = require('./constants'); + +/** + * parse + */ + +const parse = (input, options = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + const opts = options || {}; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + if (input.length > max) { + throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + } + + const ast = { type: 'root', input, nodes: [] }; + const stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + const length = input.length; + let index = 0; + let depth = 0; + let value; + + /** + * Helpers + */ + + const advance = () => input[index++]; + const push = node => { + if (node.type === 'text' && prev.type === 'dot') { + prev.type = 'text'; + } + + if (prev && prev.type === 'text' && node.type === 'text') { + prev.value += node.value; + return; + } + + block.nodes.push(node); + node.parent = block; + node.prev = prev; + prev = node; + return node; + }; + + push({ type: 'bos' }); + + while (index < length) { + block = stack[stack.length - 1]; + value = advance(); + + /** + * Invalid chars + */ + + if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { + continue; + } + + /** + * Escaped chars + */ + + if (value === CHAR_BACKSLASH) { + push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); + continue; + } + + /** + * Right square bracket (literal): ']' + */ + + if (value === CHAR_RIGHT_SQUARE_BRACKET) { + push({ type: 'text', value: '\\' + value }); + continue; + } + + /** + * Left square bracket: '[' + */ + + if (value === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + + let next; + + while (index < length && (next = advance())) { + value += next; + + if (next === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + continue; + } + + if (next === CHAR_BACKSLASH) { + value += advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + brackets--; + + if (brackets === 0) { + break; + } + } + } + + push({ type: 'text', value }); + continue; + } + + /** + * Parentheses + */ + + if (value === CHAR_LEFT_PARENTHESES) { + block = push({ type: 'paren', nodes: [] }); + stack.push(block); + push({ type: 'text', value }); + continue; + } + + if (value === CHAR_RIGHT_PARENTHESES) { + if (block.type !== 'paren') { + push({ type: 'text', value }); + continue; + } + block = stack.pop(); + push({ type: 'text', value }); + block = stack[stack.length - 1]; + continue; + } + + /** + * Quotes: '|"|` + */ + + if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { + const open = value; + let next; + + if (options.keepQuotes !== true) { + value = ''; + } + + while (index < length && (next = advance())) { + if (next === CHAR_BACKSLASH) { + value += next + advance(); + continue; + } + + if (next === open) { + if (options.keepQuotes === true) value += next; + break; + } + + value += next; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Left curly brace: '{' + */ + + if (value === CHAR_LEFT_CURLY_BRACE) { + depth++; + + const dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + const brace = { + type: 'brace', + open: true, + close: false, + dollar, + depth, + commas: 0, + ranges: 0, + nodes: [] + }; + + block = push(brace); + stack.push(block); + push({ type: 'open', value }); + continue; + } + + /** + * Right curly brace: '}' + */ + + if (value === CHAR_RIGHT_CURLY_BRACE) { + if (block.type !== 'brace') { + push({ type: 'text', value }); + continue; + } + + const type = 'close'; + block = stack.pop(); + block.close = true; + + push({ type, value }); + depth--; + + block = stack[stack.length - 1]; + continue; + } + + /** + * Comma: ',' + */ + + if (value === CHAR_COMMA && depth > 0) { + if (block.ranges > 0) { + block.ranges = 0; + const open = block.nodes.shift(); + block.nodes = [open, { type: 'text', value: stringify(block) }]; + } + + push({ type: 'comma', value }); + block.commas++; + continue; + } + + /** + * Dot: '.' + */ + + if (value === CHAR_DOT && depth > 0 && block.commas === 0) { + const siblings = block.nodes; + + if (depth === 0 || siblings.length === 0) { + push({ type: 'text', value }); + continue; + } + + if (prev.type === 'dot') { + block.range = []; + prev.value += value; + prev.type = 'range'; + + if (block.nodes.length !== 3 && block.nodes.length !== 5) { + block.invalid = true; + block.ranges = 0; + prev.type = 'text'; + continue; + } + + block.ranges++; + block.args = []; + continue; + } + + if (prev.type === 'range') { + siblings.pop(); + + const before = siblings[siblings.length - 1]; + before.value += prev.value + value; + prev = before; + block.ranges--; + continue; + } + + push({ type: 'dot', value }); + continue; + } + + /** + * Text + */ + + push({ type: 'text', value }); + } + + // Mark imbalanced braces and brackets as invalid + do { + block = stack.pop(); + + if (block.type !== 'root') { + block.nodes.forEach(node => { + if (!node.nodes) { + if (node.type === 'open') node.isOpen = true; + if (node.type === 'close') node.isClose = true; + if (!node.nodes) node.type = 'text'; + node.invalid = true; + } + }); + + // get the location of the block on parent.nodes (block's siblings) + const parent = stack[stack.length - 1]; + const index = parent.nodes.indexOf(block); + // replace the (invalid) block with it's nodes + parent.nodes.splice(index, 1, ...block.nodes); + } + } while (stack.length > 0); + + push({ type: 'eos' }); + return ast; +}; + +module.exports = parse; diff --git a/node_modules/braces/lib/stringify.js b/node_modules/braces/lib/stringify.js new file mode 100644 index 0000000..8bcf872 --- /dev/null +++ b/node_modules/braces/lib/stringify.js @@ -0,0 +1,32 @@ +'use strict'; + +const utils = require('./utils'); + +module.exports = (ast, options = {}) => { + const stringify = (node, parent = {}) => { + const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); + const invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ''; + + if (node.value) { + if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) { + return '\\' + node.value; + } + return node.value; + } + + if (node.value) { + return node.value; + } + + if (node.nodes) { + for (const child of node.nodes) { + output += stringify(child); + } + } + return output; + }; + + return stringify(ast); +}; + diff --git a/node_modules/braces/lib/utils.js b/node_modules/braces/lib/utils.js new file mode 100644 index 0000000..d19311f --- /dev/null +++ b/node_modules/braces/lib/utils.js @@ -0,0 +1,122 @@ +'use strict'; + +exports.isInteger = num => { + if (typeof num === 'number') { + return Number.isInteger(num); + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isInteger(Number(num)); + } + return false; +}; + +/** + * Find a node of the given type + */ + +exports.find = (node, type) => node.nodes.find(node => node.type === type); + +/** + * Find a node of the given type + */ + +exports.exceedsLimit = (min, max, step = 1, limit) => { + if (limit === false) return false; + if (!exports.isInteger(min) || !exports.isInteger(max)) return false; + return ((Number(max) - Number(min)) / Number(step)) >= limit; +}; + +/** + * Escape the given node with '\\' before node.value + */ + +exports.escapeNode = (block, n = 0, type) => { + const node = block.nodes[n]; + if (!node) return; + + if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { + if (node.escaped !== true) { + node.value = '\\' + node.value; + node.escaped = true; + } + } +}; + +/** + * Returns true if the given brace node should be enclosed in literal braces + */ + +exports.encloseBrace = node => { + if (node.type !== 'brace') return false; + if ((node.commas >> 0 + node.ranges >> 0) === 0) { + node.invalid = true; + return true; + } + return false; +}; + +/** + * Returns true if a brace node is invalid. + */ + +exports.isInvalidBrace = block => { + if (block.type !== 'brace') return false; + if (block.invalid === true || block.dollar) return true; + if ((block.commas >> 0 + block.ranges >> 0) === 0) { + block.invalid = true; + return true; + } + if (block.open !== true || block.close !== true) { + block.invalid = true; + return true; + } + return false; +}; + +/** + * Returns true if a node is an open or close node + */ + +exports.isOpenOrClose = node => { + if (node.type === 'open' || node.type === 'close') { + return true; + } + return node.open === true || node.close === true; +}; + +/** + * Reduce an array of text nodes. + */ + +exports.reduce = nodes => nodes.reduce((acc, node) => { + if (node.type === 'text') acc.push(node.value); + if (node.type === 'range') node.type = 'text'; + return acc; +}, []); + +/** + * Flatten an array + */ + +exports.flatten = (...args) => { + const result = []; + + const flat = arr => { + for (let i = 0; i < arr.length; i++) { + const ele = arr[i]; + + if (Array.isArray(ele)) { + flat(ele); + continue; + } + + if (ele !== undefined) { + result.push(ele); + } + } + return result; + }; + + flat(args); + return result; +}; diff --git a/node_modules/braces/package.json b/node_modules/braces/package.json new file mode 100644 index 0000000..c3c056e --- /dev/null +++ b/node_modules/braces/package.json @@ -0,0 +1,77 @@ +{ + "name": "braces", + "description": "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.", + "version": "3.0.3", + "homepage": "https://github.com/micromatch/braces", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Brian Woodward (https://twitter.com/doowb)", + "Elan Shanker (https://github.com/es128)", + "Eugene Sharygin (https://github.com/eush77)", + "hemanth.hm (http://h3manth.com)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)" + ], + "repository": "micromatch/braces", + "bugs": { + "url": "https://github.com/micromatch/braces/issues" + }, + "license": "MIT", + "files": [ + "index.js", + "lib" + ], + "main": "index.js", + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "mocha", + "benchmark": "node benchmark" + }, + "dependencies": { + "fill-range": "^7.1.1" + }, + "devDependencies": { + "ansi-colors": "^3.2.4", + "bash-path": "^2.0.1", + "gulp-format-md": "^2.0.0", + "mocha": "^6.1.1" + }, + "keywords": [ + "alpha", + "alphabetical", + "bash", + "brace", + "braces", + "expand", + "expansion", + "filepath", + "fill", + "fs", + "glob", + "globbing", + "letter", + "match", + "matches", + "matching", + "number", + "numerical", + "path", + "range", + "ranges", + "sh" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "lint": { + "reflinks": true + }, + "plugins": [ + "gulp-format-md" + ] + } +} diff --git a/node_modules/camelcase-css/README.md b/node_modules/camelcase-css/README.md new file mode 100644 index 0000000..caaa817 --- /dev/null +++ b/node_modules/camelcase-css/README.md @@ -0,0 +1,27 @@ +# camelcase-css [![NPM Version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] + +> Convert a kebab-cased CSS property into a camelCased DOM property. + + +## Installation +[Node.js](http://nodejs.org/) `>= 6` is required. Type this at the command line: +```shell +npm install camelcase-css +``` + + +## Usage +```js +const camelCaseCSS = require('camelcase-css'); + +camelCaseCSS('-webkit-border-radius'); //-> WebkitBorderRadius +camelCaseCSS('-moz-border-radius'); //-> MozBorderRadius +camelCaseCSS('-ms-border-radius'); //-> msBorderRadius +camelCaseCSS('border-radius'); //-> borderRadius +``` + + +[npm-image]: https://img.shields.io/npm/v/camelcase-css.svg +[npm-url]: https://npmjs.org/package/camelcase-css +[travis-image]: https://img.shields.io/travis/stevenvachon/camelcase-css.svg +[travis-url]: https://travis-ci.org/stevenvachon/camelcase-css diff --git a/node_modules/camelcase-css/index-es5.js b/node_modules/camelcase-css/index-es5.js new file mode 100644 index 0000000..48ef078 --- /dev/null +++ b/node_modules/camelcase-css/index-es5.js @@ -0,0 +1,24 @@ +"use strict"; + +var pattern = /-(\w|$)/g; + +var callback = function callback(dashChar, char) { + return char.toUpperCase(); +}; + +var camelCaseCSS = function camelCaseCSS(property) { + property = property.toLowerCase(); + + // NOTE :: IE8's "styleFloat" is intentionally not supported + if (property === "float") { + return "cssFloat"; + } + // Microsoft vendor-prefixes are uniquely cased + else if (property.charCodeAt(0) === 45&& property.charCodeAt(1) === 109&& property.charCodeAt(2) === 115&& property.charCodeAt(3) === 45) { + return property.substr(1).replace(pattern, callback); + } else { + return property.replace(pattern, callback); + } +}; + +module.exports = camelCaseCSS; diff --git a/node_modules/camelcase-css/index.js b/node_modules/camelcase-css/index.js new file mode 100644 index 0000000..c9d1f1b --- /dev/null +++ b/node_modules/camelcase-css/index.js @@ -0,0 +1,30 @@ +"use strict"; +const pattern = /-(\w|$)/g; + +const callback = (dashChar, char) => char.toUpperCase(); + + + +const camelCaseCSS = property => +{ + property = property.toLowerCase(); + + // NOTE :: IE8's "styleFloat" is intentionally not supported + if (property === "float") + { + return "cssFloat"; + } + // Microsoft vendor-prefixes are uniquely cased + else if (property.startsWith("-ms-")) + { + return property.substr(1).replace(pattern, callback); + } + else + { + return property.replace(pattern, callback); + } +}; + + + +module.exports = camelCaseCSS; diff --git a/node_modules/camelcase-css/license b/node_modules/camelcase-css/license new file mode 100644 index 0000000..b760007 --- /dev/null +++ b/node_modules/camelcase-css/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Steven Vachon (svachon.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/camelcase-css/package.json b/node_modules/camelcase-css/package.json new file mode 100644 index 0000000..61dc51a --- /dev/null +++ b/node_modules/camelcase-css/package.json @@ -0,0 +1,34 @@ +{ + "name": "camelcase-css", + "description": "Convert a kebab-cased CSS property into a camelCased DOM property.", + "version": "2.0.1", + "license": "MIT", + "author": "Steven Vachon (https://www.svachon.com/)", + "repository": "stevenvachon/camelcase-css", + "browser": "index-es5.js", + "devDependencies": { + "babel-cli": "^6.26.0", + "babel-core": "^6.26.3", + "babel-plugin-optimize-starts-with": "^1.0.1", + "babel-preset-env": "^1.7.0", + "chai": "^4.1.2", + "mocha": "^5.2.0" + }, + "engines": { + "node": ">= 6" + }, + "scripts": { + "pretest": "babel index.js --out-file=index-es5.js --presets=env --plugins=optimize-starts-with", + "test": "mocha test.js --check-leaks --bail" + }, + "files": [ + "index.js", + "index-es5.js" + ], + "keywords": [ + "camelcase", + "case", + "css", + "dom" + ] +} diff --git a/node_modules/chokidar/LICENSE b/node_modules/chokidar/LICENSE new file mode 100644 index 0000000..fa9162b --- /dev/null +++ b/node_modules/chokidar/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/chokidar/README.md b/node_modules/chokidar/README.md new file mode 100644 index 0000000..8e25dec --- /dev/null +++ b/node_modules/chokidar/README.md @@ -0,0 +1,308 @@ +# Chokidar [![Weekly downloads](https://img.shields.io/npm/dw/chokidar.svg)](https://github.com/paulmillr/chokidar) [![Yearly downloads](https://img.shields.io/npm/dy/chokidar.svg)](https://github.com/paulmillr/chokidar) + +> Minimal and efficient cross-platform file watching library + +[![NPM](https://nodei.co/npm/chokidar.png)](https://www.npmjs.com/package/chokidar) + +## Why? + +Node.js `fs.watch`: + +* Doesn't report filenames on MacOS. +* Doesn't report events at all when using editors like Sublime on MacOS. +* Often reports events twice. +* Emits most changes as `rename`. +* Does not provide an easy way to recursively watch file trees. +* Does not support recursive watching on Linux. + +Node.js `fs.watchFile`: + +* Almost as bad at event handling. +* Also does not provide any recursive watching. +* Results in high CPU utilization. + +Chokidar resolves these problems. + +Initially made for **[Brunch](https://brunch.io/)** (an ultra-swift web app build tool), it is now used in +[Microsoft's Visual Studio Code](https://github.com/microsoft/vscode), +[gulp](https://github.com/gulpjs/gulp/), +[karma](https://karma-runner.github.io/), +[PM2](https://github.com/Unitech/PM2), +[browserify](http://browserify.org/), +[webpack](https://webpack.github.io/), +[BrowserSync](https://www.browsersync.io/), +and [many others](https://www.npmjs.com/browse/depended/chokidar). +It has proven itself in production environments. + +Version 3 is out! Check out our blog post about it: [Chokidar 3: How to save 32TB of traffic every week](https://paulmillr.com/posts/chokidar-3-save-32tb-of-traffic/) + +## How? + +Chokidar does still rely on the Node.js core `fs` module, but when using +`fs.watch` and `fs.watchFile` for watching, it normalizes the events it +receives, often checking for truth by getting file stats and/or dir contents. + +On MacOS, chokidar by default uses a native extension exposing the Darwin +`FSEvents` API. This provides very efficient recursive watching compared with +implementations like `kqueue` available on most \*nix platforms. Chokidar still +does have to do some work to normalize the events received that way as well. + +On most other platforms, the `fs.watch`-based implementation is the default, which +avoids polling and keeps CPU usage down. Be advised that chokidar will initiate +watchers recursively for everything within scope of the paths that have been +specified, so be judicious about not wasting system resources by watching much +more than needed. + +## Getting started + +Install with npm: + +```sh +npm install chokidar +``` + +Then `require` and use it in your code: + +```javascript +const chokidar = require('chokidar'); + +// One-liner for current directory +chokidar.watch('.').on('all', (event, path) => { + console.log(event, path); +}); +``` + +## API + +```javascript +// Example of a more typical implementation structure + +// Initialize watcher. +const watcher = chokidar.watch('file, dir, glob, or array', { + ignored: /(^|[\/\\])\../, // ignore dotfiles + persistent: true +}); + +// Something to use when events are received. +const log = console.log.bind(console); +// Add event listeners. +watcher + .on('add', path => log(`File ${path} has been added`)) + .on('change', path => log(`File ${path} has been changed`)) + .on('unlink', path => log(`File ${path} has been removed`)); + +// More possible events. +watcher + .on('addDir', path => log(`Directory ${path} has been added`)) + .on('unlinkDir', path => log(`Directory ${path} has been removed`)) + .on('error', error => log(`Watcher error: ${error}`)) + .on('ready', () => log('Initial scan complete. Ready for changes')) + .on('raw', (event, path, details) => { // internal + log('Raw event info:', event, path, details); + }); + +// 'add', 'addDir' and 'change' events also receive stat() results as second +// argument when available: https://nodejs.org/api/fs.html#fs_class_fs_stats +watcher.on('change', (path, stats) => { + if (stats) console.log(`File ${path} changed size to ${stats.size}`); +}); + +// Watch new files. +watcher.add('new-file'); +watcher.add(['new-file-2', 'new-file-3', '**/other-file*']); + +// Get list of actual paths being watched on the filesystem +var watchedPaths = watcher.getWatched(); + +// Un-watch some files. +await watcher.unwatch('new-file*'); + +// Stop watching. +// The method is async! +watcher.close().then(() => console.log('closed')); + +// Full list of options. See below for descriptions. +// Do not use this example! +chokidar.watch('file', { + persistent: true, + + ignored: '*.txt', + ignoreInitial: false, + followSymlinks: true, + cwd: '.', + disableGlobbing: false, + + usePolling: false, + interval: 100, + binaryInterval: 300, + alwaysStat: false, + depth: 99, + awaitWriteFinish: { + stabilityThreshold: 2000, + pollInterval: 100 + }, + + ignorePermissionErrors: false, + atomic: true // or a custom 'atomicity delay', in milliseconds (default 100) +}); + +``` + +`chokidar.watch(paths, [options])` + +* `paths` (string or array of strings). Paths to files, dirs to be watched +recursively, or glob patterns. + - Note: globs must not contain windows separators (`\`), + because that's how they work by the standard — + you'll need to replace them with forward slashes (`/`). + - Note 2: for additional glob documentation, check out low-level + library: [picomatch](https://github.com/micromatch/picomatch). +* `options` (object) Options object as defined below: + +#### Persistence + +* `persistent` (default: `true`). Indicates whether the process +should continue to run as long as files are being watched. If set to +`false` when using `fsevents` to watch, no more events will be emitted +after `ready`, even if the process continues to run. + +#### Path filtering + +* `ignored` ([anymatch](https://github.com/es128/anymatch)-compatible definition) +Defines files/paths to be ignored. The whole relative or absolute path is +tested, not just filename. If a function with two arguments is provided, it +gets called twice per path - once with a single argument (the path), second +time with two arguments (the path and the +[`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) +object of that path). +* `ignoreInitial` (default: `false`). If set to `false` then `add`/`addDir` events are also emitted for matching paths while +instantiating the watching as chokidar discovers these file paths (before the `ready` event). +* `followSymlinks` (default: `true`). When `false`, only the +symlinks themselves will be watched for changes instead of following +the link references and bubbling events through the link's path. +* `cwd` (no default). The base directory from which watch `paths` are to be +derived. Paths emitted with events will be relative to this. +* `disableGlobbing` (default: `false`). If set to `true` then the strings passed to `.watch()` and `.add()` are treated as +literal path names, even if they look like globs. + +#### Performance + +* `usePolling` (default: `false`). +Whether to use fs.watchFile (backed by polling), or fs.watch. If polling +leads to high CPU utilization, consider setting this to `false`. It is +typically necessary to **set this to `true` to successfully watch files over +a network**, and it may be necessary to successfully watch files in other +non-standard situations. Setting to `true` explicitly on MacOS overrides the +`useFsEvents` default. You may also set the CHOKIDAR_USEPOLLING env variable +to true (1) or false (0) in order to override this option. +* _Polling-specific settings_ (effective when `usePolling: true`) + * `interval` (default: `100`). Interval of file system polling, in milliseconds. You may also + set the CHOKIDAR_INTERVAL env variable to override this option. + * `binaryInterval` (default: `300`). Interval of file system + polling for binary files. + ([see list of binary extensions](https://github.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json)) +* `useFsEvents` (default: `true` on MacOS). Whether to use the +`fsevents` watching interface if available. When set to `true` explicitly +and `fsevents` is available this supercedes the `usePolling` setting. When +set to `false` on MacOS, `usePolling: true` becomes the default. +* `alwaysStat` (default: `false`). If relying upon the +[`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) +object that may get passed with `add`, `addDir`, and `change` events, set +this to `true` to ensure it is provided even in cases where it wasn't +already available from the underlying watch events. +* `depth` (default: `undefined`). If set, limits how many levels of +subdirectories will be traversed. +* `awaitWriteFinish` (default: `false`). +By default, the `add` event will fire when a file first appears on disk, before +the entire file has been written. Furthermore, in some cases some `change` +events will be emitted while the file is being written. In some cases, +especially when watching for large files there will be a need to wait for the +write operation to finish before responding to a file creation or modification. +Setting `awaitWriteFinish` to `true` (or a truthy value) will poll file size, +holding its `add` and `change` events until the size does not change for a +configurable amount of time. The appropriate duration setting is heavily +dependent on the OS and hardware. For accurate detection this parameter should +be relatively high, making file watching much less responsive. +Use with caution. + * *`options.awaitWriteFinish` can be set to an object in order to adjust + timing params:* + * `awaitWriteFinish.stabilityThreshold` (default: 2000). Amount of time in + milliseconds for a file size to remain constant before emitting its event. + * `awaitWriteFinish.pollInterval` (default: 100). File size polling interval, in milliseconds. + +#### Errors + +* `ignorePermissionErrors` (default: `false`). Indicates whether to watch files +that don't have read permissions if possible. If watching fails due to `EPERM` +or `EACCES` with this set to `true`, the errors will be suppressed silently. +* `atomic` (default: `true` if `useFsEvents` and `usePolling` are `false`). +Automatically filters out artifacts that occur when using editors that use +"atomic writes" instead of writing directly to the source file. If a file is +re-added within 100 ms of being deleted, Chokidar emits a `change` event +rather than `unlink` then `add`. If the default of 100 ms does not work well +for you, you can override it by setting `atomic` to a custom value, in +milliseconds. + +### Methods & Events + +`chokidar.watch()` produces an instance of `FSWatcher`. Methods of `FSWatcher`: + +* `.add(path / paths)`: Add files, directories, or glob patterns for tracking. +Takes an array of strings or just one string. +* `.on(event, callback)`: Listen for an FS event. +Available events: `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `ready`, +`raw`, `error`. +Additionally `all` is available which gets emitted with the underlying event +name and path for every event other than `ready`, `raw`, and `error`. `raw` is internal, use it carefully. +* `.unwatch(path / paths)`: Stop watching files, directories, or glob patterns. +Takes an array of strings or just one string. +* `.close()`: **async** Removes all listeners from watched files. Asynchronous, returns Promise. Use with `await` to ensure bugs don't happen. +* `.getWatched()`: Returns an object representing all the paths on the file +system being watched by this `FSWatcher` instance. The object's keys are all the +directories (using absolute paths unless the `cwd` option was used), and the +values are arrays of the names of the items contained in each directory. + +## CLI + +If you need a CLI interface for your file watching, check out +[chokidar-cli](https://github.com/open-cli-tools/chokidar-cli), allowing you to +execute a command on each change, or get a stdio stream of change events. + +## Install Troubleshooting + +* `npm WARN optional dep failed, continuing fsevents@n.n.n` + * This message is normal part of how `npm` handles optional dependencies and is + not indicative of a problem. Even if accompanied by other related error messages, + Chokidar should function properly. + +* `TypeError: fsevents is not a constructor` + * Update chokidar by doing `rm -rf node_modules package-lock.json yarn.lock && npm install`, or update your dependency that uses chokidar. + +* Chokidar is producing `ENOSP` error on Linux, like this: + * `bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shell` + `Error: watch /home/ ENOSPC` + * This means Chokidar ran out of file handles and you'll need to increase their count by executing the following command in Terminal: + `echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p` + +## Changelog + +For more detailed changelog, see [`full_changelog.md`](.github/full_changelog.md). +- **v3.5 (Jan 6, 2021):** Support for ARM Macs with Apple Silicon. Fixes for deleted symlinks. +- **v3.4 (Apr 26, 2020):** Support for directory-based symlinks. Fixes for macos file replacement. +- **v3.3 (Nov 2, 2019):** `FSWatcher#close()` method became async. That fixes IO race conditions related to close method. +- **v3.2 (Oct 1, 2019):** Improve Linux RAM usage by 50%. Race condition fixes. Windows glob fixes. Improve stability by using tight range of dependency versions. +- **v3.1 (Sep 16, 2019):** dotfiles are no longer filtered out by default. Use `ignored` option if needed. Improve initial Linux scan time by 50%. +- **v3 (Apr 30, 2019):** massive CPU & RAM consumption improvements; reduces deps / package size by a factor of 17x and bumps Node.js requirement to v8.16 and higher. +- **v2 (Dec 29, 2017):** Globs are now posix-style-only; without windows support. Tons of bugfixes. +- **v1 (Apr 7, 2015):** Glob support, symlink support, tons of bugfixes. Node 0.8+ is supported +- **v0.1 (Apr 20, 2012):** Initial release, extracted from [Brunch](https://github.com/brunch/brunch/blob/9847a065aea300da99bd0753f90354cde9de1261/src/helpers.coffee#L66) + +## Also + +Why was chokidar named this way? What's the meaning behind it? + +>Chowkidar is a transliteration of a Hindi word meaning 'watchman, gatekeeper', चौकीदार. This ultimately comes from Sanskrit _ चतुष्क_ (crossway, quadrangle, consisting-of-four). This word is also used in other languages like Urdu as (چوکیدار) which is widely used in Pakistan and India. + +## License + +MIT (c) Paul Miller (), see [LICENSE](LICENSE) file. diff --git a/node_modules/chokidar/index.js b/node_modules/chokidar/index.js new file mode 100644 index 0000000..8752893 --- /dev/null +++ b/node_modules/chokidar/index.js @@ -0,0 +1,973 @@ +'use strict'; + +const { EventEmitter } = require('events'); +const fs = require('fs'); +const sysPath = require('path'); +const { promisify } = require('util'); +const readdirp = require('readdirp'); +const anymatch = require('anymatch').default; +const globParent = require('glob-parent'); +const isGlob = require('is-glob'); +const braces = require('braces'); +const normalizePath = require('normalize-path'); + +const NodeFsHandler = require('./lib/nodefs-handler'); +const FsEventsHandler = require('./lib/fsevents-handler'); +const { + EV_ALL, + EV_READY, + EV_ADD, + EV_CHANGE, + EV_UNLINK, + EV_ADD_DIR, + EV_UNLINK_DIR, + EV_RAW, + EV_ERROR, + + STR_CLOSE, + STR_END, + + BACK_SLASH_RE, + DOUBLE_SLASH_RE, + SLASH_OR_BACK_SLASH_RE, + DOT_RE, + REPLACER_RE, + + SLASH, + SLASH_SLASH, + BRACE_START, + BANG, + ONE_DOT, + TWO_DOTS, + GLOBSTAR, + SLASH_GLOBSTAR, + ANYMATCH_OPTS, + STRING_TYPE, + FUNCTION_TYPE, + EMPTY_STR, + EMPTY_FN, + + isWindows, + isMacos, + isIBMi +} = require('./lib/constants'); + +const stat = promisify(fs.stat); +const readdir = promisify(fs.readdir); + +/** + * @typedef {String} Path + * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName + * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType + */ + +/** + * + * @typedef {Object} WatchHelpers + * @property {Boolean} followSymlinks + * @property {'stat'|'lstat'} statMethod + * @property {Path} path + * @property {Path} watchPath + * @property {Function} entryPath + * @property {Boolean} hasGlob + * @property {Object} globFilter + * @property {Function} filterPath + * @property {Function} filterDir + */ + +const arrify = (value = []) => Array.isArray(value) ? value : [value]; +const flatten = (list, result = []) => { + list.forEach(item => { + if (Array.isArray(item)) { + flatten(item, result); + } else { + result.push(item); + } + }); + return result; +}; + +const unifyPaths = (paths_) => { + /** + * @type {Array} + */ + const paths = flatten(arrify(paths_)); + if (!paths.every(p => typeof p === STRING_TYPE)) { + throw new TypeError(`Non-string provided as watch path: ${paths}`); + } + return paths.map(normalizePathToUnix); +}; + +// If SLASH_SLASH occurs at the beginning of path, it is not replaced +// because "//StoragePC/DrivePool/Movies" is a valid network path +const toUnix = (string) => { + let str = string.replace(BACK_SLASH_RE, SLASH); + let prepend = false; + if (str.startsWith(SLASH_SLASH)) { + prepend = true; + } + while (str.match(DOUBLE_SLASH_RE)) { + str = str.replace(DOUBLE_SLASH_RE, SLASH); + } + if (prepend) { + str = SLASH + str; + } + return str; +}; + +// Our version of upath.normalize +// TODO: this is not equal to path-normalize module - investigate why +const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path))); + +const normalizeIgnored = (cwd = EMPTY_STR) => (path) => { + if (typeof path !== STRING_TYPE) return path; + return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path)); +}; + +const getAbsolutePath = (path, cwd) => { + if (sysPath.isAbsolute(path)) { + return path; + } + if (path.startsWith(BANG)) { + return BANG + sysPath.join(cwd, path.slice(1)); + } + return sysPath.join(cwd, path); +}; + +const undef = (opts, key) => opts[key] === undefined; + +/** + * Directory entry. + * @property {Path} path + * @property {Set} items + */ +class DirEntry { + /** + * @param {Path} dir + * @param {Function} removeWatcher + */ + constructor(dir, removeWatcher) { + this.path = dir; + this._removeWatcher = removeWatcher; + /** @type {Set} */ + this.items = new Set(); + } + + add(item) { + const {items} = this; + if (!items) return; + if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item); + } + + async remove(item) { + const {items} = this; + if (!items) return; + items.delete(item); + if (items.size > 0) return; + + const dir = this.path; + try { + await readdir(dir); + } catch (err) { + if (this._removeWatcher) { + this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir)); + } + } + } + + has(item) { + const {items} = this; + if (!items) return; + return items.has(item); + } + + /** + * @returns {Array} + */ + getChildren() { + const {items} = this; + if (!items) return; + return [...items.values()]; + } + + dispose() { + this.items.clear(); + delete this.path; + delete this._removeWatcher; + delete this.items; + Object.freeze(this); + } +} + +const STAT_METHOD_F = 'stat'; +const STAT_METHOD_L = 'lstat'; +class WatchHelper { + constructor(path, watchPath, follow, fsw) { + this.fsw = fsw; + this.path = path = path.replace(REPLACER_RE, EMPTY_STR); + this.watchPath = watchPath; + this.fullWatchPath = sysPath.resolve(watchPath); + this.hasGlob = watchPath !== path; + /** @type {object|boolean} */ + if (path === EMPTY_STR) this.hasGlob = false; + this.globSymlink = this.hasGlob && follow ? undefined : false; + this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false; + this.dirParts = this.getDirParts(path); + this.dirParts.forEach((parts) => { + if (parts.length > 1) parts.pop(); + }); + this.followSymlinks = follow; + this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L; + } + + checkGlobSymlink(entry) { + // only need to resolve once + // first entry should always have entry.parentDir === EMPTY_STR + if (this.globSymlink === undefined) { + this.globSymlink = entry.fullParentDir === this.fullWatchPath ? + false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath}; + } + + if (this.globSymlink) { + return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath); + } + + return entry.fullPath; + } + + entryPath(entry) { + return sysPath.join(this.watchPath, + sysPath.relative(this.watchPath, this.checkGlobSymlink(entry)) + ); + } + + filterPath(entry) { + const {stats} = entry; + if (stats && stats.isSymbolicLink()) return this.filterDir(entry); + const resolvedPath = this.entryPath(entry); + const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ? + this.globFilter(resolvedPath) : true; + return matchesGlob && + this.fsw._isntIgnored(resolvedPath, stats) && + this.fsw._hasReadPermissions(stats); + } + + getDirParts(path) { + if (!this.hasGlob) return []; + const parts = []; + const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path]; + expandedPath.forEach((path) => { + parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE)); + }); + return parts; + } + + filterDir(entry) { + if (this.hasGlob) { + const entryParts = this.getDirParts(this.checkGlobSymlink(entry)); + let globstar = false; + this.unmatchedGlob = !this.dirParts.some((parts) => { + return parts.every((part, i) => { + if (part === GLOBSTAR) globstar = true; + return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS); + }); + }); + } + return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats); + } +} + +/** + * Watches files & directories for changes. Emitted events: + * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error` + * + * new FSWatcher() + * .add(directories) + * .on('add', path => log('File', path, 'was added')) + */ +class FSWatcher extends EventEmitter { +// Not indenting methods for history sake; for now. +constructor(_opts) { + super(); + + const opts = {}; + if (_opts) Object.assign(opts, _opts); // for frozen objects + + /** @type {Map} */ + this._watched = new Map(); + /** @type {Map} */ + this._closers = new Map(); + /** @type {Set} */ + this._ignoredPaths = new Set(); + + /** @type {Map} */ + this._throttled = new Map(); + + /** @type {Map} */ + this._symlinkPaths = new Map(); + + this._streams = new Set(); + this.closed = false; + + // Set up default options. + if (undef(opts, 'persistent')) opts.persistent = true; + if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false; + if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false; + if (undef(opts, 'interval')) opts.interval = 100; + if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300; + if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false; + opts.enableBinaryInterval = opts.binaryInterval !== opts.interval; + + // Enable fsevents on OS X when polling isn't explicitly enabled. + if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling; + + // If we can't use fsevents, ensure the options reflect it's disabled. + const canUseFsEvents = FsEventsHandler.canUse(); + if (!canUseFsEvents) opts.useFsEvents = false; + + // Use polling on Mac if not using fsevents. + // Other platforms use non-polling fs_watch. + if (undef(opts, 'usePolling') && !opts.useFsEvents) { + opts.usePolling = isMacos; + } + + // Always default to polling on IBM i because fs.watch() is not available on IBM i. + if(isIBMi) { + opts.usePolling = true; + } + + // Global override (useful for end-developers that need to force polling for all + // instances of chokidar, regardless of usage/dependency depth) + const envPoll = process.env.CHOKIDAR_USEPOLLING; + if (envPoll !== undefined) { + const envLower = envPoll.toLowerCase(); + + if (envLower === 'false' || envLower === '0') { + opts.usePolling = false; + } else if (envLower === 'true' || envLower === '1') { + opts.usePolling = true; + } else { + opts.usePolling = !!envLower; + } + } + const envInterval = process.env.CHOKIDAR_INTERVAL; + if (envInterval) { + opts.interval = Number.parseInt(envInterval, 10); + } + + // Editor atomic write normalization enabled by default with fs.watch + if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents; + if (opts.atomic) this._pendingUnlinks = new Map(); + + if (undef(opts, 'followSymlinks')) opts.followSymlinks = true; + + if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false; + if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {}; + const awf = opts.awaitWriteFinish; + if (awf) { + if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000; + if (!awf.pollInterval) awf.pollInterval = 100; + this._pendingWrites = new Map(); + } + if (opts.ignored) opts.ignored = arrify(opts.ignored); + + let readyCalls = 0; + this._emitReady = () => { + readyCalls++; + if (readyCalls >= this._readyCount) { + this._emitReady = EMPTY_FN; + this._readyEmitted = true; + // use process.nextTick to allow time for listener to be bound + process.nextTick(() => this.emit(EV_READY)); + } + }; + this._emitRaw = (...args) => this.emit(EV_RAW, ...args); + this._readyEmitted = false; + this.options = opts; + + // Initialize with proper watcher. + if (opts.useFsEvents) { + this._fsEventsHandler = new FsEventsHandler(this); + } else { + this._nodeFsHandler = new NodeFsHandler(this); + } + + // You’re frozen when your heart’s not open. + Object.freeze(opts); +} + +// Public methods + +/** + * Adds paths to be watched on an existing FSWatcher instance + * @param {Path|Array} paths_ + * @param {String=} _origAdd private; for handling non-existent paths to be watched + * @param {Boolean=} _internal private; indicates a non-user add + * @returns {FSWatcher} for chaining + */ +add(paths_, _origAdd, _internal) { + const {cwd, disableGlobbing} = this.options; + this.closed = false; + let paths = unifyPaths(paths_); + if (cwd) { + paths = paths.map((path) => { + const absPath = getAbsolutePath(path, cwd); + + // Check `path` instead of `absPath` because the cwd portion can't be a glob + if (disableGlobbing || !isGlob(path)) { + return absPath; + } + return normalizePath(absPath); + }); + } + + // set aside negated glob strings + paths = paths.filter((path) => { + if (path.startsWith(BANG)) { + this._ignoredPaths.add(path.slice(1)); + return false; + } + + // if a path is being added that was previously ignored, stop ignoring it + this._ignoredPaths.delete(path); + this._ignoredPaths.delete(path + SLASH_GLOBSTAR); + + // reset the cached userIgnored anymatch fn + // to make ignoredPaths changes effective + this._userIgnored = undefined; + + return true; + }); + + if (this.options.useFsEvents && this._fsEventsHandler) { + if (!this._readyCount) this._readyCount = paths.length; + if (this.options.persistent) this._readyCount += paths.length; + paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path)); + } else { + if (!this._readyCount) this._readyCount = 0; + this._readyCount += paths.length; + Promise.all( + paths.map(async path => { + const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd); + if (res) this._emitReady(); + return res; + }) + ).then(results => { + if (this.closed) return; + results.filter(item => item).forEach(item => { + this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item)); + }); + }); + } + + return this; +} + +/** + * Close watchers or start ignoring events from specified paths. + * @param {Path|Array} paths_ - string or array of strings, file/directory paths and/or globs + * @returns {FSWatcher} for chaining +*/ +unwatch(paths_) { + if (this.closed) return this; + const paths = unifyPaths(paths_); + const {cwd} = this.options; + + paths.forEach((path) => { + // convert to absolute path unless relative path already matches + if (!sysPath.isAbsolute(path) && !this._closers.has(path)) { + if (cwd) path = sysPath.join(cwd, path); + path = sysPath.resolve(path); + } + + this._closePath(path); + + this._ignoredPaths.add(path); + if (this._watched.has(path)) { + this._ignoredPaths.add(path + SLASH_GLOBSTAR); + } + + // reset the cached userIgnored anymatch fn + // to make ignoredPaths changes effective + this._userIgnored = undefined; + }); + + return this; +} + +/** + * Close watchers and remove all listeners from watched paths. + * @returns {Promise}. +*/ +close() { + if (this.closed) return this._closePromise; + this.closed = true; + + // Memory management. + this.removeAllListeners(); + const closers = []; + this._closers.forEach(closerList => closerList.forEach(closer => { + const promise = closer(); + if (promise instanceof Promise) closers.push(promise); + })); + this._streams.forEach(stream => stream.destroy()); + this._userIgnored = undefined; + this._readyCount = 0; + this._readyEmitted = false; + this._watched.forEach(dirent => dirent.dispose()); + ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => { + this[`_${key}`].clear(); + }); + + this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve(); + return this._closePromise; +} + +/** + * Expose list of watched paths + * @returns {Object} for chaining +*/ +getWatched() { + const watchList = {}; + this._watched.forEach((entry, dir) => { + const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir; + watchList[key || ONE_DOT] = entry.getChildren().sort(); + }); + return watchList; +} + +emitWithAll(event, args) { + this.emit(...args); + if (event !== EV_ERROR) this.emit(EV_ALL, ...args); +} + +// Common helpers +// -------------- + +/** + * Normalize and emit events. + * Calling _emit DOES NOT MEAN emit() would be called! + * @param {EventName} event Type of event + * @param {Path} path File or directory path + * @param {*=} val1 arguments to be passed with event + * @param {*=} val2 + * @param {*=} val3 + * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag + */ +async _emit(event, path, val1, val2, val3) { + if (this.closed) return; + + const opts = this.options; + if (isWindows) path = sysPath.normalize(path); + if (opts.cwd) path = sysPath.relative(opts.cwd, path); + /** @type Array */ + const args = [event, path]; + if (val3 !== undefined) args.push(val1, val2, val3); + else if (val2 !== undefined) args.push(val1, val2); + else if (val1 !== undefined) args.push(val1); + + const awf = opts.awaitWriteFinish; + let pw; + if (awf && (pw = this._pendingWrites.get(path))) { + pw.lastChange = new Date(); + return this; + } + + if (opts.atomic) { + if (event === EV_UNLINK) { + this._pendingUnlinks.set(path, args); + setTimeout(() => { + this._pendingUnlinks.forEach((entry, path) => { + this.emit(...entry); + this.emit(EV_ALL, ...entry); + this._pendingUnlinks.delete(path); + }); + }, typeof opts.atomic === 'number' ? opts.atomic : 100); + return this; + } + if (event === EV_ADD && this._pendingUnlinks.has(path)) { + event = args[0] = EV_CHANGE; + this._pendingUnlinks.delete(path); + } + } + + if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) { + const awfEmit = (err, stats) => { + if (err) { + event = args[0] = EV_ERROR; + args[1] = err; + this.emitWithAll(event, args); + } else if (stats) { + // if stats doesn't exist the file must have been deleted + if (args.length > 2) { + args[2] = stats; + } else { + args.push(stats); + } + this.emitWithAll(event, args); + } + }; + + this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit); + return this; + } + + if (event === EV_CHANGE) { + const isThrottled = !this._throttle(EV_CHANGE, path, 50); + if (isThrottled) return this; + } + + if (opts.alwaysStat && val1 === undefined && + (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE) + ) { + const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path; + let stats; + try { + stats = await stat(fullPath); + } catch (err) {} + // Suppress event when fs_stat fails, to avoid sending undefined 'stat' + if (!stats || this.closed) return; + args.push(stats); + } + this.emitWithAll(event, args); + + return this; +} + +/** + * Common handler for errors + * @param {Error} error + * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag + */ +_handleError(error) { + const code = error && error.code; + if (error && code !== 'ENOENT' && code !== 'ENOTDIR' && + (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES')) + ) { + this.emit(EV_ERROR, error); + } + return error || this.closed; +} + +/** + * Helper utility for throttling + * @param {ThrottleType} actionType type being throttled + * @param {Path} path being acted upon + * @param {Number} timeout duration of time to suppress duplicate actions + * @returns {Object|false} tracking object or false if action should be suppressed + */ +_throttle(actionType, path, timeout) { + if (!this._throttled.has(actionType)) { + this._throttled.set(actionType, new Map()); + } + + /** @type {Map} */ + const action = this._throttled.get(actionType); + /** @type {Object} */ + const actionPath = action.get(path); + + if (actionPath) { + actionPath.count++; + return false; + } + + let timeoutObject; + const clear = () => { + const item = action.get(path); + const count = item ? item.count : 0; + action.delete(path); + clearTimeout(timeoutObject); + if (item) clearTimeout(item.timeoutObject); + return count; + }; + timeoutObject = setTimeout(clear, timeout); + const thr = {timeoutObject, clear, count: 0}; + action.set(path, thr); + return thr; +} + +_incrReadyCount() { + return this._readyCount++; +} + +/** + * Awaits write operation to finish. + * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback. + * @param {Path} path being acted upon + * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished + * @param {EventName} event + * @param {Function} awfEmit Callback to be called when ready for event to be emitted. + */ +_awaitWriteFinish(path, threshold, event, awfEmit) { + let timeoutHandler; + + let fullPath = path; + if (this.options.cwd && !sysPath.isAbsolute(path)) { + fullPath = sysPath.join(this.options.cwd, path); + } + + const now = new Date(); + + const awaitWriteFinish = (prevStat) => { + fs.stat(fullPath, (err, curStat) => { + if (err || !this._pendingWrites.has(path)) { + if (err && err.code !== 'ENOENT') awfEmit(err); + return; + } + + const now = Number(new Date()); + + if (prevStat && curStat.size !== prevStat.size) { + this._pendingWrites.get(path).lastChange = now; + } + const pw = this._pendingWrites.get(path); + const df = now - pw.lastChange; + + if (df >= threshold) { + this._pendingWrites.delete(path); + awfEmit(undefined, curStat); + } else { + timeoutHandler = setTimeout( + awaitWriteFinish, + this.options.awaitWriteFinish.pollInterval, + curStat + ); + } + }); + }; + + if (!this._pendingWrites.has(path)) { + this._pendingWrites.set(path, { + lastChange: now, + cancelWait: () => { + this._pendingWrites.delete(path); + clearTimeout(timeoutHandler); + return event; + } + }); + timeoutHandler = setTimeout( + awaitWriteFinish, + this.options.awaitWriteFinish.pollInterval + ); + } +} + +_getGlobIgnored() { + return [...this._ignoredPaths.values()]; +} + +/** + * Determines whether user has asked to ignore this path. + * @param {Path} path filepath or dir + * @param {fs.Stats=} stats result of fs.stat + * @returns {Boolean} + */ +_isIgnored(path, stats) { + if (this.options.atomic && DOT_RE.test(path)) return true; + if (!this._userIgnored) { + const {cwd} = this.options; + const ign = this.options.ignored; + + const ignored = ign && ign.map(normalizeIgnored(cwd)); + const paths = arrify(ignored) + .filter((path) => typeof path === STRING_TYPE && !isGlob(path)) + .map((path) => path + SLASH_GLOBSTAR); + const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths); + this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS); + } + + return this._userIgnored([path, stats]); +} + +_isntIgnored(path, stat) { + return !this._isIgnored(path, stat); +} + +/** + * Provides a set of common helpers and properties relating to symlink and glob handling. + * @param {Path} path file, directory, or glob pattern being watched + * @param {Number=} depth at any depth > 0, this isn't a glob + * @returns {WatchHelper} object containing helpers for this path + */ +_getWatchHelpers(path, depth) { + const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path); + const follow = this.options.followSymlinks; + + return new WatchHelper(path, watchPath, follow, this); +} + +// Directory helpers +// ----------------- + +/** + * Provides directory tracking objects + * @param {String} directory path of the directory + * @returns {DirEntry} the directory's tracking object + */ +_getWatchedDir(directory) { + if (!this._boundRemove) this._boundRemove = this._remove.bind(this); + const dir = sysPath.resolve(directory); + if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove)); + return this._watched.get(dir); +} + +// File helpers +// ------------ + +/** + * Check for read permissions. + * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405 + * @param {fs.Stats} stats - object, result of fs_stat + * @returns {Boolean} indicates whether the file can be read +*/ +_hasReadPermissions(stats) { + if (this.options.ignorePermissionErrors) return true; + + // stats.mode may be bigint + const md = stats && Number.parseInt(stats.mode, 10); + const st = md & 0o777; + const it = Number.parseInt(st.toString(8)[0], 10); + return Boolean(4 & it); +} + +/** + * Handles emitting unlink events for + * files and directories, and via recursion, for + * files and directories within directories that are unlinked + * @param {String} directory within which the following item is located + * @param {String} item base path of item/directory + * @returns {void} +*/ +_remove(directory, item, isDirectory) { + // if what is being deleted is a directory, get that directory's paths + // for recursive deleting and cleaning of watched object + // if it is not a directory, nestedDirectoryChildren will be empty array + const path = sysPath.join(directory, item); + const fullPath = sysPath.resolve(path); + isDirectory = isDirectory != null + ? isDirectory + : this._watched.has(path) || this._watched.has(fullPath); + + // prevent duplicate handling in case of arriving here nearly simultaneously + // via multiple paths (such as _handleFile and _handleDir) + if (!this._throttle('remove', path, 100)) return; + + // if the only watched file is removed, watch for its return + if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) { + this.add(directory, item, true); + } + + // This will create a new entry in the watched object in either case + // so we got to do the directory check beforehand + const wp = this._getWatchedDir(path); + const nestedDirectoryChildren = wp.getChildren(); + + // Recursively remove children directories / files. + nestedDirectoryChildren.forEach(nested => this._remove(path, nested)); + + // Check if item was on the watched list and remove it + const parent = this._getWatchedDir(directory); + const wasTracked = parent.has(item); + parent.remove(item); + + // Fixes issue #1042 -> Relative paths were detected and added as symlinks + // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612), + // but never removed from the map in case the path was deleted. + // This leads to an incorrect state if the path was recreated: + // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553 + if (this._symlinkPaths.has(fullPath)) { + this._symlinkPaths.delete(fullPath); + } + + // If we wait for this file to be fully written, cancel the wait. + let relPath = path; + if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path); + if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) { + const event = this._pendingWrites.get(relPath).cancelWait(); + if (event === EV_ADD) return; + } + + // The Entry will either be a directory that just got removed + // or a bogus entry to a file, in either case we have to remove it + this._watched.delete(path); + this._watched.delete(fullPath); + const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK; + if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path); + + // Avoid conflicts if we later create another file with the same name + if (!this.options.useFsEvents) { + this._closePath(path); + } +} + +/** + * Closes all watchers for a path + * @param {Path} path + */ +_closePath(path) { + this._closeFile(path) + const dir = sysPath.dirname(path); + this._getWatchedDir(dir).remove(sysPath.basename(path)); +} + +/** + * Closes only file-specific watchers + * @param {Path} path + */ +_closeFile(path) { + const closers = this._closers.get(path); + if (!closers) return; + closers.forEach(closer => closer()); + this._closers.delete(path); +} + +/** + * + * @param {Path} path + * @param {Function} closer + */ +_addPathCloser(path, closer) { + if (!closer) return; + let list = this._closers.get(path); + if (!list) { + list = []; + this._closers.set(path, list); + } + list.push(closer); +} + +_readdirp(root, opts) { + if (this.closed) return; + const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts}; + let stream = readdirp(root, options); + this._streams.add(stream); + stream.once(STR_CLOSE, () => { + stream = undefined; + }); + stream.once(STR_END, () => { + if (stream) { + this._streams.delete(stream); + stream = undefined; + } + }); + return stream; +} + +} + +// Export FSWatcher class +exports.FSWatcher = FSWatcher; + +/** + * Instantiates watcher with paths to be tracked. + * @param {String|Array} paths file/directory paths and/or globs + * @param {Object=} options chokidar opts + * @returns an instance of FSWatcher for chaining. + */ +const watch = (paths, options) => { + const watcher = new FSWatcher(options); + watcher.add(paths); + return watcher; +}; + +exports.watch = watch; diff --git a/node_modules/chokidar/lib/constants.js b/node_modules/chokidar/lib/constants.js new file mode 100644 index 0000000..4743865 --- /dev/null +++ b/node_modules/chokidar/lib/constants.js @@ -0,0 +1,66 @@ +'use strict'; + +const {sep} = require('path'); +const {platform} = process; +const os = require('os'); + +exports.EV_ALL = 'all'; +exports.EV_READY = 'ready'; +exports.EV_ADD = 'add'; +exports.EV_CHANGE = 'change'; +exports.EV_ADD_DIR = 'addDir'; +exports.EV_UNLINK = 'unlink'; +exports.EV_UNLINK_DIR = 'unlinkDir'; +exports.EV_RAW = 'raw'; +exports.EV_ERROR = 'error'; + +exports.STR_DATA = 'data'; +exports.STR_END = 'end'; +exports.STR_CLOSE = 'close'; + +exports.FSEVENT_CREATED = 'created'; +exports.FSEVENT_MODIFIED = 'modified'; +exports.FSEVENT_DELETED = 'deleted'; +exports.FSEVENT_MOVED = 'moved'; +exports.FSEVENT_CLONED = 'cloned'; +exports.FSEVENT_UNKNOWN = 'unknown'; +exports.FSEVENT_FLAG_MUST_SCAN_SUBDIRS = 1; +exports.FSEVENT_TYPE_FILE = 'file'; +exports.FSEVENT_TYPE_DIRECTORY = 'directory'; +exports.FSEVENT_TYPE_SYMLINK = 'symlink'; + +exports.KEY_LISTENERS = 'listeners'; +exports.KEY_ERR = 'errHandlers'; +exports.KEY_RAW = 'rawEmitters'; +exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW]; + +exports.DOT_SLASH = `.${sep}`; + +exports.BACK_SLASH_RE = /\\/g; +exports.DOUBLE_SLASH_RE = /\/\//; +exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/; +exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/; +exports.REPLACER_RE = /^\.[/\\]/; + +exports.SLASH = '/'; +exports.SLASH_SLASH = '//'; +exports.BRACE_START = '{'; +exports.BANG = '!'; +exports.ONE_DOT = '.'; +exports.TWO_DOTS = '..'; +exports.STAR = '*'; +exports.GLOBSTAR = '**'; +exports.ROOT_GLOBSTAR = '/**/*'; +exports.SLASH_GLOBSTAR = '/**'; +exports.DIR_SUFFIX = 'Dir'; +exports.ANYMATCH_OPTS = {dot: true}; +exports.STRING_TYPE = 'string'; +exports.FUNCTION_TYPE = 'function'; +exports.EMPTY_STR = ''; +exports.EMPTY_FN = () => {}; +exports.IDENTITY_FN = val => val; + +exports.isWindows = platform === 'win32'; +exports.isMacos = platform === 'darwin'; +exports.isLinux = platform === 'linux'; +exports.isIBMi = os.type() === 'OS400'; diff --git a/node_modules/chokidar/lib/fsevents-handler.js b/node_modules/chokidar/lib/fsevents-handler.js new file mode 100644 index 0000000..fe29393 --- /dev/null +++ b/node_modules/chokidar/lib/fsevents-handler.js @@ -0,0 +1,526 @@ +'use strict'; + +const fs = require('fs'); +const sysPath = require('path'); +const { promisify } = require('util'); + +let fsevents; +try { + fsevents = require('fsevents'); +} catch (error) { + if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error); +} + +if (fsevents) { + // TODO: real check + const mtch = process.version.match(/v(\d+)\.(\d+)/); + if (mtch && mtch[1] && mtch[2]) { + const maj = Number.parseInt(mtch[1], 10); + const min = Number.parseInt(mtch[2], 10); + if (maj === 8 && min < 16) { + fsevents = undefined; + } + } +} + +const { + EV_ADD, + EV_CHANGE, + EV_ADD_DIR, + EV_UNLINK, + EV_ERROR, + STR_DATA, + STR_END, + FSEVENT_CREATED, + FSEVENT_MODIFIED, + FSEVENT_DELETED, + FSEVENT_MOVED, + // FSEVENT_CLONED, + FSEVENT_UNKNOWN, + FSEVENT_FLAG_MUST_SCAN_SUBDIRS, + FSEVENT_TYPE_FILE, + FSEVENT_TYPE_DIRECTORY, + FSEVENT_TYPE_SYMLINK, + + ROOT_GLOBSTAR, + DIR_SUFFIX, + DOT_SLASH, + FUNCTION_TYPE, + EMPTY_FN, + IDENTITY_FN +} = require('./constants'); + +const Depth = (value) => isNaN(value) ? {} : {depth: value}; + +const stat = promisify(fs.stat); +const lstat = promisify(fs.lstat); +const realpath = promisify(fs.realpath); + +const statMethods = { stat, lstat }; + +/** + * @typedef {String} Path + */ + +/** + * @typedef {Object} FsEventsWatchContainer + * @property {Set} listeners + * @property {Function} rawEmitter + * @property {{stop: Function}} watcher + */ + +// fsevents instance helper functions +/** + * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances) + * @type {Map} + */ +const FSEventsWatchers = new Map(); + +// Threshold of duplicate path prefixes at which to start +// consolidating going forward +const consolidateThreshhold = 10; + +const wrongEventFlags = new Set([ + 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912 +]); + +/** + * Instantiates the fsevents interface + * @param {Path} path path to be watched + * @param {Function} callback called when fsevents is bound and ready + * @returns {{stop: Function}} new fsevents instance + */ +const createFSEventsInstance = (path, callback) => { + const stop = fsevents.watch(path, callback); + return {stop}; +}; + +/** + * Instantiates the fsevents interface or binds listeners to an existing one covering + * the same file tree. + * @param {Path} path - to be watched + * @param {Path} realPath - real path for symlinks + * @param {Function} listener - called when fsevents emits events + * @param {Function} rawEmitter - passes data to listeners of the 'raw' event + * @returns {Function} closer + */ +function setFSEventsListener(path, realPath, listener, rawEmitter) { + let watchPath = sysPath.extname(realPath) ? sysPath.dirname(realPath) : realPath; + + const parentPath = sysPath.dirname(watchPath); + let cont = FSEventsWatchers.get(watchPath); + + // If we've accumulated a substantial number of paths that + // could have been consolidated by watching one directory + // above the current one, create a watcher on the parent + // path instead, so that we do consolidate going forward. + if (couldConsolidate(parentPath)) { + watchPath = parentPath; + } + + const resolvedPath = sysPath.resolve(path); + const hasSymlink = resolvedPath !== realPath; + + const filteredListener = (fullPath, flags, info) => { + if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath); + if ( + fullPath === resolvedPath || + !fullPath.indexOf(resolvedPath + sysPath.sep) + ) listener(fullPath, flags, info); + }; + + // check if there is already a watcher on a parent path + // modifies `watchPath` to the parent path when it finds a match + let watchedParent = false; + for (const watchedPath of FSEventsWatchers.keys()) { + if (realPath.indexOf(sysPath.resolve(watchedPath) + sysPath.sep) === 0) { + watchPath = watchedPath; + cont = FSEventsWatchers.get(watchPath); + watchedParent = true; + break; + } + } + + if (cont || watchedParent) { + cont.listeners.add(filteredListener); + } else { + cont = { + listeners: new Set([filteredListener]), + rawEmitter, + watcher: createFSEventsInstance(watchPath, (fullPath, flags) => { + if (!cont.listeners.size) return; + if (flags & FSEVENT_FLAG_MUST_SCAN_SUBDIRS) return; + const info = fsevents.getInfo(fullPath, flags); + cont.listeners.forEach(list => { + list(fullPath, flags, info); + }); + + cont.rawEmitter(info.event, fullPath, info); + }) + }; + FSEventsWatchers.set(watchPath, cont); + } + + // removes this instance's listeners and closes the underlying fsevents + // instance if there are no more listeners left + return () => { + const lst = cont.listeners; + + lst.delete(filteredListener); + if (!lst.size) { + FSEventsWatchers.delete(watchPath); + if (cont.watcher) return cont.watcher.stop().then(() => { + cont.rawEmitter = cont.watcher = undefined; + Object.freeze(cont); + }); + } + }; +} + +// Decide whether or not we should start a new higher-level +// parent watcher +const couldConsolidate = (path) => { + let count = 0; + for (const watchPath of FSEventsWatchers.keys()) { + if (watchPath.indexOf(path) === 0) { + count++; + if (count >= consolidateThreshhold) { + return true; + } + } + } + + return false; +}; + +// returns boolean indicating whether fsevents can be used +const canUse = () => fsevents && FSEventsWatchers.size < 128; + +// determines subdirectory traversal levels from root to path +const calcDepth = (path, root) => { + let i = 0; + while (!path.indexOf(root) && (path = sysPath.dirname(path)) !== root) i++; + return i; +}; + +// returns boolean indicating whether the fsevents' event info has the same type +// as the one returned by fs.stat +const sameTypes = (info, stats) => ( + info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() || + info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() || + info.type === FSEVENT_TYPE_FILE && stats.isFile() +) + +/** + * @mixin + */ +class FsEventsHandler { + +/** + * @param {import('../index').FSWatcher} fsw + */ +constructor(fsw) { + this.fsw = fsw; +} +checkIgnored(path, stats) { + const ipaths = this.fsw._ignoredPaths; + if (this.fsw._isIgnored(path, stats)) { + ipaths.add(path); + if (stats && stats.isDirectory()) { + ipaths.add(path + ROOT_GLOBSTAR); + } + return true; + } + + ipaths.delete(path); + ipaths.delete(path + ROOT_GLOBSTAR); +} + +addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) { + const event = watchedDir.has(item) ? EV_CHANGE : EV_ADD; + this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts); +} + +async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) { + try { + const stats = await stat(path) + if (this.fsw.closed) return; + if (sameTypes(info, stats)) { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } catch (error) { + if (error.code === 'EACCES') { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } +} + +handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) { + if (this.fsw.closed || this.checkIgnored(path)) return; + + if (event === EV_UNLINK) { + const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY + // suppress unlink events on never before seen files + if (isDirectory || watchedDir.has(item)) { + this.fsw._remove(parent, item, isDirectory); + } + } else { + if (event === EV_ADD) { + // track new directories + if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path); + + if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) { + // push symlinks back to the top of the stack to get handled + const curDepth = opts.depth === undefined ? + undefined : calcDepth(fullPath, realPath) + 1; + return this._addToFsEvents(path, false, true, curDepth); + } + + // track new paths + // (other than symlinks being followed, which will be tracked soon) + this.fsw._getWatchedDir(parent).add(item); + } + /** + * @type {'add'|'addDir'|'unlink'|'unlinkDir'} + */ + const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event; + this.fsw._emit(eventName, path); + if (eventName === EV_ADD_DIR) this._addToFsEvents(path, false, true); + } +} + +/** + * Handle symlinks encountered during directory scan + * @param {String} watchPath - file/dir path to be watched with fsevents + * @param {String} realPath - real path (in case of symlinks) + * @param {Function} transform - path transformer + * @param {Function} globFilter - path filter in case a glob pattern was provided + * @returns {Function} closer for the watcher instance +*/ +_watchWithFsEvents(watchPath, realPath, transform, globFilter) { + if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return; + const opts = this.fsw.options; + const watchCallback = async (fullPath, flags, info) => { + if (this.fsw.closed) return; + if ( + opts.depth !== undefined && + calcDepth(fullPath, realPath) > opts.depth + ) return; + const path = transform(sysPath.join( + watchPath, sysPath.relative(watchPath, fullPath) + )); + if (globFilter && !globFilter(path)) return; + // ensure directories are tracked + const parent = sysPath.dirname(path); + const item = sysPath.basename(path); + const watchedDir = this.fsw._getWatchedDir( + info.type === FSEVENT_TYPE_DIRECTORY ? path : parent + ); + + // correct for wrong events emitted + if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) { + if (typeof opts.ignored === FUNCTION_TYPE) { + let stats; + try { + stats = await stat(path); + } catch (error) {} + if (this.fsw.closed) return; + if (this.checkIgnored(path, stats)) return; + if (sameTypes(info, stats)) { + this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } else { + this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } else { + this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } else { + switch (info.event) { + case FSEVENT_CREATED: + case FSEVENT_MODIFIED: + return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); + case FSEVENT_DELETED: + case FSEVENT_MOVED: + return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts); + } + } + }; + + const closer = setFSEventsListener( + watchPath, + realPath, + watchCallback, + this.fsw._emitRaw + ); + + this.fsw._emitReady(); + return closer; +} + +/** + * Handle symlinks encountered during directory scan + * @param {String} linkPath path to symlink + * @param {String} fullPath absolute path to the symlink + * @param {Function} transform pre-existing path transformer + * @param {Number} curDepth level of subdirectories traversed to where symlink is + * @returns {Promise} + */ +async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) { + // don't follow the same symlink more than once + if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return; + + this.fsw._symlinkPaths.set(fullPath, true); + this.fsw._incrReadyCount(); + + try { + const linkTarget = await realpath(linkPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(linkTarget)) { + return this.fsw._emitReady(); + } + + this.fsw._incrReadyCount(); + + // add the linkTarget for watching with a wrapper for transform + // that causes emitted paths to incorporate the link's path + this._addToFsEvents(linkTarget || linkPath, (path) => { + let aliasedPath = linkPath; + if (linkTarget && linkTarget !== DOT_SLASH) { + aliasedPath = path.replace(linkTarget, linkPath); + } else if (path !== DOT_SLASH) { + aliasedPath = sysPath.join(linkPath, path); + } + return transform(aliasedPath); + }, false, curDepth); + } catch(error) { + if (this.fsw._handleError(error)) { + return this.fsw._emitReady(); + } + } +} + +/** + * + * @param {Path} newPath + * @param {fs.Stats} stats + */ +emitAdd(newPath, stats, processPath, opts, forceAdd) { + const pp = processPath(newPath); + const isDir = stats.isDirectory(); + const dirObj = this.fsw._getWatchedDir(sysPath.dirname(pp)); + const base = sysPath.basename(pp); + + // ensure empty dirs get tracked + if (isDir) this.fsw._getWatchedDir(pp); + if (dirObj.has(base)) return; + dirObj.add(base); + + if (!opts.ignoreInitial || forceAdd === true) { + this.fsw._emit(isDir ? EV_ADD_DIR : EV_ADD, pp, stats); + } +} + +initWatch(realPath, path, wh, processPath) { + if (this.fsw.closed) return; + const closer = this._watchWithFsEvents( + wh.watchPath, + sysPath.resolve(realPath || wh.watchPath), + processPath, + wh.globFilter + ); + this.fsw._addPathCloser(path, closer); +} + +/** + * Handle added path with fsevents + * @param {String} path file/dir path or glob pattern + * @param {Function|Boolean=} transform converts working path to what the user expects + * @param {Boolean=} forceAdd ensure add is emitted + * @param {Number=} priorDepth Level of subdirectories already traversed. + * @returns {Promise} + */ +async _addToFsEvents(path, transform, forceAdd, priorDepth) { + if (this.fsw.closed) { + return; + } + const opts = this.fsw.options; + const processPath = typeof transform === FUNCTION_TYPE ? transform : IDENTITY_FN; + + const wh = this.fsw._getWatchHelpers(path); + + // evaluate what is at the path we're being asked to watch + try { + const stats = await statMethods[wh.statMethod](wh.watchPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(wh.watchPath, stats)) { + throw null; + } + if (stats.isDirectory()) { + // emit addDir unless this is a glob parent + if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd); + + // don't recurse further if it would exceed depth setting + if (priorDepth && priorDepth > opts.depth) return; + + // scan the contents of the dir + this.fsw._readdirp(wh.watchPath, { + fileFilter: entry => wh.filterPath(entry), + directoryFilter: entry => wh.filterDir(entry), + ...Depth(opts.depth - (priorDepth || 0)) + }).on(STR_DATA, (entry) => { + // need to check filterPath on dirs b/c filterDir is less restrictive + if (this.fsw.closed) { + return; + } + if (entry.stats.isDirectory() && !wh.filterPath(entry)) return; + + const joinedPath = sysPath.join(wh.watchPath, entry.path); + const {fullPath} = entry; + + if (wh.followSymlinks && entry.stats.isSymbolicLink()) { + // preserve the current depth here since it can't be derived from + // real paths past the symlink + const curDepth = opts.depth === undefined ? + undefined : calcDepth(joinedPath, sysPath.resolve(wh.watchPath)) + 1; + + this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth); + } else { + this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd); + } + }).on(EV_ERROR, EMPTY_FN).on(STR_END, () => { + this.fsw._emitReady(); + }); + } else { + this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd); + this.fsw._emitReady(); + } + } catch (error) { + if (!error || this.fsw._handleError(error)) { + // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__- + this.fsw._emitReady(); + this.fsw._emitReady(); + } + } + + if (opts.persistent && forceAdd !== true) { + if (typeof transform === FUNCTION_TYPE) { + // realpath has already been resolved + this.initWatch(undefined, path, wh, processPath); + } else { + let realPath; + try { + realPath = await realpath(wh.watchPath); + } catch (e) {} + this.initWatch(realPath, path, wh, processPath); + } + } +} + +} + +module.exports = FsEventsHandler; +module.exports.canUse = canUse; diff --git a/node_modules/chokidar/lib/nodefs-handler.js b/node_modules/chokidar/lib/nodefs-handler.js new file mode 100644 index 0000000..199cfe9 --- /dev/null +++ b/node_modules/chokidar/lib/nodefs-handler.js @@ -0,0 +1,654 @@ +'use strict'; + +const fs = require('fs'); +const sysPath = require('path'); +const { promisify } = require('util'); +const isBinaryPath = require('is-binary-path'); +const { + isWindows, + isLinux, + EMPTY_FN, + EMPTY_STR, + KEY_LISTENERS, + KEY_ERR, + KEY_RAW, + HANDLER_KEYS, + EV_CHANGE, + EV_ADD, + EV_ADD_DIR, + EV_ERROR, + STR_DATA, + STR_END, + BRACE_START, + STAR +} = require('./constants'); + +const THROTTLE_MODE_WATCH = 'watch'; + +const open = promisify(fs.open); +const stat = promisify(fs.stat); +const lstat = promisify(fs.lstat); +const close = promisify(fs.close); +const fsrealpath = promisify(fs.realpath); + +const statMethods = { lstat, stat }; + +// TODO: emit errors properly. Example: EMFILE on Macos. +const foreach = (val, fn) => { + if (val instanceof Set) { + val.forEach(fn); + } else { + fn(val); + } +}; + +const addAndConvert = (main, prop, item) => { + let container = main[prop]; + if (!(container instanceof Set)) { + main[prop] = container = new Set([container]); + } + container.add(item); +}; + +const clearItem = cont => key => { + const set = cont[key]; + if (set instanceof Set) { + set.clear(); + } else { + delete cont[key]; + } +}; + +const delFromSet = (main, prop, item) => { + const container = main[prop]; + if (container instanceof Set) { + container.delete(item); + } else if (container === item) { + delete main[prop]; + } +}; + +const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val; + +/** + * @typedef {String} Path + */ + +// fs_watch helpers + +// object to hold per-process fs_watch instances +// (may be shared across chokidar FSWatcher instances) + +/** + * @typedef {Object} FsWatchContainer + * @property {Set} listeners + * @property {Set} errHandlers + * @property {Set} rawEmitters + * @property {fs.FSWatcher=} watcher + * @property {Boolean=} watcherUnusable + */ + +/** + * @type {Map} + */ +const FsWatchInstances = new Map(); + +/** + * Instantiates the fs_watch interface + * @param {String} path to be watched + * @param {Object} options to be passed to fs_watch + * @param {Function} listener main event handler + * @param {Function} errHandler emits info about errors + * @param {Function} emitRaw emits raw event data + * @returns {fs.FSWatcher} new fsevents instance + */ +function createFsWatchInstance(path, options, listener, errHandler, emitRaw) { + const handleEvent = (rawEvent, evPath) => { + listener(path); + emitRaw(rawEvent, evPath, {watchedPath: path}); + + // emit based on events occurring for files from a directory's watcher in + // case the file's watcher misses it (and rely on throttling to de-dupe) + if (evPath && path !== evPath) { + fsWatchBroadcast( + sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath) + ); + } + }; + try { + return fs.watch(path, options, handleEvent); + } catch (error) { + errHandler(error); + } +} + +/** + * Helper for passing fs_watch event data to a collection of listeners + * @param {Path} fullPath absolute path bound to fs_watch instance + * @param {String} type listener type + * @param {*=} val1 arguments to be passed to listeners + * @param {*=} val2 + * @param {*=} val3 + */ +const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => { + const cont = FsWatchInstances.get(fullPath); + if (!cont) return; + foreach(cont[type], (listener) => { + listener(val1, val2, val3); + }); +}; + +/** + * Instantiates the fs_watch interface or binds listeners + * to an existing one covering the same file system entry + * @param {String} path + * @param {String} fullPath absolute path + * @param {Object} options to be passed to fs_watch + * @param {Object} handlers container for event listener functions + */ +const setFsWatchListener = (path, fullPath, options, handlers) => { + const {listener, errHandler, rawEmitter} = handlers; + let cont = FsWatchInstances.get(fullPath); + + /** @type {fs.FSWatcher=} */ + let watcher; + if (!options.persistent) { + watcher = createFsWatchInstance( + path, options, listener, errHandler, rawEmitter + ); + return watcher.close.bind(watcher); + } + if (cont) { + addAndConvert(cont, KEY_LISTENERS, listener); + addAndConvert(cont, KEY_ERR, errHandler); + addAndConvert(cont, KEY_RAW, rawEmitter); + } else { + watcher = createFsWatchInstance( + path, + options, + fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), + errHandler, // no need to use broadcast here + fsWatchBroadcast.bind(null, fullPath, KEY_RAW) + ); + if (!watcher) return; + watcher.on(EV_ERROR, async (error) => { + const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR); + cont.watcherUnusable = true; // documented since Node 10.4.1 + // Workaround for https://github.com/joyent/node/issues/4337 + if (isWindows && error.code === 'EPERM') { + try { + const fd = await open(path, 'r'); + await close(fd); + broadcastErr(error); + } catch (err) {} + } else { + broadcastErr(error); + } + }); + cont = { + listeners: listener, + errHandlers: errHandler, + rawEmitters: rawEmitter, + watcher + }; + FsWatchInstances.set(fullPath, cont); + } + // const index = cont.listeners.indexOf(listener); + + // removes this instance's listeners and closes the underlying fs_watch + // instance if there are no more listeners left + return () => { + delFromSet(cont, KEY_LISTENERS, listener); + delFromSet(cont, KEY_ERR, errHandler); + delFromSet(cont, KEY_RAW, rawEmitter); + if (isEmptySet(cont.listeners)) { + // Check to protect against issue gh-730. + // if (cont.watcherUnusable) { + cont.watcher.close(); + // } + FsWatchInstances.delete(fullPath); + HANDLER_KEYS.forEach(clearItem(cont)); + cont.watcher = undefined; + Object.freeze(cont); + } + }; +}; + +// fs_watchFile helpers + +// object to hold per-process fs_watchFile instances +// (may be shared across chokidar FSWatcher instances) +const FsWatchFileInstances = new Map(); + +/** + * Instantiates the fs_watchFile interface or binds listeners + * to an existing one covering the same file system entry + * @param {String} path to be watched + * @param {String} fullPath absolute path + * @param {Object} options options to be passed to fs_watchFile + * @param {Object} handlers container for event listener functions + * @returns {Function} closer + */ +const setFsWatchFileListener = (path, fullPath, options, handlers) => { + const {listener, rawEmitter} = handlers; + let cont = FsWatchFileInstances.get(fullPath); + + /* eslint-disable no-unused-vars, prefer-destructuring */ + let listeners = new Set(); + let rawEmitters = new Set(); + + const copts = cont && cont.options; + if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) { + // "Upgrade" the watcher to persistence or a quicker interval. + // This creates some unlikely edge case issues if the user mixes + // settings in a very weird way, but solving for those cases + // doesn't seem worthwhile for the added complexity. + listeners = cont.listeners; + rawEmitters = cont.rawEmitters; + fs.unwatchFile(fullPath); + cont = undefined; + } + + /* eslint-enable no-unused-vars, prefer-destructuring */ + + if (cont) { + addAndConvert(cont, KEY_LISTENERS, listener); + addAndConvert(cont, KEY_RAW, rawEmitter); + } else { + // TODO + // listeners.add(listener); + // rawEmitters.add(rawEmitter); + cont = { + listeners: listener, + rawEmitters: rawEmitter, + options, + watcher: fs.watchFile(fullPath, options, (curr, prev) => { + foreach(cont.rawEmitters, (rawEmitter) => { + rawEmitter(EV_CHANGE, fullPath, {curr, prev}); + }); + const currmtime = curr.mtimeMs; + if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) { + foreach(cont.listeners, (listener) => listener(path, curr)); + } + }) + }; + FsWatchFileInstances.set(fullPath, cont); + } + // const index = cont.listeners.indexOf(listener); + + // Removes this instance's listeners and closes the underlying fs_watchFile + // instance if there are no more listeners left. + return () => { + delFromSet(cont, KEY_LISTENERS, listener); + delFromSet(cont, KEY_RAW, rawEmitter); + if (isEmptySet(cont.listeners)) { + FsWatchFileInstances.delete(fullPath); + fs.unwatchFile(fullPath); + cont.options = cont.watcher = undefined; + Object.freeze(cont); + } + }; +}; + +/** + * @mixin + */ +class NodeFsHandler { + +/** + * @param {import("../index").FSWatcher} fsW + */ +constructor(fsW) { + this.fsw = fsW; + this._boundHandleError = (error) => fsW._handleError(error); +} + +/** + * Watch file for changes with fs_watchFile or fs_watch. + * @param {String} path to file or dir + * @param {Function} listener on fs change + * @returns {Function} closer for the watcher instance + */ +_watchWithNodeFs(path, listener) { + const opts = this.fsw.options; + const directory = sysPath.dirname(path); + const basename = sysPath.basename(path); + const parent = this.fsw._getWatchedDir(directory); + parent.add(basename); + const absolutePath = sysPath.resolve(path); + const options = {persistent: opts.persistent}; + if (!listener) listener = EMPTY_FN; + + let closer; + if (opts.usePolling) { + options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ? + opts.binaryInterval : opts.interval; + closer = setFsWatchFileListener(path, absolutePath, options, { + listener, + rawEmitter: this.fsw._emitRaw + }); + } else { + closer = setFsWatchListener(path, absolutePath, options, { + listener, + errHandler: this._boundHandleError, + rawEmitter: this.fsw._emitRaw + }); + } + return closer; +} + +/** + * Watch a file and emit add event if warranted. + * @param {Path} file Path + * @param {fs.Stats} stats result of fs_stat + * @param {Boolean} initialAdd was the file added at watch instantiation? + * @returns {Function} closer for the watcher instance + */ +_handleFile(file, stats, initialAdd) { + if (this.fsw.closed) { + return; + } + const dirname = sysPath.dirname(file); + const basename = sysPath.basename(file); + const parent = this.fsw._getWatchedDir(dirname); + // stats is always present + let prevStats = stats; + + // if the file is already being watched, do nothing + if (parent.has(basename)) return; + + const listener = async (path, newStats) => { + if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return; + if (!newStats || newStats.mtimeMs === 0) { + try { + const newStats = await stat(file); + if (this.fsw.closed) return; + // Check that change event was not fired because of changed only accessTime. + const at = newStats.atimeMs; + const mt = newStats.mtimeMs; + if (!at || at <= mt || mt !== prevStats.mtimeMs) { + this.fsw._emit(EV_CHANGE, file, newStats); + } + if (isLinux && prevStats.ino !== newStats.ino) { + this.fsw._closeFile(path) + prevStats = newStats; + this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener)); + } else { + prevStats = newStats; + } + } catch (error) { + // Fix issues where mtime is null but file is still present + this.fsw._remove(dirname, basename); + } + // add is about to be emitted if file not already tracked in parent + } else if (parent.has(basename)) { + // Check that change event was not fired because of changed only accessTime. + const at = newStats.atimeMs; + const mt = newStats.mtimeMs; + if (!at || at <= mt || mt !== prevStats.mtimeMs) { + this.fsw._emit(EV_CHANGE, file, newStats); + } + prevStats = newStats; + } + } + // kick off the watcher + const closer = this._watchWithNodeFs(file, listener); + + // emit an add event if we're supposed to + if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) { + if (!this.fsw._throttle(EV_ADD, file, 0)) return; + this.fsw._emit(EV_ADD, file, stats); + } + + return closer; +} + +/** + * Handle symlinks encountered while reading a dir. + * @param {Object} entry returned by readdirp + * @param {String} directory path of dir being read + * @param {String} path of this item + * @param {String} item basename of this item + * @returns {Promise} true if no more processing is needed for this entry. + */ +async _handleSymlink(entry, directory, path, item) { + if (this.fsw.closed) { + return; + } + const full = entry.fullPath; + const dir = this.fsw._getWatchedDir(directory); + + if (!this.fsw.options.followSymlinks) { + // watch symlink directly (don't follow) and detect changes + this.fsw._incrReadyCount(); + + let linkPath; + try { + linkPath = await fsrealpath(path); + } catch (e) { + this.fsw._emitReady(); + return true; + } + + if (this.fsw.closed) return; + if (dir.has(item)) { + if (this.fsw._symlinkPaths.get(full) !== linkPath) { + this.fsw._symlinkPaths.set(full, linkPath); + this.fsw._emit(EV_CHANGE, path, entry.stats); + } + } else { + dir.add(item); + this.fsw._symlinkPaths.set(full, linkPath); + this.fsw._emit(EV_ADD, path, entry.stats); + } + this.fsw._emitReady(); + return true; + } + + // don't follow the same symlink more than once + if (this.fsw._symlinkPaths.has(full)) { + return true; + } + + this.fsw._symlinkPaths.set(full, true); +} + +_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) { + // Normalize the directory name on Windows + directory = sysPath.join(directory, EMPTY_STR); + + if (!wh.hasGlob) { + throttler = this.fsw._throttle('readdir', directory, 1000); + if (!throttler) return; + } + + const previous = this.fsw._getWatchedDir(wh.path); + const current = new Set(); + + let stream = this.fsw._readdirp(directory, { + fileFilter: entry => wh.filterPath(entry), + directoryFilter: entry => wh.filterDir(entry), + depth: 0 + }).on(STR_DATA, async (entry) => { + if (this.fsw.closed) { + stream = undefined; + return; + } + const item = entry.path; + let path = sysPath.join(directory, item); + current.add(item); + + if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) { + return; + } + + if (this.fsw.closed) { + stream = undefined; + return; + } + // Files that present in current directory snapshot + // but absent in previous are added to watch list and + // emit `add` event. + if (item === target || !target && !previous.has(item)) { + this.fsw._incrReadyCount(); + + // ensure relativeness of path is preserved in case of watcher reuse + path = sysPath.join(dir, sysPath.relative(dir, path)); + + this._addToNodeFs(path, initialAdd, wh, depth + 1); + } + }).on(EV_ERROR, this._boundHandleError); + + return new Promise(resolve => + stream.once(STR_END, () => { + if (this.fsw.closed) { + stream = undefined; + return; + } + const wasThrottled = throttler ? throttler.clear() : false; + + resolve(); + + // Files that absent in current directory snapshot + // but present in previous emit `remove` event + // and are removed from @watched[directory]. + previous.getChildren().filter((item) => { + return item !== directory && + !current.has(item) && + // in case of intersecting globs; + // a path may have been filtered out of this readdir, but + // shouldn't be removed because it matches a different glob + (!wh.hasGlob || wh.filterPath({ + fullPath: sysPath.resolve(directory, item) + })); + }).forEach((item) => { + this.fsw._remove(directory, item); + }); + + stream = undefined; + + // one more time for any missed in case changes came in extremely quickly + if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler); + }) + ); +} + +/** + * Read directory to add / remove files from `@watched` list and re-read it on change. + * @param {String} dir fs path + * @param {fs.Stats} stats + * @param {Boolean} initialAdd + * @param {Number} depth relative to user-supplied path + * @param {String} target child path targeted for watch + * @param {Object} wh Common watch helpers for this path + * @param {String} realpath + * @returns {Promise} closer for the watcher instance. + */ +async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) { + const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir)); + const tracked = parentDir.has(sysPath.basename(dir)); + if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) { + if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats); + } + + // ensure dir is tracked (harmless if redundant) + parentDir.add(sysPath.basename(dir)); + this.fsw._getWatchedDir(dir); + let throttler; + let closer; + + const oDepth = this.fsw.options.depth; + if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) { + if (!target) { + await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler); + if (this.fsw.closed) return; + } + + closer = this._watchWithNodeFs(dir, (dirPath, stats) => { + // if current directory is removed, do nothing + if (stats && stats.mtimeMs === 0) return; + + this._handleRead(dirPath, false, wh, target, dir, depth, throttler); + }); + } + return closer; +} + +/** + * Handle added file, directory, or glob pattern. + * Delegates call to _handleFile / _handleDir after checks. + * @param {String} path to file or ir + * @param {Boolean} initialAdd was the file added at watch instantiation? + * @param {Object} priorWh depth relative to user-supplied path + * @param {Number} depth Child path actually targeted for watch + * @param {String=} target Child path actually targeted for watch + * @returns {Promise} + */ +async _addToNodeFs(path, initialAdd, priorWh, depth, target) { + const ready = this.fsw._emitReady; + if (this.fsw._isIgnored(path) || this.fsw.closed) { + ready(); + return false; + } + + const wh = this.fsw._getWatchHelpers(path, depth); + if (!wh.hasGlob && priorWh) { + wh.hasGlob = priorWh.hasGlob; + wh.globFilter = priorWh.globFilter; + wh.filterPath = entry => priorWh.filterPath(entry); + wh.filterDir = entry => priorWh.filterDir(entry); + } + + // evaluate what is at the path we're being asked to watch + try { + const stats = await statMethods[wh.statMethod](wh.watchPath); + if (this.fsw.closed) return; + if (this.fsw._isIgnored(wh.watchPath, stats)) { + ready(); + return false; + } + + const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START); + let closer; + if (stats.isDirectory()) { + const absPath = sysPath.resolve(path); + const targetPath = follow ? await fsrealpath(path) : path; + if (this.fsw.closed) return; + closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath); + if (this.fsw.closed) return; + // preserve this symlink's target path + if (absPath !== targetPath && targetPath !== undefined) { + this.fsw._symlinkPaths.set(absPath, targetPath); + } + } else if (stats.isSymbolicLink()) { + const targetPath = follow ? await fsrealpath(path) : path; + if (this.fsw.closed) return; + const parent = sysPath.dirname(wh.watchPath); + this.fsw._getWatchedDir(parent).add(wh.watchPath); + this.fsw._emit(EV_ADD, wh.watchPath, stats); + closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath); + if (this.fsw.closed) return; + + // preserve this symlink's target path + if (targetPath !== undefined) { + this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath); + } + } else { + closer = this._handleFile(wh.watchPath, stats, initialAdd); + } + ready(); + + this.fsw._addPathCloser(path, closer); + return false; + + } catch (error) { + if (this.fsw._handleError(error)) { + ready(); + return path; + } + } +} + +} + +module.exports = NodeFsHandler; diff --git a/node_modules/chokidar/node_modules/glob-parent/CHANGELOG.md b/node_modules/chokidar/node_modules/glob-parent/CHANGELOG.md new file mode 100644 index 0000000..fb9de96 --- /dev/null +++ b/node_modules/chokidar/node_modules/glob-parent/CHANGELOG.md @@ -0,0 +1,110 @@ +### [5.1.2](https://github.com/gulpjs/glob-parent/compare/v5.1.1...v5.1.2) (2021-03-06) + + +### Bug Fixes + +* eliminate ReDoS ([#36](https://github.com/gulpjs/glob-parent/issues/36)) ([f923116](https://github.com/gulpjs/glob-parent/commit/f9231168b0041fea3f8f954b3cceb56269fc6366)) + +### [5.1.1](https://github.com/gulpjs/glob-parent/compare/v5.1.0...v5.1.1) (2021-01-27) + + +### Bug Fixes + +* unescape exclamation mark ([#26](https://github.com/gulpjs/glob-parent/issues/26)) ([a98874f](https://github.com/gulpjs/glob-parent/commit/a98874f1a59e407f4fb1beb0db4efa8392da60bb)) + +## [5.1.0](https://github.com/gulpjs/glob-parent/compare/v5.0.0...v5.1.0) (2021-01-27) + + +### Features + +* add `flipBackslashes` option to disable auto conversion of slashes (closes [#24](https://github.com/gulpjs/glob-parent/issues/24)) ([#25](https://github.com/gulpjs/glob-parent/issues/25)) ([eecf91d](https://github.com/gulpjs/glob-parent/commit/eecf91d5e3834ed78aee39c4eaaae654d76b87b3)) + +## [5.0.0](https://github.com/gulpjs/glob-parent/compare/v4.0.0...v5.0.0) (2021-01-27) + + +### ⚠ BREAKING CHANGES + +* Drop support for node <6 & bump dependencies + +### Miscellaneous Chores + +* Drop support for node <6 & bump dependencies ([896c0c0](https://github.com/gulpjs/glob-parent/commit/896c0c00b4e7362f60b96e7fc295ae929245255a)) + +## [4.0.0](https://github.com/gulpjs/glob-parent/compare/v3.1.0...v4.0.0) (2021-01-27) + + +### ⚠ BREAKING CHANGES + +* question marks are valid path characters on Windows so avoid flagging as a glob when alone +* Update is-glob dependency + +### Features + +* hoist regexps and strings for performance gains ([4a80667](https://github.com/gulpjs/glob-parent/commit/4a80667c69355c76a572a5892b0f133c8e1f457e)) +* question marks are valid path characters on Windows so avoid flagging as a glob when alone ([2a551dd](https://github.com/gulpjs/glob-parent/commit/2a551dd0dc3235e78bf3c94843d4107072d17841)) +* Update is-glob dependency ([e41fcd8](https://github.com/gulpjs/glob-parent/commit/e41fcd895d1f7bc617dba45c9d935a7949b9c281)) + +## [3.1.0](https://github.com/gulpjs/glob-parent/compare/v3.0.1...v3.1.0) (2021-01-27) + + +### Features + +* allow basic win32 backslash use ([272afa5](https://github.com/gulpjs/glob-parent/commit/272afa5fd070fc0f796386a5993d4ee4a846988b)) +* handle extglobs (parentheses) containing separators ([7db1bdb](https://github.com/gulpjs/glob-parent/commit/7db1bdb0756e55fd14619e8ce31aa31b17b117fd)) +* new approach to braces/brackets handling ([8269bd8](https://github.com/gulpjs/glob-parent/commit/8269bd89290d99fac9395a354fb56fdcdb80f0be)) +* pre-process braces/brackets sections ([9ef8a87](https://github.com/gulpjs/glob-parent/commit/9ef8a87f66b1a43d0591e7a8e4fc5a18415ee388)) +* preserve escaped brace/bracket at end of string ([8cfb0ba](https://github.com/gulpjs/glob-parent/commit/8cfb0ba84202d51571340dcbaf61b79d16a26c76)) + + +### Bug Fixes + +* trailing escaped square brackets ([99ec9fe](https://github.com/gulpjs/glob-parent/commit/99ec9fecc60ee488ded20a94dd4f18b4f55c4ccf)) + +### [3.0.1](https://github.com/gulpjs/glob-parent/compare/v3.0.0...v3.0.1) (2021-01-27) + + +### Features + +* use path-dirname ponyfill ([cdbea5f](https://github.com/gulpjs/glob-parent/commit/cdbea5f32a58a54e001a75ddd7c0fccd4776aacc)) + + +### Bug Fixes + +* unescape glob-escaped dirnames on output ([598c533](https://github.com/gulpjs/glob-parent/commit/598c533bdf49c1428bc063aa9b8db40c5a86b030)) + +## [3.0.0](https://github.com/gulpjs/glob-parent/compare/v2.0.0...v3.0.0) (2021-01-27) + + +### ⚠ BREAKING CHANGES + +* update is-glob dependency + +### Features + +* update is-glob dependency ([5c5f8ef](https://github.com/gulpjs/glob-parent/commit/5c5f8efcee362a8e7638cf8220666acd8784f6bd)) + +## [2.0.0](https://github.com/gulpjs/glob-parent/compare/v1.3.0...v2.0.0) (2021-01-27) + + +### Features + +* move up to dirname regardless of glob characters ([f97fb83](https://github.com/gulpjs/glob-parent/commit/f97fb83be2e0a9fc8d3b760e789d2ecadd6aa0c2)) + +## [1.3.0](https://github.com/gulpjs/glob-parent/compare/v1.2.0...v1.3.0) (2021-01-27) + +## [1.2.0](https://github.com/gulpjs/glob-parent/compare/v1.1.0...v1.2.0) (2021-01-27) + + +### Reverts + +* feat: make regex test strings smaller ([dc80fa9](https://github.com/gulpjs/glob-parent/commit/dc80fa9658dca20549cfeba44bbd37d5246fcce0)) + +## [1.1.0](https://github.com/gulpjs/glob-parent/compare/v1.0.0...v1.1.0) (2021-01-27) + + +### Features + +* make regex test strings smaller ([cd83220](https://github.com/gulpjs/glob-parent/commit/cd832208638f45169f986d80fcf66e401f35d233)) + +## 1.0.0 (2021-01-27) + diff --git a/node_modules/chokidar/node_modules/glob-parent/LICENSE b/node_modules/chokidar/node_modules/glob-parent/LICENSE new file mode 100644 index 0000000..63222d7 --- /dev/null +++ b/node_modules/chokidar/node_modules/glob-parent/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2015, 2019 Elan Shanker + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/chokidar/node_modules/glob-parent/README.md b/node_modules/chokidar/node_modules/glob-parent/README.md new file mode 100644 index 0000000..36a2793 --- /dev/null +++ b/node_modules/chokidar/node_modules/glob-parent/README.md @@ -0,0 +1,137 @@ +
+ +# glob-parent + +[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Azure Pipelines Build Status][azure-pipelines-image]][azure-pipelines-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] + +Extract the non-magic parent path from a glob string. + +## Usage + +```js +var globParent = require('glob-parent'); + +globParent('path/to/*.js'); // 'path/to' +globParent('/root/path/to/*.js'); // '/root/path/to' +globParent('/*.js'); // '/' +globParent('*.js'); // '.' +globParent('**/*.js'); // '.' +globParent('path/{to,from}'); // 'path' +globParent('path/!(to|from)'); // 'path' +globParent('path/?(to|from)'); // 'path' +globParent('path/+(to|from)'); // 'path' +globParent('path/*(to|from)'); // 'path' +globParent('path/@(to|from)'); // 'path' +globParent('path/**/*'); // 'path' + +// if provided a non-glob path, returns the nearest dir +globParent('path/foo/bar.js'); // 'path/foo' +globParent('path/foo/'); // 'path/foo' +globParent('path/foo'); // 'path' (see issue #3 for details) +``` + +## API + +### `globParent(maybeGlobString, [options])` + +Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below. + +#### options + +```js +{ + // Disables the automatic conversion of slashes for Windows + flipBackslashes: true +} +``` + +## Escaping + +The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: + +- `?` (question mark) unless used as a path segment alone +- `*` (asterisk) +- `|` (pipe) +- `(` (opening parenthesis) +- `)` (closing parenthesis) +- `{` (opening curly brace) +- `}` (closing curly brace) +- `[` (opening bracket) +- `]` (closing bracket) + +**Example** + +```js +globParent('foo/[bar]/') // 'foo' +globParent('foo/\\[bar]/') // 'foo/[bar]' +``` + +## Limitations + +### Braces & Brackets +This library attempts a quick and imperfect method of determining which path +parts have glob magic without fully parsing/lexing the pattern. There are some +advanced use cases that can trip it up, such as nested braces where the outer +pair is escaped and the inner one contains a path separator. If you find +yourself in the unlikely circumstance of being affected by this or need to +ensure higher-fidelity glob handling in your library, it is recommended that you +pre-process your input with [expand-braces] and/or [expand-brackets]. + +### Windows +Backslashes are not valid path separators for globs. If a path with backslashes +is provided anyway, for simple cases, glob-parent will replace the path +separator for you and return the non-glob parent path (now with +forward-slashes, which are still valid as Windows path separators). + +This cannot be used in conjunction with escape characters. + +```js +// BAD +globParent('C:\\Program Files \\(x86\\)\\*.ext') // 'C:/Program Files /(x86/)' + +// GOOD +globParent('C:/Program Files\\(x86\\)/*.ext') // 'C:/Program Files (x86)' +``` + +If you are using escape characters for a pattern without path parts (i.e. +relative to `cwd`), prefix with `./` to avoid confusing glob-parent. + +```js +// BAD +globParent('foo \\[bar]') // 'foo ' +globParent('foo \\[bar]*') // 'foo ' + +// GOOD +globParent('./foo \\[bar]') // 'foo [bar]' +globParent('./foo \\[bar]*') // '.' +``` + +## License + +ISC + +[expand-braces]: https://github.com/jonschlinkert/expand-braces +[expand-brackets]: https://github.com/jonschlinkert/expand-brackets + +[downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg +[npm-url]: https://www.npmjs.com/package/glob-parent +[npm-image]: https://img.shields.io/npm/v/glob-parent.svg + +[azure-pipelines-url]: https://dev.azure.com/gulpjs/gulp/_build/latest?definitionId=2&branchName=master +[azure-pipelines-image]: https://dev.azure.com/gulpjs/gulp/_apis/build/status/glob-parent?branchName=master + +[travis-url]: https://travis-ci.org/gulpjs/glob-parent +[travis-image]: https://img.shields.io/travis/gulpjs/glob-parent.svg?label=travis-ci + +[appveyor-url]: https://ci.appveyor.com/project/gulpjs/glob-parent +[appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/glob-parent.svg?label=appveyor + +[coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent +[coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg + +[gitter-url]: https://gitter.im/gulpjs/gulp +[gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg diff --git a/node_modules/chokidar/node_modules/glob-parent/index.js b/node_modules/chokidar/node_modules/glob-parent/index.js new file mode 100644 index 0000000..09e257e --- /dev/null +++ b/node_modules/chokidar/node_modules/glob-parent/index.js @@ -0,0 +1,42 @@ +'use strict'; + +var isGlob = require('is-glob'); +var pathPosixDirname = require('path').posix.dirname; +var isWin32 = require('os').platform() === 'win32'; + +var slash = '/'; +var backslash = /\\/g; +var enclosure = /[\{\[].*[\}\]]$/; +var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; +var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; + +/** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + * @returns {string} + */ +module.exports = function globParent(str, opts) { + var options = Object.assign({ flipBackslashes: true }, opts); + + // flip windows path separators + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { + str = str.replace(backslash, slash); + } + + // special case for strings ending in enclosure containing path separator + if (enclosure.test(str)) { + str += slash; + } + + // preserves full path in case of trailing path separator + str += 'a'; + + // remove path parts that are globby + do { + str = pathPosixDirname(str); + } while (isGlob(str) || globby.test(str)); + + // remove escape chars and return result + return str.replace(escaped, '$1'); +}; diff --git a/node_modules/chokidar/node_modules/glob-parent/package.json b/node_modules/chokidar/node_modules/glob-parent/package.json new file mode 100644 index 0000000..125c971 --- /dev/null +++ b/node_modules/chokidar/node_modules/glob-parent/package.json @@ -0,0 +1,48 @@ +{ + "name": "glob-parent", + "version": "5.1.2", + "description": "Extract the non-magic parent path from a glob string.", + "author": "Gulp Team (https://gulpjs.com/)", + "contributors": [ + "Elan Shanker (https://github.com/es128)", + "Blaine Bublitz " + ], + "repository": "gulpjs/glob-parent", + "license": "ISC", + "engines": { + "node": ">= 6" + }, + "main": "index.js", + "files": [ + "LICENSE", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "pretest": "npm run lint", + "test": "nyc mocha --async-only", + "azure-pipelines": "nyc mocha --async-only --reporter xunit -O output=test.xunit", + "coveralls": "nyc report --reporter=text-lcov | coveralls" + }, + "dependencies": { + "is-glob": "^4.0.1" + }, + "devDependencies": { + "coveralls": "^3.0.11", + "eslint": "^2.13.1", + "eslint-config-gulp": "^3.0.1", + "expect": "^1.20.2", + "mocha": "^6.0.2", + "nyc": "^13.3.0" + }, + "keywords": [ + "glob", + "parent", + "strip", + "path", + "dirname", + "directory", + "base", + "wildcard" + ] +} diff --git a/node_modules/chokidar/package.json b/node_modules/chokidar/package.json new file mode 100644 index 0000000..e8f8b3d --- /dev/null +++ b/node_modules/chokidar/package.json @@ -0,0 +1,70 @@ +{ + "name": "chokidar", + "description": "Minimal and efficient cross-platform file watching library", + "version": "3.6.0", + "homepage": "https://github.com/paulmillr/chokidar", + "author": "Paul Miller (https://paulmillr.com)", + "contributors": [ + "Paul Miller (https://paulmillr.com)", + "Elan Shanker" + ], + "engines": { + "node": ">= 8.10.0" + }, + "main": "index.js", + "types": "./types/index.d.ts", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + }, + "devDependencies": { + "@types/node": "^14", + "chai": "^4.3", + "dtslint": "^3.3.0", + "eslint": "^7.0.0", + "mocha": "^7.0.0", + "rimraf": "^3.0.0", + "sinon": "^9.0.1", + "sinon-chai": "^3.3.0", + "typescript": "^4.4.3", + "upath": "^1.2.0" + }, + "files": [ + "index.js", + "lib/*.js", + "types/index.d.ts" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/paulmillr/chokidar.git" + }, + "bugs": { + "url": "https://github.com/paulmillr/chokidar/issues" + }, + "license": "MIT", + "scripts": { + "dtslint": "dtslint types", + "lint": "eslint --report-unused-disable-directives --ignore-path .gitignore .", + "build": "npm ls", + "mocha": "mocha --exit --timeout 90000", + "test": "npm run lint && npm run mocha" + }, + "keywords": [ + "fs", + "watch", + "watchFile", + "watcher", + "watching", + "file", + "fsevents" + ], + "funding": "https://paulmillr.com/funding/" +} diff --git a/node_modules/chokidar/types/index.d.ts b/node_modules/chokidar/types/index.d.ts new file mode 100644 index 0000000..4558066 --- /dev/null +++ b/node_modules/chokidar/types/index.d.ts @@ -0,0 +1,192 @@ +// TypeScript Version: 3.0 + +/// + +import * as fs from "fs"; +import { EventEmitter } from "events"; +import { Matcher } from 'anymatch'; + +export class FSWatcher extends EventEmitter implements fs.FSWatcher { + options: WatchOptions; + + /** + * Constructs a new FSWatcher instance with optional WatchOptions parameter. + */ + constructor(options?: WatchOptions); + + /** + * Add files, directories, or glob patterns for tracking. Takes an array of strings or just one + * string. + */ + add(paths: string | ReadonlyArray): this; + + /** + * Stop watching files, directories, or glob patterns. Takes an array of strings or just one + * string. + */ + unwatch(paths: string | ReadonlyArray): this; + + /** + * Returns an object representing all the paths on the file system being watched by this + * `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless + * the `cwd` option was used), and the values are arrays of the names of the items contained in + * each directory. + */ + getWatched(): { + [directory: string]: string[]; + }; + + /** + * Removes all listeners from watched files. + */ + close(): Promise; + + on(event: 'add'|'addDir'|'change', listener: (path: string, stats?: fs.Stats) => void): this; + + on(event: 'all', listener: (eventName: 'add'|'addDir'|'change'|'unlink'|'unlinkDir', path: string, stats?: fs.Stats) => void): this; + + /** + * Error occurred + */ + on(event: 'error', listener: (error: Error) => void): this; + + /** + * Exposes the native Node `fs.FSWatcher events` + */ + on(event: 'raw', listener: (eventName: string, path: string, details: any) => void): this; + + /** + * Fires when the initial scan is complete + */ + on(event: 'ready', listener: () => void): this; + + on(event: 'unlink'|'unlinkDir', listener: (path: string) => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + + ref(): this; + + unref(): this; +} + +export interface WatchOptions { + /** + * Indicates whether the process should continue to run as long as files are being watched. If + * set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`, + * even if the process continues to run. + */ + persistent?: boolean; + + /** + * ([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to + * be ignored. The whole relative or absolute path is tested, not just filename. If a function + * with two arguments is provided, it gets called twice per path - once with a single argument + * (the path), second time with two arguments (the path and the + * [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path). + */ + ignored?: Matcher; + + /** + * If set to `false` then `add`/`addDir` events are also emitted for matching paths while + * instantiating the watching as chokidar discovers these file paths (before the `ready` event). + */ + ignoreInitial?: boolean; + + /** + * When `false`, only the symlinks themselves will be watched for changes instead of following + * the link references and bubbling events through the link's path. + */ + followSymlinks?: boolean; + + /** + * The base directory from which watch `paths` are to be derived. Paths emitted with events will + * be relative to this. + */ + cwd?: string; + + /** + * If set to true then the strings passed to .watch() and .add() are treated as literal path + * names, even if they look like globs. Default: false. + */ + disableGlobbing?: boolean; + + /** + * Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU + * utilization, consider setting this to `false`. It is typically necessary to **set this to + * `true` to successfully watch files over a network**, and it may be necessary to successfully + * watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides + * the `useFsEvents` default. + */ + usePolling?: boolean; + + /** + * Whether to use the `fsevents` watching interface if available. When set to `true` explicitly + * and `fsevents` is available this supercedes the `usePolling` setting. When set to `false` on + * OS X, `usePolling: true` becomes the default. + */ + useFsEvents?: boolean; + + /** + * If relying upon the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that + * may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is + * provided even in cases where it wasn't already available from the underlying watch events. + */ + alwaysStat?: boolean; + + /** + * If set, limits how many levels of subdirectories will be traversed. + */ + depth?: number; + + /** + * Interval of file system polling. + */ + interval?: number; + + /** + * Interval of file system polling for binary files. ([see list of binary extensions](https://gi + * thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json)) + */ + binaryInterval?: number; + + /** + * Indicates whether to watch files that don't have read permissions if possible. If watching + * fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed + * silently. + */ + ignorePermissionErrors?: boolean; + + /** + * `true` if `useFsEvents` and `usePolling` are `false`). Automatically filters out artifacts + * that occur when using editors that use "atomic writes" instead of writing directly to the + * source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change` + * event rather than `unlink` then `add`. If the default of 100 ms does not work well for you, + * you can override it by setting `atomic` to a custom value, in milliseconds. + */ + atomic?: boolean | number; + + /** + * can be set to an object in order to adjust timing params: + */ + awaitWriteFinish?: AwaitWriteFinishOptions | boolean; +} + +export interface AwaitWriteFinishOptions { + /** + * Amount of time in milliseconds for a file size to remain constant before emitting its event. + */ + stabilityThreshold?: number; + + /** + * File size polling interval. + */ + pollInterval?: number; +} + +/** + * produces an instance of `FSWatcher`. + */ +export function watch( + paths: string | ReadonlyArray, + options?: WatchOptions +): FSWatcher; diff --git a/node_modules/commander/CHANGELOG.md b/node_modules/commander/CHANGELOG.md new file mode 100644 index 0000000..f00cb2b --- /dev/null +++ b/node_modules/commander/CHANGELOG.md @@ -0,0 +1,436 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). (Format adopted after v3.0.0.) + + + +## [4.1.1] (2020-02-02) + +### Fixed + +* TypeScript definition for `.action()` should include Promise for async ([#1157]) + +## [4.1.0] (2020-01-06) + +### Added + +* two routines to change how option values are handled, and eliminate name clashes with command properties ([#933] [#1102]) + * see storeOptionsAsProperties and passCommandToAction in README +* `.parseAsync` to use instead of `.parse` if supply async action handlers ([#806] [#1118]) + +### Fixed + +* Remove trailing blanks from wrapped help text ([#1096]) + +### Changed + +* update dependencies +* extend security coverage for Commander 2.x to 2020-02-03 +* improvements to README +* improvements to TypeScript definition documentation +* move old versions out of main CHANGELOG +* removed explicit use of `ts-node` in tests + +## [4.0.1] (2019-11-12) + +### Fixed + +* display help when requested, even if there are missing required options ([#1091]) + +## [4.0.0] (2019-11-02) + +### Added + +* automatically wrap and indent help descriptions for options and commands ([#1051]) +* `.exitOverride()` allows override of calls to `process.exit` for additional error handling and to keep program running ([#1040]) +* support for declaring required options with `.requiredOptions()` ([#1071]) +* GitHub Actions support ([#1027]) +* translation links in README + +### Changed + +* dev: switch tests from Sinon+Should to Jest with major rewrite of tests ([#1035]) +* call default subcommand even when there are unknown options ([#1047]) +* *Breaking* Commander is only officially supported on Node 8 and above, and requires Node 6 ([#1053]) + +### Fixed + +* *Breaking* keep command object out of program.args when action handler called ([#1048]) + * also, action handler now passed array of unknown arguments +* complain about unknown options when program argument supplied and action handler ([#1049]) + * this changes parameters to `command:*` event to include unknown arguments +* removed deprecated `customFds` option from call to `child_process.spawn` ([#1052]) +* rework TypeScript declarations to bring all types into imported namespace ([#1081]) + +### Migration Tips + +#### Testing for no arguments + +If you were previously using code like: + +```js +if (!program.args.length) ... +``` + +a partial replacement is: + +```js +if (program.rawArgs.length < 3) ... +``` + +## [4.0.0-1] Prerelease (2019-10-08) + +(Released in 4.0.0) + +## [4.0.0-0] Prerelease (2019-10-01) + +(Released in 4.0.0) + +## [2.20.1] (2019-09-29) + +### Fixed + +* Improve tracking of executable subcommands. + +### Changed + +* update development dependencies + +## [3.0.2] (2019-09-27) + +### Fixed + +* Improve tracking of executable subcommands. + +### Changed + +* update development dependencies + +## [3.0.1] (2019-08-30) + +### Added + +* .name and .usage to README ([#1010]) +* Table of Contents to README ([#1010]) +* TypeScript definition for `executableFile` in CommandOptions ([#1028]) + +### Changed + +* consistently use `const` rather than `var` in README ([#1026]) + +### Fixed + +* help for sub commands with custom executableFile ([#1018]) + +## [3.0.0] / 2019-08-08 + +* Add option to specify executable file name ([#999]) + * e.g. `.command('clone', 'clone description', { executableFile: 'myClone' })` +* Change docs for `.command` to contrast action handler vs git-style executable. ([#938] [#990]) +* **Breaking** Change TypeScript to use overloaded function for `.command`. ([#938] [#990]) +* Change to use straight quotes around strings in error messages (like 'this' instead of `this') ([#915]) +* Add TypeScript "reference types" for node ([#974]) +* Add support for hyphen as an option argument in subcommands ([#697]) +* Add support for a short option flag and its value to be concatenated for action handler subcommands ([#599]) + * e.g. `-p 80` can also be supplied as `-p80` +* Add executable arguments to spawn in win32, for git-style executables ([#611]) + * e.g. `node --harmony myCommand.js clone` +* Add parent command as prefix of subcommand in help ([#980]) +* Add optional custom description to `.version` ([#963]) + * e.g. `program.version('0.0.1', '-v, --vers', 'output the current version')` +* Add `.helpOption(flags, description)` routine to customise help flags and description ([#963]) + * e.g. `.helpOption('-e, --HELP', 'read more information')` +* Fix behavior of --no-* options ([#795]) + * can now define both `--foo` and `--no-foo` + * **Breaking** custom event listeners: `--no-foo` on cli now emits `option:no-foo` (previously `option:foo`) + * **Breaking** default value: defining `--no-foo` after defining `--foo` leaves the default value unchanged (previously set it to false) + * allow boolean default value, such as from environment ([#987]) +* Increment inspector port for spawned subcommands ([#991]) + * e.g. `node --inspect myCommand.js clone` + +### Migration Tips + +The custom event for a negated option like `--no-foo` is `option:no-foo` (previously `option:foo`). + +```js +program + .option('--no-foo') + .on('option:no-foo', () => { + console.log('removing foo'); + }); +``` + +When using TypeScript, adding a command does not allow an explicit `undefined` for an unwanted executable description (e.g +for a command with an action handler). + +```js +program + .command('action1', undefined, { noHelp: true }) // No longer valid + .command('action2', { noHelp: true }) // Correct +``` + +## 3.0.0-0 Prerelease / 2019-07-28 + +(Released as 3.0.0) + +## 2.20.0 / 2019-04-02 + +* fix: resolve symbolic links completely when hunting for subcommands (#935) +* Update index.d.ts (#930) +* Update Readme.md (#924) +* Remove --save option as it isn't required anymore (#918) +* Add link to the license file (#900) +* Added example of receiving args from options (#858) +* Added missing semicolon (#882) +* Add extension to .eslintrc (#876) + +## 2.19.0 / 2018-10-02 + +* Removed newline after Options and Commands headers (#864) +* Bugfix - Error output (#862) +* Fix to change default value to string (#856) + +## 2.18.0 / 2018-09-07 + +* Standardize help output (#853) +* chmod 644 travis.yml (#851) +* add support for execute typescript subcommand via ts-node (#849) + +## 2.17.1 / 2018-08-07 + +* Fix bug in command emit (#844) + +## 2.17.0 / 2018-08-03 + +* fixed newline output after help information (#833) +* Fix to emit the action even without command (#778) +* npm update (#823) + +## 2.16.0 / 2018-06-29 + +* Remove Makefile and `test/run` (#821) +* Make 'npm test' run on Windows (#820) +* Add badge to display install size (#807) +* chore: cache node_modules (#814) +* chore: remove Node.js 4 (EOL), add Node.js 10 (#813) +* fixed typo in readme (#812) +* Fix types (#804) +* Update eslint to resolve vulnerabilities in lodash (#799) +* updated readme with custom event listeners. (#791) +* fix tests (#794) + +## 2.15.0 / 2018-03-07 + +* Update downloads badge to point to graph of downloads over time instead of duplicating link to npm +* Arguments description + +## 2.14.1 / 2018-02-07 + +* Fix typing of help function + +## 2.14.0 / 2018-02-05 + +* only register the option:version event once +* Fixes issue #727: Passing empty string for option on command is set to undefined +* enable eqeqeq rule +* resolves #754 add linter configuration to project +* resolves #560 respect custom name for version option +* document how to override the version flag +* document using options per command + +## 2.13.0 / 2018-01-09 + +* Do not print default for --no- +* remove trailing spaces in command help +* Update CI's Node.js to LTS and latest version +* typedefs: Command and Option types added to commander namespace + +## 2.12.2 / 2017-11-28 + +* fix: typings are not shipped + +## 2.12.1 / 2017-11-23 + +* Move @types/node to dev dependency + +## 2.12.0 / 2017-11-22 + +* add attributeName() method to Option objects +* Documentation updated for options with --no prefix +* typings: `outputHelp` takes a string as the first parameter +* typings: use overloads +* feat(typings): update to match js api +* Print default value in option help +* Fix translation error +* Fail when using same command and alias (#491) +* feat(typings): add help callback +* fix bug when description is add after command with options (#662) +* Format js code +* Rename History.md to CHANGELOG.md (#668) +* feat(typings): add typings to support TypeScript (#646) +* use current node + +## 2.11.0 / 2017-07-03 + +* Fix help section order and padding (#652) +* feature: support for signals to subcommands (#632) +* Fixed #37, --help should not display first (#447) +* Fix translation errors. (#570) +* Add package-lock.json +* Remove engines +* Upgrade package version +* Prefix events to prevent conflicts between commands and options (#494) +* Removing dependency on graceful-readlink +* Support setting name in #name function and make it chainable +* Add .vscode directory to .gitignore (Visual Studio Code metadata) +* Updated link to ruby commander in readme files + +## 2.10.0 / 2017-06-19 + +* Update .travis.yml. drop support for older node.js versions. +* Fix require arguments in README.md +* On SemVer you do not start from 0.0.1 +* Add missing semi colon in readme +* Add save param to npm install +* node v6 travis test +* Update Readme_zh-CN.md +* Allow literal '--' to be passed-through as an argument +* Test subcommand alias help +* link build badge to master branch +* Support the alias of Git style sub-command +* added keyword commander for better search result on npm +* Fix Sub-Subcommands +* test node.js stable +* Fixes TypeError when a command has an option called `--description` +* Update README.md to make it beginner friendly and elaborate on the difference between angled and square brackets. +* Add chinese Readme file + +## 2.9.0 / 2015-10-13 + +* Add option `isDefault` to set default subcommand #415 @Qix- +* Add callback to allow filtering or post-processing of help text #434 @djulien +* Fix `undefined` text in help information close #414 #416 @zhiyelee + +## 2.8.1 / 2015-04-22 + +* Back out `support multiline description` Close #396 #397 + +## 2.8.0 / 2015-04-07 + +* Add `process.execArg` support, execution args like `--harmony` will be passed to sub-commands #387 @DigitalIO @zhiyelee +* Fix bug in Git-style sub-commands #372 @zhiyelee +* Allow commands to be hidden from help #383 @tonylukasavage +* When git-style sub-commands are in use, yet none are called, display help #382 @claylo +* Add ability to specify arguments syntax for top-level command #258 @rrthomas +* Support multiline descriptions #208 @zxqfox + +## 2.7.1 / 2015-03-11 + +* Revert #347 (fix collisions when option and first arg have same name) which causes a bug in #367. + +## 2.7.0 / 2015-03-09 + +* Fix git-style bug when installed globally. Close #335 #349 @zhiyelee +* Fix collisions when option and first arg have same name. Close #346 #347 @tonylukasavage +* Add support for camelCase on `opts()`. Close #353 @nkzawa +* Add node.js 0.12 and io.js to travis.yml +* Allow RegEx options. #337 @palanik +* Fixes exit code when sub-command failing. Close #260 #332 @pirelenito +* git-style `bin` files in $PATH make sense. Close #196 #327 @zhiyelee + +## 2.6.0 / 2014-12-30 + +* added `Command#allowUnknownOption` method. Close #138 #318 @doozr @zhiyelee +* Add application description to the help msg. Close #112 @dalssoft + +## 2.5.1 / 2014-12-15 + +* fixed two bugs incurred by variadic arguments. Close #291 @Quentin01 #302 @zhiyelee + +## 2.5.0 / 2014-10-24 + +* add support for variadic arguments. Closes #277 @whitlockjc + +## 2.4.0 / 2014-10-17 + +* fixed a bug on executing the coercion function of subcommands option. Closes #270 +* added `Command.prototype.name` to retrieve command name. Closes #264 #266 @tonylukasavage +* added `Command.prototype.opts` to retrieve all the options as a simple object of key-value pairs. Closes #262 @tonylukasavage +* fixed a bug on subcommand name. Closes #248 @jonathandelgado +* fixed function normalize doesn’t honor option terminator. Closes #216 @abbr + +## 2.3.0 / 2014-07-16 + +* add command alias'. Closes PR #210 +* fix: Typos. Closes #99 +* fix: Unused fs module. Closes #217 + +## 2.2.0 / 2014-03-29 + +* add passing of previous option value +* fix: support subcommands on windows. Closes #142 +* Now the defaultValue passed as the second argument of the coercion function. + +## 2.1.0 / 2013-11-21 + +* add: allow cflag style option params, unit test, fixes #174 + +## 2.0.0 / 2013-07-18 + +* remove input methods (.prompt, .confirm, etc) + +## Older versions + +* [1.x](./changelogs/CHANGELOG-1.md) +* [0.x](./changelogs/CHANGELOG-0.md) + +[#599]: https://github.com/tj/commander.js/issues/599 +[#611]: https://github.com/tj/commander.js/issues/611 +[#697]: https://github.com/tj/commander.js/issues/697 +[#795]: https://github.com/tj/commander.js/issues/795 +[#806]: https://github.com/tj/commander.js/issues/806 +[#915]: https://github.com/tj/commander.js/issues/915 +[#938]: https://github.com/tj/commander.js/issues/938 +[#963]: https://github.com/tj/commander.js/issues/963 +[#974]: https://github.com/tj/commander.js/issues/974 +[#980]: https://github.com/tj/commander.js/issues/980 +[#987]: https://github.com/tj/commander.js/issues/987 +[#990]: https://github.com/tj/commander.js/issues/990 +[#991]: https://github.com/tj/commander.js/issues/991 +[#993]: https://github.com/tj/commander.js/issues/993 +[#999]: https://github.com/tj/commander.js/issues/999 +[#1010]: https://github.com/tj/commander.js/pull/1010 +[#1018]: https://github.com/tj/commander.js/pull/1018 +[#1026]: https://github.com/tj/commander.js/pull/1026 +[#1027]: https://github.com/tj/commander.js/pull/1027 +[#1028]: https://github.com/tj/commander.js/pull/1028 +[#1035]: https://github.com/tj/commander.js/pull/1035 +[#1040]: https://github.com/tj/commander.js/pull/1040 +[#1047]: https://github.com/tj/commander.js/pull/1047 +[#1048]: https://github.com/tj/commander.js/pull/1048 +[#1049]: https://github.com/tj/commander.js/pull/1049 +[#1051]: https://github.com/tj/commander.js/pull/1051 +[#1052]: https://github.com/tj/commander.js/pull/1052 +[#1053]: https://github.com/tj/commander.js/pull/1053 +[#1071]: https://github.com/tj/commander.js/pull/1071 +[#1081]: https://github.com/tj/commander.js/pull/1081 +[#1091]: https://github.com/tj/commander.js/pull/1091 +[#1096]: https://github.com/tj/commander.js/pull/1096 +[#1102]: https://github.com/tj/commander.js/pull/1102 +[#1118]: https://github.com/tj/commander.js/pull/1118 +[#1157]: https://github.com/tj/commander.js/pull/1157 + +[Unreleased]: https://github.com/tj/commander.js/compare/master...develop +[4.1.1]: https://github.com/tj/commander.js/compare/v4.0.0..v4.1.1 +[4.1.0]: https://github.com/tj/commander.js/compare/v4.0.1..v4.1.0 +[4.0.1]: https://github.com/tj/commander.js/compare/v4.0.0..v4.0.1 +[4.0.0]: https://github.com/tj/commander.js/compare/v3.0.2..v4.0.0 +[4.0.0-1]: https://github.com/tj/commander.js/compare/v4.0.0-0..v4.0.0-1 +[4.0.0-0]: https://github.com/tj/commander.js/compare/v3.0.2...v4.0.0-0 +[3.0.2]: https://github.com/tj/commander.js/compare/v3.0.1...v3.0.2 +[3.0.1]: https://github.com/tj/commander.js/compare/v3.0.0...v3.0.1 +[3.0.0]: https://github.com/tj/commander.js/compare/v2.20.1...v3.0.0 +[2.20.1]: https://github.com/tj/commander.js/compare/v2.20.0...v2.20.1 diff --git a/node_modules/commander/LICENSE b/node_modules/commander/LICENSE new file mode 100644 index 0000000..10f997a --- /dev/null +++ b/node_modules/commander/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2011 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/commander/Readme.md b/node_modules/commander/Readme.md new file mode 100644 index 0000000..aa4f42b --- /dev/null +++ b/node_modules/commander/Readme.md @@ -0,0 +1,713 @@ +# Commander.js + +[![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](http://travis-ci.org/tj/commander.js) +[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander) +[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true) +[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander) + +The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander). + +Read this in other languages: English | [简体中文](./Readme_zh-CN.md) + +- [Commander.js](#commanderjs) + - [Installation](#installation) + - [Declaring program variable](#declaring-program-variable) + - [Options](#options) + - [Common option types, boolean and value](#common-option-types-boolean-and-value) + - [Default option value](#default-option-value) + - [Other option types, negatable boolean and flag|value](#other-option-types-negatable-boolean-and-flagvalue) + - [Custom option processing](#custom-option-processing) + - [Required option](#required-option) + - [Version option](#version-option) + - [Commands](#commands) + - [Specify the argument syntax](#specify-the-argument-syntax) + - [Action handler (sub)commands](#action-handler-subcommands) + - [Git-style executable (sub)commands](#git-style-executable-subcommands) + - [Automated --help](#automated---help) + - [Custom help](#custom-help) + - [.usage and .name](#usage-and-name) + - [.outputHelp(cb)](#outputhelpcb) + - [.helpOption(flags, description)](#helpoptionflags-description) + - [.help(cb)](#helpcb) + - [Custom event listeners](#custom-event-listeners) + - [Bits and pieces](#bits-and-pieces) + - [Avoiding option name clashes](#avoiding-option-name-clashes) + - [TypeScript](#typescript) + - [Node options such as --harmony](#node-options-such-as---harmony) + - [Node debugging](#node-debugging) + - [Override exit handling](#override-exit-handling) + - [Examples](#examples) + - [License](#license) + - [Support](#support) + - [Commander for enterprise](#commander-for-enterprise) + +## Installation + +```bash +npm install commander +``` + +## Declaring _program_ variable + +Commander exports a global object which is convenient for quick programs. +This is used in the examples in this README for brevity. + +```js +const program = require('commander'); +program.version('0.0.1'); +``` + +For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use. + + ```js + const commander = require('commander'); + const program = new commander.Command(); + program.version('0.0.1'); + ``` + +## Options + +Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space. + +The options can be accessed as properties on the Command object. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. Multiple short flags may be combined as a single arg, for example `-abc` is equivalent to `-a -b -c`. + +See also optional new behaviour to [avoid name clashes](#avoiding-option-name-clashes). + +### Common option types, boolean and value + +The two most used option types are a boolean flag, and an option which takes a value (declared using angle brackets). Both are `undefined` unless specified on command line. + +```js +const program = require('commander'); + +program + .option('-d, --debug', 'output extra debugging') + .option('-s, --small', 'small pizza size') + .option('-p, --pizza-type ', 'flavour of pizza'); + +program.parse(process.argv); + +if (program.debug) console.log(program.opts()); +console.log('pizza details:'); +if (program.small) console.log('- small pizza size'); +if (program.pizzaType) console.log(`- ${program.pizzaType}`); +``` + +```bash +$ pizza-options -d +{ debug: true, small: undefined, pizzaType: undefined } +pizza details: +$ pizza-options -p +error: option '-p, --pizza-type ' argument missing +$ pizza-options -ds -p vegetarian +{ debug: true, small: true, pizzaType: 'vegetarian' } +pizza details: +- small pizza size +- vegetarian +$ pizza-options --pizza-type=cheese +pizza details: +- cheese +``` + +`program.parse(arguments)` processes the arguments, leaving any args not consumed by the options as the `program.args` array. + +### Default option value + +You can specify a default value for an option which takes a value. + +```js +const program = require('commander'); + +program + .option('-c, --cheese ', 'add the specified type of cheese', 'blue'); + +program.parse(process.argv); + +console.log(`cheese: ${program.cheese}`); +``` + +```bash +$ pizza-options +cheese: blue +$ pizza-options --cheese stilton +cheese: stilton +``` + +### Other option types, negatable boolean and flag|value + +You can specify a boolean option long name with a leading `no-` to set the option value to false when used. +Defined alone this also makes the option true by default. + +If you define `--foo` first, adding `--no-foo` does not change the default value from what it would +otherwise be. You can specify a default boolean value for a boolean flag and it can be overridden on command line. + +```js +const program = require('commander'); + +program + .option('--no-sauce', 'Remove sauce') + .option('--cheese ', 'cheese flavour', 'mozzarella') + .option('--no-cheese', 'plain with no cheese') + .parse(process.argv); + +const sauceStr = program.sauce ? 'sauce' : 'no sauce'; +const cheeseStr = (program.cheese === false) ? 'no cheese' : `${program.cheese} cheese`; +console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`); +``` + +```bash +$ pizza-options +You ordered a pizza with sauce and mozzarella cheese +$ pizza-options --sauce +error: unknown option '--sauce' +$ pizza-options --cheese=blue +You ordered a pizza with sauce and blue cheese +$ pizza-options --no-sauce --no-cheese +You ordered a pizza with no sauce and no cheese +``` + +You can specify an option which functions as a flag but may also take a value (declared using square brackets). + +```js +const program = require('commander'); + +program + .option('-c, --cheese [type]', 'Add cheese with optional type'); + +program.parse(process.argv); + +if (program.cheese === undefined) console.log('no cheese'); +else if (program.cheese === true) console.log('add cheese'); +else console.log(`add cheese type ${program.cheese}`); +``` + +```bash +$ pizza-options +no cheese +$ pizza-options --cheese +add cheese +$ pizza-options --cheese mozzarella +add cheese type mozzarella +``` + +### Custom option processing + +You may specify a function to do custom processing of option values. The callback function receives two parameters, the user specified value and the +previous value for the option. It returns the new value for the option. + +This allows you to coerce the option value to the desired type, or accumulate values, or do entirely custom processing. + +You can optionally specify the default/starting value for the option after the function. + +```js +const program = require('commander'); + +function myParseInt(value, dummyPrevious) { + // parseInt takes a string and an optional radix + return parseInt(value); +} + +function increaseVerbosity(dummyValue, previous) { + return previous + 1; +} + +function collect(value, previous) { + return previous.concat([value]); +} + +function commaSeparatedList(value, dummyPrevious) { + return value.split(','); +} + +program + .option('-f, --float ', 'float argument', parseFloat) + .option('-i, --integer ', 'integer argument', myParseInt) + .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0) + .option('-c, --collect ', 'repeatable value', collect, []) + .option('-l, --list ', 'comma separated list', commaSeparatedList) +; + +program.parse(process.argv); + +if (program.float !== undefined) console.log(`float: ${program.float}`); +if (program.integer !== undefined) console.log(`integer: ${program.integer}`); +if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`); +if (program.collect.length > 0) console.log(program.collect); +if (program.list !== undefined) console.log(program.list); +``` + +```bash +$ custom -f 1e2 +float: 100 +$ custom --integer 2 +integer: 2 +$ custom -v -v -v +verbose: 3 +$ custom -c a -c b -c c +[ 'a', 'b', 'c' ] +$ custom --list x,y,z +[ 'x', 'y', 'z' ] +``` + +### Required option + +You may specify a required (mandatory) option using `.requiredOption`. The option must be specified on the command line, or by having a default value. The method is otherwise the same as `.option` in format, taking flags and description, and optional default value or custom processing. + +```js +const program = require('commander'); + +program + .requiredOption('-c, --cheese ', 'pizza must have cheese'); + +program.parse(process.argv); +``` + +``` +$ pizza +error: required option '-c, --cheese ' not specified +``` + +### Version option + +The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits. + +```js +program.version('0.0.1'); +``` + +```bash +$ ./examples/pizza -V +0.0.1 +``` + +You may change the flags and description by passing additional parameters to the `version` method, using +the same syntax for flags as the `option` method. The version flags can be named anything, but a long name is required. + +```js +program.version('0.0.1', '-v, --vers', 'output the current version'); +``` + +## Commands + +You can specify (sub)commands for your top-level command using `.command`. There are two ways these can be implemented: using an action handler attached to the command, or as a separate executable file (described in more detail later). In the first parameter to `.command` you specify the command name and any command arguments. The arguments may be `` or `[optional]`, and the last argument may also be `variadic...`. + +For example: + +```js +// Command implemented using action handler (description is supplied separately to `.command`) +// Returns new command for configuring. +program + .command('clone [destination]') + .description('clone a repository into a newly created directory') + .action((source, destination) => { + console.log('clone command called'); + }); + +// Command implemented using separate executable file (description is second parameter to `.command`) +// Returns top-level command for adding more commands. +program + .command('start ', 'start named service') + .command('stop [service]', 'stop named service, or all if no name supplied'); +``` + +### Specify the argument syntax + +You use `.arguments` to specify the arguments for the top-level command, and for subcommands they are included in the `.command` call. Angled brackets (e.g. ``) indicate required input. Square brackets (e.g. `[optional]`) indicate optional input. + +```js +const program = require('commander'); + +program + .version('0.1.0') + .arguments(' [env]') + .action(function (cmd, env) { + cmdValue = cmd; + envValue = env; + }); + +program.parse(process.argv); + +if (typeof cmdValue === 'undefined') { + console.error('no command given!'); + process.exit(1); +} +console.log('command:', cmdValue); +console.log('environment:', envValue || "no environment given"); +``` + + The last argument of a command can be variadic, and only the last argument. To make an argument variadic you + append `...` to the argument name. For example: + +```js +const program = require('commander'); + +program + .version('0.1.0') + .command('rmdir [otherDirs...]') + .action(function (dir, otherDirs) { + console.log('rmdir %s', dir); + if (otherDirs) { + otherDirs.forEach(function (oDir) { + console.log('rmdir %s', oDir); + }); + } + }); + +program.parse(process.argv); +``` + +The variadic argument is passed to the action handler as an array. (And this also applies to `program.args`.) + +### Action handler (sub)commands + +You can add options to a command that uses an action handler. +The action handler gets passed a parameter for each argument you declared, and one additional argument which is the +command object itself. This command argument has the values for the command-specific options added as properties. + +```js +const program = require('commander'); + +program + .command('rm ') + .option('-r, --recursive', 'Remove recursively') + .action(function (dir, cmdObj) { + console.log('remove ' + dir + (cmdObj.recursive ? ' recursively' : '')) + }) + +program.parse(process.argv) +``` + +You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`. + +```js +async function run() { /* code goes here */ } + +async function main() { + program + .command('run') + .action(run); + await program.parseAsync(process.argv); +} +``` + +A command's options on the command line are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated. + +Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output. + +### Git-style executable (sub)commands + +When `.command()` is invoked with a description argument, this tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools. +Commander will search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-subcommand`, like `pm-install`, `pm-search`. +You can specify a custom name with the `executableFile` configuration option. + +You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level. + +```js +// file: ./examples/pm +const program = require('commander'); + +program + .version('0.1.0') + .command('install [name]', 'install one or more packages') + .command('search [query]', 'search with optional query') + .command('update', 'update installed packages', {executableFile: 'myUpdateSubCommand'}) + .command('list', 'list packages installed', {isDefault: true}) + .parse(process.argv); +``` + +Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified. +Specifying a name with `executableFile` will override the default constructed name. + +If the program is designed to be installed globally, make sure the executables have proper modes, like `755`. + +## Automated --help + + The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free: + +```bash +$ ./examples/pizza --help +Usage: pizza [options] + +An application for pizzas ordering + +Options: + -V, --version output the version number + -p, --peppers Add peppers + -P, --pineapple Add pineapple + -b, --bbq Add bbq sauce + -c, --cheese Add the specified type of cheese (default: "marble") + -C, --no-cheese You do not want any cheese + -h, --help output usage information +``` + +### Custom help + + You can display arbitrary `-h, --help` information + by listening for "--help". Commander will automatically + exit once you are done so that the remainder of your program + does not execute causing undesired behaviors, for example + in the following executable "stuff" will not output when + `--help` is used. + +```js +#!/usr/bin/env node + +const program = require('commander'); + +program + .version('0.1.0') + .option('-f, --foo', 'enable some foo') + .option('-b, --bar', 'enable some bar') + .option('-B, --baz', 'enable some baz'); + +// must be before .parse() since +// node's emit() is immediate + +program.on('--help', function(){ + console.log('') + console.log('Examples:'); + console.log(' $ custom-help --help'); + console.log(' $ custom-help -h'); +}); + +program.parse(process.argv); + +console.log('stuff'); +``` + +Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run: + +```Text +Usage: custom-help [options] + +Options: + -h, --help output usage information + -V, --version output the version number + -f, --foo enable some foo + -b, --bar enable some bar + -B, --baz enable some baz + +Examples: + $ custom-help --help + $ custom-help -h +``` + +### .usage and .name + +These allow you to customise the usage description in the first line of the help. The name is otherwise +deduced from the (full) program arguments. Given: + +```js +program + .name("my-command") + .usage("[global options] command") +``` + +The help will start with: + +```Text +Usage: my-command [global options] command +``` + +### .outputHelp(cb) + +Output help information without exiting. +Optional callback cb allows post-processing of help text before it is displayed. + +If you want to display help by default (e.g. if no command was provided), you can use something like: + +```js +const program = require('commander'); +const colors = require('colors'); + +program + .version('0.1.0') + .command('getstream [url]', 'get stream URL') + .parse(process.argv); + +if (!process.argv.slice(2).length) { + program.outputHelp(make_red); +} + +function make_red(txt) { + return colors.red(txt); //display the help text in red on the console +} +``` + +### .helpOption(flags, description) + + Override the default help flags and description. + +```js +program + .helpOption('-e, --HELP', 'read more information'); +``` + +### .help(cb) + + Output help information and exit immediately. + Optional callback cb allows post-processing of help text before it is displayed. + +## Custom event listeners + + You can execute custom actions by listening to command and option events. + +```js +program.on('option:verbose', function () { + process.env.VERBOSE = this.verbose; +}); + +// error on unknown commands +program.on('command:*', function () { + console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args.join(' ')); + process.exit(1); +}); +``` + +## Bits and pieces + +### Avoiding option name clashes + +The original and default behaviour is that the option values are stored +as properties on the program, and the action handler is passed a +command object with the options values stored as properties. +This is very convenient to code, but the downside is possible clashes with +existing properties of Command. + +There are two new routines to change the behaviour, and the default behaviour may change in the future: + +- `storeOptionsAsProperties`: whether to store option values as properties on command object, or store separately (specify false) and access using `.opts()` +- `passCommandToAction`: whether to pass command to action handler, +or just the options (specify false) + +```js +// file: ./examples/storeOptionsAsProperties.action.js +program + .storeOptionsAsProperties(false) + .passCommandToAction(false); + +program + .name('my-program-name') + .option('-n,--name '); + +program + .command('show') + .option('-a,--action ') + .action((options) => { + console.log(options.action); + }); + +program.parse(process.argv); + +const programOptions = program.opts(); +console.log(programOptions.name); +``` + +### TypeScript + +The Commander package includes its TypeScript Definition file, but also requires the node types which you need to install yourself. e.g. + +```bash +npm install commander +npm install --save-dev @types/node +``` + +If you use `ts-node` and git-style sub-commands written as `.ts` files, you need to call your program through node to get the sub-commands called correctly. e.g. + +```bash +node -r ts-node/register pm.ts +``` + +### Node options such as `--harmony` + +You can enable `--harmony` option in two ways: + +- Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. (Note Windows does not support this pattern.) +- Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process. + +### Node debugging + +If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) git-style executable (sub)commands using `node --inspect` et al, +the inspector port is incremented by 1 for the spawned subcommand. + +### Override exit handling + +By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override +this behaviour and optionally supply a callback. The default override throws a `CommanderError`. + +The override callback is passed a `CommanderError` with properties `exitCode` number, `code` string, and `message`. The default override behaviour is to throw the error, except for async handling of executable subcommand completion which carries on. The normal display of error messages or version or help +is not affected by the override which is called after the display. + +``` js +program.exitOverride(); + +try { + program.parse(process.argv); +} catch (err) { + // custom processing... +} +``` + +## Examples + +```js +const program = require('commander'); + +program + .version('0.1.0') + .option('-C, --chdir ', 'change the working directory') + .option('-c, --config ', 'set config path. defaults to ./deploy.conf') + .option('-T, --no-tests', 'ignore test hook'); + +program + .command('setup [env]') + .description('run setup commands for all envs') + .option("-s, --setup_mode [mode]", "Which setup mode to use") + .action(function(env, options){ + const mode = options.setup_mode || "normal"; + env = env || 'all'; + console.log('setup for %s env(s) with %s mode', env, mode); + }); + +program + .command('exec ') + .alias('ex') + .description('execute the given remote cmd') + .option("-e, --exec_mode ", "Which exec mode to use") + .action(function(cmd, options){ + console.log('exec "%s" using %s mode', cmd, options.exec_mode); + }).on('--help', function() { + console.log(''); + console.log('Examples:'); + console.log(''); + console.log(' $ deploy exec sequential'); + console.log(' $ deploy exec async'); + }); + +program + .command('*') + .action(function(env){ + console.log('deploying "%s"', env); + }); + +program.parse(process.argv); +``` + +More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory. + +## License + +[MIT](https://github.com/tj/commander.js/blob/master/LICENSE) + +## Support + +Commander 4.x is supported on Node 8 and above, and is likely to work with Node 6 but not tested. +(For versions of Node below Node 6, use Commander 3.x or 2.x.) + +The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub. + +### Commander for enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Commander and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/commander/index.js b/node_modules/commander/index.js new file mode 100644 index 0000000..37d20cc --- /dev/null +++ b/node_modules/commander/index.js @@ -0,0 +1,1649 @@ +/** + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter; +var spawn = require('child_process').spawn; +var path = require('path'); +var dirname = path.dirname; +var basename = path.basename; +var fs = require('fs'); + +/** + * Inherit `Command` from `EventEmitter.prototype`. + */ + +require('util').inherits(Command, EventEmitter); + +/** + * Expose the root command. + */ + +exports = module.exports = new Command(); + +/** + * Expose `Command`. + */ + +exports.Command = Command; + +/** + * Expose `Option`. + */ + +exports.Option = Option; + +/** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {String} flags + * @param {String} description + * @api public + */ + +function Option(flags, description) { + this.flags = flags; + this.required = flags.indexOf('<') >= 0; // A value must be supplied when the option is specified. + this.optional = flags.indexOf('[') >= 0; // A value is optional when the option is specified. + this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line. + this.negate = flags.indexOf('-no-') !== -1; + flags = flags.split(/[ ,|]+/); + if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift(); + this.long = flags.shift(); + this.description = description || ''; +} + +/** + * Return option name. + * + * @return {String} + * @api private + */ + +Option.prototype.name = function() { + return this.long.replace(/^--/, ''); +}; + +/** + * Return option name, in a camelcase format that can be used + * as a object attribute key. + * + * @return {String} + * @api private + */ + +Option.prototype.attributeName = function() { + return camelcase(this.name().replace(/^no-/, '')); +}; + +/** + * Check if `arg` matches the short or long flag. + * + * @param {String} arg + * @return {Boolean} + * @api private + */ + +Option.prototype.is = function(arg) { + return this.short === arg || this.long === arg; +}; + +/** + * CommanderError class + * @class + */ +class CommanderError extends Error { + /** + * Constructs the CommanderError class + * @param {Number} exitCode suggested exit code which could be used with process.exit + * @param {String} code an id string representing the error + * @param {String} message human-readable description of the error + * @constructor + */ + constructor(exitCode, code, message) { + super(message); + // properly capture stack trace in Node.js + Error.captureStackTrace(this, this.constructor); + this.name = this.constructor.name; + this.code = code; + this.exitCode = exitCode; + } +} + +exports.CommanderError = CommanderError; + +/** + * Initialize a new `Command`. + * + * @param {String} [name] + * @api public + */ + +function Command(name) { + this.commands = []; + this.options = []; + this._execs = new Set(); + this._allowUnknownOption = false; + this._args = []; + this._name = name || ''; + this._optionValues = {}; + this._storeOptionsAsProperties = true; // backwards compatible by default + this._passCommandToAction = true; // backwards compatible by default + this._actionResults = []; + + this._helpFlags = '-h, --help'; + this._helpDescription = 'output usage information'; + this._helpShortFlag = '-h'; + this._helpLongFlag = '--help'; +} + +/** + * Define a command. + * + * There are two styles of command: pay attention to where to put the description. + * + * Examples: + * + * // Command implemented using action handler (description is supplied separately to `.command`) + * program + * .command('clone [destination]') + * .description('clone a repository into a newly created directory') + * .action((source, destination) => { + * console.log('clone command called'); + * }); + * + * // Command implemented using separate executable file (description is second parameter to `.command`) + * program + * .command('start ', 'start named service') + * .command('stop [service]', 'stop named service, or all if no name supplied'); + * + * @param {string} nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` + * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) + * @param {Object} [execOpts] - configuration options (for executable) + * @return {Command} returns new command for action handler, or top-level command for executable command + * @api public + */ + +Command.prototype.command = function(nameAndArgs, actionOptsOrExecDesc, execOpts) { + var desc = actionOptsOrExecDesc; + var opts = execOpts; + if (typeof desc === 'object' && desc !== null) { + opts = desc; + desc = null; + } + opts = opts || {}; + var args = nameAndArgs.split(/ +/); + var cmd = new Command(args.shift()); + + if (desc) { + cmd.description(desc); + this.executables = true; + this._execs.add(cmd._name); + if (opts.isDefault) this.defaultExecutable = cmd._name; + } + cmd._noHelp = !!opts.noHelp; + cmd._helpFlags = this._helpFlags; + cmd._helpDescription = this._helpDescription; + cmd._helpShortFlag = this._helpShortFlag; + cmd._helpLongFlag = this._helpLongFlag; + cmd._exitCallback = this._exitCallback; + cmd._storeOptionsAsProperties = this._storeOptionsAsProperties; + cmd._passCommandToAction = this._passCommandToAction; + + cmd._executableFile = opts.executableFile; // Custom name for executable file + this.commands.push(cmd); + cmd.parseExpectedArgs(args); + cmd.parent = this; + + if (desc) return this; + return cmd; +}; + +/** + * Define argument syntax for the top-level command. + * + * @api public + */ + +Command.prototype.arguments = function(desc) { + return this.parseExpectedArgs(desc.split(/ +/)); +}; + +/** + * Add an implicit `help [cmd]` subcommand + * which invokes `--help` for the given command. + * + * @api private + */ + +Command.prototype.addImplicitHelpCommand = function() { + this.command('help [cmd]', 'display help for [cmd]'); +}; + +/** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @param {Array} args + * @return {Command} for chaining + * @api public + */ + +Command.prototype.parseExpectedArgs = function(args) { + if (!args.length) return; + var self = this; + args.forEach(function(arg) { + var argDetails = { + required: false, + name: '', + variadic: false + }; + + switch (arg[0]) { + case '<': + argDetails.required = true; + argDetails.name = arg.slice(1, -1); + break; + case '[': + argDetails.name = arg.slice(1, -1); + break; + } + + if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') { + argDetails.variadic = true; + argDetails.name = argDetails.name.slice(0, -3); + } + if (argDetails.name) { + self._args.push(argDetails); + } + }); + return this; +}; + +/** + * Register callback to use as replacement for calling process.exit. + * + * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing + * @return {Command} for chaining + * @api public + */ + +Command.prototype.exitOverride = function(fn) { + if (fn) { + this._exitCallback = fn; + } else { + this._exitCallback = function(err) { + if (err.code !== 'commander.executeSubCommandAsync') { + throw err; + } else { + // Async callback from spawn events, not useful to throw. + } + }; + } + return this; +}; + +/** + * Call process.exit, and _exitCallback if defined. + * + * @param {Number} exitCode exit code for using with process.exit + * @param {String} code an id string representing the error + * @param {String} message human-readable description of the error + * @return never + * @api private + */ + +Command.prototype._exit = function(exitCode, code, message) { + if (this._exitCallback) { + this._exitCallback(new CommanderError(exitCode, code, message)); + // Expecting this line is not reached. + } + process.exit(exitCode); +}; + +/** + * Register callback `fn` for the command. + * + * Examples: + * + * program + * .command('help') + * .description('display verbose help') + * .action(function() { + * // output help here + * }); + * + * @param {Function} fn + * @return {Command} for chaining + * @api public + */ + +Command.prototype.action = function(fn) { + var self = this; + var listener = function(args, unknown) { + // Parse any so-far unknown options + args = args || []; + unknown = unknown || []; + + var parsed = self.parseOptions(unknown); + + // Output help if necessary + outputHelpIfRequested(self, parsed.unknown); + self._checkForMissingMandatoryOptions(); + + // If there are still any unknown options, then we simply + // die, unless someone asked for help, in which case we give it + // to them, and then we die. + if (parsed.unknown.length > 0) { + self.unknownOption(parsed.unknown[0]); + } + + // Leftover arguments need to be pushed back. Fixes issue #56 + if (parsed.args.length) args = parsed.args.concat(args); + + self._args.forEach(function(arg, i) { + if (arg.required && args[i] == null) { + self.missingArgument(arg.name); + } else if (arg.variadic) { + if (i !== self._args.length - 1) { + self.variadicArgNotLast(arg.name); + } + + args[i] = args.splice(i); + } + }); + + // The .action callback takes an extra parameter which is the command itself. + var expectedArgsCount = self._args.length; + var actionArgs = args.slice(0, expectedArgsCount); + if (self._passCommandToAction) { + actionArgs[expectedArgsCount] = self; + } else { + actionArgs[expectedArgsCount] = self.opts(); + } + // Add the extra arguments so available too. + if (args.length > expectedArgsCount) { + actionArgs.push(args.slice(expectedArgsCount)); + } + + const actionResult = fn.apply(self, actionArgs); + // Remember result in case it is async. Assume parseAsync getting called on root. + let rootCommand = self; + while (rootCommand.parent) { + rootCommand = rootCommand.parent; + } + rootCommand._actionResults.push(actionResult); + }; + var parent = this.parent || this; + var name = parent === this ? '*' : this._name; + parent.on('command:' + name, listener); + if (this._alias) parent.on('command:' + this._alias, listener); + return this; +}; + +/** + * Internal implementation shared by .option() and .requiredOption() + * + * @param {Object} config + * @param {String} flags + * @param {String} description + * @param {Function|*} [fn] - custom option processing function or default vaue + * @param {*} [defaultValue] + * @return {Command} for chaining + * @api private + */ + +Command.prototype._optionEx = function(config, flags, description, fn, defaultValue) { + var self = this, + option = new Option(flags, description), + oname = option.name(), + name = option.attributeName(); + option.mandatory = !!config.mandatory; + + // default as 3rd arg + if (typeof fn !== 'function') { + if (fn instanceof RegExp) { + // This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing. + // No longer documented in README, but still present for backwards compatibility. + var regex = fn; + fn = function(val, def) { + var m = regex.exec(val); + return m ? m[0] : def; + }; + } else { + defaultValue = fn; + fn = null; + } + } + + // preassign default value for --no-*, [optional], , or plain flag if boolean value + if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') { + // when --no-foo we make sure default is true, unless a --foo option is already defined + if (option.negate) { + const positiveLongFlag = option.long.replace(/^--no-/, '--'); + defaultValue = self.optionFor(positiveLongFlag) ? self._getOptionValue(name) : true; + } + // preassign only if we have a default + if (defaultValue !== undefined) { + self._setOptionValue(name, defaultValue); + option.defaultValue = defaultValue; + } + } + + // register the option + this.options.push(option); + + // when it's passed assign the value + // and conditionally invoke the callback + this.on('option:' + oname, function(val) { + // coercion + if (val !== null && fn) { + val = fn(val, self._getOptionValue(name) === undefined ? defaultValue : self._getOptionValue(name)); + } + + // unassigned or boolean value + if (typeof self._getOptionValue(name) === 'boolean' || typeof self._getOptionValue(name) === 'undefined') { + // if no value, negate false, and we have a default, then use it! + if (val == null) { + self._setOptionValue(name, option.negate + ? false + : defaultValue || true); + } else { + self._setOptionValue(name, val); + } + } else if (val !== null) { + // reassign + self._setOptionValue(name, option.negate ? false : val); + } + }); + + return this; +}; + +/** + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string should contain both the short and long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * Examples: + * + * // simple boolean defaulting to undefined + * program.option('-p, --pepper', 'add pepper'); + * + * program.pepper + * // => undefined + * + * --pepper + * program.pepper + * // => true + * + * // simple boolean defaulting to true (unless non-negated option is also defined) + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => false + * + * // required argument + * program.option('-C, --chdir ', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); + * + * @param {String} flags + * @param {String} description + * @param {Function|*} [fn] - custom option processing function or default vaue + * @param {*} [defaultValue] + * @return {Command} for chaining + * @api public + */ + +Command.prototype.option = function(flags, description, fn, defaultValue) { + return this._optionEx({}, flags, description, fn, defaultValue); +}; + +/* + * Add a required option which must have a value after parsing. This usually means + * the option must be specified on the command line. (Otherwise the same as .option().) + * + * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space. + * + * @param {String} flags + * @param {String} description + * @param {Function|*} [fn] - custom option processing function or default vaue + * @param {*} [defaultValue] + * @return {Command} for chaining + * @api public + */ + +Command.prototype.requiredOption = function(flags, description, fn, defaultValue) { + return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue); +}; + +/** + * Allow unknown options on the command line. + * + * @param {Boolean} arg if `true` or omitted, no error will be thrown + * for unknown options. + * @api public + */ +Command.prototype.allowUnknownOption = function(arg) { + this._allowUnknownOption = arguments.length === 0 || arg; + return this; +}; + +/** + * Whether to store option values as properties on command object, + * or store separately (specify false). In both cases the option values can be accessed using .opts(). + * + * @param {boolean} value + * @return {Command} Command for chaining + * @api public + */ + +Command.prototype.storeOptionsAsProperties = function(value) { + this._storeOptionsAsProperties = (value === undefined) || value; + if (this.options.length) { + // This is for programmer, not end user. + console.error('Commander usage error: call storeOptionsAsProperties before adding options'); + } + return this; +}; + +/** + * Whether to pass command to action handler, + * or just the options (specify false). + * + * @param {boolean} value + * @return {Command} Command for chaining + * @api public + */ + +Command.prototype.passCommandToAction = function(value) { + this._passCommandToAction = (value === undefined) || value; + return this; +}; + +/** + * Store option value + * + * @param {String} key + * @param {Object} value + * @api private + */ + +Command.prototype._setOptionValue = function(key, value) { + if (this._storeOptionsAsProperties) { + this[key] = value; + } else { + this._optionValues[key] = value; + } +}; + +/** + * Retrieve option value + * + * @param {String} key + * @return {Object} value + * @api private + */ + +Command.prototype._getOptionValue = function(key) { + if (this._storeOptionsAsProperties) { + return this[key]; + } + return this._optionValues[key]; +}; + +/** + * Parse `argv`, setting options and invoking commands when defined. + * + * @param {Array} argv + * @return {Command} for chaining + * @api public + */ + +Command.prototype.parse = function(argv) { + // implicit help + if (this.executables) this.addImplicitHelpCommand(); + + // store raw args + this.rawArgs = argv; + + // guess name + this._name = this._name || basename(argv[1], '.js'); + + // github-style sub-commands with no sub-command + if (this.executables && argv.length < 3 && !this.defaultExecutable) { + // this user needs help + argv.push(this._helpLongFlag); + } + + // process argv + var normalized = this.normalize(argv.slice(2)); + var parsed = this.parseOptions(normalized); + var args = this.args = parsed.args; + + var result = this.parseArgs(this.args, parsed.unknown); + + if (args[0] === 'help' && args.length === 1) this.help(); + + // Note for future: we could return early if we found an action handler in parseArgs, as none of following code needed? + + // --help + if (args[0] === 'help') { + args[0] = args[1]; + args[1] = this._helpLongFlag; + } else { + // If calling through to executable subcommand we could check for help flags before failing, + // but a somewhat unlikely case since program options not passed to executable subcommands. + // Wait for reports to see if check needed and what usage pattern is. + this._checkForMissingMandatoryOptions(); + } + + // executable sub-commands + // (Debugging note for future: args[0] is not right if an action has been called) + var name = result.args[0]; + var subCommand = null; + + // Look for subcommand + if (name) { + subCommand = this.commands.find(function(command) { + return command._name === name; + }); + } + + // Look for alias + if (!subCommand && name) { + subCommand = this.commands.find(function(command) { + return command.alias() === name; + }); + if (subCommand) { + name = subCommand._name; + args[0] = name; + } + } + + // Look for default subcommand + if (!subCommand && this.defaultExecutable) { + name = this.defaultExecutable; + args.unshift(name); + subCommand = this.commands.find(function(command) { + return command._name === name; + }); + } + + if (this._execs.has(name)) { + return this.executeSubCommand(argv, args, parsed.unknown, subCommand ? subCommand._executableFile : undefined); + } + + return result; +}; + +/** + * Parse `argv`, setting options and invoking commands when defined. + * + * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise. + * + * @param {Array} argv + * @return {Promise} + * @api public + */ +Command.prototype.parseAsync = function(argv) { + this.parse(argv); + return Promise.all(this._actionResults); +}; + +/** + * Execute a sub-command executable. + * + * @param {Array} argv + * @param {Array} args + * @param {Array} unknown + * @param {String} executableFile + * @api private + */ + +Command.prototype.executeSubCommand = function(argv, args, unknown, executableFile) { + args = args.concat(unknown); + + if (!args.length) this.help(); + + var isExplicitJS = false; // Whether to use node to launch "executable" + + // executable + var pm = argv[1]; + // name of the subcommand, like `pm-install` + var bin = basename(pm, path.extname(pm)) + '-' + args[0]; + if (executableFile != null) { + bin = executableFile; + // Check for same extensions as we scan for below so get consistent launch behaviour. + var executableExt = path.extname(executableFile); + isExplicitJS = executableExt === '.js' || executableExt === '.ts' || executableExt === '.mjs'; + } + + // In case of globally installed, get the base dir where executable + // subcommand file should be located at + var baseDir; + + var resolvedLink = fs.realpathSync(pm); + + baseDir = dirname(resolvedLink); + + // prefer local `./` to bin in the $PATH + var localBin = path.join(baseDir, bin); + + // whether bin file is a js script with explicit `.js` or `.ts` extension + if (exists(localBin + '.js')) { + bin = localBin + '.js'; + isExplicitJS = true; + } else if (exists(localBin + '.ts')) { + bin = localBin + '.ts'; + isExplicitJS = true; + } else if (exists(localBin + '.mjs')) { + bin = localBin + '.mjs'; + isExplicitJS = true; + } else if (exists(localBin)) { + bin = localBin; + } + + args = args.slice(1); + + var proc; + if (process.platform !== 'win32') { + if (isExplicitJS) { + args.unshift(bin); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); + + proc = spawn(process.argv[0], args, { stdio: 'inherit' }); + } else { + proc = spawn(bin, args, { stdio: 'inherit' }); + } + } else { + args.unshift(bin); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); + proc = spawn(process.execPath, args, { stdio: 'inherit' }); + } + + var signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP']; + signals.forEach(function(signal) { + process.on(signal, function() { + if (proc.killed === false && proc.exitCode === null) { + proc.kill(signal); + } + }); + }); + + // By default terminate process when spawned process terminates. + // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running! + const exitCallback = this._exitCallback; + if (!exitCallback) { + proc.on('close', process.exit.bind(process)); + } else { + proc.on('close', () => { + exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)')); + }); + } + proc.on('error', function(err) { + if (err.code === 'ENOENT') { + console.error('error: %s(1) does not exist, try --help', bin); + } else if (err.code === 'EACCES') { + console.error('error: %s(1) not executable. try chmod or run with root', bin); + } + if (!exitCallback) { + process.exit(1); + } else { + const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)'); + wrappedError.nestedError = err; + exitCallback(wrappedError); + } + }); + + // Store the reference to the child process + this.runningCommand = proc; +}; + +/** + * Normalize `args`, splitting joined short flags. For example + * the arg "-abc" is equivalent to "-a -b -c". + * This also normalizes equal sign and splits "--abc=def" into "--abc def". + * + * @param {Array} args + * @return {Array} + * @api private + */ + +Command.prototype.normalize = function(args) { + var ret = [], + arg, + lastOpt, + index, + short, + opt; + + for (var i = 0, len = args.length; i < len; ++i) { + arg = args[i]; + if (i > 0) { + lastOpt = this.optionFor(args[i - 1]); + } + + if (arg === '--') { + // Honor option terminator + ret = ret.concat(args.slice(i)); + break; + } else if (lastOpt && lastOpt.required) { + ret.push(arg); + } else if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') { + short = arg.slice(0, 2); + opt = this.optionFor(short); + if (opt && (opt.required || opt.optional)) { + ret.push(short); + ret.push(arg.slice(2)); + } else { + arg.slice(1).split('').forEach(function(c) { + ret.push('-' + c); + }); + } + } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) { + ret.push(arg.slice(0, index), arg.slice(index + 1)); + } else { + ret.push(arg); + } + } + + return ret; +}; + +/** + * Parse command `args`. + * + * When listener(s) are available those + * callbacks are invoked, otherwise the "*" + * event is emitted and those actions are invoked. + * + * @param {Array} args + * @return {Command} for chaining + * @api private + */ + +Command.prototype.parseArgs = function(args, unknown) { + var name; + + if (args.length) { + name = args[0]; + if (this.listeners('command:' + name).length) { + this.emit('command:' + args.shift(), args, unknown); + } else { + this.emit('command:*', args, unknown); + } + } else { + outputHelpIfRequested(this, unknown); + + // If there were no args and we have unknown options, + // then they are extraneous and we need to error. + if (unknown.length > 0 && !this.defaultExecutable) { + this.unknownOption(unknown[0]); + } + if (this.commands.length === 0 && + this._args.filter(function(a) { return a.required; }).length === 0) { + this.emit('command:*'); + } + } + + return this; +}; + +/** + * Return an option matching `arg` if any. + * + * @param {String} arg + * @return {Option} + * @api private + */ + +Command.prototype.optionFor = function(arg) { + for (var i = 0, len = this.options.length; i < len; ++i) { + if (this.options[i].is(arg)) { + return this.options[i]; + } + } +}; + +/** + * Display an error message if a mandatory option does not have a value. + * + * @api private + */ + +Command.prototype._checkForMissingMandatoryOptions = function() { + // Walk up hierarchy so can call from action handler after checking for displaying help. + for (var cmd = this; cmd; cmd = cmd.parent) { + cmd.options.forEach((anOption) => { + if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) { + cmd.missingMandatoryOptionValue(anOption); + } + }); + } +}; + +/** + * Parse options from `argv` returning `argv` + * void of these options. + * + * @param {Array} argv + * @return {{args: Array, unknown: Array}} + * @api public + */ + +Command.prototype.parseOptions = function(argv) { + var args = [], + len = argv.length, + literal, + option, + arg; + + var unknownOptions = []; + + // parse options + for (var i = 0; i < len; ++i) { + arg = argv[i]; + + // literal args after -- + if (literal) { + args.push(arg); + continue; + } + + if (arg === '--') { + literal = true; + continue; + } + + // find matching Option + option = this.optionFor(arg); + + // option is defined + if (option) { + // requires arg + if (option.required) { + arg = argv[++i]; + if (arg == null) return this.optionMissingArgument(option); + this.emit('option:' + option.name(), arg); + // optional arg + } else if (option.optional) { + arg = argv[i + 1]; + if (arg == null || (arg[0] === '-' && arg !== '-')) { + arg = null; + } else { + ++i; + } + this.emit('option:' + option.name(), arg); + // flag + } else { + this.emit('option:' + option.name()); + } + continue; + } + + // looks like an option + if (arg.length > 1 && arg[0] === '-') { + unknownOptions.push(arg); + + // If the next argument looks like it might be + // an argument for this option, we pass it on. + // If it isn't, then it'll simply be ignored + if ((i + 1) < argv.length && (argv[i + 1][0] !== '-' || argv[i + 1] === '-')) { + unknownOptions.push(argv[++i]); + } + continue; + } + + // arg + args.push(arg); + } + + return { args: args, unknown: unknownOptions }; +}; + +/** + * Return an object containing options as key-value pairs + * + * @return {Object} + * @api public + */ +Command.prototype.opts = function() { + if (this._storeOptionsAsProperties) { + // Preserve original behaviour so backwards compatible when still using properties + var result = {}, + len = this.options.length; + + for (var i = 0; i < len; i++) { + var key = this.options[i].attributeName(); + result[key] = key === this._versionOptionName ? this._version : this[key]; + } + return result; + } + + return this._optionValues; +}; + +/** + * Argument `name` is missing. + * + * @param {String} name + * @api private + */ + +Command.prototype.missingArgument = function(name) { + const message = `error: missing required argument '${name}'`; + console.error(message); + this._exit(1, 'commander.missingArgument', message); +}; + +/** + * `Option` is missing an argument, but received `flag` or nothing. + * + * @param {Option} option + * @param {String} [flag] + * @api private + */ + +Command.prototype.optionMissingArgument = function(option, flag) { + let message; + if (flag) { + message = `error: option '${option.flags}' argument missing, got '${flag}'`; + } else { + message = `error: option '${option.flags}' argument missing`; + } + console.error(message); + this._exit(1, 'commander.optionMissingArgument', message); +}; + +/** + * `Option` does not have a value, and is a mandatory option. + * + * @param {Option} option + * @api private + */ + +Command.prototype.missingMandatoryOptionValue = function(option) { + const message = `error: required option '${option.flags}' not specified`; + console.error(message); + this._exit(1, 'commander.missingMandatoryOptionValue', message); +}; + +/** + * Unknown option `flag`. + * + * @param {String} flag + * @api private + */ + +Command.prototype.unknownOption = function(flag) { + if (this._allowUnknownOption) return; + const message = `error: unknown option '${flag}'`; + console.error(message); + this._exit(1, 'commander.unknownOption', message); +}; + +/** + * Variadic argument with `name` is not the last argument as required. + * + * @param {String} name + * @api private + */ + +Command.prototype.variadicArgNotLast = function(name) { + const message = `error: variadic arguments must be last '${name}'`; + console.error(message); + this._exit(1, 'commander.variadicArgNotLast', message); +}; + +/** + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * You can optionally supply the flags and description to override the defaults. + * + * @param {String} str + * @param {String} [flags] + * @param {String} [description] + * @return {Command} for chaining + * @api public + */ + +Command.prototype.version = function(str, flags, description) { + if (arguments.length === 0) return this._version; + this._version = str; + flags = flags || '-V, --version'; + description = description || 'output the version number'; + var versionOption = new Option(flags, description); + this._versionOptionName = versionOption.long.substr(2) || 'version'; + this.options.push(versionOption); + var self = this; + this.on('option:' + this._versionOptionName, function() { + process.stdout.write(str + '\n'); + self._exit(0, 'commander.version', str); + }); + return this; +}; + +/** + * Set the description to `str`. + * + * @param {String} str + * @param {Object} [argsDescription] + * @return {String|Command} + * @api public + */ + +Command.prototype.description = function(str, argsDescription) { + if (arguments.length === 0) return this._description; + this._description = str; + this._argsDescription = argsDescription; + return this; +}; + +/** + * Set an alias for the command + * + * @param {String} alias + * @return {String|Command} + * @api public + */ + +Command.prototype.alias = function(alias) { + var command = this; + if (this.commands.length !== 0) { + command = this.commands[this.commands.length - 1]; + } + + if (arguments.length === 0) return command._alias; + + if (alias === command._name) throw new Error('Command alias can\'t be the same as its name'); + + command._alias = alias; + return this; +}; + +/** + * Set / get the command usage `str`. + * + * @param {String} [str] + * @return {String|Command} + * @api public + */ + +Command.prototype.usage = function(str) { + var args = this._args.map(function(arg) { + return humanReadableArgName(arg); + }); + + var usage = '[options]' + + (this.commands.length ? ' [command]' : '') + + (this._args.length ? ' ' + args.join(' ') : ''); + + if (arguments.length === 0) return this._usage || usage; + this._usage = str; + + return this; +}; + +/** + * Get or set the name of the command + * + * @param {String} [str] + * @return {String|Command} + * @api public + */ + +Command.prototype.name = function(str) { + if (arguments.length === 0) return this._name; + this._name = str; + return this; +}; + +/** + * Return prepared commands. + * + * @return {Array} + * @api private + */ + +Command.prototype.prepareCommands = function() { + return this.commands.filter(function(cmd) { + return !cmd._noHelp; + }).map(function(cmd) { + var args = cmd._args.map(function(arg) { + return humanReadableArgName(arg); + }).join(' '); + + return [ + cmd._name + + (cmd._alias ? '|' + cmd._alias : '') + + (cmd.options.length ? ' [options]' : '') + + (args ? ' ' + args : ''), + cmd._description + ]; + }); +}; + +/** + * Return the largest command length. + * + * @return {Number} + * @api private + */ + +Command.prototype.largestCommandLength = function() { + var commands = this.prepareCommands(); + return commands.reduce(function(max, command) { + return Math.max(max, command[0].length); + }, 0); +}; + +/** + * Return the largest option length. + * + * @return {Number} + * @api private + */ + +Command.prototype.largestOptionLength = function() { + var options = [].slice.call(this.options); + options.push({ + flags: this._helpFlags + }); + + return options.reduce(function(max, option) { + return Math.max(max, option.flags.length); + }, 0); +}; + +/** + * Return the largest arg length. + * + * @return {Number} + * @api private + */ + +Command.prototype.largestArgLength = function() { + return this._args.reduce(function(max, arg) { + return Math.max(max, arg.name.length); + }, 0); +}; + +/** + * Return the pad width. + * + * @return {Number} + * @api private + */ + +Command.prototype.padWidth = function() { + var width = this.largestOptionLength(); + if (this._argsDescription && this._args.length) { + if (this.largestArgLength() > width) { + width = this.largestArgLength(); + } + } + + if (this.commands && this.commands.length) { + if (this.largestCommandLength() > width) { + width = this.largestCommandLength(); + } + } + + return width; +}; + +/** + * Return help for options. + * + * @return {String} + * @api private + */ + +Command.prototype.optionHelp = function() { + var width = this.padWidth(); + + var columns = process.stdout.columns || 80; + var descriptionWidth = columns - width - 4; + + // Append the help information + return this.options.map(function(option) { + const fullDesc = option.description + + ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : ''); + return pad(option.flags, width) + ' ' + optionalWrap(fullDesc, descriptionWidth, width + 2); + }).concat([pad(this._helpFlags, width) + ' ' + optionalWrap(this._helpDescription, descriptionWidth, width + 2)]) + .join('\n'); +}; + +/** + * Return command help documentation. + * + * @return {String} + * @api private + */ + +Command.prototype.commandHelp = function() { + if (!this.commands.length) return ''; + + var commands = this.prepareCommands(); + var width = this.padWidth(); + + var columns = process.stdout.columns || 80; + var descriptionWidth = columns - width - 4; + + return [ + 'Commands:', + commands.map(function(cmd) { + var desc = cmd[1] ? ' ' + cmd[1] : ''; + return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2); + }).join('\n').replace(/^/gm, ' '), + '' + ].join('\n'); +}; + +/** + * Return program help documentation. + * + * @return {String} + * @api private + */ + +Command.prototype.helpInformation = function() { + var desc = []; + if (this._description) { + desc = [ + this._description, + '' + ]; + + var argsDescription = this._argsDescription; + if (argsDescription && this._args.length) { + var width = this.padWidth(); + var columns = process.stdout.columns || 80; + var descriptionWidth = columns - width - 5; + desc.push('Arguments:'); + desc.push(''); + this._args.forEach(function(arg) { + desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name], descriptionWidth, width + 4)); + }); + desc.push(''); + } + } + + var cmdName = this._name; + if (this._alias) { + cmdName = cmdName + '|' + this._alias; + } + var parentCmdNames = ''; + for (var parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { + parentCmdNames = parentCmd.name() + ' ' + parentCmdNames; + } + var usage = [ + 'Usage: ' + parentCmdNames + cmdName + ' ' + this.usage(), + '' + ]; + + var cmds = []; + var commandHelp = this.commandHelp(); + if (commandHelp) cmds = [commandHelp]; + + var options = [ + 'Options:', + '' + this.optionHelp().replace(/^/gm, ' '), + '' + ]; + + return usage + .concat(desc) + .concat(options) + .concat(cmds) + .join('\n'); +}; + +/** + * Output help information for this command. + * + * When listener(s) are available for the helpLongFlag + * those callbacks are invoked. + * + * @api public + */ + +Command.prototype.outputHelp = function(cb) { + if (!cb) { + cb = function(passthru) { + return passthru; + }; + } + const cbOutput = cb(this.helpInformation()); + if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) { + throw new Error('outputHelp callback must return a string or a Buffer'); + } + process.stdout.write(cbOutput); + this.emit(this._helpLongFlag); +}; + +/** + * You can pass in flags and a description to override the help + * flags and help description for your command. + * + * @param {String} [flags] + * @param {String} [description] + * @return {Command} + * @api public + */ + +Command.prototype.helpOption = function(flags, description) { + this._helpFlags = flags || this._helpFlags; + this._helpDescription = description || this._helpDescription; + + var splitFlags = this._helpFlags.split(/[ ,|]+/); + + if (splitFlags.length > 1) this._helpShortFlag = splitFlags.shift(); + + this._helpLongFlag = splitFlags.shift(); + + return this; +}; + +/** + * Output help information and exit. + * + * @param {Function} [cb] + * @api public + */ + +Command.prototype.help = function(cb) { + this.outputHelp(cb); + // exitCode: preserving original behaviour which was calling process.exit() + // message: do not have all displayed text available so only passing placeholder. + this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)'); +}; + +/** + * Camel-case the given `flag` + * + * @param {String} flag + * @return {String} + * @api private + */ + +function camelcase(flag) { + return flag.split('-').reduce(function(str, word) { + return str + word[0].toUpperCase() + word.slice(1); + }); +} + +/** + * Pad `str` to `width`. + * + * @param {String} str + * @param {Number} width + * @return {String} + * @api private + */ + +function pad(str, width) { + var len = Math.max(0, width - str.length); + return str + Array(len + 1).join(' '); +} + +/** + * Wraps the given string with line breaks at the specified width while breaking + * words and indenting every but the first line on the left. + * + * @param {String} str + * @param {Number} width + * @param {Number} indent + * @return {String} + * @api private + */ +function wrap(str, width, indent) { + var regex = new RegExp('.{1,' + (width - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g'); + var lines = str.match(regex) || []; + return lines.map(function(line, i) { + if (line.slice(-1) === '\n') { + line = line.slice(0, line.length - 1); + } + return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line.trimRight(); + }).join('\n'); +} + +/** + * Optionally wrap the given str to a max width of width characters per line + * while indenting with indent spaces. Do not wrap if insufficient width or + * string is manually formatted. + * + * @param {String} str + * @param {Number} width + * @param {Number} indent + * @return {String} + * @api private + */ +function optionalWrap(str, width, indent) { + // Detect manually wrapped and indented strings by searching for line breaks + // followed by multiple spaces/tabs. + if (str.match(/[\n]\s+/)) return str; + // Do not wrap to narrow columns (or can end up with a word per line). + const minWidth = 40; + if (width < minWidth) return str; + + return wrap(str, width, indent); +} + +/** + * Output help information if help flags specified + * + * @param {Command} cmd - command to output help for + * @param {Array} options - array of options to search for -h or --help + * @api private + */ + +function outputHelpIfRequested(cmd, options) { + options = options || []; + + for (var i = 0; i < options.length; i++) { + if (options[i] === cmd._helpLongFlag || options[i] === cmd._helpShortFlag) { + cmd.outputHelp(); + // (Do not have all displayed text available so only passing placeholder.) + cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)'); + } + } +} + +/** + * Takes an argument and returns its human readable equivalent for help usage. + * + * @param {Object} arg + * @return {String} + * @api private + */ + +function humanReadableArgName(arg) { + var nameOutput = arg.name + (arg.variadic === true ? '...' : ''); + + return arg.required + ? '<' + nameOutput + '>' + : '[' + nameOutput + ']'; +} + +// for versions before node v0.8 when there weren't `fs.existsSync` +function exists(file) { + try { + if (fs.statSync(file).isFile()) { + return true; + } + } catch (e) { + return false; + } +} + +/** + * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command). + * + * @param {string[]} args - array of arguments from node.execArgv + * @returns {string[]} + * @api private + */ + +function incrementNodeInspectorPort(args) { + // Testing for these options: + // --inspect[=[host:]port] + // --inspect-brk[=[host:]port] + // --inspect-port=[host:]port + return args.map((arg) => { + var result = arg; + if (arg.indexOf('--inspect') === 0) { + var debugOption; + var debugHost = '127.0.0.1'; + var debugPort = '9229'; + var match; + if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { + // e.g. --inspect + debugOption = match[1]; + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) { + debugOption = match[1]; + if (/^\d+$/.test(match[3])) { + // e.g. --inspect=1234 + debugPort = match[3]; + } else { + // e.g. --inspect=localhost + debugHost = match[3]; + } + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) { + // e.g. --inspect=localhost:1234 + debugOption = match[1]; + debugHost = match[3]; + debugPort = match[4]; + } + + if (debugOption && debugPort !== '0') { + result = `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; + } + } + return result; + }); +} diff --git a/node_modules/commander/package.json b/node_modules/commander/package.json new file mode 100644 index 0000000..e4781e5 --- /dev/null +++ b/node_modules/commander/package.json @@ -0,0 +1,41 @@ +{ + "name": "commander", + "version": "4.1.1", + "description": "the complete solution for node.js command-line programs", + "keywords": [ + "commander", + "command", + "option", + "parser" + ], + "author": "TJ Holowaychuk ", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/tj/commander.js.git" + }, + "scripts": { + "lint": "eslint index.js \"tests/**/*.js\"", + "test": "jest && npm run test-typings", + "test-typings": "tsc -p tsconfig.json" + }, + "main": "index", + "files": [ + "index.js", + "typings/index.d.ts" + ], + "dependencies": {}, + "devDependencies": { + "@types/jest": "^24.0.23", + "@types/node": "^12.12.11", + "eslint": "^6.7.0", + "eslint-plugin-jest": "^22.21.0", + "jest": "^24.8.0", + "standard": "^14.3.1", + "typescript": "^3.7.2" + }, + "typings": "typings/index.d.ts", + "engines": { + "node": ">= 6" + } +} diff --git a/node_modules/commander/typings/index.d.ts b/node_modules/commander/typings/index.d.ts new file mode 100644 index 0000000..082a3a3 --- /dev/null +++ b/node_modules/commander/typings/index.d.ts @@ -0,0 +1,311 @@ +// Type definitions for commander +// Original definitions by: Alan Agius , Marcelo Dezem , vvakame , Jules Randolph + +/// + +declare namespace commander { + + interface CommanderError extends Error { + code: string; + exitCode: number; + message: string; + nestedError?: string; + } + type CommanderErrorConstructor = { new (exitCode: number, code: string, message: string): CommanderError }; + + interface Option { + flags: string; + required: boolean; // A value must be supplied when the option is specified. + optional: boolean; // A value is optional when the option is specified. + mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line. + bool: boolean; + short?: string; + long: string; + description: string; + } + type OptionConstructor = { new (flags: string, description?: string): Option }; + + interface Command extends NodeJS.EventEmitter { + [key: string]: any; // options as properties + + args: string[]; + + /** + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * You can optionally supply the flags and description to override the defaults. + */ + version(str: string, flags?: string, description?: string): Command; + + /** + * Define a command, implemented using an action handler. + * + * @remarks + * The command description is supplied using `.description`, not as a parameter to `.command`. + * + * @example + * ```ts + * program + * .command('clone [destination]') + * .description('clone a repository into a newly created directory') + * .action((source, destination) => { + * console.log('clone command called'); + * }); + * ``` + * + * @param nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` + * @param opts - configuration options + * @returns new command + */ + command(nameAndArgs: string, opts?: CommandOptions): Command; + /** + * Define a command, implemented in a separate executable file. + * + * @remarks + * The command description is supplied as the second parameter to `.command`. + * + * @example + * ```ts + * program + * .command('start ', 'start named service') + * .command('stop [service]', 'stop named serice, or all if no name supplied'); + * ``` + * + * @param nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` + * @param description - description of executable command + * @param opts - configuration options + * @returns top level command for chaining more command definitions + */ + command(nameAndArgs: string, description: string, opts?: commander.CommandOptions): Command; + + /** + * Define argument syntax for the top-level command. + * + * @returns Command for chaining + */ + arguments(desc: string): Command; + + /** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @returns Command for chaining + */ + parseExpectedArgs(args: string[]): Command; + + /** + * Register callback to use as replacement for calling process.exit. + */ + exitOverride(callback?: (err: CommanderError) => never|void): Command; + + /** + * Register callback `fn` for the command. + * + * @example + * program + * .command('help') + * .description('display verbose help') + * .action(function() { + * // output help here + * }); + * + * @returns Command for chaining + */ + action(fn: (...args: any[]) => void | Promise): Command; + + /** + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string should contain both the short and long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * @example + * // simple boolean defaulting to false + * program.option('-p, --pepper', 'add pepper'); + * + * --pepper + * program.pepper + * // => Boolean + * + * // simple boolean defaulting to true + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => false + * + * // required argument + * program.option('-C, --chdir ', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); + * + * @returns Command for chaining + */ + option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command; + option(flags: string, description?: string, defaultValue?: any): Command; + + /** + * Define a required option, which must have a value after parsing. This usually means + * the option must be specified on the command line. (Otherwise the same as .option().) + * + * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space. + */ + requiredOption(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command; + requiredOption(flags: string, description?: string, defaultValue?: any): Command; + + + /** + * Whether to store option values as properties on command object, + * or store separately (specify false). In both cases the option values can be accessed using .opts(). + * + * @return Command for chaining + */ + storeOptionsAsProperties(value?: boolean): Command; + + /** + * Whether to pass command to action handler, + * or just the options (specify false). + * + * @return Command for chaining + */ + passCommandToAction(value?: boolean): Command; + + /** + * Allow unknown options on the command line. + * + * @param [arg] if `true` or omitted, no error will be thrown for unknown options. + * @returns Command for chaining + */ + allowUnknownOption(arg?: boolean): Command; + + /** + * Parse `argv`, setting options and invoking commands when defined. + * + * @returns Command for chaining + */ + parse(argv: string[]): Command; + + /** + * Parse `argv`, setting options and invoking commands when defined. + * + * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise. + * + * @returns Promise + */ + parseAsync(argv: string[]): Promise; + + /** + * Parse options from `argv` returning `argv` void of these options. + */ + parseOptions(argv: string[]): commander.ParseOptionsResult; + + /** + * Return an object containing options as key-value pairs + */ + opts(): { [key: string]: any }; + + /** + * Set the description. + * + * @returns Command for chaining + */ + description(str: string, argsDescription?: {[argName: string]: string}): Command; + /** + * Get the description. + */ + description(): string; + + /** + * Set an alias for the command. + * + * @returns Command for chaining + */ + alias(alias: string): Command; + /** + * Get alias for the command. + */ + alias(): string; + + /** + * Set the command usage. + * + * @returns Command for chaining + */ + usage(str: string): Command; + /** + * Get the command usage. + */ + usage(): string; + + /** + * Set the name of the command. + * + * @returns Command for chaining + */ + name(str: string): Command; + /** + * Get the name of the command. + */ + name(): string; + + /** + * Output help information for this command. + * + * When listener(s) are available for the helpLongFlag + * those callbacks are invoked. + */ + outputHelp(cb?: (str: string) => string): void; + + /** + * You can pass in flags and a description to override the help + * flags and help description for your command. + */ + helpOption(flags?: string, description?: string): Command; + + /** + * Output help information and exit. + */ + help(cb?: (str: string) => string): never; + } + type CommandConstructor = { new (name?: string): Command }; + + + interface CommandOptions { + noHelp?: boolean; + isDefault?: boolean; + executableFile?: string; + } + + interface ParseOptionsResult { + args: string[]; + unknown: string[]; + } + + interface CommanderStatic extends Command { + Command: CommandConstructor; + Option: OptionConstructor; + CommanderError:CommanderErrorConstructor; + } + +} + +declare const commander: commander.CommanderStatic; +export = commander; diff --git a/node_modules/cross-spawn/LICENSE b/node_modules/cross-spawn/LICENSE new file mode 100644 index 0000000..8407b9a --- /dev/null +++ b/node_modules/cross-spawn/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 Made With MOXY Lda + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/cross-spawn/README.md b/node_modules/cross-spawn/README.md new file mode 100644 index 0000000..1ed9252 --- /dev/null +++ b/node_modules/cross-spawn/README.md @@ -0,0 +1,89 @@ +# cross-spawn + +[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][ci-image]][ci-url] [![Build status][appveyor-image]][appveyor-url] + +[npm-url]:https://npmjs.org/package/cross-spawn +[downloads-image]:https://img.shields.io/npm/dm/cross-spawn.svg +[npm-image]:https://img.shields.io/npm/v/cross-spawn.svg +[ci-url]:https://github.com/moxystudio/node-cross-spawn/actions/workflows/ci.yaml +[ci-image]:https://github.com/moxystudio/node-cross-spawn/actions/workflows/ci.yaml/badge.svg +[appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn +[appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg + +A cross platform solution to node's spawn and spawnSync. + +## Installation + +Node.js version 8 and up: +`$ npm install cross-spawn` + +Node.js version 7 and under: +`$ npm install cross-spawn@6` + +## Why + +Node has issues when using spawn on Windows: + +- It ignores [PATHEXT](https://github.com/joyent/node/issues/2318) +- It does not support [shebangs](https://en.wikipedia.org/wiki/Shebang_(Unix)) +- Has problems running commands with [spaces](https://github.com/nodejs/node/issues/7367) +- Has problems running commands with posix relative paths (e.g.: `./my-folder/my-executable`) +- Has an [issue](https://github.com/moxystudio/node-cross-spawn/issues/82) with command shims (files in `node_modules/.bin/`), where arguments with quotes and parenthesis would result in [invalid syntax error](https://github.com/moxystudio/node-cross-spawn/blob/e77b8f22a416db46b6196767bcd35601d7e11d54/test/index.test.js#L149) +- No `options.shell` support on node `` where `` must not contain any arguments. +If you would like to have the shebang support improved, feel free to contribute via a pull-request. + +Remember to always test your code on Windows! + + +## Tests + +`$ npm test` +`$ npm test -- --watch` during development + + +## License + +Released under the [MIT License](https://www.opensource.org/licenses/mit-license.php). diff --git a/node_modules/cross-spawn/index.js b/node_modules/cross-spawn/index.js new file mode 100644 index 0000000..5509742 --- /dev/null +++ b/node_modules/cross-spawn/index.js @@ -0,0 +1,39 @@ +'use strict'; + +const cp = require('child_process'); +const parse = require('./lib/parse'); +const enoent = require('./lib/enoent'); + +function spawn(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); + + // Spawn the child process + const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); + + // Hook into child process "exit" event to emit an error if the command + // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + enoent.hookChildProcess(spawned, parsed); + + return spawned; +} + +function spawnSync(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); + + // Spawn the child process + const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); + + // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + + return result; +} + +module.exports = spawn; +module.exports.spawn = spawn; +module.exports.sync = spawnSync; + +module.exports._parse = parse; +module.exports._enoent = enoent; diff --git a/node_modules/cross-spawn/lib/enoent.js b/node_modules/cross-spawn/lib/enoent.js new file mode 100644 index 0000000..da33471 --- /dev/null +++ b/node_modules/cross-spawn/lib/enoent.js @@ -0,0 +1,59 @@ +'use strict'; + +const isWin = process.platform === 'win32'; + +function notFoundError(original, syscall) { + return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { + code: 'ENOENT', + errno: 'ENOENT', + syscall: `${syscall} ${original.command}`, + path: original.command, + spawnargs: original.args, + }); +} + +function hookChildProcess(cp, parsed) { + if (!isWin) { + return; + } + + const originalEmit = cp.emit; + + cp.emit = function (name, arg1) { + // If emitting "exit" event and exit code is 1, we need to check if + // the command exists and emit an "error" instead + // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 + if (name === 'exit') { + const err = verifyENOENT(arg1, parsed); + + if (err) { + return originalEmit.call(cp, 'error', err); + } + } + + return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params + }; +} + +function verifyENOENT(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawn'); + } + + return null; +} + +function verifyENOENTSync(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawnSync'); + } + + return null; +} + +module.exports = { + hookChildProcess, + verifyENOENT, + verifyENOENTSync, + notFoundError, +}; diff --git a/node_modules/cross-spawn/lib/parse.js b/node_modules/cross-spawn/lib/parse.js new file mode 100644 index 0000000..0129d74 --- /dev/null +++ b/node_modules/cross-spawn/lib/parse.js @@ -0,0 +1,91 @@ +'use strict'; + +const path = require('path'); +const resolveCommand = require('./util/resolveCommand'); +const escape = require('./util/escape'); +const readShebang = require('./util/readShebang'); + +const isWin = process.platform === 'win32'; +const isExecutableRegExp = /\.(?:com|exe)$/i; +const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; + +function detectShebang(parsed) { + parsed.file = resolveCommand(parsed); + + const shebang = parsed.file && readShebang(parsed.file); + + if (shebang) { + parsed.args.unshift(parsed.file); + parsed.command = shebang; + + return resolveCommand(parsed); + } + + return parsed.file; +} + +function parseNonShell(parsed) { + if (!isWin) { + return parsed; + } + + // Detect & add support for shebangs + const commandFile = detectShebang(parsed); + + // We don't need a shell if the command filename is an executable + const needsShell = !isExecutableRegExp.test(commandFile); + + // If a shell is required, use cmd.exe and take care of escaping everything correctly + // Note that `forceShell` is an hidden option used only in tests + if (parsed.options.forceShell || needsShell) { + // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` + // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument + // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, + // we need to double escape them + const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); + + // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) + // This is necessary otherwise it will always fail with ENOENT in those cases + parsed.command = path.normalize(parsed.command); + + // Escape command & arguments + parsed.command = escape.command(parsed.command); + parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); + + const shellCommand = [parsed.command].concat(parsed.args).join(' '); + + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.command = process.env.comspec || 'cmd.exe'; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + } + + return parsed; +} + +function parse(command, args, options) { + // Normalize arguments, similar to nodejs + if (args && !Array.isArray(args)) { + options = args; + args = null; + } + + args = args ? args.slice(0) : []; // Clone array to avoid changing the original + options = Object.assign({}, options); // Clone object to avoid changing the original + + // Build our parsed object + const parsed = { + command, + args, + options, + file: undefined, + original: { + command, + args, + }, + }; + + // Delegate further parsing to shell or non-shell + return options.shell ? parsed : parseNonShell(parsed); +} + +module.exports = parse; diff --git a/node_modules/cross-spawn/lib/util/escape.js b/node_modules/cross-spawn/lib/util/escape.js new file mode 100644 index 0000000..7bf2905 --- /dev/null +++ b/node_modules/cross-spawn/lib/util/escape.js @@ -0,0 +1,47 @@ +'use strict'; + +// See http://www.robvanderwoude.com/escapechars.php +const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; + +function escapeCommand(arg) { + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + return arg; +} + +function escapeArgument(arg, doubleEscapeMetaChars) { + // Convert to string + arg = `${arg}`; + + // Algorithm below is based on https://qntm.org/cmd + // It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input + // Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information + + // Sequence of backslashes followed by a double quote: + // double up all the backslashes and escape the double quote + arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"'); + + // Sequence of backslashes followed by the end of the string + // (which will become a double quote later): + // double up all the backslashes + arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1'); + + // All other backslashes occur literally + + // Quote the whole thing: + arg = `"${arg}"`; + + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + // Double escape meta chars if necessary + if (doubleEscapeMetaChars) { + arg = arg.replace(metaCharsRegExp, '^$1'); + } + + return arg; +} + +module.exports.command = escapeCommand; +module.exports.argument = escapeArgument; diff --git a/node_modules/cross-spawn/lib/util/readShebang.js b/node_modules/cross-spawn/lib/util/readShebang.js new file mode 100644 index 0000000..5e83733 --- /dev/null +++ b/node_modules/cross-spawn/lib/util/readShebang.js @@ -0,0 +1,23 @@ +'use strict'; + +const fs = require('fs'); +const shebangCommand = require('shebang-command'); + +function readShebang(command) { + // Read the first 150 bytes from the file + const size = 150; + const buffer = Buffer.alloc(size); + + let fd; + + try { + fd = fs.openSync(command, 'r'); + fs.readSync(fd, buffer, 0, size, 0); + fs.closeSync(fd); + } catch (e) { /* Empty */ } + + // Attempt to extract shebang (null is returned if not a shebang) + return shebangCommand(buffer.toString()); +} + +module.exports = readShebang; diff --git a/node_modules/cross-spawn/lib/util/resolveCommand.js b/node_modules/cross-spawn/lib/util/resolveCommand.js new file mode 100644 index 0000000..7972455 --- /dev/null +++ b/node_modules/cross-spawn/lib/util/resolveCommand.js @@ -0,0 +1,52 @@ +'use strict'; + +const path = require('path'); +const which = require('which'); +const getPathKey = require('path-key'); + +function resolveCommandAttempt(parsed, withoutPathExt) { + const env = parsed.options.env || process.env; + const cwd = process.cwd(); + const hasCustomCwd = parsed.options.cwd != null; + // Worker threads do not have process.chdir() + const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; + + // If a custom `cwd` was specified, we need to change the process cwd + // because `which` will do stat calls but does not support a custom cwd + if (shouldSwitchCwd) { + try { + process.chdir(parsed.options.cwd); + } catch (err) { + /* Empty */ + } + } + + let resolved; + + try { + resolved = which.sync(parsed.command, { + path: env[getPathKey({ env })], + pathExt: withoutPathExt ? path.delimiter : undefined, + }); + } catch (e) { + /* Empty */ + } finally { + if (shouldSwitchCwd) { + process.chdir(cwd); + } + } + + // If we successfully resolved, ensure that an absolute path is returned + // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it + if (resolved) { + resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); + } + + return resolved; +} + +function resolveCommand(parsed) { + return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); +} + +module.exports = resolveCommand; diff --git a/node_modules/cross-spawn/package.json b/node_modules/cross-spawn/package.json new file mode 100644 index 0000000..24b2eb4 --- /dev/null +++ b/node_modules/cross-spawn/package.json @@ -0,0 +1,73 @@ +{ + "name": "cross-spawn", + "version": "7.0.6", + "description": "Cross platform child_process#spawn and child_process#spawnSync", + "keywords": [ + "spawn", + "spawnSync", + "windows", + "cross-platform", + "path-ext", + "shebang", + "cmd", + "execute" + ], + "author": "André Cruz ", + "homepage": "https://github.com/moxystudio/node-cross-spawn", + "repository": { + "type": "git", + "url": "git@github.com:moxystudio/node-cross-spawn.git" + }, + "license": "MIT", + "main": "index.js", + "files": [ + "lib" + ], + "scripts": { + "lint": "eslint .", + "test": "jest --env node --coverage", + "prerelease": "npm t && npm run lint", + "release": "standard-version", + "postrelease": "git push --follow-tags origin HEAD && npm publish" + }, + "husky": { + "hooks": { + "commit-msg": "commitlint -E HUSKY_GIT_PARAMS", + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "*.js": [ + "eslint --fix", + "git add" + ] + }, + "commitlint": { + "extends": [ + "@commitlint/config-conventional" + ] + }, + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "devDependencies": { + "@commitlint/cli": "^8.1.0", + "@commitlint/config-conventional": "^8.1.0", + "babel-core": "^6.26.3", + "babel-jest": "^24.9.0", + "babel-preset-moxy": "^3.1.0", + "eslint": "^5.16.0", + "eslint-config-moxy": "^7.1.0", + "husky": "^3.0.5", + "jest": "^24.9.0", + "lint-staged": "^9.2.5", + "mkdirp": "^0.5.1", + "rimraf": "^3.0.0", + "standard-version": "^9.5.0" + }, + "engines": { + "node": ">= 8" + } +} diff --git a/node_modules/cssesc/LICENSE-MIT.txt b/node_modules/cssesc/LICENSE-MIT.txt new file mode 100644 index 0000000..a41e0a7 --- /dev/null +++ b/node_modules/cssesc/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/cssesc/README.md b/node_modules/cssesc/README.md new file mode 100644 index 0000000..58fb8fe --- /dev/null +++ b/node_modules/cssesc/README.md @@ -0,0 +1,201 @@ +# cssesc [![Build status](https://travis-ci.org/mathiasbynens/cssesc.svg?branch=master)](https://travis-ci.org/mathiasbynens/cssesc) [![Code coverage status](https://img.shields.io/codecov/c/github/mathiasbynens/cssesc.svg)](https://codecov.io/gh/mathiasbynens/cssesc) + +A JavaScript library for escaping CSS strings and identifiers while generating the shortest possible ASCII-only output. + +This is a JavaScript library for [escaping text for use in CSS strings or identifiers](https://mathiasbynens.be/notes/css-escapes) while generating the shortest possible valid ASCII-only output. [Here’s an online demo.](https://mothereff.in/css-escapes) + +[A polyfill for the CSSOM `CSS.escape()` method is available in a separate repository.](https://mths.be/cssescape) (In comparison, _cssesc_ is much more powerful.) + +Feel free to fork if you see possible improvements! + +## Installation + +Via [npm](https://www.npmjs.com/): + +```bash +npm install cssesc +``` + +In a browser: + +```html + +``` + +In [Node.js](https://nodejs.org/): + +```js +const cssesc = require('cssesc'); +``` + +In Ruby using [the `ruby-cssesc` wrapper gem](https://github.com/borodean/ruby-cssesc): + +```bash +gem install ruby-cssesc +``` + +```ruby +require 'ruby-cssesc' +CSSEsc.escape('I ♥ Ruby', is_identifier: true) +``` + +In Sass using [`sassy-escape`](https://github.com/borodean/sassy-escape): + +```bash +gem install sassy-escape +``` + +```scss +body { + content: escape('I ♥ Sass', $is-identifier: true); +} +``` + +## API + +### `cssesc(value, options)` + +This function takes a value and returns an escaped version of the value where any characters that are not printable ASCII symbols are escaped using the shortest possible (but valid) [escape sequences for use in CSS strings or identifiers](https://mathiasbynens.be/notes/css-escapes). + +```js +cssesc('Ich ♥ Bücher'); +// → 'Ich \\2665 B\\FC cher' + +cssesc('foo 𝌆 bar'); +// → 'foo \\1D306 bar' +``` + +By default, `cssesc` returns a string that can be used as part of a CSS string. If the target is a CSS identifier rather than a CSS string, use the `isIdentifier: true` setting (see below). + +The optional `options` argument accepts an object with the following options: + +#### `isIdentifier` + +The default value for the `isIdentifier` option is `false`. This means that the input text will be escaped for use in a CSS string literal. If you want to use the result as a CSS identifier instead (in a selector, for example), set this option to `true`. + +```js +cssesc('123a2b'); +// → '123a2b' + +cssesc('123a2b', { + 'isIdentifier': true +}); +// → '\\31 23a2b' +``` + +#### `quotes` + +The default value for the `quotes` option is `'single'`. This means that any occurences of `'` in the input text will be escaped as `\'`, so that the output can be used in a CSS string literal wrapped in single quotes. + +```js +cssesc('Lorem ipsum "dolor" sit \'amet\' etc.'); +// → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.' +// → "Lorem ipsum \"dolor\" sit \\'amet\\' etc." + +cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', { + 'quotes': 'single' +}); +// → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.' +// → "Lorem ipsum \"dolor\" sit \\'amet\\' etc." +``` + +If you want to use the output as part of a CSS string literal wrapped in double quotes, set the `quotes` option to `'double'`. + +```js +cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', { + 'quotes': 'double' +}); +// → 'Lorem ipsum \\"dolor\\" sit \'amet\' etc.' +// → "Lorem ipsum \\\"dolor\\\" sit 'amet' etc." +``` + +#### `wrap` + +The `wrap` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output will be a valid CSS string literal wrapped in quotes. The type of quotes can be specified through the `quotes` setting. + +```js +cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', { + 'quotes': 'single', + 'wrap': true +}); +// → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\'' +// → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'" + +cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', { + 'quotes': 'double', + 'wrap': true +}); +// → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."' +// → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\"" +``` + +#### `escapeEverything` + +The `escapeEverything` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, all the symbols in the output will be escaped, even printable ASCII symbols. + +```js +cssesc('lolwat"foo\'bar', { + 'escapeEverything': true +}); +// → '\\6C\\6F\\6C\\77\\61\\74\\"\\66\\6F\\6F\\\'\\62\\61\\72' +// → "\\6C\\6F\\6C\\77\\61\\74\\\"\\66\\6F\\6F\\'\\62\\61\\72" +``` + +#### Overriding the default options globally + +The global default settings can be overridden by modifying the `css.options` object. This saves you from passing in an `options` object for every call to `encode` if you want to use the non-default setting. + +```js +// Read the global default setting for `escapeEverything`: +cssesc.options.escapeEverything; +// → `false` by default + +// Override the global default setting for `escapeEverything`: +cssesc.options.escapeEverything = true; + +// Using the global default setting for `escapeEverything`, which is now `true`: +cssesc('foo © bar ≠ baz 𝌆 qux'); +// → '\\66\\6F\\6F\\ \\A9\\ \\62\\61\\72\\ \\2260\\ \\62\\61\\7A\\ \\1D306\\ \\71\\75\\78' +``` + +### `cssesc.version` + +A string representing the semantic version number. + +### Using the `cssesc` binary + +To use the `cssesc` binary in your shell, simply install cssesc globally using npm: + +```bash +npm install -g cssesc +``` + +After that you will be able to escape text for use in CSS strings or identifiers from the command line: + +```bash +$ cssesc 'föo ♥ bår 𝌆 baz' +f\F6o \2665 b\E5r \1D306 baz +``` + +If the output needs to be a CSS identifier rather than part of a string literal, use the `-i`/`--identifier` option: + +```bash +$ cssesc --identifier 'föo ♥ bår 𝌆 baz' +f\F6o\ \2665\ b\E5r\ \1D306\ baz +``` + +See `cssesc --help` for the full list of options. + +## Support + +This library supports the Node.js and browser versions mentioned in [`.babelrc`](https://github.com/mathiasbynens/cssesc/blob/master/.babelrc). For a version that supports a wider variety of legacy browsers and environments out-of-the-box, [see v0.1.0](https://github.com/mathiasbynens/cssesc/releases/tag/v0.1.0). + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## License + +This library is available under the [MIT](https://mths.be/mit) license. diff --git a/node_modules/cssesc/bin/cssesc b/node_modules/cssesc/bin/cssesc new file mode 100644 index 0000000..188c034 --- /dev/null +++ b/node_modules/cssesc/bin/cssesc @@ -0,0 +1,116 @@ +#!/usr/bin/env node +const fs = require('fs'); +const cssesc = require('../cssesc.js'); +const strings = process.argv.splice(2); +const stdin = process.stdin; +const options = {}; +const log = console.log; + +const main = function() { + const option = strings[0]; + + if (/^(?:-h|--help|undefined)$/.test(option)) { + log( + 'cssesc v%s - https://mths.be/cssesc', + cssesc.version + ); + log([ + '\nUsage:\n', + '\tcssesc [string]', + '\tcssesc [-i | --identifier] [string]', + '\tcssesc [-s | --single-quotes] [string]', + '\tcssesc [-d | --double-quotes] [string]', + '\tcssesc [-w | --wrap] [string]', + '\tcssesc [-e | --escape-everything] [string]', + '\tcssesc [-v | --version]', + '\tcssesc [-h | --help]', + '\nExamples:\n', + '\tcssesc \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'', + '\tcssesc --identifier \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'', + '\tcssesc --escape-everything \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'', + '\tcssesc --double-quotes --wrap \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'', + '\techo \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\' | cssesc' + ].join('\n')); + return process.exit(1); + } + + if (/^(?:-v|--version)$/.test(option)) { + log('v%s', cssesc.version); + return process.exit(1); + } + + strings.forEach(function(string) { + // Process options + if (/^(?:-i|--identifier)$/.test(string)) { + options.isIdentifier = true; + return; + } + if (/^(?:-s|--single-quotes)$/.test(string)) { + options.quotes = 'single'; + return; + } + if (/^(?:-d|--double-quotes)$/.test(string)) { + options.quotes = 'double'; + return; + } + if (/^(?:-w|--wrap)$/.test(string)) { + options.wrap = true; + return; + } + if (/^(?:-e|--escape-everything)$/.test(string)) { + options.escapeEverything = true; + return; + } + + // Process string(s) + let result; + try { + result = cssesc(string, options); + log(result); + } catch (exception) { + log(exception.message + '\n'); + log('Error: failed to escape.'); + log('If you think this is a bug in cssesc, please report it:'); + log('https://github.com/mathiasbynens/cssesc/issues/new'); + log( + '\nStack trace using cssesc@%s:\n', + cssesc.version + ); + log(exception.stack); + return process.exit(1); + } + }); + // Return with exit status 0 outside of the `forEach` loop, in case + // multiple strings were passed in. + return process.exit(0); + +}; + +if (stdin.isTTY) { + // handle shell arguments + main(); +} else { + let timeout; + // Either the script is called from within a non-TTY context, or `stdin` + // content is being piped in. + if (!process.stdout.isTTY) { + // The script was called from a non-TTY context. This is a rather uncommon + // use case we don’t actively support. However, we don’t want the script + // to wait forever in such cases, so… + timeout = setTimeout(function() { + // …if no piped data arrived after a whole minute, handle shell + // arguments instead. + main(); + }, 60000); + } + let data = ''; + stdin.on('data', function(chunk) { + clearTimeout(timeout); + data += chunk; + }); + stdin.on('end', function() { + strings.push(data.trim()); + main(); + }); + stdin.resume(); +} diff --git a/node_modules/cssesc/cssesc.js b/node_modules/cssesc/cssesc.js new file mode 100644 index 0000000..1c0928e --- /dev/null +++ b/node_modules/cssesc/cssesc.js @@ -0,0 +1,110 @@ +/*! https://mths.be/cssesc v3.0.0 by @mathias */ +'use strict'; + +var object = {}; +var hasOwnProperty = object.hasOwnProperty; +var merge = function merge(options, defaults) { + if (!options) { + return defaults; + } + var result = {}; + for (var key in defaults) { + // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since + // only recognized option names are used. + result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key]; + } + return result; +}; + +var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/; +var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/; +var regexAlwaysEscape = /['"\\]/; +var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g; + +// https://mathiasbynens.be/notes/css-escapes#css +var cssesc = function cssesc(string, options) { + options = merge(options, cssesc.options); + if (options.quotes != 'single' && options.quotes != 'double') { + options.quotes = 'single'; + } + var quote = options.quotes == 'double' ? '"' : '\''; + var isIdentifier = options.isIdentifier; + + var firstChar = string.charAt(0); + var output = ''; + var counter = 0; + var length = string.length; + while (counter < length) { + var character = string.charAt(counter++); + var codePoint = character.charCodeAt(); + var value = void 0; + // If it’s not a printable ASCII character… + if (codePoint < 0x20 || codePoint > 0x7E) { + if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) { + // It’s a high surrogate, and there is a next character. + var extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { + // next character is low surrogate + codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000; + } else { + // It’s an unmatched surrogate; only append this code unit, in case + // the next code unit is the high surrogate of a surrogate pair. + counter--; + } + } + value = '\\' + codePoint.toString(16).toUpperCase() + ' '; + } else { + if (options.escapeEverything) { + if (regexAnySingleEscape.test(character)) { + value = '\\' + character; + } else { + value = '\\' + codePoint.toString(16).toUpperCase() + ' '; + } + } else if (/[\t\n\f\r\x0B]/.test(character)) { + value = '\\' + codePoint.toString(16).toUpperCase() + ' '; + } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) { + value = '\\' + character; + } else { + value = character; + } + } + output += value; + } + + if (isIdentifier) { + if (/^-[-\d]/.test(output)) { + output = '\\-' + output.slice(1); + } else if (/\d/.test(firstChar)) { + output = '\\3' + firstChar + ' ' + output.slice(1); + } + } + + // Remove spaces after `\HEX` escapes that are not followed by a hex digit, + // since they’re redundant. Note that this is only possible if the escape + // sequence isn’t preceded by an odd number of backslashes. + output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) { + if ($1 && $1.length % 2) { + // It’s not safe to remove the space, so don’t. + return $0; + } + // Strip the space. + return ($1 || '') + $2; + }); + + if (!isIdentifier && options.wrap) { + return quote + output + quote; + } + return output; +}; + +// Expose default options (so they can be overridden globally). +cssesc.options = { + 'escapeEverything': false, + 'isIdentifier': false, + 'quotes': 'single', + 'wrap': false +}; + +cssesc.version = '3.0.0'; + +module.exports = cssesc; diff --git a/node_modules/cssesc/man/cssesc.1 b/node_modules/cssesc/man/cssesc.1 new file mode 100644 index 0000000..eee4996 --- /dev/null +++ b/node_modules/cssesc/man/cssesc.1 @@ -0,0 +1,70 @@ +.Dd August 9, 2013 +.Dt cssesc 1 +.Sh NAME +.Nm cssesc +.Nd escape text for use in CSS string literals or identifiers +.Sh SYNOPSIS +.Nm +.Op Fl i | -identifier Ar string +.br +.Op Fl s | -single-quotes Ar string +.br +.Op Fl d | -double-quotes Ar string +.br +.Op Fl w | -wrap Ar string +.br +.Op Fl e | -escape-everything Ar string +.br +.Op Fl v | -version +.br +.Op Fl h | -help +.Sh DESCRIPTION +.Nm +escapes strings for use in CSS string literals or identifiers while generating the shortest possible valid ASCII-only output. +.Sh OPTIONS +.Bl -ohang -offset +.It Sy "-s, --single-quotes" +Escape any occurences of ' in the input string as \\', so that the output can be used in a CSS string literal wrapped in single quotes. +.It Sy "-d, --double-quotes" +Escape any occurences of " in the input string as \\", so that the output can be used in a CSS string literal wrapped in double quotes. +.It Sy "-w, --wrap" +Make sure the output is a valid CSS string literal wrapped in quotes. The type of quotes can be specified using the +.Ar -s | --single-quotes +or +.Ar -d | --double-quotes +settings. +.It Sy "-e, --escape-everything" +Escape all the symbols in the output, even printable ASCII symbols. +.It Sy "-v, --version" +Print cssesc's version. +.It Sy "-h, --help" +Show the help screen. +.El +.Sh EXIT STATUS +The +.Nm cssesc +utility exits with one of the following values: +.Pp +.Bl -tag -width flag -compact +.It Li 0 +.Nm +successfully escaped the given text and printed the result. +.It Li 1 +.Nm +wasn't instructed to escape anything (for example, the +.Ar --help +flag was set); or, an error occurred. +.El +.Sh EXAMPLES +.Bl -ohang -offset +.It Sy "cssesc 'foo bar baz'" +Print an escaped version of the given text. +.It Sy echo\ 'foo bar baz'\ |\ cssesc +Print an escaped version of the text that gets piped in. +.El +.Sh BUGS +cssesc's bug tracker is located at . +.Sh AUTHOR +Mathias Bynens +.Sh WWW + diff --git a/node_modules/cssesc/package.json b/node_modules/cssesc/package.json new file mode 100644 index 0000000..076c84d --- /dev/null +++ b/node_modules/cssesc/package.json @@ -0,0 +1,51 @@ +{ + "name": "cssesc", + "version": "3.0.0", + "description": "A JavaScript library for escaping CSS strings and identifiers while generating the shortest possible ASCII-only output.", + "homepage": "https://mths.be/cssesc", + "engines": { + "node": ">=4" + }, + "main": "cssesc.js", + "bin": "bin/cssesc", + "man": "man/cssesc.1", + "keywords": [ + "css", + "escape", + "identifier", + "string", + "tool" + ], + "license": "MIT", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "repository": { + "type": "git", + "url": "https://github.com/mathiasbynens/cssesc.git" + }, + "bugs": "https://github.com/mathiasbynens/cssesc/issues", + "files": [ + "LICENSE-MIT.txt", + "cssesc.js", + "bin/", + "man/" + ], + "scripts": { + "build": "grunt template && babel cssesc.js -o cssesc.js", + "test": "mocha tests", + "cover": "istanbul cover --report html node_modules/.bin/_mocha tests -- -u exports -R spec" + }, + "devDependencies": { + "babel-cli": "^6.26.0", + "babel-preset-env": "^1.6.1", + "codecov": "^1.0.1", + "grunt": "^1.0.1", + "grunt-template": "^1.0.0", + "istanbul": "^0.4.4", + "mocha": "^2.5.3", + "regenerate": "^1.2.1", + "requirejs": "^2.1.16" + } +} diff --git a/node_modules/didyoumean/LICENSE b/node_modules/didyoumean/LICENSE new file mode 100644 index 0000000..32c23db --- /dev/null +++ b/node_modules/didyoumean/LICENSE @@ -0,0 +1,14 @@ +## License + +didYouMean.js copyright (c) 2013 Dave Porter. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License +[here](http://www.apache.org/licenses/LICENSE-2.0). + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/node_modules/didyoumean/README.md b/node_modules/didyoumean/README.md new file mode 100644 index 0000000..cd16698 --- /dev/null +++ b/node_modules/didyoumean/README.md @@ -0,0 +1,134 @@ +didYouMean.js - A simple JavaScript matching engine +=================================================== + +[Available on GitHub](https://github.com/dcporter/didyoumean.js). + +A super-simple, highly optimized JS library for matching human-quality input to a list of potential +matches. You can use it to suggest a misspelled command-line utility option to a user, or to offer +links to nearby valid URLs on your 404 page. (The examples below are taken from a personal project, +my [HTML5 business card](http://dcporter.aws.af.cm/me), which uses didYouMean.js to suggest correct +URLs from misspelled ones, such as [dcporter.aws.af.cm/me/instagarm](http://dcporter.aws.af.cm/me/instagarm).) +Uses the [Levenshtein distance algorithm](https://en.wikipedia.org/wiki/Levenshtein_distance). + +didYouMean.js works in the browser as well as in node.js. To install it for use in node: + +``` +npm install didyoumean +``` + + +Examples +-------- + +Matching against a list of strings: +``` +var input = 'insargrm' +var list = ['facebook', 'twitter', 'instagram', 'linkedin']; +console.log(didYouMean(input, list)); +> 'instagram' +// The method matches 'insargrm' to 'instagram'. + +input = 'google plus'; +console.log(didYouMean(input, list)); +> null +// The method was unable to find 'google plus' in the list of options. +``` + +Matching against a list of objects: +``` +var input = 'insargrm'; +var list = [ { id: 'facebook' }, { id: 'twitter' }, { id: 'instagram' }, { id: 'linkedin' } ]; +var key = 'id'; +console.log(didYouMean(input, list, key)); +> 'instagram' +// The method returns the matching value. + +didYouMean.returnWinningObject = true; +console.log(didYouMean(input, list, key)); +> { id: 'instagram' } +// The method returns the matching object. +``` + + +didYouMean(str, list, [key]) +---------------------------- + +- str: The string input to match. +- list: An array of strings or objects to match against. +- key (OPTIONAL): If your list array contains objects, you must specify the key which contains the string + to match against. + +Returns: the closest matching string, or null if no strings exceed the threshold. + + +Options +------- + +Options are set on the didYouMean function object. You may change them at any time. + +### threshold + + By default, the method will only return strings whose edit distance is less than 40% (0.4x) of their length. + For example, if a ten-letter string is five edits away from its nearest match, the method will return null. + + You can control this by setting the "threshold" value on the didYouMean function. For example, to set the + edit distance threshold to 50% of the input string's length: + + ``` + didYouMean.threshold = 0.5; + ``` + + To return the nearest match no matter the threshold, set this value to null. + +### thresholdAbsolute + + This option behaves the same as threshold, but instead takes an integer number of edit steps. For example, + if thresholdAbsolute is set to 20 (the default), then the method will only return strings whose edit distance + is less than 20. Both options apply. + +### caseSensitive + + By default, the method will perform case-insensitive comparisons. If you wish to force case sensitivity, set + the "caseSensitive" value to true: + + ``` + didYouMean.caseSensitive = true; + ``` + +### nullResultValue + + By default, the method will return null if there is no sufficiently close match. You can change this value here. + +### returnWinningObject + + By default, the method will return the winning string value (if any). If your list contains objects rather + than strings, you may set returnWinningObject to true. + + ``` + didYouMean.returnWinningObject = true; + ``` + + This option has no effect on lists of strings. + +### returnFirstMatch + + By default, the method will search all values and return the closest match. If you're simply looking for a "good- + enough" match, you can set your thresholds appropriately and set returnFirstMatch to true to substantially speed + things up. + + +License +------- + +didYouMean copyright (c) 2013-2014 Dave Porter. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License +[here](http://www.apache.org/licenses/LICENSE-2.0). + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/node_modules/didyoumean/didYouMean-1.2.1.js b/node_modules/didyoumean/didYouMean-1.2.1.js new file mode 100644 index 0000000..febb30e --- /dev/null +++ b/node_modules/didyoumean/didYouMean-1.2.1.js @@ -0,0 +1,274 @@ +/* + +didYouMean.js - A simple JavaScript matching engine +=================================================== + +[Available on GitHub](https://github.com/dcporter/didyoumean.js). + +A super-simple, highly optimized JS library for matching human-quality input to a list of potential +matches. You can use it to suggest a misspelled command-line utility option to a user, or to offer +links to nearby valid URLs on your 404 page. (The examples below are taken from a personal project, +my [HTML5 business card](http://dcporter.aws.af.cm/me), which uses didYouMean.js to suggest correct +URLs from misspelled ones, such as [dcporter.aws.af.cm/me/instagarm](http://dcporter.aws.af.cm/me/instagarm).) +Uses the [Levenshtein distance algorithm](https://en.wikipedia.org/wiki/Levenshtein_distance). + +didYouMean.js works in the browser as well as in node.js. To install it for use in node: + +``` +npm install didyoumean +``` + + +Examples +-------- + +Matching against a list of strings: +``` +var input = 'insargrm' +var list = ['facebook', 'twitter', 'instagram', 'linkedin']; +console.log(didYouMean(input, list)); +> 'instagram' +// The method matches 'insargrm' to 'instagram'. + +input = 'google plus'; +console.log(didYouMean(input, list)); +> null +// The method was unable to find 'google plus' in the list of options. +``` + +Matching against a list of objects: +``` +var input = 'insargrm'; +var list = [ { id: 'facebook' }, { id: 'twitter' }, { id: 'instagram' }, { id: 'linkedin' } ]; +var key = 'id'; +console.log(didYouMean(input, list, key)); +> 'instagram' +// The method returns the matching value. + +didYouMean.returnWinningObject = true; +console.log(didYouMean(input, list, key)); +> { id: 'instagram' } +// The method returns the matching object. +``` + + +didYouMean(str, list, [key]) +---------------------------- + +- str: The string input to match. +- list: An array of strings or objects to match against. +- key (OPTIONAL): If your list array contains objects, you must specify the key which contains the string + to match against. + +Returns: the closest matching string, or null if no strings exceed the threshold. + + +Options +------- + +Options are set on the didYouMean function object. You may change them at any time. + +### threshold + + By default, the method will only return strings whose edit distance is less than 40% (0.4x) of their length. + For example, if a ten-letter string is five edits away from its nearest match, the method will return null. + + You can control this by setting the "threshold" value on the didYouMean function. For example, to set the + edit distance threshold to 50% of the input string's length: + + ``` + didYouMean.threshold = 0.5; + ``` + + To return the nearest match no matter the threshold, set this value to null. + +### thresholdAbsolute + + This option behaves the same as threshold, but instead takes an integer number of edit steps. For example, + if thresholdAbsolute is set to 20 (the default), then the method will only return strings whose edit distance + is less than 20. Both options apply. + +### caseSensitive + + By default, the method will perform case-insensitive comparisons. If you wish to force case sensitivity, set + the "caseSensitive" value to true: + + ``` + didYouMean.caseSensitive = true; + ``` + +### nullResultValue + + By default, the method will return null if there is no sufficiently close match. You can change this value here. + +### returnWinningObject + + By default, the method will return the winning string value (if any). If your list contains objects rather + than strings, you may set returnWinningObject to true. + + ``` + didYouMean.returnWinningObject = true; + ``` + + This option has no effect on lists of strings. + +### returnFirstMatch + + By default, the method will search all values and return the closest match. If you're simply looking for a "good- + enough" match, you can set your thresholds appropriately and set returnFirstMatch to true to substantially speed + things up. + + +License +------- + +didYouMean copyright (c) 2013-2014 Dave Porter. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License +[here](http://www.apache.org/licenses/LICENSE-2.0). + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +*/ +(function() { + "use strict"; + + // The didYouMean method. + function didYouMean(str, list, key) { + if (!str) return null; + + // If we're running a case-insensitive search, smallify str. + if (!didYouMean.caseSensitive) { str = str.toLowerCase(); } + + // Calculate the initial value (the threshold) if present. + var thresholdRelative = didYouMean.threshold === null ? null : didYouMean.threshold * str.length, + thresholdAbsolute = didYouMean.thresholdAbsolute, + winningVal; + if (thresholdRelative !== null && thresholdAbsolute !== null) winningVal = Math.min(thresholdRelative, thresholdAbsolute); + else if (thresholdRelative !== null) winningVal = thresholdRelative; + else if (thresholdAbsolute !== null) winningVal = thresholdAbsolute; + else winningVal = null; + + // Get the edit distance to each option. If the closest one is less than 40% (by default) of str's length, + // then return it. + var winner, candidate, testCandidate, val, + i, len = list.length; + for (i = 0; i < len; i++) { + // Get item. + candidate = list[i]; + // If there's a key, get the candidate value out of the object. + if (key) { candidate = candidate[key]; } + // Gatekeep. + if (!candidate) { continue; } + // If we're running a case-insensitive search, smallify the candidate. + if (!didYouMean.caseSensitive) { testCandidate = candidate.toLowerCase(); } + else { testCandidate = candidate; } + // Get and compare edit distance. + val = getEditDistance(str, testCandidate, winningVal); + // If this value is smaller than our current winning value, OR if we have no winning val yet (i.e. the + // threshold option is set to null, meaning the caller wants a match back no matter how bad it is), then + // this is our new winner. + if (winningVal === null || val < winningVal) { + winningVal = val; + // Set the winner to either the value or its object, depending on the returnWinningObject option. + if (key && didYouMean.returnWinningObject) winner = list[i]; + else winner = candidate; + // If we're returning the first match, return it now. + if (didYouMean.returnFirstMatch) return winner; + } + } + + // If we have a winner, return it. + return winner || didYouMean.nullResultValue; + } + + // Set default options. + didYouMean.threshold = 0.4; + didYouMean.thresholdAbsolute = 20; + didYouMean.caseSensitive = false; + didYouMean.nullResultValue = null; + didYouMean.returnWinningObject = null; + didYouMean.returnFirstMatch = false; + + // Expose. + // In node... + if (typeof module !== 'undefined' && module.exports) { + module.exports = didYouMean; + } + // Otherwise... + else { + window.didYouMean = didYouMean; + } + + var MAX_INT = Math.pow(2,32) - 1; // We could probably go higher than this, but for practical reasons let's not. + function getEditDistance(a, b, max) { + // Handle null or undefined max. + max = max || max === 0 ? max : MAX_INT; + + var lena = a.length; + var lenb = b.length; + + // Fast path - no A or B. + if (lena === 0) return Math.min(max + 1, lenb); + if (lenb === 0) return Math.min(max + 1, lena); + + // Fast path - length diff larger than max. + if (Math.abs(lena - lenb) > max) return max + 1; + + // Slow path. + var matrix = [], + i, j, colMin, minJ, maxJ; + + // Set up the first row ([0, 1, 2, 3, etc]). + for (i = 0; i <= lenb; i++) { matrix[i] = [i]; } + + // Set up the first column (same). + for (j = 0; j <= lena; j++) { matrix[0][j] = j; } + + // Loop over the rest of the columns. + for (i = 1; i <= lenb; i++) { + colMin = MAX_INT; + minJ = 1; + if (i > max) minJ = i - max; + maxJ = lenb + 1; + if (maxJ > max + i) maxJ = max + i; + // Loop over the rest of the rows. + for (j = 1; j <= lena; j++) { + // If j is out of bounds, just put a large value in the slot. + if (j < minJ || j > maxJ) { + matrix[i][j] = max + 1; + } + + // Otherwise do the normal Levenshtein thing. + else { + // If the characters are the same, there's no change in edit distance. + if (b.charAt(i - 1) === a.charAt(j - 1)) { + matrix[i][j] = matrix[i - 1][j - 1]; + } + // Otherwise, see if we're substituting, inserting or deleting. + else { + matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // Substitute + Math.min(matrix[i][j - 1] + 1, // Insert + matrix[i - 1][j] + 1)); // Delete + } + } + + // Either way, update colMin. + if (matrix[i][j] < colMin) colMin = matrix[i][j]; + } + + // If this column's minimum is greater than the allowed maximum, there's no point + // in going on with life. + if (colMin > max) return max + 1; + } + // If we made it this far without running into the max, then return the final matrix value. + return matrix[lenb][lena]; + } + +})(); diff --git a/node_modules/didyoumean/didYouMean-1.2.1.min.js b/node_modules/didyoumean/didYouMean-1.2.1.min.js new file mode 100644 index 0000000..c41abd8 --- /dev/null +++ b/node_modules/didyoumean/didYouMean-1.2.1.min.js @@ -0,0 +1,17 @@ +/* + didYouMean.js copyright (c) 2013-2014 Dave Porter. + + [Available on GitHub](https://github.com/dcporter/didyoumean.js). + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License + [here](http://www.apache.org/licenses/LICENSE-2.0). + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +(function(){"use strict";function e(t,r,i){if(!t)return null;if(!e.caseSensitive){t=t.toLowerCase()}var s=e.threshold===null?null:e.threshold*t.length,o=e.thresholdAbsolute,u;if(s!==null&&o!==null)u=Math.min(s,o);else if(s!==null)u=s;else if(o!==null)u=o;else u=null;var a,f,l,c,h,p=r.length;for(h=0;hr)return r+1;var o=[],u,a,f,l,c;for(u=0;u<=s;u++){o[u]=[u]}for(a=0;a<=i;a++){o[0][a]=a}for(u=1;u<=s;u++){f=t;l=1;if(u>r)l=u-r;c=s+1;if(c>r+u)c=r+u;for(a=1;a<=i;a++){if(ac){o[u][a]=r+1}else{if(n.charAt(u-1)===e.charAt(a-1)){o[u][a]=o[u-1][a-1]}else{o[u][a]=Math.min(o[u-1][a-1]+1,Math.min(o[u][a-1]+1,o[u-1][a]+1))}}if(o[u][a]r)return r+1}return o[s][i]}e.threshold=.4;e.thresholdAbsolute=20;e.caseSensitive=false;e.nullResultValue=null;e.returnWinningObject=null;e.returnFirstMatch=false;if(typeof module!=="undefined"&&module.exports){module.exports=e}else{window.didYouMean=e}var t=Math.pow(2,32)-1})(); \ No newline at end of file diff --git a/node_modules/didyoumean/package.json b/node_modules/didyoumean/package.json new file mode 100644 index 0000000..1301d03 --- /dev/null +++ b/node_modules/didyoumean/package.json @@ -0,0 +1,27 @@ +{ + "name": "didyoumean", + "version": "1.2.2", + "description": "Match human-quality input to potential matches by edit distance.", + "homepage": "https://github.com/dcporter/didyoumean.js", + "author": { + "name": "Dave Porter", + "email": "dcporter@gmail.com", + "url": "http://dcporter.net/" + }, + "keywords": [ + "didyoumean", + "mean", + "edit", + "distance", + "levenshtein" + ], + "main": "./didYouMean-1.2.1.js", + "repository": { + "type": "git", + "url": "https://github.com/dcporter/didyoumean.js.git" + }, + "bugs": { + "url": "https://github.com/dcporter/didyoumean.js/issues" + }, + "license": "Apache-2.0" +} diff --git a/node_modules/dlv/README.md b/node_modules/dlv/README.md new file mode 100644 index 0000000..6a8429d --- /dev/null +++ b/node_modules/dlv/README.md @@ -0,0 +1,76 @@ +# `dlv(obj, keypath)` [![NPM](https://img.shields.io/npm/v/dlv.svg)](https://npmjs.com/package/dlv) [![Build](https://travis-ci.org/developit/dlv.svg?branch=master)](https://travis-ci.org/developit/dlv) + +> Safely get a dot-notated path within a nested object, with ability to return a default if the full key path does not exist or the value is undefined + + +### Why? + +Smallest possible implementation: only **130 bytes.** + +You could write this yourself, but then you'd have to write [tests]. + +Supports ES Modules, CommonJS and globals. + + +### Installation + +`npm install --save dlv` + + +### Usage + +`delve(object, keypath, [default])` + +```js +import delve from 'dlv'; + +let obj = { + a: { + b: { + c: 1, + d: undefined, + e: null + } + } +}; + +//use string dot notation for keys +delve(obj, 'a.b.c') === 1; + +//or use an array key +delve(obj, ['a', 'b', 'c']) === 1; + +delve(obj, 'a.b') === obj.a.b; + +//returns undefined if the full key path does not exist and no default is specified +delve(obj, 'a.b.f') === undefined; + +//optional third parameter for default if the full key in path is missing +delve(obj, 'a.b.f', 'foo') === 'foo'; + +//or if the key exists but the value is undefined +delve(obj, 'a.b.d', 'foo') === 'foo'; + +//Non-truthy defined values are still returned if they exist at the full keypath +delve(obj, 'a.b.e', 'foo') === null; + +//undefined obj or key returns undefined, unless a default is supplied +delve(undefined, 'a.b.c') === undefined; +delve(undefined, 'a.b.c', 'foo') === 'foo'; +delve(obj, undefined, 'foo') === 'foo'; +``` + + +### Setter Counterparts + +- [dset](https://github.com/lukeed/dset) by [@lukeed](https://github.com/lukeed) is the spiritual "set" counterpart of `dlv` and very fast. +- [bury](https://github.com/kalmbach/bury) by [@kalmbach](https://github.com/kalmbach) does the opposite of `dlv` and is implemented in a very similar manner. + + +### License + +[MIT](https://oss.ninja/mit/developit/) + + +[preact]: https://github.com/developit/preact +[tests]: https://github.com/developit/dlv/blob/master/test.js diff --git a/node_modules/dlv/dist/dlv.es.js b/node_modules/dlv/dist/dlv.es.js new file mode 100644 index 0000000..06b981b --- /dev/null +++ b/node_modules/dlv/dist/dlv.es.js @@ -0,0 +1,2 @@ +export default function(t,e,l,n,r){for(e=e.split?e.split("."):e,n=0;n (http://jasonformat.com)", + "repository": "developit/dlv", + "license": "MIT", + "devDependencies": { + "microbundle": "^0.11.0" + } +} diff --git a/node_modules/eastasianwidth/README.md b/node_modules/eastasianwidth/README.md new file mode 100644 index 0000000..a8b71ee --- /dev/null +++ b/node_modules/eastasianwidth/README.md @@ -0,0 +1,32 @@ +# East Asian Width + +Get [East Asian Width](http://www.unicode.org/reports/tr11/) from a character. + +'F'(Fullwidth), 'H'(Halfwidth), 'W'(Wide), 'Na'(Narrow), 'A'(Ambiguous) or 'N'(Natural). + +Original Code is [東アジアの文字幅 (East Asian Width) の判定 - 中途](http://d.hatena.ne.jp/takenspc/20111126#1322252878). + +## Install + + $ npm install eastasianwidth + +## Usage + + var eaw = require('eastasianwidth'); + console.log(eaw.eastAsianWidth('₩')) // 'F' + console.log(eaw.eastAsianWidth('。')) // 'H' + console.log(eaw.eastAsianWidth('뀀')) // 'W' + console.log(eaw.eastAsianWidth('a')) // 'Na' + console.log(eaw.eastAsianWidth('①')) // 'A' + console.log(eaw.eastAsianWidth('ف')) // 'N' + + console.log(eaw.characterLength('₩')) // 2 + console.log(eaw.characterLength('。')) // 1 + console.log(eaw.characterLength('뀀')) // 2 + console.log(eaw.characterLength('a')) // 1 + console.log(eaw.characterLength('①')) // 2 + console.log(eaw.characterLength('ف')) // 1 + + console.log(eaw.length('あいうえお')) // 10 + console.log(eaw.length('abcdefg')) // 7 + console.log(eaw.length('¢₩。ᅵㄅ뀀¢⟭a⊙①بف')) // 19 diff --git a/node_modules/eastasianwidth/eastasianwidth.js b/node_modules/eastasianwidth/eastasianwidth.js new file mode 100644 index 0000000..7d0aa0f --- /dev/null +++ b/node_modules/eastasianwidth/eastasianwidth.js @@ -0,0 +1,311 @@ +var eaw = {}; + +if ('undefined' == typeof module) { + window.eastasianwidth = eaw; +} else { + module.exports = eaw; +} + +eaw.eastAsianWidth = function(character) { + var x = character.charCodeAt(0); + var y = (character.length == 2) ? character.charCodeAt(1) : 0; + var codePoint = x; + if ((0xD800 <= x && x <= 0xDBFF) && (0xDC00 <= y && y <= 0xDFFF)) { + x &= 0x3FF; + y &= 0x3FF; + codePoint = (x << 10) | y; + codePoint += 0x10000; + } + + if ((0x3000 == codePoint) || + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6)) { + return 'F'; + } + if ((0x20A9 == codePoint) || + (0xFF61 <= codePoint && codePoint <= 0xFFBE) || + (0xFFC2 <= codePoint && codePoint <= 0xFFC7) || + (0xFFCA <= codePoint && codePoint <= 0xFFCF) || + (0xFFD2 <= codePoint && codePoint <= 0xFFD7) || + (0xFFDA <= codePoint && codePoint <= 0xFFDC) || + (0xFFE8 <= codePoint && codePoint <= 0xFFEE)) { + return 'H'; + } + if ((0x1100 <= codePoint && codePoint <= 0x115F) || + (0x11A3 <= codePoint && codePoint <= 0x11A7) || + (0x11FA <= codePoint && codePoint <= 0x11FF) || + (0x2329 <= codePoint && codePoint <= 0x232A) || + (0x2E80 <= codePoint && codePoint <= 0x2E99) || + (0x2E9B <= codePoint && codePoint <= 0x2EF3) || + (0x2F00 <= codePoint && codePoint <= 0x2FD5) || + (0x2FF0 <= codePoint && codePoint <= 0x2FFB) || + (0x3001 <= codePoint && codePoint <= 0x303E) || + (0x3041 <= codePoint && codePoint <= 0x3096) || + (0x3099 <= codePoint && codePoint <= 0x30FF) || + (0x3105 <= codePoint && codePoint <= 0x312D) || + (0x3131 <= codePoint && codePoint <= 0x318E) || + (0x3190 <= codePoint && codePoint <= 0x31BA) || + (0x31C0 <= codePoint && codePoint <= 0x31E3) || + (0x31F0 <= codePoint && codePoint <= 0x321E) || + (0x3220 <= codePoint && codePoint <= 0x3247) || + (0x3250 <= codePoint && codePoint <= 0x32FE) || + (0x3300 <= codePoint && codePoint <= 0x4DBF) || + (0x4E00 <= codePoint && codePoint <= 0xA48C) || + (0xA490 <= codePoint && codePoint <= 0xA4C6) || + (0xA960 <= codePoint && codePoint <= 0xA97C) || + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || + (0xD7B0 <= codePoint && codePoint <= 0xD7C6) || + (0xD7CB <= codePoint && codePoint <= 0xD7FB) || + (0xF900 <= codePoint && codePoint <= 0xFAFF) || + (0xFE10 <= codePoint && codePoint <= 0xFE19) || + (0xFE30 <= codePoint && codePoint <= 0xFE52) || + (0xFE54 <= codePoint && codePoint <= 0xFE66) || + (0xFE68 <= codePoint && codePoint <= 0xFE6B) || + (0x1B000 <= codePoint && codePoint <= 0x1B001) || + (0x1F200 <= codePoint && codePoint <= 0x1F202) || + (0x1F210 <= codePoint && codePoint <= 0x1F23A) || + (0x1F240 <= codePoint && codePoint <= 0x1F248) || + (0x1F250 <= codePoint && codePoint <= 0x1F251) || + (0x20000 <= codePoint && codePoint <= 0x2F73F) || + (0x2B740 <= codePoint && codePoint <= 0x2FFFD) || + (0x30000 <= codePoint && codePoint <= 0x3FFFD)) { + return 'W'; + } + if ((0x0020 <= codePoint && codePoint <= 0x007E) || + (0x00A2 <= codePoint && codePoint <= 0x00A3) || + (0x00A5 <= codePoint && codePoint <= 0x00A6) || + (0x00AC == codePoint) || + (0x00AF == codePoint) || + (0x27E6 <= codePoint && codePoint <= 0x27ED) || + (0x2985 <= codePoint && codePoint <= 0x2986)) { + return 'Na'; + } + if ((0x00A1 == codePoint) || + (0x00A4 == codePoint) || + (0x00A7 <= codePoint && codePoint <= 0x00A8) || + (0x00AA == codePoint) || + (0x00AD <= codePoint && codePoint <= 0x00AE) || + (0x00B0 <= codePoint && codePoint <= 0x00B4) || + (0x00B6 <= codePoint && codePoint <= 0x00BA) || + (0x00BC <= codePoint && codePoint <= 0x00BF) || + (0x00C6 == codePoint) || + (0x00D0 == codePoint) || + (0x00D7 <= codePoint && codePoint <= 0x00D8) || + (0x00DE <= codePoint && codePoint <= 0x00E1) || + (0x00E6 == codePoint) || + (0x00E8 <= codePoint && codePoint <= 0x00EA) || + (0x00EC <= codePoint && codePoint <= 0x00ED) || + (0x00F0 == codePoint) || + (0x00F2 <= codePoint && codePoint <= 0x00F3) || + (0x00F7 <= codePoint && codePoint <= 0x00FA) || + (0x00FC == codePoint) || + (0x00FE == codePoint) || + (0x0101 == codePoint) || + (0x0111 == codePoint) || + (0x0113 == codePoint) || + (0x011B == codePoint) || + (0x0126 <= codePoint && codePoint <= 0x0127) || + (0x012B == codePoint) || + (0x0131 <= codePoint && codePoint <= 0x0133) || + (0x0138 == codePoint) || + (0x013F <= codePoint && codePoint <= 0x0142) || + (0x0144 == codePoint) || + (0x0148 <= codePoint && codePoint <= 0x014B) || + (0x014D == codePoint) || + (0x0152 <= codePoint && codePoint <= 0x0153) || + (0x0166 <= codePoint && codePoint <= 0x0167) || + (0x016B == codePoint) || + (0x01CE == codePoint) || + (0x01D0 == codePoint) || + (0x01D2 == codePoint) || + (0x01D4 == codePoint) || + (0x01D6 == codePoint) || + (0x01D8 == codePoint) || + (0x01DA == codePoint) || + (0x01DC == codePoint) || + (0x0251 == codePoint) || + (0x0261 == codePoint) || + (0x02C4 == codePoint) || + (0x02C7 == codePoint) || + (0x02C9 <= codePoint && codePoint <= 0x02CB) || + (0x02CD == codePoint) || + (0x02D0 == codePoint) || + (0x02D8 <= codePoint && codePoint <= 0x02DB) || + (0x02DD == codePoint) || + (0x02DF == codePoint) || + (0x0300 <= codePoint && codePoint <= 0x036F) || + (0x0391 <= codePoint && codePoint <= 0x03A1) || + (0x03A3 <= codePoint && codePoint <= 0x03A9) || + (0x03B1 <= codePoint && codePoint <= 0x03C1) || + (0x03C3 <= codePoint && codePoint <= 0x03C9) || + (0x0401 == codePoint) || + (0x0410 <= codePoint && codePoint <= 0x044F) || + (0x0451 == codePoint) || + (0x2010 == codePoint) || + (0x2013 <= codePoint && codePoint <= 0x2016) || + (0x2018 <= codePoint && codePoint <= 0x2019) || + (0x201C <= codePoint && codePoint <= 0x201D) || + (0x2020 <= codePoint && codePoint <= 0x2022) || + (0x2024 <= codePoint && codePoint <= 0x2027) || + (0x2030 == codePoint) || + (0x2032 <= codePoint && codePoint <= 0x2033) || + (0x2035 == codePoint) || + (0x203B == codePoint) || + (0x203E == codePoint) || + (0x2074 == codePoint) || + (0x207F == codePoint) || + (0x2081 <= codePoint && codePoint <= 0x2084) || + (0x20AC == codePoint) || + (0x2103 == codePoint) || + (0x2105 == codePoint) || + (0x2109 == codePoint) || + (0x2113 == codePoint) || + (0x2116 == codePoint) || + (0x2121 <= codePoint && codePoint <= 0x2122) || + (0x2126 == codePoint) || + (0x212B == codePoint) || + (0x2153 <= codePoint && codePoint <= 0x2154) || + (0x215B <= codePoint && codePoint <= 0x215E) || + (0x2160 <= codePoint && codePoint <= 0x216B) || + (0x2170 <= codePoint && codePoint <= 0x2179) || + (0x2189 == codePoint) || + (0x2190 <= codePoint && codePoint <= 0x2199) || + (0x21B8 <= codePoint && codePoint <= 0x21B9) || + (0x21D2 == codePoint) || + (0x21D4 == codePoint) || + (0x21E7 == codePoint) || + (0x2200 == codePoint) || + (0x2202 <= codePoint && codePoint <= 0x2203) || + (0x2207 <= codePoint && codePoint <= 0x2208) || + (0x220B == codePoint) || + (0x220F == codePoint) || + (0x2211 == codePoint) || + (0x2215 == codePoint) || + (0x221A == codePoint) || + (0x221D <= codePoint && codePoint <= 0x2220) || + (0x2223 == codePoint) || + (0x2225 == codePoint) || + (0x2227 <= codePoint && codePoint <= 0x222C) || + (0x222E == codePoint) || + (0x2234 <= codePoint && codePoint <= 0x2237) || + (0x223C <= codePoint && codePoint <= 0x223D) || + (0x2248 == codePoint) || + (0x224C == codePoint) || + (0x2252 == codePoint) || + (0x2260 <= codePoint && codePoint <= 0x2261) || + (0x2264 <= codePoint && codePoint <= 0x2267) || + (0x226A <= codePoint && codePoint <= 0x226B) || + (0x226E <= codePoint && codePoint <= 0x226F) || + (0x2282 <= codePoint && codePoint <= 0x2283) || + (0x2286 <= codePoint && codePoint <= 0x2287) || + (0x2295 == codePoint) || + (0x2299 == codePoint) || + (0x22A5 == codePoint) || + (0x22BF == codePoint) || + (0x2312 == codePoint) || + (0x2460 <= codePoint && codePoint <= 0x24E9) || + (0x24EB <= codePoint && codePoint <= 0x254B) || + (0x2550 <= codePoint && codePoint <= 0x2573) || + (0x2580 <= codePoint && codePoint <= 0x258F) || + (0x2592 <= codePoint && codePoint <= 0x2595) || + (0x25A0 <= codePoint && codePoint <= 0x25A1) || + (0x25A3 <= codePoint && codePoint <= 0x25A9) || + (0x25B2 <= codePoint && codePoint <= 0x25B3) || + (0x25B6 <= codePoint && codePoint <= 0x25B7) || + (0x25BC <= codePoint && codePoint <= 0x25BD) || + (0x25C0 <= codePoint && codePoint <= 0x25C1) || + (0x25C6 <= codePoint && codePoint <= 0x25C8) || + (0x25CB == codePoint) || + (0x25CE <= codePoint && codePoint <= 0x25D1) || + (0x25E2 <= codePoint && codePoint <= 0x25E5) || + (0x25EF == codePoint) || + (0x2605 <= codePoint && codePoint <= 0x2606) || + (0x2609 == codePoint) || + (0x260E <= codePoint && codePoint <= 0x260F) || + (0x2614 <= codePoint && codePoint <= 0x2615) || + (0x261C == codePoint) || + (0x261E == codePoint) || + (0x2640 == codePoint) || + (0x2642 == codePoint) || + (0x2660 <= codePoint && codePoint <= 0x2661) || + (0x2663 <= codePoint && codePoint <= 0x2665) || + (0x2667 <= codePoint && codePoint <= 0x266A) || + (0x266C <= codePoint && codePoint <= 0x266D) || + (0x266F == codePoint) || + (0x269E <= codePoint && codePoint <= 0x269F) || + (0x26BE <= codePoint && codePoint <= 0x26BF) || + (0x26C4 <= codePoint && codePoint <= 0x26CD) || + (0x26CF <= codePoint && codePoint <= 0x26E1) || + (0x26E3 == codePoint) || + (0x26E8 <= codePoint && codePoint <= 0x26FF) || + (0x273D == codePoint) || + (0x2757 == codePoint) || + (0x2776 <= codePoint && codePoint <= 0x277F) || + (0x2B55 <= codePoint && codePoint <= 0x2B59) || + (0x3248 <= codePoint && codePoint <= 0x324F) || + (0xE000 <= codePoint && codePoint <= 0xF8FF) || + (0xFE00 <= codePoint && codePoint <= 0xFE0F) || + (0xFFFD == codePoint) || + (0x1F100 <= codePoint && codePoint <= 0x1F10A) || + (0x1F110 <= codePoint && codePoint <= 0x1F12D) || + (0x1F130 <= codePoint && codePoint <= 0x1F169) || + (0x1F170 <= codePoint && codePoint <= 0x1F19A) || + (0xE0100 <= codePoint && codePoint <= 0xE01EF) || + (0xF0000 <= codePoint && codePoint <= 0xFFFFD) || + (0x100000 <= codePoint && codePoint <= 0x10FFFD)) { + return 'A'; + } + + return 'N'; +}; + +eaw.characterLength = function(character) { + var code = this.eastAsianWidth(character); + if (code == 'F' || code == 'W' || code == 'A') { + return 2; + } else { + return 1; + } +}; + +// Split a string considering surrogate-pairs. +function stringToArray(string) { + return string.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || []; +} + +eaw.length = function(string) { + var characters = stringToArray(string); + var len = 0; + for (var i = 0; i < characters.length; i++) { + len = len + this.characterLength(characters[i]); + } + return len; +}; + +eaw.slice = function(text, start, end) { + textLen = eaw.length(text) + start = start ? start : 0; + end = end ? end : 1; + if (start < 0) { + start = textLen + start; + } + if (end < 0) { + end = textLen + end; + } + var result = ''; + var eawLen = 0; + var chars = stringToArray(text); + for (var i = 0; i < chars.length; i++) { + var char = chars[i]; + var charLen = eaw.length(char); + if (eawLen >= start - (charLen == 2 ? 1 : 0)) { + if (eawLen + charLen <= end) { + result += char; + } else { + break; + } + } + eawLen += charLen; + } + return result; +}; diff --git a/node_modules/eastasianwidth/package.json b/node_modules/eastasianwidth/package.json new file mode 100644 index 0000000..cb7ac6a --- /dev/null +++ b/node_modules/eastasianwidth/package.json @@ -0,0 +1,18 @@ +{ + "name": "eastasianwidth", + "version": "0.2.0", + "description": "Get East Asian Width from a character.", + "main": "eastasianwidth.js", + "files": [ + "eastasianwidth.js" + ], + "scripts": { + "test": "mocha" + }, + "repository": "git://github.com/komagata/eastasianwidth.git", + "author": "Masaki Komagata", + "license": "MIT", + "devDependencies": { + "mocha": "~1.9.0" + } +} diff --git a/node_modules/fast-glob/LICENSE b/node_modules/fast-glob/LICENSE new file mode 100644 index 0000000..65a9994 --- /dev/null +++ b/node_modules/fast-glob/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Denis Malinochkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/fast-glob/README.md b/node_modules/fast-glob/README.md new file mode 100644 index 0000000..1d7843a --- /dev/null +++ b/node_modules/fast-glob/README.md @@ -0,0 +1,830 @@ +# fast-glob + +> It's a very fast and efficient [glob][glob_definition] library for [Node.js][node_js]. + +This package provides methods for traversing the file system and returning pathnames that matched a defined set of a specified pattern according to the rules used by the Unix Bash shell with some simplifications, meanwhile results are returned in **arbitrary order**. Quick, simple, effective. + +## Table of Contents + +
+Details + +* [Highlights](#highlights) +* [Old and modern mode](#old-and-modern-mode) +* [Pattern syntax](#pattern-syntax) + * [Basic syntax](#basic-syntax) + * [Advanced syntax](#advanced-syntax) +* [Installation](#installation) +* [API](#api) + * [Asynchronous](#asynchronous) + * [Synchronous](#synchronous) + * [Stream](#stream) + * [patterns](#patterns) + * [[options]](#options) + * [Helpers](#helpers) + * [generateTasks](#generatetaskspatterns-options) + * [isDynamicPattern](#isdynamicpatternpattern-options) + * [escapePath](#escapepathpath) + * [convertPathToPattern](#convertpathtopatternpath) +* [Options](#options-3) + * [Common](#common) + * [concurrency](#concurrency) + * [cwd](#cwd) + * [deep](#deep) + * [followSymbolicLinks](#followsymboliclinks) + * [fs](#fs) + * [ignore](#ignore) + * [suppressErrors](#suppresserrors) + * [throwErrorOnBrokenSymbolicLink](#throwerroronbrokensymboliclink) + * [Output control](#output-control) + * [absolute](#absolute) + * [markDirectories](#markdirectories) + * [objectMode](#objectmode) + * [onlyDirectories](#onlydirectories) + * [onlyFiles](#onlyfiles) + * [stats](#stats) + * [unique](#unique) + * [Matching control](#matching-control) + * [braceExpansion](#braceexpansion) + * [caseSensitiveMatch](#casesensitivematch) + * [dot](#dot) + * [extglob](#extglob) + * [globstar](#globstar) + * [baseNameMatch](#basenamematch) +* [FAQ](#faq) + * [What is a static or dynamic pattern?](#what-is-a-static-or-dynamic-pattern) + * [How to write patterns on Windows?](#how-to-write-patterns-on-windows) + * [Why are parentheses match wrong?](#why-are-parentheses-match-wrong) + * [How to exclude directory from reading?](#how-to-exclude-directory-from-reading) + * [How to use UNC path?](#how-to-use-unc-path) + * [Compatible with `node-glob`?](#compatible-with-node-glob) +* [Benchmarks](#benchmarks) + * [Server](#server) + * [Nettop](#nettop) +* [Changelog](#changelog) +* [License](#license) + +
+ +## Highlights + +* Fast. Probably the fastest. +* Supports multiple and negative patterns. +* Synchronous, Promise and Stream API. +* Object mode. Can return more than just strings. +* Error-tolerant. + +## Old and modern mode + +This package works in two modes, depending on the environment in which it is used. + +* **Old mode**. Node.js below 10.10 or when the [`stats`](#stats) option is *enabled*. +* **Modern mode**. Node.js 10.10+ and the [`stats`](#stats) option is *disabled*. + +The modern mode is faster. Learn more about the [internal mechanism][nodelib_fs_scandir_old_and_modern_modern]. + +## Pattern syntax + +> :warning: Always use forward-slashes in glob expressions (patterns and [`ignore`](#ignore) option). Use backslashes for escaping characters. + +There is more than one form of syntax: basic and advanced. Below is a brief overview of the supported features. Also pay attention to our [FAQ](#faq). + +> :book: This package uses [`micromatch`][micromatch] as a library for pattern matching. + +### Basic syntax + +* An asterisk (`*`) — matches everything except slashes (path separators), hidden files (names starting with `.`). +* A double star or globstar (`**`) — matches zero or more directories. +* Question mark (`?`) – matches any single character except slashes (path separators). +* Sequence (`[seq]`) — matches any character in sequence. + +> :book: A few additional words about the [basic matching behavior][picomatch_matching_behavior]. + +Some examples: + +* `src/**/*.js` — matches all files in the `src` directory (any level of nesting) that have the `.js` extension. +* `src/*.??` — matches all files in the `src` directory (only first level of nesting) that have a two-character extension. +* `file-[01].js` — matches files: `file-0.js`, `file-1.js`. + +### Advanced syntax + +* [Escapes characters][micromatch_backslashes] (`\\`) — matching special characters (`$^*+?()[]`) as literals. +* [POSIX character classes][picomatch_posix_brackets] (`[[:digit:]]`). +* [Extended globs][micromatch_extglobs] (`?(pattern-list)`). +* [Bash style brace expansions][micromatch_braces] (`{}`). +* [Regexp character classes][micromatch_regex_character_classes] (`[1-5]`). +* [Regex groups][regular_expressions_brackets] (`(a|b)`). + +> :book: A few additional words about the [advanced matching behavior][micromatch_extended_globbing]. + +Some examples: + +* `src/**/*.{css,scss}` — matches all files in the `src` directory (any level of nesting) that have the `.css` or `.scss` extension. +* `file-[[:digit:]].js` — matches files: `file-0.js`, `file-1.js`, …, `file-9.js`. +* `file-{1..3}.js` — matches files: `file-1.js`, `file-2.js`, `file-3.js`. +* `file-(1|2)` — matches files: `file-1.js`, `file-2.js`. + +## Installation + +```console +npm install fast-glob +``` + +## API + +### Asynchronous + +```js +fg(patterns, [options]) +fg.async(patterns, [options]) +fg.glob(patterns, [options]) +``` + +Returns a `Promise` with an array of matching entries. + +```js +const fg = require('fast-glob'); + +const entries = await fg(['.editorconfig', '**/index.js'], { dot: true }); + +// ['.editorconfig', 'services/index.js'] +``` + +### Synchronous + +```js +fg.sync(patterns, [options]) +fg.globSync(patterns, [options]) +``` + +Returns an array of matching entries. + +```js +const fg = require('fast-glob'); + +const entries = fg.sync(['.editorconfig', '**/index.js'], { dot: true }); + +// ['.editorconfig', 'services/index.js'] +``` + +### Stream + +```js +fg.stream(patterns, [options]) +fg.globStream(patterns, [options]) +``` + +Returns a [`ReadableStream`][node_js_stream_readable_streams] when the `data` event will be emitted with matching entry. + +```js +const fg = require('fast-glob'); + +const stream = fg.stream(['.editorconfig', '**/index.js'], { dot: true }); + +for await (const entry of stream) { + // .editorconfig + // services/index.js +} +``` + +#### patterns + +* Required: `true` +* Type: `string | string[]` + +Any correct pattern(s). + +> :1234: [Pattern syntax](#pattern-syntax) +> +> :warning: This package does not respect the order of patterns. First, all the negative patterns are applied, and only then the positive patterns. If you want to get a certain order of records, use sorting or split calls. + +#### [options] + +* Required: `false` +* Type: [`Options`](#options-3) + +See [Options](#options-3) section. + +### Helpers + +#### `generateTasks(patterns, [options])` + +Returns the internal representation of patterns ([`Task`](./src/managers/tasks.ts) is a combining patterns by base directory). + +```js +fg.generateTasks('*'); + +[{ + base: '.', // Parent directory for all patterns inside this task + dynamic: true, // Dynamic or static patterns are in this task + patterns: ['*'], + positive: ['*'], + negative: [] +}] +``` + +##### patterns + +* Required: `true` +* Type: `string | string[]` + +Any correct pattern(s). + +##### [options] + +* Required: `false` +* Type: [`Options`](#options-3) + +See [Options](#options-3) section. + +#### `isDynamicPattern(pattern, [options])` + +Returns `true` if the passed pattern is a dynamic pattern. + +> :1234: [What is a static or dynamic pattern?](#what-is-a-static-or-dynamic-pattern) + +```js +fg.isDynamicPattern('*'); // true +fg.isDynamicPattern('abc'); // false +``` + +##### pattern + +* Required: `true` +* Type: `string` + +Any correct pattern. + +##### [options] + +* Required: `false` +* Type: [`Options`](#options-3) + +See [Options](#options-3) section. + +#### `escapePath(path)` + +Returns the path with escaped special characters depending on the platform. + +* Posix: + * `*?|(){}[]`; + * `!` at the beginning of line; + * `@+!` before the opening parenthesis; + * `\\` before non-special characters; +* Windows: + * `(){}[]` + * `!` at the beginning of line; + * `@+!` before the opening parenthesis; + * Characters like `*?|` cannot be used in the path ([windows_naming_conventions][windows_naming_conventions]), so they will not be escaped; + +```js +fg.escapePath('!abc'); +// \\!abc +fg.escapePath('[OpenSource] mrmlnc – fast-glob (Deluxe Edition) 2014') + '/*.flac' +// \\[OpenSource\\] mrmlnc – fast-glob \\(Deluxe Edition\\) 2014/*.flac + +fg.posix.escapePath('C:\\Program Files (x86)\\**\\*'); +// C:\\\\Program Files \\(x86\\)\\*\\*\\* +fg.win32.escapePath('C:\\Program Files (x86)\\**\\*'); +// Windows: C:\\Program Files \\(x86\\)\\**\\* +``` + +#### `convertPathToPattern(path)` + +Converts a path to a pattern depending on the platform, including special character escaping. + +* Posix. Works similarly to the `fg.posix.escapePath` method. +* Windows. Works similarly to the `fg.win32.escapePath` method, additionally converting backslashes to forward slashes in cases where they are not escape characters (`!()+@{}[]`). + +```js +fg.convertPathToPattern('[OpenSource] mrmlnc – fast-glob (Deluxe Edition) 2014') + '/*.flac'; +// \\[OpenSource\\] mrmlnc – fast-glob \\(Deluxe Edition\\) 2014/*.flac + +fg.convertPathToPattern('C:/Program Files (x86)/**/*'); +// Posix: C:/Program Files \\(x86\\)/\\*\\*/\\* +// Windows: C:/Program Files \\(x86\\)/**/* + +fg.convertPathToPattern('C:\\Program Files (x86)\\**\\*'); +// Posix: C:\\\\Program Files \\(x86\\)\\*\\*\\* +// Windows: C:/Program Files \\(x86\\)/**/* + +fg.posix.convertPathToPattern('\\\\?\\c:\\Program Files (x86)') + '/**/*'; +// Posix: \\\\\\?\\\\c:\\\\Program Files \\(x86\\)/**/* (broken pattern) +fg.win32.convertPathToPattern('\\\\?\\c:\\Program Files (x86)') + '/**/*'; +// Windows: //?/c:/Program Files \\(x86\\)/**/* +``` + +## Options + +### Common options + +#### concurrency + +* Type: `number` +* Default: `os.cpus().length` + +Specifies the maximum number of concurrent requests from a reader to read directories. + +> :book: The higher the number, the higher the performance and load on the file system. If you want to read in quiet mode, set the value to a comfortable number or `1`. + +
+ +More details + +In Node, there are [two types of threads][nodejs_thread_pool]: Event Loop (code) and a Thread Pool (fs, dns, …). The thread pool size controlled by the `UV_THREADPOOL_SIZE` environment variable. Its default size is 4 ([documentation][libuv_thread_pool]). The pool is one for all tasks within a single Node process. + +Any code can make 4 real concurrent accesses to the file system. The rest of the FS requests will wait in the queue. + +> :book: Each new instance of FG in the same Node process will use the same Thread pool. + +But this package also has the `concurrency` option. This option allows you to control the number of concurrent accesses to the FS at the package level. By default, this package has a value equal to the number of cores available for the current Node process. This allows you to set a value smaller than the pool size (`concurrency: 1`) or, conversely, to prepare tasks for the pool queue more quickly (`concurrency: Number.POSITIVE_INFINITY`). + +So, in fact, this package can **only make 4 concurrent requests to the FS**. You can increase this value by using an environment variable (`UV_THREADPOOL_SIZE`), but in practice this does not give a multiple advantage. + +
+ +#### cwd + +* Type: `string` +* Default: `process.cwd()` + +The current working directory in which to search. + +#### deep + +* Type: `number` +* Default: `Infinity` + +Specifies the maximum depth of a read directory relative to the start directory. + +For example, you have the following tree: + +```js +dir/ +└── one/ // 1 + └── two/ // 2 + └── file.js // 3 +``` + +```js +// With base directory +fg.sync('dir/**', { onlyFiles: false, deep: 1 }); // ['dir/one'] +fg.sync('dir/**', { onlyFiles: false, deep: 2 }); // ['dir/one', 'dir/one/two'] + +// With cwd option +fg.sync('**', { onlyFiles: false, cwd: 'dir', deep: 1 }); // ['one'] +fg.sync('**', { onlyFiles: false, cwd: 'dir', deep: 2 }); // ['one', 'one/two'] +``` + +> :book: If you specify a pattern with some base directory, this directory will not participate in the calculation of the depth of the found directories. Think of it as a [`cwd`](#cwd) option. + +#### followSymbolicLinks + +* Type: `boolean` +* Default: `true` + +Indicates whether to traverse descendants of symbolic link directories when expanding `**` patterns. + +> :book: Note that this option does not affect the base directory of the pattern. For example, if `./a` is a symlink to directory `./b` and you specified `['./a**', './b/**']` patterns, then directory `./a` will still be read. + +> :book: If the [`stats`](#stats) option is specified, the information about the symbolic link (`fs.lstat`) will be replaced with information about the entry (`fs.stat`) behind it. + +#### fs + +* Type: `FileSystemAdapter` +* Default: `fs.*` + +Custom implementation of methods for working with the file system. Supports objects with enumerable properties only. + +```ts +export interface FileSystemAdapter { + lstat?: typeof fs.lstat; + stat?: typeof fs.stat; + lstatSync?: typeof fs.lstatSync; + statSync?: typeof fs.statSync; + readdir?: typeof fs.readdir; + readdirSync?: typeof fs.readdirSync; +} +``` + +#### ignore + +* Type: `string[]` +* Default: `[]` + +An array of glob patterns to exclude matches. This is an alternative way to use negative patterns. + +```js +dir/ +├── package-lock.json +└── package.json +``` + +```js +fg.sync(['*.json', '!package-lock.json']); // ['package.json'] +fg.sync('*.json', { ignore: ['package-lock.json'] }); // ['package.json'] +``` + +#### suppressErrors + +* Type: `boolean` +* Default: `false` + +By default this package suppress only `ENOENT` errors. Set to `true` to suppress any error. + +> :book: Can be useful when the directory has entries with a special level of access. + +#### throwErrorOnBrokenSymbolicLink + +* Type: `boolean` +* Default: `false` + +Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`. + +> :book: This option has no effect on errors when reading the symbolic link directory. + +### Output control + +#### absolute + +* Type: `boolean` +* Default: `false` + +Return the absolute path for entries. + +```js +fg.sync('*.js', { absolute: false }); // ['index.js'] +fg.sync('*.js', { absolute: true }); // ['/home/user/index.js'] +``` + +> :book: This option is required if you want to use negative patterns with absolute path, for example, `!${__dirname}/*.js`. + +#### markDirectories + +* Type: `boolean` +* Default: `false` + +Mark the directory path with the final slash. + +```js +fg.sync('*', { onlyFiles: false, markDirectories: false }); // ['index.js', 'controllers'] +fg.sync('*', { onlyFiles: false, markDirectories: true }); // ['index.js', 'controllers/'] +``` + +#### objectMode + +* Type: `boolean` +* Default: `false` + +Returns objects (instead of strings) describing entries. + +```js +fg.sync('*', { objectMode: false }); // ['src/index.js'] +fg.sync('*', { objectMode: true }); // [{ name: 'index.js', path: 'src/index.js', dirent: }] +``` + +The object has the following fields: + +* name (`string`) — the last part of the path (basename) +* path (`string`) — full path relative to the pattern base directory +* dirent ([`fs.Dirent`][node_js_fs_class_fs_dirent]) — instance of `fs.Dirent` + +> :book: An object is an internal representation of entry, so getting it does not affect performance. + +#### onlyDirectories + +* Type: `boolean` +* Default: `false` + +Return only directories. + +```js +fg.sync('*', { onlyDirectories: false }); // ['index.js', 'src'] +fg.sync('*', { onlyDirectories: true }); // ['src'] +``` + +> :book: If `true`, the [`onlyFiles`](#onlyfiles) option is automatically `false`. + +#### onlyFiles + +* Type: `boolean` +* Default: `true` + +Return only files. + +```js +fg.sync('*', { onlyFiles: false }); // ['index.js', 'src'] +fg.sync('*', { onlyFiles: true }); // ['index.js'] +``` + +#### stats + +* Type: `boolean` +* Default: `false` + +Enables an [object mode](#objectmode) with an additional field: + +* stats ([`fs.Stats`][node_js_fs_class_fs_stats]) — instance of `fs.Stats` + +```js +fg.sync('*', { stats: false }); // ['src/index.js'] +fg.sync('*', { stats: true }); // [{ name: 'index.js', path: 'src/index.js', dirent: , stats: }] +``` + +> :book: Returns `fs.stat` instead of `fs.lstat` for symbolic links when the [`followSymbolicLinks`](#followsymboliclinks) option is specified. +> +> :warning: Unlike [object mode](#objectmode) this mode requires additional calls to the file system. On average, this mode is slower at least twice. See [old and modern mode](#old-and-modern-mode) for more details. + +#### unique + +* Type: `boolean` +* Default: `true` + +Ensures that the returned entries are unique. + +```js +fg.sync(['*.json', 'package.json'], { unique: false }); // ['package.json', 'package.json'] +fg.sync(['*.json', 'package.json'], { unique: true }); // ['package.json'] +``` + +If `true` and similar entries are found, the result is the first found. + +### Matching control + +#### braceExpansion + +* Type: `boolean` +* Default: `true` + +Enables Bash-like brace expansion. + +> :1234: [Syntax description][bash_hackers_syntax_expansion_brace] or more [detailed description][micromatch_braces]. + +```js +dir/ +├── abd +├── acd +└── a{b,c}d +``` + +```js +fg.sync('a{b,c}d', { braceExpansion: false }); // ['a{b,c}d'] +fg.sync('a{b,c}d', { braceExpansion: true }); // ['abd', 'acd'] +``` + +#### caseSensitiveMatch + +* Type: `boolean` +* Default: `true` + +Enables a [case-sensitive][wikipedia_case_sensitivity] mode for matching files. + +```js +dir/ +├── file.txt +└── File.txt +``` + +```js +fg.sync('file.txt', { caseSensitiveMatch: false }); // ['file.txt', 'File.txt'] +fg.sync('file.txt', { caseSensitiveMatch: true }); // ['file.txt'] +``` + +#### dot + +* Type: `boolean` +* Default: `false` + +Allow patterns to match entries that begin with a period (`.`). + +> :book: Note that an explicit dot in a portion of the pattern will always match dot files. + +```js +dir/ +├── .editorconfig +└── package.json +``` + +```js +fg.sync('*', { dot: false }); // ['package.json'] +fg.sync('*', { dot: true }); // ['.editorconfig', 'package.json'] +``` + +#### extglob + +* Type: `boolean` +* Default: `true` + +Enables Bash-like `extglob` functionality. + +> :1234: [Syntax description][micromatch_extglobs]. + +```js +dir/ +├── README.md +└── package.json +``` + +```js +fg.sync('*.+(json|md)', { extglob: false }); // [] +fg.sync('*.+(json|md)', { extglob: true }); // ['README.md', 'package.json'] +``` + +#### globstar + +* Type: `boolean` +* Default: `true` + +Enables recursively repeats a pattern containing `**`. If `false`, `**` behaves exactly like `*`. + +```js +dir/ +└── a + └── b +``` + +```js +fg.sync('**', { onlyFiles: false, globstar: false }); // ['a'] +fg.sync('**', { onlyFiles: false, globstar: true }); // ['a', 'a/b'] +``` + +#### baseNameMatch + +* Type: `boolean` +* Default: `false` + +If set to `true`, then patterns without slashes will be matched against the basename of the path if it contains slashes. + +```js +dir/ +└── one/ + └── file.md +``` + +```js +fg.sync('*.md', { baseNameMatch: false }); // [] +fg.sync('*.md', { baseNameMatch: true }); // ['one/file.md'] +``` + +## FAQ + +## What is a static or dynamic pattern? + +All patterns can be divided into two types: + +* **static**. A pattern is considered static if it can be used to get an entry on the file system without using matching mechanisms. For example, the `file.js` pattern is a static pattern because we can just verify that it exists on the file system. +* **dynamic**. A pattern is considered dynamic if it cannot be used directly to find occurrences without using a matching mechanisms. For example, the `*` pattern is a dynamic pattern because we cannot use this pattern directly. + +A pattern is considered dynamic if it contains the following characters (`…` — any characters or their absence) or options: + +* The [`caseSensitiveMatch`](#casesensitivematch) option is disabled +* `\\` (the escape character) +* `*`, `?`, `!` (at the beginning of line) +* `[…]` +* `(…|…)` +* `@(…)`, `!(…)`, `*(…)`, `?(…)`, `+(…)` (respects the [`extglob`](#extglob) option) +* `{…,…}`, `{…..…}` (respects the [`braceExpansion`](#braceexpansion) option) + +## How to write patterns on Windows? + +Always use forward-slashes in glob expressions (patterns and [`ignore`](#ignore) option). Use backslashes for escaping characters. With the [`cwd`](#cwd) option use a convenient format. + +**Bad** + +```ts +[ + 'directory\\*', + path.join(process.cwd(), '**') +] +``` + +**Good** + +```ts +[ + 'directory/*', + fg.convertPathToPattern(process.cwd()) + '/**' +] +``` + +> :book: Use the [`.convertPathToPattern`](#convertpathtopatternpath) package to convert Windows-style path to a Unix-style path. + +Read more about [matching with backslashes][micromatch_backslashes]. + +## Why are parentheses match wrong? + +```js +dir/ +└── (special-*file).txt +``` + +```js +fg.sync(['(special-*file).txt']) // [] +``` + +Refers to Bash. You need to escape special characters: + +```js +fg.sync(['\\(special-*file\\).txt']) // ['(special-*file).txt'] +``` + +Read more about [matching special characters as literals][picomatch_matching_special_characters_as_literals]. Or use the [`.escapePath`](#escapepathpath). + +## How to exclude directory from reading? + +You can use a negative pattern like this: `!**/node_modules` or `!**/node_modules/**`. Also you can use [`ignore`](#ignore) option. Just look at the example below. + +```js +first/ +├── file.md +└── second/ + └── file.txt +``` + +If you don't want to read the `second` directory, you must write the following pattern: `!**/second` or `!**/second/**`. + +```js +fg.sync(['**/*.md', '!**/second']); // ['first/file.md'] +fg.sync(['**/*.md'], { ignore: ['**/second/**'] }); // ['first/file.md'] +``` + +> :warning: When you write `!**/second/**/*` it means that the directory will be **read**, but all the entries will not be included in the results. + +You have to understand that if you write the pattern to exclude directories, then the directory will not be read under any circumstances. + +## How to use UNC path? + +You cannot use [Uniform Naming Convention (UNC)][unc_path] paths as patterns (due to syntax) directly, but you can use them as [`cwd`](#cwd) directory or use the `fg.convertPathToPattern` method. + +```ts +// cwd +fg.sync('*', { cwd: '\\\\?\\C:\\Python27' /* or //?/C:/Python27 */ }); +fg.sync('Python27/*', { cwd: '\\\\?\\C:\\' /* or //?/C:/ */ }); + +// .convertPathToPattern +fg.sync(fg.convertPathToPattern('\\\\?\\c:\\Python27') + '/*'); +``` + +## Compatible with `node-glob`? + +| node-glob | fast-glob | +| :----------: | :-------: | +| `cwd` | [`cwd`](#cwd) | +| `root` | – | +| `dot` | [`dot`](#dot) | +| `nomount` | – | +| `mark` | [`markDirectories`](#markdirectories) | +| `nosort` | – | +| `nounique` | [`unique`](#unique) | +| `nobrace` | [`braceExpansion`](#braceexpansion) | +| `noglobstar` | [`globstar`](#globstar) | +| `noext` | [`extglob`](#extglob) | +| `nocase` | [`caseSensitiveMatch`](#casesensitivematch) | +| `matchBase` | [`baseNameMatch`](#basenamematch) | +| `nodir` | [`onlyFiles`](#onlyfiles) | +| `ignore` | [`ignore`](#ignore) | +| `follow` | [`followSymbolicLinks`](#followsymboliclinks) | +| `realpath` | – | +| `absolute` | [`absolute`](#absolute) | + +## Benchmarks + +You can see results [here](https://github.com/mrmlnc/fast-glob/actions/workflows/benchmark.yml?query=branch%3Amaster) for every commit into the `main` branch. + +* **Product benchmark** – comparison with the main competitors. +* **Regress benchmark** – regression between the current version and the version from the npm registry. + +## Changelog + +See the [Releases section of our GitHub project][github_releases] for changelog for each release version. + +## License + +This software is released under the terms of the MIT license. + +[bash_hackers_syntax_expansion_brace]: https://wiki.bash-hackers.org/syntax/expansion/brace +[github_releases]: https://github.com/mrmlnc/fast-glob/releases +[glob_definition]: https://en.wikipedia.org/wiki/Glob_(programming) +[glob_linux_man]: http://man7.org/linux/man-pages/man3/glob.3.html +[micromatch_backslashes]: https://github.com/micromatch/micromatch#backslashes +[micromatch_braces]: https://github.com/micromatch/braces +[micromatch_extended_globbing]: https://github.com/micromatch/micromatch#extended-globbing +[micromatch_extglobs]: https://github.com/micromatch/micromatch#extglobs +[micromatch_regex_character_classes]: https://github.com/micromatch/micromatch#regex-character-classes +[micromatch]: https://github.com/micromatch/micromatch +[node_js_fs_class_fs_dirent]: https://nodejs.org/api/fs.html#fs_class_fs_dirent +[node_js_fs_class_fs_stats]: https://nodejs.org/api/fs.html#fs_class_fs_stats +[node_js_stream_readable_streams]: https://nodejs.org/api/stream.html#stream_readable_streams +[node_js]: https://nodejs.org/en +[nodelib_fs_scandir_old_and_modern_modern]: https://github.com/nodelib/nodelib/blob/master/packages/fs/fs.scandir/README.md#old-and-modern-mode +[npm_normalize_path]: https://www.npmjs.com/package/normalize-path +[npm_unixify]: https://www.npmjs.com/package/unixify +[picomatch_matching_behavior]: https://github.com/micromatch/picomatch#matching-behavior-vs-bash +[picomatch_matching_special_characters_as_literals]: https://github.com/micromatch/picomatch#matching-special-characters-as-literals +[picomatch_posix_brackets]: https://github.com/micromatch/picomatch#posix-brackets +[regular_expressions_brackets]: https://www.regular-expressions.info/brackets.html +[unc_path]: https://learn.microsoft.com/openspecs/windows_protocols/ms-dtyp/62e862f4-2a51-452e-8eeb-dc4ff5ee33cc +[wikipedia_case_sensitivity]: https://en.wikipedia.org/wiki/Case_sensitivity +[nodejs_thread_pool]: https://nodejs.org/en/docs/guides/dont-block-the-event-loop +[libuv_thread_pool]: http://docs.libuv.org/en/v1.x/threadpool.html +[windows_naming_conventions]: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions diff --git a/node_modules/fast-glob/node_modules/glob-parent/CHANGELOG.md b/node_modules/fast-glob/node_modules/glob-parent/CHANGELOG.md new file mode 100644 index 0000000..fb9de96 --- /dev/null +++ b/node_modules/fast-glob/node_modules/glob-parent/CHANGELOG.md @@ -0,0 +1,110 @@ +### [5.1.2](https://github.com/gulpjs/glob-parent/compare/v5.1.1...v5.1.2) (2021-03-06) + + +### Bug Fixes + +* eliminate ReDoS ([#36](https://github.com/gulpjs/glob-parent/issues/36)) ([f923116](https://github.com/gulpjs/glob-parent/commit/f9231168b0041fea3f8f954b3cceb56269fc6366)) + +### [5.1.1](https://github.com/gulpjs/glob-parent/compare/v5.1.0...v5.1.1) (2021-01-27) + + +### Bug Fixes + +* unescape exclamation mark ([#26](https://github.com/gulpjs/glob-parent/issues/26)) ([a98874f](https://github.com/gulpjs/glob-parent/commit/a98874f1a59e407f4fb1beb0db4efa8392da60bb)) + +## [5.1.0](https://github.com/gulpjs/glob-parent/compare/v5.0.0...v5.1.0) (2021-01-27) + + +### Features + +* add `flipBackslashes` option to disable auto conversion of slashes (closes [#24](https://github.com/gulpjs/glob-parent/issues/24)) ([#25](https://github.com/gulpjs/glob-parent/issues/25)) ([eecf91d](https://github.com/gulpjs/glob-parent/commit/eecf91d5e3834ed78aee39c4eaaae654d76b87b3)) + +## [5.0.0](https://github.com/gulpjs/glob-parent/compare/v4.0.0...v5.0.0) (2021-01-27) + + +### ⚠ BREAKING CHANGES + +* Drop support for node <6 & bump dependencies + +### Miscellaneous Chores + +* Drop support for node <6 & bump dependencies ([896c0c0](https://github.com/gulpjs/glob-parent/commit/896c0c00b4e7362f60b96e7fc295ae929245255a)) + +## [4.0.0](https://github.com/gulpjs/glob-parent/compare/v3.1.0...v4.0.0) (2021-01-27) + + +### ⚠ BREAKING CHANGES + +* question marks are valid path characters on Windows so avoid flagging as a glob when alone +* Update is-glob dependency + +### Features + +* hoist regexps and strings for performance gains ([4a80667](https://github.com/gulpjs/glob-parent/commit/4a80667c69355c76a572a5892b0f133c8e1f457e)) +* question marks are valid path characters on Windows so avoid flagging as a glob when alone ([2a551dd](https://github.com/gulpjs/glob-parent/commit/2a551dd0dc3235e78bf3c94843d4107072d17841)) +* Update is-glob dependency ([e41fcd8](https://github.com/gulpjs/glob-parent/commit/e41fcd895d1f7bc617dba45c9d935a7949b9c281)) + +## [3.1.0](https://github.com/gulpjs/glob-parent/compare/v3.0.1...v3.1.0) (2021-01-27) + + +### Features + +* allow basic win32 backslash use ([272afa5](https://github.com/gulpjs/glob-parent/commit/272afa5fd070fc0f796386a5993d4ee4a846988b)) +* handle extglobs (parentheses) containing separators ([7db1bdb](https://github.com/gulpjs/glob-parent/commit/7db1bdb0756e55fd14619e8ce31aa31b17b117fd)) +* new approach to braces/brackets handling ([8269bd8](https://github.com/gulpjs/glob-parent/commit/8269bd89290d99fac9395a354fb56fdcdb80f0be)) +* pre-process braces/brackets sections ([9ef8a87](https://github.com/gulpjs/glob-parent/commit/9ef8a87f66b1a43d0591e7a8e4fc5a18415ee388)) +* preserve escaped brace/bracket at end of string ([8cfb0ba](https://github.com/gulpjs/glob-parent/commit/8cfb0ba84202d51571340dcbaf61b79d16a26c76)) + + +### Bug Fixes + +* trailing escaped square brackets ([99ec9fe](https://github.com/gulpjs/glob-parent/commit/99ec9fecc60ee488ded20a94dd4f18b4f55c4ccf)) + +### [3.0.1](https://github.com/gulpjs/glob-parent/compare/v3.0.0...v3.0.1) (2021-01-27) + + +### Features + +* use path-dirname ponyfill ([cdbea5f](https://github.com/gulpjs/glob-parent/commit/cdbea5f32a58a54e001a75ddd7c0fccd4776aacc)) + + +### Bug Fixes + +* unescape glob-escaped dirnames on output ([598c533](https://github.com/gulpjs/glob-parent/commit/598c533bdf49c1428bc063aa9b8db40c5a86b030)) + +## [3.0.0](https://github.com/gulpjs/glob-parent/compare/v2.0.0...v3.0.0) (2021-01-27) + + +### ⚠ BREAKING CHANGES + +* update is-glob dependency + +### Features + +* update is-glob dependency ([5c5f8ef](https://github.com/gulpjs/glob-parent/commit/5c5f8efcee362a8e7638cf8220666acd8784f6bd)) + +## [2.0.0](https://github.com/gulpjs/glob-parent/compare/v1.3.0...v2.0.0) (2021-01-27) + + +### Features + +* move up to dirname regardless of glob characters ([f97fb83](https://github.com/gulpjs/glob-parent/commit/f97fb83be2e0a9fc8d3b760e789d2ecadd6aa0c2)) + +## [1.3.0](https://github.com/gulpjs/glob-parent/compare/v1.2.0...v1.3.0) (2021-01-27) + +## [1.2.0](https://github.com/gulpjs/glob-parent/compare/v1.1.0...v1.2.0) (2021-01-27) + + +### Reverts + +* feat: make regex test strings smaller ([dc80fa9](https://github.com/gulpjs/glob-parent/commit/dc80fa9658dca20549cfeba44bbd37d5246fcce0)) + +## [1.1.0](https://github.com/gulpjs/glob-parent/compare/v1.0.0...v1.1.0) (2021-01-27) + + +### Features + +* make regex test strings smaller ([cd83220](https://github.com/gulpjs/glob-parent/commit/cd832208638f45169f986d80fcf66e401f35d233)) + +## 1.0.0 (2021-01-27) + diff --git a/node_modules/fast-glob/node_modules/glob-parent/LICENSE b/node_modules/fast-glob/node_modules/glob-parent/LICENSE new file mode 100644 index 0000000..63222d7 --- /dev/null +++ b/node_modules/fast-glob/node_modules/glob-parent/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2015, 2019 Elan Shanker + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/fast-glob/node_modules/glob-parent/README.md b/node_modules/fast-glob/node_modules/glob-parent/README.md new file mode 100644 index 0000000..36a2793 --- /dev/null +++ b/node_modules/fast-glob/node_modules/glob-parent/README.md @@ -0,0 +1,137 @@ +

+ + + +

+ +# glob-parent + +[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Azure Pipelines Build Status][azure-pipelines-image]][azure-pipelines-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] + +Extract the non-magic parent path from a glob string. + +## Usage + +```js +var globParent = require('glob-parent'); + +globParent('path/to/*.js'); // 'path/to' +globParent('/root/path/to/*.js'); // '/root/path/to' +globParent('/*.js'); // '/' +globParent('*.js'); // '.' +globParent('**/*.js'); // '.' +globParent('path/{to,from}'); // 'path' +globParent('path/!(to|from)'); // 'path' +globParent('path/?(to|from)'); // 'path' +globParent('path/+(to|from)'); // 'path' +globParent('path/*(to|from)'); // 'path' +globParent('path/@(to|from)'); // 'path' +globParent('path/**/*'); // 'path' + +// if provided a non-glob path, returns the nearest dir +globParent('path/foo/bar.js'); // 'path/foo' +globParent('path/foo/'); // 'path/foo' +globParent('path/foo'); // 'path' (see issue #3 for details) +``` + +## API + +### `globParent(maybeGlobString, [options])` + +Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below. + +#### options + +```js +{ + // Disables the automatic conversion of slashes for Windows + flipBackslashes: true +} +``` + +## Escaping + +The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: + +- `?` (question mark) unless used as a path segment alone +- `*` (asterisk) +- `|` (pipe) +- `(` (opening parenthesis) +- `)` (closing parenthesis) +- `{` (opening curly brace) +- `}` (closing curly brace) +- `[` (opening bracket) +- `]` (closing bracket) + +**Example** + +```js +globParent('foo/[bar]/') // 'foo' +globParent('foo/\\[bar]/') // 'foo/[bar]' +``` + +## Limitations + +### Braces & Brackets +This library attempts a quick and imperfect method of determining which path +parts have glob magic without fully parsing/lexing the pattern. There are some +advanced use cases that can trip it up, such as nested braces where the outer +pair is escaped and the inner one contains a path separator. If you find +yourself in the unlikely circumstance of being affected by this or need to +ensure higher-fidelity glob handling in your library, it is recommended that you +pre-process your input with [expand-braces] and/or [expand-brackets]. + +### Windows +Backslashes are not valid path separators for globs. If a path with backslashes +is provided anyway, for simple cases, glob-parent will replace the path +separator for you and return the non-glob parent path (now with +forward-slashes, which are still valid as Windows path separators). + +This cannot be used in conjunction with escape characters. + +```js +// BAD +globParent('C:\\Program Files \\(x86\\)\\*.ext') // 'C:/Program Files /(x86/)' + +// GOOD +globParent('C:/Program Files\\(x86\\)/*.ext') // 'C:/Program Files (x86)' +``` + +If you are using escape characters for a pattern without path parts (i.e. +relative to `cwd`), prefix with `./` to avoid confusing glob-parent. + +```js +// BAD +globParent('foo \\[bar]') // 'foo ' +globParent('foo \\[bar]*') // 'foo ' + +// GOOD +globParent('./foo \\[bar]') // 'foo [bar]' +globParent('./foo \\[bar]*') // '.' +``` + +## License + +ISC + +[expand-braces]: https://github.com/jonschlinkert/expand-braces +[expand-brackets]: https://github.com/jonschlinkert/expand-brackets + +[downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg +[npm-url]: https://www.npmjs.com/package/glob-parent +[npm-image]: https://img.shields.io/npm/v/glob-parent.svg + +[azure-pipelines-url]: https://dev.azure.com/gulpjs/gulp/_build/latest?definitionId=2&branchName=master +[azure-pipelines-image]: https://dev.azure.com/gulpjs/gulp/_apis/build/status/glob-parent?branchName=master + +[travis-url]: https://travis-ci.org/gulpjs/glob-parent +[travis-image]: https://img.shields.io/travis/gulpjs/glob-parent.svg?label=travis-ci + +[appveyor-url]: https://ci.appveyor.com/project/gulpjs/glob-parent +[appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/glob-parent.svg?label=appveyor + +[coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent +[coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg + +[gitter-url]: https://gitter.im/gulpjs/gulp +[gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg diff --git a/node_modules/fast-glob/node_modules/glob-parent/index.js b/node_modules/fast-glob/node_modules/glob-parent/index.js new file mode 100644 index 0000000..09e257e --- /dev/null +++ b/node_modules/fast-glob/node_modules/glob-parent/index.js @@ -0,0 +1,42 @@ +'use strict'; + +var isGlob = require('is-glob'); +var pathPosixDirname = require('path').posix.dirname; +var isWin32 = require('os').platform() === 'win32'; + +var slash = '/'; +var backslash = /\\/g; +var enclosure = /[\{\[].*[\}\]]$/; +var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; +var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; + +/** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + * @returns {string} + */ +module.exports = function globParent(str, opts) { + var options = Object.assign({ flipBackslashes: true }, opts); + + // flip windows path separators + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { + str = str.replace(backslash, slash); + } + + // special case for strings ending in enclosure containing path separator + if (enclosure.test(str)) { + str += slash; + } + + // preserves full path in case of trailing path separator + str += 'a'; + + // remove path parts that are globby + do { + str = pathPosixDirname(str); + } while (isGlob(str) || globby.test(str)); + + // remove escape chars and return result + return str.replace(escaped, '$1'); +}; diff --git a/node_modules/fast-glob/node_modules/glob-parent/package.json b/node_modules/fast-glob/node_modules/glob-parent/package.json new file mode 100644 index 0000000..125c971 --- /dev/null +++ b/node_modules/fast-glob/node_modules/glob-parent/package.json @@ -0,0 +1,48 @@ +{ + "name": "glob-parent", + "version": "5.1.2", + "description": "Extract the non-magic parent path from a glob string.", + "author": "Gulp Team (https://gulpjs.com/)", + "contributors": [ + "Elan Shanker (https://github.com/es128)", + "Blaine Bublitz " + ], + "repository": "gulpjs/glob-parent", + "license": "ISC", + "engines": { + "node": ">= 6" + }, + "main": "index.js", + "files": [ + "LICENSE", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "pretest": "npm run lint", + "test": "nyc mocha --async-only", + "azure-pipelines": "nyc mocha --async-only --reporter xunit -O output=test.xunit", + "coveralls": "nyc report --reporter=text-lcov | coveralls" + }, + "dependencies": { + "is-glob": "^4.0.1" + }, + "devDependencies": { + "coveralls": "^3.0.11", + "eslint": "^2.13.1", + "eslint-config-gulp": "^3.0.1", + "expect": "^1.20.2", + "mocha": "^6.0.2", + "nyc": "^13.3.0" + }, + "keywords": [ + "glob", + "parent", + "strip", + "path", + "dirname", + "directory", + "base", + "wildcard" + ] +} diff --git a/node_modules/fast-glob/out/index.d.ts b/node_modules/fast-glob/out/index.d.ts new file mode 100644 index 0000000..46823bb --- /dev/null +++ b/node_modules/fast-glob/out/index.d.ts @@ -0,0 +1,40 @@ +/// +import * as taskManager from './managers/tasks'; +import { Options as OptionsInternal } from './settings'; +import { Entry as EntryInternal, FileSystemAdapter as FileSystemAdapterInternal, Pattern as PatternInternal } from './types'; +type EntryObjectModePredicate = { + [TKey in keyof Pick]-?: true; +}; +type EntryStatsPredicate = { + [TKey in keyof Pick]-?: true; +}; +type EntryObjectPredicate = EntryObjectModePredicate | EntryStatsPredicate; +declare function FastGlob(source: PatternInternal | PatternInternal[], options: OptionsInternal & EntryObjectPredicate): Promise; +declare function FastGlob(source: PatternInternal | PatternInternal[], options?: OptionsInternal): Promise; +declare namespace FastGlob { + type Options = OptionsInternal; + type Entry = EntryInternal; + type Task = taskManager.Task; + type Pattern = PatternInternal; + type FileSystemAdapter = FileSystemAdapterInternal; + const glob: typeof FastGlob; + const globSync: typeof sync; + const globStream: typeof stream; + const async: typeof FastGlob; + function sync(source: PatternInternal | PatternInternal[], options: OptionsInternal & EntryObjectPredicate): EntryInternal[]; + function sync(source: PatternInternal | PatternInternal[], options?: OptionsInternal): string[]; + function stream(source: PatternInternal | PatternInternal[], options?: OptionsInternal): NodeJS.ReadableStream; + function generateTasks(source: PatternInternal | PatternInternal[], options?: OptionsInternal): Task[]; + function isDynamicPattern(source: PatternInternal, options?: OptionsInternal): boolean; + function escapePath(source: string): PatternInternal; + function convertPathToPattern(source: string): PatternInternal; + namespace posix { + function escapePath(source: string): PatternInternal; + function convertPathToPattern(source: string): PatternInternal; + } + namespace win32 { + function escapePath(source: string): PatternInternal; + function convertPathToPattern(source: string): PatternInternal; + } +} +export = FastGlob; diff --git a/node_modules/fast-glob/out/index.js b/node_modules/fast-glob/out/index.js new file mode 100644 index 0000000..90365d4 --- /dev/null +++ b/node_modules/fast-glob/out/index.js @@ -0,0 +1,102 @@ +"use strict"; +const taskManager = require("./managers/tasks"); +const async_1 = require("./providers/async"); +const stream_1 = require("./providers/stream"); +const sync_1 = require("./providers/sync"); +const settings_1 = require("./settings"); +const utils = require("./utils"); +async function FastGlob(source, options) { + assertPatternsInput(source); + const works = getWorks(source, async_1.default, options); + const result = await Promise.all(works); + return utils.array.flatten(result); +} +// https://github.com/typescript-eslint/typescript-eslint/issues/60 +// eslint-disable-next-line no-redeclare +(function (FastGlob) { + FastGlob.glob = FastGlob; + FastGlob.globSync = sync; + FastGlob.globStream = stream; + FastGlob.async = FastGlob; + function sync(source, options) { + assertPatternsInput(source); + const works = getWorks(source, sync_1.default, options); + return utils.array.flatten(works); + } + FastGlob.sync = sync; + function stream(source, options) { + assertPatternsInput(source); + const works = getWorks(source, stream_1.default, options); + /** + * The stream returned by the provider cannot work with an asynchronous iterator. + * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. + * This affects performance (+25%). I don't see best solution right now. + */ + return utils.stream.merge(works); + } + FastGlob.stream = stream; + function generateTasks(source, options) { + assertPatternsInput(source); + const patterns = [].concat(source); + const settings = new settings_1.default(options); + return taskManager.generate(patterns, settings); + } + FastGlob.generateTasks = generateTasks; + function isDynamicPattern(source, options) { + assertPatternsInput(source); + const settings = new settings_1.default(options); + return utils.pattern.isDynamicPattern(source, settings); + } + FastGlob.isDynamicPattern = isDynamicPattern; + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escape(source); + } + FastGlob.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertPathToPattern(source); + } + FastGlob.convertPathToPattern = convertPathToPattern; + let posix; + (function (posix) { + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escapePosixPath(source); + } + posix.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertPosixPathToPattern(source); + } + posix.convertPathToPattern = convertPathToPattern; + })(posix = FastGlob.posix || (FastGlob.posix = {})); + let win32; + (function (win32) { + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escapeWindowsPath(source); + } + win32.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertWindowsPathToPattern(source); + } + win32.convertPathToPattern = convertPathToPattern; + })(win32 = FastGlob.win32 || (FastGlob.win32 = {})); +})(FastGlob || (FastGlob = {})); +function getWorks(source, _Provider, options) { + const patterns = [].concat(source); + const settings = new settings_1.default(options); + const tasks = taskManager.generate(patterns, settings); + const provider = new _Provider(settings); + return tasks.map(provider.read, provider); +} +function assertPatternsInput(input) { + const source = [].concat(input); + const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item)); + if (!isValidSource) { + throw new TypeError('Patterns must be a string (non empty) or an array of strings'); + } +} +module.exports = FastGlob; diff --git a/node_modules/fast-glob/out/managers/tasks.d.ts b/node_modules/fast-glob/out/managers/tasks.d.ts new file mode 100644 index 0000000..59d2c42 --- /dev/null +++ b/node_modules/fast-glob/out/managers/tasks.d.ts @@ -0,0 +1,22 @@ +import Settings from '../settings'; +import { Pattern, PatternsGroup } from '../types'; +export type Task = { + base: string; + dynamic: boolean; + patterns: Pattern[]; + positive: Pattern[]; + negative: Pattern[]; +}; +export declare function generate(input: Pattern[], settings: Settings): Task[]; +/** + * Returns tasks grouped by basic pattern directories. + * + * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. + * This is necessary because directory traversal starts at the base directory and goes deeper. + */ +export declare function convertPatternsToTasks(positive: Pattern[], negative: Pattern[], dynamic: boolean): Task[]; +export declare function getPositivePatterns(patterns: Pattern[]): Pattern[]; +export declare function getNegativePatternsAsPositive(patterns: Pattern[], ignore: Pattern[]): Pattern[]; +export declare function groupPatternsByBaseDirectory(patterns: Pattern[]): PatternsGroup; +export declare function convertPatternGroupsToTasks(positive: PatternsGroup, negative: Pattern[], dynamic: boolean): Task[]; +export declare function convertPatternGroupToTask(base: string, positive: Pattern[], negative: Pattern[], dynamic: boolean): Task; diff --git a/node_modules/fast-glob/out/managers/tasks.js b/node_modules/fast-glob/out/managers/tasks.js new file mode 100644 index 0000000..335a765 --- /dev/null +++ b/node_modules/fast-glob/out/managers/tasks.js @@ -0,0 +1,110 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0; +const utils = require("../utils"); +function generate(input, settings) { + const patterns = processPatterns(input, settings); + const ignore = processPatterns(settings.ignore, settings); + const positivePatterns = getPositivePatterns(patterns); + const negativePatterns = getNegativePatternsAsPositive(patterns, ignore); + const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings)); + const dynamicPatterns = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings)); + const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); + const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); + return staticTasks.concat(dynamicTasks); +} +exports.generate = generate; +function processPatterns(input, settings) { + let patterns = input; + /** + * The original pattern like `{,*,**,a/*}` can lead to problems checking the depth when matching entry + * and some problems with the micromatch package (see fast-glob issues: #365, #394). + * + * To solve this problem, we expand all patterns containing brace expansion. This can lead to a slight slowdown + * in matching in the case of a large set of patterns after expansion. + */ + if (settings.braceExpansion) { + patterns = utils.pattern.expandPatternsWithBraceExpansion(patterns); + } + /** + * If the `baseNameMatch` option is enabled, we must add globstar to patterns, so that they can be used + * at any nesting level. + * + * We do this here, because otherwise we have to complicate the filtering logic. For example, we need to change + * the pattern in the filter before creating a regular expression. There is no need to change the patterns + * in the application. Only on the input. + */ + if (settings.baseNameMatch) { + patterns = patterns.map((pattern) => pattern.includes('/') ? pattern : `**/${pattern}`); + } + /** + * This method also removes duplicate slashes that may have been in the pattern or formed as a result of expansion. + */ + return patterns.map((pattern) => utils.pattern.removeDuplicateSlashes(pattern)); +} +/** + * Returns tasks grouped by basic pattern directories. + * + * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. + * This is necessary because directory traversal starts at the base directory and goes deeper. + */ +function convertPatternsToTasks(positive, negative, dynamic) { + const tasks = []; + const patternsOutsideCurrentDirectory = utils.pattern.getPatternsOutsideCurrentDirectory(positive); + const patternsInsideCurrentDirectory = utils.pattern.getPatternsInsideCurrentDirectory(positive); + const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); + const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); + tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); + /* + * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory + * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest. + */ + if ('.' in insideCurrentDirectoryGroup) { + tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic)); + } + else { + tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); + } + return tasks; +} +exports.convertPatternsToTasks = convertPatternsToTasks; +function getPositivePatterns(patterns) { + return utils.pattern.getPositivePatterns(patterns); +} +exports.getPositivePatterns = getPositivePatterns; +function getNegativePatternsAsPositive(patterns, ignore) { + const negative = utils.pattern.getNegativePatterns(patterns).concat(ignore); + const positive = negative.map(utils.pattern.convertToPositivePattern); + return positive; +} +exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; +function groupPatternsByBaseDirectory(patterns) { + const group = {}; + return patterns.reduce((collection, pattern) => { + const base = utils.pattern.getBaseDirectory(pattern); + if (base in collection) { + collection[base].push(pattern); + } + else { + collection[base] = [pattern]; + } + return collection; + }, group); +} +exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; +function convertPatternGroupsToTasks(positive, negative, dynamic) { + return Object.keys(positive).map((base) => { + return convertPatternGroupToTask(base, positive[base], negative, dynamic); + }); +} +exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; +function convertPatternGroupToTask(base, positive, negative, dynamic) { + return { + dynamic, + positive, + negative, + base, + patterns: [].concat(positive, negative.map(utils.pattern.convertToNegativePattern)) + }; +} +exports.convertPatternGroupToTask = convertPatternGroupToTask; diff --git a/node_modules/fast-glob/out/providers/async.d.ts b/node_modules/fast-glob/out/providers/async.d.ts new file mode 100644 index 0000000..2742616 --- /dev/null +++ b/node_modules/fast-glob/out/providers/async.d.ts @@ -0,0 +1,9 @@ +import { Task } from '../managers/tasks'; +import { Entry, EntryItem, ReaderOptions } from '../types'; +import ReaderAsync from '../readers/async'; +import Provider from './provider'; +export default class ProviderAsync extends Provider> { + protected _reader: ReaderAsync; + read(task: Task): Promise; + api(root: string, task: Task, options: ReaderOptions): Promise; +} diff --git a/node_modules/fast-glob/out/providers/async.js b/node_modules/fast-glob/out/providers/async.js new file mode 100644 index 0000000..0c5286e --- /dev/null +++ b/node_modules/fast-glob/out/providers/async.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const async_1 = require("../readers/async"); +const provider_1 = require("./provider"); +class ProviderAsync extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new async_1.default(this._settings); + } + async read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const entries = await this.api(root, task, options); + return entries.map((entry) => options.transform(entry)); + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +exports.default = ProviderAsync; diff --git a/node_modules/fast-glob/out/providers/filters/deep.d.ts b/node_modules/fast-glob/out/providers/filters/deep.d.ts new file mode 100644 index 0000000..377fab8 --- /dev/null +++ b/node_modules/fast-glob/out/providers/filters/deep.d.ts @@ -0,0 +1,16 @@ +import { MicromatchOptions, EntryFilterFunction, Pattern } from '../../types'; +import Settings from '../../settings'; +export default class DeepFilter { + private readonly _settings; + private readonly _micromatchOptions; + constructor(_settings: Settings, _micromatchOptions: MicromatchOptions); + getFilter(basePath: string, positive: Pattern[], negative: Pattern[]): EntryFilterFunction; + private _getMatcher; + private _getNegativePatternsRe; + private _filter; + private _isSkippedByDeep; + private _getEntryLevel; + private _isSkippedSymbolicLink; + private _isSkippedByPositivePatterns; + private _isSkippedByNegativePatterns; +} diff --git a/node_modules/fast-glob/out/providers/filters/deep.js b/node_modules/fast-glob/out/providers/filters/deep.js new file mode 100644 index 0000000..644bf41 --- /dev/null +++ b/node_modules/fast-glob/out/providers/filters/deep.js @@ -0,0 +1,62 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils = require("../../utils"); +const partial_1 = require("../matchers/partial"); +class DeepFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + } + getFilter(basePath, positive, negative) { + const matcher = this._getMatcher(positive); + const negativeRe = this._getNegativePatternsRe(negative); + return (entry) => this._filter(basePath, entry, matcher, negativeRe); + } + _getMatcher(patterns) { + return new partial_1.default(patterns, this._settings, this._micromatchOptions); + } + _getNegativePatternsRe(patterns) { + const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern); + return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); + } + _filter(basePath, entry, matcher, negativeRe) { + if (this._isSkippedByDeep(basePath, entry.path)) { + return false; + } + if (this._isSkippedSymbolicLink(entry)) { + return false; + } + const filepath = utils.path.removeLeadingDotSegment(entry.path); + if (this._isSkippedByPositivePatterns(filepath, matcher)) { + return false; + } + return this._isSkippedByNegativePatterns(filepath, negativeRe); + } + _isSkippedByDeep(basePath, entryPath) { + /** + * Avoid unnecessary depth calculations when it doesn't matter. + */ + if (this._settings.deep === Infinity) { + return false; + } + return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; + } + _getEntryLevel(basePath, entryPath) { + const entryPathDepth = entryPath.split('/').length; + if (basePath === '') { + return entryPathDepth; + } + const basePathDepth = basePath.split('/').length; + return entryPathDepth - basePathDepth; + } + _isSkippedSymbolicLink(entry) { + return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); + } + _isSkippedByPositivePatterns(entryPath, matcher) { + return !this._settings.baseNameMatch && !matcher.match(entryPath); + } + _isSkippedByNegativePatterns(entryPath, patternsRe) { + return !utils.pattern.matchAny(entryPath, patternsRe); + } +} +exports.default = DeepFilter; diff --git a/node_modules/fast-glob/out/providers/filters/entry.d.ts b/node_modules/fast-glob/out/providers/filters/entry.d.ts new file mode 100644 index 0000000..23db353 --- /dev/null +++ b/node_modules/fast-glob/out/providers/filters/entry.d.ts @@ -0,0 +1,17 @@ +import Settings from '../../settings'; +import { EntryFilterFunction, MicromatchOptions, Pattern } from '../../types'; +export default class EntryFilter { + private readonly _settings; + private readonly _micromatchOptions; + readonly index: Map; + constructor(_settings: Settings, _micromatchOptions: MicromatchOptions); + getFilter(positive: Pattern[], negative: Pattern[]): EntryFilterFunction; + private _filter; + private _isDuplicateEntry; + private _createIndexRecord; + private _onlyFileFilter; + private _onlyDirectoryFilter; + private _isMatchToPatternsSet; + private _isMatchToAbsoluteNegative; + private _isMatchToPatterns; +} diff --git a/node_modules/fast-glob/out/providers/filters/entry.js b/node_modules/fast-glob/out/providers/filters/entry.js new file mode 100644 index 0000000..0c9210c --- /dev/null +++ b/node_modules/fast-glob/out/providers/filters/entry.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils = require("../../utils"); +class EntryFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this.index = new Map(); + } + getFilter(positive, negative) { + const [absoluteNegative, relativeNegative] = utils.pattern.partitionAbsoluteAndRelative(negative); + const patterns = { + positive: { + all: utils.pattern.convertPatternsToRe(positive, this._micromatchOptions) + }, + negative: { + absolute: utils.pattern.convertPatternsToRe(absoluteNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })), + relative: utils.pattern.convertPatternsToRe(relativeNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })) + } + }; + return (entry) => this._filter(entry, patterns); + } + _filter(entry, patterns) { + const filepath = utils.path.removeLeadingDotSegment(entry.path); + if (this._settings.unique && this._isDuplicateEntry(filepath)) { + return false; + } + if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { + return false; + } + const isMatched = this._isMatchToPatternsSet(filepath, patterns, entry.dirent.isDirectory()); + if (this._settings.unique && isMatched) { + this._createIndexRecord(filepath); + } + return isMatched; + } + _isDuplicateEntry(filepath) { + return this.index.has(filepath); + } + _createIndexRecord(filepath) { + this.index.set(filepath, undefined); + } + _onlyFileFilter(entry) { + return this._settings.onlyFiles && !entry.dirent.isFile(); + } + _onlyDirectoryFilter(entry) { + return this._settings.onlyDirectories && !entry.dirent.isDirectory(); + } + _isMatchToPatternsSet(filepath, patterns, isDirectory) { + const isMatched = this._isMatchToPatterns(filepath, patterns.positive.all, isDirectory); + if (!isMatched) { + return false; + } + const isMatchedByRelativeNegative = this._isMatchToPatterns(filepath, patterns.negative.relative, isDirectory); + if (isMatchedByRelativeNegative) { + return false; + } + const isMatchedByAbsoluteNegative = this._isMatchToAbsoluteNegative(filepath, patterns.negative.absolute, isDirectory); + if (isMatchedByAbsoluteNegative) { + return false; + } + return true; + } + _isMatchToAbsoluteNegative(filepath, patternsRe, isDirectory) { + if (patternsRe.length === 0) { + return false; + } + const fullpath = utils.path.makeAbsolute(this._settings.cwd, filepath); + return this._isMatchToPatterns(fullpath, patternsRe, isDirectory); + } + _isMatchToPatterns(filepath, patternsRe, isDirectory) { + if (patternsRe.length === 0) { + return false; + } + // Trying to match files and directories by patterns. + const isMatched = utils.pattern.matchAny(filepath, patternsRe); + // A pattern with a trailling slash can be used for directory matching. + // To apply such pattern, we need to add a tralling slash to the path. + if (!isMatched && isDirectory) { + return utils.pattern.matchAny(filepath + '/', patternsRe); + } + return isMatched; + } +} +exports.default = EntryFilter; diff --git a/node_modules/fast-glob/out/providers/filters/error.d.ts b/node_modules/fast-glob/out/providers/filters/error.d.ts new file mode 100644 index 0000000..170eb25 --- /dev/null +++ b/node_modules/fast-glob/out/providers/filters/error.d.ts @@ -0,0 +1,8 @@ +import Settings from '../../settings'; +import { ErrorFilterFunction } from '../../types'; +export default class ErrorFilter { + private readonly _settings; + constructor(_settings: Settings); + getFilter(): ErrorFilterFunction; + private _isNonFatalError; +} diff --git a/node_modules/fast-glob/out/providers/filters/error.js b/node_modules/fast-glob/out/providers/filters/error.js new file mode 100644 index 0000000..1c6f241 --- /dev/null +++ b/node_modules/fast-glob/out/providers/filters/error.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils = require("../../utils"); +class ErrorFilter { + constructor(_settings) { + this._settings = _settings; + } + getFilter() { + return (error) => this._isNonFatalError(error); + } + _isNonFatalError(error) { + return utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors; + } +} +exports.default = ErrorFilter; diff --git a/node_modules/fast-glob/out/providers/matchers/matcher.d.ts b/node_modules/fast-glob/out/providers/matchers/matcher.d.ts new file mode 100644 index 0000000..d04c232 --- /dev/null +++ b/node_modules/fast-glob/out/providers/matchers/matcher.d.ts @@ -0,0 +1,33 @@ +import { Pattern, MicromatchOptions, PatternRe } from '../../types'; +import Settings from '../../settings'; +export type PatternSegment = StaticPatternSegment | DynamicPatternSegment; +type StaticPatternSegment = { + dynamic: false; + pattern: Pattern; +}; +type DynamicPatternSegment = { + dynamic: true; + pattern: Pattern; + patternRe: PatternRe; +}; +export type PatternSection = PatternSegment[]; +export type PatternInfo = { + /** + * Indicates that the pattern has a globstar (more than a single section). + */ + complete: boolean; + pattern: Pattern; + segments: PatternSegment[]; + sections: PatternSection[]; +}; +export default abstract class Matcher { + private readonly _patterns; + private readonly _settings; + private readonly _micromatchOptions; + protected readonly _storage: PatternInfo[]; + constructor(_patterns: Pattern[], _settings: Settings, _micromatchOptions: MicromatchOptions); + private _fillStorage; + private _getPatternSegments; + private _splitSegmentsIntoSections; +} +export {}; diff --git a/node_modules/fast-glob/out/providers/matchers/matcher.js b/node_modules/fast-glob/out/providers/matchers/matcher.js new file mode 100644 index 0000000..eae67c9 --- /dev/null +++ b/node_modules/fast-glob/out/providers/matchers/matcher.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils = require("../../utils"); +class Matcher { + constructor(_patterns, _settings, _micromatchOptions) { + this._patterns = _patterns; + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this._storage = []; + this._fillStorage(); + } + _fillStorage() { + for (const pattern of this._patterns) { + const segments = this._getPatternSegments(pattern); + const sections = this._splitSegmentsIntoSections(segments); + this._storage.push({ + complete: sections.length <= 1, + pattern, + segments, + sections + }); + } + } + _getPatternSegments(pattern) { + const parts = utils.pattern.getPatternParts(pattern, this._micromatchOptions); + return parts.map((part) => { + const dynamic = utils.pattern.isDynamicPattern(part, this._settings); + if (!dynamic) { + return { + dynamic: false, + pattern: part + }; + } + return { + dynamic: true, + pattern: part, + patternRe: utils.pattern.makeRe(part, this._micromatchOptions) + }; + }); + } + _splitSegmentsIntoSections(segments) { + return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern)); + } +} +exports.default = Matcher; diff --git a/node_modules/fast-glob/out/providers/matchers/partial.d.ts b/node_modules/fast-glob/out/providers/matchers/partial.d.ts new file mode 100644 index 0000000..91520f6 --- /dev/null +++ b/node_modules/fast-glob/out/providers/matchers/partial.d.ts @@ -0,0 +1,4 @@ +import Matcher from './matcher'; +export default class PartialMatcher extends Matcher { + match(filepath: string): boolean; +} diff --git a/node_modules/fast-glob/out/providers/matchers/partial.js b/node_modules/fast-glob/out/providers/matchers/partial.js new file mode 100644 index 0000000..1dfffeb --- /dev/null +++ b/node_modules/fast-glob/out/providers/matchers/partial.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const matcher_1 = require("./matcher"); +class PartialMatcher extends matcher_1.default { + match(filepath) { + const parts = filepath.split('/'); + const levels = parts.length; + const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); + for (const pattern of patterns) { + const section = pattern.sections[0]; + /** + * In this case, the pattern has a globstar and we must read all directories unconditionally, + * but only if the level has reached the end of the first group. + * + * fixtures/{a,b}/** + * ^ true/false ^ always true + */ + if (!pattern.complete && levels > section.length) { + return true; + } + const match = parts.every((part, index) => { + const segment = pattern.segments[index]; + if (segment.dynamic && segment.patternRe.test(part)) { + return true; + } + if (!segment.dynamic && segment.pattern === part) { + return true; + } + return false; + }); + if (match) { + return true; + } + } + return false; + } +} +exports.default = PartialMatcher; diff --git a/node_modules/fast-glob/out/providers/provider.d.ts b/node_modules/fast-glob/out/providers/provider.d.ts new file mode 100644 index 0000000..1053460 --- /dev/null +++ b/node_modules/fast-glob/out/providers/provider.d.ts @@ -0,0 +1,19 @@ +import { Task } from '../managers/tasks'; +import Settings from '../settings'; +import { MicromatchOptions, ReaderOptions } from '../types'; +import DeepFilter from './filters/deep'; +import EntryFilter from './filters/entry'; +import ErrorFilter from './filters/error'; +import EntryTransformer from './transformers/entry'; +export default abstract class Provider { + protected readonly _settings: Settings; + readonly errorFilter: ErrorFilter; + readonly entryFilter: EntryFilter; + readonly deepFilter: DeepFilter; + readonly entryTransformer: EntryTransformer; + constructor(_settings: Settings); + abstract read(_task: Task): T; + protected _getRootDirectory(task: Task): string; + protected _getReaderOptions(task: Task): ReaderOptions; + protected _getMicromatchOptions(): MicromatchOptions; +} diff --git a/node_modules/fast-glob/out/providers/provider.js b/node_modules/fast-glob/out/providers/provider.js new file mode 100644 index 0000000..da88ee0 --- /dev/null +++ b/node_modules/fast-glob/out/providers/provider.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = require("path"); +const deep_1 = require("./filters/deep"); +const entry_1 = require("./filters/entry"); +const error_1 = require("./filters/error"); +const entry_2 = require("./transformers/entry"); +class Provider { + constructor(_settings) { + this._settings = _settings; + this.errorFilter = new error_1.default(this._settings); + this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); + this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); + this.entryTransformer = new entry_2.default(this._settings); + } + _getRootDirectory(task) { + return path.resolve(this._settings.cwd, task.base); + } + _getReaderOptions(task) { + const basePath = task.base === '.' ? '' : task.base; + return { + basePath, + pathSegmentSeparator: '/', + concurrency: this._settings.concurrency, + deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), + entryFilter: this.entryFilter.getFilter(task.positive, task.negative), + errorFilter: this.errorFilter.getFilter(), + followSymbolicLinks: this._settings.followSymbolicLinks, + fs: this._settings.fs, + stats: this._settings.stats, + throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, + transform: this.entryTransformer.getTransformer() + }; + } + _getMicromatchOptions() { + return { + dot: this._settings.dot, + matchBase: this._settings.baseNameMatch, + nobrace: !this._settings.braceExpansion, + nocase: !this._settings.caseSensitiveMatch, + noext: !this._settings.extglob, + noglobstar: !this._settings.globstar, + posix: true, + strictSlashes: false + }; + } +} +exports.default = Provider; diff --git a/node_modules/fast-glob/out/providers/stream.d.ts b/node_modules/fast-glob/out/providers/stream.d.ts new file mode 100644 index 0000000..3d02a1f --- /dev/null +++ b/node_modules/fast-glob/out/providers/stream.d.ts @@ -0,0 +1,11 @@ +/// +import { Readable } from 'stream'; +import { Task } from '../managers/tasks'; +import ReaderStream from '../readers/stream'; +import { ReaderOptions } from '../types'; +import Provider from './provider'; +export default class ProviderStream extends Provider { + protected _reader: ReaderStream; + read(task: Task): Readable; + api(root: string, task: Task, options: ReaderOptions): Readable; +} diff --git a/node_modules/fast-glob/out/providers/stream.js b/node_modules/fast-glob/out/providers/stream.js new file mode 100644 index 0000000..85da62e --- /dev/null +++ b/node_modules/fast-glob/out/providers/stream.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = require("stream"); +const stream_2 = require("../readers/stream"); +const provider_1 = require("./provider"); +class ProviderStream extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new stream_2.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const source = this.api(root, task, options); + const destination = new stream_1.Readable({ objectMode: true, read: () => { } }); + source + .once('error', (error) => destination.emit('error', error)) + .on('data', (entry) => destination.emit('data', options.transform(entry))) + .once('end', () => destination.emit('end')); + destination + .once('close', () => source.destroy()); + return destination; + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +exports.default = ProviderStream; diff --git a/node_modules/fast-glob/out/providers/sync.d.ts b/node_modules/fast-glob/out/providers/sync.d.ts new file mode 100644 index 0000000..9c0fe1e --- /dev/null +++ b/node_modules/fast-glob/out/providers/sync.d.ts @@ -0,0 +1,9 @@ +import { Task } from '../managers/tasks'; +import ReaderSync from '../readers/sync'; +import { Entry, EntryItem, ReaderOptions } from '../types'; +import Provider from './provider'; +export default class ProviderSync extends Provider { + protected _reader: ReaderSync; + read(task: Task): EntryItem[]; + api(root: string, task: Task, options: ReaderOptions): Entry[]; +} diff --git a/node_modules/fast-glob/out/providers/sync.js b/node_modules/fast-glob/out/providers/sync.js new file mode 100644 index 0000000..d70aa1b --- /dev/null +++ b/node_modules/fast-glob/out/providers/sync.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const sync_1 = require("../readers/sync"); +const provider_1 = require("./provider"); +class ProviderSync extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new sync_1.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const entries = this.api(root, task, options); + return entries.map(options.transform); + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +exports.default = ProviderSync; diff --git a/node_modules/fast-glob/out/providers/transformers/entry.d.ts b/node_modules/fast-glob/out/providers/transformers/entry.d.ts new file mode 100644 index 0000000..e9b85fa --- /dev/null +++ b/node_modules/fast-glob/out/providers/transformers/entry.d.ts @@ -0,0 +1,8 @@ +import Settings from '../../settings'; +import { EntryTransformerFunction } from '../../types'; +export default class EntryTransformer { + private readonly _settings; + constructor(_settings: Settings); + getTransformer(): EntryTransformerFunction; + private _transform; +} diff --git a/node_modules/fast-glob/out/providers/transformers/entry.js b/node_modules/fast-glob/out/providers/transformers/entry.js new file mode 100644 index 0000000..d11903c --- /dev/null +++ b/node_modules/fast-glob/out/providers/transformers/entry.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils = require("../../utils"); +class EntryTransformer { + constructor(_settings) { + this._settings = _settings; + } + getTransformer() { + return (entry) => this._transform(entry); + } + _transform(entry) { + let filepath = entry.path; + if (this._settings.absolute) { + filepath = utils.path.makeAbsolute(this._settings.cwd, filepath); + filepath = utils.path.unixify(filepath); + } + if (this._settings.markDirectories && entry.dirent.isDirectory()) { + filepath += '/'; + } + if (!this._settings.objectMode) { + return filepath; + } + return Object.assign(Object.assign({}, entry), { path: filepath }); + } +} +exports.default = EntryTransformer; diff --git a/node_modules/fast-glob/out/readers/async.d.ts b/node_modules/fast-glob/out/readers/async.d.ts new file mode 100644 index 0000000..fbca428 --- /dev/null +++ b/node_modules/fast-glob/out/readers/async.d.ts @@ -0,0 +1,10 @@ +import * as fsWalk from '@nodelib/fs.walk'; +import { Entry, ReaderOptions, Pattern } from '../types'; +import Reader from './reader'; +import ReaderStream from './stream'; +export default class ReaderAsync extends Reader> { + protected _walkAsync: typeof fsWalk.walk; + protected _readerStream: ReaderStream; + dynamic(root: string, options: ReaderOptions): Promise; + static(patterns: Pattern[], options: ReaderOptions): Promise; +} diff --git a/node_modules/fast-glob/out/readers/async.js b/node_modules/fast-glob/out/readers/async.js new file mode 100644 index 0000000..d024145 --- /dev/null +++ b/node_modules/fast-glob/out/readers/async.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const fsWalk = require("@nodelib/fs.walk"); +const reader_1 = require("./reader"); +const stream_1 = require("./stream"); +class ReaderAsync extends reader_1.default { + constructor() { + super(...arguments); + this._walkAsync = fsWalk.walk; + this._readerStream = new stream_1.default(this._settings); + } + dynamic(root, options) { + return new Promise((resolve, reject) => { + this._walkAsync(root, options, (error, entries) => { + if (error === null) { + resolve(entries); + } + else { + reject(error); + } + }); + }); + } + async static(patterns, options) { + const entries = []; + const stream = this._readerStream.static(patterns, options); + // After #235, replace it with an asynchronous iterator. + return new Promise((resolve, reject) => { + stream.once('error', reject); + stream.on('data', (entry) => entries.push(entry)); + stream.once('end', () => resolve(entries)); + }); + } +} +exports.default = ReaderAsync; diff --git a/node_modules/fast-glob/out/readers/reader.d.ts b/node_modules/fast-glob/out/readers/reader.d.ts new file mode 100644 index 0000000..2af16b6 --- /dev/null +++ b/node_modules/fast-glob/out/readers/reader.d.ts @@ -0,0 +1,15 @@ +/// +import * as fs from 'fs'; +import * as fsStat from '@nodelib/fs.stat'; +import Settings from '../settings'; +import { Entry, ErrnoException, Pattern, ReaderOptions } from '../types'; +export default abstract class Reader { + protected readonly _settings: Settings; + protected readonly _fsStatSettings: fsStat.Settings; + constructor(_settings: Settings); + abstract dynamic(root: string, options: ReaderOptions): T; + abstract static(patterns: Pattern[], options: ReaderOptions): T; + protected _getFullEntryPath(filepath: string): string; + protected _makeEntry(stats: fs.Stats, pattern: Pattern): Entry; + protected _isFatalError(error: ErrnoException): boolean; +} diff --git a/node_modules/fast-glob/out/readers/reader.js b/node_modules/fast-glob/out/readers/reader.js new file mode 100644 index 0000000..7b40255 --- /dev/null +++ b/node_modules/fast-glob/out/readers/reader.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = require("path"); +const fsStat = require("@nodelib/fs.stat"); +const utils = require("../utils"); +class Reader { + constructor(_settings) { + this._settings = _settings; + this._fsStatSettings = new fsStat.Settings({ + followSymbolicLink: this._settings.followSymbolicLinks, + fs: this._settings.fs, + throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks + }); + } + _getFullEntryPath(filepath) { + return path.resolve(this._settings.cwd, filepath); + } + _makeEntry(stats, pattern) { + const entry = { + name: pattern, + path: pattern, + dirent: utils.fs.createDirentFromStats(pattern, stats) + }; + if (this._settings.stats) { + entry.stats = stats; + } + return entry; + } + _isFatalError(error) { + return !utils.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; + } +} +exports.default = Reader; diff --git a/node_modules/fast-glob/out/readers/stream.d.ts b/node_modules/fast-glob/out/readers/stream.d.ts new file mode 100644 index 0000000..1c74cac --- /dev/null +++ b/node_modules/fast-glob/out/readers/stream.d.ts @@ -0,0 +1,14 @@ +/// +import { Readable } from 'stream'; +import * as fsStat from '@nodelib/fs.stat'; +import * as fsWalk from '@nodelib/fs.walk'; +import { Pattern, ReaderOptions } from '../types'; +import Reader from './reader'; +export default class ReaderStream extends Reader { + protected _walkStream: typeof fsWalk.walkStream; + protected _stat: typeof fsStat.stat; + dynamic(root: string, options: ReaderOptions): Readable; + static(patterns: Pattern[], options: ReaderOptions): Readable; + private _getEntry; + private _getStat; +} diff --git a/node_modules/fast-glob/out/readers/stream.js b/node_modules/fast-glob/out/readers/stream.js new file mode 100644 index 0000000..317c6d5 --- /dev/null +++ b/node_modules/fast-glob/out/readers/stream.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = require("stream"); +const fsStat = require("@nodelib/fs.stat"); +const fsWalk = require("@nodelib/fs.walk"); +const reader_1 = require("./reader"); +class ReaderStream extends reader_1.default { + constructor() { + super(...arguments); + this._walkStream = fsWalk.walkStream; + this._stat = fsStat.stat; + } + dynamic(root, options) { + return this._walkStream(root, options); + } + static(patterns, options) { + const filepaths = patterns.map(this._getFullEntryPath, this); + const stream = new stream_1.PassThrough({ objectMode: true }); + stream._write = (index, _enc, done) => { + return this._getEntry(filepaths[index], patterns[index], options) + .then((entry) => { + if (entry !== null && options.entryFilter(entry)) { + stream.push(entry); + } + if (index === filepaths.length - 1) { + stream.end(); + } + done(); + }) + .catch(done); + }; + for (let i = 0; i < filepaths.length; i++) { + stream.write(i); + } + return stream; + } + _getEntry(filepath, pattern, options) { + return this._getStat(filepath) + .then((stats) => this._makeEntry(stats, pattern)) + .catch((error) => { + if (options.errorFilter(error)) { + return null; + } + throw error; + }); + } + _getStat(filepath) { + return new Promise((resolve, reject) => { + this._stat(filepath, this._fsStatSettings, (error, stats) => { + return error === null ? resolve(stats) : reject(error); + }); + }); + } +} +exports.default = ReaderStream; diff --git a/node_modules/fast-glob/out/readers/sync.d.ts b/node_modules/fast-glob/out/readers/sync.d.ts new file mode 100644 index 0000000..c96ffee --- /dev/null +++ b/node_modules/fast-glob/out/readers/sync.d.ts @@ -0,0 +1,12 @@ +import * as fsStat from '@nodelib/fs.stat'; +import * as fsWalk from '@nodelib/fs.walk'; +import { Entry, Pattern, ReaderOptions } from '../types'; +import Reader from './reader'; +export default class ReaderSync extends Reader { + protected _walkSync: typeof fsWalk.walkSync; + protected _statSync: typeof fsStat.statSync; + dynamic(root: string, options: ReaderOptions): Entry[]; + static(patterns: Pattern[], options: ReaderOptions): Entry[]; + private _getEntry; + private _getStat; +} diff --git a/node_modules/fast-glob/out/readers/sync.js b/node_modules/fast-glob/out/readers/sync.js new file mode 100644 index 0000000..4704d65 --- /dev/null +++ b/node_modules/fast-glob/out/readers/sync.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const fsStat = require("@nodelib/fs.stat"); +const fsWalk = require("@nodelib/fs.walk"); +const reader_1 = require("./reader"); +class ReaderSync extends reader_1.default { + constructor() { + super(...arguments); + this._walkSync = fsWalk.walkSync; + this._statSync = fsStat.statSync; + } + dynamic(root, options) { + return this._walkSync(root, options); + } + static(patterns, options) { + const entries = []; + for (const pattern of patterns) { + const filepath = this._getFullEntryPath(pattern); + const entry = this._getEntry(filepath, pattern, options); + if (entry === null || !options.entryFilter(entry)) { + continue; + } + entries.push(entry); + } + return entries; + } + _getEntry(filepath, pattern, options) { + try { + const stats = this._getStat(filepath); + return this._makeEntry(stats, pattern); + } + catch (error) { + if (options.errorFilter(error)) { + return null; + } + throw error; + } + } + _getStat(filepath) { + return this._statSync(filepath, this._fsStatSettings); + } +} +exports.default = ReaderSync; diff --git a/node_modules/fast-glob/out/settings.d.ts b/node_modules/fast-glob/out/settings.d.ts new file mode 100644 index 0000000..76a74f8 --- /dev/null +++ b/node_modules/fast-glob/out/settings.d.ts @@ -0,0 +1,164 @@ +import { FileSystemAdapter, Pattern } from './types'; +export declare const DEFAULT_FILE_SYSTEM_ADAPTER: FileSystemAdapter; +export type Options = { + /** + * Return the absolute path for entries. + * + * @default false + */ + absolute?: boolean; + /** + * If set to `true`, then patterns without slashes will be matched against + * the basename of the path if it contains slashes. + * + * @default false + */ + baseNameMatch?: boolean; + /** + * Enables Bash-like brace expansion. + * + * @default true + */ + braceExpansion?: boolean; + /** + * Enables a case-sensitive mode for matching files. + * + * @default true + */ + caseSensitiveMatch?: boolean; + /** + * Specifies the maximum number of concurrent requests from a reader to read + * directories. + * + * @default os.cpus().length + */ + concurrency?: number; + /** + * The current working directory in which to search. + * + * @default process.cwd() + */ + cwd?: string; + /** + * Specifies the maximum depth of a read directory relative to the start + * directory. + * + * @default Infinity + */ + deep?: number; + /** + * Allow patterns to match entries that begin with a period (`.`). + * + * @default false + */ + dot?: boolean; + /** + * Enables Bash-like `extglob` functionality. + * + * @default true + */ + extglob?: boolean; + /** + * Indicates whether to traverse descendants of symbolic link directories. + * + * @default true + */ + followSymbolicLinks?: boolean; + /** + * Custom implementation of methods for working with the file system. + * + * @default fs.* + */ + fs?: Partial; + /** + * Enables recursively repeats a pattern containing `**`. + * If `false`, `**` behaves exactly like `*`. + * + * @default true + */ + globstar?: boolean; + /** + * An array of glob patterns to exclude matches. + * This is an alternative way to use negative patterns. + * + * @default [] + */ + ignore?: Pattern[]; + /** + * Mark the directory path with the final slash. + * + * @default false + */ + markDirectories?: boolean; + /** + * Returns objects (instead of strings) describing entries. + * + * @default false + */ + objectMode?: boolean; + /** + * Return only directories. + * + * @default false + */ + onlyDirectories?: boolean; + /** + * Return only files. + * + * @default true + */ + onlyFiles?: boolean; + /** + * Enables an object mode (`objectMode`) with an additional `stats` field. + * + * @default false + */ + stats?: boolean; + /** + * By default this package suppress only `ENOENT` errors. + * Set to `true` to suppress any error. + * + * @default false + */ + suppressErrors?: boolean; + /** + * Throw an error when symbolic link is broken if `true` or safely + * return `lstat` call if `false`. + * + * @default false + */ + throwErrorOnBrokenSymbolicLink?: boolean; + /** + * Ensures that the returned entries are unique. + * + * @default true + */ + unique?: boolean; +}; +export default class Settings { + private readonly _options; + readonly absolute: boolean; + readonly baseNameMatch: boolean; + readonly braceExpansion: boolean; + readonly caseSensitiveMatch: boolean; + readonly concurrency: number; + readonly cwd: string; + readonly deep: number; + readonly dot: boolean; + readonly extglob: boolean; + readonly followSymbolicLinks: boolean; + readonly fs: FileSystemAdapter; + readonly globstar: boolean; + readonly ignore: Pattern[]; + readonly markDirectories: boolean; + readonly objectMode: boolean; + readonly onlyDirectories: boolean; + readonly onlyFiles: boolean; + readonly stats: boolean; + readonly suppressErrors: boolean; + readonly throwErrorOnBrokenSymbolicLink: boolean; + readonly unique: boolean; + constructor(_options?: Options); + private _getValue; + private _getFileSystemMethods; +} diff --git a/node_modules/fast-glob/out/settings.js b/node_modules/fast-glob/out/settings.js new file mode 100644 index 0000000..23f916c --- /dev/null +++ b/node_modules/fast-glob/out/settings.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; +const fs = require("fs"); +const os = require("os"); +/** + * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. + * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 + */ +const CPU_COUNT = Math.max(os.cpus().length, 1); +exports.DEFAULT_FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + lstatSync: fs.lstatSync, + stat: fs.stat, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync +}; +class Settings { + constructor(_options = {}) { + this._options = _options; + this.absolute = this._getValue(this._options.absolute, false); + this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); + this.braceExpansion = this._getValue(this._options.braceExpansion, true); + this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); + this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); + this.cwd = this._getValue(this._options.cwd, process.cwd()); + this.deep = this._getValue(this._options.deep, Infinity); + this.dot = this._getValue(this._options.dot, false); + this.extglob = this._getValue(this._options.extglob, true); + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); + this.fs = this._getFileSystemMethods(this._options.fs); + this.globstar = this._getValue(this._options.globstar, true); + this.ignore = this._getValue(this._options.ignore, []); + this.markDirectories = this._getValue(this._options.markDirectories, false); + this.objectMode = this._getValue(this._options.objectMode, false); + this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); + this.onlyFiles = this._getValue(this._options.onlyFiles, true); + this.stats = this._getValue(this._options.stats, false); + this.suppressErrors = this._getValue(this._options.suppressErrors, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); + this.unique = this._getValue(this._options.unique, true); + if (this.onlyDirectories) { + this.onlyFiles = false; + } + if (this.stats) { + this.objectMode = true; + } + // Remove the cast to the array in the next major (#404). + this.ignore = [].concat(this.ignore); + } + _getValue(option, value) { + return option === undefined ? value : option; + } + _getFileSystemMethods(methods = {}) { + return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); + } +} +exports.default = Settings; diff --git a/node_modules/fast-glob/out/types/index.d.ts b/node_modules/fast-glob/out/types/index.d.ts new file mode 100644 index 0000000..6506caf --- /dev/null +++ b/node_modules/fast-glob/out/types/index.d.ts @@ -0,0 +1,31 @@ +/// +import * as fsWalk from '@nodelib/fs.walk'; +export type ErrnoException = NodeJS.ErrnoException; +export type Entry = fsWalk.Entry; +export type EntryItem = string | Entry; +export type Pattern = string; +export type PatternRe = RegExp; +export type PatternsGroup = Record; +export type ReaderOptions = fsWalk.Options & { + transform(entry: Entry): EntryItem; + deepFilter: DeepFilterFunction; + entryFilter: EntryFilterFunction; + errorFilter: ErrorFilterFunction; + fs: FileSystemAdapter; + stats: boolean; +}; +export type ErrorFilterFunction = fsWalk.ErrorFilterFunction; +export type EntryFilterFunction = fsWalk.EntryFilterFunction; +export type DeepFilterFunction = fsWalk.DeepFilterFunction; +export type EntryTransformerFunction = (entry: Entry) => EntryItem; +export type MicromatchOptions = { + dot?: boolean; + matchBase?: boolean; + nobrace?: boolean; + nocase?: boolean; + noext?: boolean; + noglobstar?: boolean; + posix?: boolean; + strictSlashes?: boolean; +}; +export type FileSystemAdapter = fsWalk.FileSystemAdapter; diff --git a/node_modules/fast-glob/out/types/index.js b/node_modules/fast-glob/out/types/index.js new file mode 100644 index 0000000..c8ad2e5 --- /dev/null +++ b/node_modules/fast-glob/out/types/index.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/fast-glob/out/utils/array.d.ts b/node_modules/fast-glob/out/utils/array.d.ts new file mode 100644 index 0000000..98e7325 --- /dev/null +++ b/node_modules/fast-glob/out/utils/array.d.ts @@ -0,0 +1,2 @@ +export declare function flatten(items: T[][]): T[]; +export declare function splitWhen(items: T[], predicate: (item: T) => boolean): T[][]; diff --git a/node_modules/fast-glob/out/utils/array.js b/node_modules/fast-glob/out/utils/array.js new file mode 100644 index 0000000..50c406e --- /dev/null +++ b/node_modules/fast-glob/out/utils/array.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.splitWhen = exports.flatten = void 0; +function flatten(items) { + return items.reduce((collection, item) => [].concat(collection, item), []); +} +exports.flatten = flatten; +function splitWhen(items, predicate) { + const result = [[]]; + let groupIndex = 0; + for (const item of items) { + if (predicate(item)) { + groupIndex++; + result[groupIndex] = []; + } + else { + result[groupIndex].push(item); + } + } + return result; +} +exports.splitWhen = splitWhen; diff --git a/node_modules/fast-glob/out/utils/errno.d.ts b/node_modules/fast-glob/out/utils/errno.d.ts new file mode 100644 index 0000000..1c08d3b --- /dev/null +++ b/node_modules/fast-glob/out/utils/errno.d.ts @@ -0,0 +1,2 @@ +import { ErrnoException } from '../types'; +export declare function isEnoentCodeError(error: ErrnoException): boolean; diff --git a/node_modules/fast-glob/out/utils/errno.js b/node_modules/fast-glob/out/utils/errno.js new file mode 100644 index 0000000..f0bd801 --- /dev/null +++ b/node_modules/fast-glob/out/utils/errno.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isEnoentCodeError = void 0; +function isEnoentCodeError(error) { + return error.code === 'ENOENT'; +} +exports.isEnoentCodeError = isEnoentCodeError; diff --git a/node_modules/fast-glob/out/utils/fs.d.ts b/node_modules/fast-glob/out/utils/fs.d.ts new file mode 100644 index 0000000..64c61ce --- /dev/null +++ b/node_modules/fast-glob/out/utils/fs.d.ts @@ -0,0 +1,4 @@ +/// +import * as fs from 'fs'; +import { Dirent } from '@nodelib/fs.walk'; +export declare function createDirentFromStats(name: string, stats: fs.Stats): Dirent; diff --git a/node_modules/fast-glob/out/utils/fs.js b/node_modules/fast-glob/out/utils/fs.js new file mode 100644 index 0000000..ace7c74 --- /dev/null +++ b/node_modules/fast-glob/out/utils/fs.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createDirentFromStats = void 0; +class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } +} +function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); +} +exports.createDirentFromStats = createDirentFromStats; diff --git a/node_modules/fast-glob/out/utils/index.d.ts b/node_modules/fast-glob/out/utils/index.d.ts new file mode 100644 index 0000000..f634cad --- /dev/null +++ b/node_modules/fast-glob/out/utils/index.d.ts @@ -0,0 +1,8 @@ +import * as array from './array'; +import * as errno from './errno'; +import * as fs from './fs'; +import * as path from './path'; +import * as pattern from './pattern'; +import * as stream from './stream'; +import * as string from './string'; +export { array, errno, fs, path, pattern, stream, string }; diff --git a/node_modules/fast-glob/out/utils/index.js b/node_modules/fast-glob/out/utils/index.js new file mode 100644 index 0000000..0f92c16 --- /dev/null +++ b/node_modules/fast-glob/out/utils/index.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0; +const array = require("./array"); +exports.array = array; +const errno = require("./errno"); +exports.errno = errno; +const fs = require("./fs"); +exports.fs = fs; +const path = require("./path"); +exports.path = path; +const pattern = require("./pattern"); +exports.pattern = pattern; +const stream = require("./stream"); +exports.stream = stream; +const string = require("./string"); +exports.string = string; diff --git a/node_modules/fast-glob/out/utils/path.d.ts b/node_modules/fast-glob/out/utils/path.d.ts new file mode 100644 index 0000000..0b13f4b --- /dev/null +++ b/node_modules/fast-glob/out/utils/path.d.ts @@ -0,0 +1,13 @@ +import { Pattern } from '../types'; +/** + * Designed to work only with simple paths: `dir\\file`. + */ +export declare function unixify(filepath: string): string; +export declare function makeAbsolute(cwd: string, filepath: string): string; +export declare function removeLeadingDotSegment(entry: string): string; +export declare const escape: typeof escapeWindowsPath; +export declare function escapeWindowsPath(pattern: Pattern): Pattern; +export declare function escapePosixPath(pattern: Pattern): Pattern; +export declare const convertPathToPattern: typeof convertWindowsPathToPattern; +export declare function convertWindowsPathToPattern(filepath: string): Pattern; +export declare function convertPosixPathToPattern(filepath: string): Pattern; diff --git a/node_modules/fast-glob/out/utils/path.js b/node_modules/fast-glob/out/utils/path.js new file mode 100644 index 0000000..7b53b39 --- /dev/null +++ b/node_modules/fast-glob/out/utils/path.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.convertPosixPathToPattern = exports.convertWindowsPathToPattern = exports.convertPathToPattern = exports.escapePosixPath = exports.escapeWindowsPath = exports.escape = exports.removeLeadingDotSegment = exports.makeAbsolute = exports.unixify = void 0; +const os = require("os"); +const path = require("path"); +const IS_WINDOWS_PLATFORM = os.platform() === 'win32'; +const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ +/** + * All non-escaped special characters. + * Posix: ()*?[]{|}, !+@ before (, ! at the beginning, \\ before non-special characters. + * Windows: (){}[], !+@ before (, ! at the beginning. + */ +const POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g; +const WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()[\]{}]|^!|[!+@](?=\())/g; +/** + * The device path (\\.\ or \\?\). + * https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths + */ +const DOS_DEVICE_PATH_RE = /^\\\\([.?])/; +/** + * All backslashes except those escaping special characters. + * Windows: !()+@{} + * https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions + */ +const WINDOWS_BACKSLASHES_RE = /\\(?![!()+@[\]{}])/g; +/** + * Designed to work only with simple paths: `dir\\file`. + */ +function unixify(filepath) { + return filepath.replace(/\\/g, '/'); +} +exports.unixify = unixify; +function makeAbsolute(cwd, filepath) { + return path.resolve(cwd, filepath); +} +exports.makeAbsolute = makeAbsolute; +function removeLeadingDotSegment(entry) { + // We do not use `startsWith` because this is 10x slower than current implementation for some cases. + // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with + if (entry.charAt(0) === '.') { + const secondCharactery = entry.charAt(1); + if (secondCharactery === '/' || secondCharactery === '\\') { + return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); + } + } + return entry; +} +exports.removeLeadingDotSegment = removeLeadingDotSegment; +exports.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath; +function escapeWindowsPath(pattern) { + return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); +} +exports.escapeWindowsPath = escapeWindowsPath; +function escapePosixPath(pattern) { + return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); +} +exports.escapePosixPath = escapePosixPath; +exports.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern; +function convertWindowsPathToPattern(filepath) { + return escapeWindowsPath(filepath) + .replace(DOS_DEVICE_PATH_RE, '//$1') + .replace(WINDOWS_BACKSLASHES_RE, '/'); +} +exports.convertWindowsPathToPattern = convertWindowsPathToPattern; +function convertPosixPathToPattern(filepath) { + return escapePosixPath(filepath); +} +exports.convertPosixPathToPattern = convertPosixPathToPattern; diff --git a/node_modules/fast-glob/out/utils/pattern.d.ts b/node_modules/fast-glob/out/utils/pattern.d.ts new file mode 100644 index 0000000..e3598a9 --- /dev/null +++ b/node_modules/fast-glob/out/utils/pattern.d.ts @@ -0,0 +1,49 @@ +import { MicromatchOptions, Pattern, PatternRe } from '../types'; +type PatternTypeOptions = { + braceExpansion?: boolean; + caseSensitiveMatch?: boolean; + extglob?: boolean; +}; +export declare function isStaticPattern(pattern: Pattern, options?: PatternTypeOptions): boolean; +export declare function isDynamicPattern(pattern: Pattern, options?: PatternTypeOptions): boolean; +export declare function convertToPositivePattern(pattern: Pattern): Pattern; +export declare function convertToNegativePattern(pattern: Pattern): Pattern; +export declare function isNegativePattern(pattern: Pattern): boolean; +export declare function isPositivePattern(pattern: Pattern): boolean; +export declare function getNegativePatterns(patterns: Pattern[]): Pattern[]; +export declare function getPositivePatterns(patterns: Pattern[]): Pattern[]; +/** + * Returns patterns that can be applied inside the current directory. + * + * @example + * // ['./*', '*', 'a/*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +export declare function getPatternsInsideCurrentDirectory(patterns: Pattern[]): Pattern[]; +/** + * Returns patterns to be expanded relative to (outside) the current directory. + * + * @example + * // ['../*', './../*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +export declare function getPatternsOutsideCurrentDirectory(patterns: Pattern[]): Pattern[]; +export declare function isPatternRelatedToParentDirectory(pattern: Pattern): boolean; +export declare function getBaseDirectory(pattern: Pattern): string; +export declare function hasGlobStar(pattern: Pattern): boolean; +export declare function endsWithSlashGlobStar(pattern: Pattern): boolean; +export declare function isAffectDepthOfReadingPattern(pattern: Pattern): boolean; +export declare function expandPatternsWithBraceExpansion(patterns: Pattern[]): Pattern[]; +export declare function expandBraceExpansion(pattern: Pattern): Pattern[]; +export declare function getPatternParts(pattern: Pattern, options: MicromatchOptions): Pattern[]; +export declare function makeRe(pattern: Pattern, options: MicromatchOptions): PatternRe; +export declare function convertPatternsToRe(patterns: Pattern[], options: MicromatchOptions): PatternRe[]; +export declare function matchAny(entry: string, patternsRe: PatternRe[]): boolean; +/** + * This package only works with forward slashes as a path separator. + * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. + */ +export declare function removeDuplicateSlashes(pattern: string): string; +export declare function partitionAbsoluteAndRelative(patterns: Pattern[]): Pattern[][]; +export declare function isAbsolute(pattern: string): boolean; +export {}; diff --git a/node_modules/fast-glob/out/utils/pattern.js b/node_modules/fast-glob/out/utils/pattern.js new file mode 100644 index 0000000..b2924e7 --- /dev/null +++ b/node_modules/fast-glob/out/utils/pattern.js @@ -0,0 +1,206 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isAbsolute = exports.partitionAbsoluteAndRelative = exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; +const path = require("path"); +const globParent = require("glob-parent"); +const micromatch = require("micromatch"); +const GLOBSTAR = '**'; +const ESCAPE_SYMBOL = '\\'; +const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; +const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/; +const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/; +const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/; +const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./; +/** + * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string. + * The latter is due to the presence of the device path at the beginning of the UNC path. + */ +const DOUBLE_SLASH_RE = /(?!^)\/{2,}/g; +function isStaticPattern(pattern, options = {}) { + return !isDynamicPattern(pattern, options); +} +exports.isStaticPattern = isStaticPattern; +function isDynamicPattern(pattern, options = {}) { + /** + * A special case with an empty string is necessary for matching patterns that start with a forward slash. + * An empty string cannot be a dynamic pattern. + * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. + */ + if (pattern === '') { + return false; + } + /** + * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check + * filepath directly (without read directory). + */ + if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { + return true; + } + if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.braceExpansion !== false && hasBraceExpansion(pattern)) { + return true; + } + return false; +} +exports.isDynamicPattern = isDynamicPattern; +function hasBraceExpansion(pattern) { + const openingBraceIndex = pattern.indexOf('{'); + if (openingBraceIndex === -1) { + return false; + } + const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1); + if (closingBraceIndex === -1) { + return false; + } + const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex); + return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent); +} +function convertToPositivePattern(pattern) { + return isNegativePattern(pattern) ? pattern.slice(1) : pattern; +} +exports.convertToPositivePattern = convertToPositivePattern; +function convertToNegativePattern(pattern) { + return '!' + pattern; +} +exports.convertToNegativePattern = convertToNegativePattern; +function isNegativePattern(pattern) { + return pattern.startsWith('!') && pattern[1] !== '('; +} +exports.isNegativePattern = isNegativePattern; +function isPositivePattern(pattern) { + return !isNegativePattern(pattern); +} +exports.isPositivePattern = isPositivePattern; +function getNegativePatterns(patterns) { + return patterns.filter(isNegativePattern); +} +exports.getNegativePatterns = getNegativePatterns; +function getPositivePatterns(patterns) { + return patterns.filter(isPositivePattern); +} +exports.getPositivePatterns = getPositivePatterns; +/** + * Returns patterns that can be applied inside the current directory. + * + * @example + * // ['./*', '*', 'a/*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +function getPatternsInsideCurrentDirectory(patterns) { + return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); +} +exports.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; +/** + * Returns patterns to be expanded relative to (outside) the current directory. + * + * @example + * // ['../*', './../*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +function getPatternsOutsideCurrentDirectory(patterns) { + return patterns.filter(isPatternRelatedToParentDirectory); +} +exports.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; +function isPatternRelatedToParentDirectory(pattern) { + return pattern.startsWith('..') || pattern.startsWith('./..'); +} +exports.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; +function getBaseDirectory(pattern) { + return globParent(pattern, { flipBackslashes: false }); +} +exports.getBaseDirectory = getBaseDirectory; +function hasGlobStar(pattern) { + return pattern.includes(GLOBSTAR); +} +exports.hasGlobStar = hasGlobStar; +function endsWithSlashGlobStar(pattern) { + return pattern.endsWith('/' + GLOBSTAR); +} +exports.endsWithSlashGlobStar = endsWithSlashGlobStar; +function isAffectDepthOfReadingPattern(pattern) { + const basename = path.basename(pattern); + return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); +} +exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; +function expandPatternsWithBraceExpansion(patterns) { + return patterns.reduce((collection, pattern) => { + return collection.concat(expandBraceExpansion(pattern)); + }, []); +} +exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; +function expandBraceExpansion(pattern) { + const patterns = micromatch.braces(pattern, { expand: true, nodupes: true, keepEscaping: true }); + /** + * Sort the patterns by length so that the same depth patterns are processed side by side. + * `a/{b,}/{c,}/*` – `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']` + */ + patterns.sort((a, b) => a.length - b.length); + /** + * Micromatch can return an empty string in the case of patterns like `{a,}`. + */ + return patterns.filter((pattern) => pattern !== ''); +} +exports.expandBraceExpansion = expandBraceExpansion; +function getPatternParts(pattern, options) { + let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); + /** + * The scan method returns an empty array in some cases. + * See micromatch/picomatch#58 for more details. + */ + if (parts.length === 0) { + parts = [pattern]; + } + /** + * The scan method does not return an empty part for the pattern with a forward slash. + * This is another part of micromatch/picomatch#58. + */ + if (parts[0].startsWith('/')) { + parts[0] = parts[0].slice(1); + parts.unshift(''); + } + return parts; +} +exports.getPatternParts = getPatternParts; +function makeRe(pattern, options) { + return micromatch.makeRe(pattern, options); +} +exports.makeRe = makeRe; +function convertPatternsToRe(patterns, options) { + return patterns.map((pattern) => makeRe(pattern, options)); +} +exports.convertPatternsToRe = convertPatternsToRe; +function matchAny(entry, patternsRe) { + return patternsRe.some((patternRe) => patternRe.test(entry)); +} +exports.matchAny = matchAny; +/** + * This package only works with forward slashes as a path separator. + * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. + */ +function removeDuplicateSlashes(pattern) { + return pattern.replace(DOUBLE_SLASH_RE, '/'); +} +exports.removeDuplicateSlashes = removeDuplicateSlashes; +function partitionAbsoluteAndRelative(patterns) { + const absolute = []; + const relative = []; + for (const pattern of patterns) { + if (isAbsolute(pattern)) { + absolute.push(pattern); + } + else { + relative.push(pattern); + } + } + return [absolute, relative]; +} +exports.partitionAbsoluteAndRelative = partitionAbsoluteAndRelative; +function isAbsolute(pattern) { + return path.isAbsolute(pattern); +} +exports.isAbsolute = isAbsolute; diff --git a/node_modules/fast-glob/out/utils/stream.d.ts b/node_modules/fast-glob/out/utils/stream.d.ts new file mode 100644 index 0000000..4daf913 --- /dev/null +++ b/node_modules/fast-glob/out/utils/stream.d.ts @@ -0,0 +1,4 @@ +/// +/// +import { Readable } from 'stream'; +export declare function merge(streams: Readable[]): NodeJS.ReadableStream; diff --git a/node_modules/fast-glob/out/utils/stream.js b/node_modules/fast-glob/out/utils/stream.js new file mode 100644 index 0000000..b32028c --- /dev/null +++ b/node_modules/fast-glob/out/utils/stream.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.merge = void 0; +const merge2 = require("merge2"); +function merge(streams) { + const mergedStream = merge2(streams); + streams.forEach((stream) => { + stream.once('error', (error) => mergedStream.emit('error', error)); + }); + mergedStream.once('close', () => propagateCloseEventToSources(streams)); + mergedStream.once('end', () => propagateCloseEventToSources(streams)); + return mergedStream; +} +exports.merge = merge; +function propagateCloseEventToSources(streams) { + streams.forEach((stream) => stream.emit('close')); +} diff --git a/node_modules/fast-glob/out/utils/string.d.ts b/node_modules/fast-glob/out/utils/string.d.ts new file mode 100644 index 0000000..c884735 --- /dev/null +++ b/node_modules/fast-glob/out/utils/string.d.ts @@ -0,0 +1,2 @@ +export declare function isString(input: unknown): input is string; +export declare function isEmpty(input: string): boolean; diff --git a/node_modules/fast-glob/out/utils/string.js b/node_modules/fast-glob/out/utils/string.js new file mode 100644 index 0000000..76e7ea5 --- /dev/null +++ b/node_modules/fast-glob/out/utils/string.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isEmpty = exports.isString = void 0; +function isString(input) { + return typeof input === 'string'; +} +exports.isString = isString; +function isEmpty(input) { + return input === ''; +} +exports.isEmpty = isEmpty; diff --git a/node_modules/fast-glob/package.json b/node_modules/fast-glob/package.json new file mode 100644 index 0000000..e910de9 --- /dev/null +++ b/node_modules/fast-glob/package.json @@ -0,0 +1,81 @@ +{ + "name": "fast-glob", + "version": "3.3.3", + "description": "It's a very fast and efficient glob library for Node.js", + "license": "MIT", + "repository": "mrmlnc/fast-glob", + "author": { + "name": "Denis Malinochkin", + "url": "https://mrmlnc.com" + }, + "engines": { + "node": ">=8.6.0" + }, + "main": "out/index.js", + "typings": "out/index.d.ts", + "files": [ + "out", + "!out/{benchmark,tests}", + "!out/**/*.map", + "!out/**/*.spec.*" + ], + "keywords": [ + "glob", + "patterns", + "fast", + "implementation" + ], + "devDependencies": { + "@nodelib/fs.macchiato": "^1.0.1", + "@types/glob-parent": "^5.1.0", + "@types/merge2": "^1.1.4", + "@types/micromatch": "^4.0.0", + "@types/mocha": "^5.2.7", + "@types/node": "^14.18.53", + "@types/picomatch": "^2.3.0", + "@types/sinon": "^7.5.0", + "bencho": "^0.1.1", + "eslint": "^6.5.1", + "eslint-config-mrmlnc": "^1.1.0", + "execa": "^7.1.1", + "fast-glob": "^3.0.4", + "fdir": "6.0.1", + "glob": "^10.0.0", + "hereby": "^1.8.1", + "mocha": "^6.2.1", + "rimraf": "^5.0.0", + "sinon": "^7.5.0", + "snap-shot-it": "^7.9.10", + "typescript": "^4.9.5" + }, + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "scripts": { + "clean": "rimraf out", + "lint": "eslint \"src/**/*.ts\" --cache", + "compile": "tsc", + "test": "mocha \"out/**/*.spec.js\" -s 0", + "test:e2e": "mocha \"out/**/*.e2e.js\" -s 0", + "test:e2e:sync": "mocha \"out/**/*.e2e.js\" -s 0 --grep \"\\(sync\\)\"", + "test:e2e:async": "mocha \"out/**/*.e2e.js\" -s 0 --grep \"\\(async\\)\"", + "test:e2e:stream": "mocha \"out/**/*.e2e.js\" -s 0 --grep \"\\(stream\\)\"", + "build": "npm run clean && npm run compile && npm run lint && npm test", + "watch": "npm run clean && npm run compile -- -- --sourceMap --watch", + "bench:async": "npm run bench:product:async && npm run bench:regression:async", + "bench:stream": "npm run bench:product:stream && npm run bench:regression:stream", + "bench:sync": "npm run bench:product:sync && npm run bench:regression:sync", + "bench:product": "npm run bench:product:async && npm run bench:product:sync && npm run bench:product:stream", + "bench:product:async": "hereby bench:product:async", + "bench:product:sync": "hereby bench:product:sync", + "bench:product:stream": "hereby bench:product:stream", + "bench:regression": "npm run bench:regression:async && npm run bench:regression:sync && npm run bench:regression:stream", + "bench:regression:async": "hereby bench:regression:async", + "bench:regression:sync": "hereby bench:regression:sync", + "bench:regression:stream": "hereby bench:regression:stream" + } +} diff --git a/node_modules/fastq/.github/dependabot.yml b/node_modules/fastq/.github/dependabot.yml new file mode 100644 index 0000000..7e7cbe1 --- /dev/null +++ b/node_modules/fastq/.github/dependabot.yml @@ -0,0 +1,11 @@ +version: 2 +updates: +- package-ecosystem: npm + directory: "/" + schedule: + interval: daily + open-pull-requests-limit: 10 + ignore: + - dependency-name: standard + versions: + - 16.0.3 diff --git a/node_modules/fastq/.github/workflows/ci.yml b/node_modules/fastq/.github/workflows/ci.yml new file mode 100644 index 0000000..09dc7a3 --- /dev/null +++ b/node_modules/fastq/.github/workflows/ci.yml @@ -0,0 +1,75 @@ +name: ci + +on: [push, pull_request] + +jobs: + legacy: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: ['0.10', '0.12', 4.x, 6.x, 8.x, 10.x, 12.x, 13.x, 14.x, 15.x, 16.x] + + steps: + - uses: actions/checkout@v3 + with: + persist-credentials: false + + - name: Use Node.js + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + + - name: Install + run: | + npm install --production && npm install tape + + - name: Run tests + run: | + npm run legacy + + test: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [18.x, 20.x, 22.x] + + steps: + - uses: actions/checkout@v3 + with: + persist-credentials: false + + - name: Use Node.js + uses: actions/setup-node@v3 + with: + node-version: ${{ matrix.node-version }} + + - name: Install + run: | + npm install + + - name: Run tests + run: | + npm run test + + types: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + with: + persist-credentials: false + + - name: Use Node.js + uses: actions/setup-node@v3 + with: + node-version: 16 + + - name: Install + run: | + npm install + + - name: Run types tests + run: | + npm run typescript diff --git a/node_modules/fastq/LICENSE b/node_modules/fastq/LICENSE new file mode 100644 index 0000000..27c7bb4 --- /dev/null +++ b/node_modules/fastq/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2015-2020, Matteo Collina + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/fastq/README.md b/node_modules/fastq/README.md new file mode 100644 index 0000000..1644111 --- /dev/null +++ b/node_modules/fastq/README.md @@ -0,0 +1,312 @@ +# fastq + +![ci][ci-url] +[![npm version][npm-badge]][npm-url] + +Fast, in memory work queue. + +Benchmarks (1 million tasks): + +* setImmediate: 812ms +* fastq: 854ms +* async.queue: 1298ms +* neoAsync.queue: 1249ms + +Obtained on node 12.16.1, on a dedicated server. + +If you need zero-overhead series function call, check out +[fastseries](http://npm.im/fastseries). For zero-overhead parallel +function call, check out [fastparallel](http://npm.im/fastparallel). + +[![js-standard-style](https://raw.githubusercontent.com/feross/standard/master/badge.png)](https://github.com/feross/standard) + + * Installation + * Usage + * API + * Licence & copyright + +## Install + +`npm i fastq --save` + +## Usage (callback API) + +```js +'use strict' + +const queue = require('fastq')(worker, 1) + +queue.push(42, function (err, result) { + if (err) { throw err } + console.log('the result is', result) +}) + +function worker (arg, cb) { + cb(null, arg * 2) +} +``` + +## Usage (promise API) + +```js +const queue = require('fastq').promise(worker, 1) + +async function worker (arg) { + return arg * 2 +} + +async function run () { + const result = await queue.push(42) + console.log('the result is', result) +} + +run() +``` + +### Setting "this" + +```js +'use strict' + +const that = { hello: 'world' } +const queue = require('fastq')(that, worker, 1) + +queue.push(42, function (err, result) { + if (err) { throw err } + console.log(this) + console.log('the result is', result) +}) + +function worker (arg, cb) { + console.log(this) + cb(null, arg * 2) +} +``` + +### Using with TypeScript (callback API) + +```ts +'use strict' + +import * as fastq from "fastq"; +import type { queue, done } from "fastq"; + +type Task = { + id: number +} + +const q: queue = fastq(worker, 1) + +q.push({ id: 42}) + +function worker (arg: Task, cb: done) { + console.log(arg.id) + cb(null) +} +``` + +### Using with TypeScript (promise API) + +```ts +'use strict' + +import * as fastq from "fastq"; +import type { queueAsPromised } from "fastq"; + +type Task = { + id: number +} + +const q: queueAsPromised = fastq.promise(asyncWorker, 1) + +q.push({ id: 42}).catch((err) => console.error(err)) + +async function asyncWorker (arg: Task): Promise { + // No need for a try-catch block, fastq handles errors automatically + console.log(arg.id) +} +``` + +## API + +* fastqueue() +* queue#push() +* queue#unshift() +* queue#pause() +* queue#resume() +* queue#idle() +* queue#length() +* queue#getQueue() +* queue#kill() +* queue#killAndDrain() +* queue#error() +* queue#concurrency +* queue#drain +* queue#empty +* queue#saturated +* fastqueue.promise() + +------------------------------------------------------- + +### fastqueue([that], worker, concurrency) + +Creates a new queue. + +Arguments: + +* `that`, optional context of the `worker` function. +* `worker`, worker function, it would be called with `that` as `this`, + if that is specified. +* `concurrency`, number of concurrent tasks that could be executed in + parallel. + +------------------------------------------------------- + +### queue.push(task, done) + +Add a task at the end of the queue. `done(err, result)` will be called +when the task was processed. + +------------------------------------------------------- + +### queue.unshift(task, done) + +Add a task at the beginning of the queue. `done(err, result)` will be called +when the task was processed. + +------------------------------------------------------- + +### queue.pause() + +Pause the processing of tasks. Currently worked tasks are not +stopped. + +------------------------------------------------------- + +### queue.resume() + +Resume the processing of tasks. + +------------------------------------------------------- + +### queue.idle() + +Returns `false` if there are tasks being processed or waiting to be processed. +`true` otherwise. + +------------------------------------------------------- + +### queue.length() + +Returns the number of tasks waiting to be processed (in the queue). + +------------------------------------------------------- + +### queue.getQueue() + +Returns all the tasks be processed (in the queue). Returns empty array when there are no tasks + +------------------------------------------------------- + +### queue.kill() + +Removes all tasks waiting to be processed, and reset `drain` to an empty +function. + +------------------------------------------------------- + +### queue.killAndDrain() + +Same than `kill` but the `drain` function will be called before reset to empty. + +------------------------------------------------------- + +### queue.error(handler) + +Set a global error handler. `handler(err, task)` will be called +each time a task is completed, `err` will be not null if the task has thrown an error. + +------------------------------------------------------- + +### queue.concurrency + +Property that returns the number of concurrent tasks that could be executed in +parallel. It can be altered at runtime. + +------------------------------------------------------- + +### queue.paused + +Property (Read-Only) that returns `true` when the queue is in a paused state. + +------------------------------------------------------- + +### queue.drain + +Function that will be called when the last +item from the queue has been processed by a worker. +It can be altered at runtime. + +------------------------------------------------------- + +### queue.empty + +Function that will be called when the last +item from the queue has been assigned to a worker. +It can be altered at runtime. + +------------------------------------------------------- + +### queue.saturated + +Function that will be called when the queue hits the concurrency +limit. +It can be altered at runtime. + +------------------------------------------------------- + +### fastqueue.promise([that], worker(arg), concurrency) + +Creates a new queue with `Promise` apis. It also offers all the methods +and properties of the object returned by [`fastqueue`](#fastqueue) with the modified +[`push`](#pushPromise) and [`unshift`](#unshiftPromise) methods. + +Node v10+ is required to use the promisified version. + +Arguments: +* `that`, optional context of the `worker` function. +* `worker`, worker function, it would be called with `that` as `this`, + if that is specified. It MUST return a `Promise`. +* `concurrency`, number of concurrent tasks that could be executed in + parallel. + + +#### queue.push(task) => Promise + +Add a task at the end of the queue. The returned `Promise` will be fulfilled (rejected) +when the task is completed successfully (unsuccessfully). + +This promise could be ignored as it will not lead to a `'unhandledRejection'`. + + +#### queue.unshift(task) => Promise + +Add a task at the beginning of the queue. The returned `Promise` will be fulfilled (rejected) +when the task is completed successfully (unsuccessfully). + +This promise could be ignored as it will not lead to a `'unhandledRejection'`. + + +#### queue.drained() => Promise + +Wait for the queue to be drained. The returned `Promise` will be resolved when all tasks in the queue have been processed by a worker. + +This promise could be ignored as it will not lead to a `'unhandledRejection'`. + +## License + +ISC + +[ci-url]: https://github.com/mcollina/fastq/workflows/ci/badge.svg +[npm-badge]: https://badge.fury.io/js/fastq.svg +[npm-url]: https://badge.fury.io/js/fastq diff --git a/node_modules/fastq/SECURITY.md b/node_modules/fastq/SECURITY.md new file mode 100644 index 0000000..dd9f1d5 --- /dev/null +++ b/node_modules/fastq/SECURITY.md @@ -0,0 +1,15 @@ +# Security Policy + +## Supported Versions + +Use this section to tell people about which versions of your project are +currently being supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 1.x | :white_check_mark: | +| < 1.0 | :x: | + +## Reporting a Vulnerability + +Please report all vulnerabilities at [https://github.com/mcollina/fastq/security](https://github.com/mcollina/fastq/security). diff --git a/node_modules/fastq/bench.js b/node_modules/fastq/bench.js new file mode 100644 index 0000000..4eaa829 --- /dev/null +++ b/node_modules/fastq/bench.js @@ -0,0 +1,66 @@ +'use strict' + +const max = 1000000 +const fastqueue = require('./')(worker, 1) +const { promisify } = require('util') +const immediate = promisify(setImmediate) +const qPromise = require('./').promise(immediate, 1) +const async = require('async') +const neo = require('neo-async') +const asyncqueue = async.queue(worker, 1) +const neoqueue = neo.queue(worker, 1) + +function bench (func, done) { + const key = max + '*' + func.name + let count = -1 + + console.time(key) + end() + + function end () { + if (++count < max) { + func(end) + } else { + console.timeEnd(key) + if (done) { + done() + } + } + } +} + +function benchFastQ (done) { + fastqueue.push(42, done) +} + +function benchAsyncQueue (done) { + asyncqueue.push(42, done) +} + +function benchNeoQueue (done) { + neoqueue.push(42, done) +} + +function worker (arg, cb) { + setImmediate(cb) +} + +function benchSetImmediate (cb) { + worker(42, cb) +} + +function benchFastQPromise (done) { + qPromise.push(42).then(function () { done() }, done) +} + +function runBench (done) { + async.eachSeries([ + benchSetImmediate, + benchFastQ, + benchNeoQueue, + benchAsyncQueue, + benchFastQPromise + ], bench, done) +} + +runBench(runBench) diff --git a/node_modules/fastq/example.js b/node_modules/fastq/example.js new file mode 100644 index 0000000..665fdc8 --- /dev/null +++ b/node_modules/fastq/example.js @@ -0,0 +1,14 @@ +'use strict' + +/* eslint-disable no-var */ + +var queue = require('./')(worker, 1) + +queue.push(42, function (err, result) { + if (err) { throw err } + console.log('the result is', result) +}) + +function worker (arg, cb) { + cb(null, 42 * 2) +} diff --git a/node_modules/fastq/example.mjs b/node_modules/fastq/example.mjs new file mode 100644 index 0000000..81be789 --- /dev/null +++ b/node_modules/fastq/example.mjs @@ -0,0 +1,11 @@ +import { promise as queueAsPromised } from './queue.js' + +/* eslint-disable */ + +const queue = queueAsPromised(worker, 1) + +console.log('the result is', await queue.push(42)) + +async function worker (arg) { + return 42 * 2 +} diff --git a/node_modules/fastq/index.d.ts b/node_modules/fastq/index.d.ts new file mode 100644 index 0000000..817cdb5 --- /dev/null +++ b/node_modules/fastq/index.d.ts @@ -0,0 +1,57 @@ +declare function fastq(context: C, worker: fastq.worker, concurrency: number): fastq.queue +declare function fastq(worker: fastq.worker, concurrency: number): fastq.queue + +declare namespace fastq { + type worker = (this: C, task: T, cb: fastq.done) => void + type asyncWorker = (this: C, task: T) => Promise + type done = (err: Error | null, result?: R) => void + type errorHandler = (err: Error, task: T) => void + + interface queue { + /** Add a task at the end of the queue. `done(err, result)` will be called when the task was processed. */ + push(task: T, done?: done): void + /** Add a task at the beginning of the queue. `done(err, result)` will be called when the task was processed. */ + unshift(task: T, done?: done): void + /** Pause the processing of tasks. Currently worked tasks are not stopped. */ + pause(): any + /** Resume the processing of tasks. */ + resume(): any + running(): number + /** Returns `false` if there are tasks being processed or waiting to be processed. `true` otherwise. */ + idle(): boolean + /** Returns the number of tasks waiting to be processed (in the queue). */ + length(): number + /** Returns all the tasks be processed (in the queue). Returns empty array when there are no tasks */ + getQueue(): T[] + /** Removes all tasks waiting to be processed, and reset `drain` to an empty function. */ + kill(): any + /** Same than `kill` but the `drain` function will be called before reset to empty. */ + killAndDrain(): any + /** Set a global error handler. `handler(err, task)` will be called each time a task is completed, `err` will be not null if the task has thrown an error. */ + error(handler: errorHandler): void + /** Property that returns the number of concurrent tasks that could be executed in parallel. It can be altered at runtime. */ + concurrency: number + /** Property (Read-Only) that returns `true` when the queue is in a paused state. */ + readonly paused: boolean + /** Function that will be called when the last item from the queue has been processed by a worker. It can be altered at runtime. */ + drain(): any + /** Function that will be called when the last item from the queue has been assigned to a worker. It can be altered at runtime. */ + empty: () => void + /** Function that will be called when the queue hits the concurrency limit. It can be altered at runtime. */ + saturated: () => void + } + + interface queueAsPromised extends queue { + /** Add a task at the end of the queue. The returned `Promise` will be fulfilled (rejected) when the task is completed successfully (unsuccessfully). */ + push(task: T): Promise + /** Add a task at the beginning of the queue. The returned `Promise` will be fulfilled (rejected) when the task is completed successfully (unsuccessfully). */ + unshift(task: T): Promise + /** Wait for the queue to be drained. The returned `Promise` will be resolved when all tasks in the queue have been processed by a worker. */ + drained(): Promise + } + + function promise(context: C, worker: fastq.asyncWorker, concurrency: number): fastq.queueAsPromised + function promise(worker: fastq.asyncWorker, concurrency: number): fastq.queueAsPromised +} + +export = fastq diff --git a/node_modules/fastq/package.json b/node_modules/fastq/package.json new file mode 100644 index 0000000..989151f --- /dev/null +++ b/node_modules/fastq/package.json @@ -0,0 +1,53 @@ +{ + "name": "fastq", + "version": "1.19.1", + "description": "Fast, in memory work queue", + "main": "queue.js", + "scripts": { + "lint": "standard --verbose | snazzy", + "unit": "nyc --lines 100 --branches 100 --functions 100 --check-coverage --reporter=text tape test/test.js test/promise.js", + "coverage": "nyc --reporter=html --reporter=cobertura --reporter=text tape test/test.js test/promise.js", + "test:report": "npm run lint && npm run unit:report", + "test": "npm run lint && npm run unit", + "typescript": "tsc --project ./test/tsconfig.json", + "legacy": "tape test/test.js" + }, + "pre-commit": [ + "test", + "typescript" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/mcollina/fastq.git" + }, + "keywords": [ + "fast", + "queue", + "async", + "worker" + ], + "author": "Matteo Collina ", + "license": "ISC", + "bugs": { + "url": "https://github.com/mcollina/fastq/issues" + }, + "homepage": "https://github.com/mcollina/fastq#readme", + "devDependencies": { + "async": "^3.1.0", + "neo-async": "^2.6.1", + "nyc": "^17.0.0", + "pre-commit": "^1.2.2", + "snazzy": "^9.0.0", + "standard": "^16.0.0", + "tape": "^5.0.0", + "typescript": "^5.0.4" + }, + "dependencies": { + "reusify": "^1.0.4" + }, + "standard": { + "ignore": [ + "example.mjs" + ] + } +} diff --git a/node_modules/fastq/queue.js b/node_modules/fastq/queue.js new file mode 100644 index 0000000..7ea8a31 --- /dev/null +++ b/node_modules/fastq/queue.js @@ -0,0 +1,311 @@ +'use strict' + +/* eslint-disable no-var */ + +var reusify = require('reusify') + +function fastqueue (context, worker, _concurrency) { + if (typeof context === 'function') { + _concurrency = worker + worker = context + context = null + } + + if (!(_concurrency >= 1)) { + throw new Error('fastqueue concurrency must be equal to or greater than 1') + } + + var cache = reusify(Task) + var queueHead = null + var queueTail = null + var _running = 0 + var errorHandler = null + + var self = { + push: push, + drain: noop, + saturated: noop, + pause: pause, + paused: false, + + get concurrency () { + return _concurrency + }, + set concurrency (value) { + if (!(value >= 1)) { + throw new Error('fastqueue concurrency must be equal to or greater than 1') + } + _concurrency = value + + if (self.paused) return + for (; queueHead && _running < _concurrency;) { + _running++ + release() + } + }, + + running: running, + resume: resume, + idle: idle, + length: length, + getQueue: getQueue, + unshift: unshift, + empty: noop, + kill: kill, + killAndDrain: killAndDrain, + error: error + } + + return self + + function running () { + return _running + } + + function pause () { + self.paused = true + } + + function length () { + var current = queueHead + var counter = 0 + + while (current) { + current = current.next + counter++ + } + + return counter + } + + function getQueue () { + var current = queueHead + var tasks = [] + + while (current) { + tasks.push(current.value) + current = current.next + } + + return tasks + } + + function resume () { + if (!self.paused) return + self.paused = false + if (queueHead === null) { + _running++ + release() + return + } + for (; queueHead && _running < _concurrency;) { + _running++ + release() + } + } + + function idle () { + return _running === 0 && self.length() === 0 + } + + function push (value, done) { + var current = cache.get() + + current.context = context + current.release = release + current.value = value + current.callback = done || noop + current.errorHandler = errorHandler + + if (_running >= _concurrency || self.paused) { + if (queueTail) { + queueTail.next = current + queueTail = current + } else { + queueHead = current + queueTail = current + self.saturated() + } + } else { + _running++ + worker.call(context, current.value, current.worked) + } + } + + function unshift (value, done) { + var current = cache.get() + + current.context = context + current.release = release + current.value = value + current.callback = done || noop + current.errorHandler = errorHandler + + if (_running >= _concurrency || self.paused) { + if (queueHead) { + current.next = queueHead + queueHead = current + } else { + queueHead = current + queueTail = current + self.saturated() + } + } else { + _running++ + worker.call(context, current.value, current.worked) + } + } + + function release (holder) { + if (holder) { + cache.release(holder) + } + var next = queueHead + if (next && _running <= _concurrency) { + if (!self.paused) { + if (queueTail === queueHead) { + queueTail = null + } + queueHead = next.next + next.next = null + worker.call(context, next.value, next.worked) + if (queueTail === null) { + self.empty() + } + } else { + _running-- + } + } else if (--_running === 0) { + self.drain() + } + } + + function kill () { + queueHead = null + queueTail = null + self.drain = noop + } + + function killAndDrain () { + queueHead = null + queueTail = null + self.drain() + self.drain = noop + } + + function error (handler) { + errorHandler = handler + } +} + +function noop () {} + +function Task () { + this.value = null + this.callback = noop + this.next = null + this.release = noop + this.context = null + this.errorHandler = null + + var self = this + + this.worked = function worked (err, result) { + var callback = self.callback + var errorHandler = self.errorHandler + var val = self.value + self.value = null + self.callback = noop + if (self.errorHandler) { + errorHandler(err, val) + } + callback.call(self.context, err, result) + self.release(self) + } +} + +function queueAsPromised (context, worker, _concurrency) { + if (typeof context === 'function') { + _concurrency = worker + worker = context + context = null + } + + function asyncWrapper (arg, cb) { + worker.call(this, arg) + .then(function (res) { + cb(null, res) + }, cb) + } + + var queue = fastqueue(context, asyncWrapper, _concurrency) + + var pushCb = queue.push + var unshiftCb = queue.unshift + + queue.push = push + queue.unshift = unshift + queue.drained = drained + + return queue + + function push (value) { + var p = new Promise(function (resolve, reject) { + pushCb(value, function (err, result) { + if (err) { + reject(err) + return + } + resolve(result) + }) + }) + + // Let's fork the promise chain to + // make the error bubble up to the user but + // not lead to a unhandledRejection + p.catch(noop) + + return p + } + + function unshift (value) { + var p = new Promise(function (resolve, reject) { + unshiftCb(value, function (err, result) { + if (err) { + reject(err) + return + } + resolve(result) + }) + }) + + // Let's fork the promise chain to + // make the error bubble up to the user but + // not lead to a unhandledRejection + p.catch(noop) + + return p + } + + function drained () { + var p = new Promise(function (resolve) { + process.nextTick(function () { + if (queue.idle()) { + resolve() + } else { + var previousDrain = queue.drain + queue.drain = function () { + if (typeof previousDrain === 'function') previousDrain() + resolve() + queue.drain = previousDrain + } + } + }) + }) + + return p + } +} + +module.exports = fastqueue +module.exports.promise = queueAsPromised diff --git a/node_modules/fastq/test/example.ts b/node_modules/fastq/test/example.ts new file mode 100644 index 0000000..a47d441 --- /dev/null +++ b/node_modules/fastq/test/example.ts @@ -0,0 +1,83 @@ +import * as fastq from '../' +import { promise as queueAsPromised } from '../' + +// Basic example + +const queue = fastq(worker, 1) + +queue.push('world', (err, result) => { + if (err) throw err + console.log('the result is', result) +}) + +queue.push('push without cb') + +queue.concurrency + +queue.drain() + +queue.empty = () => undefined + +console.log('the queue tasks are', queue.getQueue()) + +queue.idle() + +queue.kill() + +queue.killAndDrain() + +queue.length + +queue.pause() + +queue.resume() + +queue.running() + +queue.saturated = () => undefined + +queue.unshift('world', (err, result) => { + if (err) throw err + console.log('the result is', result) +}) + +queue.unshift('unshift without cb') + +function worker(task: any, cb: fastq.done) { + cb(null, 'hello ' + task) +} + +// Generics example + +interface GenericsContext { + base: number; +} + +const genericsQueue = fastq({ base: 6 }, genericsWorker, 1) + +genericsQueue.push(7, (err, done) => { + if (err) throw err + console.log('the result is', done) +}) + +genericsQueue.unshift(7, (err, done) => { + if (err) throw err + console.log('the result is', done) +}) + +function genericsWorker(this: GenericsContext, task: number, cb: fastq.done) { + cb(null, 'the meaning of life is ' + (this.base * task)) +} + +const queue2 = queueAsPromised(asyncWorker, 1) + +async function asyncWorker(task: any) { + return 'hello ' + task +} + +async function run () { + await queue.push(42) + await queue.unshift(42) +} + +run() diff --git a/node_modules/fastq/test/promise.js b/node_modules/fastq/test/promise.js new file mode 100644 index 0000000..45349a4 --- /dev/null +++ b/node_modules/fastq/test/promise.js @@ -0,0 +1,291 @@ +'use strict' + +const test = require('tape') +const buildQueue = require('../').promise +const { promisify } = require('util') +const sleep = promisify(setTimeout) +const immediate = promisify(setImmediate) + +test('concurrency', function (t) { + t.plan(2) + t.throws(buildQueue.bind(null, worker, 0)) + t.doesNotThrow(buildQueue.bind(null, worker, 1)) + + async function worker (arg) { + return true + } +}) + +test('worker execution', async function (t) { + const queue = buildQueue(worker, 1) + + const result = await queue.push(42) + + t.equal(result, true, 'result matches') + + async function worker (arg) { + t.equal(arg, 42) + return true + } +}) + +test('limit', async function (t) { + const queue = buildQueue(worker, 1) + + const [res1, res2] = await Promise.all([queue.push(10), queue.push(0)]) + t.equal(res1, 10, 'the result matches') + t.equal(res2, 0, 'the result matches') + + async function worker (arg) { + await sleep(arg) + return arg + } +}) + +test('multiple executions', async function (t) { + const queue = buildQueue(worker, 1) + const toExec = [1, 2, 3, 4, 5] + const expected = ['a', 'b', 'c', 'd', 'e'] + let count = 0 + + await Promise.all(toExec.map(async function (task, i) { + const result = await queue.push(task) + t.equal(result, expected[i], 'the result matches') + })) + + async function worker (arg) { + t.equal(arg, toExec[count], 'arg matches') + return expected[count++] + } +}) + +test('drained', async function (t) { + const queue = buildQueue(worker, 2) + + const toExec = new Array(10).fill(10) + let count = 0 + + async function worker (arg) { + await sleep(arg) + count++ + } + + toExec.forEach(function (i) { + queue.push(i) + }) + + await queue.drained() + + t.equal(count, toExec.length) + + toExec.forEach(function (i) { + queue.push(i) + }) + + await queue.drained() + + t.equal(count, toExec.length * 2) +}) + +test('drained with exception should not throw', async function (t) { + const queue = buildQueue(worker, 2) + + const toExec = new Array(10).fill(10) + + async function worker () { + throw new Error('foo') + } + + toExec.forEach(function (i) { + queue.push(i) + }) + + await queue.drained() +}) + +test('drained with drain function', async function (t) { + let drainCalled = false + const queue = buildQueue(worker, 2) + + queue.drain = function () { + drainCalled = true + } + + const toExec = new Array(10).fill(10) + let count = 0 + + async function worker (arg) { + await sleep(arg) + count++ + } + + toExec.forEach(function () { + queue.push() + }) + + await queue.drained() + + t.equal(count, toExec.length) + t.equal(drainCalled, true) +}) + +test('drained while idle should resolve', async function (t) { + const queue = buildQueue(worker, 2) + + async function worker (arg) { + await sleep(arg) + } + + await queue.drained() +}) + +test('drained while idle should not call the drain function', async function (t) { + let drainCalled = false + const queue = buildQueue(worker, 2) + + queue.drain = function () { + drainCalled = true + } + + async function worker (arg) { + await sleep(arg) + } + + await queue.drained() + + t.equal(drainCalled, false) +}) + +test('set this', async function (t) { + t.plan(1) + const that = {} + const queue = buildQueue(that, worker, 1) + + await queue.push(42) + + async function worker (arg) { + t.equal(this, that, 'this matches') + } +}) + +test('unshift', async function (t) { + const queue = buildQueue(worker, 1) + const expected = [1, 2, 3, 4] + + await Promise.all([ + queue.push(1), + queue.push(4), + queue.unshift(3), + queue.unshift(2) + ]) + + t.is(expected.length, 0) + + async function worker (arg) { + t.equal(expected.shift(), arg, 'tasks come in order') + } +}) + +test('push with worker throwing error', async function (t) { + t.plan(5) + const q = buildQueue(async function (task, cb) { + throw new Error('test error') + }, 1) + q.error(function (err, task) { + t.ok(err instanceof Error, 'global error handler should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + t.equal(task, 42, 'The task executed should be passed') + }) + try { + await q.push(42) + } catch (err) { + t.ok(err instanceof Error, 'push callback should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + } +}) + +test('unshift with worker throwing error', async function (t) { + t.plan(2) + const q = buildQueue(async function (task, cb) { + throw new Error('test error') + }, 1) + try { + await q.unshift(42) + } catch (err) { + t.ok(err instanceof Error, 'push callback should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + } +}) + +test('no unhandledRejection (push)', async function (t) { + function handleRejection () { + t.fail('unhandledRejection') + } + process.once('unhandledRejection', handleRejection) + const q = buildQueue(async function (task, cb) { + throw new Error('test error') + }, 1) + + q.push(42) + + await immediate() + process.removeListener('unhandledRejection', handleRejection) +}) + +test('no unhandledRejection (unshift)', async function (t) { + function handleRejection () { + t.fail('unhandledRejection') + } + process.once('unhandledRejection', handleRejection) + const q = buildQueue(async function (task, cb) { + throw new Error('test error') + }, 1) + + q.unshift(42) + + await immediate() + process.removeListener('unhandledRejection', handleRejection) +}) + +test('drained should resolve after async tasks complete', async function (t) { + const logs = [] + + async function processTask () { + await new Promise(resolve => setTimeout(resolve, 0)) + logs.push('processed') + } + + const queue = buildQueue(processTask, 1) + queue.drain = () => logs.push('called drain') + + queue.drained().then(() => logs.push('drained promise resolved')) + + await Promise.all([ + queue.push(), + queue.push(), + queue.push() + ]) + + t.deepEqual(logs, [ + 'processed', + 'processed', + 'processed', + 'called drain', + 'drained promise resolved' + ], 'events happened in correct order') +}) + +test('drained should handle undefined drain function', async function (t) { + const queue = buildQueue(worker, 1) + + async function worker (arg) { + await sleep(10) + return arg + } + + queue.drain = undefined + queue.push(1) + await queue.drained() + + t.pass('drained resolved successfully with undefined drain') +}) diff --git a/node_modules/fastq/test/test.js b/node_modules/fastq/test/test.js new file mode 100644 index 0000000..79f0f6c --- /dev/null +++ b/node_modules/fastq/test/test.js @@ -0,0 +1,653 @@ +'use strict' + +/* eslint-disable no-var */ + +var test = require('tape') +var buildQueue = require('../') + +test('concurrency', function (t) { + t.plan(6) + t.throws(buildQueue.bind(null, worker, 0)) + t.throws(buildQueue.bind(null, worker, NaN)) + t.doesNotThrow(buildQueue.bind(null, worker, 1)) + + var queue = buildQueue(worker, 1) + t.throws(function () { + queue.concurrency = 0 + }) + t.throws(function () { + queue.concurrency = NaN + }) + t.doesNotThrow(function () { + queue.concurrency = 2 + }) + + function worker (arg, cb) { + cb(null, true) + } +}) + +test('worker execution', function (t) { + t.plan(3) + + var queue = buildQueue(worker, 1) + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + }) + + function worker (arg, cb) { + t.equal(arg, 42) + cb(null, true) + } +}) + +test('limit', function (t) { + t.plan(4) + + var expected = [10, 0] + var queue = buildQueue(worker, 1) + + queue.push(10, result) + queue.push(0, result) + + function result (err, arg) { + t.error(err, 'no error') + t.equal(arg, expected.shift(), 'the result matches') + } + + function worker (arg, cb) { + setTimeout(cb, arg, null, arg) + } +}) + +test('multiple executions', function (t) { + t.plan(15) + + var queue = buildQueue(worker, 1) + var toExec = [1, 2, 3, 4, 5] + var count = 0 + + toExec.forEach(function (task) { + queue.push(task, done) + }) + + function done (err, result) { + t.error(err, 'no error') + t.equal(result, toExec[count - 1], 'the result matches') + } + + function worker (arg, cb) { + t.equal(arg, toExec[count], 'arg matches') + count++ + setImmediate(cb, null, arg) + } +}) + +test('multiple executions, one after another', function (t) { + t.plan(15) + + var queue = buildQueue(worker, 1) + var toExec = [1, 2, 3, 4, 5] + var count = 0 + + queue.push(toExec[0], done) + + function done (err, result) { + t.error(err, 'no error') + t.equal(result, toExec[count - 1], 'the result matches') + if (count < toExec.length) { + queue.push(toExec[count], done) + } + } + + function worker (arg, cb) { + t.equal(arg, toExec[count], 'arg matches') + count++ + setImmediate(cb, null, arg) + } +}) + +test('set this', function (t) { + t.plan(3) + + var that = {} + var queue = buildQueue(that, worker, 1) + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(this, that, 'this matches') + }) + + function worker (arg, cb) { + t.equal(this, that, 'this matches') + cb(null, true) + } +}) + +test('drain', function (t) { + t.plan(4) + + var queue = buildQueue(worker, 1) + var worked = false + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + }) + + queue.drain = function () { + t.equal(true, worked, 'drained') + } + + function worker (arg, cb) { + t.equal(arg, 42) + worked = true + setImmediate(cb, null, true) + } +}) + +test('pause && resume', function (t) { + t.plan(13) + + var queue = buildQueue(worker, 1) + var worked = false + var expected = [42, 24] + + t.notOk(queue.paused, 'it should not be paused') + + queue.pause() + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + }) + + queue.push(24, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + }) + + t.notOk(worked, 'it should be paused') + t.ok(queue.paused, 'it should be paused') + + queue.resume() + queue.pause() + queue.resume() + queue.resume() // second resume is a no-op + + function worker (arg, cb) { + t.notOk(queue.paused, 'it should not be paused') + t.ok(queue.running() <= queue.concurrency, 'should respect the concurrency') + t.equal(arg, expected.shift()) + worked = true + process.nextTick(function () { cb(null, true) }) + } +}) + +test('pause in flight && resume', function (t) { + t.plan(16) + + var queue = buildQueue(worker, 1) + var expected = [42, 24, 12] + + t.notOk(queue.paused, 'it should not be paused') + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + t.ok(queue.paused, 'it should be paused') + process.nextTick(function () { + queue.resume() + queue.pause() + queue.resume() + }) + }) + + queue.push(24, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + t.notOk(queue.paused, 'it should not be paused') + }) + + queue.push(12, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + t.notOk(queue.paused, 'it should not be paused') + }) + + queue.pause() + + function worker (arg, cb) { + t.ok(queue.running() <= queue.concurrency, 'should respect the concurrency') + t.equal(arg, expected.shift()) + process.nextTick(function () { cb(null, true) }) + } +}) + +test('altering concurrency', function (t) { + t.plan(24) + + var queue = buildQueue(worker, 1) + + queue.push(24, workDone) + queue.push(24, workDone) + queue.push(24, workDone) + + queue.pause() + + queue.concurrency = 3 // concurrency changes are ignored while paused + queue.concurrency = 2 + + queue.resume() + + t.equal(queue.running(), 2, '2 jobs running') + + queue.concurrency = 3 + + t.equal(queue.running(), 3, '3 jobs running') + + queue.concurrency = 1 + + t.equal(queue.running(), 3, '3 jobs running') // running jobs can't be killed + + queue.push(24, workDone) + queue.push(24, workDone) + queue.push(24, workDone) + queue.push(24, workDone) + + function workDone (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + } + + function worker (arg, cb) { + t.ok(queue.running() <= queue.concurrency, 'should respect the concurrency') + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('idle()', function (t) { + t.plan(12) + + var queue = buildQueue(worker, 1) + + t.ok(queue.idle(), 'queue is idle') + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + t.notOk(queue.idle(), 'queue is not idle') + }) + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + // it will go idle after executing this function + setImmediate(function () { + t.ok(queue.idle(), 'queue is now idle') + }) + }) + + t.notOk(queue.idle(), 'queue is not idle') + + function worker (arg, cb) { + t.notOk(queue.idle(), 'queue is not idle') + t.equal(arg, 42) + setImmediate(cb, null, true) + } +}) + +test('saturated', function (t) { + t.plan(9) + + var queue = buildQueue(worker, 1) + var preworked = 0 + var worked = 0 + + queue.saturated = function () { + t.pass('saturated') + t.equal(preworked, 1, 'started 1 task') + t.equal(worked, 0, 'worked zero task') + } + + queue.push(42, done) + queue.push(42, done) + + function done (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + } + + function worker (arg, cb) { + t.equal(arg, 42) + preworked++ + setImmediate(function () { + worked++ + cb(null, true) + }) + } +}) + +test('length', function (t) { + t.plan(7) + + var queue = buildQueue(worker, 1) + + t.equal(queue.length(), 0, 'nothing waiting') + queue.push(42, done) + t.equal(queue.length(), 0, 'nothing waiting') + queue.push(42, done) + t.equal(queue.length(), 1, 'one task waiting') + queue.push(42, done) + t.equal(queue.length(), 2, 'two tasks waiting') + + function done (err, result) { + t.error(err, 'no error') + } + + function worker (arg, cb) { + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('getQueue', function (t) { + t.plan(10) + + var queue = buildQueue(worker, 1) + + t.equal(queue.getQueue().length, 0, 'nothing waiting') + queue.push(42, done) + t.equal(queue.getQueue().length, 0, 'nothing waiting') + queue.push(42, done) + t.equal(queue.getQueue().length, 1, 'one task waiting') + t.equal(queue.getQueue()[0], 42, 'should be equal') + queue.push(43, done) + t.equal(queue.getQueue().length, 2, 'two tasks waiting') + t.equal(queue.getQueue()[0], 42, 'should be equal') + t.equal(queue.getQueue()[1], 43, 'should be equal') + + function done (err, result) { + t.error(err, 'no error') + } + + function worker (arg, cb) { + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('unshift', function (t) { + t.plan(8) + + var queue = buildQueue(worker, 1) + var expected = [1, 2, 3, 4] + + queue.push(1, done) + queue.push(4, done) + queue.unshift(3, done) + queue.unshift(2, done) + + function done (err, result) { + t.error(err, 'no error') + } + + function worker (arg, cb) { + t.equal(expected.shift(), arg, 'tasks come in order') + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('unshift && empty', function (t) { + t.plan(2) + + var queue = buildQueue(worker, 1) + var completed = false + + queue.pause() + + queue.empty = function () { + t.notOk(completed, 'the task has not completed yet') + } + + queue.unshift(1, done) + + queue.resume() + + function done (err, result) { + completed = true + t.error(err, 'no error') + } + + function worker (arg, cb) { + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('push && empty', function (t) { + t.plan(2) + + var queue = buildQueue(worker, 1) + var completed = false + + queue.pause() + + queue.empty = function () { + t.notOk(completed, 'the task has not completed yet') + } + + queue.push(1, done) + + queue.resume() + + function done (err, result) { + completed = true + t.error(err, 'no error') + } + + function worker (arg, cb) { + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('kill', function (t) { + t.plan(5) + + var queue = buildQueue(worker, 1) + var expected = [1] + + var predrain = queue.drain + + queue.drain = function drain () { + t.fail('drain should never be called') + } + + queue.push(1, done) + queue.push(4, done) + queue.unshift(3, done) + queue.unshift(2, done) + queue.kill() + + function done (err, result) { + t.error(err, 'no error') + setImmediate(function () { + t.equal(queue.length(), 0, 'no queued tasks') + t.equal(queue.running(), 0, 'no running tasks') + t.equal(queue.drain, predrain, 'drain is back to default') + }) + } + + function worker (arg, cb) { + t.equal(expected.shift(), arg, 'tasks come in order') + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('killAndDrain', function (t) { + t.plan(6) + + var queue = buildQueue(worker, 1) + var expected = [1] + + var predrain = queue.drain + + queue.drain = function drain () { + t.pass('drain has been called') + } + + queue.push(1, done) + queue.push(4, done) + queue.unshift(3, done) + queue.unshift(2, done) + queue.killAndDrain() + + function done (err, result) { + t.error(err, 'no error') + setImmediate(function () { + t.equal(queue.length(), 0, 'no queued tasks') + t.equal(queue.running(), 0, 'no running tasks') + t.equal(queue.drain, predrain, 'drain is back to default') + }) + } + + function worker (arg, cb) { + t.equal(expected.shift(), arg, 'tasks come in order') + setImmediate(function () { + cb(null, true) + }) + } +}) + +test('pause && idle', function (t) { + t.plan(11) + + var queue = buildQueue(worker, 1) + var worked = false + + t.notOk(queue.paused, 'it should not be paused') + t.ok(queue.idle(), 'should be idle') + + queue.pause() + + queue.push(42, function (err, result) { + t.error(err, 'no error') + t.equal(result, true, 'result matches') + }) + + t.notOk(worked, 'it should be paused') + t.ok(queue.paused, 'it should be paused') + t.notOk(queue.idle(), 'should not be idle') + + queue.resume() + + t.notOk(queue.paused, 'it should not be paused') + t.notOk(queue.idle(), 'it should not be idle') + + function worker (arg, cb) { + t.equal(arg, 42) + worked = true + process.nextTick(cb.bind(null, null, true)) + process.nextTick(function () { + t.ok(queue.idle(), 'is should be idle') + }) + } +}) + +test('push without cb', function (t) { + t.plan(1) + + var queue = buildQueue(worker, 1) + + queue.push(42) + + function worker (arg, cb) { + t.equal(arg, 42) + cb() + } +}) + +test('unshift without cb', function (t) { + t.plan(1) + + var queue = buildQueue(worker, 1) + + queue.unshift(42) + + function worker (arg, cb) { + t.equal(arg, 42) + cb() + } +}) + +test('push with worker throwing error', function (t) { + t.plan(5) + var q = buildQueue(function (task, cb) { + cb(new Error('test error'), null) + }, 1) + q.error(function (err, task) { + t.ok(err instanceof Error, 'global error handler should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + t.equal(task, 42, 'The task executed should be passed') + }) + q.push(42, function (err) { + t.ok(err instanceof Error, 'push callback should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + }) +}) + +test('unshift with worker throwing error', function (t) { + t.plan(5) + var q = buildQueue(function (task, cb) { + cb(new Error('test error'), null) + }, 1) + q.error(function (err, task) { + t.ok(err instanceof Error, 'global error handler should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + t.equal(task, 42, 'The task executed should be passed') + }) + q.unshift(42, function (err) { + t.ok(err instanceof Error, 'unshift callback should catch the error') + t.match(err.message, /test error/, 'error message should be "test error"') + }) +}) + +test('pause/resume should trigger drain event', function (t) { + t.plan(1) + + var queue = buildQueue(worker, 1) + queue.pause() + queue.drain = function () { + t.pass('drain should be called') + } + + function worker (arg, cb) { + cb(null, true) + } + + queue.resume() +}) + +test('paused flag', function (t) { + t.plan(2) + + var queue = buildQueue(function (arg, cb) { + cb(null) + }, 1) + t.equal(queue.paused, false) + queue.pause() + t.equal(queue.paused, true) +}) diff --git a/node_modules/fastq/test/tsconfig.json b/node_modules/fastq/test/tsconfig.json new file mode 100644 index 0000000..66e16e9 --- /dev/null +++ b/node_modules/fastq/test/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "es6", + "module": "commonjs", + "noEmit": true, + "strict": true + }, + "files": [ + "./example.ts" + ] +} diff --git a/node_modules/fill-range/LICENSE b/node_modules/fill-range/LICENSE new file mode 100644 index 0000000..9af4a67 --- /dev/null +++ b/node_modules/fill-range/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/fill-range/README.md b/node_modules/fill-range/README.md new file mode 100644 index 0000000..8d756fe --- /dev/null +++ b/node_modules/fill-range/README.md @@ -0,0 +1,237 @@ +# fill-range [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/fill-range.svg?style=flat)](https://www.npmjs.com/package/fill-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![NPM total downloads](https://img.shields.io/npm/dt/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/fill-range.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/fill-range) + +> Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex` + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save fill-range +``` + +## Usage + +Expands numbers and letters, optionally using a `step` as the last argument. _(Numbers may be defined as JavaScript numbers or strings)_. + +```js +const fill = require('fill-range'); +// fill(from, to[, step, options]); + +console.log(fill('1', '10')); //=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] +console.log(fill('1', '10', { toRegex: true })); //=> [1-9]|10 +``` + +**Params** + +* `from`: **{String|Number}** the number or letter to start with +* `to`: **{String|Number}** the number or letter to end with +* `step`: **{String|Number|Object|Function}** Optionally pass a [step](#optionsstep) to use. +* `options`: **{Object|Function}**: See all available [options](#options) + +## Examples + +By default, an array of values is returned. + +**Alphabetical ranges** + +```js +console.log(fill('a', 'e')); //=> ['a', 'b', 'c', 'd', 'e'] +console.log(fill('A', 'E')); //=> [ 'A', 'B', 'C', 'D', 'E' ] +``` + +**Numerical ranges** + +Numbers can be defined as actual numbers or strings. + +```js +console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ] +console.log(fill('1', '5')); //=> [ 1, 2, 3, 4, 5 ] +``` + +**Negative ranges** + +Numbers can be defined as actual numbers or strings. + +```js +console.log(fill('-5', '-1')); //=> [ '-5', '-4', '-3', '-2', '-1' ] +console.log(fill('-5', '5')); //=> [ '-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5' ] +``` + +**Steps (increments)** + +```js +// numerical ranges with increments +console.log(fill('0', '25', 4)); //=> [ '0', '4', '8', '12', '16', '20', '24' ] +console.log(fill('0', '25', 5)); //=> [ '0', '5', '10', '15', '20', '25' ] +console.log(fill('0', '25', 6)); //=> [ '0', '6', '12', '18', '24' ] + +// alphabetical ranges with increments +console.log(fill('a', 'z', 4)); //=> [ 'a', 'e', 'i', 'm', 'q', 'u', 'y' ] +console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] +console.log(fill('a', 'z', 6)); //=> [ 'a', 'g', 'm', 's', 'y' ] +``` + +## Options + +### options.step + +**Type**: `number` (formatted as a string or number) + +**Default**: `undefined` + +**Description**: The increment to use for the range. Can be used with letters or numbers. + +**Example(s)** + +```js +// numbers +console.log(fill('1', '10', 2)); //=> [ '1', '3', '5', '7', '9' ] +console.log(fill('1', '10', 3)); //=> [ '1', '4', '7', '10' ] +console.log(fill('1', '10', 4)); //=> [ '1', '5', '9' ] + +// letters +console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] +console.log(fill('a', 'z', 7)); //=> [ 'a', 'h', 'o', 'v' ] +console.log(fill('a', 'z', 9)); //=> [ 'a', 'j', 's' ] +``` + +### options.strictRanges + +**Type**: `boolean` + +**Default**: `false` + +**Description**: By default, `null` is returned when an invalid range is passed. Enable this option to throw a `RangeError` on invalid ranges. + +**Example(s)** + +The following are all invalid: + +```js +fill('1.1', '2'); // decimals not supported in ranges +fill('a', '2'); // incompatible range values +fill(1, 10, 'foo'); // invalid "step" argument +``` + +### options.stringify + +**Type**: `boolean` + +**Default**: `undefined` + +**Description**: Cast all returned values to strings. By default, integers are returned as numbers. + +**Example(s)** + +```js +console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ] +console.log(fill(1, 5, { stringify: true })); //=> [ '1', '2', '3', '4', '5' ] +``` + +### options.toRegex + +**Type**: `boolean` + +**Default**: `undefined` + +**Description**: Create a regex-compatible source string, instead of expanding values to an array. + +**Example(s)** + +```js +// alphabetical range +console.log(fill('a', 'e', { toRegex: true })); //=> '[a-e]' +// alphabetical with step +console.log(fill('a', 'z', 3, { toRegex: true })); //=> 'a|d|g|j|m|p|s|v|y' +// numerical range +console.log(fill('1', '100', { toRegex: true })); //=> '[1-9]|[1-9][0-9]|100' +// numerical range with zero padding +console.log(fill('000001', '100000', { toRegex: true })); +//=> '0{5}[1-9]|0{4}[1-9][0-9]|0{3}[1-9][0-9]{2}|0{2}[1-9][0-9]{3}|0[1-9][0-9]{4}|100000' +``` + +### options.transform + +**Type**: `function` + +**Default**: `undefined` + +**Description**: Customize each value in the returned array (or [string](#optionstoRegex)). _(you can also pass this function as the last argument to `fill()`)_. + +**Example(s)** + +```js +// add zero padding +console.log(fill(1, 5, value => String(value).padStart(4, '0'))); +//=> ['0001', '0002', '0003', '0004', '0005'] +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 116 | [jonschlinkert](https://github.com/jonschlinkert) | +| 4 | [paulmillr](https://github.com/paulmillr) | +| 2 | [realityking](https://github.com/realityking) | +| 2 | [bluelovers](https://github.com/bluelovers) | +| 1 | [edorivai](https://github.com/edorivai) | +| 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! + + + + + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._ \ No newline at end of file diff --git a/node_modules/fill-range/index.js b/node_modules/fill-range/index.js new file mode 100644 index 0000000..ddb212e --- /dev/null +++ b/node_modules/fill-range/index.js @@ -0,0 +1,248 @@ +/*! + * fill-range + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Licensed under the MIT License. + */ + +'use strict'; + +const util = require('util'); +const toRegexRange = require('to-regex-range'); + +const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); + +const transform = toNumber => { + return value => toNumber === true ? Number(value) : String(value); +}; + +const isValidValue = value => { + return typeof value === 'number' || (typeof value === 'string' && value !== ''); +}; + +const isNumber = num => Number.isInteger(+num); + +const zeros = input => { + let value = `${input}`; + let index = -1; + if (value[0] === '-') value = value.slice(1); + if (value === '0') return false; + while (value[++index] === '0'); + return index > 0; +}; + +const stringify = (start, end, options) => { + if (typeof start === 'string' || typeof end === 'string') { + return true; + } + return options.stringify === true; +}; + +const pad = (input, maxLength, toNumber) => { + if (maxLength > 0) { + let dash = input[0] === '-' ? '-' : ''; + if (dash) input = input.slice(1); + input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); + } + if (toNumber === false) { + return String(input); + } + return input; +}; + +const toMaxLen = (input, maxLength) => { + let negative = input[0] === '-' ? '-' : ''; + if (negative) { + input = input.slice(1); + maxLength--; + } + while (input.length < maxLength) input = '0' + input; + return negative ? ('-' + input) : input; +}; + +const toSequence = (parts, options, maxLen) => { + parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + + let prefix = options.capture ? '' : '?:'; + let positives = ''; + let negatives = ''; + let result; + + if (parts.positives.length) { + positives = parts.positives.map(v => toMaxLen(String(v), maxLen)).join('|'); + } + + if (parts.negatives.length) { + negatives = `-(${prefix}${parts.negatives.map(v => toMaxLen(String(v), maxLen)).join('|')})`; + } + + if (positives && negatives) { + result = `${positives}|${negatives}`; + } else { + result = positives || negatives; + } + + if (options.wrap) { + return `(${prefix}${result})`; + } + + return result; +}; + +const toRange = (a, b, isNumbers, options) => { + if (isNumbers) { + return toRegexRange(a, b, { wrap: false, ...options }); + } + + let start = String.fromCharCode(a); + if (a === b) return start; + + let stop = String.fromCharCode(b); + return `[${start}-${stop}]`; +}; + +const toRegex = (start, end, options) => { + if (Array.isArray(start)) { + let wrap = options.wrap === true; + let prefix = options.capture ? '' : '?:'; + return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); + } + return toRegexRange(start, end, options); +}; + +const rangeError = (...args) => { + return new RangeError('Invalid range arguments: ' + util.inspect(...args)); +}; + +const invalidRange = (start, end, options) => { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; +}; + +const invalidStep = (step, options) => { + if (options.strictRanges === true) { + throw new TypeError(`Expected step "${step}" to be a number`); + } + return []; +}; + +const fillNumbers = (start, end, step = 1, options = {}) => { + let a = Number(start); + let b = Number(end); + + if (!Number.isInteger(a) || !Number.isInteger(b)) { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; + } + + // fix negative zero + if (a === 0) a = 0; + if (b === 0) b = 0; + + let descending = a > b; + let startString = String(start); + let endString = String(end); + let stepString = String(step); + step = Math.max(Math.abs(step), 1); + + let padded = zeros(startString) || zeros(endString) || zeros(stepString); + let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; + let toNumber = padded === false && stringify(start, end, options) === false; + let format = options.transform || transform(toNumber); + + if (options.toRegex && step === 1) { + return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); + } + + let parts = { negatives: [], positives: [] }; + let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + if (options.toRegex === true && step > 1) { + push(a); + } else { + range.push(pad(format(a, index), maxLen, toNumber)); + } + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return step > 1 + ? toSequence(parts, options, maxLen) + : toRegex(range, null, { wrap: false, ...options }); + } + + return range; +}; + +const fillLetters = (start, end, step = 1, options = {}) => { + if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { + return invalidRange(start, end, options); + } + + let format = options.transform || (val => String.fromCharCode(val)); + let a = `${start}`.charCodeAt(0); + let b = `${end}`.charCodeAt(0); + + let descending = a > b; + let min = Math.min(a, b); + let max = Math.max(a, b); + + if (options.toRegex && step === 1) { + return toRange(min, max, false, options); + } + + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + range.push(format(a, index)); + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return toRegex(range, null, { wrap: false, options }); + } + + return range; +}; + +const fill = (start, end, step, options = {}) => { + if (end == null && isValidValue(start)) { + return [start]; + } + + if (!isValidValue(start) || !isValidValue(end)) { + return invalidRange(start, end, options); + } + + if (typeof step === 'function') { + return fill(start, end, 1, { transform: step }); + } + + if (isObject(step)) { + return fill(start, end, 0, step); + } + + let opts = { ...options }; + if (opts.capture === true) opts.wrap = true; + step = step || opts.step || 1; + + if (!isNumber(step)) { + if (step != null && !isObject(step)) return invalidStep(step, opts); + return fill(start, end, 1, step); + } + + if (isNumber(start) && isNumber(end)) { + return fillNumbers(start, end, step, opts); + } + + return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); +}; + +module.exports = fill; diff --git a/node_modules/fill-range/package.json b/node_modules/fill-range/package.json new file mode 100644 index 0000000..582357f --- /dev/null +++ b/node_modules/fill-range/package.json @@ -0,0 +1,74 @@ +{ + "name": "fill-range", + "description": "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`", + "version": "7.1.1", + "homepage": "https://github.com/jonschlinkert/fill-range", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Edo Rivai (edo.rivai.nl)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)", + "Paul Miller (paulmillr.com)", + "Rouven Weßling (www.rouvenwessling.de)", + "(https://github.com/wtgtybhertgeghgtwtg)" + ], + "repository": "jonschlinkert/fill-range", + "bugs": { + "url": "https://github.com/jonschlinkert/fill-range/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=8" + }, + "scripts": { + "lint": "eslint --cache --cache-location node_modules/.cache/.eslintcache --report-unused-disable-directives --ignore-path .gitignore .", + "mocha": "mocha --reporter dot", + "test": "npm run lint && npm run mocha", + "test:ci": "npm run test:cover", + "test:cover": "nyc npm run mocha" + }, + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "devDependencies": { + "gulp-format-md": "^2.0.0", + "mocha": "^6.1.1", + "nyc": "^15.1.0" + }, + "keywords": [ + "alpha", + "alphabetical", + "array", + "bash", + "brace", + "expand", + "expansion", + "fill", + "glob", + "match", + "matches", + "matching", + "number", + "numerical", + "range", + "ranges", + "regex", + "sh" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + } + } +} diff --git a/node_modules/foreground-child/LICENSE b/node_modules/foreground-child/LICENSE new file mode 100644 index 0000000..2d80720 --- /dev/null +++ b/node_modules/foreground-child/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2015-2023 Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/foreground-child/README.md b/node_modules/foreground-child/README.md new file mode 100644 index 0000000..477ca57 --- /dev/null +++ b/node_modules/foreground-child/README.md @@ -0,0 +1,128 @@ +# foreground-child + +Run a child as if it's the foreground process. Give it stdio. Exit +when it exits. + +Mostly this module is here to support some use cases around +wrapping child processes for test coverage and such. But it's +also generally useful any time you want one program to execute +another as if it's the "main" process, for example, if a program +takes a `--cmd` argument to execute in some way. + +## USAGE + +```js +import { foregroundChild } from 'foreground-child' +// hybrid module, this also works: +// const { foregroundChild } = require('foreground-child') + +// cats out this file +const child = foregroundChild('cat', [__filename]) + +// At this point, it's best to just do nothing else. +// return or whatever. +// If the child gets a signal, or just exits, then this +// parent process will exit in the same way. +``` + +You can provide custom spawn options by passing an object after +the program and arguments: + +```js +const child = foregroundChild(`cat ${__filename}`, { shell: true }) +``` + +A callback can optionally be provided, if you want to perform an +action before your foreground-child exits: + +```js +const child = foregroundChild('cat', [__filename], spawnOptions, () => { + doSomeActions() +}) +``` + +The callback can return a Promise in order to perform +asynchronous actions. If the callback does not return a promise, +then it must complete its actions within a single JavaScript +tick. + +```js +const child = foregroundChild('cat', [__filename], async () => { + await doSomeAsyncActions() +}) +``` + +If the callback throws or rejects, then it will be unhandled, and +node will exit in error. + +If the callback returns a string value, then that will be used as +the signal to exit the parent process. If it returns a number, +then that number will be used as the parent exit status code. If +it returns boolean `false`, then the parent process will not be +terminated. If it returns `undefined`, then it will exit with the +same signal/code as the child process. + +## Caveats + +The "normal" standard IO file descriptors (0, 1, and 2 for stdin, +stdout, and stderr respectively) are shared with the child process. +Additionally, if there is an IPC channel set up in the parent, then +messages are proxied to the child on file descriptor 3. + +In Node, it's possible to also map arbitrary file descriptors +into a child process. In these cases, foreground-child will not +map the file descriptors into the child. If file descriptors 0, +1, or 2 are used for the IPC channel, then strange behavior may +happen (like printing IPC messages to stderr, for example). + +Note that a SIGKILL will always kill the parent process, but +will not proxy the signal to the child process, because SIGKILL +cannot be caught. In order to address this, a special "watchdog" +child process is spawned which will send a SIGKILL to the child +process if it does not terminate within half a second after the +watchdog receives a SIGHUP due to its parent terminating. + +On Windows, issuing a `process.kill(process.pid, signal)` with a +fatal termination signal may cause the process to exit with a `1` +status code rather than reporting the signal properly. This +module tries to do the right thing, but on Windows systems, you +may see that incorrect result. There is as far as I'm aware no +workaround for this. + +## util: `foreground-child/proxy-signals` + +If you just want to proxy the signals to a child process that the +main process receives, you can use the `proxy-signals` export +from this package. + +```js +import { proxySignals } from 'foreground-child/proxy-signals' + +const childProcess = spawn('command', ['some', 'args']) +proxySignals(childProcess) +``` + +Now, any fatal signal received by the current process will be +proxied to the child process. + +It doesn't go in the other direction; ie, signals sent to the +child process will not affect the parent. For that, listen to the +child `exit` or `close` events, and handle them appropriately. + +## util: `foreground-child/watchdog` + +If you are spawning a child process, and want to ensure that it +isn't left dangling if the parent process exits, you can use the +watchdog utility exported by this module. + +```js +import { watchdog } from 'foreground-child/watchdog' + +const childProcess = spawn('command', ['some', 'args']) +const watchdogProcess = watchdog(childProcess) + +// watchdogProcess is a reference to the process monitoring the +// parent and child. There's usually no reason to do anything +// with it, as it's silent and will terminate +// automatically when it's no longer needed. +``` diff --git a/node_modules/foreground-child/dist/commonjs/all-signals.d.ts b/node_modules/foreground-child/dist/commonjs/all-signals.d.ts new file mode 100644 index 0000000..ecc0a62 --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/all-signals.d.ts @@ -0,0 +1,2 @@ +export declare const allSignals: NodeJS.Signals[]; +//# sourceMappingURL=all-signals.d.ts.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/all-signals.d.ts.map b/node_modules/foreground-child/dist/commonjs/all-signals.d.ts.map new file mode 100644 index 0000000..cd1c161 --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/all-signals.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"all-signals.d.ts","sourceRoot":"","sources":["../../src/all-signals.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,UAAU,EAShB,MAAM,CAAC,OAAO,EAAE,CAAA"} \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/all-signals.js b/node_modules/foreground-child/dist/commonjs/all-signals.js new file mode 100644 index 0000000..1692af0 --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/all-signals.js @@ -0,0 +1,58 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.allSignals = void 0; +const node_constants_1 = __importDefault(require("node:constants")); +exports.allSignals = +// this is the full list of signals that Node will let us do anything with +Object.keys(node_constants_1.default).filter(k => k.startsWith('SIG') && + // https://github.com/tapjs/signal-exit/issues/21 + k !== 'SIGPROF' && + // no sense trying to listen for SIGKILL, it's impossible + k !== 'SIGKILL'); +// These are some obscure signals that are reported by kill -l +// on macOS, Linux, or Windows, but which don't have any mapping +// in Node.js. No sense trying if they're just going to throw +// every time on every platform. +// +// 'SIGEMT', +// 'SIGLOST', +// 'SIGPOLL', +// 'SIGRTMAX', +// 'SIGRTMAX-1', +// 'SIGRTMAX-10', +// 'SIGRTMAX-11', +// 'SIGRTMAX-12', +// 'SIGRTMAX-13', +// 'SIGRTMAX-14', +// 'SIGRTMAX-15', +// 'SIGRTMAX-2', +// 'SIGRTMAX-3', +// 'SIGRTMAX-4', +// 'SIGRTMAX-5', +// 'SIGRTMAX-6', +// 'SIGRTMAX-7', +// 'SIGRTMAX-8', +// 'SIGRTMAX-9', +// 'SIGRTMIN', +// 'SIGRTMIN+1', +// 'SIGRTMIN+10', +// 'SIGRTMIN+11', +// 'SIGRTMIN+12', +// 'SIGRTMIN+13', +// 'SIGRTMIN+14', +// 'SIGRTMIN+15', +// 'SIGRTMIN+16', +// 'SIGRTMIN+2', +// 'SIGRTMIN+3', +// 'SIGRTMIN+4', +// 'SIGRTMIN+5', +// 'SIGRTMIN+6', +// 'SIGRTMIN+7', +// 'SIGRTMIN+8', +// 'SIGRTMIN+9', +// 'SIGSTKFLT', +// 'SIGUNUSED', +//# sourceMappingURL=all-signals.js.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/all-signals.js.map b/node_modules/foreground-child/dist/commonjs/all-signals.js.map new file mode 100644 index 0000000..51c056d --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/all-signals.js.map @@ -0,0 +1 @@ +{"version":3,"file":"all-signals.js","sourceRoot":"","sources":["../../src/all-signals.ts"],"names":[],"mappings":";;;;;;AAAA,oEAAsC;AACzB,QAAA,UAAU;AACrB,0EAA0E;AAC1E,MAAM,CAAC,IAAI,CAAC,wBAAS,CAAC,CAAC,MAAM,CAC3B,CAAC,CAAC,EAAE,CACF,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC;IACnB,iDAAiD;IACjD,CAAC,KAAK,SAAS;IACf,yDAAyD;IACzD,CAAC,KAAK,SAAS,CACE,CAAA;AAEvB,8DAA8D;AAC9D,gEAAgE;AAChE,6DAA6D;AAC7D,gCAAgC;AAChC,EAAE;AACF,YAAY;AACZ,aAAa;AACb,aAAa;AACb,cAAc;AACd,gBAAgB;AAChB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,cAAc;AACd,gBAAgB;AAChB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,eAAe;AACf,eAAe","sourcesContent":["import constants from 'node:constants'\nexport const allSignals =\n // this is the full list of signals that Node will let us do anything with\n Object.keys(constants).filter(\n k =>\n k.startsWith('SIG') &&\n // https://github.com/tapjs/signal-exit/issues/21\n k !== 'SIGPROF' &&\n // no sense trying to listen for SIGKILL, it's impossible\n k !== 'SIGKILL',\n ) as NodeJS.Signals[]\n\n// These are some obscure signals that are reported by kill -l\n// on macOS, Linux, or Windows, but which don't have any mapping\n// in Node.js. No sense trying if they're just going to throw\n// every time on every platform.\n//\n// 'SIGEMT',\n// 'SIGLOST',\n// 'SIGPOLL',\n// 'SIGRTMAX',\n// 'SIGRTMAX-1',\n// 'SIGRTMAX-10',\n// 'SIGRTMAX-11',\n// 'SIGRTMAX-12',\n// 'SIGRTMAX-13',\n// 'SIGRTMAX-14',\n// 'SIGRTMAX-15',\n// 'SIGRTMAX-2',\n// 'SIGRTMAX-3',\n// 'SIGRTMAX-4',\n// 'SIGRTMAX-5',\n// 'SIGRTMAX-6',\n// 'SIGRTMAX-7',\n// 'SIGRTMAX-8',\n// 'SIGRTMAX-9',\n// 'SIGRTMIN',\n// 'SIGRTMIN+1',\n// 'SIGRTMIN+10',\n// 'SIGRTMIN+11',\n// 'SIGRTMIN+12',\n// 'SIGRTMIN+13',\n// 'SIGRTMIN+14',\n// 'SIGRTMIN+15',\n// 'SIGRTMIN+16',\n// 'SIGRTMIN+2',\n// 'SIGRTMIN+3',\n// 'SIGRTMIN+4',\n// 'SIGRTMIN+5',\n// 'SIGRTMIN+6',\n// 'SIGRTMIN+7',\n// 'SIGRTMIN+8',\n// 'SIGRTMIN+9',\n// 'SIGSTKFLT',\n// 'SIGUNUSED',\n"]} \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/index.d.ts b/node_modules/foreground-child/dist/commonjs/index.d.ts new file mode 100644 index 0000000..d15b38e --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/index.d.ts @@ -0,0 +1,58 @@ +import { ChildProcessByStdio, SpawnOptions, ChildProcess } from 'child_process'; +/** + * The signature for the cleanup method. + * + * Arguments indicate the exit status of the child process. + * + * If a Promise is returned, then the process is not terminated + * until it resolves, and the resolution value is treated as the + * exit status (if a number) or signal exit (if a signal string). + * + * If `undefined` is returned, then no change is made, and the parent + * exits in the same way that the child exited. + * + * If boolean `false` is returned, then the parent's exit is canceled. + * + * If a number is returned, then the parent process exits with the number + * as its exitCode. + * + * If a signal string is returned, then the parent process is killed with + * the same signal that caused the child to exit. + */ +export type Cleanup = (code: number | null, signal: null | NodeJS.Signals, processInfo: { + watchdogPid?: ChildProcess['pid']; +}) => void | undefined | number | NodeJS.Signals | false | Promise; +export type FgArgs = [program: string | [cmd: string, ...args: string[]], cleanup?: Cleanup] | [ + program: [cmd: string, ...args: string[]], + opts?: SpawnOptions, + cleanup?: Cleanup +] | [program: string, cleanup?: Cleanup] | [program: string, opts?: SpawnOptions, cleanup?: Cleanup] | [program: string, args?: string[], cleanup?: Cleanup] | [ + program: string, + args?: string[], + opts?: SpawnOptions, + cleanup?: Cleanup +]; +/** + * Normalizes the arguments passed to `foregroundChild`. + * + * Exposed for testing. + * + * @internal + */ +export declare const normalizeFgArgs: (fgArgs: FgArgs) => [program: string, args: string[], spawnOpts: SpawnOptions, cleanup: Cleanup]; +/** + * Spawn the specified program as a "foreground" process, or at least as + * close as is possible given node's lack of exec-without-fork. + * + * Cleanup method may be used to modify or ignore the result of the child's + * exit code or signal. If cleanup returns undefined (or a Promise that + * resolves to undefined), then the parent will exit in the same way that + * the child did. + * + * Return boolean `false` to prevent the parent's exit entirely. + */ +export declare function foregroundChild(cmd: string | [cmd: string, ...args: string[]], cleanup?: Cleanup): ChildProcessByStdio; +export declare function foregroundChild(program: string, args?: string[], cleanup?: Cleanup): ChildProcessByStdio; +export declare function foregroundChild(program: string, spawnOpts?: SpawnOptions, cleanup?: Cleanup): ChildProcessByStdio; +export declare function foregroundChild(program: string, args?: string[], spawnOpts?: SpawnOptions, cleanup?: Cleanup): ChildProcessByStdio; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/index.d.ts.map b/node_modules/foreground-child/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000..b26fecd --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EAInB,YAAY,EACZ,YAAY,EACb,MAAM,eAAe,CAAA;AAUtB;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,MAAM,OAAO,GAAG,CACpB,IAAI,EAAE,MAAM,GAAG,IAAI,EACnB,MAAM,EAAE,IAAI,GAAG,MAAM,CAAC,OAAO,EAC7B,WAAW,EAAE;IACX,WAAW,CAAC,EAAE,YAAY,CAAC,KAAK,CAAC,CAAA;CAClC,KAEC,IAAI,GACJ,SAAS,GACT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AAE,IAAI,CAAC,CAAA;AACxC,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,EACf,IAAI,CAAC,EAAE,MAAM,EAAE,EACf,OAAO,CAAC,EAAE,OAAO,GAChB,mBAAmB,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACxC,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,EACf,SAAS,CAAC,EAAE,YAAY,EACxB,OAAO,CAAC,EAAE,OAAO,GAChB,mBAAmB,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACxC,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,EACf,IAAI,CAAC,EAAE,MAAM,EAAE,EACf,SAAS,CAAC,EAAE,YAAY,EACxB,OAAO,CAAC,EAAE,OAAO,GAChB,mBAAmB,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/index.js b/node_modules/foreground-child/dist/commonjs/index.js new file mode 100644 index 0000000..6db65c6 --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/index.js @@ -0,0 +1,123 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.normalizeFgArgs = void 0; +exports.foregroundChild = foregroundChild; +const child_process_1 = require("child_process"); +const cross_spawn_1 = __importDefault(require("cross-spawn")); +const signal_exit_1 = require("signal-exit"); +const proxy_signals_js_1 = require("./proxy-signals.js"); +const watchdog_js_1 = require("./watchdog.js"); +/* c8 ignore start */ +const spawn = process?.platform === 'win32' ? cross_spawn_1.default : child_process_1.spawn; +/** + * Normalizes the arguments passed to `foregroundChild`. + * + * Exposed for testing. + * + * @internal + */ +const normalizeFgArgs = (fgArgs) => { + let [program, args = [], spawnOpts = {}, cleanup = () => { }] = fgArgs; + if (typeof args === 'function') { + cleanup = args; + spawnOpts = {}; + args = []; + } + else if (!!args && typeof args === 'object' && !Array.isArray(args)) { + if (typeof spawnOpts === 'function') + cleanup = spawnOpts; + spawnOpts = args; + args = []; + } + else if (typeof spawnOpts === 'function') { + cleanup = spawnOpts; + spawnOpts = {}; + } + if (Array.isArray(program)) { + const [pp, ...pa] = program; + program = pp; + args = pa; + } + return [program, args, { ...spawnOpts }, cleanup]; +}; +exports.normalizeFgArgs = normalizeFgArgs; +function foregroundChild(...fgArgs) { + const [program, args, spawnOpts, cleanup] = (0, exports.normalizeFgArgs)(fgArgs); + spawnOpts.stdio = [0, 1, 2]; + if (process.send) { + spawnOpts.stdio.push('ipc'); + } + const child = spawn(program, args, spawnOpts); + const childHangup = () => { + try { + child.kill('SIGHUP'); + /* c8 ignore start */ + } + catch (_) { + // SIGHUP is weird on windows + child.kill('SIGTERM'); + } + /* c8 ignore stop */ + }; + const removeOnExit = (0, signal_exit_1.onExit)(childHangup); + (0, proxy_signals_js_1.proxySignals)(child); + const dog = (0, watchdog_js_1.watchdog)(child); + let done = false; + child.on('close', async (code, signal) => { + /* c8 ignore start */ + if (done) + return; + /* c8 ignore stop */ + done = true; + const result = cleanup(code, signal, { + watchdogPid: dog.pid, + }); + const res = isPromise(result) ? await result : result; + removeOnExit(); + if (res === false) + return; + else if (typeof res === 'string') { + signal = res; + code = null; + } + else if (typeof res === 'number') { + code = res; + signal = null; + } + if (signal) { + // If there is nothing else keeping the event loop alive, + // then there's a race between a graceful exit and getting + // the signal to this process. Put this timeout here to + // make sure we're still alive to get the signal, and thus + // exit with the intended signal code. + /* istanbul ignore next */ + setTimeout(() => { }, 2000); + try { + process.kill(process.pid, signal); + /* c8 ignore start */ + } + catch (_) { + process.kill(process.pid, 'SIGTERM'); + } + /* c8 ignore stop */ + } + else { + process.exit(code || 0); + } + }); + if (process.send) { + process.removeAllListeners('message'); + child.on('message', (message, sendHandle) => { + process.send?.(message, sendHandle); + }); + process.on('message', (message, sendHandle) => { + child.send(message, sendHandle); + }); + } + return child; +} +const isPromise = (o) => !!o && typeof o === 'object' && typeof o.then === 'function'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/index.js.map b/node_modules/foreground-child/dist/commonjs/index.js.map new file mode 100644 index 0000000..56037c8 --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;AAuIA,0CAyFC;AAhOD,iDAOsB;AACtB,8DAAoC;AACpC,6CAAoC;AACpC,yDAAiD;AACjD,+CAAwC;AAExC,qBAAqB;AACrB,MAAM,KAAK,GAAG,OAAO,EAAE,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,qBAAU,CAAC,CAAC,CAAC,qBAAS,CAAA;AAsDpE;;;;;;GAMG;AACI,MAAM,eAAe,GAAG,CAC7B,MAAc,EAMd,EAAE;IACF,IAAI,CAAC,OAAO,EAAE,IAAI,GAAG,EAAE,EAAE,SAAS,GAAG,EAAE,EAAE,OAAO,GAAG,GAAG,EAAE,GAAE,CAAC,CAAC,GAAG,MAAM,CAAA;IACrE,IAAI,OAAO,IAAI,KAAK,UAAU,EAAE,CAAC;QAC/B,OAAO,GAAG,IAAI,CAAA;QACd,SAAS,GAAG,EAAE,CAAA;QACd,IAAI,GAAG,EAAE,CAAA;IACX,CAAC;SAAM,IAAI,CAAC,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;QACtE,IAAI,OAAO,SAAS,KAAK,UAAU;YAAE,OAAO,GAAG,SAAS,CAAA;QACxD,SAAS,GAAG,IAAI,CAAA;QAChB,IAAI,GAAG,EAAE,CAAA;IACX,CAAC;SAAM,IAAI,OAAO,SAAS,KAAK,UAAU,EAAE,CAAC;QAC3C,OAAO,GAAG,SAAS,CAAA;QACnB,SAAS,GAAG,EAAE,CAAA;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IACH,CAAC,CAAC,CAAA;IAEF,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,OAAO,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAA;QAErC,KAAK,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,EAAE;YAC1C,OAAO,CAAC,IAAI,EAAE,CAAC,OAAO,EAAE,UAAU,CAAC,CAAA;QACrC,CAAC,CAAC,CAAA;QAEF,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,EAAE;YAC5C,KAAK,CAAC,IAAI,CACR,OAAuB,EACvB,UAAoC,CACrC,CAAA;QACH,CAAC,CAAC,CAAA;IACJ,CAAC;IAED,OAAO,KAAK,CAAA;AACd,CAAC;AAED,MAAM,SAAS,GAAG,CAAC,CAAM,EAAqB,EAAE,CAC9C,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,CAAC,IAAI,KAAK,UAAU,CAAA","sourcesContent":["import {\n ChildProcessByStdio,\n SendHandle,\n Serializable,\n spawn as nodeSpawn,\n SpawnOptions,\n ChildProcess,\n} from 'child_process'\nimport crossSpawn from 'cross-spawn'\nimport { onExit } from 'signal-exit'\nimport { proxySignals } from './proxy-signals.js'\nimport { watchdog } from './watchdog.js'\n\n/* c8 ignore start */\nconst spawn = process?.platform === 'win32' ? crossSpawn : nodeSpawn\n/* c8 ignore stop */\n\n/**\n * The signature for the cleanup method.\n *\n * Arguments indicate the exit status of the child process.\n *\n * If a Promise is returned, then the process is not terminated\n * until it resolves, and the resolution value is treated as the\n * exit status (if a number) or signal exit (if a signal string).\n *\n * If `undefined` is returned, then no change is made, and the parent\n * exits in the same way that the child exited.\n *\n * If boolean `false` is returned, then the parent's exit is canceled.\n *\n * If a number is returned, then the parent process exits with the number\n * as its exitCode.\n *\n * If a signal string is returned, then the parent process is killed with\n * the same signal that caused the child to exit.\n */\nexport type Cleanup = (\n code: number | null,\n signal: null | NodeJS.Signals,\n processInfo: {\n watchdogPid?: ChildProcess['pid']\n },\n) =>\n | void\n | undefined\n | number\n | NodeJS.Signals\n | false\n | Promise\n\nexport type FgArgs =\n | [program: string | [cmd: string, ...args: string[]], cleanup?: Cleanup]\n | [\n program: [cmd: string, ...args: string[]],\n opts?: SpawnOptions,\n cleanup?: Cleanup,\n ]\n | [program: string, cleanup?: Cleanup]\n | [program: string, opts?: SpawnOptions, cleanup?: Cleanup]\n | [program: string, args?: string[], cleanup?: Cleanup]\n | [\n program: string,\n args?: string[],\n opts?: SpawnOptions,\n cleanup?: Cleanup,\n ]\n\n/**\n * Normalizes the arguments passed to `foregroundChild`.\n *\n * Exposed for testing.\n *\n * @internal\n */\nexport const normalizeFgArgs = (\n fgArgs: FgArgs,\n): [\n program: string,\n args: string[],\n spawnOpts: SpawnOptions,\n cleanup: Cleanup,\n] => {\n let [program, args = [], spawnOpts = {}, cleanup = () => {}] = fgArgs\n if (typeof args === 'function') {\n cleanup = args\n spawnOpts = {}\n args = []\n } else if (!!args && typeof args === 'object' && !Array.isArray(args)) {\n if (typeof spawnOpts === 'function') cleanup = spawnOpts\n spawnOpts = args\n args = []\n } else if (typeof spawnOpts === 'function') {\n cleanup = spawnOpts\n spawnOpts = {}\n }\n if (Array.isArray(program)) {\n const [pp, ...pa] = program\n program = pp\n args = pa\n }\n return [program, args, { ...spawnOpts }, cleanup]\n}\n\n/**\n * Spawn the specified program as a \"foreground\" process, or at least as\n * close as is possible given node's lack of exec-without-fork.\n *\n * Cleanup method may be used to modify or ignore the result of the child's\n * exit code or signal. If cleanup returns undefined (or a Promise that\n * resolves to undefined), then the parent will exit in the same way that\n * the child did.\n *\n * Return boolean `false` to prevent the parent's exit entirely.\n */\nexport function foregroundChild(\n cmd: string | [cmd: string, ...args: string[]],\n cleanup?: Cleanup,\n): ChildProcessByStdio\nexport function foregroundChild(\n program: string,\n args?: string[],\n cleanup?: Cleanup,\n): ChildProcessByStdio\nexport function foregroundChild(\n program: string,\n spawnOpts?: SpawnOptions,\n cleanup?: Cleanup,\n): ChildProcessByStdio\nexport function foregroundChild(\n program: string,\n args?: string[],\n spawnOpts?: SpawnOptions,\n cleanup?: Cleanup,\n): ChildProcessByStdio\nexport function foregroundChild(\n ...fgArgs: FgArgs\n): ChildProcessByStdio {\n const [program, args, spawnOpts, cleanup] = normalizeFgArgs(fgArgs)\n\n spawnOpts.stdio = [0, 1, 2]\n if (process.send) {\n spawnOpts.stdio.push('ipc')\n }\n\n const child = spawn(program, args, spawnOpts) as ChildProcessByStdio<\n null,\n null,\n null\n >\n\n const childHangup = () => {\n try {\n child.kill('SIGHUP')\n\n /* c8 ignore start */\n } catch (_) {\n // SIGHUP is weird on windows\n child.kill('SIGTERM')\n }\n /* c8 ignore stop */\n }\n const removeOnExit = onExit(childHangup)\n\n proxySignals(child)\n const dog = watchdog(child)\n\n let done = false\n child.on('close', async (code, signal) => {\n /* c8 ignore start */\n if (done) return\n /* c8 ignore stop */\n done = true\n const result = cleanup(code, signal, {\n watchdogPid: dog.pid,\n })\n const res = isPromise(result) ? await result : result\n removeOnExit()\n\n if (res === false) return\n else if (typeof res === 'string') {\n signal = res\n code = null\n } else if (typeof res === 'number') {\n code = res\n signal = null\n }\n\n if (signal) {\n // If there is nothing else keeping the event loop alive,\n // then there's a race between a graceful exit and getting\n // the signal to this process. Put this timeout here to\n // make sure we're still alive to get the signal, and thus\n // exit with the intended signal code.\n /* istanbul ignore next */\n setTimeout(() => {}, 2000)\n try {\n process.kill(process.pid, signal)\n /* c8 ignore start */\n } catch (_) {\n process.kill(process.pid, 'SIGTERM')\n }\n /* c8 ignore stop */\n } else {\n process.exit(code || 0)\n }\n })\n\n if (process.send) {\n process.removeAllListeners('message')\n\n child.on('message', (message, sendHandle) => {\n process.send?.(message, sendHandle)\n })\n\n process.on('message', (message, sendHandle) => {\n child.send(\n message as Serializable,\n sendHandle as SendHandle | undefined,\n )\n })\n }\n\n return child\n}\n\nconst isPromise = (o: any): o is Promise =>\n !!o && typeof o === 'object' && typeof o.then === 'function'\n"]} \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/package.json b/node_modules/foreground-child/dist/commonjs/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/foreground-child/dist/commonjs/proxy-signals.d.ts b/node_modules/foreground-child/dist/commonjs/proxy-signals.d.ts new file mode 100644 index 0000000..edf17bd --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/proxy-signals.d.ts @@ -0,0 +1,6 @@ +import { type ChildProcess } from 'child_process'; +/** + * Starts forwarding signals to `child` through `parent`. + */ +export declare const proxySignals: (child: ChildProcess) => () => void; +//# sourceMappingURL=proxy-signals.d.ts.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/proxy-signals.d.ts.map b/node_modules/foreground-child/dist/commonjs/proxy-signals.d.ts.map new file mode 100644 index 0000000..7c19279 --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/proxy-signals.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"proxy-signals.d.ts","sourceRoot":"","sources":["../../src/proxy-signals.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,eAAe,CAAA;AAGjD;;GAEG;AACH,eAAO,MAAM,YAAY,UAAW,YAAY,eA4B/C,CAAA"} \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/proxy-signals.js b/node_modules/foreground-child/dist/commonjs/proxy-signals.js new file mode 100644 index 0000000..3913e7b --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/proxy-signals.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.proxySignals = void 0; +const all_signals_js_1 = require("./all-signals.js"); +/** + * Starts forwarding signals to `child` through `parent`. + */ +const proxySignals = (child) => { + const listeners = new Map(); + for (const sig of all_signals_js_1.allSignals) { + const listener = () => { + // some signals can only be received, not sent + try { + child.kill(sig); + /* c8 ignore start */ + } + catch (_) { } + /* c8 ignore stop */ + }; + try { + // if it's a signal this system doesn't recognize, skip it + process.on(sig, listener); + listeners.set(sig, listener); + /* c8 ignore start */ + } + catch (_) { } + /* c8 ignore stop */ + } + const unproxy = () => { + for (const [sig, listener] of listeners) { + process.removeListener(sig, listener); + } + }; + child.on('exit', unproxy); + return unproxy; +}; +exports.proxySignals = proxySignals; +//# sourceMappingURL=proxy-signals.js.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/proxy-signals.js.map b/node_modules/foreground-child/dist/commonjs/proxy-signals.js.map new file mode 100644 index 0000000..1995822 --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/proxy-signals.js.map @@ -0,0 +1 @@ +{"version":3,"file":"proxy-signals.js","sourceRoot":"","sources":["../../src/proxy-signals.ts"],"names":[],"mappings":";;;AACA,qDAA6C;AAE7C;;GAEG;AACI,MAAM,YAAY,GAAG,CAAC,KAAmB,EAAE,EAAE;IAClD,MAAM,SAAS,GAAG,IAAI,GAAG,EAAE,CAAA;IAE3B,KAAK,MAAM,GAAG,IAAI,2BAAU,EAAE,CAAC;QAC7B,MAAM,QAAQ,GAAG,GAAG,EAAE;YACpB,8CAA8C;YAC9C,IAAI,CAAC;gBACH,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;gBACf,qBAAqB;YACvB,CAAC;YAAC,OAAO,CAAC,EAAE,CAAC,CAAA,CAAC;YACd,oBAAoB;QACtB,CAAC,CAAA;QACD,IAAI,CAAC;YACH,0DAA0D;YAC1D,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;YACzB,SAAS,CAAC,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;YAC5B,qBAAqB;QACvB,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC,CAAA,CAAC;QACd,oBAAoB;IACtB,CAAC;IAED,MAAM,OAAO,GAAG,GAAG,EAAE;QACnB,KAAK,MAAM,CAAC,GAAG,EAAE,QAAQ,CAAC,IAAI,SAAS,EAAE,CAAC;YACxC,OAAO,CAAC,cAAc,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;QACvC,CAAC;IACH,CAAC,CAAA;IACD,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACzB,OAAO,OAAO,CAAA;AAChB,CAAC,CAAA;AA5BY,QAAA,YAAY,gBA4BxB","sourcesContent":["import { type ChildProcess } from 'child_process'\nimport { allSignals } from './all-signals.js'\n\n/**\n * Starts forwarding signals to `child` through `parent`.\n */\nexport const proxySignals = (child: ChildProcess) => {\n const listeners = new Map()\n\n for (const sig of allSignals) {\n const listener = () => {\n // some signals can only be received, not sent\n try {\n child.kill(sig)\n /* c8 ignore start */\n } catch (_) {}\n /* c8 ignore stop */\n }\n try {\n // if it's a signal this system doesn't recognize, skip it\n process.on(sig, listener)\n listeners.set(sig, listener)\n /* c8 ignore start */\n } catch (_) {}\n /* c8 ignore stop */\n }\n\n const unproxy = () => {\n for (const [sig, listener] of listeners) {\n process.removeListener(sig, listener)\n }\n }\n child.on('exit', unproxy)\n return unproxy\n}\n"]} \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/watchdog.d.ts b/node_modules/foreground-child/dist/commonjs/watchdog.d.ts new file mode 100644 index 0000000..f10c9de --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/watchdog.d.ts @@ -0,0 +1,10 @@ +import { ChildProcess } from 'child_process'; +/** + * Pass in a ChildProcess, and this will spawn a watchdog process that + * will make sure it exits if the parent does, thus preventing any + * dangling detached zombie processes. + * + * If the child ends before the parent, then the watchdog will terminate. + */ +export declare const watchdog: (child: ChildProcess) => ChildProcess; +//# sourceMappingURL=watchdog.d.ts.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/watchdog.d.ts.map b/node_modules/foreground-child/dist/commonjs/watchdog.d.ts.map new file mode 100644 index 0000000..d9ec243 --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/watchdog.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"watchdog.d.ts","sourceRoot":"","sources":["../../src/watchdog.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,YAAY,EAAS,MAAM,eAAe,CAAA;AAyBnD;;;;;;GAMG;AACH,eAAO,MAAM,QAAQ,UAAW,YAAY,iBAc3C,CAAA"} \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/watchdog.js b/node_modules/foreground-child/dist/commonjs/watchdog.js new file mode 100644 index 0000000..514e234 --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/watchdog.js @@ -0,0 +1,50 @@ +"use strict"; +// this spawns a child process that listens for SIGHUP when the +// parent process exits, and after 200ms, sends a SIGKILL to the +// child, in case it did not terminate. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.watchdog = void 0; +const child_process_1 = require("child_process"); +const watchdogCode = String.raw ` +const pid = parseInt(process.argv[1], 10) +process.title = 'node (foreground-child watchdog pid=' + pid + ')' +if (!isNaN(pid)) { + let barked = false + // keepalive + const interval = setInterval(() => {}, 60000) + const bark = () => { + clearInterval(interval) + if (barked) return + barked = true + process.removeListener('SIGHUP', bark) + setTimeout(() => { + try { + process.kill(pid, 'SIGKILL') + setTimeout(() => process.exit(), 200) + } catch (_) {} + }, 500) + }) + process.on('SIGHUP', bark) +} +`; +/** + * Pass in a ChildProcess, and this will spawn a watchdog process that + * will make sure it exits if the parent does, thus preventing any + * dangling detached zombie processes. + * + * If the child ends before the parent, then the watchdog will terminate. + */ +const watchdog = (child) => { + let dogExited = false; + const dog = (0, child_process_1.spawn)(process.execPath, ['-e', watchdogCode, String(child.pid)], { + stdio: 'ignore', + }); + dog.on('exit', () => (dogExited = true)); + child.on('exit', () => { + if (!dogExited) + dog.kill('SIGKILL'); + }); + return dog; +}; +exports.watchdog = watchdog; +//# sourceMappingURL=watchdog.js.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/commonjs/watchdog.js.map b/node_modules/foreground-child/dist/commonjs/watchdog.js.map new file mode 100644 index 0000000..d486c97 --- /dev/null +++ b/node_modules/foreground-child/dist/commonjs/watchdog.js.map @@ -0,0 +1 @@ +{"version":3,"file":"watchdog.js","sourceRoot":"","sources":["../../src/watchdog.ts"],"names":[],"mappings":";AAAA,+DAA+D;AAC/D,gEAAgE;AAChE,uCAAuC;;;AAEvC,iDAAmD;AAEnD,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;CAqB9B,CAAA;AAED;;;;;;GAMG;AACI,MAAM,QAAQ,GAAG,CAAC,KAAmB,EAAE,EAAE;IAC9C,IAAI,SAAS,GAAG,KAAK,CAAA;IACrB,MAAM,GAAG,GAAG,IAAA,qBAAK,EACf,OAAO,CAAC,QAAQ,EAChB,CAAC,IAAI,EAAE,YAAY,EAAE,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,EACvC;QACE,KAAK,EAAE,QAAQ;KAChB,CACF,CAAA;IACD,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,CAAA;IACxC,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE;QACpB,IAAI,CAAC,SAAS;YAAE,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;IACrC,CAAC,CAAC,CAAA;IACF,OAAO,GAAG,CAAA;AACZ,CAAC,CAAA;AAdY,QAAA,QAAQ,YAcpB","sourcesContent":["// this spawns a child process that listens for SIGHUP when the\n// parent process exits, and after 200ms, sends a SIGKILL to the\n// child, in case it did not terminate.\n\nimport { ChildProcess, spawn } from 'child_process'\n\nconst watchdogCode = String.raw`\nconst pid = parseInt(process.argv[1], 10)\nprocess.title = 'node (foreground-child watchdog pid=' + pid + ')'\nif (!isNaN(pid)) {\n let barked = false\n // keepalive\n const interval = setInterval(() => {}, 60000)\n const bark = () => {\n clearInterval(interval)\n if (barked) return\n barked = true\n process.removeListener('SIGHUP', bark)\n setTimeout(() => {\n try {\n process.kill(pid, 'SIGKILL')\n setTimeout(() => process.exit(), 200)\n } catch (_) {}\n }, 500)\n })\n process.on('SIGHUP', bark)\n}\n`\n\n/**\n * Pass in a ChildProcess, and this will spawn a watchdog process that\n * will make sure it exits if the parent does, thus preventing any\n * dangling detached zombie processes.\n *\n * If the child ends before the parent, then the watchdog will terminate.\n */\nexport const watchdog = (child: ChildProcess) => {\n let dogExited = false\n const dog = spawn(\n process.execPath,\n ['-e', watchdogCode, String(child.pid)],\n {\n stdio: 'ignore',\n },\n )\n dog.on('exit', () => (dogExited = true))\n child.on('exit', () => {\n if (!dogExited) dog.kill('SIGKILL')\n })\n return dog\n}\n"]} \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/all-signals.d.ts b/node_modules/foreground-child/dist/esm/all-signals.d.ts new file mode 100644 index 0000000..ecc0a62 --- /dev/null +++ b/node_modules/foreground-child/dist/esm/all-signals.d.ts @@ -0,0 +1,2 @@ +export declare const allSignals: NodeJS.Signals[]; +//# sourceMappingURL=all-signals.d.ts.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/all-signals.d.ts.map b/node_modules/foreground-child/dist/esm/all-signals.d.ts.map new file mode 100644 index 0000000..cd1c161 --- /dev/null +++ b/node_modules/foreground-child/dist/esm/all-signals.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"all-signals.d.ts","sourceRoot":"","sources":["../../src/all-signals.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,UAAU,EAShB,MAAM,CAAC,OAAO,EAAE,CAAA"} \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/all-signals.js b/node_modules/foreground-child/dist/esm/all-signals.js new file mode 100644 index 0000000..7e8d54d --- /dev/null +++ b/node_modules/foreground-child/dist/esm/all-signals.js @@ -0,0 +1,52 @@ +import constants from 'node:constants'; +export const allSignals = +// this is the full list of signals that Node will let us do anything with +Object.keys(constants).filter(k => k.startsWith('SIG') && + // https://github.com/tapjs/signal-exit/issues/21 + k !== 'SIGPROF' && + // no sense trying to listen for SIGKILL, it's impossible + k !== 'SIGKILL'); +// These are some obscure signals that are reported by kill -l +// on macOS, Linux, or Windows, but which don't have any mapping +// in Node.js. No sense trying if they're just going to throw +// every time on every platform. +// +// 'SIGEMT', +// 'SIGLOST', +// 'SIGPOLL', +// 'SIGRTMAX', +// 'SIGRTMAX-1', +// 'SIGRTMAX-10', +// 'SIGRTMAX-11', +// 'SIGRTMAX-12', +// 'SIGRTMAX-13', +// 'SIGRTMAX-14', +// 'SIGRTMAX-15', +// 'SIGRTMAX-2', +// 'SIGRTMAX-3', +// 'SIGRTMAX-4', +// 'SIGRTMAX-5', +// 'SIGRTMAX-6', +// 'SIGRTMAX-7', +// 'SIGRTMAX-8', +// 'SIGRTMAX-9', +// 'SIGRTMIN', +// 'SIGRTMIN+1', +// 'SIGRTMIN+10', +// 'SIGRTMIN+11', +// 'SIGRTMIN+12', +// 'SIGRTMIN+13', +// 'SIGRTMIN+14', +// 'SIGRTMIN+15', +// 'SIGRTMIN+16', +// 'SIGRTMIN+2', +// 'SIGRTMIN+3', +// 'SIGRTMIN+4', +// 'SIGRTMIN+5', +// 'SIGRTMIN+6', +// 'SIGRTMIN+7', +// 'SIGRTMIN+8', +// 'SIGRTMIN+9', +// 'SIGSTKFLT', +// 'SIGUNUSED', +//# sourceMappingURL=all-signals.js.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/all-signals.js.map b/node_modules/foreground-child/dist/esm/all-signals.js.map new file mode 100644 index 0000000..1c63c6b --- /dev/null +++ b/node_modules/foreground-child/dist/esm/all-signals.js.map @@ -0,0 +1 @@ +{"version":3,"file":"all-signals.js","sourceRoot":"","sources":["../../src/all-signals.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,gBAAgB,CAAA;AACtC,MAAM,CAAC,MAAM,UAAU;AACrB,0EAA0E;AAC1E,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,CAC3B,CAAC,CAAC,EAAE,CACF,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC;IACnB,iDAAiD;IACjD,CAAC,KAAK,SAAS;IACf,yDAAyD;IACzD,CAAC,KAAK,SAAS,CACE,CAAA;AAEvB,8DAA8D;AAC9D,gEAAgE;AAChE,6DAA6D;AAC7D,gCAAgC;AAChC,EAAE;AACF,YAAY;AACZ,aAAa;AACb,aAAa;AACb,cAAc;AACd,gBAAgB;AAChB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,cAAc;AACd,gBAAgB;AAChB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB,eAAe;AACf,eAAe","sourcesContent":["import constants from 'node:constants'\nexport const allSignals =\n // this is the full list of signals that Node will let us do anything with\n Object.keys(constants).filter(\n k =>\n k.startsWith('SIG') &&\n // https://github.com/tapjs/signal-exit/issues/21\n k !== 'SIGPROF' &&\n // no sense trying to listen for SIGKILL, it's impossible\n k !== 'SIGKILL',\n ) as NodeJS.Signals[]\n\n// These are some obscure signals that are reported by kill -l\n// on macOS, Linux, or Windows, but which don't have any mapping\n// in Node.js. No sense trying if they're just going to throw\n// every time on every platform.\n//\n// 'SIGEMT',\n// 'SIGLOST',\n// 'SIGPOLL',\n// 'SIGRTMAX',\n// 'SIGRTMAX-1',\n// 'SIGRTMAX-10',\n// 'SIGRTMAX-11',\n// 'SIGRTMAX-12',\n// 'SIGRTMAX-13',\n// 'SIGRTMAX-14',\n// 'SIGRTMAX-15',\n// 'SIGRTMAX-2',\n// 'SIGRTMAX-3',\n// 'SIGRTMAX-4',\n// 'SIGRTMAX-5',\n// 'SIGRTMAX-6',\n// 'SIGRTMAX-7',\n// 'SIGRTMAX-8',\n// 'SIGRTMAX-9',\n// 'SIGRTMIN',\n// 'SIGRTMIN+1',\n// 'SIGRTMIN+10',\n// 'SIGRTMIN+11',\n// 'SIGRTMIN+12',\n// 'SIGRTMIN+13',\n// 'SIGRTMIN+14',\n// 'SIGRTMIN+15',\n// 'SIGRTMIN+16',\n// 'SIGRTMIN+2',\n// 'SIGRTMIN+3',\n// 'SIGRTMIN+4',\n// 'SIGRTMIN+5',\n// 'SIGRTMIN+6',\n// 'SIGRTMIN+7',\n// 'SIGRTMIN+8',\n// 'SIGRTMIN+9',\n// 'SIGSTKFLT',\n// 'SIGUNUSED',\n"]} \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/index.d.ts b/node_modules/foreground-child/dist/esm/index.d.ts new file mode 100644 index 0000000..d15b38e --- /dev/null +++ b/node_modules/foreground-child/dist/esm/index.d.ts @@ -0,0 +1,58 @@ +import { ChildProcessByStdio, SpawnOptions, ChildProcess } from 'child_process'; +/** + * The signature for the cleanup method. + * + * Arguments indicate the exit status of the child process. + * + * If a Promise is returned, then the process is not terminated + * until it resolves, and the resolution value is treated as the + * exit status (if a number) or signal exit (if a signal string). + * + * If `undefined` is returned, then no change is made, and the parent + * exits in the same way that the child exited. + * + * If boolean `false` is returned, then the parent's exit is canceled. + * + * If a number is returned, then the parent process exits with the number + * as its exitCode. + * + * If a signal string is returned, then the parent process is killed with + * the same signal that caused the child to exit. + */ +export type Cleanup = (code: number | null, signal: null | NodeJS.Signals, processInfo: { + watchdogPid?: ChildProcess['pid']; +}) => void | undefined | number | NodeJS.Signals | false | Promise; +export type FgArgs = [program: string | [cmd: string, ...args: string[]], cleanup?: Cleanup] | [ + program: [cmd: string, ...args: string[]], + opts?: SpawnOptions, + cleanup?: Cleanup +] | [program: string, cleanup?: Cleanup] | [program: string, opts?: SpawnOptions, cleanup?: Cleanup] | [program: string, args?: string[], cleanup?: Cleanup] | [ + program: string, + args?: string[], + opts?: SpawnOptions, + cleanup?: Cleanup +]; +/** + * Normalizes the arguments passed to `foregroundChild`. + * + * Exposed for testing. + * + * @internal + */ +export declare const normalizeFgArgs: (fgArgs: FgArgs) => [program: string, args: string[], spawnOpts: SpawnOptions, cleanup: Cleanup]; +/** + * Spawn the specified program as a "foreground" process, or at least as + * close as is possible given node's lack of exec-without-fork. + * + * Cleanup method may be used to modify or ignore the result of the child's + * exit code or signal. If cleanup returns undefined (or a Promise that + * resolves to undefined), then the parent will exit in the same way that + * the child did. + * + * Return boolean `false` to prevent the parent's exit entirely. + */ +export declare function foregroundChild(cmd: string | [cmd: string, ...args: string[]], cleanup?: Cleanup): ChildProcessByStdio; +export declare function foregroundChild(program: string, args?: string[], cleanup?: Cleanup): ChildProcessByStdio; +export declare function foregroundChild(program: string, spawnOpts?: SpawnOptions, cleanup?: Cleanup): ChildProcessByStdio; +export declare function foregroundChild(program: string, args?: string[], spawnOpts?: SpawnOptions, cleanup?: Cleanup): ChildProcessByStdio; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/index.d.ts.map b/node_modules/foreground-child/dist/esm/index.d.ts.map new file mode 100644 index 0000000..b26fecd --- /dev/null +++ b/node_modules/foreground-child/dist/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EAInB,YAAY,EACZ,YAAY,EACb,MAAM,eAAe,CAAA;AAUtB;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,MAAM,OAAO,GAAG,CACpB,IAAI,EAAE,MAAM,GAAG,IAAI,EACnB,MAAM,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AAG,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,CAAC,EAC9C,OAAO,CAAC,EAAE,OAAO,GAChB,mBAAmB,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACxC,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,EACf,IAAI,CAAC,EAAE,MAAM,EAAE,EACf,OAAO,CAAC,EAAE,OAAO,GAChB,mBAAmB,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACxC,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,EACf,SAAS,CAAC,EAAE,YAAY,EACxB,OAAO,CAAC,EAAE,OAAO,GAChB,mBAAmB,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACxC,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,EACf,IAAI,CAAC,EAAE,MAAM,EAAE,EACf,SAAS,CAAC,EAAE,YAAY,EACxB,OAAO,CAAC,EAAE,OAAO,GAChB,mBAAmB,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/index.js b/node_modules/foreground-child/dist/esm/index.js new file mode 100644 index 0000000..6266b58 --- /dev/null +++ b/node_modules/foreground-child/dist/esm/index.js @@ -0,0 +1,115 @@ +import { spawn as nodeSpawn, } from 'child_process'; +import crossSpawn from 'cross-spawn'; +import { onExit } from 'signal-exit'; +import { proxySignals } from './proxy-signals.js'; +import { watchdog } from './watchdog.js'; +/* c8 ignore start */ +const spawn = process?.platform === 'win32' ? crossSpawn : nodeSpawn; +/** + * Normalizes the arguments passed to `foregroundChild`. + * + * Exposed for testing. + * + * @internal + */ +export const normalizeFgArgs = (fgArgs) => { + let [program, args = [], spawnOpts = {}, cleanup = () => { }] = fgArgs; + if (typeof args === 'function') { + cleanup = args; + spawnOpts = {}; + args = []; + } + else if (!!args && typeof args === 'object' && !Array.isArray(args)) { + if (typeof spawnOpts === 'function') + cleanup = spawnOpts; + spawnOpts = args; + args = []; + } + else if (typeof spawnOpts === 'function') { + cleanup = spawnOpts; + spawnOpts = {}; + } + if (Array.isArray(program)) { + const [pp, ...pa] = program; + program = pp; + args = pa; + } + return [program, args, { ...spawnOpts }, cleanup]; +}; +export function foregroundChild(...fgArgs) { + const [program, args, spawnOpts, cleanup] = normalizeFgArgs(fgArgs); + spawnOpts.stdio = [0, 1, 2]; + if (process.send) { + spawnOpts.stdio.push('ipc'); + } + const child = spawn(program, args, spawnOpts); + const childHangup = () => { + try { + child.kill('SIGHUP'); + /* c8 ignore start */ + } + catch (_) { + // SIGHUP is weird on windows + child.kill('SIGTERM'); + } + /* c8 ignore stop */ + }; + const removeOnExit = onExit(childHangup); + proxySignals(child); + const dog = watchdog(child); + let done = false; + child.on('close', async (code, signal) => { + /* c8 ignore start */ + if (done) + return; + /* c8 ignore stop */ + done = true; + const result = cleanup(code, signal, { + watchdogPid: dog.pid, + }); + const res = isPromise(result) ? await result : result; + removeOnExit(); + if (res === false) + return; + else if (typeof res === 'string') { + signal = res; + code = null; + } + else if (typeof res === 'number') { + code = res; + signal = null; + } + if (signal) { + // If there is nothing else keeping the event loop alive, + // then there's a race between a graceful exit and getting + // the signal to this process. Put this timeout here to + // make sure we're still alive to get the signal, and thus + // exit with the intended signal code. + /* istanbul ignore next */ + setTimeout(() => { }, 2000); + try { + process.kill(process.pid, signal); + /* c8 ignore start */ + } + catch (_) { + process.kill(process.pid, 'SIGTERM'); + } + /* c8 ignore stop */ + } + else { + process.exit(code || 0); + } + }); + if (process.send) { + process.removeAllListeners('message'); + child.on('message', (message, sendHandle) => { + process.send?.(message, sendHandle); + }); + process.on('message', (message, sendHandle) => { + child.send(message, sendHandle); + }); + } + return child; +} +const isPromise = (o) => !!o && typeof o === 'object' && typeof o.then === 'function'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/index.js.map b/node_modules/foreground-child/dist/esm/index.js.map new file mode 100644 index 0000000..7d9d1bd --- /dev/null +++ b/node_modules/foreground-child/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,IAAI,SAAS,GAGnB,MAAM,eAAe,CAAA;AACtB,OAAO,UAAU,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAExC,qBAAqB;AACrB,MAAM,KAAK,GAAG,OAAO,EAAE,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAAA;AAsDpE;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAC7B,MAAc,EAMd,EAAE;IACF,IAAI,CAAC,OAAO,EAAE,IAAI,GAAG,EAAE,EAAE,SAAS,GAAG,EAAE,EAAE,OAAO,GAAG,GAAG,EAAE,GAAE,CAAC,CAAC,GAAG,MAAM,CAAA;IACrE,IAAI,OAAO,IAAI,KAAK,UAAU,EAAE,CAAC;QAC/B,OAAO,GAAG,IAAI,CAAA;QACd,SAAS,GAAG,EAAE,CAAA;QACd,IAAI,GAAG,EAAE,CAAA;IACX,CAAC;SAAM,IAAI,CAAC,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;QACtE,IAAI,OAAO,SAAS,KAAK,UAAU;YAAE,OAAO,GAAG,SAAS,CAAA;QACxD,SAAS,GAAG,IAAI,CAAA;QAChB,IAAI,GAAG,EAAE,CAAA;IACX,CAAC;SAAM,IAAI,OAAO,SAAS,KAAK,UAAU,EAAE,CAAC;QAC3C,OAAO,GAAG,SAAS,CAAA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;IAEF,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,OAAO,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAA;QAErC,KAAK,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,EAAE;YAC1C,OAAO,CAAC,IAAI,EAAE,CAAC,OAAO,EAAE,UAAU,CAAC,CAAA;QACrC,CAAC,CAAC,CAAA;QAEF,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,EAAE;YAC5C,KAAK,CAAC,IAAI,CACR,OAAuB,EACvB,UAAoC,CACrC,CAAA;QACH,CAAC,CAAC,CAAA;IACJ,CAAC;IAED,OAAO,KAAK,CAAA;AACd,CAAC;AAED,MAAM,SAAS,GAAG,CAAC,CAAM,EAAqB,EAAE,CAC9C,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,CAAC,IAAI,KAAK,UAAU,CAAA","sourcesContent":["import {\n ChildProcessByStdio,\n SendHandle,\n Serializable,\n spawn as nodeSpawn,\n SpawnOptions,\n ChildProcess,\n} from 'child_process'\nimport crossSpawn from 'cross-spawn'\nimport { onExit } from 'signal-exit'\nimport { proxySignals } from './proxy-signals.js'\nimport { watchdog } from './watchdog.js'\n\n/* c8 ignore start */\nconst spawn = process?.platform === 'win32' ? crossSpawn : nodeSpawn\n/* c8 ignore stop */\n\n/**\n * The signature for the cleanup method.\n *\n * Arguments indicate the exit status of the child process.\n *\n * If a Promise is returned, then the process is not terminated\n * until it resolves, and the resolution value is treated as the\n * exit status (if a number) or signal exit (if a signal string).\n *\n * If `undefined` is returned, then no change is made, and the parent\n * exits in the same way that the child exited.\n *\n * If boolean `false` is returned, then the parent's exit is canceled.\n *\n * If a number is returned, then the parent process exits with the number\n * as its exitCode.\n *\n * If a signal string is returned, then the parent process is killed with\n * the same signal that caused the child to exit.\n */\nexport type Cleanup = (\n code: number | null,\n signal: null | NodeJS.Signals,\n processInfo: {\n watchdogPid?: ChildProcess['pid']\n },\n) =>\n | void\n | undefined\n | number\n | NodeJS.Signals\n | false\n | Promise\n\nexport type FgArgs =\n | [program: string | [cmd: string, ...args: string[]], cleanup?: Cleanup]\n | [\n program: [cmd: string, ...args: string[]],\n opts?: SpawnOptions,\n cleanup?: Cleanup,\n ]\n | [program: string, cleanup?: Cleanup]\n | [program: string, opts?: SpawnOptions, cleanup?: Cleanup]\n | [program: string, args?: string[], cleanup?: Cleanup]\n | [\n program: string,\n args?: string[],\n opts?: SpawnOptions,\n cleanup?: Cleanup,\n ]\n\n/**\n * Normalizes the arguments passed to `foregroundChild`.\n *\n * Exposed for testing.\n *\n * @internal\n */\nexport const normalizeFgArgs = (\n fgArgs: FgArgs,\n): [\n program: string,\n args: string[],\n spawnOpts: SpawnOptions,\n cleanup: Cleanup,\n] => {\n let [program, args = [], spawnOpts = {}, cleanup = () => {}] = fgArgs\n if (typeof args === 'function') {\n cleanup = args\n spawnOpts = {}\n args = []\n } else if (!!args && typeof args === 'object' && !Array.isArray(args)) {\n if (typeof spawnOpts === 'function') cleanup = spawnOpts\n spawnOpts = args\n args = []\n } else if (typeof spawnOpts === 'function') {\n cleanup = spawnOpts\n spawnOpts = {}\n }\n if (Array.isArray(program)) {\n const [pp, ...pa] = program\n program = pp\n args = pa\n }\n return [program, args, { ...spawnOpts }, cleanup]\n}\n\n/**\n * Spawn the specified program as a \"foreground\" process, or at least as\n * close as is possible given node's lack of exec-without-fork.\n *\n * Cleanup method may be used to modify or ignore the result of the child's\n * exit code or signal. If cleanup returns undefined (or a Promise that\n * resolves to undefined), then the parent will exit in the same way that\n * the child did.\n *\n * Return boolean `false` to prevent the parent's exit entirely.\n */\nexport function foregroundChild(\n cmd: string | [cmd: string, ...args: string[]],\n cleanup?: Cleanup,\n): ChildProcessByStdio\nexport function foregroundChild(\n program: string,\n args?: string[],\n cleanup?: Cleanup,\n): ChildProcessByStdio\nexport function foregroundChild(\n program: string,\n spawnOpts?: SpawnOptions,\n cleanup?: Cleanup,\n): ChildProcessByStdio\nexport function foregroundChild(\n program: string,\n args?: string[],\n spawnOpts?: SpawnOptions,\n cleanup?: Cleanup,\n): ChildProcessByStdio\nexport function foregroundChild(\n ...fgArgs: FgArgs\n): ChildProcessByStdio {\n const [program, args, spawnOpts, cleanup] = normalizeFgArgs(fgArgs)\n\n spawnOpts.stdio = [0, 1, 2]\n if (process.send) {\n spawnOpts.stdio.push('ipc')\n }\n\n const child = spawn(program, args, spawnOpts) as ChildProcessByStdio<\n null,\n null,\n null\n >\n\n const childHangup = () => {\n try {\n child.kill('SIGHUP')\n\n /* c8 ignore start */\n } catch (_) {\n // SIGHUP is weird on windows\n child.kill('SIGTERM')\n }\n /* c8 ignore stop */\n }\n const removeOnExit = onExit(childHangup)\n\n proxySignals(child)\n const dog = watchdog(child)\n\n let done = false\n child.on('close', async (code, signal) => {\n /* c8 ignore start */\n if (done) return\n /* c8 ignore stop */\n done = true\n const result = cleanup(code, signal, {\n watchdogPid: dog.pid,\n })\n const res = isPromise(result) ? await result : result\n removeOnExit()\n\n if (res === false) return\n else if (typeof res === 'string') {\n signal = res\n code = null\n } else if (typeof res === 'number') {\n code = res\n signal = null\n }\n\n if (signal) {\n // If there is nothing else keeping the event loop alive,\n // then there's a race between a graceful exit and getting\n // the signal to this process. Put this timeout here to\n // make sure we're still alive to get the signal, and thus\n // exit with the intended signal code.\n /* istanbul ignore next */\n setTimeout(() => {}, 2000)\n try {\n process.kill(process.pid, signal)\n /* c8 ignore start */\n } catch (_) {\n process.kill(process.pid, 'SIGTERM')\n }\n /* c8 ignore stop */\n } else {\n process.exit(code || 0)\n }\n })\n\n if (process.send) {\n process.removeAllListeners('message')\n\n child.on('message', (message, sendHandle) => {\n process.send?.(message, sendHandle)\n })\n\n process.on('message', (message, sendHandle) => {\n child.send(\n message as Serializable,\n sendHandle as SendHandle | undefined,\n )\n })\n }\n\n return child\n}\n\nconst isPromise = (o: any): o is Promise =>\n !!o && typeof o === 'object' && typeof o.then === 'function'\n"]} \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/package.json b/node_modules/foreground-child/dist/esm/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/node_modules/foreground-child/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/foreground-child/dist/esm/proxy-signals.d.ts b/node_modules/foreground-child/dist/esm/proxy-signals.d.ts new file mode 100644 index 0000000..edf17bd --- /dev/null +++ b/node_modules/foreground-child/dist/esm/proxy-signals.d.ts @@ -0,0 +1,6 @@ +import { type ChildProcess } from 'child_process'; +/** + * Starts forwarding signals to `child` through `parent`. + */ +export declare const proxySignals: (child: ChildProcess) => () => void; +//# sourceMappingURL=proxy-signals.d.ts.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/proxy-signals.d.ts.map b/node_modules/foreground-child/dist/esm/proxy-signals.d.ts.map new file mode 100644 index 0000000..7c19279 --- /dev/null +++ b/node_modules/foreground-child/dist/esm/proxy-signals.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"proxy-signals.d.ts","sourceRoot":"","sources":["../../src/proxy-signals.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,eAAe,CAAA;AAGjD;;GAEG;AACH,eAAO,MAAM,YAAY,UAAW,YAAY,eA4B/C,CAAA"} \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/proxy-signals.js b/node_modules/foreground-child/dist/esm/proxy-signals.js new file mode 100644 index 0000000..8e1efe3 --- /dev/null +++ b/node_modules/foreground-child/dist/esm/proxy-signals.js @@ -0,0 +1,34 @@ +import { allSignals } from './all-signals.js'; +/** + * Starts forwarding signals to `child` through `parent`. + */ +export const proxySignals = (child) => { + const listeners = new Map(); + for (const sig of allSignals) { + const listener = () => { + // some signals can only be received, not sent + try { + child.kill(sig); + /* c8 ignore start */ + } + catch (_) { } + /* c8 ignore stop */ + }; + try { + // if it's a signal this system doesn't recognize, skip it + process.on(sig, listener); + listeners.set(sig, listener); + /* c8 ignore start */ + } + catch (_) { } + /* c8 ignore stop */ + } + const unproxy = () => { + for (const [sig, listener] of listeners) { + process.removeListener(sig, listener); + } + }; + child.on('exit', unproxy); + return unproxy; +}; +//# sourceMappingURL=proxy-signals.js.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/proxy-signals.js.map b/node_modules/foreground-child/dist/esm/proxy-signals.js.map new file mode 100644 index 0000000..978750f --- /dev/null +++ b/node_modules/foreground-child/dist/esm/proxy-signals.js.map @@ -0,0 +1 @@ +{"version":3,"file":"proxy-signals.js","sourceRoot":"","sources":["../../src/proxy-signals.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAE7C;;GAEG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,KAAmB,EAAE,EAAE;IAClD,MAAM,SAAS,GAAG,IAAI,GAAG,EAAE,CAAA;IAE3B,KAAK,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;QAC7B,MAAM,QAAQ,GAAG,GAAG,EAAE;YACpB,8CAA8C;YAC9C,IAAI,CAAC;gBACH,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;gBACf,qBAAqB;YACvB,CAAC;YAAC,OAAO,CAAC,EAAE,CAAC,CAAA,CAAC;YACd,oBAAoB;QACtB,CAAC,CAAA;QACD,IAAI,CAAC;YACH,0DAA0D;YAC1D,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;YACzB,SAAS,CAAC,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;YAC5B,qBAAqB;QACvB,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC,CAAA,CAAC;QACd,oBAAoB;IACtB,CAAC;IAED,MAAM,OAAO,GAAG,GAAG,EAAE;QACnB,KAAK,MAAM,CAAC,GAAG,EAAE,QAAQ,CAAC,IAAI,SAAS,EAAE,CAAC;YACxC,OAAO,CAAC,cAAc,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;QACvC,CAAC;IACH,CAAC,CAAA;IACD,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACzB,OAAO,OAAO,CAAA;AAChB,CAAC,CAAA","sourcesContent":["import { type ChildProcess } from 'child_process'\nimport { allSignals } from './all-signals.js'\n\n/**\n * Starts forwarding signals to `child` through `parent`.\n */\nexport const proxySignals = (child: ChildProcess) => {\n const listeners = new Map()\n\n for (const sig of allSignals) {\n const listener = () => {\n // some signals can only be received, not sent\n try {\n child.kill(sig)\n /* c8 ignore start */\n } catch (_) {}\n /* c8 ignore stop */\n }\n try {\n // if it's a signal this system doesn't recognize, skip it\n process.on(sig, listener)\n listeners.set(sig, listener)\n /* c8 ignore start */\n } catch (_) {}\n /* c8 ignore stop */\n }\n\n const unproxy = () => {\n for (const [sig, listener] of listeners) {\n process.removeListener(sig, listener)\n }\n }\n child.on('exit', unproxy)\n return unproxy\n}\n"]} \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/watchdog.d.ts b/node_modules/foreground-child/dist/esm/watchdog.d.ts new file mode 100644 index 0000000..f10c9de --- /dev/null +++ b/node_modules/foreground-child/dist/esm/watchdog.d.ts @@ -0,0 +1,10 @@ +import { ChildProcess } from 'child_process'; +/** + * Pass in a ChildProcess, and this will spawn a watchdog process that + * will make sure it exits if the parent does, thus preventing any + * dangling detached zombie processes. + * + * If the child ends before the parent, then the watchdog will terminate. + */ +export declare const watchdog: (child: ChildProcess) => ChildProcess; +//# sourceMappingURL=watchdog.d.ts.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/watchdog.d.ts.map b/node_modules/foreground-child/dist/esm/watchdog.d.ts.map new file mode 100644 index 0000000..d9ec243 --- /dev/null +++ b/node_modules/foreground-child/dist/esm/watchdog.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"watchdog.d.ts","sourceRoot":"","sources":["../../src/watchdog.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,YAAY,EAAS,MAAM,eAAe,CAAA;AAyBnD;;;;;;GAMG;AACH,eAAO,MAAM,QAAQ,UAAW,YAAY,iBAc3C,CAAA"} \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/watchdog.js b/node_modules/foreground-child/dist/esm/watchdog.js new file mode 100644 index 0000000..7aa184e --- /dev/null +++ b/node_modules/foreground-child/dist/esm/watchdog.js @@ -0,0 +1,46 @@ +// this spawns a child process that listens for SIGHUP when the +// parent process exits, and after 200ms, sends a SIGKILL to the +// child, in case it did not terminate. +import { spawn } from 'child_process'; +const watchdogCode = String.raw ` +const pid = parseInt(process.argv[1], 10) +process.title = 'node (foreground-child watchdog pid=' + pid + ')' +if (!isNaN(pid)) { + let barked = false + // keepalive + const interval = setInterval(() => {}, 60000) + const bark = () => { + clearInterval(interval) + if (barked) return + barked = true + process.removeListener('SIGHUP', bark) + setTimeout(() => { + try { + process.kill(pid, 'SIGKILL') + setTimeout(() => process.exit(), 200) + } catch (_) {} + }, 500) + }) + process.on('SIGHUP', bark) +} +`; +/** + * Pass in a ChildProcess, and this will spawn a watchdog process that + * will make sure it exits if the parent does, thus preventing any + * dangling detached zombie processes. + * + * If the child ends before the parent, then the watchdog will terminate. + */ +export const watchdog = (child) => { + let dogExited = false; + const dog = spawn(process.execPath, ['-e', watchdogCode, String(child.pid)], { + stdio: 'ignore', + }); + dog.on('exit', () => (dogExited = true)); + child.on('exit', () => { + if (!dogExited) + dog.kill('SIGKILL'); + }); + return dog; +}; +//# sourceMappingURL=watchdog.js.map \ No newline at end of file diff --git a/node_modules/foreground-child/dist/esm/watchdog.js.map b/node_modules/foreground-child/dist/esm/watchdog.js.map new file mode 100644 index 0000000..6f4e39f --- /dev/null +++ b/node_modules/foreground-child/dist/esm/watchdog.js.map @@ -0,0 +1 @@ +{"version":3,"file":"watchdog.js","sourceRoot":"","sources":["../../src/watchdog.ts"],"names":[],"mappings":"AAAA,+DAA+D;AAC/D,gEAAgE;AAChE,uCAAuC;AAEvC,OAAO,EAAgB,KAAK,EAAE,MAAM,eAAe,CAAA;AAEnD,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;CAqB9B,CAAA;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,KAAmB,EAAE,EAAE;IAC9C,IAAI,SAAS,GAAG,KAAK,CAAA;IACrB,MAAM,GAAG,GAAG,KAAK,CACf,OAAO,CAAC,QAAQ,EAChB,CAAC,IAAI,EAAE,YAAY,EAAE,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,EACvC;QACE,KAAK,EAAE,QAAQ;KAChB,CACF,CAAA;IACD,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,CAAA;IACxC,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE;QACpB,IAAI,CAAC,SAAS;YAAE,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;IACrC,CAAC,CAAC,CAAA;IACF,OAAO,GAAG,CAAA;AACZ,CAAC,CAAA","sourcesContent":["// this spawns a child process that listens for SIGHUP when the\n// parent process exits, and after 200ms, sends a SIGKILL to the\n// child, in case it did not terminate.\n\nimport { ChildProcess, spawn } from 'child_process'\n\nconst watchdogCode = String.raw`\nconst pid = parseInt(process.argv[1], 10)\nprocess.title = 'node (foreground-child watchdog pid=' + pid + ')'\nif (!isNaN(pid)) {\n let barked = false\n // keepalive\n const interval = setInterval(() => {}, 60000)\n const bark = () => {\n clearInterval(interval)\n if (barked) return\n barked = true\n process.removeListener('SIGHUP', bark)\n setTimeout(() => {\n try {\n process.kill(pid, 'SIGKILL')\n setTimeout(() => process.exit(), 200)\n } catch (_) {}\n }, 500)\n })\n process.on('SIGHUP', bark)\n}\n`\n\n/**\n * Pass in a ChildProcess, and this will spawn a watchdog process that\n * will make sure it exits if the parent does, thus preventing any\n * dangling detached zombie processes.\n *\n * If the child ends before the parent, then the watchdog will terminate.\n */\nexport const watchdog = (child: ChildProcess) => {\n let dogExited = false\n const dog = spawn(\n process.execPath,\n ['-e', watchdogCode, String(child.pid)],\n {\n stdio: 'ignore',\n },\n )\n dog.on('exit', () => (dogExited = true))\n child.on('exit', () => {\n if (!dogExited) dog.kill('SIGKILL')\n })\n return dog\n}\n"]} \ No newline at end of file diff --git a/node_modules/foreground-child/package.json b/node_modules/foreground-child/package.json new file mode 100644 index 0000000..75f5b99 --- /dev/null +++ b/node_modules/foreground-child/package.json @@ -0,0 +1,106 @@ +{ + "name": "foreground-child", + "version": "3.3.1", + "description": "Run a child as if it's the foreground process. Give it stdio. Exit when it exits.", + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "exports": { + "./watchdog": { + "import": { + "types": "./dist/esm/watchdog.d.ts", + "default": "./dist/esm/watchdog.js" + }, + "require": { + "types": "./dist/commonjs/watchdog.d.ts", + "default": "./dist/commonjs/watchdog.js" + } + }, + "./proxy-signals": { + "import": { + "types": "./dist/esm/proxy-signals.d.ts", + "default": "./dist/esm/proxy-signals.js" + }, + "require": { + "types": "./dist/commonjs/proxy-signals.d.ts", + "default": "./dist/commonjs/proxy-signals.js" + } + }, + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=14" + }, + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --log-level warn", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" + }, + "prettier": { + "experimentalTernaries": true, + "semi": false, + "printWidth": 75, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "tap": { + "typecheck": true + }, + "repository": { + "type": "git", + "url": "git+https://github.com/tapjs/foreground-child.git" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "devDependencies": { + "@types/cross-spawn": "^6.0.2", + "@types/node": "^18.15.11", + "@types/tap": "^15.0.8", + "prettier": "^3.3.2", + "tap": "^21.1.0", + "tshy": "^3.0.2", + "typedoc": "^0.24.2", + "typescript": "^5.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "tshy": { + "exports": { + "./watchdog": "./src/watchdog.ts", + "./proxy-signals": "./src/proxy-signals.ts", + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "type": "module", + "module": "./dist/esm/index.js" +} diff --git a/node_modules/function-bind/.eslintrc b/node_modules/function-bind/.eslintrc new file mode 100644 index 0000000..71a054f --- /dev/null +++ b/node_modules/function-bind/.eslintrc @@ -0,0 +1,21 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "indent": [2, 4], + "no-new-func": [1], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "max-lines-per-function": 0, + "strict": [0] + }, + }, + ], +} diff --git a/node_modules/function-bind/.github/FUNDING.yml b/node_modules/function-bind/.github/FUNDING.yml new file mode 100644 index 0000000..7448219 --- /dev/null +++ b/node_modules/function-bind/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/function-bind +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/function-bind/.github/SECURITY.md b/node_modules/function-bind/.github/SECURITY.md new file mode 100644 index 0000000..82e4285 --- /dev/null +++ b/node_modules/function-bind/.github/SECURITY.md @@ -0,0 +1,3 @@ +# Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. diff --git a/node_modules/function-bind/.nycrc b/node_modules/function-bind/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/function-bind/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/function-bind/CHANGELOG.md b/node_modules/function-bind/CHANGELOG.md new file mode 100644 index 0000000..f9e6cc0 --- /dev/null +++ b/node_modules/function-bind/CHANGELOG.md @@ -0,0 +1,136 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.2](https://github.com/ljharb/function-bind/compare/v1.1.1...v1.1.2) - 2023-10-12 + +### Merged + +- Point to the correct file [`#16`](https://github.com/ljharb/function-bind/pull/16) + +### Commits + +- [Tests] migrate tests to Github Actions [`4f8b57c`](https://github.com/ljharb/function-bind/commit/4f8b57c02f2011fe9ae353d5e74e8745f0988af8) +- [Tests] remove `jscs` [`90eb2ed`](https://github.com/ljharb/function-bind/commit/90eb2edbeefd5b76cd6c3a482ea3454db169b31f) +- [meta] update `.gitignore` [`53fcdc3`](https://github.com/ljharb/function-bind/commit/53fcdc371cd66634d6e9b71c836a50f437e89fed) +- [Tests] up to `node` `v11.10`, `v10.15`, `v9.11`, `v8.15`, `v6.16`, `v4.9`; use `nvm install-latest-npm`; run audit script in tests [`1fe8f6e`](https://github.com/ljharb/function-bind/commit/1fe8f6e9aed0dfa8d8b3cdbd00c7f5ea0cd2b36e) +- [meta] add `auto-changelog` [`1921fcb`](https://github.com/ljharb/function-bind/commit/1921fcb5b416b63ffc4acad051b6aad5722f777d) +- [Robustness] remove runtime dependency on all builtins except `.apply` [`f743e61`](https://github.com/ljharb/function-bind/commit/f743e61aa6bb2360358c04d4884c9db853d118b7) +- Docs: enable badges; update wording [`503cb12`](https://github.com/ljharb/function-bind/commit/503cb12d998b5f91822776c73332c7adcd6355dd) +- [readme] update badges [`290c5db`](https://github.com/ljharb/function-bind/commit/290c5dbbbda7264efaeb886552a374b869a4bb48) +- [Tests] switch to nyc for coverage [`ea360ba`](https://github.com/ljharb/function-bind/commit/ea360ba907fc2601ed18d01a3827fa2d3533cdf8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`cae5e9e`](https://github.com/ljharb/function-bind/commit/cae5e9e07a5578dc6df26c03ee22851ce05b943c) +- [meta] add `funding` field; create FUNDING.yml [`c9f4274`](https://github.com/ljharb/function-bind/commit/c9f4274aa80ea3aae9657a3938fdba41a3b04ca6) +- [Tests] fix eslint errors from #15 [`f69aaa2`](https://github.com/ljharb/function-bind/commit/f69aaa2beb2fdab4415bfb885760a699d0b9c964) +- [actions] fix permissions [`99a0cd9`](https://github.com/ljharb/function-bind/commit/99a0cd9f3b5bac223a0d572f081834cd73314be7) +- [meta] use `npmignore` to autogenerate an npmignore file [`f03b524`](https://github.com/ljharb/function-bind/commit/f03b524ca91f75a109a5d062f029122c86ecd1ae) +- [Dev Deps] update `@ljharb/eslint‑config`, `eslint`, `tape` [`7af9300`](https://github.com/ljharb/function-bind/commit/7af930023ae2ce7645489532821e4fbbcd7a2280) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` [`64a9127`](https://github.com/ljharb/function-bind/commit/64a9127ab0bd331b93d6572eaf6e9971967fc08c) +- [Tests] use `aud` instead of `npm audit` [`e75069c`](https://github.com/ljharb/function-bind/commit/e75069c50010a8fcce2a9ce2324934c35fdb4386) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`d03555c`](https://github.com/ljharb/function-bind/commit/d03555ca59dea3b71ce710045e4303b9e2619e28) +- [meta] add `safe-publish-latest` [`9c8f809`](https://github.com/ljharb/function-bind/commit/9c8f8092aed027d7e80c94f517aa892385b64f09) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`baf6893`](https://github.com/ljharb/function-bind/commit/baf6893e27f5b59abe88bc1995e6f6ed1e527397) +- [meta] create SECURITY.md [`4db1779`](https://github.com/ljharb/function-bind/commit/4db17799f1f28ae294cb95e0081ca2b591c3911b) +- [Tests] add `npm run audit` [`c8b38ec`](https://github.com/ljharb/function-bind/commit/c8b38ec40ed3f85dabdee40ed4148f1748375bc2) +- Revert "Point to the correct file" [`05cdf0f`](https://github.com/ljharb/function-bind/commit/05cdf0fa205c6a3c5ba40bbedd1dfa9874f915c9) + +## [v1.1.1](https://github.com/ljharb/function-bind/compare/v1.1.0...v1.1.1) - 2017-08-28 + +### Commits + +- [Tests] up to `node` `v8`; newer npm breaks on older node; fix scripts [`817f7d2`](https://github.com/ljharb/function-bind/commit/817f7d28470fdbff8ef608d4d565dd4d1430bc5e) +- [Dev Deps] update `eslint`, `jscs`, `tape`, `@ljharb/eslint-config` [`854288b`](https://github.com/ljharb/function-bind/commit/854288b1b6f5c555f89aceb9eff1152510262084) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`83e639f`](https://github.com/ljharb/function-bind/commit/83e639ff74e6cd6921285bccec22c1bcf72311bd) +- Only apps should have lockfiles [`5ed97f5`](https://github.com/ljharb/function-bind/commit/5ed97f51235c17774e0832e122abda0f3229c908) +- Use a SPDX-compliant “license” field. [`5feefea`](https://github.com/ljharb/function-bind/commit/5feefea0dc0193993e83e5df01ded424403a5381) + +## [v1.1.0](https://github.com/ljharb/function-bind/compare/v1.0.2...v1.1.0) - 2016-02-14 + +### Commits + +- Update `eslint`, `tape`; use my personal shared `eslint` config [`9c9062a`](https://github.com/ljharb/function-bind/commit/9c9062abbe9dd70b59ea2c3a3c3a81f29b457097) +- Add `npm run eslint` [`dd96c56`](https://github.com/ljharb/function-bind/commit/dd96c56720034a3c1ffee10b8a59a6f7c53e24ad) +- [New] return the native `bind` when available. [`82186e0`](https://github.com/ljharb/function-bind/commit/82186e03d73e580f95ff167e03f3582bed90ed72) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`a3dd767`](https://github.com/ljharb/function-bind/commit/a3dd76720c795cb7f4586b0544efabf8aa107b8b) +- Update `eslint` [`3dae2f7`](https://github.com/ljharb/function-bind/commit/3dae2f7423de30a2d20313ddb1edc19660142fe9) +- Update `tape`, `covert`, `jscs` [`a181eee`](https://github.com/ljharb/function-bind/commit/a181eee0cfa24eb229c6e843a971f36e060a2f6a) +- [Tests] up to `node` `v5.6`, `v4.3` [`964929a`](https://github.com/ljharb/function-bind/commit/964929a6a4ddb36fb128de2bcc20af5e4f22e1ed) +- Test up to `io.js` `v2.1` [`2be7310`](https://github.com/ljharb/function-bind/commit/2be7310f2f74886a7124ca925be411117d41d5ea) +- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`45f3d68`](https://github.com/ljharb/function-bind/commit/45f3d6865c6ca93726abcef54febe009087af101) +- [Dev Deps] update `tape`, `jscs` [`6e1340d`](https://github.com/ljharb/function-bind/commit/6e1340d94642deaecad3e717825db641af4f8b1f) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`d9bad2b`](https://github.com/ljharb/function-bind/commit/d9bad2b778b1b3a6dd2876087b88b3acf319f8cc) +- Update `eslint` [`935590c`](https://github.com/ljharb/function-bind/commit/935590caa024ab356102e4858e8fc315b2ccc446) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`8c9a1ef`](https://github.com/ljharb/function-bind/commit/8c9a1efd848e5167887aa8501857a0940a480c57) +- Test on `io.js` `v2.2` [`9a3a38c`](https://github.com/ljharb/function-bind/commit/9a3a38c92013aed6e108666e7bd40969b84ac86e) +- Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. [`69afc26`](https://github.com/ljharb/function-bind/commit/69afc2617405b147dd2a8d8ae73ca9e9283f18b4) +- [Dev Deps] Update `tape`, `eslint` [`36c1be0`](https://github.com/ljharb/function-bind/commit/36c1be0ab12b45fe5df6b0fdb01a5d5137fd0115) +- Update `tape`, `jscs` [`98d8303`](https://github.com/ljharb/function-bind/commit/98d8303cd5ca1c6b8f985469f86b0d44d7d45f6e) +- Update `jscs` [`9633a4e`](https://github.com/ljharb/function-bind/commit/9633a4e9fbf82051c240855166e468ba8ba0846f) +- Update `tape`, `jscs` [`c80ef0f`](https://github.com/ljharb/function-bind/commit/c80ef0f46efc9791e76fa50de4414092ac147831) +- Test up to `io.js` `v3.0` [`7e2c853`](https://github.com/ljharb/function-bind/commit/7e2c8537d52ab9cf5a655755561d8917684c0df4) +- Test on `io.js` `v2.4` [`5a199a2`](https://github.com/ljharb/function-bind/commit/5a199a27ba46795ba5eaf0845d07d4b8232895c9) +- Test on `io.js` `v2.3` [`a511b88`](https://github.com/ljharb/function-bind/commit/a511b8896de0bddf3b56862daa416c701f4d0453) +- Fixing a typo from 822b4e1938db02dc9584aa434fd3a45cb20caf43 [`732d6b6`](https://github.com/ljharb/function-bind/commit/732d6b63a9b33b45230e630dbcac7a10855d3266) +- Update `jscs` [`da52a48`](https://github.com/ljharb/function-bind/commit/da52a4886c06d6490f46ae30b15e4163ba08905d) +- Lock covert to v1.0.0. [`d6150fd`](https://github.com/ljharb/function-bind/commit/d6150fda1e6f486718ebdeff823333d9e48e7430) + +## [v1.0.2](https://github.com/ljharb/function-bind/compare/v1.0.1...v1.0.2) - 2014-10-04 + +## [v1.0.1](https://github.com/ljharb/function-bind/compare/v1.0.0...v1.0.1) - 2014-10-03 + +### Merged + +- make CI build faster [`#3`](https://github.com/ljharb/function-bind/pull/3) + +### Commits + +- Using my standard jscs.json [`d8ee94c`](https://github.com/ljharb/function-bind/commit/d8ee94c993eff0a84cf5744fe6a29627f5cffa1a) +- Adding `npm run lint` [`7571ab7`](https://github.com/ljharb/function-bind/commit/7571ab7dfdbd99b25a1dbb2d232622bd6f4f9c10) +- Using consistent indentation [`e91a1b1`](https://github.com/ljharb/function-bind/commit/e91a1b13a61e99ec1e530e299b55508f74218a95) +- Updating jscs [`7e17892`](https://github.com/ljharb/function-bind/commit/7e1789284bc629bc9c1547a61c9b227bbd8c7a65) +- Using consistent quotes [`c50b57f`](https://github.com/ljharb/function-bind/commit/c50b57fcd1c5ec38320979c837006069ebe02b77) +- Adding keywords [`cb94631`](https://github.com/ljharb/function-bind/commit/cb946314eed35f21186a25fb42fc118772f9ee00) +- Directly export a function expression instead of using a declaration, and relying on hoisting. [`5a33c5f`](https://github.com/ljharb/function-bind/commit/5a33c5f45642de180e0d207110bf7d1843ceb87c) +- Naming npm URL and badge in README; use SVG [`2aef8fc`](https://github.com/ljharb/function-bind/commit/2aef8fcb79d54e63a58ae557c4e60949e05d5e16) +- Naming deps URLs in README [`04228d7`](https://github.com/ljharb/function-bind/commit/04228d766670ee45ca24e98345c1f6a7621065b5) +- Naming travis-ci URLs in README; using SVG [`62c810c`](https://github.com/ljharb/function-bind/commit/62c810c2f54ced956cd4d4ab7b793055addfe36e) +- Make sure functions are invoked correctly (also passing coverage tests) [`2b289b4`](https://github.com/ljharb/function-bind/commit/2b289b4dfbf037ffcfa4dc95eb540f6165e9e43a) +- Removing the strict mode pragmas; they make tests fail. [`1aa701d`](https://github.com/ljharb/function-bind/commit/1aa701d199ddc3782476e8f7eef82679be97b845) +- Adding myself as a contributor [`85fd57b`](https://github.com/ljharb/function-bind/commit/85fd57b0860e5a7af42de9a287f3f265fc6d72fc) +- Adding strict mode pragmas [`915b08e`](https://github.com/ljharb/function-bind/commit/915b08e084c86a722eafe7245e21db74aa21ca4c) +- Adding devDeps URLs to README [`4ccc731`](https://github.com/ljharb/function-bind/commit/4ccc73112c1769859e4ca3076caf4086b3cba2cd) +- Fixing the description. [`a7a472c`](https://github.com/ljharb/function-bind/commit/a7a472cf649af515c635cf560fc478fbe48999c8) +- Using a function expression instead of a function declaration. [`b5d3e4e`](https://github.com/ljharb/function-bind/commit/b5d3e4ea6aaffc63888953eeb1fbc7ff45f1fa14) +- Updating tape [`f086be6`](https://github.com/ljharb/function-bind/commit/f086be6029fb56dde61a258c1340600fa174d1e0) +- Updating jscs [`5f9bdb3`](https://github.com/ljharb/function-bind/commit/5f9bdb375ab13ba48f30852aab94029520c54d71) +- Updating jscs [`9b409ba`](https://github.com/ljharb/function-bind/commit/9b409ba6118e23395a4e5d83ef39152aab9d3bfc) +- Run coverage as part of tests. [`8e1b6d4`](https://github.com/ljharb/function-bind/commit/8e1b6d459f047d1bd4fee814e01247c984c80bd0) +- Run linter as part of tests [`c1ca83f`](https://github.com/ljharb/function-bind/commit/c1ca83f832df94587d09e621beba682fabfaa987) +- Updating covert [`701e837`](https://github.com/ljharb/function-bind/commit/701e83774b57b4d3ef631e1948143f43a72f4bb9) + +## [v1.0.0](https://github.com/ljharb/function-bind/compare/v0.2.0...v1.0.0) - 2014-08-09 + +### Commits + +- Make sure old and unstable nodes don't fail Travis [`27adca3`](https://github.com/ljharb/function-bind/commit/27adca34a4ab6ad67b6dfde43942a1b103ce4d75) +- Fixing an issue when the bound function is called as a constructor in ES3. [`e20122d`](https://github.com/ljharb/function-bind/commit/e20122d267d92ce553859b280cbbea5d27c07731) +- Adding `npm run coverage` [`a2e29c4`](https://github.com/ljharb/function-bind/commit/a2e29c4ecaef9e2f6cd1603e868c139073375502) +- Updating tape [`b741168`](https://github.com/ljharb/function-bind/commit/b741168b12b235b1717ff696087645526b69213c) +- Upgrading tape [`63631a0`](https://github.com/ljharb/function-bind/commit/63631a04c7fbe97cc2fa61829cc27246d6986f74) +- Updating tape [`363cb46`](https://github.com/ljharb/function-bind/commit/363cb46dafb23cb3e347729a22f9448051d78464) + +## v0.2.0 - 2014-03-23 + +### Commits + +- Updating test coverage to match es5-shim. [`aa94d44`](https://github.com/ljharb/function-bind/commit/aa94d44b8f9d7f69f10e060db7709aa7a694e5d4) +- initial [`942ee07`](https://github.com/ljharb/function-bind/commit/942ee07e94e542d91798137bc4b80b926137e066) +- Setting the bound function's length properly. [`079f46a`](https://github.com/ljharb/function-bind/commit/079f46a2d3515b7c0b308c2c13fceb641f97ca25) +- Ensuring that some older browsers will throw when given a regex. [`36ac55b`](https://github.com/ljharb/function-bind/commit/36ac55b87f460d4330253c92870aa26fbfe8227f) +- Removing npm scripts that don't have dependencies [`9d2be60`](https://github.com/ljharb/function-bind/commit/9d2be600002cb8bc8606f8f3585ad3e05868c750) +- Updating tape [`297a4ac`](https://github.com/ljharb/function-bind/commit/297a4acc5464db381940aafb194d1c88f4e678f3) +- Skipping length tests for now. [`d9891ea`](https://github.com/ljharb/function-bind/commit/d9891ea4d2aaffa69f408339cdd61ff740f70565) +- don't take my tea [`dccd930`](https://github.com/ljharb/function-bind/commit/dccd930bfd60ea10cb178d28c97550c3bc8c1e07) diff --git a/node_modules/function-bind/LICENSE b/node_modules/function-bind/LICENSE new file mode 100644 index 0000000..62d6d23 --- /dev/null +++ b/node_modules/function-bind/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2013 Raynos. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/node_modules/function-bind/README.md b/node_modules/function-bind/README.md new file mode 100644 index 0000000..814c20b --- /dev/null +++ b/node_modules/function-bind/README.md @@ -0,0 +1,46 @@ +# function-bind [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] + +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Implementation of function.prototype.bind + +Old versions of phantomjs, Internet Explorer < 9, and node < 0.6 don't support `Function.prototype.bind`. + +## Example + +```js +Function.prototype.bind = require("function-bind") +``` + +## Installation + +`npm install function-bind` + +## Contributors + + - Raynos + +## MIT Licenced + +[package-url]: https://npmjs.org/package/function-bind +[npm-version-svg]: https://versionbadg.es/Raynos/function-bind.svg +[deps-svg]: https://david-dm.org/Raynos/function-bind.svg +[deps-url]: https://david-dm.org/Raynos/function-bind +[dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg +[dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/function-bind.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/function-bind.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/function-bind.svg +[downloads-url]: https://npm-stat.com/charts.html?package=function-bind +[codecov-image]: https://codecov.io/gh/Raynos/function-bind/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/Raynos/function-bind/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/Raynos/function-bind +[actions-url]: https://github.com/Raynos/function-bind/actions diff --git a/node_modules/function-bind/implementation.js b/node_modules/function-bind/implementation.js new file mode 100644 index 0000000..fd4384c --- /dev/null +++ b/node_modules/function-bind/implementation.js @@ -0,0 +1,84 @@ +'use strict'; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; + +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + + }; + + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; diff --git a/node_modules/function-bind/index.js b/node_modules/function-bind/index.js new file mode 100644 index 0000000..3bb6b96 --- /dev/null +++ b/node_modules/function-bind/index.js @@ -0,0 +1,5 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = Function.prototype.bind || implementation; diff --git a/node_modules/function-bind/package.json b/node_modules/function-bind/package.json new file mode 100644 index 0000000..6185963 --- /dev/null +++ b/node_modules/function-bind/package.json @@ -0,0 +1,87 @@ +{ + "name": "function-bind", + "version": "1.1.2", + "description": "Implementation of Function.prototype.bind", + "keywords": [ + "function", + "bind", + "shim", + "es5" + ], + "author": "Raynos ", + "repository": { + "type": "git", + "url": "https://github.com/Raynos/function-bind.git" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "main": "index", + "homepage": "https://github.com/Raynos/function-bind", + "contributors": [ + { + "name": "Raynos" + }, + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "bugs": { + "url": "https://github.com/Raynos/function-bind/issues", + "email": "raynos2@gmail.com" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.1" + }, + "license": "MIT", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepack": "npmignore --auto --commentLines=autogenerated", + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "nyc tape 'test/**/*.js'", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "ie/8..latest", + "firefox/16..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/function-bind/test/.eslintrc b/node_modules/function-bind/test/.eslintrc new file mode 100644 index 0000000..8a56d5b --- /dev/null +++ b/node_modules/function-bind/test/.eslintrc @@ -0,0 +1,9 @@ +{ + "rules": { + "array-bracket-newline": 0, + "array-element-newline": 0, + "max-statements-per-line": [2, { "max": 2 }], + "no-invalid-this": 0, + "no-magic-numbers": 0, + } +} diff --git a/node_modules/function-bind/test/index.js b/node_modules/function-bind/test/index.js new file mode 100644 index 0000000..2edecce --- /dev/null +++ b/node_modules/function-bind/test/index.js @@ -0,0 +1,252 @@ +// jscs:disable requireUseStrict + +var test = require('tape'); + +var functionBind = require('../implementation'); +var getCurrentContext = function () { return this; }; + +test('functionBind is a function', function (t) { + t.equal(typeof functionBind, 'function'); + t.end(); +}); + +test('non-functions', function (t) { + var nonFunctions = [true, false, [], {}, 42, 'foo', NaN, /a/g]; + t.plan(nonFunctions.length); + for (var i = 0; i < nonFunctions.length; ++i) { + try { functionBind.call(nonFunctions[i]); } catch (ex) { + t.ok(ex instanceof TypeError, 'throws when given ' + String(nonFunctions[i])); + } + } + t.end(); +}); + +test('without a context', function (t) { + t.test('binds properly', function (st) { + var args, context; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }) + }; + namespace.func(1, 2, 3); + st.deepEqual(args, [1, 2, 3]); + st.equal(context, getCurrentContext.call()); + st.end(); + }); + + t.test('binds properly, and still supplies bound arguments', function (st) { + var args, context; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, undefined, 1, 2, 3) + }; + namespace.func(4, 5, 6); + st.deepEqual(args, [1, 2, 3, 4, 5, 6]); + st.equal(context, getCurrentContext.call()); + st.end(); + }); + + t.test('returns properly', function (st) { + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, null) + }; + var context = namespace.func(1, 2, 3); + st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); + st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); + st.end(); + }); + + t.test('returns properly with bound arguments', function (st) { + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, null, 1, 2, 3) + }; + var context = namespace.func(4, 5, 6); + st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); + st.end(); + }); + + t.test('called as a constructor', function (st) { + var thunkify = function (value) { + return function () { return value; }; + }; + st.test('returns object value', function (sst) { + var expectedReturnValue = [1, 2, 3]; + var Constructor = functionBind.call(thunkify(expectedReturnValue), null); + var result = new Constructor(); + sst.equal(result, expectedReturnValue); + sst.end(); + }); + + st.test('does not return primitive value', function (sst) { + var Constructor = functionBind.call(thunkify(42), null); + var result = new Constructor(); + sst.notEqual(result, 42); + sst.end(); + }); + + st.test('object from bound constructor is instance of original and bound constructor', function (sst) { + var A = function (x) { + this.name = x || 'A'; + }; + var B = functionBind.call(A, null, 'B'); + + var result = new B(); + sst.ok(result instanceof B, 'result is instance of bound constructor'); + sst.ok(result instanceof A, 'result is instance of original constructor'); + sst.end(); + }); + + st.end(); + }); + + t.end(); +}); + +test('with a context', function (t) { + t.test('with no bound arguments', function (st) { + var args, context; + var boundContext = {}; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, boundContext) + }; + namespace.func(1, 2, 3); + st.equal(context, boundContext, 'binds a context properly'); + st.deepEqual(args, [1, 2, 3], 'supplies passed arguments'); + st.end(); + }); + + t.test('with bound arguments', function (st) { + var args, context; + var boundContext = {}; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, boundContext, 1, 2, 3) + }; + namespace.func(4, 5, 6); + st.equal(context, boundContext, 'binds a context properly'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'supplies bound and passed arguments'); + st.end(); + }); + + t.test('returns properly', function (st) { + var boundContext = {}; + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, boundContext) + }; + var context = namespace.func(1, 2, 3); + st.equal(context, boundContext, 'returned context is bound context'); + st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); + st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); + st.end(); + }); + + t.test('returns properly with bound arguments', function (st) { + var boundContext = {}; + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, boundContext, 1, 2, 3) + }; + var context = namespace.func(4, 5, 6); + st.equal(context, boundContext, 'returned context is bound context'); + st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); + st.end(); + }); + + t.test('passes the correct arguments when called as a constructor', function (st) { + var expected = { name: 'Correct' }; + var namespace = { + Func: functionBind.call(function (arg) { + return arg; + }, { name: 'Incorrect' }) + }; + var returned = new namespace.Func(expected); + st.equal(returned, expected, 'returns the right arg when called as a constructor'); + st.end(); + }); + + t.test('has the new instance\'s context when called as a constructor', function (st) { + var actualContext; + var expectedContext = { foo: 'bar' }; + var namespace = { + Func: functionBind.call(function () { + actualContext = this; + }, expectedContext) + }; + var result = new namespace.Func(); + st.equal(result instanceof namespace.Func, true); + st.notEqual(actualContext, expectedContext); + st.end(); + }); + + t.end(); +}); + +test('bound function length', function (t) { + t.test('sets a correct length without thisArg', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }); + st.equal(subject.length, 3); + st.equal(subject(1, 2, 3), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}); + st.equal(subject.length, 3); + st.equal(subject(1, 2, 3), 6); + st.end(); + }); + + t.test('sets a correct length without thisArg and first argument', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1); + st.equal(subject.length, 2); + st.equal(subject(2, 3), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg and first argument', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1); + st.equal(subject.length, 2); + st.equal(subject(2, 3), 6); + st.end(); + }); + + t.test('sets a correct length without thisArg and too many arguments', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1, 2, 3, 4); + st.equal(subject.length, 0); + st.equal(subject(), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg and too many arguments', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1, 2, 3, 4); + st.equal(subject.length, 0); + st.equal(subject(), 6); + st.end(); + }); +}); diff --git a/node_modules/glob-parent/LICENSE b/node_modules/glob-parent/LICENSE new file mode 100644 index 0000000..d701b08 --- /dev/null +++ b/node_modules/glob-parent/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2015, 2019 Elan Shanker, 2021 Blaine Bublitz , Eric Schoffstall and other contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/glob-parent/README.md b/node_modules/glob-parent/README.md new file mode 100644 index 0000000..6ae18a1 --- /dev/null +++ b/node_modules/glob-parent/README.md @@ -0,0 +1,134 @@ +

+ + + +

+ +# glob-parent + +[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][ci-image]][ci-url] [![Coveralls Status][coveralls-image]][coveralls-url] + +Extract the non-magic parent path from a glob string. + +## Usage + +```js +var globParent = require('glob-parent'); + +globParent('path/to/*.js'); // 'path/to' +globParent('/root/path/to/*.js'); // '/root/path/to' +globParent('/*.js'); // '/' +globParent('*.js'); // '.' +globParent('**/*.js'); // '.' +globParent('path/{to,from}'); // 'path' +globParent('path/!(to|from)'); // 'path' +globParent('path/?(to|from)'); // 'path' +globParent('path/+(to|from)'); // 'path' +globParent('path/*(to|from)'); // 'path' +globParent('path/@(to|from)'); // 'path' +globParent('path/**/*'); // 'path' + +// if provided a non-glob path, returns the nearest dir +globParent('path/foo/bar.js'); // 'path/foo' +globParent('path/foo/'); // 'path/foo' +globParent('path/foo'); // 'path' (see issue #3 for details) +``` + +## API + +### `globParent(maybeGlobString, [options])` + +Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below. + +#### options + +```js +{ + // Disables the automatic conversion of slashes for Windows + flipBackslashes: true; +} +``` + +## Escaping + +The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: + +- `?` (question mark) unless used as a path segment alone +- `*` (asterisk) +- `|` (pipe) +- `(` (opening parenthesis) +- `)` (closing parenthesis) +- `{` (opening curly brace) +- `}` (closing curly brace) +- `[` (opening bracket) +- `]` (closing bracket) + +**Example** + +```js +globParent('foo/[bar]/'); // 'foo' +globParent('foo/\\[bar]/'); // 'foo/[bar]' +``` + +## Limitations + +### Braces & Brackets + +This library attempts a quick and imperfect method of determining which path +parts have glob magic without fully parsing/lexing the pattern. There are some +advanced use cases that can trip it up, such as nested braces where the outer +pair is escaped and the inner one contains a path separator. If you find +yourself in the unlikely circumstance of being affected by this or need to +ensure higher-fidelity glob handling in your library, it is recommended that you +pre-process your input with [expand-braces] and/or [expand-brackets]. + +### Windows + +Backslashes are not valid path separators for globs. If a path with backslashes +is provided anyway, for simple cases, glob-parent will replace the path +separator for you and return the non-glob parent path (now with +forward-slashes, which are still valid as Windows path separators). + +This cannot be used in conjunction with escape characters. + +```js +// BAD +globParent('C:\\Program Files \\(x86\\)\\*.ext'); // 'C:/Program Files /(x86/)' + +// GOOD +globParent('C:/Program Files\\(x86\\)/*.ext'); // 'C:/Program Files (x86)' +``` + +If you are using escape characters for a pattern without path parts (i.e. +relative to `cwd`), prefix with `./` to avoid confusing glob-parent. + +```js +// BAD +globParent('foo \\[bar]'); // 'foo ' +globParent('foo \\[bar]*'); // 'foo ' + +// GOOD +globParent('./foo \\[bar]'); // 'foo [bar]' +globParent('./foo \\[bar]*'); // '.' +``` + +## License + +ISC + + +[downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg?style=flat-square +[npm-url]: https://www.npmjs.com/package/glob-parent +[npm-image]: https://img.shields.io/npm/v/glob-parent.svg?style=flat-square + +[ci-url]: https://github.com/gulpjs/glob-parent/actions?query=workflow:dev +[ci-image]: https://img.shields.io/github/workflow/status/gulpjs/glob-parent/dev?style=flat-square + +[coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent +[coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg?style=flat-square + + + +[expand-braces]: https://github.com/jonschlinkert/expand-braces +[expand-brackets]: https://github.com/jonschlinkert/expand-brackets + diff --git a/node_modules/glob-parent/index.js b/node_modules/glob-parent/index.js new file mode 100644 index 0000000..09dde64 --- /dev/null +++ b/node_modules/glob-parent/index.js @@ -0,0 +1,75 @@ +'use strict'; + +var isGlob = require('is-glob'); +var pathPosixDirname = require('path').posix.dirname; +var isWin32 = require('os').platform() === 'win32'; + +var slash = '/'; +var backslash = /\\/g; +var escaped = /\\([!*?|[\](){}])/g; + +/** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + */ +module.exports = function globParent(str, opts) { + var options = Object.assign({ flipBackslashes: true }, opts); + + // flip windows path separators + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { + str = str.replace(backslash, slash); + } + + // special case for strings ending in enclosure containing path separator + if (isEnclosure(str)) { + str += slash; + } + + // preserves full path in case of trailing path separator + str += 'a'; + + // remove path parts that are globby + do { + str = pathPosixDirname(str); + } while (isGlobby(str)); + + // remove escape chars and return result + return str.replace(escaped, '$1'); +}; + +function isEnclosure(str) { + var lastChar = str.slice(-1); + + var enclosureStart; + switch (lastChar) { + case '}': + enclosureStart = '{'; + break; + case ']': + enclosureStart = '['; + break; + default: + return false; + } + + var foundIndex = str.indexOf(enclosureStart); + if (foundIndex < 0) { + return false; + } + + return str.slice(foundIndex + 1, -1).includes(slash); +} + +function isGlobby(str) { + if (/\([^()]+$/.test(str)) { + return true; + } + if (str[0] === '{' || str[0] === '[') { + return true; + } + if (/[^\\][{[]/.test(str)) { + return true; + } + return isGlob(str); +} diff --git a/node_modules/glob-parent/package.json b/node_modules/glob-parent/package.json new file mode 100644 index 0000000..baeab42 --- /dev/null +++ b/node_modules/glob-parent/package.json @@ -0,0 +1,54 @@ +{ + "name": "glob-parent", + "version": "6.0.2", + "description": "Extract the non-magic parent path from a glob string.", + "author": "Gulp Team (https://gulpjs.com/)", + "contributors": [ + "Elan Shanker (https://github.com/es128)", + "Blaine Bublitz " + ], + "repository": "gulpjs/glob-parent", + "license": "ISC", + "engines": { + "node": ">=10.13.0" + }, + "main": "index.js", + "files": [ + "LICENSE", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "pretest": "npm run lint", + "test": "nyc mocha --async-only" + }, + "dependencies": { + "is-glob": "^4.0.3" + }, + "devDependencies": { + "eslint": "^7.0.0", + "eslint-config-gulp": "^5.0.0", + "expect": "^26.0.1", + "mocha": "^7.1.2", + "nyc": "^15.0.1" + }, + "nyc": { + "reporter": [ + "lcov", + "text-summary" + ] + }, + "prettier": { + "singleQuote": true + }, + "keywords": [ + "glob", + "parent", + "strip", + "path", + "dirname", + "directory", + "base", + "wildcard" + ] +} diff --git a/node_modules/glob/LICENSE b/node_modules/glob/LICENSE new file mode 100644 index 0000000..ec7df93 --- /dev/null +++ b/node_modules/glob/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2009-2023 Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/glob/README.md b/node_modules/glob/README.md new file mode 100644 index 0000000..023cd77 --- /dev/null +++ b/node_modules/glob/README.md @@ -0,0 +1,1265 @@ +# Glob + +Match files using the patterns the shell uses. + +The most correct and second fastest glob implementation in +JavaScript. (See **Comparison to Other JavaScript Glob +Implementations** at the bottom of this readme.) + +![a fun cartoon logo made of glob characters](https://github.com/isaacs/node-glob/raw/main/logo/glob.png) + +## Usage + +Install with npm + +``` +npm i glob +``` + +**Note** the npm package name is _not_ `node-glob` that's a +different thing that was abandoned years ago. Just `glob`. + +```js +// load using import +import { glob, globSync, globStream, globStreamSync, Glob } from 'glob' +// or using commonjs, that's fine, too +const { + glob, + globSync, + globStream, + globStreamSync, + Glob, +} = require('glob') + +// the main glob() and globSync() resolve/return array of filenames + +// all js files, but don't look in node_modules +const jsfiles = await glob('**/*.js', { ignore: 'node_modules/**' }) + +// pass in a signal to cancel the glob walk +const stopAfter100ms = await glob('**/*.css', { + signal: AbortSignal.timeout(100), +}) + +// multiple patterns supported as well +const images = await glob(['css/*.{png,jpeg}', 'public/*.{png,jpeg}']) + +// but of course you can do that with the glob pattern also +// the sync function is the same, just returns a string[] instead +// of Promise +const imagesAlt = globSync('{css,public}/*.{png,jpeg}') + +// you can also stream them, this is a Minipass stream +const filesStream = globStream(['**/*.dat', 'logs/**/*.log']) + +// construct a Glob object if you wanna do it that way, which +// allows for much faster walks if you have to look in the same +// folder multiple times. +const g = new Glob('**/foo', {}) +// glob objects are async iterators, can also do globIterate() or +// g.iterate(), same deal +for await (const file of g) { + console.log('found a foo file:', file) +} +// pass a glob as the glob options to reuse its settings and caches +const g2 = new Glob('**/bar', g) +// sync iteration works as well +for (const file of g2) { + console.log('found a bar file:', file) +} + +// you can also pass withFileTypes: true to get Path objects +// these are like a Dirent, but with some more added powers +// check out http://npm.im/path-scurry for more info on their API +const g3 = new Glob('**/baz/**', { withFileTypes: true }) +g3.stream().on('data', path => { + console.log( + 'got a path object', + path.fullpath(), + path.isDirectory(), + path.readdirSync().map(e => e.name), + ) +}) + +// if you use stat:true and withFileTypes, you can sort results +// by things like modified time, filter by permission mode, etc. +// All Stats fields will be available in that case. Slightly +// slower, though. +// For example: +const results = await glob('**', { stat: true, withFileTypes: true }) + +const timeSortedFiles = results + .sort((a, b) => a.mtimeMs - b.mtimeMs) + .map(path => path.fullpath()) + +const groupReadableFiles = results + .filter(path => path.mode & 0o040) + .map(path => path.fullpath()) + +// custom ignores can be done like this, for example by saying +// you'll ignore all markdown files, and all folders named 'docs' +const customIgnoreResults = await glob('**', { + ignore: { + ignored: p => /\.md$/.test(p.name), + childrenIgnored: p => p.isNamed('docs'), + }, +}) + +// another fun use case, only return files with the same name as +// their parent folder, plus either `.ts` or `.js` +const folderNamedModules = await glob('**/*.{ts,js}', { + ignore: { + ignored: p => { + const pp = p.parent + return !(p.isNamed(pp.name + '.ts') || p.isNamed(pp.name + '.js')) + }, + }, +}) + +// find all files edited in the last hour, to do this, we ignore +// all of them that are more than an hour old +const newFiles = await glob('**', { + // need stat so we have mtime + stat: true, + // only want the files, not the dirs + nodir: true, + ignore: { + ignored: p => { + return new Date() - p.mtime > 60 * 60 * 1000 + }, + // could add similar childrenIgnored here as well, but + // directory mtime is inconsistent across platforms, so + // probably better not to, unless you know the system + // tracks this reliably. + }, +}) +``` + +**Note** Glob patterns should always use `/` as a path separator, +even on Windows systems, as `\` is used to escape glob +characters. If you wish to use `\` as a path separator _instead +of_ using it as an escape character on Windows platforms, you may +set `windowsPathsNoEscape:true` in the options. In this mode, +special glob characters cannot be escaped, making it impossible +to match a literal `*` `?` and so on in filenames. + +## Command Line Interface + +``` +$ glob -h + +Usage: + glob [options] [ [ ...]] + +Expand the positional glob expression arguments into any matching file system +paths found. + + -c --cmd= + Run the command provided, passing the glob expression + matches as arguments. + + -A --all By default, the glob cli command will not expand any + arguments that are an exact match to a file on disk. + + This prevents double-expanding, in case the shell + expands an argument whose filename is a glob + expression. + + For example, if 'app/*.ts' would match 'app/[id].ts', + then on Windows powershell or cmd.exe, 'glob app/*.ts' + will expand to 'app/[id].ts', as expected. However, in + posix shells such as bash or zsh, the shell will first + expand 'app/*.ts' to a list of filenames. Then glob + will look for a file matching 'app/[id].ts' (ie, + 'app/i.ts' or 'app/d.ts'), which is unexpected. + + Setting '--all' prevents this behavior, causing glob to + treat ALL patterns as glob expressions to be expanded, + even if they are an exact match to a file on disk. + + When setting this option, be sure to enquote arguments + so that the shell will not expand them prior to passing + them to the glob command process. + + -a --absolute Expand to absolute paths + -d --dot-relative Prepend './' on relative matches + -m --mark Append a / on any directories matched + -x --posix Always resolve to posix style paths, using '/' as the + directory separator, even on Windows. Drive letter + absolute matches on Windows will be expanded to their + full resolved UNC maths, eg instead of 'C:\foo\bar', it + will expand to '//?/C:/foo/bar'. + + -f --follow Follow symlinked directories when expanding '**' + -R --realpath Call 'fs.realpath' on all of the results. In the case + of an entry that cannot be resolved, the entry is + omitted. This incurs a slight performance penalty, of + course, because of the added system calls. + + -s --stat Call 'fs.lstat' on all entries, whether required or not + to determine if it's a valid match. + + -b --match-base Perform a basename-only match if the pattern does not + contain any slash characters. That is, '*.js' would be + treated as equivalent to '**/*.js', matching js files + in all directories. + + --dot Allow patterns to match files/directories that start + with '.', even if the pattern does not start with '.' + + --nobrace Do not expand {...} patterns + --nocase Perform a case-insensitive match. This defaults to + 'true' on macOS and Windows platforms, and false on all + others. + + Note: 'nocase' should only be explicitly set when it is + known that the filesystem's case sensitivity differs + from the platform default. If set 'true' on + case-insensitive file systems, then the walk may return + more or less results than expected. + + --nodir Do not match directories, only files. + + Note: to *only* match directories, append a '/' at the + end of the pattern. + + --noext Do not expand extglob patterns, such as '+(a|b)' + --noglobstar Do not expand '**' against multiple path portions. Ie, + treat it as a normal '*' instead. + + --windows-path-no-escape + Use '\' as a path separator *only*, and *never* as an + escape character. If set, all '\' characters are + replaced with '/' in the pattern. + + -D --max-depth= Maximum depth to traverse from the current working + directory + + -C --cwd= Current working directory to execute/match in + -r --root= A string path resolved against the 'cwd', which is used + as the starting point for absolute patterns that start + with '/' (but not drive letters or UNC paths on + Windows). + + Note that this *doesn't* necessarily limit the walk to + the 'root' directory, and doesn't affect the cwd + starting point for non-absolute patterns. A pattern + containing '..' will still be able to traverse out of + the root directory, if it is not an actual root + directory on the filesystem, and any non-absolute + patterns will still be matched in the 'cwd'. + + To start absolute and non-absolute patterns in the same + path, you can use '--root=' to set it to the empty + string. However, be aware that on Windows systems, a + pattern like 'x:/*' or '//host/share/*' will *always* + start in the 'x:/' or '//host/share/' directory, + regardless of the --root setting. + + --platform= Defaults to the value of 'process.platform' if + available, or 'linux' if not. Setting --platform=win32 + on non-Windows systems may cause strange behavior! + + -i --ignore= + Glob patterns to ignore Can be set multiple times + -v --debug Output a huge amount of noisy debug information about + patterns as they are parsed and used to match files. + + -h --help Show this usage information +``` + +## `glob(pattern: string | string[], options?: GlobOptions) => Promise` + +Perform an asynchronous glob search for the pattern(s) specified. +Returns +[Path](https://isaacs.github.io/path-scurry/classes/PathBase) +objects if the `withFileTypes` option is set to `true`. See below +for full options field desciptions. + +## `globSync(pattern: string | string[], options?: GlobOptions) => string[] | Path[]` + +Synchronous form of `glob()`. + +Alias: `glob.sync()` + +## `globIterate(pattern: string | string[], options?: GlobOptions) => AsyncGenerator` + +Return an async iterator for walking glob pattern matches. + +Alias: `glob.iterate()` + +## `globIterateSync(pattern: string | string[], options?: GlobOptions) => Generator` + +Return a sync iterator for walking glob pattern matches. + +Alias: `glob.iterate.sync()`, `glob.sync.iterate()` + +## `globStream(pattern: string | string[], options?: GlobOptions) => Minipass` + +Return a stream that emits all the strings or `Path` objects and +then emits `end` when completed. + +Alias: `glob.stream()` + +## `globStreamSync(pattern: string | string[], options?: GlobOptions) => Minipass` + +Syncronous form of `globStream()`. Will read all the matches as +fast as you consume them, even all in a single tick if you +consume them immediately, but will still respond to backpressure +if they're not consumed immediately. + +Alias: `glob.stream.sync()`, `glob.sync.stream()` + +## `hasMagic(pattern: string | string[], options?: GlobOptions) => boolean` + +Returns `true` if the provided pattern contains any "magic" glob +characters, given the options provided. + +Brace expansion is not considered "magic" unless the +`magicalBraces` option is set, as brace expansion just turns one +string into an array of strings. So a pattern like `'x{a,b}y'` +would return `false`, because `'xay'` and `'xby'` both do not +contain any magic glob characters, and it's treated the same as +if you had called it on `['xay', 'xby']`. When +`magicalBraces:true` is in the options, brace expansion _is_ +treated as a pattern having magic. + +## `escape(pattern: string, options?: GlobOptions) => string` + +Escape all magic characters in a glob pattern, so that it will +only ever match literal strings + +If the `windowsPathsNoEscape` option is used, then characters are +escaped by wrapping in `[]`, because a magic character wrapped in +a character class can only be satisfied by that exact character. + +Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot +be escaped or unescaped. + +## `unescape(pattern: string, options?: GlobOptions) => string` + +Un-escape a glob string that may contain some escaped characters. + +If the `windowsPathsNoEscape` option is used, then square-brace +escapes are removed, but not backslash escapes. For example, it +will turn the string `'[*]'` into `*`, but it will not turn +`'\\*'` into `'*'`, because `\` is a path separator in +`windowsPathsNoEscape` mode. + +When `windowsPathsNoEscape` is not set, then both brace escapes +and backslash escapes are removed. + +Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot +be escaped or unescaped. + +## Class `Glob` + +An object that can perform glob pattern traversals. + +### `const g = new Glob(pattern: string | string[], options: GlobOptions)` + +Options object is required. + +See full options descriptions below. + +Note that a previous `Glob` object can be passed as the +`GlobOptions` to another `Glob` instantiation to re-use settings +and caches with a new pattern. + +Traversal functions can be called multiple times to run the walk +again. + +### `g.stream()` + +Stream results asynchronously, + +### `g.streamSync()` + +Stream results synchronously. + +### `g.iterate()` + +Default async iteration function. Returns an AsyncGenerator that +iterates over the results. + +### `g.iterateSync()` + +Default sync iteration function. Returns a Generator that +iterates over the results. + +### `g.walk()` + +Returns a Promise that resolves to the results array. + +### `g.walkSync()` + +Returns a results array. + +### Properties + +All options are stored as properties on the `Glob` object. + +- `opts` The options provided to the constructor. +- `patterns` An array of parsed immutable `Pattern` objects. + +## Options + +Exported as `GlobOptions` TypeScript interface. A `GlobOptions` +object may be provided to any of the exported methods, and must +be provided to the `Glob` constructor. + +All options are optional, boolean, and false by default, unless +otherwise noted. + +All resolved options are added to the Glob object as properties. + +If you are running many `glob` operations, you can pass a Glob +object as the `options` argument to a subsequent operation to +share the previously loaded cache. + +- `cwd` String path or `file://` string or URL object. The + current working directory in which to search. Defaults to + `process.cwd()`. See also: "Windows, CWDs, Drive Letters, and + UNC Paths", below. + + This option may be either a string path or a `file://` URL + object or string. + +- `root` A string path resolved against the `cwd` option, which + is used as the starting point for absolute patterns that start + with `/`, (but not drive letters or UNC paths on Windows). + + Note that this _doesn't_ necessarily limit the walk to the + `root` directory, and doesn't affect the cwd starting point for + non-absolute patterns. A pattern containing `..` will still be + able to traverse out of the root directory, if it is not an + actual root directory on the filesystem, and any non-absolute + patterns will be matched in the `cwd`. For example, the + pattern `/../*` with `{root:'/some/path'}` will return all + files in `/some`, not all files in `/some/path`. The pattern + `*` with `{root:'/some/path'}` will return all the entries in + the cwd, not the entries in `/some/path`. + + To start absolute and non-absolute patterns in the same + path, you can use `{root:''}`. However, be aware that on + Windows systems, a pattern like `x:/*` or `//host/share/*` will + _always_ start in the `x:/` or `//host/share` directory, + regardless of the `root` setting. + +- `windowsPathsNoEscape` Use `\\` as a path separator _only_, and + _never_ as an escape character. If set, all `\\` characters are + replaced with `/` in the pattern. + + Note that this makes it **impossible** to match against paths + containing literal glob pattern characters, but allows matching + with patterns constructed using `path.join()` and + `path.resolve()` on Windows platforms, mimicking the (buggy!) + behavior of Glob v7 and before on Windows. Please use with + caution, and be mindful of [the caveat below about Windows + paths](#windows). (For legacy reasons, this is also set if + `allowWindowsEscape` is set to the exact value `false`.) + +- `dot` Include `.dot` files in normal matches and `globstar` + matches. Note that an explicit dot in a portion of the pattern + will always match dot files. + +- `magicalBraces` Treat brace expansion like `{a,b}` as a "magic" + pattern. Has no effect if {@link nobrace} is set. + + Only has effect on the {@link hasMagic} function, no effect on + glob pattern matching itself. + +- `dotRelative` Prepend all relative path strings with `./` (or + `.\` on Windows). + + Without this option, returned relative paths are "bare", so + instead of returning `'./foo/bar'`, they are returned as + `'foo/bar'`. + + Relative patterns starting with `'../'` are not prepended with + `./`, even if this option is set. + +- `mark` Add a `/` character to directory matches. Note that this + requires additional stat calls. + +- `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. + +- `noglobstar` Do not match `**` against multiple filenames. (Ie, + treat it as a normal `*` instead.) + +- `noext` Do not match "extglob" patterns such as `+(a|b)`. + +- `nocase` Perform a case-insensitive match. This defaults to + `true` on macOS and Windows systems, and `false` on all others. + + **Note** `nocase` should only be explicitly set when it is + known that the filesystem's case sensitivity differs from the + platform default. If set `true` on case-sensitive file + systems, or `false` on case-insensitive file systems, then the + walk may return more or less results than expected. + +- `maxDepth` Specify a number to limit the depth of the directory + traversal to this many levels below the `cwd`. + +- `matchBase` Perform a basename-only match if the pattern does + not contain any slash characters. That is, `*.js` would be + treated as equivalent to `**/*.js`, matching all js files in + all directories. + +- `nodir` Do not match directories, only files. (Note: to match + _only_ directories, put a `/` at the end of the pattern.) + + Note: when `follow` and `nodir` are both set, then symbolic + links to directories are also omitted. + +- `stat` Call `lstat()` on all entries, whether required or not + to determine whether it's a valid match. When used with + `withFileTypes`, this means that matches will include data such + as modified time, permissions, and so on. Note that this will + incur a performance cost due to the added system calls. + +- `ignore` string or string[], or an object with `ignore` and + `ignoreChildren` methods. + + If a string or string[] is provided, then this is treated as a + glob pattern or array of glob patterns to exclude from matches. + To ignore all children within a directory, as well as the entry + itself, append `'/**'` to the ignore pattern. + + **Note** `ignore` patterns are _always_ in `dot:true` mode, + regardless of any other settings. + + If an object is provided that has `ignored(path)` and/or + `childrenIgnored(path)` methods, then these methods will be + called to determine whether any Path is a match or if its + children should be traversed, respectively. + +- `follow` Follow symlinked directories when expanding `**` + patterns. This can result in a lot of duplicate references in + the presence of cyclic links, and make performance quite bad. + + By default, a `**` in a pattern will follow 1 symbolic link if + it is not the first item in the pattern, or none if it is the + first item in the pattern, following the same behavior as Bash. + + Note: when `follow` and `nodir` are both set, then symbolic + links to directories are also omitted. + +- `realpath` Set to true to call `fs.realpath` on all of the + results. In the case of an entry that cannot be resolved, the + entry is omitted. This incurs a slight performance penalty, of + course, because of the added system calls. + +- `absolute` Set to true to always receive absolute paths for + matched files. Set to `false` to always receive relative paths + for matched files. + + By default, when this option is not set, absolute paths are + returned for patterns that are absolute, and otherwise paths + are returned that are relative to the `cwd` setting. + + This does _not_ make an extra system call to get the realpath, + it only does string path resolution. + + `absolute` may not be used along with `withFileTypes`. + +- `posix` Set to true to use `/` as the path separator in + returned results. On posix systems, this has no effect. On + Windows systems, this will return `/` delimited path results, + and absolute paths will be returned in their full resolved UNC + path form, eg insted of `'C:\\foo\\bar'`, it will return + `//?/C:/foo/bar`. + +- `platform` Defaults to value of `process.platform` if + available, or `'linux'` if not. Setting `platform:'win32'` on + non-Windows systems may cause strange behavior. + +- `withFileTypes` Return [PathScurry](http://npm.im/path-scurry) + `Path` objects instead of strings. These are similar to a + NodeJS `Dirent` object, but with additional methods and + properties. + + `withFileTypes` may not be used along with `absolute`. + +- `signal` An AbortSignal which will cancel the Glob walk when + triggered. + +- `fs` An override object to pass in custom filesystem methods. + See [PathScurry docs](http://npm.im/path-scurry) for what can + be overridden. + +- `scurry` A [PathScurry](http://npm.im/path-scurry) object used + to traverse the file system. If the `nocase` option is set + explicitly, then any provided `scurry` object must match this + setting. + +- `includeChildMatches` boolean, default `true`. Do not match any + children of any matches. For example, the pattern `**\/foo` + would match `a/foo`, but not `a/foo/b/foo` in this mode. + + This is especially useful for cases like "find all + `node_modules` folders, but not the ones in `node_modules`". + + In order to support this, the `Ignore` implementation must + support an `add(pattern: string)` method. If using the default + `Ignore` class, then this is fine, but if this is set to + `false`, and a custom `Ignore` is provided that does not have + an `add()` method, then it will throw an error. + + **Caveat** It _only_ ignores matches that would be a descendant + of a previous match, and only if that descendant is matched + _after_ the ancestor is encountered. Since the file system walk + happens in indeterminate order, it's possible that a match will + already be added before its ancestor, if multiple or braced + patterns are used. + + For example: + + ```js + const results = await glob( + [ + // likely to match first, since it's just a stat + 'a/b/c/d/e/f', + + // this pattern is more complicated! It must to various readdir() + // calls and test the results against a regular expression, and that + // is certainly going to take a little bit longer. + // + // So, later on, it encounters a match at 'a/b/c/d/e', but it's too + // late to ignore a/b/c/d/e/f, because it's already been emitted. + 'a/[bdf]/?/[a-z]/*', + ], + { includeChildMatches: false }, + ) + ``` + + It's best to only set this to `false` if you can be reasonably + sure that no components of the pattern will potentially match + one another's file system descendants, or if the occasional + included child entry will not cause problems. + +## Glob Primer + +Much more information about glob pattern expansion can be found +by running `man bash` and searching for `Pattern Matching`. + +"Globs" are the patterns you type when you do stuff like `ls +*.js` on the command line, or put `build/*` in a `.gitignore` +file. + +Before parsing the path part patterns, braced sections are +expanded into a set. Braced sections start with `{` and end with +`}`, with 2 or more comma-delimited sections within. Braced +sections may contain slash characters, so `a{/b/c,bcd}` would +expand into `a/b/c` and `abcd`. + +The following characters have special magic meaning when used in +a path portion. With the exception of `**`, none of these match +path separators (ie, `/` on all platforms, and `\` on Windows). + +- `*` Matches 0 or more characters in a single path portion. + When alone in a path portion, it must match at least 1 + character. If `dot:true` is not specified, then `*` will not + match against a `.` character at the start of a path portion. +- `?` Matches 1 character. If `dot:true` is not specified, then + `?` will not match against a `.` character at the start of a + path portion. +- `[...]` Matches a range of characters, similar to a RegExp + range. If the first character of the range is `!` or `^` then + it matches any character not in the range. If the first + character is `]`, then it will be considered the same as `\]`, + rather than the end of the character class. +- `!(pattern|pattern|pattern)` Matches anything that does not + match any of the patterns provided. May _not_ contain `/` + characters. Similar to `*`, if alone in a path portion, then + the path portion must have at least one character. +- `?(pattern|pattern|pattern)` Matches zero or one occurrence of + the patterns provided. May _not_ contain `/` characters. +- `+(pattern|pattern|pattern)` Matches one or more occurrences of + the patterns provided. May _not_ contain `/` characters. +- `*(a|b|c)` Matches zero or more occurrences of the patterns + provided. May _not_ contain `/` characters. +- `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns + provided. May _not_ contain `/` characters. +- `**` If a "globstar" is alone in a path portion, then it + matches zero or more directories and subdirectories searching + for matches. It does not crawl symlinked directories, unless + `{follow:true}` is passed in the options object. A pattern + like `a/b/**` will only match `a/b` if it is a directory. + Follows 1 symbolic link if not the first item in the pattern, + or 0 if it is the first item, unless `follow:true` is set, in + which case it follows all symbolic links. + +`[:class:]` patterns are supported by this implementation, but +`[=c=]` and `[.symbol.]` style class patterns are not. + +### Dots + +If a file or directory path portion has a `.` as the first +character, then it will not match any glob pattern unless that +pattern's corresponding path part also has a `.` as its first +character. + +For example, the pattern `a/.*/c` would match the file at +`a/.b/c`. However the pattern `a/*/c` would not, because `*` does +not start with a dot character. + +You can make glob treat dots as normal characters by setting +`dot:true` in the options. + +### Basename Matching + +If you set `matchBase:true` in the options, and the pattern has +no slashes in it, then it will seek for any file anywhere in the +tree with a matching basename. For example, `*.js` would match +`test/simple/basic.js`. + +### Empty Sets + +If no matching files are found, then an empty array is returned. +This differs from the shell, where the pattern itself is +returned. For example: + +```sh +$ echo a*s*d*f +a*s*d*f +``` + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a +worthwhile goal, some discrepancies exist between node-glob and +other implementations, and are intentional. + +The double-star character `**` is supported by default, unless +the `noglobstar` flag is set. This is supported in the manner of +bsdglob and bash 5, where `**` only has special significance if +it is the only thing in a path part. That is, `a/**/b` will match +`a/x/y/b`, but `a/**b` will not. + +Note that symlinked directories are not traversed as part of a +`**`, though their contents may match against subsequent portions +of the pattern. This prevents infinite loops and duplicates and +the like. You can force glob to traverse symlinks with `**` by +setting `{follow:true}` in the options. + +There is no equivalent of the `nonull` option. A pattern that +does not find any matches simply resolves to nothing. (An empty +array, immediately ended stream, etc.) + +If brace expansion is not disabled, then it is performed before +any other interpretation of the glob pattern. Thus, a pattern +like `+(a|{b),c)}`, which would not be valid in bash or zsh, is +expanded **first** into the set of `+(a|b)` and `+(a|c)`, and +those patterns are checked for validity. Since those two are +valid, matching proceeds. + +The character class patterns `[:class:]` (posix standard named +classes) style class patterns are supported and unicode-aware, +but `[=c=]` (locale-specific character collation weight), and +`[.symbol.]` (collating symbol), are not. + +### Repeated Slashes + +Unlike Bash and zsh, repeated `/` are always coalesced into a +single path separator. + +### Comments and Negation + +Previously, this module let you mark a pattern as a "comment" if +it started with a `#` character, or a "negated" pattern if it +started with a `!` character. + +These options were deprecated in version 5, and removed in +version 6. + +To specify things that should not match, use the `ignore` option. + +## Windows + +**Please only use forward-slashes in glob expressions.** + +Though windows uses either `/` or `\` as its path separator, only +`/` characters are used by this glob implementation. You must use +forward-slashes **only** in glob expressions. Back-slashes will +always be interpreted as escape characters, not path separators. + +Results from absolute patterns such as `/foo/*` are mounted onto +the root setting using `path.join`. On windows, this will by +default result in `/foo/*` matching `C:\foo\bar.txt`. + +To automatically coerce all `\` characters to `/` in pattern +strings, **thus making it impossible to escape literal glob +characters**, you may set the `windowsPathsNoEscape` option to +`true`. + +### Windows, CWDs, Drive Letters, and UNC Paths + +On posix systems, when a pattern starts with `/`, any `cwd` +option is ignored, and the traversal starts at `/`, plus any +non-magic path portions specified in the pattern. + +On Windows systems, the behavior is similar, but the concept of +an "absolute path" is somewhat more involved. + +#### UNC Paths + +A UNC path may be used as the start of a pattern on Windows +platforms. For example, a pattern like: `//?/x:/*` will return +all file entries in the root of the `x:` drive. A pattern like +`//ComputerName/Share/*` will return all files in the associated +share. + +UNC path roots are always compared case insensitively. + +#### Drive Letters + +A pattern starting with a drive letter, like `c:/*`, will search +in that drive, regardless of any `cwd` option provided. + +If the pattern starts with `/`, and is not a UNC path, and there +is an explicit `cwd` option set with a drive letter, then the +drive letter in the `cwd` is used as the root of the directory +traversal. + +For example, `glob('/tmp', { cwd: 'c:/any/thing' })` will return +`['c:/tmp']` as the result. + +If an explicit `cwd` option is not provided, and the pattern +starts with `/`, then the traversal will run on the root of the +drive provided as the `cwd` option. (That is, it is the result of +`path.resolve('/')`.) + +## Race Conditions + +Glob searching, by its very nature, is susceptible to race +conditions, since it relies on directory walking. + +As a result, it is possible that a file that exists when glob +looks for it may have been deleted or modified by the time it +returns the result. + +By design, this implementation caches all readdir calls that it +makes, in order to cut down on system overhead. However, this +also makes it even more susceptible to races, especially if the +cache object is reused between glob calls. + +Users are thus advised not to use a glob result as a guarantee of +filesystem state in the face of rapid changes. For the vast +majority of operations, this is never a problem. + +### See Also: + +- `man sh` +- `man bash` [Pattern + Matching](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) +- `man 3 fnmatch` +- `man 5 gitignore` +- [minimatch documentation](https://github.com/isaacs/minimatch) + +## Glob Logo + +Glob's logo was created by [Tanya +Brassie](http://tanyabrassie.com/). Logo files can be found +[here](https://github.com/isaacs/node-glob/tree/master/logo). + +The logo is licensed under a [Creative Commons +Attribution-ShareAlike 4.0 International +License](https://creativecommons.org/licenses/by-sa/4.0/). + +## Contributing + +Any change to behavior (including bugfixes) must come with a +test. + +Patches that fail tests or reduce performance will be rejected. + +```sh +# to run tests +npm test + +# to re-generate test fixtures +npm run test-regen + +# run the benchmarks +npm run bench + +# to profile javascript +npm run prof +``` + +## Comparison to Other JavaScript Glob Implementations + +**tl;dr** + +- If you want glob matching that is as faithful as possible to + Bash pattern expansion semantics, and as fast as possible + within that constraint, _use this module_. +- If you are reasonably sure that the patterns you will encounter + are relatively simple, and want the absolutely fastest glob + matcher out there, _use [fast-glob](http://npm.im/fast-glob)_. +- If you are reasonably sure that the patterns you will encounter + are relatively simple, and want the convenience of + automatically respecting `.gitignore` files, _use + [globby](http://npm.im/globby)_. + +There are some other glob matcher libraries on npm, but these +three are (in my opinion, as of 2023) the best. + +--- + +**full explanation** + +Every library reflects a set of opinions and priorities in the +trade-offs it makes. Other than this library, I can personally +recommend both [globby](http://npm.im/globby) and +[fast-glob](http://npm.im/fast-glob), though they differ in their +benefits and drawbacks. + +Both have very nice APIs and are reasonably fast. + +`fast-glob` is, as far as I am aware, the fastest glob +implementation in JavaScript today. However, there are many +cases where the choices that `fast-glob` makes in pursuit of +speed mean that its results differ from the results returned by +Bash and other sh-like shells, which may be surprising. + +In my testing, `fast-glob` is around 10-20% faster than this +module when walking over 200k files nested 4 directories +deep[1](#fn-webscale). However, there are some inconsistencies +with Bash matching behavior that this module does not suffer +from: + +- `**` only matches files, not directories +- `..` path portions are not handled unless they appear at the + start of the pattern +- `./!()` will not match any files that _start_ with + ``, even if they do not match ``. For + example, `!(9).txt` will not match `9999.txt`. +- Some brace patterns in the middle of a pattern will result in + failing to find certain matches. +- Extglob patterns are allowed to contain `/` characters. + +Globby exhibits all of the same pattern semantics as fast-glob, +(as it is a wrapper around fast-glob) and is slightly slower than +node-glob (by about 10-20% in the benchmark test set, or in other +words, anywhere from 20-50% slower than fast-glob). However, it +adds some API conveniences that may be worth the costs. + +- Support for `.gitignore` and other ignore files. +- Support for negated globs (ie, patterns starting with `!` + rather than using a separate `ignore` option). + +The priority of this module is "correctness" in the sense of +performing a glob pattern expansion as faithfully as possible to +the behavior of Bash and other sh-like shells, with as much speed +as possible. + +Note that prior versions of `node-glob` are _not_ on this list. +Former versions of this module are far too slow for any cases +where performance matters at all, and were designed with APIs +that are extremely dated by current JavaScript standards. + +--- + +[1]: In the cases where this module +returns results and `fast-glob` doesn't, it's even faster, of +course. + +![lumpy space princess saying 'oh my GLOB'](https://github.com/isaacs/node-glob/raw/main/oh-my-glob.gif) + +### Benchmark Results + +First number is time, smaller is better. + +Second number is the count of results returned. + +``` +--- pattern: '**' --- +~~ sync ~~ +node fast-glob sync 0m0.598s 200364 +node globby sync 0m0.765s 200364 +node current globSync mjs 0m0.683s 222656 +node current glob syncStream 0m0.649s 222656 +~~ async ~~ +node fast-glob async 0m0.350s 200364 +node globby async 0m0.509s 200364 +node current glob async mjs 0m0.463s 222656 +node current glob stream 0m0.411s 222656 + +--- pattern: '**/..' --- +~~ sync ~~ +node fast-glob sync 0m0.486s 0 +node globby sync 0m0.769s 200364 +node current globSync mjs 0m0.564s 2242 +node current glob syncStream 0m0.583s 2242 +~~ async ~~ +node fast-glob async 0m0.283s 0 +node globby async 0m0.512s 200364 +node current glob async mjs 0m0.299s 2242 +node current glob stream 0m0.312s 2242 + +--- pattern: './**/0/**/0/**/0/**/0/**/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.490s 10 +node globby sync 0m0.517s 10 +node current globSync mjs 0m0.540s 10 +node current glob syncStream 0m0.550s 10 +~~ async ~~ +node fast-glob async 0m0.290s 10 +node globby async 0m0.296s 10 +node current glob async mjs 0m0.278s 10 +node current glob stream 0m0.302s 10 + +--- pattern: './**/[01]/**/[12]/**/[23]/**/[45]/**/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.500s 160 +node globby sync 0m0.528s 160 +node current globSync mjs 0m0.556s 160 +node current glob syncStream 0m0.573s 160 +~~ async ~~ +node fast-glob async 0m0.283s 160 +node globby async 0m0.301s 160 +node current glob async mjs 0m0.306s 160 +node current glob stream 0m0.322s 160 + +--- pattern: './**/0/**/0/**/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.502s 5230 +node globby sync 0m0.527s 5230 +node current globSync mjs 0m0.544s 5230 +node current glob syncStream 0m0.557s 5230 +~~ async ~~ +node fast-glob async 0m0.285s 5230 +node globby async 0m0.305s 5230 +node current glob async mjs 0m0.304s 5230 +node current glob stream 0m0.310s 5230 + +--- pattern: '**/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.580s 200023 +node globby sync 0m0.771s 200023 +node current globSync mjs 0m0.685s 200023 +node current glob syncStream 0m0.649s 200023 +~~ async ~~ +node fast-glob async 0m0.349s 200023 +node globby async 0m0.509s 200023 +node current glob async mjs 0m0.427s 200023 +node current glob stream 0m0.388s 200023 + +--- pattern: '{**/*.txt,**/?/**/*.txt,**/?/**/?/**/*.txt,**/?/**/?/**/?/**/*.txt,**/?/**/?/**/?/**/?/**/*.txt}' --- +~~ sync ~~ +node fast-glob sync 0m0.589s 200023 +node globby sync 0m0.771s 200023 +node current globSync mjs 0m0.716s 200023 +node current glob syncStream 0m0.684s 200023 +~~ async ~~ +node fast-glob async 0m0.351s 200023 +node globby async 0m0.518s 200023 +node current glob async mjs 0m0.462s 200023 +node current glob stream 0m0.468s 200023 + +--- pattern: '**/5555/0000/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.496s 1000 +node globby sync 0m0.519s 1000 +node current globSync mjs 0m0.539s 1000 +node current glob syncStream 0m0.567s 1000 +~~ async ~~ +node fast-glob async 0m0.285s 1000 +node globby async 0m0.299s 1000 +node current glob async mjs 0m0.305s 1000 +node current glob stream 0m0.301s 1000 + +--- pattern: './**/0/**/../[01]/**/0/../**/0/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.484s 0 +node globby sync 0m0.507s 0 +node current globSync mjs 0m0.577s 4880 +node current glob syncStream 0m0.586s 4880 +~~ async ~~ +node fast-glob async 0m0.280s 0 +node globby async 0m0.298s 0 +node current glob async mjs 0m0.327s 4880 +node current glob stream 0m0.324s 4880 + +--- pattern: '**/????/????/????/????/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.547s 100000 +node globby sync 0m0.673s 100000 +node current globSync mjs 0m0.626s 100000 +node current glob syncStream 0m0.618s 100000 +~~ async ~~ +node fast-glob async 0m0.315s 100000 +node globby async 0m0.414s 100000 +node current glob async mjs 0m0.366s 100000 +node current glob stream 0m0.345s 100000 + +--- pattern: './{**/?{/**/?{/**/?{/**/?,,,,},,,,},,,,},,,}/**/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.588s 100000 +node globby sync 0m0.670s 100000 +node current globSync mjs 0m0.717s 200023 +node current glob syncStream 0m0.687s 200023 +~~ async ~~ +node fast-glob async 0m0.343s 100000 +node globby async 0m0.418s 100000 +node current glob async mjs 0m0.519s 200023 +node current glob stream 0m0.451s 200023 + +--- pattern: '**/!(0|9).txt' --- +~~ sync ~~ +node fast-glob sync 0m0.573s 160023 +node globby sync 0m0.731s 160023 +node current globSync mjs 0m0.680s 180023 +node current glob syncStream 0m0.659s 180023 +~~ async ~~ +node fast-glob async 0m0.345s 160023 +node globby async 0m0.476s 160023 +node current glob async mjs 0m0.427s 180023 +node current glob stream 0m0.388s 180023 + +--- pattern: './{*/**/../{*/**/../{*/**/../{*/**/../{*/**,,,,},,,,},,,,},,,,},,,,}/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.483s 0 +node globby sync 0m0.512s 0 +node current globSync mjs 0m0.811s 200023 +node current glob syncStream 0m0.773s 200023 +~~ async ~~ +node fast-glob async 0m0.280s 0 +node globby async 0m0.299s 0 +node current glob async mjs 0m0.617s 200023 +node current glob stream 0m0.568s 200023 + +--- pattern: './*/**/../*/**/../*/**/../*/**/../*/**/../*/**/../*/**/../*/**/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.485s 0 +node globby sync 0m0.507s 0 +node current globSync mjs 0m0.759s 200023 +node current glob syncStream 0m0.740s 200023 +~~ async ~~ +node fast-glob async 0m0.281s 0 +node globby async 0m0.297s 0 +node current glob async mjs 0m0.544s 200023 +node current glob stream 0m0.464s 200023 + +--- pattern: './*/**/../*/**/../*/**/../*/**/../*/**/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.486s 0 +node globby sync 0m0.513s 0 +node current globSync mjs 0m0.734s 200023 +node current glob syncStream 0m0.696s 200023 +~~ async ~~ +node fast-glob async 0m0.286s 0 +node globby async 0m0.296s 0 +node current glob async mjs 0m0.506s 200023 +node current glob stream 0m0.483s 200023 + +--- pattern: './0/**/../1/**/../2/**/../3/**/../4/**/../5/**/../6/**/../7/**/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.060s 0 +node globby sync 0m0.074s 0 +node current globSync mjs 0m0.067s 0 +node current glob syncStream 0m0.066s 0 +~~ async ~~ +node fast-glob async 0m0.060s 0 +node globby async 0m0.075s 0 +node current glob async mjs 0m0.066s 0 +node current glob stream 0m0.067s 0 + +--- pattern: './**/?/**/?/**/?/**/?/**/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.568s 100000 +node globby sync 0m0.651s 100000 +node current globSync mjs 0m0.619s 100000 +node current glob syncStream 0m0.617s 100000 +~~ async ~~ +node fast-glob async 0m0.332s 100000 +node globby async 0m0.409s 100000 +node current glob async mjs 0m0.372s 100000 +node current glob stream 0m0.351s 100000 + +--- pattern: '**/*/**/*/**/*/**/*/**' --- +~~ sync ~~ +node fast-glob sync 0m0.603s 200113 +node globby sync 0m0.798s 200113 +node current globSync mjs 0m0.730s 222137 +node current glob syncStream 0m0.693s 222137 +~~ async ~~ +node fast-glob async 0m0.356s 200113 +node globby async 0m0.525s 200113 +node current glob async mjs 0m0.508s 222137 +node current glob stream 0m0.455s 222137 + +--- pattern: './**/*/**/*/**/*/**/*/**/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.622s 200000 +node globby sync 0m0.792s 200000 +node current globSync mjs 0m0.722s 200000 +node current glob syncStream 0m0.695s 200000 +~~ async ~~ +node fast-glob async 0m0.369s 200000 +node globby async 0m0.527s 200000 +node current glob async mjs 0m0.502s 200000 +node current glob stream 0m0.481s 200000 + +--- pattern: '**/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.588s 200023 +node globby sync 0m0.771s 200023 +node current globSync mjs 0m0.684s 200023 +node current glob syncStream 0m0.658s 200023 +~~ async ~~ +node fast-glob async 0m0.352s 200023 +node globby async 0m0.516s 200023 +node current glob async mjs 0m0.432s 200023 +node current glob stream 0m0.384s 200023 + +--- pattern: './**/**/**/**/**/**/**/**/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.589s 200023 +node globby sync 0m0.766s 200023 +node current globSync mjs 0m0.682s 200023 +node current glob syncStream 0m0.652s 200023 +~~ async ~~ +node fast-glob async 0m0.352s 200023 +node globby async 0m0.523s 200023 +node current glob async mjs 0m0.436s 200023 +node current glob stream 0m0.380s 200023 + +--- pattern: '**/*/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.592s 200023 +node globby sync 0m0.776s 200023 +node current globSync mjs 0m0.691s 200023 +node current glob syncStream 0m0.659s 200023 +~~ async ~~ +node fast-glob async 0m0.357s 200023 +node globby async 0m0.513s 200023 +node current glob async mjs 0m0.471s 200023 +node current glob stream 0m0.424s 200023 + +--- pattern: '**/*/**/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.585s 200023 +node globby sync 0m0.766s 200023 +node current globSync mjs 0m0.694s 200023 +node current glob syncStream 0m0.664s 200023 +~~ async ~~ +node fast-glob async 0m0.350s 200023 +node globby async 0m0.514s 200023 +node current glob async mjs 0m0.472s 200023 +node current glob stream 0m0.424s 200023 + +--- pattern: '**/[0-9]/**/*.txt' --- +~~ sync ~~ +node fast-glob sync 0m0.544s 100000 +node globby sync 0m0.636s 100000 +node current globSync mjs 0m0.626s 100000 +node current glob syncStream 0m0.621s 100000 +~~ async ~~ +node fast-glob async 0m0.322s 100000 +node globby async 0m0.404s 100000 +node current glob async mjs 0m0.360s 100000 +node current glob stream 0m0.352s 100000 +``` diff --git a/node_modules/glob/dist/commonjs/glob.d.ts b/node_modules/glob/dist/commonjs/glob.d.ts new file mode 100644 index 0000000..25262b3 --- /dev/null +++ b/node_modules/glob/dist/commonjs/glob.d.ts @@ -0,0 +1,388 @@ +import { Minimatch } from 'minimatch'; +import { Minipass } from 'minipass'; +import { FSOption, Path, PathScurry } from 'path-scurry'; +import { IgnoreLike } from './ignore.js'; +import { Pattern } from './pattern.js'; +export type MatchSet = Minimatch['set']; +export type GlobParts = Exclude; +/** + * A `GlobOptions` object may be provided to any of the exported methods, and + * must be provided to the `Glob` constructor. + * + * All options are optional, boolean, and false by default, unless otherwise + * noted. + * + * All resolved options are added to the Glob object as properties. + * + * If you are running many `glob` operations, you can pass a Glob object as the + * `options` argument to a subsequent operation to share the previously loaded + * cache. + */ +export interface GlobOptions { + /** + * Set to `true` to always receive absolute paths for + * matched files. Set to `false` to always return relative paths. + * + * When this option is not set, absolute paths are returned for patterns + * that are absolute, and otherwise paths are returned that are relative + * to the `cwd` setting. + * + * This does _not_ make an extra system call to get + * the realpath, it only does string path resolution. + * + * Conflicts with {@link withFileTypes} + */ + absolute?: boolean; + /** + * Set to false to enable {@link windowsPathsNoEscape} + * + * @deprecated + */ + allowWindowsEscape?: boolean; + /** + * The current working directory in which to search. Defaults to + * `process.cwd()`. + * + * May be eiher a string path or a `file://` URL object or string. + */ + cwd?: string | URL; + /** + * Include `.dot` files in normal matches and `globstar` + * matches. Note that an explicit dot in a portion of the pattern + * will always match dot files. + */ + dot?: boolean; + /** + * Prepend all relative path strings with `./` (or `.\` on Windows). + * + * Without this option, returned relative paths are "bare", so instead of + * returning `'./foo/bar'`, they are returned as `'foo/bar'`. + * + * Relative patterns starting with `'../'` are not prepended with `./`, even + * if this option is set. + */ + dotRelative?: boolean; + /** + * Follow symlinked directories when expanding `**` + * patterns. This can result in a lot of duplicate references in + * the presence of cyclic links, and make performance quite bad. + * + * By default, a `**` in a pattern will follow 1 symbolic link if + * it is not the first item in the pattern, or none if it is the + * first item in the pattern, following the same behavior as Bash. + */ + follow?: boolean; + /** + * string or string[], or an object with `ignore` and `ignoreChildren` + * methods. + * + * If a string or string[] is provided, then this is treated as a glob + * pattern or array of glob patterns to exclude from matches. To ignore all + * children within a directory, as well as the entry itself, append `'/**'` + * to the ignore pattern. + * + * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of + * any other settings. + * + * If an object is provided that has `ignored(path)` and/or + * `childrenIgnored(path)` methods, then these methods will be called to + * determine whether any Path is a match or if its children should be + * traversed, respectively. + */ + ignore?: string | string[] | IgnoreLike; + /** + * Treat brace expansion like `{a,b}` as a "magic" pattern. Has no + * effect if {@link nobrace} is set. + * + * Only has effect on the {@link hasMagic} function. + */ + magicalBraces?: boolean; + /** + * Add a `/` character to directory matches. Note that this requires + * additional stat calls in some cases. + */ + mark?: boolean; + /** + * Perform a basename-only match if the pattern does not contain any slash + * characters. That is, `*.js` would be treated as equivalent to + * `**\/*.js`, matching all js files in all directories. + */ + matchBase?: boolean; + /** + * Limit the directory traversal to a given depth below the cwd. + * Note that this does NOT prevent traversal to sibling folders, + * root patterns, and so on. It only limits the maximum folder depth + * that the walk will descend, relative to the cwd. + */ + maxDepth?: number; + /** + * Do not expand `{a,b}` and `{1..3}` brace sets. + */ + nobrace?: boolean; + /** + * Perform a case-insensitive match. This defaults to `true` on macOS and + * Windows systems, and `false` on all others. + * + * **Note** `nocase` should only be explicitly set when it is + * known that the filesystem's case sensitivity differs from the + * platform default. If set `true` on case-sensitive file + * systems, or `false` on case-insensitive file systems, then the + * walk may return more or less results than expected. + */ + nocase?: boolean; + /** + * Do not match directories, only files. (Note: to match + * _only_ directories, put a `/` at the end of the pattern.) + */ + nodir?: boolean; + /** + * Do not match "extglob" patterns such as `+(a|b)`. + */ + noext?: boolean; + /** + * Do not match `**` against multiple filenames. (Ie, treat it as a normal + * `*` instead.) + * + * Conflicts with {@link matchBase} + */ + noglobstar?: boolean; + /** + * Defaults to value of `process.platform` if available, or `'linux'` if + * not. Setting `platform:'win32'` on non-Windows systems may cause strange + * behavior. + */ + platform?: NodeJS.Platform; + /** + * Set to true to call `fs.realpath` on all of the + * results. In the case of an entry that cannot be resolved, the + * entry is omitted. This incurs a slight performance penalty, of + * course, because of the added system calls. + */ + realpath?: boolean; + /** + * + * A string path resolved against the `cwd` option, which + * is used as the starting point for absolute patterns that start + * with `/`, (but not drive letters or UNC paths on Windows). + * + * Note that this _doesn't_ necessarily limit the walk to the + * `root` directory, and doesn't affect the cwd starting point for + * non-absolute patterns. A pattern containing `..` will still be + * able to traverse out of the root directory, if it is not an + * actual root directory on the filesystem, and any non-absolute + * patterns will be matched in the `cwd`. For example, the + * pattern `/../*` with `{root:'/some/path'}` will return all + * files in `/some`, not all files in `/some/path`. The pattern + * `*` with `{root:'/some/path'}` will return all the entries in + * the cwd, not the entries in `/some/path`. + * + * To start absolute and non-absolute patterns in the same + * path, you can use `{root:''}`. However, be aware that on + * Windows systems, a pattern like `x:/*` or `//host/share/*` will + * _always_ start in the `x:/` or `//host/share` directory, + * regardless of the `root` setting. + */ + root?: string; + /** + * A [PathScurry](http://npm.im/path-scurry) object used + * to traverse the file system. If the `nocase` option is set + * explicitly, then any provided `scurry` object must match this + * setting. + */ + scurry?: PathScurry; + /** + * Call `lstat()` on all entries, whether required or not to determine + * if it's a valid match. When used with {@link withFileTypes}, this means + * that matches will include data such as modified time, permissions, and + * so on. Note that this will incur a performance cost due to the added + * system calls. + */ + stat?: boolean; + /** + * An AbortSignal which will cancel the Glob walk when + * triggered. + */ + signal?: AbortSignal; + /** + * Use `\\` as a path separator _only_, and + * _never_ as an escape character. If set, all `\\` characters are + * replaced with `/` in the pattern. + * + * Note that this makes it **impossible** to match against paths + * containing literal glob pattern characters, but allows matching + * with patterns constructed using `path.join()` and + * `path.resolve()` on Windows platforms, mimicking the (buggy!) + * behavior of Glob v7 and before on Windows. Please use with + * caution, and be mindful of [the caveat below about Windows + * paths](#windows). (For legacy reasons, this is also set if + * `allowWindowsEscape` is set to the exact value `false`.) + */ + windowsPathsNoEscape?: boolean; + /** + * Return [PathScurry](http://npm.im/path-scurry) + * `Path` objects instead of strings. These are similar to a + * NodeJS `Dirent` object, but with additional methods and + * properties. + * + * Conflicts with {@link absolute} + */ + withFileTypes?: boolean; + /** + * An fs implementation to override some or all of the defaults. See + * http://npm.im/path-scurry for details about what can be overridden. + */ + fs?: FSOption; + /** + * Just passed along to Minimatch. Note that this makes all pattern + * matching operations slower and *extremely* noisy. + */ + debug?: boolean; + /** + * Return `/` delimited paths, even on Windows. + * + * On posix systems, this has no effect. But, on Windows, it means that + * paths will be `/` delimited, and absolute paths will be their full + * resolved UNC forms, eg instead of `'C:\\foo\\bar'`, it would return + * `'//?/C:/foo/bar'` + */ + posix?: boolean; + /** + * Do not match any children of any matches. For example, the pattern + * `**\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode. + * + * This is especially useful for cases like "find all `node_modules` + * folders, but not the ones in `node_modules`". + * + * In order to support this, the `Ignore` implementation must support an + * `add(pattern: string)` method. If using the default `Ignore` class, then + * this is fine, but if this is set to `false`, and a custom `Ignore` is + * provided that does not have an `add()` method, then it will throw an + * error. + * + * **Caveat** It *only* ignores matches that would be a descendant of a + * previous match, and only if that descendant is matched *after* the + * ancestor is encountered. Since the file system walk happens in + * indeterminate order, it's possible that a match will already be added + * before its ancestor, if multiple or braced patterns are used. + * + * For example: + * + * ```ts + * const results = await glob([ + * // likely to match first, since it's just a stat + * 'a/b/c/d/e/f', + * + * // this pattern is more complicated! It must to various readdir() + * // calls and test the results against a regular expression, and that + * // is certainly going to take a little bit longer. + * // + * // So, later on, it encounters a match at 'a/b/c/d/e', but it's too + * // late to ignore a/b/c/d/e/f, because it's already been emitted. + * 'a/[bdf]/?/[a-z]/*', + * ], { includeChildMatches: false }) + * ``` + * + * It's best to only set this to `false` if you can be reasonably sure that + * no components of the pattern will potentially match one another's file + * system descendants, or if the occasional included child entry will not + * cause problems. + * + * @default true + */ + includeChildMatches?: boolean; +} +export type GlobOptionsWithFileTypesTrue = GlobOptions & { + withFileTypes: true; + absolute?: undefined; + mark?: undefined; + posix?: undefined; +}; +export type GlobOptionsWithFileTypesFalse = GlobOptions & { + withFileTypes?: false; +}; +export type GlobOptionsWithFileTypesUnset = GlobOptions & { + withFileTypes?: undefined; +}; +export type Result = Opts extends GlobOptionsWithFileTypesTrue ? Path : Opts extends GlobOptionsWithFileTypesFalse ? string : Opts extends GlobOptionsWithFileTypesUnset ? string : string | Path; +export type Results = Result[]; +export type FileTypes = Opts extends GlobOptionsWithFileTypesTrue ? true : Opts extends GlobOptionsWithFileTypesFalse ? false : Opts extends GlobOptionsWithFileTypesUnset ? false : boolean; +/** + * An object that can perform glob pattern traversals. + */ +export declare class Glob implements GlobOptions { + absolute?: boolean; + cwd: string; + root?: string; + dot: boolean; + dotRelative: boolean; + follow: boolean; + ignore?: string | string[] | IgnoreLike; + magicalBraces: boolean; + mark?: boolean; + matchBase: boolean; + maxDepth: number; + nobrace: boolean; + nocase: boolean; + nodir: boolean; + noext: boolean; + noglobstar: boolean; + pattern: string[]; + platform: NodeJS.Platform; + realpath: boolean; + scurry: PathScurry; + stat: boolean; + signal?: AbortSignal; + windowsPathsNoEscape: boolean; + withFileTypes: FileTypes; + includeChildMatches: boolean; + /** + * The options provided to the constructor. + */ + opts: Opts; + /** + * An array of parsed immutable {@link Pattern} objects. + */ + patterns: Pattern[]; + /** + * All options are stored as properties on the `Glob` object. + * + * See {@link GlobOptions} for full options descriptions. + * + * Note that a previous `Glob` object can be passed as the + * `GlobOptions` to another `Glob` instantiation to re-use settings + * and caches with a new pattern. + * + * Traversal functions can be called multiple times to run the walk + * again. + */ + constructor(pattern: string | string[], opts: Opts); + /** + * Returns a Promise that resolves to the results array. + */ + walk(): Promise>; + /** + * synchronous {@link Glob.walk} + */ + walkSync(): Results; + /** + * Stream results asynchronously. + */ + stream(): Minipass, Result>; + /** + * Stream results synchronously. + */ + streamSync(): Minipass, Result>; + /** + * Default sync iteration function. Returns a Generator that + * iterates over the results. + */ + iterateSync(): Generator, void, void>; + [Symbol.iterator](): Generator, void, void>; + /** + * Default async iteration function. Returns an AsyncGenerator that + * iterates over the results. + */ + iterate(): AsyncGenerator, void, void>; + [Symbol.asyncIterator](): AsyncGenerator, void, void>; +} +//# sourceMappingURL=glob.d.ts.map \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/glob.d.ts.map b/node_modules/glob/dist/commonjs/glob.d.ts.map new file mode 100644 index 0000000..c32dc74 --- /dev/null +++ b/node_modules/glob/dist/commonjs/glob.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"glob.d.ts","sourceRoot":"","sources":["../../src/glob.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAoB,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AAEnC,OAAO,EACL,QAAQ,EACR,IAAI,EACJ,UAAU,EAIX,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAGtC,MAAM,MAAM,QAAQ,GAAG,SAAS,CAAC,KAAK,CAAC,CAAA;AACvC,MAAM,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC,WAAW,CAAC,EAAE,SAAS,CAAC,CAAA;AAalE;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,WAAW;IAC1B;;;;;;;;;;;;OAYG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAA;IAElB;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAE5B;;;;;OAKG;IACH,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,CAAA;IAElB;;;;OAIG;IACH,GAAG,CAAC,EAAE,OAAO,CAAA;IAEb;;;;;;;;OAQG;IACH,WAAW,CAAC,EAAE,OAAO,CAAA;IAErB;;;;;;;;OAQG;IACH,MAAM,CAAC,EAAE,OAAO,CAAA;IAEhB;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CAAC,EAAE,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AAI,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAGnD,CAAC,MAAM,CAAC,aAAa,CAAC;CAGvB"} \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/glob.js b/node_modules/glob/dist/commonjs/glob.js new file mode 100644 index 0000000..e1339bb --- /dev/null +++ b/node_modules/glob/dist/commonjs/glob.js @@ -0,0 +1,247 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Glob = void 0; +const minimatch_1 = require("minimatch"); +const node_url_1 = require("node:url"); +const path_scurry_1 = require("path-scurry"); +const pattern_js_1 = require("./pattern.js"); +const walker_js_1 = require("./walker.js"); +// if no process global, just call it linux. +// so we default to case-sensitive, / separators +const defaultPlatform = (typeof process === 'object' && + process && + typeof process.platform === 'string') ? + process.platform + : 'linux'; +/** + * An object that can perform glob pattern traversals. + */ +class Glob { + absolute; + cwd; + root; + dot; + dotRelative; + follow; + ignore; + magicalBraces; + mark; + matchBase; + maxDepth; + nobrace; + nocase; + nodir; + noext; + noglobstar; + pattern; + platform; + realpath; + scurry; + stat; + signal; + windowsPathsNoEscape; + withFileTypes; + includeChildMatches; + /** + * The options provided to the constructor. + */ + opts; + /** + * An array of parsed immutable {@link Pattern} objects. + */ + patterns; + /** + * All options are stored as properties on the `Glob` object. + * + * See {@link GlobOptions} for full options descriptions. + * + * Note that a previous `Glob` object can be passed as the + * `GlobOptions` to another `Glob` instantiation to re-use settings + * and caches with a new pattern. + * + * Traversal functions can be called multiple times to run the walk + * again. + */ + constructor(pattern, opts) { + /* c8 ignore start */ + if (!opts) + throw new TypeError('glob options required'); + /* c8 ignore stop */ + this.withFileTypes = !!opts.withFileTypes; + this.signal = opts.signal; + this.follow = !!opts.follow; + this.dot = !!opts.dot; + this.dotRelative = !!opts.dotRelative; + this.nodir = !!opts.nodir; + this.mark = !!opts.mark; + if (!opts.cwd) { + this.cwd = ''; + } + else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) { + opts.cwd = (0, node_url_1.fileURLToPath)(opts.cwd); + } + this.cwd = opts.cwd || ''; + this.root = opts.root; + this.magicalBraces = !!opts.magicalBraces; + this.nobrace = !!opts.nobrace; + this.noext = !!opts.noext; + this.realpath = !!opts.realpath; + this.absolute = opts.absolute; + this.includeChildMatches = opts.includeChildMatches !== false; + this.noglobstar = !!opts.noglobstar; + this.matchBase = !!opts.matchBase; + this.maxDepth = + typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity; + this.stat = !!opts.stat; + this.ignore = opts.ignore; + if (this.withFileTypes && this.absolute !== undefined) { + throw new Error('cannot set absolute and withFileTypes:true'); + } + if (typeof pattern === 'string') { + pattern = [pattern]; + } + this.windowsPathsNoEscape = + !!opts.windowsPathsNoEscape || + opts.allowWindowsEscape === + false; + if (this.windowsPathsNoEscape) { + pattern = pattern.map(p => p.replace(/\\/g, '/')); + } + if (this.matchBase) { + if (opts.noglobstar) { + throw new TypeError('base matching requires globstar'); + } + pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`)); + } + this.pattern = pattern; + this.platform = opts.platform || defaultPlatform; + this.opts = { ...opts, platform: this.platform }; + if (opts.scurry) { + this.scurry = opts.scurry; + if (opts.nocase !== undefined && + opts.nocase !== opts.scurry.nocase) { + throw new Error('nocase option contradicts provided scurry option'); + } + } + else { + const Scurry = opts.platform === 'win32' ? path_scurry_1.PathScurryWin32 + : opts.platform === 'darwin' ? path_scurry_1.PathScurryDarwin + : opts.platform ? path_scurry_1.PathScurryPosix + : path_scurry_1.PathScurry; + this.scurry = new Scurry(this.cwd, { + nocase: opts.nocase, + fs: opts.fs, + }); + } + this.nocase = this.scurry.nocase; + // If you do nocase:true on a case-sensitive file system, then + // we need to use regexps instead of strings for non-magic + // path portions, because statting `aBc` won't return results + // for the file `AbC` for example. + const nocaseMagicOnly = this.platform === 'darwin' || this.platform === 'win32'; + const mmo = { + // default nocase based on platform + ...opts, + dot: this.dot, + matchBase: this.matchBase, + nobrace: this.nobrace, + nocase: this.nocase, + nocaseMagicOnly, + nocomment: true, + noext: this.noext, + nonegate: true, + optimizationLevel: 2, + platform: this.platform, + windowsPathsNoEscape: this.windowsPathsNoEscape, + debug: !!this.opts.debug, + }; + const mms = this.pattern.map(p => new minimatch_1.Minimatch(p, mmo)); + const [matchSet, globParts] = mms.reduce((set, m) => { + set[0].push(...m.set); + set[1].push(...m.globParts); + return set; + }, [[], []]); + this.patterns = matchSet.map((set, i) => { + const g = globParts[i]; + /* c8 ignore start */ + if (!g) + throw new Error('invalid pattern object'); + /* c8 ignore stop */ + return new pattern_js_1.Pattern(set, g, 0, this.platform); + }); + } + async walk() { + // Walkers always return array of Path objects, so we just have to + // coerce them into the right shape. It will have already called + // realpath() if the option was set to do so, so we know that's cached. + // start out knowing the cwd, at least + return [ + ...(await new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, { + ...this.opts, + maxDepth: this.maxDepth !== Infinity ? + this.maxDepth + this.scurry.cwd.depth() + : Infinity, + platform: this.platform, + nocase: this.nocase, + includeChildMatches: this.includeChildMatches, + }).walk()), + ]; + } + walkSync() { + return [ + ...new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, { + ...this.opts, + maxDepth: this.maxDepth !== Infinity ? + this.maxDepth + this.scurry.cwd.depth() + : Infinity, + platform: this.platform, + nocase: this.nocase, + includeChildMatches: this.includeChildMatches, + }).walkSync(), + ]; + } + stream() { + return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, { + ...this.opts, + maxDepth: this.maxDepth !== Infinity ? + this.maxDepth + this.scurry.cwd.depth() + : Infinity, + platform: this.platform, + nocase: this.nocase, + includeChildMatches: this.includeChildMatches, + }).stream(); + } + streamSync() { + return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, { + ...this.opts, + maxDepth: this.maxDepth !== Infinity ? + this.maxDepth + this.scurry.cwd.depth() + : Infinity, + platform: this.platform, + nocase: this.nocase, + includeChildMatches: this.includeChildMatches, + }).streamSync(); + } + /** + * Default sync iteration function. Returns a Generator that + * iterates over the results. + */ + iterateSync() { + return this.streamSync()[Symbol.iterator](); + } + [Symbol.iterator]() { + return this.iterateSync(); + } + /** + * Default async iteration function. Returns an AsyncGenerator that + * iterates over the results. + */ + iterate() { + return this.stream()[Symbol.asyncIterator](); + } + [Symbol.asyncIterator]() { + return this.iterate(); + } +} +exports.Glob = Glob; +//# sourceMappingURL=glob.js.map \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/glob.js.map b/node_modules/glob/dist/commonjs/glob.js.map new file mode 100644 index 0000000..ddab419 --- /dev/null +++ b/node_modules/glob/dist/commonjs/glob.js.map @@ -0,0 +1 @@ +{"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/glob.ts"],"names":[],"mappings":";;;AAAA,yCAAuD;AAEvD,uCAAwC;AACxC,6CAOoB;AAEpB,6CAAsC;AACtC,2CAAoD;AAKpD,4CAA4C;AAC5C,gDAAgD;AAChD,MAAM,eAAe,GACnB,CACE,OAAO,OAAO,KAAK,QAAQ;IAC3B,OAAO;IACP,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,CACrC,CAAC,CAAC;IACD,OAAO,CAAC,QAAQ;IAClB,CAAC,CAAC,OAAO,CAAA;AAyVX;;GAEG;AACH,MAAa,IAAI;IACf,QAAQ,CAAU;IAClB,GAAG,CAAQ;IACX,IAAI,CAAS;IACb,GAAG,CAAS;IACZ,WAAW,CAAS;IACpB,MAAM,CAAS;IACf,MAAM,CAAiC;IACvC,aAAa,CAAS;IACtB,IAAI,CAAU;IACd,SAAS,CAAS;IAClB,QAAQ,CAAQ;IAChB,OAAO,CAAS;IAChB,MAAM,CAAS;IACf,KAAK,CAAS;IACd,KAAK,CAAS;IACd,UAAU,CAAS;IACnB,OAAO,CAAU;IACjB,QAAQ,CAAiB;IACzB,QAAQ,CAAS;IACjB,MAAM,CAAY;IAClB,IAAI,CAAS;IACb,MAAM,CAAc;IACpB,oBAAoB,CAAS;IAC7B,aAAa,CAAiB;IAC9B,mBAAmB,CAAS;IAE5B;;OAEG;IAC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A;IAC7C,CAAC;IACD,CAAC,MAAM,CAAC,QAAQ,CAAC;QACf,OAAO,IAAI,CAAC,WAAW,EAAE,CAAA;IAC3B,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAA;IAC9C,CAAC;IACD,CAAC,MAAM,CAAC,aAAa,CAAC;QACpB,OAAO,IAAI,CAAC,OAAO,EAAE,CAAA;IACvB,CAAC;CACF;AA7QD,oBA6QC","sourcesContent":["import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport {\n FSOption,\n Path,\n PathScurry,\n PathScurryDarwin,\n PathScurryPosix,\n PathScurryWin32,\n} from 'path-scurry'\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 (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\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 /**\n * Do not match any children of any matches. For example, the pattern\n * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n *\n * This is especially useful for cases like \"find all `node_modules`\n * folders, but not the ones in `node_modules`\".\n *\n * In order to support this, the `Ignore` implementation must support an\n * `add(pattern: string)` method. If using the default `Ignore` class, then\n * this is fine, but if this is set to `false`, and a custom `Ignore` is\n * provided that does not have an `add()` method, then it will throw an\n * error.\n *\n * **Caveat** It *only* ignores matches that would be a descendant of a\n * previous match, and only if that descendant is matched *after* the\n * ancestor is encountered. Since the file system walk happens in\n * indeterminate order, it's possible that a match will already be added\n * before its ancestor, if multiple or braced patterns are used.\n *\n * For example:\n *\n * ```ts\n * const results = await glob([\n * // likely to match first, since it's just a stat\n * 'a/b/c/d/e/f',\n *\n * // this pattern is more complicated! It must to various readdir()\n * // calls and test the results against a regular expression, and that\n * // is certainly going to take a little bit longer.\n * //\n * // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n * // late to ignore a/b/c/d/e/f, because it's already been emitted.\n * 'a/[bdf]/?/[a-z]/*',\n * ], { includeChildMatches: false })\n * ```\n *\n * It's best to only set this to `false` if you can be reasonably sure that\n * no components of the pattern will potentially match one another's file\n * system descendants, or if the occasional included child entry will not\n * cause problems.\n *\n * @default true\n */\n includeChildMatches?: 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 =\n Opts extends GlobOptionsWithFileTypesTrue ? Path\n : Opts extends GlobOptionsWithFileTypesFalse ? string\n : Opts extends GlobOptionsWithFileTypesUnset ? string\n : string | Path\nexport type Results = Result[]\n\nexport type FileTypes =\n Opts extends GlobOptionsWithFileTypesTrue ? true\n : Opts extends GlobOptionsWithFileTypesFalse ? false\n : Opts extends GlobOptionsWithFileTypesUnset ? 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 includeChildMatches: boolean\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 this.includeChildMatches = opts.includeChildMatches !== false\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 { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n 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' ? PathScurryWin32\n : opts.platform === 'darwin' ? PathScurryDarwin\n : opts.platform ? 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 includeChildMatches: this.includeChildMatches,\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 includeChildMatches: this.includeChildMatches,\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 includeChildMatches: this.includeChildMatches,\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 includeChildMatches: this.includeChildMatches,\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"]} \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/has-magic.d.ts b/node_modules/glob/dist/commonjs/has-magic.d.ts new file mode 100644 index 0000000..8aec3bd --- /dev/null +++ b/node_modules/glob/dist/commonjs/has-magic.d.ts @@ -0,0 +1,14 @@ +import { GlobOptions } from './glob.js'; +/** + * Return true if the patterns provided contain any magic glob characters, + * given the options provided. + * + * Brace expansion is not considered "magic" unless the `magicalBraces` option + * is set, as brace expansion just turns one string into an array of strings. + * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and + * `'xby'` both do not contain any magic glob characters, and it's treated the + * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true` + * is in the options, brace expansion _is_ treated as a pattern having magic. + */ +export declare const hasMagic: (pattern: string | string[], options?: GlobOptions) => boolean; +//# sourceMappingURL=has-magic.d.ts.map \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/has-magic.d.ts.map b/node_modules/glob/dist/commonjs/has-magic.d.ts.map new file mode 100644 index 0000000..b24dd4e --- /dev/null +++ b/node_modules/glob/dist/commonjs/has-magic.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"has-magic.d.ts","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAEvC;;;;;;;;;;GAUG;AACH,eAAO,MAAM,QAAQ,YACV,MAAM,GAAG,MAAM,EAAE,YACjB,WAAW,KACnB,OAQF,CAAA"} \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/has-magic.js b/node_modules/glob/dist/commonjs/has-magic.js new file mode 100644 index 0000000..0918bd5 --- /dev/null +++ b/node_modules/glob/dist/commonjs/has-magic.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hasMagic = void 0; +const minimatch_1 = require("minimatch"); +/** + * Return true if the patterns provided contain any magic glob characters, + * given the options provided. + * + * Brace expansion is not considered "magic" unless the `magicalBraces` option + * is set, as brace expansion just turns one string into an array of strings. + * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and + * `'xby'` both do not contain any magic glob characters, and it's treated the + * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true` + * is in the options, brace expansion _is_ treated as a pattern having magic. + */ +const hasMagic = (pattern, options = {}) => { + if (!Array.isArray(pattern)) { + pattern = [pattern]; + } + for (const p of pattern) { + if (new minimatch_1.Minimatch(p, options).hasMagic()) + return true; + } + return false; +}; +exports.hasMagic = hasMagic; +//# sourceMappingURL=has-magic.js.map \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/has-magic.js.map b/node_modules/glob/dist/commonjs/has-magic.js.map new file mode 100644 index 0000000..44deab2 --- /dev/null +++ b/node_modules/glob/dist/commonjs/has-magic.js.map @@ -0,0 +1 @@ +{"version":3,"file":"has-magic.js","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":";;;AAAA,yCAAqC;AAGrC;;;;;;;;;;GAUG;AACI,MAAM,QAAQ,GAAG,CACtB,OAA0B,EAC1B,UAAuB,EAAE,EAChB,EAAE;IACX,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,OAAO,GAAG,CAAC,OAAO,CAAC,CAAA;IACrB,CAAC;IACD,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACxB,IAAI,IAAI,qBAAS,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE;YAAE,OAAO,IAAI,CAAA;IACvD,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA;AAXY,QAAA,QAAQ,YAWpB","sourcesContent":["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"]} \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/ignore.d.ts b/node_modules/glob/dist/commonjs/ignore.d.ts new file mode 100644 index 0000000..1893b16 --- /dev/null +++ b/node_modules/glob/dist/commonjs/ignore.d.ts @@ -0,0 +1,24 @@ +import { Minimatch, MinimatchOptions } from 'minimatch'; +import { Path } from 'path-scurry'; +import { GlobWalkerOpts } from './walker.js'; +export interface IgnoreLike { + ignored?: (p: Path) => boolean; + childrenIgnored?: (p: Path) => boolean; + add?: (ignore: string) => void; +} +/** + * Class used to process ignored patterns + */ +export declare class Ignore implements IgnoreLike { + relative: Minimatch[]; + relativeChildren: Minimatch[]; + absolute: Minimatch[]; + absoluteChildren: Minimatch[]; + platform: NodeJS.Platform; + mmopts: MinimatchOptions; + constructor(ignored: string[], { nobrace, nocase, noext, noglobstar, platform, }: GlobWalkerOpts); + add(ign: string): void; + ignored(p: Path): boolean; + childrenIgnored(p: Path): boolean; +} +//# sourceMappingURL=ignore.d.ts.map \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/ignore.d.ts.map b/node_modules/glob/dist/commonjs/ignore.d.ts.map new file mode 100644 index 0000000..57d6ab6 --- /dev/null +++ b/node_modules/glob/dist/commonjs/ignore.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ignore.d.ts","sourceRoot":"","sources":["../../src/ignore.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAElC,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C,MAAM,WAAW,UAAU;IACzB,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IAC9B,eAAe,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IACtC,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAA;CAC/B;AAWD;;GAEG;AACH,qBAAa,MAAO,YAAW,UAAU;IACvC,QAAQ,EAAE,SAAS,EAAE,CAAA;IACrB,gBAAgB,EAAE,SAAS,EAAE,CAAA;IAC7B,QAAQ,EAAE,SAAS,EAAE,CAAA;IACrB,gBAAgB,EAAE,SAAS,EAAE,CAAA;IAC7B,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAA;IACzB,MAAM,EAAE,gBAAgB,CAAA;gBAGtB,OAAO,EAAE,MAAM,EAAE,EACjB,EACE,OAAO,EACP,MAAM,EACN,KAAK,EACL,UAAU,EACV,QAA0B,GAC3B,EAAE,cAAc;IAqBnB,GAAG,CAAC,GAAG,EAAE,MAAM;IAyCf,OAAO,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;IAczB,eAAe,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;CAWlC"} \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/ignore.js b/node_modules/glob/dist/commonjs/ignore.js new file mode 100644 index 0000000..5f1fde0 --- /dev/null +++ b/node_modules/glob/dist/commonjs/ignore.js @@ -0,0 +1,119 @@ +"use strict"; +// give it a pattern, and it'll be able to tell you if +// a given path should be ignored. +// Ignoring a path ignores its children if the pattern ends in /** +// Ignores are always parsed in dot:true mode +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Ignore = void 0; +const minimatch_1 = require("minimatch"); +const pattern_js_1 = require("./pattern.js"); +const defaultPlatform = (typeof process === 'object' && + process && + typeof process.platform === 'string') ? + process.platform + : 'linux'; +/** + * Class used to process ignored patterns + */ +class Ignore { + relative; + relativeChildren; + absolute; + absoluteChildren; + platform; + mmopts; + constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = defaultPlatform, }) { + this.relative = []; + this.absolute = []; + this.relativeChildren = []; + this.absoluteChildren = []; + this.platform = platform; + this.mmopts = { + dot: true, + nobrace, + nocase, + noext, + noglobstar, + optimizationLevel: 2, + platform, + nocomment: true, + nonegate: true, + }; + for (const ign of ignored) + this.add(ign); + } + add(ign) { + // this is a little weird, but it gives us a clean set of optimized + // minimatch matchers, without getting tripped up if one of them + // ends in /** inside a brace section, and it's only inefficient at + // the start of the walk, not along it. + // It'd be nice if the Pattern class just had a .test() method, but + // handling globstars is a bit of a pita, and that code already lives + // in minimatch anyway. + // Another way would be if maybe Minimatch could take its set/globParts + // as an option, and then we could at least just use Pattern to test + // for absolute-ness. + // Yet another way, Minimatch could take an array of glob strings, and + // a cwd option, and do the right thing. + const mm = new minimatch_1.Minimatch(ign, this.mmopts); + for (let i = 0; i < mm.set.length; i++) { + const parsed = mm.set[i]; + const globParts = mm.globParts[i]; + /* c8 ignore start */ + if (!parsed || !globParts) { + throw new Error('invalid pattern object'); + } + // strip off leading ./ portions + // https://github.com/isaacs/node-glob/issues/570 + while (parsed[0] === '.' && globParts[0] === '.') { + parsed.shift(); + globParts.shift(); + } + /* c8 ignore stop */ + const p = new pattern_js_1.Pattern(parsed, globParts, 0, this.platform); + const m = new minimatch_1.Minimatch(p.globString(), this.mmopts); + const children = globParts[globParts.length - 1] === '**'; + const absolute = p.isAbsolute(); + if (absolute) + this.absolute.push(m); + else + this.relative.push(m); + if (children) { + if (absolute) + this.absoluteChildren.push(m); + else + this.relativeChildren.push(m); + } + } + } + ignored(p) { + const fullpath = p.fullpath(); + const fullpaths = `${fullpath}/`; + const relative = p.relative() || '.'; + const relatives = `${relative}/`; + for (const m of this.relative) { + if (m.match(relative) || m.match(relatives)) + return true; + } + for (const m of this.absolute) { + if (m.match(fullpath) || m.match(fullpaths)) + return true; + } + return false; + } + childrenIgnored(p) { + const fullpath = p.fullpath() + '/'; + const relative = (p.relative() || '.') + '/'; + for (const m of this.relativeChildren) { + if (m.match(relative)) + return true; + } + for (const m of this.absoluteChildren) { + if (m.match(fullpath)) + return true; + } + return false; + } +} +exports.Ignore = Ignore; +//# sourceMappingURL=ignore.js.map \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/ignore.js.map b/node_modules/glob/dist/commonjs/ignore.js.map new file mode 100644 index 0000000..d9dfdfa --- /dev/null +++ b/node_modules/glob/dist/commonjs/ignore.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ignore.js","sourceRoot":"","sources":["../../src/ignore.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,kCAAkC;AAClC,kEAAkE;AAClE,6CAA6C;;;AAE7C,yCAAuD;AAEvD,6CAAsC;AAStC,MAAM,eAAe,GACnB,CACE,OAAO,OAAO,KAAK,QAAQ;IAC3B,OAAO;IACP,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,CACrC,CAAC,CAAC;IACD,OAAO,CAAC,QAAQ;IAClB,CAAC,CAAC,OAAO,CAAA;AAEX;;GAEG;AACH,MAAa,MAAM;IACjB,QAAQ,CAAa;IACrB,gBAAgB,CAAa;IAC7B,QAAQ,CAAa;IACrB,gBAAgB,CAAa;IAC7B,QAAQ,CAAiB;IACzB,MAAM,CAAkB;IAExB,YACE,OAAiB,EACjB,EACE,OAAO,EACP,MAA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,CAAC,QAAQ,EAAE,CAAC;YAC9B,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC;gBAAE,OAAO,IAAI,CAAA;QAC1D,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAC9B,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC;gBAAE,OAAO,IAAI,CAAA;QAC1D,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,eAAe,CAAC,CAAO;QACrB,MAAM,QAAQ,GAAG,CAAC,CAAC,QAAQ,EAAE,GAAG,GAAG,CAAA;QACnC,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAC,GAAG,GAAG,CAAA;QAC5C,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;CACF;AAvGD,wBAuGC","sourcesContent":["// 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, MinimatchOptions } 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 add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\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 platform: NodeJS.Platform\n mmopts: MinimatchOptions\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 this.platform = platform\n this.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 for (const ign of ignored) this.add(ign)\n }\n\n add(ign: string) {\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 const mm = new Minimatch(ign, this.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 // strip off leading ./ portions\n // https://github.com/isaacs/node-glob/issues/570\n while (parsed[0] === '.' && globParts[0] === '.') {\n parsed.shift()\n globParts.shift()\n }\n /* c8 ignore stop */\n const p = new Pattern(parsed, globParts, 0, this.platform)\n const m = new Minimatch(p.globString(), this.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 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"]} \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/index.d.ts b/node_modules/glob/dist/commonjs/index.d.ts new file mode 100644 index 0000000..9c326dd --- /dev/null +++ b/node_modules/glob/dist/commonjs/index.d.ts @@ -0,0 +1,97 @@ +import { Minipass } from 'minipass'; +import { Path } from 'path-scurry'; +import type { GlobOptions, GlobOptionsWithFileTypesFalse, GlobOptionsWithFileTypesTrue, GlobOptionsWithFileTypesUnset } from './glob.js'; +import { Glob } from './glob.js'; +export { escape, unescape } from 'minimatch'; +export type { FSOption, Path, WalkOptions, WalkOptionsWithFileTypesTrue, WalkOptionsWithFileTypesUnset, } from 'path-scurry'; +export { Glob } from './glob.js'; +export type { GlobOptions, GlobOptionsWithFileTypesFalse, GlobOptionsWithFileTypesTrue, GlobOptionsWithFileTypesUnset, } from './glob.js'; +export { hasMagic } from './has-magic.js'; +export { Ignore } from './ignore.js'; +export type { IgnoreLike } from './ignore.js'; +export type { MatchStream } from './walker.js'; +/** + * Syncronous form of {@link globStream}. Will read all the matches as fast as + * you consume them, even all in a single tick if you consume them immediately, + * but will still respond to backpressure if they're not consumed immediately. + */ +export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Minipass; +export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Minipass; +export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesUnset): Minipass; +export declare function globStreamSync(pattern: string | string[], options: GlobOptions): Minipass | Minipass; +/** + * Return a stream that emits all the strings or `Path` objects and + * then emits `end` when completed. + */ +export declare function globStream(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Minipass; +export declare function globStream(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Minipass; +export declare function globStream(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Minipass; +export declare function globStream(pattern: string | string[], options: GlobOptions): Minipass | Minipass; +/** + * Synchronous form of {@link glob} + */ +export declare function globSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): string[]; +export declare function globSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Path[]; +export declare function globSync(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): string[]; +export declare function globSync(pattern: string | string[], options: GlobOptions): Path[] | string[]; +/** + * Perform an asynchronous glob search for the pattern(s) specified. Returns + * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the + * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for + * full option descriptions. + */ +declare function glob_(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Promise; +declare function glob_(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Promise; +declare function glob_(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Promise; +declare function glob_(pattern: string | string[], options: GlobOptions): Promise; +/** + * Return a sync iterator for walking glob pattern matches. + */ +export declare function globIterateSync(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Generator; +export declare function globIterateSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Generator; +export declare function globIterateSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Generator; +export declare function globIterateSync(pattern: string | string[], options: GlobOptions): Generator | Generator; +/** + * Return an async iterator for walking glob pattern matches. + */ +export declare function globIterate(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): AsyncGenerator; +export declare function globIterate(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): AsyncGenerator; +export declare function globIterate(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): AsyncGenerator; +export declare function globIterate(pattern: string | string[], options: GlobOptions): AsyncGenerator | AsyncGenerator; +export declare const streamSync: typeof globStreamSync; +export declare const stream: typeof globStream & { + sync: typeof globStreamSync; +}; +export declare const iterateSync: typeof globIterateSync; +export declare const iterate: typeof globIterate & { + sync: typeof globIterateSync; +}; +export declare const sync: typeof globSync & { + stream: typeof globStreamSync; + iterate: typeof globIterateSync; +}; +export declare const glob: typeof glob_ & { + glob: typeof glob_; + globSync: typeof globSync; + sync: typeof globSync & { + stream: typeof globStreamSync; + iterate: typeof globIterateSync; + }; + globStream: typeof globStream; + stream: typeof globStream & { + sync: typeof globStreamSync; + }; + globStreamSync: typeof globStreamSync; + streamSync: typeof globStreamSync; + globIterate: typeof globIterate; + iterate: typeof globIterate & { + sync: typeof globIterateSync; + }; + globIterateSync: typeof globIterateSync; + iterateSync: typeof globIterateSync; + Glob: typeof Glob; + hasMagic: (pattern: string | string[], options?: GlobOptions) => boolean; + escape: (s: string, { windowsPathsNoEscape, }?: Pick) => string; + unescape: (s: string, { windowsPathsNoEscape, }?: Pick) => string; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/index.d.ts.map b/node_modules/glob/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000..5fb3225 --- /dev/null +++ b/node_modules/glob/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,KAAK,EACV,WAAW,EACX,6BAA6B,EAC7B,4BAA4B,EAC5B,6BAA6B,EAC9B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AAE,6BAA6B,GAAG,SAAS,GAClD,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACrC,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,4BAA4B,GACpC,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACnC,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,6BAA6B,GACrC,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AACrC,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,WAAW,GACnB,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;AASxE,eAAO,MAAM,UAAU,uBAAiB,CAAA;AACxC,eAAO,MAAM,MAAM;;CAAsD,CAAA;AACzE,eAAO,MAAM,WAAW,wBAAkB,CAAA;AAC1C,eAAO,MAAM,OAAO;;CAElB,CAAA;AACF,eAAO,MAAM,IAAI;;;CAGf,CAAA;AAEF,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;CAgBf,CAAA"} \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/index.js b/node_modules/glob/dist/commonjs/index.js new file mode 100644 index 0000000..151495d --- /dev/null +++ b/node_modules/glob/dist/commonjs/index.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.glob = exports.sync = exports.iterate = exports.iterateSync = exports.stream = exports.streamSync = exports.Ignore = exports.hasMagic = exports.Glob = exports.unescape = exports.escape = void 0; +exports.globStreamSync = globStreamSync; +exports.globStream = globStream; +exports.globSync = globSync; +exports.globIterateSync = globIterateSync; +exports.globIterate = globIterate; +const minimatch_1 = require("minimatch"); +const glob_js_1 = require("./glob.js"); +const has_magic_js_1 = require("./has-magic.js"); +var minimatch_2 = require("minimatch"); +Object.defineProperty(exports, "escape", { enumerable: true, get: function () { return minimatch_2.escape; } }); +Object.defineProperty(exports, "unescape", { enumerable: true, get: function () { return minimatch_2.unescape; } }); +var glob_js_2 = require("./glob.js"); +Object.defineProperty(exports, "Glob", { enumerable: true, get: function () { return glob_js_2.Glob; } }); +var has_magic_js_2 = require("./has-magic.js"); +Object.defineProperty(exports, "hasMagic", { enumerable: true, get: function () { return has_magic_js_2.hasMagic; } }); +var ignore_js_1 = require("./ignore.js"); +Object.defineProperty(exports, "Ignore", { enumerable: true, get: function () { return ignore_js_1.Ignore; } }); +function globStreamSync(pattern, options = {}) { + return new glob_js_1.Glob(pattern, options).streamSync(); +} +function globStream(pattern, options = {}) { + return new glob_js_1.Glob(pattern, options).stream(); +} +function globSync(pattern, options = {}) { + return new glob_js_1.Glob(pattern, options).walkSync(); +} +async function glob_(pattern, options = {}) { + return new glob_js_1.Glob(pattern, options).walk(); +} +function globIterateSync(pattern, options = {}) { + return new glob_js_1.Glob(pattern, options).iterateSync(); +} +function globIterate(pattern, options = {}) { + return new glob_js_1.Glob(pattern, options).iterate(); +} +// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc +exports.streamSync = globStreamSync; +exports.stream = Object.assign(globStream, { sync: globStreamSync }); +exports.iterateSync = globIterateSync; +exports.iterate = Object.assign(globIterate, { + sync: globIterateSync, +}); +exports.sync = Object.assign(globSync, { + stream: globStreamSync, + iterate: globIterateSync, +}); +exports.glob = Object.assign(glob_, { + glob: glob_, + globSync, + sync: exports.sync, + globStream, + stream: exports.stream, + globStreamSync, + streamSync: exports.streamSync, + globIterate, + iterate: exports.iterate, + globIterateSync, + iterateSync: exports.iterateSync, + Glob: glob_js_1.Glob, + hasMagic: has_magic_js_1.hasMagic, + escape: minimatch_1.escape, + unescape: minimatch_1.unescape, +}); +exports.glob.glob = exports.glob; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/index.js.map b/node_modules/glob/dist/commonjs/index.js.map new file mode 100644 index 0000000..e648b1d --- /dev/null +++ b/node_modules/glob/dist/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAqDA,wCAKC;AAsBD,gCAKC;AAqBD,4BAKC;AAkDD,0CAKC;AAqBD,kCAKC;AAhMD,yCAA4C;AAS5C,uCAAgC;AAChC,iDAAyC;AAEzC,uCAA4C;AAAnC,mGAAA,MAAM,OAAA;AAAE,qGAAA,QAAQ,OAAA;AAQzB,qCAAgC;AAAvB,+FAAA,IAAI,OAAA;AAOb,+CAAyC;AAAhC,wGAAA,QAAQ,OAAA;AACjB,yCAAoC;AAA3B,mGAAA,MAAM,OAAA;AAyBf,SAAgB,cAAc,CAC5B,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,UAAU,EAAE,CAAA;AAChD,CAAC;AAsBD,SAAgB,UAAU,CACxB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,MAAM,EAAE,CAAA;AAC5C,CAAC;AAqBD,SAAgB,QAAQ,CACtB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAA;AAC9C,CAAC;AAwBD,KAAK,UAAU,KAAK,CAClB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,IAAI,EAAE,CAAA;AAC1C,CAAC;AAqBD,SAAgB,eAAe,CAC7B,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,WAAW,EAAE,CAAA;AACjD,CAAC;AAqBD,SAAgB,WAAW,CACzB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,OAAO,EAAE,CAAA;AAC7C,CAAC;AAED,iEAAiE;AACpD,QAAA,UAAU,GAAG,cAAc,CAAA;AAC3B,QAAA,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC,CAAA;AAC5D,QAAA,WAAW,GAAG,eAAe,CAAA;AAC7B,QAAA,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE;IAChD,IAAI,EAAE,eAAe;CACtB,CAAC,CAAA;AACW,QAAA,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE;IAC1C,MAAM,EAAE,cAAc;IACtB,OAAO,EAAE,eAAe;CACzB,CAAC,CAAA;AAEW,QAAA,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE;IACvC,IAAI,EAAE,KAAK;IACX,QAAQ;IACR,IAAI,EAAJ,YAAI;IACJ,UAAU;IACV,MAAM,EAAN,cAAM;IACN,cAAc;IACd,UAAU,EAAV,kBAAU;IACV,WAAW;IACX,OAAO,EAAP,eAAO;IACP,eAAe;IACf,WAAW,EAAX,mBAAW;IACX,IAAI,EAAJ,cAAI;IACJ,QAAQ,EAAR,uBAAQ;IACR,MAAM,EAAN,kBAAM;IACN,QAAQ,EAAR,oBAAQ;CACT,CAAC,CAAA;AACF,YAAI,CAAC,IAAI,GAAG,YAAI,CAAA","sourcesContent":["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\nexport { escape, unescape } from 'minimatch'\nexport type {\n FSOption,\n Path,\n WalkOptions,\n WalkOptionsWithFileTypesTrue,\n WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\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 { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.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\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"]} \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/package.json b/node_modules/glob/dist/commonjs/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/node_modules/glob/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/glob/dist/commonjs/pattern.d.ts b/node_modules/glob/dist/commonjs/pattern.d.ts new file mode 100644 index 0000000..9636df3 --- /dev/null +++ b/node_modules/glob/dist/commonjs/pattern.d.ts @@ -0,0 +1,76 @@ +import { GLOBSTAR } from 'minimatch'; +export type MMPattern = string | RegExp | typeof GLOBSTAR; +export type PatternList = [p: MMPattern, ...rest: MMPattern[]]; +export type UNCPatternList = [ + p0: '', + p1: '', + p2: string, + p3: string, + ...rest: MMPattern[] +]; +export type DrivePatternList = [p0: string, ...rest: MMPattern[]]; +export type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]; +export type GlobList = [p: string, ...rest: string[]]; +/** + * An immutable-ish view on an array of glob parts and their parsed + * results + */ +export declare class Pattern { + #private; + readonly length: number; + constructor(patternList: MMPattern[], globList: string[], index: number, platform: NodeJS.Platform); + /** + * The first entry in the parsed list of patterns + */ + pattern(): MMPattern; + /** + * true of if pattern() returns a string + */ + isString(): boolean; + /** + * true of if pattern() returns GLOBSTAR + */ + isGlobstar(): boolean; + /** + * true if pattern() returns a regexp + */ + isRegExp(): boolean; + /** + * The /-joined set of glob parts that make up this pattern + */ + globString(): string; + /** + * true if there are more pattern parts after this one + */ + hasMore(): boolean; + /** + * The rest of the pattern after this part, or null if this is the end + */ + rest(): Pattern | null; + /** + * true if the pattern represents a //unc/path/ on windows + */ + isUNC(): boolean; + /** + * True if the pattern starts with a drive letter on Windows + */ + isDrive(): boolean; + /** + * True if the pattern is rooted on an absolute path + */ + isAbsolute(): boolean; + /** + * consume the root of the pattern, and return it + */ + root(): string; + /** + * Check to see if the current globstar pattern is allowed to follow + * a symbolic link. + */ + checkFollowGlobstar(): boolean; + /** + * Mark that the current globstar pattern is following a symbolic link + */ + markFollowGlobstar(): boolean; +} +//# sourceMappingURL=pattern.d.ts.map \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/pattern.d.ts.map b/node_modules/glob/dist/commonjs/pattern.d.ts.map new file mode 100644 index 0000000..cdf3223 --- /dev/null +++ b/node_modules/glob/dist/commonjs/pattern.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pattern.d.ts","sourceRoot":"","sources":["../../src/pattern.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,QAAQ,CAAA;AAGzD,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;AAC9D,MAAM,MAAM,cAAc,GAAG;IAC3B,EAAE,EAAE,EAAE;IACN,EAAE,EAAE,EAAE;IACN,EAAE,EAAE,MAAM;IACV,EAAE,EAAE,MAAM;IACV,GAAG,IAAI,EAAE,SAAS,EAAE;CACrB,CAAA;AACD,MAAM,MAAM,gBAAgB,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;AACjE,MAAM,MAAM,mBAAmB,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;AAChE,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,CAAC,CAAA;AAMrD;;;GAGG;AACH,qBAAa,OAAO;;IAIlB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;gBAUrB,WAAW,EAAE,SAAS,EAAE,EACxB,QAAQ,EAAE,MAAM,EAAE,EAClB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,CAAC,QAAQ;IA6D3B;;OAEG;IACH,OAAO,IAAI,SAAS;IAIpB;;OAEG;IACH,QAAQ,IAAI,OAAO;IAGnB;;OAEG;IACH,UAAU,IAAI,OAAO;IAGrB;;OAEG;IACH,QAAQ,IAAI,OAAO;IAInB;;OAEG;IACH,UAAU,IAAI,MAAM;IAUpB;;OAEG;IACH,OAAO,IAAI,OAAO;IAIlB;;OAEG;IACH,IAAI,IAAI,OAAO,GAAG,IAAI;IAetB;;OAEG;IACH,KAAK,IAAI,OAAO;IAoBhB;;OAEG;IACH,OAAO,IAAI,OAAO;IAelB;;OAEG;IACH,UAAU,IAAI,OAAO;IAUrB;;OAEG;IACH,IAAI,IAAI,MAAM;IASd;;;OAGG;IACH,mBAAmB,IAAI,OAAO;IAQ9B;;OAEG;IACH,kBAAkB,IAAI,OAAO;CAM9B"} \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/pattern.js b/node_modules/glob/dist/commonjs/pattern.js new file mode 100644 index 0000000..f0de35f --- /dev/null +++ b/node_modules/glob/dist/commonjs/pattern.js @@ -0,0 +1,219 @@ +"use strict"; +// this is just a very light wrapper around 2 arrays with an offset index +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Pattern = void 0; +const minimatch_1 = require("minimatch"); +const isPatternList = (pl) => pl.length >= 1; +const isGlobList = (gl) => gl.length >= 1; +/** + * An immutable-ish view on an array of glob parts and their parsed + * results + */ +class Pattern { + #patternList; + #globList; + #index; + length; + #platform; + #rest; + #globString; + #isDrive; + #isUNC; + #isAbsolute; + #followGlobstar = true; + constructor(patternList, globList, index, platform) { + if (!isPatternList(patternList)) { + throw new TypeError('empty pattern list'); + } + if (!isGlobList(globList)) { + throw new TypeError('empty glob list'); + } + if (globList.length !== patternList.length) { + throw new TypeError('mismatched pattern list and glob list lengths'); + } + this.length = patternList.length; + if (index < 0 || index >= this.length) { + throw new TypeError('index out of range'); + } + this.#patternList = patternList; + this.#globList = globList; + this.#index = index; + this.#platform = platform; + // normalize root entries of absolute patterns on initial creation. + if (this.#index === 0) { + // c: => ['c:/'] + // C:/ => ['C:/'] + // C:/x => ['C:/', 'x'] + // //host/share => ['//host/share/'] + // //host/share/ => ['//host/share/'] + // //host/share/x => ['//host/share/', 'x'] + // /etc => ['/', 'etc'] + // / => ['/'] + if (this.isUNC()) { + // '' / '' / 'host' / 'share' + const [p0, p1, p2, p3, ...prest] = this.#patternList; + const [g0, g1, g2, g3, ...grest] = this.#globList; + if (prest[0] === '') { + // ends in / + prest.shift(); + grest.shift(); + } + const p = [p0, p1, p2, p3, ''].join('/'); + const g = [g0, g1, g2, g3, ''].join('/'); + this.#patternList = [p, ...prest]; + this.#globList = [g, ...grest]; + this.length = this.#patternList.length; + } + else if (this.isDrive() || this.isAbsolute()) { + const [p1, ...prest] = this.#patternList; + const [g1, ...grest] = this.#globList; + if (prest[0] === '') { + // ends in / + prest.shift(); + grest.shift(); + } + const p = p1 + '/'; + const g = g1 + '/'; + this.#patternList = [p, ...prest]; + this.#globList = [g, ...grest]; + this.length = this.#patternList.length; + } + } + } + /** + * The first entry in the parsed list of patterns + */ + pattern() { + return this.#patternList[this.#index]; + } + /** + * true of if pattern() returns a string + */ + isString() { + return typeof this.#patternList[this.#index] === 'string'; + } + /** + * true of if pattern() returns GLOBSTAR + */ + isGlobstar() { + return this.#patternList[this.#index] === minimatch_1.GLOBSTAR; + } + /** + * true if pattern() returns a regexp + */ + isRegExp() { + return this.#patternList[this.#index] instanceof RegExp; + } + /** + * The /-joined set of glob parts that make up this pattern + */ + globString() { + return (this.#globString = + this.#globString || + (this.#index === 0 ? + this.isAbsolute() ? + this.#globList[0] + this.#globList.slice(1).join('/') + : this.#globList.join('/') + : this.#globList.slice(this.#index).join('/'))); + } + /** + * true if there are more pattern parts after this one + */ + hasMore() { + return this.length > this.#index + 1; + } + /** + * The rest of the pattern after this part, or null if this is the end + */ + rest() { + if (this.#rest !== undefined) + return this.#rest; + if (!this.hasMore()) + return (this.#rest = null); + this.#rest = new Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform); + this.#rest.#isAbsolute = this.#isAbsolute; + this.#rest.#isUNC = this.#isUNC; + this.#rest.#isDrive = this.#isDrive; + return this.#rest; + } + /** + * true if the pattern represents a //unc/path/ on windows + */ + isUNC() { + const pl = this.#patternList; + return this.#isUNC !== undefined ? + this.#isUNC + : (this.#isUNC = + this.#platform === 'win32' && + this.#index === 0 && + pl[0] === '' && + pl[1] === '' && + typeof pl[2] === 'string' && + !!pl[2] && + typeof pl[3] === 'string' && + !!pl[3]); + } + // pattern like C:/... + // split = ['C:', ...] + // XXX: would be nice to handle patterns like `c:*` to test the cwd + // in c: for *, but I don't know of a way to even figure out what that + // cwd is without actually chdir'ing into it? + /** + * True if the pattern starts with a drive letter on Windows + */ + isDrive() { + const pl = this.#patternList; + return this.#isDrive !== undefined ? + this.#isDrive + : (this.#isDrive = + this.#platform === 'win32' && + this.#index === 0 && + this.length > 1 && + typeof pl[0] === 'string' && + /^[a-z]:$/i.test(pl[0])); + } + // pattern = '/' or '/...' or '/x/...' + // split = ['', ''] or ['', ...] or ['', 'x', ...] + // Drive and UNC both considered absolute on windows + /** + * True if the pattern is rooted on an absolute path + */ + isAbsolute() { + const pl = this.#patternList; + return this.#isAbsolute !== undefined ? + this.#isAbsolute + : (this.#isAbsolute = + (pl[0] === '' && pl.length > 1) || + this.isDrive() || + this.isUNC()); + } + /** + * consume the root of the pattern, and return it + */ + root() { + const p = this.#patternList[0]; + return (typeof p === 'string' && this.isAbsolute() && this.#index === 0) ? + p + : ''; + } + /** + * Check to see if the current globstar pattern is allowed to follow + * a symbolic link. + */ + checkFollowGlobstar() { + return !(this.#index === 0 || + !this.isGlobstar() || + !this.#followGlobstar); + } + /** + * Mark that the current globstar pattern is following a symbolic link + */ + markFollowGlobstar() { + if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar) + return false; + this.#followGlobstar = false; + return true; + } +} +exports.Pattern = Pattern; +//# sourceMappingURL=pattern.js.map \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/pattern.js.map b/node_modules/glob/dist/commonjs/pattern.js.map new file mode 100644 index 0000000..fc10ea5 --- /dev/null +++ b/node_modules/glob/dist/commonjs/pattern.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pattern.js","sourceRoot":"","sources":["../../src/pattern.ts"],"names":[],"mappings":";AAAA,yEAAyE;;;AAEzE,yCAAoC;AAgBpC,MAAM,aAAa,GAAG,CAAC,EAAe,EAAqB,EAAE,CAC3D,EAAE,CAAC,MAAM,IAAI,CAAC,CAAA;AAChB,MAAM,UAAU,GAAG,CAAC,EAAY,EAAkB,EAAE,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,CAAA;AAEnE;;;GAGG;AACH,MAAa,OAAO;IACT,YAAY,CAAa;IACzB,SAAS,CAAU;IACnB,MAAM,CAAQ;IACd,MAAM,CAAQ;IACd,SAAS,CAAiB;IACnC,KAAK,CAAiB;IACtB,WAAW,CAAS;IACpB,QAAQ,CAAU;IAClB,MAAM,CAAU;IAChB,WAAW,CAAU;IACrB,eAAe,GAAY,IAAI,CAAA;IAE/B,YACE,WAAwB,EACxB,QAAkB,EAClB,KAAa,EACb,QAAy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B,CAAC,IAAI,CAAC,eAAe,CACtB,CAAA;IACH,CAAC;IAED;;OAEG;IACH,kBAAkB;QAChB,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,IAAI,CAAC,eAAe;YAClE,OAAO,KAAK,CAAA;QACd,IAAI,CAAC,eAAe,GAAG,KAAK,CAAA;QAC5B,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AArOD,0BAqOC","sourcesContent":["// 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 (\n typeof p === 'string' && this.isAbsolute() && this.#index === 0\n ) ?\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"]} \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/processor.d.ts b/node_modules/glob/dist/commonjs/processor.d.ts new file mode 100644 index 0000000..ccedfbf --- /dev/null +++ b/node_modules/glob/dist/commonjs/processor.d.ts @@ -0,0 +1,59 @@ +import { MMRegExp } from 'minimatch'; +import { Path } from 'path-scurry'; +import { Pattern } from './pattern.js'; +import { GlobWalkerOpts } from './walker.js'; +/** + * A cache of which patterns have been processed for a given Path + */ +export declare class HasWalkedCache { + store: Map>; + constructor(store?: Map>); + copy(): HasWalkedCache; + hasWalked(target: Path, pattern: Pattern): boolean | undefined; + storeWalked(target: Path, pattern: Pattern): void; +} +/** + * A record of which paths have been matched in a given walk step, + * and whether they only are considered a match if they are a directory, + * and whether their absolute or relative path should be returned. + */ +export declare class MatchRecord { + store: Map; + add(target: Path, absolute: boolean, ifDir: boolean): void; + entries(): [Path, boolean, boolean][]; +} +/** + * A collection of patterns that must be processed in a subsequent step + * for a given path. + */ +export declare class SubWalks { + store: Map; + add(target: Path, pattern: Pattern): void; + get(target: Path): Pattern[]; + entries(): [Path, Pattern[]][]; + keys(): Path[]; +} +/** + * The class that processes patterns for a given path. + * + * Handles child entry filtering, and determining whether a path's + * directory contents must be read. + */ +export declare class Processor { + hasWalkedCache: HasWalkedCache; + matches: MatchRecord; + subwalks: SubWalks; + patterns?: Pattern[]; + follow: boolean; + dot: boolean; + opts: GlobWalkerOpts; + constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache); + processPatterns(target: Path, patterns: Pattern[]): this; + subwalkTargets(): Path[]; + child(): Processor; + filterEntries(parent: Path, entries: Path[]): Processor; + testGlobstar(e: Path, pattern: Pattern, rest: Pattern | null, absolute: boolean): void; + testRegExp(e: Path, p: MMRegExp, rest: Pattern | null, absolute: boolean): void; + testString(e: Path, p: string, rest: Pattern | null, absolute: boolean): void; +} +//# sourceMappingURL=processor.d.ts.map \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/processor.d.ts.map b/node_modules/glob/dist/commonjs/processor.d.ts.map new file mode 100644 index 0000000..aa266fe --- /dev/null +++ b/node_modules/glob/dist/commonjs/processor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"processor.d.ts","sourceRoot":"","sources":["../../src/processor.ts"],"names":[],"mappings":"AAEA,OAAO,EAAY,QAAQ,EAAE,MAAM,WAAW,CAAA;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAa,OAAO,EAAE,MAAM,cAAc,CAAA;AACjD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C;;GAEG;AACH,qBAAa,cAAc;IACzB,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAA;gBACnB,KAAK,GAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAa;IAGvD,IAAI;IAGJ,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;IAGxC,WAAW,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;CAM3C;AAED;;;;GAIG;AACH,qBAAa,WAAW;IACtB,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAY;IACpC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO;IAMnD,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE;CAOtC;AAED;;;GAGG;AACH,qBAAa,QAAQ;IACnB,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAY;IACvC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;IAWlC,GAAG,CAAC,MAAM,EAAE,IAAI,GAAG,OAAO,EAAE;IAS5B,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE;IAG9B,IAAI,IAAI,IAAI,EAAE;CAGf;AAED;;;;;GAKG;AACH,qBAAa,SAAS;IACpB,cAAc,EAAE,cAAc,CAAA;IAC9B,OAAO,cAAoB;IAC3B,QAAQ,WAAiB;IACzB,QAAQ,CAAC,EAAE,OAAO,EAAE,CAAA;IACpB,MAAM,EAAE,OAAO,CAAA;IACf,GAAG,EAAE,OAAO,CAAA;IACZ,IAAI,EAAE,cAAc,CAAA;gBAER,IAAI,EAAE,cAAc,EAAE,cAAc,CAAC,EAAE,cAAc;IAQjE,eAAe,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE;IAmGjD,cAAc,IAAI,IAAI,EAAE;IAIxB,KAAK;IAQL,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,SAAS;IAqBvD,YAAY,CACV,CAAC,EAAE,IAAI,EACP,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,OAAO,GAAG,IAAI,EACpB,QAAQ,EAAE,OAAO;IA8CnB,UAAU,CACR,CAAC,EAAE,IAAI,EACP,CAAC,EAAE,QAAQ,EACX,IAAI,EAAE,OAAO,GAAG,IAAI,EACpB,QAAQ,EAAE,OAAO;IAUnB,UAAU,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,IAAI,EAAE,QAAQ,EAAE,OAAO;CASvE"} \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/processor.js b/node_modules/glob/dist/commonjs/processor.js new file mode 100644 index 0000000..ee3bb43 --- /dev/null +++ b/node_modules/glob/dist/commonjs/processor.js @@ -0,0 +1,301 @@ +"use strict"; +// synchronous utility for filtering entries and calculating subwalks +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Processor = exports.SubWalks = exports.MatchRecord = exports.HasWalkedCache = void 0; +const minimatch_1 = require("minimatch"); +/** + * A cache of which patterns have been processed for a given Path + */ +class HasWalkedCache { + store; + constructor(store = new Map()) { + this.store = store; + } + copy() { + return new HasWalkedCache(new Map(this.store)); + } + hasWalked(target, pattern) { + return this.store.get(target.fullpath())?.has(pattern.globString()); + } + storeWalked(target, pattern) { + const fullpath = target.fullpath(); + const cached = this.store.get(fullpath); + if (cached) + cached.add(pattern.globString()); + else + this.store.set(fullpath, new Set([pattern.globString()])); + } +} +exports.HasWalkedCache = HasWalkedCache; +/** + * A record of which paths have been matched in a given walk step, + * and whether they only are considered a match if they are a directory, + * and whether their absolute or relative path should be returned. + */ +class MatchRecord { + store = new Map(); + add(target, absolute, ifDir) { + const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0); + const current = this.store.get(target); + this.store.set(target, current === undefined ? n : n & current); + } + // match, absolute, ifdir + entries() { + return [...this.store.entries()].map(([path, n]) => [ + path, + !!(n & 2), + !!(n & 1), + ]); + } +} +exports.MatchRecord = MatchRecord; +/** + * A collection of patterns that must be processed in a subsequent step + * for a given path. + */ +class SubWalks { + store = new Map(); + add(target, pattern) { + if (!target.canReaddir()) { + return; + } + const subs = this.store.get(target); + if (subs) { + if (!subs.find(p => p.globString() === pattern.globString())) { + subs.push(pattern); + } + } + else + this.store.set(target, [pattern]); + } + get(target) { + const subs = this.store.get(target); + /* c8 ignore start */ + if (!subs) { + throw new Error('attempting to walk unknown path'); + } + /* c8 ignore stop */ + return subs; + } + entries() { + return this.keys().map(k => [k, this.store.get(k)]); + } + keys() { + return [...this.store.keys()].filter(t => t.canReaddir()); + } +} +exports.SubWalks = SubWalks; +/** + * The class that processes patterns for a given path. + * + * Handles child entry filtering, and determining whether a path's + * directory contents must be read. + */ +class Processor { + hasWalkedCache; + matches = new MatchRecord(); + subwalks = new SubWalks(); + patterns; + follow; + dot; + opts; + constructor(opts, hasWalkedCache) { + this.opts = opts; + this.follow = !!opts.follow; + this.dot = !!opts.dot; + this.hasWalkedCache = + hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache(); + } + processPatterns(target, patterns) { + this.patterns = patterns; + const processingSet = patterns.map(p => [target, p]); + // map of paths to the magic-starting subwalks they need to walk + // first item in patterns is the filter + for (let [t, pattern] of processingSet) { + this.hasWalkedCache.storeWalked(t, pattern); + const root = pattern.root(); + const absolute = pattern.isAbsolute() && this.opts.absolute !== false; + // start absolute patterns at root + if (root) { + t = t.resolve(root === '/' && this.opts.root !== undefined ? + this.opts.root + : root); + const rest = pattern.rest(); + if (!rest) { + this.matches.add(t, true, false); + continue; + } + else { + pattern = rest; + } + } + if (t.isENOENT()) + continue; + let p; + let rest; + let changed = false; + while (typeof (p = pattern.pattern()) === 'string' && + (rest = pattern.rest())) { + const c = t.resolve(p); + t = c; + pattern = rest; + changed = true; + } + p = pattern.pattern(); + rest = pattern.rest(); + if (changed) { + if (this.hasWalkedCache.hasWalked(t, pattern)) + continue; + this.hasWalkedCache.storeWalked(t, pattern); + } + // now we have either a final string for a known entry, + // more strings for an unknown entry, + // or a pattern starting with magic, mounted on t. + if (typeof p === 'string') { + // must not be final entry, otherwise we would have + // concatenated it earlier. + const ifDir = p === '..' || p === '' || p === '.'; + this.matches.add(t.resolve(p), absolute, ifDir); + continue; + } + else if (p === minimatch_1.GLOBSTAR) { + // if no rest, match and subwalk pattern + // if rest, process rest and subwalk pattern + // if it's a symlink, but we didn't get here by way of a + // globstar match (meaning it's the first time THIS globstar + // has traversed a symlink), then we follow it. Otherwise, stop. + if (!t.isSymbolicLink() || + this.follow || + pattern.checkFollowGlobstar()) { + this.subwalks.add(t, pattern); + } + const rp = rest?.pattern(); + const rrest = rest?.rest(); + if (!rest || ((rp === '' || rp === '.') && !rrest)) { + // only HAS to be a dir if it ends in **/ or **/. + // but ending in ** will match files as well. + this.matches.add(t, absolute, rp === '' || rp === '.'); + } + else { + if (rp === '..') { + // this would mean you're matching **/.. at the fs root, + // and no thanks, I'm not gonna test that specific case. + /* c8 ignore start */ + const tp = t.parent || t; + /* c8 ignore stop */ + if (!rrest) + this.matches.add(tp, absolute, true); + else if (!this.hasWalkedCache.hasWalked(tp, rrest)) { + this.subwalks.add(tp, rrest); + } + } + } + } + else if (p instanceof RegExp) { + this.subwalks.add(t, pattern); + } + } + return this; + } + subwalkTargets() { + return this.subwalks.keys(); + } + child() { + return new Processor(this.opts, this.hasWalkedCache); + } + // return a new Processor containing the subwalks for each + // child entry, and a set of matches, and + // a hasWalkedCache that's a copy of this one + // then we're going to call + filterEntries(parent, entries) { + const patterns = this.subwalks.get(parent); + // put matches and entry walks into the results processor + const results = this.child(); + for (const e of entries) { + for (const pattern of patterns) { + const absolute = pattern.isAbsolute(); + const p = pattern.pattern(); + const rest = pattern.rest(); + if (p === minimatch_1.GLOBSTAR) { + results.testGlobstar(e, pattern, rest, absolute); + } + else if (p instanceof RegExp) { + results.testRegExp(e, p, rest, absolute); + } + else { + results.testString(e, p, rest, absolute); + } + } + } + return results; + } + testGlobstar(e, pattern, rest, absolute) { + if (this.dot || !e.name.startsWith('.')) { + if (!pattern.hasMore()) { + this.matches.add(e, absolute, false); + } + if (e.canReaddir()) { + // if we're in follow mode or it's not a symlink, just keep + // testing the same pattern. If there's more after the globstar, + // then this symlink consumes the globstar. If not, then we can + // follow at most ONE symlink along the way, so we mark it, which + // also checks to ensure that it wasn't already marked. + if (this.follow || !e.isSymbolicLink()) { + this.subwalks.add(e, pattern); + } + else if (e.isSymbolicLink()) { + if (rest && pattern.checkFollowGlobstar()) { + this.subwalks.add(e, rest); + } + else if (pattern.markFollowGlobstar()) { + this.subwalks.add(e, pattern); + } + } + } + } + // if the NEXT thing matches this entry, then also add + // the rest. + if (rest) { + const rp = rest.pattern(); + if (typeof rp === 'string' && + // dots and empty were handled already + rp !== '..' && + rp !== '' && + rp !== '.') { + this.testString(e, rp, rest.rest(), absolute); + } + else if (rp === '..') { + /* c8 ignore start */ + const ep = e.parent || e; + /* c8 ignore stop */ + this.subwalks.add(ep, rest); + } + else if (rp instanceof RegExp) { + this.testRegExp(e, rp, rest.rest(), absolute); + } + } + } + testRegExp(e, p, rest, absolute) { + if (!p.test(e.name)) + return; + if (!rest) { + this.matches.add(e, absolute, false); + } + else { + this.subwalks.add(e, rest); + } + } + testString(e, p, rest, absolute) { + // should never happen? + if (!e.isNamed(p)) + return; + if (!rest) { + this.matches.add(e, absolute, false); + } + else { + this.subwalks.add(e, rest); + } + } +} +exports.Processor = Processor; +//# sourceMappingURL=processor.js.map \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/processor.js.map b/node_modules/glob/dist/commonjs/processor.js.map new file mode 100644 index 0000000..58a7088 --- /dev/null +++ b/node_modules/glob/dist/commonjs/processor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"processor.js","sourceRoot":"","sources":["../../src/processor.ts"],"names":[],"mappings":";AAAA,qEAAqE;;;AAErE,yCAA8C;AAK9C;;GAEG;AACH,MAAa,cAAc;IACzB,KAAK,CAA0B;IAC/B,YAAY,QAAkC,IAAI,GAAG,EAAE;QACrD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;IACD,IAAI;QACF,OAAO,IAAI,cAAc,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAA;IAChD,CAAC;IACD,SAAS,CAAC,MAAY,EAAE,OAAgB;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAA;IACrE,CAAC;IACD,WAAW,CAAC,MAAY,EAAE,OAAgB;QACxC,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAA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AAU,CAAC,CAAO,EAAE,CAAS,EAAE,IAAoB,EAAE,QAAiB;QACpE,uBAAuB;QACvB,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;YAAE,OAAM;QACzB,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACtC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;CACF;AA9ND,8BA8NC","sourcesContent":["// 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 =\n hasWalkedCache ? hasWalkedCache.copy() : 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"]} \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/walker.d.ts b/node_modules/glob/dist/commonjs/walker.d.ts new file mode 100644 index 0000000..499c8f4 --- /dev/null +++ b/node_modules/glob/dist/commonjs/walker.d.ts @@ -0,0 +1,97 @@ +/** + * Single-use utility classes to provide functionality to the {@link Glob} + * methods. + * + * @module + */ +import { Minipass } from 'minipass'; +import { Path } from 'path-scurry'; +import { IgnoreLike } from './ignore.js'; +import { Pattern } from './pattern.js'; +import { Processor } from './processor.js'; +export interface GlobWalkerOpts { + absolute?: boolean; + allowWindowsEscape?: boolean; + cwd?: string | URL; + dot?: boolean; + dotRelative?: boolean; + follow?: boolean; + ignore?: string | string[] | IgnoreLike; + mark?: boolean; + matchBase?: boolean; + maxDepth?: number; + nobrace?: boolean; + nocase?: boolean; + nodir?: boolean; + noext?: boolean; + noglobstar?: boolean; + platform?: NodeJS.Platform; + posix?: boolean; + realpath?: boolean; + root?: string; + stat?: boolean; + signal?: AbortSignal; + windowsPathsNoEscape?: boolean; + withFileTypes?: boolean; + includeChildMatches?: boolean; +} +export type GWOFileTypesTrue = GlobWalkerOpts & { + withFileTypes: true; +}; +export type GWOFileTypesFalse = GlobWalkerOpts & { + withFileTypes: false; +}; +export type GWOFileTypesUnset = GlobWalkerOpts & { + withFileTypes?: undefined; +}; +export type Result = O extends GWOFileTypesTrue ? Path : O extends GWOFileTypesFalse ? string : O extends GWOFileTypesUnset ? string : Path | string; +export type Matches = O extends GWOFileTypesTrue ? Set : O extends GWOFileTypesFalse ? Set : O extends GWOFileTypesUnset ? Set : Set; +export type MatchStream = Minipass, Result>; +/** + * basic walking utilities that all the glob walker types use + */ +export declare abstract class GlobUtil { + #private; + path: Path; + patterns: Pattern[]; + opts: O; + seen: Set; + paused: boolean; + aborted: boolean; + signal?: AbortSignal; + maxDepth: number; + includeChildMatches: boolean; + constructor(patterns: Pattern[], path: Path, opts: O); + pause(): void; + resume(): void; + onResume(fn: () => any): void; + matchCheck(e: Path, ifDir: boolean): Promise; + matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined; + matchCheckSync(e: Path, ifDir: boolean): Path | undefined; + abstract matchEmit(p: Result): void; + abstract matchEmit(p: string | Path): void; + matchFinish(e: Path, absolute: boolean): void; + match(e: Path, absolute: boolean, ifDir: boolean): Promise; + matchSync(e: Path, absolute: boolean, ifDir: boolean): void; + walkCB(target: Path, patterns: Pattern[], cb: () => any): void; + walkCB2(target: Path, patterns: Pattern[], processor: Processor, cb: () => any): any; + walkCB3(target: Path, entries: Path[], processor: Processor, cb: () => any): void; + walkCBSync(target: Path, patterns: Pattern[], cb: () => any): void; + walkCB2Sync(target: Path, patterns: Pattern[], processor: Processor, cb: () => any): any; + walkCB3Sync(target: Path, entries: Path[], processor: Processor, cb: () => any): void; +} +export declare class GlobWalker extends GlobUtil { + matches: Set>; + constructor(patterns: Pattern[], path: Path, opts: O); + matchEmit(e: Result): void; + walk(): Promise>>; + walkSync(): Set>; +} +export declare class GlobStream extends GlobUtil { + results: Minipass, Result>; + constructor(patterns: Pattern[], path: Path, opts: O); + matchEmit(e: Result): void; + stream(): MatchStream; + streamSync(): MatchStream; +} +//# sourceMappingURL=walker.d.ts.map \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/walker.d.ts.map b/node_modules/glob/dist/commonjs/walker.d.ts.map new file mode 100644 index 0000000..769957b --- /dev/null +++ b/node_modules/glob/dist/commonjs/walker.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"walker.d.ts","sourceRoot":"","sources":["../../src/walker.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAU,UAAU,EAAE,MAAM,aAAa,CAAA;AAOhD,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SAAS,EACpB,EAAE,EAAE,MAAM,GAAG;IAqCf,WAAW,CACT,MAAM,EAAE,IAAI,EACZ,OAAO,EAAE,IAAI,EAAE,EACf,SAAS,EAAE,SAAS,EACpB,EAAE,EAAE,MAAM,GAAG;CAoBhB;AAED,qBAAa,UAAU,CACrB,CAAC,SAAS,cAAc,GAAG,cAAc,CACzC,SAAQ,QAAQ,CAAC,CAAC,CAAC;IACnB,OAAO,iBAAuB;gBAElB,QAAQ,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAIpD,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI;IAIvB,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IAiBrC,QAAQ,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;CAW3B;AAED,qBAAa,UAAU,CACrB,CAAC,SAAS,cAAc,GAAG,cAAc,CACzC,SAAQ,QAAQ,CAAC,CAAC,CAAC;IACnB,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;gBAE3B,QAAQ,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAUpD,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI;IAK7B,MAAM,IAAI,WAAW,CAAC,CAAC,CAAC;IAYxB,UAAU,IAAI,WAAW,CAAC,CAAC,CAAC;CAO7B"} \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/walker.js b/node_modules/glob/dist/commonjs/walker.js new file mode 100644 index 0000000..cb15946 --- /dev/null +++ b/node_modules/glob/dist/commonjs/walker.js @@ -0,0 +1,387 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GlobStream = exports.GlobWalker = exports.GlobUtil = void 0; +/** + * Single-use utility classes to provide functionality to the {@link Glob} + * methods. + * + * @module + */ +const minipass_1 = require("minipass"); +const ignore_js_1 = require("./ignore.js"); +const processor_js_1 = require("./processor.js"); +const makeIgnore = (ignore, opts) => typeof ignore === 'string' ? new ignore_js_1.Ignore([ignore], opts) + : Array.isArray(ignore) ? new ignore_js_1.Ignore(ignore, opts) + : ignore; +/** + * basic walking utilities that all the glob walker types use + */ +class GlobUtil { + path; + patterns; + opts; + seen = new Set(); + paused = false; + aborted = false; + #onResume = []; + #ignore; + #sep; + signal; + maxDepth; + includeChildMatches; + constructor(patterns, path, opts) { + this.patterns = patterns; + this.path = path; + this.opts = opts; + this.#sep = !opts.posix && opts.platform === 'win32' ? '\\' : '/'; + this.includeChildMatches = opts.includeChildMatches !== false; + if (opts.ignore || !this.includeChildMatches) { + this.#ignore = makeIgnore(opts.ignore ?? [], opts); + if (!this.includeChildMatches && + typeof this.#ignore.add !== 'function') { + const m = 'cannot ignore child matches, ignore lacks add() method.'; + throw new Error(m); + } + } + // ignore, always set with maxDepth, but it's optional on the + // GlobOptions type + /* c8 ignore start */ + this.maxDepth = opts.maxDepth || Infinity; + /* c8 ignore stop */ + if (opts.signal) { + this.signal = opts.signal; + this.signal.addEventListener('abort', () => { + this.#onResume.length = 0; + }); + } + } + #ignored(path) { + return this.seen.has(path) || !!this.#ignore?.ignored?.(path); + } + #childrenIgnored(path) { + return !!this.#ignore?.childrenIgnored?.(path); + } + // backpressure mechanism + pause() { + this.paused = true; + } + resume() { + /* c8 ignore start */ + if (this.signal?.aborted) + return; + /* c8 ignore stop */ + this.paused = false; + let fn = undefined; + while (!this.paused && (fn = this.#onResume.shift())) { + fn(); + } + } + onResume(fn) { + if (this.signal?.aborted) + return; + /* c8 ignore start */ + if (!this.paused) { + fn(); + } + else { + /* c8 ignore stop */ + this.#onResume.push(fn); + } + } + // do the requisite realpath/stat checking, and return the path + // to add or undefined to filter it out. + async matchCheck(e, ifDir) { + if (ifDir && this.opts.nodir) + return undefined; + let rpc; + if (this.opts.realpath) { + rpc = e.realpathCached() || (await e.realpath()); + if (!rpc) + return undefined; + e = rpc; + } + const needStat = e.isUnknown() || this.opts.stat; + const s = needStat ? await e.lstat() : e; + if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) { + const target = await s.realpath(); + /* c8 ignore start */ + if (target && (target.isUnknown() || this.opts.stat)) { + await target.lstat(); + } + /* c8 ignore stop */ + } + return this.matchCheckTest(s, ifDir); + } + matchCheckTest(e, ifDir) { + return (e && + (this.maxDepth === Infinity || e.depth() <= this.maxDepth) && + (!ifDir || e.canReaddir()) && + (!this.opts.nodir || !e.isDirectory()) && + (!this.opts.nodir || + !this.opts.follow || + !e.isSymbolicLink() || + !e.realpathCached()?.isDirectory()) && + !this.#ignored(e)) ? + e + : undefined; + } + matchCheckSync(e, ifDir) { + if (ifDir && this.opts.nodir) + return undefined; + let rpc; + if (this.opts.realpath) { + rpc = e.realpathCached() || e.realpathSync(); + if (!rpc) + return undefined; + e = rpc; + } + const needStat = e.isUnknown() || this.opts.stat; + const s = needStat ? e.lstatSync() : e; + if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) { + const target = s.realpathSync(); + if (target && (target?.isUnknown() || this.opts.stat)) { + target.lstatSync(); + } + } + return this.matchCheckTest(s, ifDir); + } + matchFinish(e, absolute) { + if (this.#ignored(e)) + return; + // we know we have an ignore if this is false, but TS doesn't + if (!this.includeChildMatches && this.#ignore?.add) { + const ign = `${e.relativePosix()}/**`; + this.#ignore.add(ign); + } + const abs = this.opts.absolute === undefined ? absolute : this.opts.absolute; + this.seen.add(e); + const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''; + // ok, we have what we need! + if (this.opts.withFileTypes) { + this.matchEmit(e); + } + else if (abs) { + const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath(); + this.matchEmit(abs + mark); + } + else { + const rel = this.opts.posix ? e.relativePosix() : e.relative(); + const pre = this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ? + '.' + this.#sep + : ''; + this.matchEmit(!rel ? '.' + mark : pre + rel + mark); + } + } + async match(e, absolute, ifDir) { + const p = await this.matchCheck(e, ifDir); + if (p) + this.matchFinish(p, absolute); + } + matchSync(e, absolute, ifDir) { + const p = this.matchCheckSync(e, ifDir); + if (p) + this.matchFinish(p, absolute); + } + walkCB(target, patterns, cb) { + /* c8 ignore start */ + if (this.signal?.aborted) + cb(); + /* c8 ignore stop */ + this.walkCB2(target, patterns, new processor_js_1.Processor(this.opts), cb); + } + walkCB2(target, patterns, processor, cb) { + if (this.#childrenIgnored(target)) + return cb(); + if (this.signal?.aborted) + cb(); + if (this.paused) { + this.onResume(() => this.walkCB2(target, patterns, processor, cb)); + return; + } + processor.processPatterns(target, patterns); + // done processing. all of the above is sync, can be abstracted out. + // subwalks is a map of paths to the entry filters they need + // matches is a map of paths to [absolute, ifDir] tuples. + let tasks = 1; + const next = () => { + if (--tasks === 0) + cb(); + }; + for (const [m, absolute, ifDir] of processor.matches.entries()) { + if (this.#ignored(m)) + continue; + tasks++; + this.match(m, absolute, ifDir).then(() => next()); + } + for (const t of processor.subwalkTargets()) { + if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) { + continue; + } + tasks++; + const childrenCached = t.readdirCached(); + if (t.calledReaddir()) + this.walkCB3(t, childrenCached, processor, next); + else { + t.readdirCB((_, entries) => this.walkCB3(t, entries, processor, next), true); + } + } + next(); + } + walkCB3(target, entries, processor, cb) { + processor = processor.filterEntries(target, entries); + let tasks = 1; + const next = () => { + if (--tasks === 0) + cb(); + }; + for (const [m, absolute, ifDir] of processor.matches.entries()) { + if (this.#ignored(m)) + continue; + tasks++; + this.match(m, absolute, ifDir).then(() => next()); + } + for (const [target, patterns] of processor.subwalks.entries()) { + tasks++; + this.walkCB2(target, patterns, processor.child(), next); + } + next(); + } + walkCBSync(target, patterns, cb) { + /* c8 ignore start */ + if (this.signal?.aborted) + cb(); + /* c8 ignore stop */ + this.walkCB2Sync(target, patterns, new processor_js_1.Processor(this.opts), cb); + } + walkCB2Sync(target, patterns, processor, cb) { + if (this.#childrenIgnored(target)) + return cb(); + if (this.signal?.aborted) + cb(); + if (this.paused) { + this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb)); + return; + } + processor.processPatterns(target, patterns); + // done processing. all of the above is sync, can be abstracted out. + // subwalks is a map of paths to the entry filters they need + // matches is a map of paths to [absolute, ifDir] tuples. + let tasks = 1; + const next = () => { + if (--tasks === 0) + cb(); + }; + for (const [m, absolute, ifDir] of processor.matches.entries()) { + if (this.#ignored(m)) + continue; + this.matchSync(m, absolute, ifDir); + } + for (const t of processor.subwalkTargets()) { + if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) { + continue; + } + tasks++; + const children = t.readdirSync(); + this.walkCB3Sync(t, children, processor, next); + } + next(); + } + walkCB3Sync(target, entries, processor, cb) { + processor = processor.filterEntries(target, entries); + let tasks = 1; + const next = () => { + if (--tasks === 0) + cb(); + }; + for (const [m, absolute, ifDir] of processor.matches.entries()) { + if (this.#ignored(m)) + continue; + this.matchSync(m, absolute, ifDir); + } + for (const [target, patterns] of processor.subwalks.entries()) { + tasks++; + this.walkCB2Sync(target, patterns, processor.child(), next); + } + next(); + } +} +exports.GlobUtil = GlobUtil; +class GlobWalker extends GlobUtil { + matches = new Set(); + constructor(patterns, path, opts) { + super(patterns, path, opts); + } + matchEmit(e) { + this.matches.add(e); + } + async walk() { + if (this.signal?.aborted) + throw this.signal.reason; + if (this.path.isUnknown()) { + await this.path.lstat(); + } + await new Promise((res, rej) => { + this.walkCB(this.path, this.patterns, () => { + if (this.signal?.aborted) { + rej(this.signal.reason); + } + else { + res(this.matches); + } + }); + }); + return this.matches; + } + walkSync() { + if (this.signal?.aborted) + throw this.signal.reason; + if (this.path.isUnknown()) { + this.path.lstatSync(); + } + // nothing for the callback to do, because this never pauses + this.walkCBSync(this.path, this.patterns, () => { + if (this.signal?.aborted) + throw this.signal.reason; + }); + return this.matches; + } +} +exports.GlobWalker = GlobWalker; +class GlobStream extends GlobUtil { + results; + constructor(patterns, path, opts) { + super(patterns, path, opts); + this.results = new minipass_1.Minipass({ + signal: this.signal, + objectMode: true, + }); + this.results.on('drain', () => this.resume()); + this.results.on('resume', () => this.resume()); + } + matchEmit(e) { + this.results.write(e); + if (!this.results.flowing) + this.pause(); + } + stream() { + const target = this.path; + if (target.isUnknown()) { + target.lstat().then(() => { + this.walkCB(target, this.patterns, () => this.results.end()); + }); + } + else { + this.walkCB(target, this.patterns, () => this.results.end()); + } + return this.results; + } + streamSync() { + if (this.path.isUnknown()) { + this.path.lstatSync(); + } + this.walkCBSync(this.path, this.patterns, () => this.results.end()); + return this.results; + } +} +exports.GlobStream = GlobStream; +//# sourceMappingURL=walker.js.map \ No newline at end of file diff --git a/node_modules/glob/dist/commonjs/walker.js.map b/node_modules/glob/dist/commonjs/walker.js.map new file mode 100644 index 0000000..49b0138 --- /dev/null +++ b/node_modules/glob/dist/commonjs/walker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"walker.js","sourceRoot":"","sources":["../../src/walker.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACH,uCAAmC;AAEnC,2CAAgD;AAQhD,iDAA0C;AA0D1C,MAAM,UAAU,GAAG,CACjB,MAAsC,EACtC,IAAoB,EACR,EAAE,CACd,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,kBAAM,CAAC,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC;IACvD,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,kBAAM,CAAC,MAAM,EAAE,IAAI,CAAC;QAClD,CAAC,CAAC,MAAM,CAAA;AAEV;;GAEG;AACH,MAAsB,QAAQ;IAC5B,IAAI,CAAM;IACV,QAAQ,CAAW;IACnB,IAAI,CAAG;IACP,IAAI,GAAc,IAAI,GAAG,EAAQ,CAAA;IACjC,MAAM,GAAY,KAAK,CAAA;IACvB,OAAO,GAAY,KAAK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QACJ,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAA;QACxB,IAAI,MAAM,CAAC,SAAS,EAAE,EAAE,CAAC;YACvB,MAAM,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE;gBACvB,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;YAC9D,CAAC,CAAC,CAAA;QACJ,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;QAC9D,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;IAED,UAAU;QACR,IAAI,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;YAC1B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAA;QACvB,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;QACnE,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;CACF;AAvCD,gCAuCC","sourcesContent":["/**\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 includeChildMatches?: 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 =\n O extends GWOFileTypesTrue ? Path\n : O extends GWOFileTypesFalse ? string\n : O extends GWOFileTypesUnset ? string\n : Path | string\n\nexport type Matches =\n O extends GWOFileTypesTrue ? Set\n : O extends GWOFileTypesFalse ? Set\n : O extends GWOFileTypesUnset ? Set\n : Set\n\nexport type MatchStream = Minipass<\n Result,\n Result\n>\n\nconst makeIgnore = (\n ignore: string | string[] | IgnoreLike,\n opts: GlobWalkerOpts,\n): IgnoreLike =>\n typeof ignore === 'string' ? new Ignore([ignore], opts)\n : Array.isArray(ignore) ? 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 includeChildMatches: boolean\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 this.includeChildMatches = opts.includeChildMatches !== false\n if (opts.ignore || !this.includeChildMatches) {\n this.#ignore = makeIgnore(opts.ignore ?? [], opts)\n if (\n !this.includeChildMatches &&\n typeof this.#ignore.add !== 'function'\n ) {\n const m = 'cannot ignore child matches, ignore lacks add() method.'\n throw new Error(m)\n }\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 const s = needStat ? await e.lstat() : e\n if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n const target = await s.realpath()\n /* c8 ignore start */\n if (target && (target.isUnknown() || this.opts.stat)) {\n await target.lstat()\n }\n /* c8 ignore stop */\n }\n return this.matchCheckTest(s, ifDir)\n }\n\n matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n return (\n e &&\n (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n (!ifDir || e.canReaddir()) &&\n (!this.opts.nodir || !e.isDirectory()) &&\n (!this.opts.nodir ||\n !this.opts.follow ||\n !e.isSymbolicLink() ||\n !e.realpathCached()?.isDirectory()) &&\n !this.#ignored(e)\n ) ?\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 const s = needStat ? e.lstatSync() : e\n if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n const target = s.realpathSync()\n if (target && (target?.isUnknown() || this.opts.stat)) {\n target.lstatSync()\n }\n }\n return this.matchCheckTest(s, 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 // we know we have an ignore if this is false, but TS doesn't\n if (!this.includeChildMatches && this.#ignore?.add) {\n const ign = `${e.relativePosix()}/**`\n this.#ignore.add(ign)\n }\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 = new Set>()\n\n constructor(patterns: Pattern[], path: Path, opts: O) {\n super(patterns, path, opts)\n }\n\n matchEmit(e: Result): 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(): Set> {\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: Minipass, Result>\n\n constructor(patterns: Pattern[], path: Path, opts: O) {\n super(patterns, path, opts)\n this.results = new Minipass, Result>({\n signal: this.signal,\n objectMode: true,\n })\n this.results.on('drain', () => this.resume())\n this.results.on('resume', () => this.resume())\n }\n\n matchEmit(e: Result): 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"]} \ No newline at end of file diff --git a/node_modules/glob/dist/esm/bin.d.mts b/node_modules/glob/dist/esm/bin.d.mts new file mode 100644 index 0000000..77298e4 --- /dev/null +++ b/node_modules/glob/dist/esm/bin.d.mts @@ -0,0 +1,3 @@ +#!/usr/bin/env node +export {}; +//# sourceMappingURL=bin.d.mts.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/bin.d.mts.map b/node_modules/glob/dist/esm/bin.d.mts.map new file mode 100644 index 0000000..ec64bdd --- /dev/null +++ b/node_modules/glob/dist/esm/bin.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"bin.d.mts","sourceRoot":"","sources":["../../src/bin.mts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/glob/dist/esm/bin.mjs b/node_modules/glob/dist/esm/bin.mjs new file mode 100644 index 0000000..5c7bf1e --- /dev/null +++ b/node_modules/glob/dist/esm/bin.mjs @@ -0,0 +1,270 @@ +#!/usr/bin/env node +import { foregroundChild } from 'foreground-child'; +import { existsSync } from 'fs'; +import { jack } from 'jackspeak'; +import { loadPackageJson } from 'package-json-from-dist'; +import { join } from 'path'; +import { globStream } from './index.js'; +const { version } = loadPackageJson(import.meta.url, '../package.json'); +const j = jack({ + usage: 'glob [options] [ [ ...]]', +}) + .description(` + Glob v${version} + + Expand the positional glob expression arguments into any matching file + system paths found. + `) + .opt({ + cmd: { + short: 'c', + hint: 'command', + description: `Run the command provided, passing the glob expression + matches as arguments.`, + }, +}) + .opt({ + default: { + short: 'p', + hint: 'pattern', + description: `If no positional arguments are provided, glob will use + this pattern`, + }, +}) + .flag({ + all: { + short: 'A', + description: `By default, the glob cli command will not expand any + arguments that are an exact match to a file on disk. + + This prevents double-expanding, in case the shell expands + an argument whose filename is a glob expression. + + For example, if 'app/*.ts' would match 'app/[id].ts', then + on Windows powershell or cmd.exe, 'glob app/*.ts' will + expand to 'app/[id].ts', as expected. However, in posix + shells such as bash or zsh, the shell will first expand + 'app/*.ts' to a list of filenames. Then glob will look + for a file matching 'app/[id].ts' (ie, 'app/i.ts' or + 'app/d.ts'), which is unexpected. + + Setting '--all' prevents this behavior, causing glob + to treat ALL patterns as glob expressions to be expanded, + even if they are an exact match to a file on disk. + + When setting this option, be sure to enquote arguments + so that the shell will not expand them prior to passing + them to the glob command process. + `, + }, + absolute: { + short: 'a', + description: 'Expand to absolute paths', + }, + 'dot-relative': { + short: 'd', + description: `Prepend './' on relative matches`, + }, + mark: { + short: 'm', + description: `Append a / on any directories matched`, + }, + posix: { + short: 'x', + description: `Always resolve to posix style paths, using '/' as the + directory separator, even on Windows. Drive letter + absolute matches on Windows will be expanded to their + full resolved UNC maths, eg instead of 'C:\\foo\\bar', + it will expand to '//?/C:/foo/bar'. + `, + }, + follow: { + short: 'f', + description: `Follow symlinked directories when expanding '**'`, + }, + realpath: { + short: 'R', + description: `Call 'fs.realpath' on all of the results. In the case + of an entry that cannot be resolved, the entry is + omitted. This incurs a slight performance penalty, of + course, because of the added system calls.`, + }, + stat: { + short: 's', + description: `Call 'fs.lstat' on all entries, whether required or not + to determine if it's a valid match.`, + }, + 'match-base': { + short: 'b', + description: `Perform a basename-only match if the pattern does not + contain any slash characters. That is, '*.js' would be + treated as equivalent to '**/*.js', matching js files + in all directories. + `, + }, + dot: { + description: `Allow patterns to match files/directories that start + with '.', even if the pattern does not start with '.' + `, + }, + nobrace: { + description: 'Do not expand {...} patterns', + }, + nocase: { + description: `Perform a case-insensitive match. This defaults to + 'true' on macOS and Windows platforms, and false on + all others. + + Note: 'nocase' should only be explicitly set when it is + known that the filesystem's case sensitivity differs + from the platform default. If set 'true' on + case-insensitive file systems, then the walk may return + more or less results than expected. + `, + }, + nodir: { + description: `Do not match directories, only files. + + Note: to *only* match directories, append a '/' at the + end of the pattern. + `, + }, + noext: { + description: `Do not expand extglob patterns, such as '+(a|b)'`, + }, + noglobstar: { + description: `Do not expand '**' against multiple path portions. + Ie, treat it as a normal '*' instead.`, + }, + 'windows-path-no-escape': { + description: `Use '\\' as a path separator *only*, and *never* as an + escape character. If set, all '\\' characters are + replaced with '/' in the pattern.`, + }, +}) + .num({ + 'max-depth': { + short: 'D', + description: `Maximum depth to traverse from the current + working directory`, + }, +}) + .opt({ + cwd: { + short: 'C', + description: 'Current working directory to execute/match in', + default: process.cwd(), + }, + root: { + short: 'r', + description: `A string path resolved against the 'cwd', which is + used as the starting point for absolute patterns that + start with '/' (but not drive letters or UNC paths + on Windows). + + Note that this *doesn't* necessarily limit the walk to + the 'root' directory, and doesn't affect the cwd + starting point for non-absolute patterns. A pattern + containing '..' will still be able to traverse out of + the root directory, if it is not an actual root directory + on the filesystem, and any non-absolute patterns will + still be matched in the 'cwd'. + + To start absolute and non-absolute patterns in the same + path, you can use '--root=' to set it to the empty + string. However, be aware that on Windows systems, a + pattern like 'x:/*' or '//host/share/*' will *always* + start in the 'x:/' or '//host/share/' directory, + regardless of the --root setting. + `, + }, + platform: { + description: `Defaults to the value of 'process.platform' if + available, or 'linux' if not. Setting --platform=win32 + on non-Windows systems may cause strange behavior!`, + validOptions: [ + 'aix', + 'android', + 'darwin', + 'freebsd', + 'haiku', + 'linux', + 'openbsd', + 'sunos', + 'win32', + 'cygwin', + 'netbsd', + ], + }, +}) + .optList({ + ignore: { + short: 'i', + description: `Glob patterns to ignore`, + }, +}) + .flag({ + debug: { + short: 'v', + description: `Output a huge amount of noisy debug information about + patterns as they are parsed and used to match files.`, + }, +}) + .flag({ + help: { + short: 'h', + description: 'Show this usage information', + }, +}); +try { + const { positionals, values } = j.parse(); + if (values.help) { + console.log(j.usage()); + process.exit(0); + } + if (positionals.length === 0 && !values.default) + throw 'No patterns provided'; + if (positionals.length === 0 && values.default) + positionals.push(values.default); + const patterns = values.all ? positionals : positionals.filter(p => !existsSync(p)); + const matches = values.all ? + [] + : positionals.filter(p => existsSync(p)).map(p => join(p)); + const stream = globStream(patterns, { + absolute: values.absolute, + cwd: values.cwd, + dot: values.dot, + dotRelative: values['dot-relative'], + follow: values.follow, + ignore: values.ignore, + mark: values.mark, + matchBase: values['match-base'], + maxDepth: values['max-depth'], + nobrace: values.nobrace, + nocase: values.nocase, + nodir: values.nodir, + noext: values.noext, + noglobstar: values.noglobstar, + platform: values.platform, + realpath: values.realpath, + root: values.root, + stat: values.stat, + debug: values.debug, + posix: values.posix, + }); + const cmd = values.cmd; + if (!cmd) { + matches.forEach(m => console.log(m)); + stream.on('data', f => console.log(f)); + } + else { + stream.on('data', f => matches.push(f)); + stream.on('end', () => foregroundChild(cmd, matches, { shell: true })); + } +} +catch (e) { + console.error(j.usage()); + console.error(e instanceof Error ? e.message : String(e)); + process.exit(1); +} +//# sourceMappingURL=bin.mjs.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/bin.mjs.map b/node_modules/glob/dist/esm/bin.mjs.map new file mode 100644 index 0000000..67247d5 --- /dev/null +++ b/node_modules/glob/dist/esm/bin.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bin.mjs","sourceRoot":"","sources":["../../src/bin.mts"],"names":[],"mappings":";AACA,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,IAAI,CAAA;AAC/B,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAA;AACxD,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAA;AAC3B,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AAEvC,MAAM,EAAE,OAAO,EAAE,GAAG,eAAe,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAA;AAEvE,MAAM,CAAC,GAAG,IAAI,CAAC;IACb,KAAK,EAAE,4CAA4C;CACpD,CAAC;KACC,WAAW,CACV;YACQ,OAAO;;;;GAIhB,CACA;KACA,GAAG,CAAC;IACH,GAAG,EAAE;QACH,KAAK,EAAE,GAAG;QACV,IAAI,EAAE,SAAS;QACf,WAAW,EAAE;0CACuB;KACrC;CACF,CAAC;KACD,GAAG,CAAC;IACH,OAAO,EAAE;QACP,KAAK,EAAE,GAAG;QACV,IAAI,EAAE,SAAS;QACf,WAAW,EAAE;iCACc;KAC5B;CACF,CAAC;KACD,IAAI,CAAC;IACJ,GAAG,EAAE;QACH,KAAK,EAAE,GAAG;QACV,WAAW,EAAE;;;;;;;;;;;;;;;;;;;;;OAqBZ;KACF;IACD,QAAQ,EAAE;QACR,KAAK,EAAE,GAAG;QACV,WAAW,EAAE,0BAA0B;KACxC;IACD,cAAc,EAAE;QACd,KAAK,EAAE,GAAG;QACV,WAAW,EAAE,kCAAkC;KAChD;IACD,IAAI,EAAE;QACJ,KAAK,EAAE,GAAG;QACV,WAAW,EAAE,uCAAuC;KACrD;IACD,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AAC,CAAC,CAAA;QACvC,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,eAAe,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAA;IACxE,CAAC;AACH,CAAC;AAAC,OAAO,CAAC,EAAE,CAAC;IACX,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAA;IACxB,OAAO,CAAC,KAAK,CAAC,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;IACzD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;AACjB,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { foregroundChild } from 'foreground-child'\nimport { existsSync } from 'fs'\nimport { jack } from 'jackspeak'\nimport { loadPackageJson } from 'package-json-from-dist'\nimport { join } from 'path'\nimport { globStream } from './index.js'\n\nconst { version } = loadPackageJson(import.meta.url, '../package.json')\n\nconst j = jack({\n usage: 'glob [options] [ [ ...]]',\n})\n .description(\n `\n Glob v${version}\n\n Expand the positional glob expression arguments into any matching file\n system paths found.\n `,\n )\n .opt({\n cmd: {\n short: 'c',\n hint: 'command',\n description: `Run the command provided, passing the glob expression\n matches as arguments.`,\n },\n })\n .opt({\n default: {\n short: 'p',\n hint: 'pattern',\n description: `If no positional arguments are provided, glob will use\n this pattern`,\n },\n })\n .flag({\n all: {\n short: 'A',\n description: `By default, the glob cli command will not expand any\n arguments that are an exact match to a file on disk.\n\n This prevents double-expanding, in case the shell expands\n an argument whose filename is a glob expression.\n\n For example, if 'app/*.ts' would match 'app/[id].ts', then\n on Windows powershell or cmd.exe, 'glob app/*.ts' will\n expand to 'app/[id].ts', as expected. However, in posix\n shells such as bash or zsh, the shell will first expand\n 'app/*.ts' to a list of filenames. Then glob will look\n for a file matching 'app/[id].ts' (ie, 'app/i.ts' or\n 'app/d.ts'), which is unexpected.\n\n Setting '--all' prevents this behavior, causing glob\n to treat ALL patterns as glob expressions to be expanded,\n even if they are an exact match to a file on disk.\n\n When setting this option, be sure to enquote arguments\n so that the shell will not expand them prior to passing\n them to the glob command process.\n `,\n },\n absolute: {\n short: 'a',\n description: 'Expand to absolute paths',\n },\n 'dot-relative': {\n short: 'd',\n description: `Prepend './' on relative matches`,\n },\n mark: {\n short: 'm',\n description: `Append a / on any directories matched`,\n },\n posix: {\n short: 'x',\n description: `Always resolve to posix style paths, using '/' as the\n directory separator, even on Windows. Drive letter\n absolute matches on Windows will be expanded to their\n full resolved UNC maths, eg instead of 'C:\\\\foo\\\\bar',\n it will expand to '//?/C:/foo/bar'.\n `,\n },\n\n follow: {\n short: 'f',\n description: `Follow symlinked directories when expanding '**'`,\n },\n realpath: {\n short: 'R',\n description: `Call 'fs.realpath' on all of the results. In the case\n of an entry that cannot be resolved, the entry is\n omitted. This incurs a slight performance penalty, of\n course, because of the added system calls.`,\n },\n stat: {\n short: 's',\n description: `Call 'fs.lstat' on all entries, whether required or not\n to determine if it's a valid match.`,\n },\n 'match-base': {\n short: 'b',\n description: `Perform a basename-only match if the pattern does not\n contain any slash characters. That is, '*.js' would be\n treated as equivalent to '**/*.js', matching js files\n in all directories.\n `,\n },\n\n dot: {\n description: `Allow patterns to match files/directories that start\n with '.', even if the pattern does not start with '.'\n `,\n },\n nobrace: {\n description: 'Do not expand {...} patterns',\n },\n nocase: {\n description: `Perform a case-insensitive match. This defaults to\n 'true' on macOS and Windows platforms, and false on\n all others.\n\n Note: 'nocase' should only be explicitly set when it is\n known that the filesystem's case sensitivity differs\n from the platform default. If set 'true' on\n case-insensitive file systems, then the walk may return\n more or less results than expected.\n `,\n },\n nodir: {\n description: `Do not match directories, only files.\n\n Note: to *only* match directories, append a '/' at the\n end of the pattern.\n `,\n },\n noext: {\n description: `Do not expand extglob patterns, such as '+(a|b)'`,\n },\n noglobstar: {\n description: `Do not expand '**' against multiple path portions.\n Ie, treat it as a normal '*' instead.`,\n },\n 'windows-path-no-escape': {\n description: `Use '\\\\' as a path separator *only*, and *never* as an\n escape character. If set, all '\\\\' characters are\n replaced with '/' in the pattern.`,\n },\n })\n .num({\n 'max-depth': {\n short: 'D',\n description: `Maximum depth to traverse from the current\n working directory`,\n },\n })\n .opt({\n cwd: {\n short: 'C',\n description: 'Current working directory to execute/match in',\n default: process.cwd(),\n },\n root: {\n short: 'r',\n description: `A string path resolved against the 'cwd', which is\n used as the starting point for absolute patterns that\n start with '/' (but not drive letters or UNC paths\n on Windows).\n\n Note that this *doesn't* necessarily limit the walk to\n the 'root' directory, and doesn't affect the cwd\n starting point for non-absolute patterns. A pattern\n containing '..' will still be able to traverse out of\n the root directory, if it is not an actual root directory\n on the filesystem, and any non-absolute patterns will\n still be matched in the 'cwd'.\n\n To start absolute and non-absolute patterns in the same\n path, you can use '--root=' to set it to the empty\n string. However, be aware that on Windows systems, a\n pattern like 'x:/*' or '//host/share/*' will *always*\n start in the 'x:/' or '//host/share/' directory,\n regardless of the --root setting.\n `,\n },\n platform: {\n description: `Defaults to the value of 'process.platform' if\n available, or 'linux' if not. Setting --platform=win32\n on non-Windows systems may cause strange behavior!`,\n validOptions: [\n 'aix',\n 'android',\n 'darwin',\n 'freebsd',\n 'haiku',\n 'linux',\n 'openbsd',\n 'sunos',\n 'win32',\n 'cygwin',\n 'netbsd',\n ],\n },\n })\n .optList({\n ignore: {\n short: 'i',\n description: `Glob patterns to ignore`,\n },\n })\n .flag({\n debug: {\n short: 'v',\n description: `Output a huge amount of noisy debug information about\n patterns as they are parsed and used to match files.`,\n },\n })\n .flag({\n help: {\n short: 'h',\n description: 'Show this usage information',\n },\n })\n\ntry {\n const { positionals, values } = j.parse()\n if (values.help) {\n console.log(j.usage())\n process.exit(0)\n }\n if (positionals.length === 0 && !values.default)\n throw 'No patterns provided'\n if (positionals.length === 0 && values.default)\n positionals.push(values.default)\n const patterns =\n values.all ? positionals : positionals.filter(p => !existsSync(p))\n const matches =\n values.all ?\n []\n : positionals.filter(p => existsSync(p)).map(p => join(p))\n const stream = globStream(patterns, {\n absolute: values.absolute,\n cwd: values.cwd,\n dot: values.dot,\n dotRelative: values['dot-relative'],\n follow: values.follow,\n ignore: values.ignore,\n mark: values.mark,\n matchBase: values['match-base'],\n maxDepth: values['max-depth'],\n nobrace: values.nobrace,\n nocase: values.nocase,\n nodir: values.nodir,\n noext: values.noext,\n noglobstar: values.noglobstar,\n platform: values.platform as undefined | NodeJS.Platform,\n realpath: values.realpath,\n root: values.root,\n stat: values.stat,\n debug: values.debug,\n posix: values.posix,\n })\n\n const cmd = values.cmd\n if (!cmd) {\n matches.forEach(m => console.log(m))\n stream.on('data', f => console.log(f))\n } else {\n stream.on('data', f => matches.push(f))\n stream.on('end', () => foregroundChild(cmd, matches, { shell: true }))\n }\n} catch (e) {\n console.error(j.usage())\n console.error(e instanceof Error ? e.message : String(e))\n process.exit(1)\n}\n"]} \ No newline at end of file diff --git a/node_modules/glob/dist/esm/glob.d.ts b/node_modules/glob/dist/esm/glob.d.ts new file mode 100644 index 0000000..25262b3 --- /dev/null +++ b/node_modules/glob/dist/esm/glob.d.ts @@ -0,0 +1,388 @@ +import { Minimatch } from 'minimatch'; +import { Minipass } from 'minipass'; +import { FSOption, Path, PathScurry } from 'path-scurry'; +import { IgnoreLike } from './ignore.js'; +import { Pattern } from './pattern.js'; +export type MatchSet = Minimatch['set']; +export type GlobParts = Exclude; +/** + * A `GlobOptions` object may be provided to any of the exported methods, and + * must be provided to the `Glob` constructor. + * + * All options are optional, boolean, and false by default, unless otherwise + * noted. + * + * All resolved options are added to the Glob object as properties. + * + * If you are running many `glob` operations, you can pass a Glob object as the + * `options` argument to a subsequent operation to share the previously loaded + * cache. + */ +export interface GlobOptions { + /** + * Set to `true` to always receive absolute paths for + * matched files. Set to `false` to always return relative paths. + * + * When this option is not set, absolute paths are returned for patterns + * that are absolute, and otherwise paths are returned that are relative + * to the `cwd` setting. + * + * This does _not_ make an extra system call to get + * the realpath, it only does string path resolution. + * + * Conflicts with {@link withFileTypes} + */ + absolute?: boolean; + /** + * Set to false to enable {@link windowsPathsNoEscape} + * + * @deprecated + */ + allowWindowsEscape?: boolean; + /** + * The current working directory in which to search. Defaults to + * `process.cwd()`. + * + * May be eiher a string path or a `file://` URL object or string. + */ + cwd?: string | URL; + /** + * Include `.dot` files in normal matches and `globstar` + * matches. Note that an explicit dot in a portion of the pattern + * will always match dot files. + */ + dot?: boolean; + /** + * Prepend all relative path strings with `./` (or `.\` on Windows). + * + * Without this option, returned relative paths are "bare", so instead of + * returning `'./foo/bar'`, they are returned as `'foo/bar'`. + * + * Relative patterns starting with `'../'` are not prepended with `./`, even + * if this option is set. + */ + dotRelative?: boolean; + /** + * Follow symlinked directories when expanding `**` + * patterns. This can result in a lot of duplicate references in + * the presence of cyclic links, and make performance quite bad. + * + * By default, a `**` in a pattern will follow 1 symbolic link if + * it is not the first item in the pattern, or none if it is the + * first item in the pattern, following the same behavior as Bash. + */ + follow?: boolean; + /** + * string or string[], or an object with `ignore` and `ignoreChildren` + * methods. + * + * If a string or string[] is provided, then this is treated as a glob + * pattern or array of glob patterns to exclude from matches. To ignore all + * children within a directory, as well as the entry itself, append `'/**'` + * to the ignore pattern. + * + * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of + * any other settings. + * + * If an object is provided that has `ignored(path)` and/or + * `childrenIgnored(path)` methods, then these methods will be called to + * determine whether any Path is a match or if its children should be + * traversed, respectively. + */ + ignore?: string | string[] | IgnoreLike; + /** + * Treat brace expansion like `{a,b}` as a "magic" pattern. Has no + * effect if {@link nobrace} is set. + * + * Only has effect on the {@link hasMagic} function. + */ + magicalBraces?: boolean; + /** + * Add a `/` character to directory matches. Note that this requires + * additional stat calls in some cases. + */ + mark?: boolean; + /** + * Perform a basename-only match if the pattern does not contain any slash + * characters. That is, `*.js` would be treated as equivalent to + * `**\/*.js`, matching all js files in all directories. + */ + matchBase?: boolean; + /** + * Limit the directory traversal to a given depth below the cwd. + * Note that this does NOT prevent traversal to sibling folders, + * root patterns, and so on. It only limits the maximum folder depth + * that the walk will descend, relative to the cwd. + */ + maxDepth?: number; + /** + * Do not expand `{a,b}` and `{1..3}` brace sets. + */ + nobrace?: boolean; + /** + * Perform a case-insensitive match. This defaults to `true` on macOS and + * Windows systems, and `false` on all others. + * + * **Note** `nocase` should only be explicitly set when it is + * known that the filesystem's case sensitivity differs from the + * platform default. If set `true` on case-sensitive file + * systems, or `false` on case-insensitive file systems, then the + * walk may return more or less results than expected. + */ + nocase?: boolean; + /** + * Do not match directories, only files. (Note: to match + * _only_ directories, put a `/` at the end of the pattern.) + */ + nodir?: boolean; + /** + * Do not match "extglob" patterns such as `+(a|b)`. + */ + noext?: boolean; + /** + * Do not match `**` against multiple filenames. (Ie, treat it as a normal + * `*` instead.) + * + * Conflicts with {@link matchBase} + */ + noglobstar?: boolean; + /** + * Defaults to value of `process.platform` if available, or `'linux'` if + * not. Setting `platform:'win32'` on non-Windows systems may cause strange + * behavior. + */ + platform?: NodeJS.Platform; + /** + * Set to true to call `fs.realpath` on all of the + * results. In the case of an entry that cannot be resolved, the + * entry is omitted. This incurs a slight performance penalty, of + * course, because of the added system calls. + */ + realpath?: boolean; + /** + * + * A string path resolved against the `cwd` option, which + * is used as the starting point for absolute patterns that start + * with `/`, (but not drive letters or UNC paths on Windows). + * + * Note that this _doesn't_ necessarily limit the walk to the + * `root` directory, and doesn't affect the cwd starting point for + * non-absolute patterns. A pattern containing `..` will still be + * able to traverse out of the root directory, if it is not an + * actual root directory on the filesystem, and any non-absolute + * patterns will be matched in the `cwd`. For example, the + * pattern `/../*` with `{root:'/some/path'}` will return all + * files in `/some`, not all files in `/some/path`. The pattern + * `*` with `{root:'/some/path'}` will return all the entries in + * the cwd, not the entries in `/some/path`. + * + * To start absolute and non-absolute patterns in the same + * path, you can use `{root:''}`. However, be aware that on + * Windows systems, a pattern like `x:/*` or `//host/share/*` will + * _always_ start in the `x:/` or `//host/share` directory, + * regardless of the `root` setting. + */ + root?: string; + /** + * A [PathScurry](http://npm.im/path-scurry) object used + * to traverse the file system. If the `nocase` option is set + * explicitly, then any provided `scurry` object must match this + * setting. + */ + scurry?: PathScurry; + /** + * Call `lstat()` on all entries, whether required or not to determine + * if it's a valid match. When used with {@link withFileTypes}, this means + * that matches will include data such as modified time, permissions, and + * so on. Note that this will incur a performance cost due to the added + * system calls. + */ + stat?: boolean; + /** + * An AbortSignal which will cancel the Glob walk when + * triggered. + */ + signal?: AbortSignal; + /** + * Use `\\` as a path separator _only_, and + * _never_ as an escape character. If set, all `\\` characters are + * replaced with `/` in the pattern. + * + * Note that this makes it **impossible** to match against paths + * containing literal glob pattern characters, but allows matching + * with patterns constructed using `path.join()` and + * `path.resolve()` on Windows platforms, mimicking the (buggy!) + * behavior of Glob v7 and before on Windows. Please use with + * caution, and be mindful of [the caveat below about Windows + * paths](#windows). (For legacy reasons, this is also set if + * `allowWindowsEscape` is set to the exact value `false`.) + */ + windowsPathsNoEscape?: boolean; + /** + * Return [PathScurry](http://npm.im/path-scurry) + * `Path` objects instead of strings. These are similar to a + * NodeJS `Dirent` object, but with additional methods and + * properties. + * + * Conflicts with {@link absolute} + */ + withFileTypes?: boolean; + /** + * An fs implementation to override some or all of the defaults. See + * http://npm.im/path-scurry for details about what can be overridden. + */ + fs?: FSOption; + /** + * Just passed along to Minimatch. Note that this makes all pattern + * matching operations slower and *extremely* noisy. + */ + debug?: boolean; + /** + * Return `/` delimited paths, even on Windows. + * + * On posix systems, this has no effect. But, on Windows, it means that + * paths will be `/` delimited, and absolute paths will be their full + * resolved UNC forms, eg instead of `'C:\\foo\\bar'`, it would return + * `'//?/C:/foo/bar'` + */ + posix?: boolean; + /** + * Do not match any children of any matches. For example, the pattern + * `**\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode. + * + * This is especially useful for cases like "find all `node_modules` + * folders, but not the ones in `node_modules`". + * + * In order to support this, the `Ignore` implementation must support an + * `add(pattern: string)` method. If using the default `Ignore` class, then + * this is fine, but if this is set to `false`, and a custom `Ignore` is + * provided that does not have an `add()` method, then it will throw an + * error. + * + * **Caveat** It *only* ignores matches that would be a descendant of a + * previous match, and only if that descendant is matched *after* the + * ancestor is encountered. Since the file system walk happens in + * indeterminate order, it's possible that a match will already be added + * before its ancestor, if multiple or braced patterns are used. + * + * For example: + * + * ```ts + * const results = await glob([ + * // likely to match first, since it's just a stat + * 'a/b/c/d/e/f', + * + * // this pattern is more complicated! It must to various readdir() + * // calls and test the results against a regular expression, and that + * // is certainly going to take a little bit longer. + * // + * // So, later on, it encounters a match at 'a/b/c/d/e', but it's too + * // late to ignore a/b/c/d/e/f, because it's already been emitted. + * 'a/[bdf]/?/[a-z]/*', + * ], { includeChildMatches: false }) + * ``` + * + * It's best to only set this to `false` if you can be reasonably sure that + * no components of the pattern will potentially match one another's file + * system descendants, or if the occasional included child entry will not + * cause problems. + * + * @default true + */ + includeChildMatches?: boolean; +} +export type GlobOptionsWithFileTypesTrue = GlobOptions & { + withFileTypes: true; + absolute?: undefined; + mark?: undefined; + posix?: undefined; +}; +export type GlobOptionsWithFileTypesFalse = GlobOptions & { + withFileTypes?: false; +}; +export type GlobOptionsWithFileTypesUnset = GlobOptions & { + withFileTypes?: undefined; +}; +export type Result = Opts extends GlobOptionsWithFileTypesTrue ? Path : Opts extends GlobOptionsWithFileTypesFalse ? string : Opts extends GlobOptionsWithFileTypesUnset ? string : string | Path; +export type Results = Result[]; +export type FileTypes = Opts extends GlobOptionsWithFileTypesTrue ? true : Opts extends GlobOptionsWithFileTypesFalse ? false : Opts extends GlobOptionsWithFileTypesUnset ? false : boolean; +/** + * An object that can perform glob pattern traversals. + */ +export declare class Glob implements GlobOptions { + absolute?: boolean; + cwd: string; + root?: string; + dot: boolean; + dotRelative: boolean; + follow: boolean; + ignore?: string | string[] | IgnoreLike; + magicalBraces: boolean; + mark?: boolean; + matchBase: boolean; + maxDepth: number; + nobrace: boolean; + nocase: boolean; + nodir: boolean; + noext: boolean; + noglobstar: boolean; + pattern: string[]; + platform: NodeJS.Platform; + realpath: boolean; + scurry: PathScurry; + stat: boolean; + signal?: AbortSignal; + windowsPathsNoEscape: boolean; + withFileTypes: FileTypes; + includeChildMatches: boolean; + /** + * The options provided to the constructor. + */ + opts: Opts; + /** + * An array of parsed immutable {@link Pattern} objects. + */ + patterns: Pattern[]; + /** + * All options are stored as properties on the `Glob` object. + * + * See {@link GlobOptions} for full options descriptions. + * + * Note that a previous `Glob` object can be passed as the + * `GlobOptions` to another `Glob` instantiation to re-use settings + * and caches with a new pattern. + * + * Traversal functions can be called multiple times to run the walk + * again. + */ + constructor(pattern: string | string[], opts: Opts); + /** + * Returns a Promise that resolves to the results array. + */ + walk(): Promise>; + /** + * synchronous {@link Glob.walk} + */ + walkSync(): Results; + /** + * Stream results asynchronously. + */ + stream(): Minipass, Result>; + /** + * Stream results synchronously. + */ + streamSync(): Minipass, Result>; + /** + * Default sync iteration function. Returns a Generator that + * iterates over the results. + */ + iterateSync(): Generator, void, void>; + [Symbol.iterator](): Generator, void, void>; + /** + * Default async iteration function. Returns an AsyncGenerator that + * iterates over the results. + */ + iterate(): AsyncGenerator, void, void>; + [Symbol.asyncIterator](): AsyncGenerator, void, void>; +} +//# sourceMappingURL=glob.d.ts.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/glob.d.ts.map b/node_modules/glob/dist/esm/glob.d.ts.map new file mode 100644 index 0000000..c32dc74 --- /dev/null +++ b/node_modules/glob/dist/esm/glob.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"glob.d.ts","sourceRoot":"","sources":["../../src/glob.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAoB,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AAEnC,OAAO,EACL,QAAQ,EACR,IAAI,EACJ,UAAU,EAIX,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OA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AE,CAAA;IAEnB;;;;;;;;;;;OAWG;gBACS,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,IAAI,EAAE,IAAI;IA2HlD;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAoBpC;;OAEG;IACH,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAgBzB;;OAEG;IACH,MAAM,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAc9C;;OAEG;IACH,UAAU,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAclD;;;OAGG;IACH,WAAW,IAAI,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAGlD,CAAC,MAAM,CAAC,QAAQ,CAAC;IAIjB;;;OAGG;IACH,OAAO,IAAI,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAGnD,CAAC,MAAM,CAAC,aAAa,CAAC;CAGvB"} \ No newline at end of file diff --git a/node_modules/glob/dist/esm/glob.js b/node_modules/glob/dist/esm/glob.js new file mode 100644 index 0000000..c9ff3b0 --- /dev/null +++ b/node_modules/glob/dist/esm/glob.js @@ -0,0 +1,243 @@ +import { Minimatch } from 'minimatch'; +import { fileURLToPath } from 'node:url'; +import { PathScurry, PathScurryDarwin, PathScurryPosix, PathScurryWin32, } from 'path-scurry'; +import { Pattern } from './pattern.js'; +import { GlobStream, GlobWalker } from './walker.js'; +// if no process global, just call it linux. +// so we default to case-sensitive, / separators +const defaultPlatform = (typeof process === 'object' && + process && + typeof process.platform === 'string') ? + process.platform + : 'linux'; +/** + * An object that can perform glob pattern traversals. + */ +export class Glob { + absolute; + cwd; + root; + dot; + dotRelative; + follow; + ignore; + magicalBraces; + mark; + matchBase; + maxDepth; + nobrace; + nocase; + nodir; + noext; + noglobstar; + pattern; + platform; + realpath; + scurry; + stat; + signal; + windowsPathsNoEscape; + withFileTypes; + includeChildMatches; + /** + * The options provided to the constructor. + */ + opts; + /** + * An array of parsed immutable {@link Pattern} objects. + */ + patterns; + /** + * All options are stored as properties on the `Glob` object. + * + * See {@link GlobOptions} for full options descriptions. + * + * Note that a previous `Glob` object can be passed as the + * `GlobOptions` to another `Glob` instantiation to re-use settings + * and caches with a new pattern. + * + * Traversal functions can be called multiple times to run the walk + * again. + */ + constructor(pattern, opts) { + /* c8 ignore start */ + if (!opts) + throw new TypeError('glob options required'); + /* c8 ignore stop */ + this.withFileTypes = !!opts.withFileTypes; + this.signal = opts.signal; + this.follow = !!opts.follow; + this.dot = !!opts.dot; + this.dotRelative = !!opts.dotRelative; + this.nodir = !!opts.nodir; + this.mark = !!opts.mark; + if (!opts.cwd) { + this.cwd = ''; + } + else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) { + opts.cwd = fileURLToPath(opts.cwd); + } + this.cwd = opts.cwd || ''; + this.root = opts.root; + this.magicalBraces = !!opts.magicalBraces; + this.nobrace = !!opts.nobrace; + this.noext = !!opts.noext; + this.realpath = !!opts.realpath; + this.absolute = opts.absolute; + this.includeChildMatches = opts.includeChildMatches !== false; + this.noglobstar = !!opts.noglobstar; + this.matchBase = !!opts.matchBase; + this.maxDepth = + typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity; + this.stat = !!opts.stat; + this.ignore = opts.ignore; + if (this.withFileTypes && this.absolute !== undefined) { + throw new Error('cannot set absolute and withFileTypes:true'); + } + if (typeof pattern === 'string') { + pattern = [pattern]; + } + this.windowsPathsNoEscape = + !!opts.windowsPathsNoEscape || + opts.allowWindowsEscape === + false; + if (this.windowsPathsNoEscape) { + pattern = pattern.map(p => p.replace(/\\/g, '/')); + } + if (this.matchBase) { + if (opts.noglobstar) { + throw new TypeError('base matching requires globstar'); + } + pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`)); + } + this.pattern = pattern; + this.platform = opts.platform || defaultPlatform; + this.opts = { ...opts, platform: this.platform }; + if (opts.scurry) { + this.scurry = opts.scurry; + if (opts.nocase !== undefined && + opts.nocase !== opts.scurry.nocase) { + throw new Error('nocase option contradicts provided scurry option'); + } + } + else { + const Scurry = opts.platform === 'win32' ? PathScurryWin32 + : opts.platform === 'darwin' ? PathScurryDarwin + : opts.platform ? PathScurryPosix + : PathScurry; + this.scurry = new Scurry(this.cwd, { + nocase: opts.nocase, + fs: opts.fs, + }); + } + this.nocase = this.scurry.nocase; + // If you do nocase:true on a case-sensitive file system, then + // we need to use regexps instead of strings for non-magic + // path portions, because statting `aBc` won't return results + // for the file `AbC` for example. + const nocaseMagicOnly = this.platform === 'darwin' || this.platform === 'win32'; + const mmo = { + // default nocase based on platform + ...opts, + dot: this.dot, + matchBase: this.matchBase, + nobrace: this.nobrace, + nocase: this.nocase, + nocaseMagicOnly, + nocomment: true, + noext: this.noext, + nonegate: true, + optimizationLevel: 2, + platform: this.platform, + windowsPathsNoEscape: this.windowsPathsNoEscape, + debug: !!this.opts.debug, + }; + const mms = this.pattern.map(p => new Minimatch(p, mmo)); + const [matchSet, globParts] = mms.reduce((set, m) => { + set[0].push(...m.set); + set[1].push(...m.globParts); + return set; + }, [[], []]); + this.patterns = matchSet.map((set, i) => { + const g = globParts[i]; + /* c8 ignore start */ + if (!g) + throw new Error('invalid pattern object'); + /* c8 ignore stop */ + return new Pattern(set, g, 0, this.platform); + }); + } + async walk() { + // Walkers always return array of Path objects, so we just have to + // coerce them into the right shape. It will have already called + // realpath() if the option was set to do so, so we know that's cached. + // start out knowing the cwd, at least + return [ + ...(await new GlobWalker(this.patterns, this.scurry.cwd, { + ...this.opts, + maxDepth: this.maxDepth !== Infinity ? + this.maxDepth + this.scurry.cwd.depth() + : Infinity, + platform: this.platform, + nocase: this.nocase, + includeChildMatches: this.includeChildMatches, + }).walk()), + ]; + } + walkSync() { + return [ + ...new GlobWalker(this.patterns, this.scurry.cwd, { + ...this.opts, + maxDepth: this.maxDepth !== Infinity ? + this.maxDepth + this.scurry.cwd.depth() + : Infinity, + platform: this.platform, + nocase: this.nocase, + includeChildMatches: this.includeChildMatches, + }).walkSync(), + ]; + } + stream() { + return new GlobStream(this.patterns, this.scurry.cwd, { + ...this.opts, + maxDepth: this.maxDepth !== Infinity ? + this.maxDepth + this.scurry.cwd.depth() + : Infinity, + platform: this.platform, + nocase: this.nocase, + includeChildMatches: this.includeChildMatches, + }).stream(); + } + streamSync() { + return new GlobStream(this.patterns, this.scurry.cwd, { + ...this.opts, + maxDepth: this.maxDepth !== Infinity ? + this.maxDepth + this.scurry.cwd.depth() + : Infinity, + platform: this.platform, + nocase: this.nocase, + includeChildMatches: this.includeChildMatches, + }).streamSync(); + } + /** + * Default sync iteration function. Returns a Generator that + * iterates over the results. + */ + iterateSync() { + return this.streamSync()[Symbol.iterator](); + } + [Symbol.iterator]() { + return this.iterateSync(); + } + /** + * Default async iteration function. Returns an AsyncGenerator that + * iterates over the results. + */ + iterate() { + return this.stream()[Symbol.asyncIterator](); + } + [Symbol.asyncIterator]() { + return this.iterate(); + } +} +//# sourceMappingURL=glob.js.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/glob.js.map b/node_modules/glob/dist/esm/glob.js.map new file mode 100644 index 0000000..a62c323 --- /dev/null +++ b/node_modules/glob/dist/esm/glob.js.map @@ -0,0 +1 @@ +{"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/glob.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAoB,MAAM,WAAW,CAAA;AAEvD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AACxC,OAAO,EAGL,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,eAAe,GAChB,MAAM,aAAa,CAAA;AAEpB,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAKpD,4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QAAQ;YACvB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;SAC9C,CAAC,CAAC,MAAM,EAAE,CAAA;IACb,CAAC;IAMD,UAAU;QACR,OAAO,IAAI,UAAU,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;YACpD,GAAG,IAAI,CAAC,IAAI;YACZ,QAAQ,EACN,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC;gBAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE;gBACzC,CAAC,CAAC,QAAQ;YACZ,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;SAC9C,CAAC,CAAC,UAAU,EAAE,CAAA;IACjB,CAAC;IAED;;;OAGG;IACH,WAAW;QACT,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAA;IAC7C,CAAC;IACD,CAAC,MAAM,CAAC,QAAQ,CAAC;QACf,OAAO,IAAI,CAAC,WAAW,EAAE,CAAA;IAC3B,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAA;IAC9C,CAAC;IACD,CAAC,MAAM,CAAC,aAAa,CAAC;QACpB,OAAO,IAAI,CAAC,OAAO,EAAE,CAAA;IACvB,CAAC;CACF","sourcesContent":["import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport {\n FSOption,\n Path,\n PathScurry,\n PathScurryDarwin,\n PathScurryPosix,\n PathScurryWin32,\n} from 'path-scurry'\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 (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\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 /**\n * Do not match any children of any matches. For example, the pattern\n * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n *\n * This is especially useful for cases like \"find all `node_modules`\n * folders, but not the ones in `node_modules`\".\n *\n * In order to support this, the `Ignore` implementation must support an\n * `add(pattern: string)` method. If using the default `Ignore` class, then\n * this is fine, but if this is set to `false`, and a custom `Ignore` is\n * provided that does not have an `add()` method, then it will throw an\n * error.\n *\n * **Caveat** It *only* ignores matches that would be a descendant of a\n * previous match, and only if that descendant is matched *after* the\n * ancestor is encountered. Since the file system walk happens in\n * indeterminate order, it's possible that a match will already be added\n * before its ancestor, if multiple or braced patterns are used.\n *\n * For example:\n *\n * ```ts\n * const results = await glob([\n * // likely to match first, since it's just a stat\n * 'a/b/c/d/e/f',\n *\n * // this pattern is more complicated! It must to various readdir()\n * // calls and test the results against a regular expression, and that\n * // is certainly going to take a little bit longer.\n * //\n * // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n * // late to ignore a/b/c/d/e/f, because it's already been emitted.\n * 'a/[bdf]/?/[a-z]/*',\n * ], { includeChildMatches: false })\n * ```\n *\n * It's best to only set this to `false` if you can be reasonably sure that\n * no components of the pattern will potentially match one another's file\n * system descendants, or if the occasional included child entry will not\n * cause problems.\n *\n * @default true\n */\n includeChildMatches?: 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 =\n Opts extends GlobOptionsWithFileTypesTrue ? Path\n : Opts extends GlobOptionsWithFileTypesFalse ? string\n : Opts extends GlobOptionsWithFileTypesUnset ? string\n : string | Path\nexport type Results = Result[]\n\nexport type FileTypes =\n Opts extends GlobOptionsWithFileTypesTrue ? true\n : Opts extends GlobOptionsWithFileTypesFalse ? false\n : Opts extends GlobOptionsWithFileTypesUnset ? 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 includeChildMatches: boolean\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 this.includeChildMatches = opts.includeChildMatches !== false\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 { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n 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' ? PathScurryWin32\n : opts.platform === 'darwin' ? PathScurryDarwin\n : opts.platform ? 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 includeChildMatches: this.includeChildMatches,\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 includeChildMatches: this.includeChildMatches,\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 includeChildMatches: this.includeChildMatches,\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 includeChildMatches: this.includeChildMatches,\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"]} \ No newline at end of file diff --git a/node_modules/glob/dist/esm/has-magic.d.ts b/node_modules/glob/dist/esm/has-magic.d.ts new file mode 100644 index 0000000..8aec3bd --- /dev/null +++ b/node_modules/glob/dist/esm/has-magic.d.ts @@ -0,0 +1,14 @@ +import { GlobOptions } from './glob.js'; +/** + * Return true if the patterns provided contain any magic glob characters, + * given the options provided. + * + * Brace expansion is not considered "magic" unless the `magicalBraces` option + * is set, as brace expansion just turns one string into an array of strings. + * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and + * `'xby'` both do not contain any magic glob characters, and it's treated the + * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true` + * is in the options, brace expansion _is_ treated as a pattern having magic. + */ +export declare const hasMagic: (pattern: string | string[], options?: GlobOptions) => boolean; +//# sourceMappingURL=has-magic.d.ts.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/has-magic.d.ts.map b/node_modules/glob/dist/esm/has-magic.d.ts.map new file mode 100644 index 0000000..b24dd4e --- /dev/null +++ b/node_modules/glob/dist/esm/has-magic.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"has-magic.d.ts","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAEvC;;;;;;;;;;GAUG;AACH,eAAO,MAAM,QAAQ,YACV,MAAM,GAAG,MAAM,EAAE,YACjB,WAAW,KACnB,OAQF,CAAA"} \ No newline at end of file diff --git a/node_modules/glob/dist/esm/has-magic.js b/node_modules/glob/dist/esm/has-magic.js new file mode 100644 index 0000000..ba2321a --- /dev/null +++ b/node_modules/glob/dist/esm/has-magic.js @@ -0,0 +1,23 @@ +import { Minimatch } from 'minimatch'; +/** + * Return true if the patterns provided contain any magic glob characters, + * given the options provided. + * + * Brace expansion is not considered "magic" unless the `magicalBraces` option + * is set, as brace expansion just turns one string into an array of strings. + * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and + * `'xby'` both do not contain any magic glob characters, and it's treated the + * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true` + * is in the options, brace expansion _is_ treated as a pattern having magic. + */ +export const hasMagic = (pattern, options = {}) => { + if (!Array.isArray(pattern)) { + pattern = [pattern]; + } + for (const p of pattern) { + if (new Minimatch(p, options).hasMagic()) + return true; + } + return false; +}; +//# sourceMappingURL=has-magic.js.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/has-magic.js.map b/node_modules/glob/dist/esm/has-magic.js.map new file mode 100644 index 0000000..a20f5aa --- /dev/null +++ b/node_modules/glob/dist/esm/has-magic.js.map @@ -0,0 +1 @@ +{"version":3,"file":"has-magic.js","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AAGrC;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,OAA0B,EAC1B,UAAuB,EAAE,EAChB,EAAE;IACX,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,OAAO,GAAG,CAAC,OAAO,CAAC,CAAA;IACrB,CAAC;IACD,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACxB,IAAI,IAAI,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE;YAAE,OAAO,IAAI,CAAA;IACvD,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA","sourcesContent":["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"]} \ No newline at end of file diff --git a/node_modules/glob/dist/esm/ignore.d.ts b/node_modules/glob/dist/esm/ignore.d.ts new file mode 100644 index 0000000..1893b16 --- /dev/null +++ b/node_modules/glob/dist/esm/ignore.d.ts @@ -0,0 +1,24 @@ +import { Minimatch, MinimatchOptions } from 'minimatch'; +import { Path } from 'path-scurry'; +import { GlobWalkerOpts } from './walker.js'; +export interface IgnoreLike { + ignored?: (p: Path) => boolean; + childrenIgnored?: (p: Path) => boolean; + add?: (ignore: string) => void; +} +/** + * Class used to process ignored patterns + */ +export declare class Ignore implements IgnoreLike { + relative: Minimatch[]; + relativeChildren: Minimatch[]; + absolute: Minimatch[]; + absoluteChildren: Minimatch[]; + platform: NodeJS.Platform; + mmopts: MinimatchOptions; + constructor(ignored: string[], { nobrace, nocase, noext, noglobstar, platform, }: GlobWalkerOpts); + add(ign: string): void; + ignored(p: Path): boolean; + childrenIgnored(p: Path): boolean; +} +//# sourceMappingURL=ignore.d.ts.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/ignore.d.ts.map b/node_modules/glob/dist/esm/ignore.d.ts.map new file mode 100644 index 0000000..57d6ab6 --- /dev/null +++ b/node_modules/glob/dist/esm/ignore.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ignore.d.ts","sourceRoot":"","sources":["../../src/ignore.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAElC,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C,MAAM,WAAW,UAAU;IACzB,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IAC9B,eAAe,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IACtC,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAA;CAC/B;AAWD;;GAEG;AACH,qBAAa,MAAO,YAAW,UAAU;IACvC,QAAQ,EAAE,SAAS,EAAE,CAAA;IACrB,gBAAgB,EAAE,SAAS,EAAE,CAAA;IAC7B,QAAQ,EAAE,SAAS,EAAE,CAAA;IACrB,gBAAgB,EAAE,SAAS,EAAE,CAAA;IAC7B,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAA;IACzB,MAAM,EAAE,gBAAgB,CAAA;gBAGtB,OAAO,EAAE,MAAM,EAAE,EACjB,EACE,OAAO,EACP,MAAM,EACN,KAAK,EACL,UAAU,EACV,QAA0B,GAC3B,EAAE,cAAc;IAqBnB,GAAG,CAAC,GAAG,EAAE,MAAM;IAyCf,OAAO,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;IAczB,eAAe,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;CAWlC"} \ No newline at end of file diff --git a/node_modules/glob/dist/esm/ignore.js b/node_modules/glob/dist/esm/ignore.js new file mode 100644 index 0000000..539c4a4 --- /dev/null +++ b/node_modules/glob/dist/esm/ignore.js @@ -0,0 +1,115 @@ +// give it a pattern, and it'll be able to tell you if +// a given path should be ignored. +// Ignoring a path ignores its children if the pattern ends in /** +// Ignores are always parsed in dot:true mode +import { Minimatch } from 'minimatch'; +import { Pattern } from './pattern.js'; +const defaultPlatform = (typeof process === 'object' && + process && + typeof process.platform === 'string') ? + process.platform + : 'linux'; +/** + * Class used to process ignored patterns + */ +export class Ignore { + relative; + relativeChildren; + absolute; + absoluteChildren; + platform; + mmopts; + constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = defaultPlatform, }) { + this.relative = []; + this.absolute = []; + this.relativeChildren = []; + this.absoluteChildren = []; + this.platform = platform; + this.mmopts = { + dot: true, + nobrace, + nocase, + noext, + noglobstar, + optimizationLevel: 2, + platform, + nocomment: true, + nonegate: true, + }; + for (const ign of ignored) + this.add(ign); + } + add(ign) { + // this is a little weird, but it gives us a clean set of optimized + // minimatch matchers, without getting tripped up if one of them + // ends in /** inside a brace section, and it's only inefficient at + // the start of the walk, not along it. + // It'd be nice if the Pattern class just had a .test() method, but + // handling globstars is a bit of a pita, and that code already lives + // in minimatch anyway. + // Another way would be if maybe Minimatch could take its set/globParts + // as an option, and then we could at least just use Pattern to test + // for absolute-ness. + // Yet another way, Minimatch could take an array of glob strings, and + // a cwd option, and do the right thing. + const mm = new Minimatch(ign, this.mmopts); + for (let i = 0; i < mm.set.length; i++) { + const parsed = mm.set[i]; + const globParts = mm.globParts[i]; + /* c8 ignore start */ + if (!parsed || !globParts) { + throw new Error('invalid pattern object'); + } + // strip off leading ./ portions + // https://github.com/isaacs/node-glob/issues/570 + while (parsed[0] === '.' && globParts[0] === '.') { + parsed.shift(); + globParts.shift(); + } + /* c8 ignore stop */ + const p = new Pattern(parsed, globParts, 0, this.platform); + const m = new Minimatch(p.globString(), this.mmopts); + const children = globParts[globParts.length - 1] === '**'; + const absolute = p.isAbsolute(); + if (absolute) + this.absolute.push(m); + else + this.relative.push(m); + if (children) { + if (absolute) + this.absoluteChildren.push(m); + else + this.relativeChildren.push(m); + } + } + } + ignored(p) { + const fullpath = p.fullpath(); + const fullpaths = `${fullpath}/`; + const relative = p.relative() || '.'; + const relatives = `${relative}/`; + for (const m of this.relative) { + if (m.match(relative) || m.match(relatives)) + return true; + } + for (const m of this.absolute) { + if (m.match(fullpath) || m.match(fullpaths)) + return true; + } + return false; + } + childrenIgnored(p) { + const fullpath = p.fullpath() + '/'; + const relative = (p.relative() || '.') + '/'; + for (const m of this.relativeChildren) { + if (m.match(relative)) + return true; + } + for (const m of this.absoluteChildren) { + if (m.match(fullpath)) + return true; + } + return false; + } +} +//# sourceMappingURL=ignore.js.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/ignore.js.map b/node_modules/glob/dist/esm/ignore.js.map new file mode 100644 index 0000000..2cddba2 --- /dev/null +++ b/node_modules/glob/dist/esm/ignore.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ignore.js","sourceRoot":"","sources":["../../src/ignore.ts"],"names":[],"mappings":"AAAA,sDAAs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ACpC,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;CACF","sourcesContent":["// 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, MinimatchOptions } 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 add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\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 platform: NodeJS.Platform\n mmopts: MinimatchOptions\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 this.platform = platform\n this.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 for (const ign of ignored) this.add(ign)\n }\n\n add(ign: string) {\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 const mm = new Minimatch(ign, this.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 // strip off leading ./ portions\n // https://github.com/isaacs/node-glob/issues/570\n while (parsed[0] === '.' && globParts[0] === '.') {\n parsed.shift()\n globParts.shift()\n }\n /* c8 ignore stop */\n const p = new Pattern(parsed, globParts, 0, this.platform)\n const m = new Minimatch(p.globString(), this.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 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"]} \ No newline at end of file diff --git a/node_modules/glob/dist/esm/index.d.ts b/node_modules/glob/dist/esm/index.d.ts new file mode 100644 index 0000000..9c326dd --- /dev/null +++ b/node_modules/glob/dist/esm/index.d.ts @@ -0,0 +1,97 @@ +import { Minipass } from 'minipass'; +import { Path } from 'path-scurry'; +import type { GlobOptions, GlobOptionsWithFileTypesFalse, GlobOptionsWithFileTypesTrue, GlobOptionsWithFileTypesUnset } from './glob.js'; +import { Glob } from './glob.js'; +export { escape, unescape } from 'minimatch'; +export type { FSOption, Path, WalkOptions, WalkOptionsWithFileTypesTrue, WalkOptionsWithFileTypesUnset, } from 'path-scurry'; +export { Glob } from './glob.js'; +export type { GlobOptions, GlobOptionsWithFileTypesFalse, GlobOptionsWithFileTypesTrue, GlobOptionsWithFileTypesUnset, } from './glob.js'; +export { hasMagic } from './has-magic.js'; +export { Ignore } from './ignore.js'; +export type { IgnoreLike } from './ignore.js'; +export type { MatchStream } from './walker.js'; +/** + * Syncronous form of {@link globStream}. Will read all the matches as fast as + * you consume them, even all in a single tick if you consume them immediately, + * but will still respond to backpressure if they're not consumed immediately. + */ +export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Minipass; +export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Minipass; +export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesUnset): Minipass; +export declare function globStreamSync(pattern: string | string[], options: GlobOptions): Minipass | Minipass; +/** + * Return a stream that emits all the strings or `Path` objects and + * then emits `end` when completed. + */ +export declare function globStream(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Minipass; +export declare function globStream(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Minipass; +export declare function globStream(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Minipass; +export declare function globStream(pattern: string | string[], options: GlobOptions): Minipass | Minipass; +/** + * Synchronous form of {@link glob} + */ +export declare function globSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): string[]; +export declare function globSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Path[]; +export declare function globSync(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): string[]; +export declare function globSync(pattern: string | string[], options: GlobOptions): Path[] | string[]; +/** + * Perform an asynchronous glob search for the pattern(s) specified. Returns + * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the + * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for + * full option descriptions. + */ +declare function glob_(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Promise; +declare function glob_(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Promise; +declare function glob_(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Promise; +declare function glob_(pattern: string | string[], options: GlobOptions): Promise; +/** + * Return a sync iterator for walking glob pattern matches. + */ +export declare function globIterateSync(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Generator; +export declare function globIterateSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Generator; +export declare function globIterateSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Generator; +export declare function globIterateSync(pattern: string | string[], options: GlobOptions): Generator | Generator; +/** + * Return an async iterator for walking glob pattern matches. + */ +export declare function globIterate(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): AsyncGenerator; +export declare function globIterate(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): AsyncGenerator; +export declare function globIterate(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): AsyncGenerator; +export declare function globIterate(pattern: string | string[], options: GlobOptions): AsyncGenerator | AsyncGenerator; +export declare const streamSync: typeof globStreamSync; +export declare const stream: typeof globStream & { + sync: typeof globStreamSync; +}; +export declare const iterateSync: typeof globIterateSync; +export declare const iterate: typeof globIterate & { + sync: typeof globIterateSync; +}; +export declare const sync: typeof globSync & { + stream: typeof globStreamSync; + iterate: typeof globIterateSync; +}; +export declare const glob: typeof glob_ & { + glob: typeof glob_; + globSync: typeof globSync; + sync: typeof globSync & { + stream: typeof globStreamSync; + iterate: typeof globIterateSync; + }; + globStream: typeof globStream; + stream: typeof globStream & { + sync: typeof globStreamSync; + }; + globStreamSync: typeof globStreamSync; + streamSync: typeof globStreamSync; + globIterate: typeof globIterate; + iterate: typeof globIterate & { + sync: typeof globIterateSync; + }; + globIterateSync: typeof globIterateSync; + iterateSync: typeof globIterateSync; + Glob: typeof Glob; + hasMagic: (pattern: string | string[], options?: GlobOptions) => boolean; + escape: (s: string, { windowsPathsNoEscape, }?: Pick) => string; + unescape: (s: string, { windowsPathsNoEscape, }?: Pick) => string; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/index.d.ts.map b/node_modules/glob/dist/esm/index.d.ts.map new file mode 100644 index 0000000..5fb3225 --- /dev/null +++ b/node_modules/glob/dist/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,KAAK,EACV,WAAW,EACX,6BAA6B,EAC7B,4BAA4B,EAC5B,6BAA6B,EAC9B,MAAM,WAAW,CAAA;AAClB,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAGhC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAC5C,YAAY,EACV,QAAQ,EACR,IAAI,EACJ,WAAW,EACX,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,YAAY,EACV,WAAW,EACX,6BAA6B,EAC7B,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,WAAW,CAAA;AAClB,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAC7C,YAAY,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAE9C;;;;GAIG;AACH,wBAAgB,cAAc,CAC5B,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAC1B,OAAO,EAAE,4BAA4B,GACpC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;AACvB,wBA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CAAA;AACF,eAAO,MAAM,IAAI;;;CAGf,CAAA;AAEF,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;CAgBf,CAAA"} \ No newline at end of file diff --git a/node_modules/glob/dist/esm/index.js b/node_modules/glob/dist/esm/index.js new file mode 100644 index 0000000..e15c1f9 --- /dev/null +++ b/node_modules/glob/dist/esm/index.js @@ -0,0 +1,55 @@ +import { escape, unescape } from 'minimatch'; +import { Glob } from './glob.js'; +import { hasMagic } from './has-magic.js'; +export { escape, unescape } from 'minimatch'; +export { Glob } from './glob.js'; +export { hasMagic } from './has-magic.js'; +export { Ignore } from './ignore.js'; +export function globStreamSync(pattern, options = {}) { + return new Glob(pattern, options).streamSync(); +} +export function globStream(pattern, options = {}) { + return new Glob(pattern, options).stream(); +} +export function globSync(pattern, options = {}) { + return new Glob(pattern, options).walkSync(); +} +async function glob_(pattern, options = {}) { + return new Glob(pattern, options).walk(); +} +export function globIterateSync(pattern, options = {}) { + return new Glob(pattern, options).iterateSync(); +} +export function globIterate(pattern, options = {}) { + return new Glob(pattern, options).iterate(); +} +// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc +export const streamSync = globStreamSync; +export const stream = Object.assign(globStream, { sync: globStreamSync }); +export const iterateSync = globIterateSync; +export const iterate = Object.assign(globIterate, { + sync: globIterateSync, +}); +export const sync = Object.assign(globSync, { + stream: globStreamSync, + iterate: globIterateSync, +}); +export const glob = Object.assign(glob_, { + glob: glob_, + globSync, + sync, + globStream, + stream, + globStreamSync, + streamSync, + globIterate, + iterate, + globIterateSync, + iterateSync, + Glob, + hasMagic, + escape, + unescape, +}); +glob.glob = glob; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/index.js.map b/node_modules/glob/dist/esm/index.js.map new file mode 100644 index 0000000..a4f93dd --- /dev/null +++ b/node_modules/glob/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[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AAC,OAAO,EAAE,OAAO,CAAC,CAAC,OAAO,EAAE,CAAA;AAC7C,CAAC;AAED,iEAAiE;AACjE,MAAM,CAAC,MAAM,UAAU,GAAG,cAAc,CAAA;AACxC,MAAM,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC,CAAA;AACzE,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAA;AAC1C,MAAM,CAAC,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE;IAChD,IAAI,EAAE,eAAe;CACtB,CAAC,CAAA;AACF,MAAM,CAAC,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE;IAC1C,MAAM,EAAE,cAAc;IACtB,OAAO,EAAE,eAAe;CACzB,CAAC,CAAA;AAEF,MAAM,CAAC,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE;IACvC,IAAI,EAAE,KAAK;IACX,QAAQ;IACR,IAAI;IACJ,UAAU;IACV,MAAM;IACN,cAAc;IACd,UAAU;IACV,WAAW;IACX,OAAO;IACP,eAAe;IACf,WAAW;IACX,IAAI;IACJ,QAAQ;IACR,MAAM;IACN,QAAQ;CACT,CAAC,CAAA;AACF,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA","sourcesContent":["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\nexport { escape, unescape } from 'minimatch'\nexport type {\n FSOption,\n Path,\n WalkOptions,\n WalkOptionsWithFileTypesTrue,\n WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\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 { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.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\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"]} \ No newline at end of file diff --git a/node_modules/glob/dist/esm/package.json b/node_modules/glob/dist/esm/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/node_modules/glob/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/glob/dist/esm/pattern.d.ts b/node_modules/glob/dist/esm/pattern.d.ts new file mode 100644 index 0000000..9636df3 --- /dev/null +++ b/node_modules/glob/dist/esm/pattern.d.ts @@ -0,0 +1,76 @@ +import { GLOBSTAR } from 'minimatch'; +export type MMPattern = string | RegExp | typeof GLOBSTAR; +export type PatternList = [p: MMPattern, ...rest: MMPattern[]]; +export type UNCPatternList = [ + p0: '', + p1: '', + p2: string, + p3: string, + ...rest: MMPattern[] +]; +export type DrivePatternList = [p0: string, ...rest: MMPattern[]]; +export type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]; +export type GlobList = [p: string, ...rest: string[]]; +/** + * An immutable-ish view on an array of glob parts and their parsed + * results + */ +export declare class Pattern { + #private; + readonly length: number; + constructor(patternList: MMPattern[], globList: string[], index: number, platform: NodeJS.Platform); + /** + * The first entry in the parsed list of patterns + */ + pattern(): MMPattern; + /** + * true of if pattern() returns a string + */ + isString(): boolean; + /** + * true of if pattern() returns GLOBSTAR + */ + isGlobstar(): boolean; + /** + * true if pattern() returns a regexp + */ + isRegExp(): boolean; + /** + * The /-joined set of glob parts that make up this pattern + */ + globString(): string; + /** + * true if there are more pattern parts after this one + */ + hasMore(): boolean; + /** + * The rest of the pattern after this part, or null if this is the end + */ + rest(): Pattern | null; + /** + * true if the pattern represents a //unc/path/ on windows + */ + isUNC(): boolean; + /** + * True if the pattern starts with a drive letter on Windows + */ + isDrive(): boolean; + /** + * True if the pattern is rooted on an absolute path + */ + isAbsolute(): boolean; + /** + * consume the root of the pattern, and return it + */ + root(): string; + /** + * Check to see if the current globstar pattern is allowed to follow + * a symbolic link. + */ + checkFollowGlobstar(): boolean; + /** + * Mark that the current globstar pattern is following a symbolic link + */ + markFollowGlobstar(): boolean; +} +//# sourceMappingURL=pattern.d.ts.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/pattern.d.ts.map b/node_modules/glob/dist/esm/pattern.d.ts.map new file mode 100644 index 0000000..cdf3223 --- /dev/null +++ b/node_modules/glob/dist/esm/pattern.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pattern.d.ts","sourceRoot":"","sources":["../../src/pattern.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,QAAQ,CAAA;AAGzD,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;AAC9D,MAAM,MAAM,cAAc,GAAG;IAC3B,EAAE,EAAE,EAAE;IACN,EAAE,EAAE,EAAE;IACN,EAAE,EAAE,MAAM;IACV,EAAE,EAAE,MAAM;IACV,GAAG,IAAI,EAAE,SAAS,EAAE;CACrB,CAAA;AACD,MAAM,MAAM,gBAAgB,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;AACjE,MAAM,MAAM,mBAAmB,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;AAChE,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,CAAC,CAAA;AAMrD;;;GAGG;AACH,qBAAa,OAAO;;IAIlB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;gBAUrB,WAAW,EAAE,SAAS,EAAE,EACxB,QAAQ,EAAE,MAAM,EAAE,EAClB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,CAAC,QAAQ;IA6D3B;;OAEG;IACH,OAAO,IAAI,SAAS;IAIpB;;OAEG;IACH,QAAQ,IAAI,OAAO;IAGnB;;OAEG;IACH,UAAU,IAAI,OAAO;IAGrB;;OAEG;IACH,QAAQ,IAAI,OAAO;IAInB;;OAEG;IACH,UAAU,IAAI,MAAM;IAUpB;;OAEG;IACH,OAAO,IAAI,OAAO;IAIlB;;OAEG;IACH,IAAI,IAAI,OAAO,GAAG,IAAI;IAetB;;OAEG;IACH,KAAK,IAAI,OAAO;IAoBhB;;OAEG;IACH,OAAO,IAAI,OAAO;IAelB;;OAEG;IACH,UAAU,IAAI,OAAO;IAUrB;;OAEG;IACH,IAAI,IAAI,MAAM;IASd;;;OAGG;IACH,mBAAmB,IAAI,OAAO;IAQ9B;;OAEG;IACH,kBAAkB,IAAI,OAAO;CAM9B"} \ No newline at end of file diff --git a/node_modules/glob/dist/esm/pattern.js b/node_modules/glob/dist/esm/pattern.js new file mode 100644 index 0000000..b41defa --- /dev/null +++ b/node_modules/glob/dist/esm/pattern.js @@ -0,0 +1,215 @@ +// this is just a very light wrapper around 2 arrays with an offset index +import { GLOBSTAR } from 'minimatch'; +const isPatternList = (pl) => pl.length >= 1; +const isGlobList = (gl) => gl.length >= 1; +/** + * An immutable-ish view on an array of glob parts and their parsed + * results + */ +export class Pattern { + #patternList; + #globList; + #index; + length; + #platform; + #rest; + #globString; + #isDrive; + #isUNC; + #isAbsolute; + #followGlobstar = true; + constructor(patternList, globList, index, platform) { + if (!isPatternList(patternList)) { + throw new TypeError('empty pattern list'); + } + if (!isGlobList(globList)) { + throw new TypeError('empty glob list'); + } + if (globList.length !== patternList.length) { + throw new TypeError('mismatched pattern list and glob list lengths'); + } + this.length = patternList.length; + if (index < 0 || index >= this.length) { + throw new TypeError('index out of range'); + } + this.#patternList = patternList; + this.#globList = globList; + this.#index = index; + this.#platform = platform; + // normalize root entries of absolute patterns on initial creation. + if (this.#index === 0) { + // c: => ['c:/'] + // C:/ => ['C:/'] + // C:/x => ['C:/', 'x'] + // //host/share => ['//host/share/'] + // //host/share/ => ['//host/share/'] + // //host/share/x => ['//host/share/', 'x'] + // /etc => ['/', 'etc'] + // / => ['/'] + if (this.isUNC()) { + // '' / '' / 'host' / 'share' + const [p0, p1, p2, p3, ...prest] = this.#patternList; + const [g0, g1, g2, g3, ...grest] = this.#globList; + if (prest[0] === '') { + // ends in / + prest.shift(); + grest.shift(); + } + const p = [p0, p1, p2, p3, ''].join('/'); + const g = [g0, g1, g2, g3, ''].join('/'); + this.#patternList = [p, ...prest]; + this.#globList = [g, ...grest]; + this.length = this.#patternList.length; + } + else if (this.isDrive() || this.isAbsolute()) { + const [p1, ...prest] = this.#patternList; + const [g1, ...grest] = this.#globList; + if (prest[0] === '') { + // ends in / + prest.shift(); + grest.shift(); + } + const p = p1 + '/'; + const g = g1 + '/'; + this.#patternList = [p, ...prest]; + this.#globList = [g, ...grest]; + this.length = this.#patternList.length; + } + } + } + /** + * The first entry in the parsed list of patterns + */ + pattern() { + return this.#patternList[this.#index]; + } + /** + * true of if pattern() returns a string + */ + isString() { + return typeof this.#patternList[this.#index] === 'string'; + } + /** + * true of if pattern() returns GLOBSTAR + */ + isGlobstar() { + return this.#patternList[this.#index] === GLOBSTAR; + } + /** + * true if pattern() returns a regexp + */ + isRegExp() { + return this.#patternList[this.#index] instanceof RegExp; + } + /** + * The /-joined set of glob parts that make up this pattern + */ + globString() { + return (this.#globString = + this.#globString || + (this.#index === 0 ? + this.isAbsolute() ? + this.#globList[0] + this.#globList.slice(1).join('/') + : this.#globList.join('/') + : this.#globList.slice(this.#index).join('/'))); + } + /** + * true if there are more pattern parts after this one + */ + hasMore() { + return this.length > this.#index + 1; + } + /** + * The rest of the pattern after this part, or null if this is the end + */ + rest() { + if (this.#rest !== undefined) + return this.#rest; + if (!this.hasMore()) + return (this.#rest = null); + this.#rest = new Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform); + this.#rest.#isAbsolute = this.#isAbsolute; + this.#rest.#isUNC = this.#isUNC; + this.#rest.#isDrive = this.#isDrive; + return this.#rest; + } + /** + * true if the pattern represents a //unc/path/ on windows + */ + isUNC() { + const pl = this.#patternList; + return this.#isUNC !== undefined ? + this.#isUNC + : (this.#isUNC = + this.#platform === 'win32' && + this.#index === 0 && + pl[0] === '' && + pl[1] === '' && + typeof pl[2] === 'string' && + !!pl[2] && + typeof pl[3] === 'string' && + !!pl[3]); + } + // pattern like C:/... + // split = ['C:', ...] + // XXX: would be nice to handle patterns like `c:*` to test the cwd + // in c: for *, but I don't know of a way to even figure out what that + // cwd is without actually chdir'ing into it? + /** + * True if the pattern starts with a drive letter on Windows + */ + isDrive() { + const pl = this.#patternList; + return this.#isDrive !== undefined ? + this.#isDrive + : (this.#isDrive = + this.#platform === 'win32' && + this.#index === 0 && + this.length > 1 && + typeof pl[0] === 'string' && + /^[a-z]:$/i.test(pl[0])); + } + // pattern = '/' or '/...' or '/x/...' + // split = ['', ''] or ['', ...] or ['', 'x', ...] + // Drive and UNC both considered absolute on windows + /** + * True if the pattern is rooted on an absolute path + */ + isAbsolute() { + const pl = this.#patternList; + return this.#isAbsolute !== undefined ? + this.#isAbsolute + : (this.#isAbsolute = + (pl[0] === '' && pl.length > 1) || + this.isDrive() || + this.isUNC()); + } + /** + * consume the root of the pattern, and return it + */ + root() { + const p = this.#patternList[0]; + return (typeof p === 'string' && this.isAbsolute() && this.#index === 0) ? + p + : ''; + } + /** + * Check to see if the current globstar pattern is allowed to follow + * a symbolic link. + */ + checkFollowGlobstar() { + return !(this.#index === 0 || + !this.isGlobstar() || + !this.#followGlobstar); + } + /** + * Mark that the current globstar pattern is following a symbolic link + */ + markFollowGlobstar() { + if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar) + return false; + this.#followGlobstar = false; + return true; + } +} +//# sourceMappingURL=pattern.js.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/pattern.js.map b/node_modules/glob/dist/esm/pattern.js.map new file mode 100644 index 0000000..566a306 --- /dev/null +++ b/node_modules/glob/dist/esm/pattern.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pattern.js","sourceRoot":"","sources":["../../src/pattern.ts"],"names":[],"mappings":"AAAA,yEAAyE;AAEzE,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAgBpC,MAAM,aAAa,GAAG,CAAC,EAAe,EAAqB,EAAE,CAC3D,EAAE,CAAC,MAAM,IAAI,CAAC,CAAA;AAChB,MAAM,UAAU,GAAG,CAAC,EAAY,EAAkB,EAAE,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,CAAA;AAEnE;;;GAGG;AACH,MAAM,OAAO,OAAO;IACT,YAAY,CAAa;IACzB,SAAS,CAAU;IACnB,MAAM,CAAQ;IACd,MAAM,CAAQ;IACd,SAAS,CAAiB;IACnC,KAAK,CAAiB;IACtB,WAAW,CAAS;IACpB,QAAQ,CAAU;IAClB,MAAM,CAAU;IAChB,WAAW,CAAU;IACrB,eAAe,GAAY,IAAI,CAAA;IAE/B,YACE,WAAwB,EACxB,QAAkB,EAClB,KAAa,EACb,QAAyB;QAEzB,IAAI,CAAC,aAAa,CAAC,WAAW,CAAC,EAAE,CAAC;YAChC,MAAM,IAAI,SAAS,CAAC,oBAAoB,CAAC,CAAA;QAC3C,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC1B,MAAM,IAAI,SAAS,CAAC,iBAAiB,CAAC,CAAA;QACxC,CAAC;QACD,IA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QAC5B,OAAO,IAAI,CAAA;IACb,CAAC;CACF","sourcesContent":["// 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 (\n typeof p === 'string' && this.isAbsolute() && this.#index === 0\n ) ?\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"]} \ No newline at end of file diff --git a/node_modules/glob/dist/esm/processor.d.ts b/node_modules/glob/dist/esm/processor.d.ts new file mode 100644 index 0000000..ccedfbf --- /dev/null +++ b/node_modules/glob/dist/esm/processor.d.ts @@ -0,0 +1,59 @@ +import { MMRegExp } from 'minimatch'; +import { Path } from 'path-scurry'; +import { Pattern } from './pattern.js'; +import { GlobWalkerOpts } from './walker.js'; +/** + * A cache of which patterns have been processed for a given Path + */ +export declare class HasWalkedCache { + store: Map>; + constructor(store?: Map>); + copy(): HasWalkedCache; + hasWalked(target: Path, pattern: Pattern): boolean | undefined; + storeWalked(target: Path, pattern: Pattern): void; +} +/** + * A record of which paths have been matched in a given walk step, + * and whether they only are considered a match if they are a directory, + * and whether their absolute or relative path should be returned. + */ +export declare class MatchRecord { + store: Map; + add(target: Path, absolute: boolean, ifDir: boolean): void; + entries(): [Path, boolean, boolean][]; +} +/** + * A collection of patterns that must be processed in a subsequent step + * for a given path. + */ +export declare class SubWalks { + store: Map; + add(target: Path, pattern: Pattern): void; + get(target: Path): Pattern[]; + entries(): [Path, Pattern[]][]; + keys(): Path[]; +} +/** + * The class that processes patterns for a given path. + * + * Handles child entry filtering, and determining whether a path's + * directory contents must be read. + */ +export declare class Processor { + hasWalkedCache: HasWalkedCache; + matches: MatchRecord; + subwalks: SubWalks; + patterns?: Pattern[]; + follow: boolean; + dot: boolean; + opts: GlobWalkerOpts; + constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache); + processPatterns(target: Path, patterns: Pattern[]): this; + subwalkTargets(): Path[]; + child(): Processor; + filterEntries(parent: Path, entries: Path[]): Processor; + testGlobstar(e: Path, pattern: Pattern, rest: Pattern | null, absolute: boolean): void; + testRegExp(e: Path, p: MMRegExp, rest: Pattern | null, absolute: boolean): void; + testString(e: Path, p: string, rest: Pattern | null, absolute: boolean): void; +} +//# sourceMappingURL=processor.d.ts.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/processor.d.ts.map b/node_modules/glob/dist/esm/processor.d.ts.map new file mode 100644 index 0000000..aa266fe --- /dev/null +++ b/node_modules/glob/dist/esm/processor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"processor.d.ts","sourceRoot":"","sources":["../../src/processor.ts"],"names":[],"mappings":"AAEA,OAAO,EAAY,QAAQ,EAAE,MAAM,WAAW,CAAA;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAa,OAAO,EAAE,MAAM,cAAc,CAAA;AACjD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C;;GAEG;AACH,qBAAa,cAAc;IACzB,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAA;gBACnB,KAAK,GAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAa;IAGvD,IAAI;IAGJ,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;IAGxC,WAAW,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;CAM3C;AAED;;;;GAIG;AACH,qBAAa,WAAW;IACtB,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAY;IACpC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO;IAMnD,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE;CAOtC;AAED;;;GAGG;AACH,qBAAa,QAAQ;IACnB,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAY;IACvC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;IAWlC,GAAG,CAAC,MAAM,EAAE,IAAI,GAAG,OAAO,EAAE;IAS5B,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE;IAG9B,IAAI,IAAI,IAAI,EAAE;CAGf;AAED;;;;;GAKG;AACH,qBAAa,SAAS;IACpB,cAAc,EAAE,cAAc,CAAA;IAC9B,OAAO,cAAoB;IAC3B,QAAQ,WAAiB;IACzB,QAAQ,CAAC,EAAE,OAAO,EAAE,CAAA;IACpB,MAAM,EAAE,OAAO,CAAA;IACf,GAAG,EAAE,OAAO,CAAA;IACZ,IAAI,EAAE,cAAc,CAAA;gBAER,IAAI,EAAE,cAAc,EAAE,cAAc,CAAC,EAAE,cAAc;IAQjE,eAAe,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE;IAmGjD,cAAc,IAAI,IAAI,EAAE;IAIxB,KAAK;IAQL,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,SAAS;IAqBvD,YAAY,CACV,CAAC,EAAE,IAAI,EACP,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,OAAO,GAAG,IAAI,EACpB,QAAQ,EAAE,OAAO;IA8CnB,UAAU,CACR,CAAC,EAAE,IAAI,EACP,CAAC,EAAE,QAAQ,EACX,IAAI,EAAE,OAAO,GAAG,IAAI,EACpB,QAAQ,EAAE,OAAO;IAUnB,UAAU,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,IAAI,EAAE,QAAQ,EAAE,OAAO;CASvE"} \ No newline at end of file diff --git a/node_modules/glob/dist/esm/processor.js b/node_modules/glob/dist/esm/processor.js new file mode 100644 index 0000000..f874892 --- /dev/null +++ b/node_modules/glob/dist/esm/processor.js @@ -0,0 +1,294 @@ +// synchronous utility for filtering entries and calculating subwalks +import { GLOBSTAR } from 'minimatch'; +/** + * A cache of which patterns have been processed for a given Path + */ +export class HasWalkedCache { + store; + constructor(store = new Map()) { + this.store = store; + } + copy() { + return new HasWalkedCache(new Map(this.store)); + } + hasWalked(target, pattern) { + return this.store.get(target.fullpath())?.has(pattern.globString()); + } + storeWalked(target, pattern) { + const fullpath = target.fullpath(); + const cached = this.store.get(fullpath); + if (cached) + cached.add(pattern.globString()); + else + this.store.set(fullpath, new Set([pattern.globString()])); + } +} +/** + * A record of which paths have been matched in a given walk step, + * and whether they only are considered a match if they are a directory, + * and whether their absolute or relative path should be returned. + */ +export class MatchRecord { + store = new Map(); + add(target, absolute, ifDir) { + const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0); + const current = this.store.get(target); + this.store.set(target, current === undefined ? n : n & current); + } + // match, absolute, ifdir + entries() { + return [...this.store.entries()].map(([path, n]) => [ + path, + !!(n & 2), + !!(n & 1), + ]); + } +} +/** + * A collection of patterns that must be processed in a subsequent step + * for a given path. + */ +export class SubWalks { + store = new Map(); + add(target, pattern) { + if (!target.canReaddir()) { + return; + } + const subs = this.store.get(target); + if (subs) { + if (!subs.find(p => p.globString() === pattern.globString())) { + subs.push(pattern); + } + } + else + this.store.set(target, [pattern]); + } + get(target) { + const subs = this.store.get(target); + /* c8 ignore start */ + if (!subs) { + throw new Error('attempting to walk unknown path'); + } + /* c8 ignore stop */ + return subs; + } + entries() { + return this.keys().map(k => [k, this.store.get(k)]); + } + keys() { + return [...this.store.keys()].filter(t => t.canReaddir()); + } +} +/** + * The class that processes patterns for a given path. + * + * Handles child entry filtering, and determining whether a path's + * directory contents must be read. + */ +export class Processor { + hasWalkedCache; + matches = new MatchRecord(); + subwalks = new SubWalks(); + patterns; + follow; + dot; + opts; + constructor(opts, hasWalkedCache) { + this.opts = opts; + this.follow = !!opts.follow; + this.dot = !!opts.dot; + this.hasWalkedCache = + hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache(); + } + processPatterns(target, patterns) { + this.patterns = patterns; + const processingSet = patterns.map(p => [target, p]); + // map of paths to the magic-starting subwalks they need to walk + // first item in patterns is the filter + for (let [t, pattern] of processingSet) { + this.hasWalkedCache.storeWalked(t, pattern); + const root = pattern.root(); + const absolute = pattern.isAbsolute() && this.opts.absolute !== false; + // start absolute patterns at root + if (root) { + t = t.resolve(root === '/' && this.opts.root !== undefined ? + this.opts.root + : root); + const rest = pattern.rest(); + if (!rest) { + this.matches.add(t, true, false); + continue; + } + else { + pattern = rest; + } + } + if (t.isENOENT()) + continue; + let p; + let rest; + let changed = false; + while (typeof (p = pattern.pattern()) === 'string' && + (rest = pattern.rest())) { + const c = t.resolve(p); + t = c; + pattern = rest; + changed = true; + } + p = pattern.pattern(); + rest = pattern.rest(); + if (changed) { + if (this.hasWalkedCache.hasWalked(t, pattern)) + continue; + this.hasWalkedCache.storeWalked(t, pattern); + } + // now we have either a final string for a known entry, + // more strings for an unknown entry, + // or a pattern starting with magic, mounted on t. + if (typeof p === 'string') { + // must not be final entry, otherwise we would have + // concatenated it earlier. + const ifDir = p === '..' || p === '' || p === '.'; + this.matches.add(t.resolve(p), absolute, ifDir); + continue; + } + else if (p === GLOBSTAR) { + // if no rest, match and subwalk pattern + // if rest, process rest and subwalk pattern + // if it's a symlink, but we didn't get here by way of a + // globstar match (meaning it's the first time THIS globstar + // has traversed a symlink), then we follow it. Otherwise, stop. + if (!t.isSymbolicLink() || + this.follow || + pattern.checkFollowGlobstar()) { + this.subwalks.add(t, pattern); + } + const rp = rest?.pattern(); + const rrest = rest?.rest(); + if (!rest || ((rp === '' || rp === '.') && !rrest)) { + // only HAS to be a dir if it ends in **/ or **/. + // but ending in ** will match files as well. + this.matches.add(t, absolute, rp === '' || rp === '.'); + } + else { + if (rp === '..') { + // this would mean you're matching **/.. at the fs root, + // and no thanks, I'm not gonna test that specific case. + /* c8 ignore start */ + const tp = t.parent || t; + /* c8 ignore stop */ + if (!rrest) + this.matches.add(tp, absolute, true); + else if (!this.hasWalkedCache.hasWalked(tp, rrest)) { + this.subwalks.add(tp, rrest); + } + } + } + } + else if (p instanceof RegExp) { + this.subwalks.add(t, pattern); + } + } + return this; + } + subwalkTargets() { + return this.subwalks.keys(); + } + child() { + return new Processor(this.opts, this.hasWalkedCache); + } + // return a new Processor containing the subwalks for each + // child entry, and a set of matches, and + // a hasWalkedCache that's a copy of this one + // then we're going to call + filterEntries(parent, entries) { + const patterns = this.subwalks.get(parent); + // put matches and entry walks into the results processor + const results = this.child(); + for (const e of entries) { + for (const pattern of patterns) { + const absolute = pattern.isAbsolute(); + const p = pattern.pattern(); + const rest = pattern.rest(); + if (p === GLOBSTAR) { + results.testGlobstar(e, pattern, rest, absolute); + } + else if (p instanceof RegExp) { + results.testRegExp(e, p, rest, absolute); + } + else { + results.testString(e, p, rest, absolute); + } + } + } + return results; + } + testGlobstar(e, pattern, rest, absolute) { + if (this.dot || !e.name.startsWith('.')) { + if (!pattern.hasMore()) { + this.matches.add(e, absolute, false); + } + if (e.canReaddir()) { + // if we're in follow mode or it's not a symlink, just keep + // testing the same pattern. If there's more after the globstar, + // then this symlink consumes the globstar. If not, then we can + // follow at most ONE symlink along the way, so we mark it, which + // also checks to ensure that it wasn't already marked. + if (this.follow || !e.isSymbolicLink()) { + this.subwalks.add(e, pattern); + } + else if (e.isSymbolicLink()) { + if (rest && pattern.checkFollowGlobstar()) { + this.subwalks.add(e, rest); + } + else if (pattern.markFollowGlobstar()) { + this.subwalks.add(e, pattern); + } + } + } + } + // if the NEXT thing matches this entry, then also add + // the rest. + if (rest) { + const rp = rest.pattern(); + if (typeof rp === 'string' && + // dots and empty were handled already + rp !== '..' && + rp !== '' && + rp !== '.') { + this.testString(e, rp, rest.rest(), absolute); + } + else if (rp === '..') { + /* c8 ignore start */ + const ep = e.parent || e; + /* c8 ignore stop */ + this.subwalks.add(ep, rest); + } + else if (rp instanceof RegExp) { + this.testRegExp(e, rp, rest.rest(), absolute); + } + } + } + testRegExp(e, p, rest, absolute) { + if (!p.test(e.name)) + return; + if (!rest) { + this.matches.add(e, absolute, false); + } + else { + this.subwalks.add(e, rest); + } + } + testString(e, p, rest, absolute) { + // should never happen? + if (!e.isNamed(p)) + return; + if (!rest) { + this.matches.add(e, absolute, false); + } + else { + this.subwalks.add(e, rest); + } + } +} +//# sourceMappingURL=processor.js.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/processor.js.map b/node_modules/glob/dist/esm/processor.js.map new file mode 100644 index 0000000..05a8324 --- /dev/null +++ b/node_modules/glob/dist/esm/processor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"processor.js","sourceRoot":"","sources":["../../src/processor.ts"],"names":[],"mappings":"AAAA,qEAAqE;AAErE,OAAO,EAAE,QAAQ,EAAY,MAAM,WAAW,CAAA;AAK9C;;GAEG;AACH,MAAM,OAAO,cAAc;IACzB,KAAK,CAA0B;IAC/B,YAAY,QAAkC,IAAI,GAAG,EAAE;QACrD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;IACD,IAAI;QACF,OAAO,IAAI,cAAc,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAA;IAChD,CAAC;IACD,SAAS,CAAC,MAAY,EAAE,OAAgB;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAA;IACrE,CAAC;IACD,WAAW,CAAC,MAAY,EAAE,OAAgB;QACxC,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAA;QAClC,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAA;QACvC,IAAI,MAAM;YAAE,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAA;;YACvC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,CAAA;IAChE,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,OAAO,WAAW;IACtB,KAAK,GAAsB,IAAI,GAAG,EAAE,CAAA;IACpC,GAAG,CAAC,MAAY,EAAE,QAAiB,EAAE,KA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IAAI,EAAE,CAAC;gBACvB,qBAAqB;gBACrB,MAAM,EAAE,GAAG,CAAC,CAAC,MAAM,IAAI,CAAC,CAAA;gBACxB,oBAAoB;gBACpB,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;YAC7B,CAAC;iBAAM,IAAI,EAAE,YAAY,MAAM,EAAE,CAAC;gBAChC,IAAI,CAAC,UAAU,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,IAAI,EAAE,EAAE,QAAQ,CAAC,CAAA;YAC/C,CAAC;QACH,CAAC;IACH,CAAC;IAED,UAAU,CACR,CAAO,EACP,CAAW,EACX,IAAoB,EACpB,QAAiB;QAEjB,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;YAAE,OAAM;QAC3B,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACtC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;IAED,UAAU,CAAC,CAAO,EAAE,CAAS,EAAE,IAAoB,EAAE,QAAiB;QACpE,uBAAuB;QACvB,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;YAAE,OAAM;QACzB,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACtC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;CACF","sourcesContent":["// 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 =\n hasWalkedCache ? hasWalkedCache.copy() : 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"]} \ No newline at end of file diff --git a/node_modules/glob/dist/esm/walker.d.ts b/node_modules/glob/dist/esm/walker.d.ts new file mode 100644 index 0000000..499c8f4 --- /dev/null +++ b/node_modules/glob/dist/esm/walker.d.ts @@ -0,0 +1,97 @@ +/** + * Single-use utility classes to provide functionality to the {@link Glob} + * methods. + * + * @module + */ +import { Minipass } from 'minipass'; +import { Path } from 'path-scurry'; +import { IgnoreLike } from './ignore.js'; +import { Pattern } from './pattern.js'; +import { Processor } from './processor.js'; +export interface GlobWalkerOpts { + absolute?: boolean; + allowWindowsEscape?: boolean; + cwd?: string | URL; + dot?: boolean; + dotRelative?: boolean; + follow?: boolean; + ignore?: string | string[] | IgnoreLike; + mark?: boolean; + matchBase?: boolean; + maxDepth?: number; + nobrace?: boolean; + nocase?: boolean; + nodir?: boolean; + noext?: boolean; + noglobstar?: boolean; + platform?: NodeJS.Platform; + posix?: boolean; + realpath?: boolean; + root?: string; + stat?: boolean; + signal?: AbortSignal; + windowsPathsNoEscape?: boolean; + withFileTypes?: boolean; + includeChildMatches?: boolean; +} +export type GWOFileTypesTrue = GlobWalkerOpts & { + withFileTypes: true; +}; +export type GWOFileTypesFalse = GlobWalkerOpts & { + withFileTypes: false; +}; +export type GWOFileTypesUnset = GlobWalkerOpts & { + withFileTypes?: undefined; +}; +export type Result = O extends GWOFileTypesTrue ? Path : O extends GWOFileTypesFalse ? string : O extends GWOFileTypesUnset ? string : Path | string; +export type Matches = O extends GWOFileTypesTrue ? Set : O extends GWOFileTypesFalse ? Set : O extends GWOFileTypesUnset ? Set : Set; +export type MatchStream = Minipass, Result>; +/** + * basic walking utilities that all the glob walker types use + */ +export declare abstract class GlobUtil { + #private; + path: Path; + patterns: Pattern[]; + opts: O; + seen: Set; + paused: boolean; + aborted: boolean; + signal?: AbortSignal; + maxDepth: number; + includeChildMatches: boolean; + constructor(patterns: Pattern[], path: Path, opts: O); + pause(): void; + resume(): void; + onResume(fn: () => any): void; + matchCheck(e: Path, ifDir: boolean): Promise; + matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined; + matchCheckSync(e: Path, ifDir: boolean): Path | undefined; + abstract matchEmit(p: Result): void; + abstract matchEmit(p: string | Path): void; + matchFinish(e: Path, absolute: boolean): void; + match(e: Path, absolute: boolean, ifDir: boolean): Promise; + matchSync(e: Path, absolute: boolean, ifDir: boolean): void; + walkCB(target: Path, patterns: Pattern[], cb: () => any): void; + walkCB2(target: Path, patterns: Pattern[], processor: Processor, cb: () => any): any; + walkCB3(target: Path, entries: Path[], processor: Processor, cb: () => any): void; + walkCBSync(target: Path, patterns: Pattern[], cb: () => any): void; + walkCB2Sync(target: Path, patterns: Pattern[], processor: Processor, cb: () => any): any; + walkCB3Sync(target: Path, entries: Path[], processor: Processor, cb: () => any): void; +} +export declare class GlobWalker extends GlobUtil { + matches: Set>; + constructor(patterns: Pattern[], path: Path, opts: O); + matchEmit(e: Result): void; + walk(): Promise>>; + walkSync(): Set>; +} +export declare class GlobStream extends GlobUtil { + results: Minipass, Result>; + constructor(patterns: Pattern[], path: Path, opts: O); + matchEmit(e: Result): void; + stream(): MatchStream; + streamSync(): MatchStream; +} +//# sourceMappingURL=walker.d.ts.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/walker.d.ts.map b/node_modules/glob/dist/esm/walker.d.ts.map new file mode 100644 index 0000000..769957b --- /dev/null +++ b/node_modules/glob/dist/esm/walker.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"walker.d.ts","sourceRoot":"","sources":["../../src/walker.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAU,UAAU,EAAE,MAAM,aAAa,CAAA;AAOhD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAE1C,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAC5B,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,CAAA;IAClB,GAAG,CAAC,EAAE,OAAO,CAAA;IACb,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,UAAU,CAAA;IACvC,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,SAAS,CAAC,EAAE,OAAO,CAAA;IAGnB,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C,CAAC;IAiBrC,QAAQ,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;CAW3B;AAED,qBAAa,UAAU,CACrB,CAAC,SAAS,cAAc,GAAG,cAAc,CACzC,SAAQ,QAAQ,CAAC,CAAC,CAAC;IACnB,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;gBAE3B,QAAQ,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAUpD,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI;IAK7B,MAAM,IAAI,WAAW,CAAC,CAAC,CAAC;IAYxB,UAAU,IAAI,WAAW,CAAC,CAAC,CAAC;CAO7B"} \ No newline at end of file diff --git a/node_modules/glob/dist/esm/walker.js b/node_modules/glob/dist/esm/walker.js new file mode 100644 index 0000000..3d68196 --- /dev/null +++ b/node_modules/glob/dist/esm/walker.js @@ -0,0 +1,381 @@ +/** + * Single-use utility classes to provide functionality to the {@link Glob} + * methods. + * + * @module + */ +import { Minipass } from 'minipass'; +import { Ignore } from './ignore.js'; +import { Processor } from './processor.js'; +const makeIgnore = (ignore, opts) => typeof ignore === 'string' ? new Ignore([ignore], opts) + : Array.isArray(ignore) ? new Ignore(ignore, opts) + : ignore; +/** + * basic walking utilities that all the glob walker types use + */ +export class GlobUtil { + path; + patterns; + opts; + seen = new Set(); + paused = false; + aborted = false; + #onResume = []; + #ignore; + #sep; + signal; + maxDepth; + includeChildMatches; + constructor(patterns, path, opts) { + this.patterns = patterns; + this.path = path; + this.opts = opts; + this.#sep = !opts.posix && opts.platform === 'win32' ? '\\' : '/'; + this.includeChildMatches = opts.includeChildMatches !== false; + if (opts.ignore || !this.includeChildMatches) { + this.#ignore = makeIgnore(opts.ignore ?? [], opts); + if (!this.includeChildMatches && + typeof this.#ignore.add !== 'function') { + const m = 'cannot ignore child matches, ignore lacks add() method.'; + throw new Error(m); + } + } + // ignore, always set with maxDepth, but it's optional on the + // GlobOptions type + /* c8 ignore start */ + this.maxDepth = opts.maxDepth || Infinity; + /* c8 ignore stop */ + if (opts.signal) { + this.signal = opts.signal; + this.signal.addEventListener('abort', () => { + this.#onResume.length = 0; + }); + } + } + #ignored(path) { + return this.seen.has(path) || !!this.#ignore?.ignored?.(path); + } + #childrenIgnored(path) { + return !!this.#ignore?.childrenIgnored?.(path); + } + // backpressure mechanism + pause() { + this.paused = true; + } + resume() { + /* c8 ignore start */ + if (this.signal?.aborted) + return; + /* c8 ignore stop */ + this.paused = false; + let fn = undefined; + while (!this.paused && (fn = this.#onResume.shift())) { + fn(); + } + } + onResume(fn) { + if (this.signal?.aborted) + return; + /* c8 ignore start */ + if (!this.paused) { + fn(); + } + else { + /* c8 ignore stop */ + this.#onResume.push(fn); + } + } + // do the requisite realpath/stat checking, and return the path + // to add or undefined to filter it out. + async matchCheck(e, ifDir) { + if (ifDir && this.opts.nodir) + return undefined; + let rpc; + if (this.opts.realpath) { + rpc = e.realpathCached() || (await e.realpath()); + if (!rpc) + return undefined; + e = rpc; + } + const needStat = e.isUnknown() || this.opts.stat; + const s = needStat ? await e.lstat() : e; + if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) { + const target = await s.realpath(); + /* c8 ignore start */ + if (target && (target.isUnknown() || this.opts.stat)) { + await target.lstat(); + } + /* c8 ignore stop */ + } + return this.matchCheckTest(s, ifDir); + } + matchCheckTest(e, ifDir) { + return (e && + (this.maxDepth === Infinity || e.depth() <= this.maxDepth) && + (!ifDir || e.canReaddir()) && + (!this.opts.nodir || !e.isDirectory()) && + (!this.opts.nodir || + !this.opts.follow || + !e.isSymbolicLink() || + !e.realpathCached()?.isDirectory()) && + !this.#ignored(e)) ? + e + : undefined; + } + matchCheckSync(e, ifDir) { + if (ifDir && this.opts.nodir) + return undefined; + let rpc; + if (this.opts.realpath) { + rpc = e.realpathCached() || e.realpathSync(); + if (!rpc) + return undefined; + e = rpc; + } + const needStat = e.isUnknown() || this.opts.stat; + const s = needStat ? e.lstatSync() : e; + if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) { + const target = s.realpathSync(); + if (target && (target?.isUnknown() || this.opts.stat)) { + target.lstatSync(); + } + } + return this.matchCheckTest(s, ifDir); + } + matchFinish(e, absolute) { + if (this.#ignored(e)) + return; + // we know we have an ignore if this is false, but TS doesn't + if (!this.includeChildMatches && this.#ignore?.add) { + const ign = `${e.relativePosix()}/**`; + this.#ignore.add(ign); + } + const abs = this.opts.absolute === undefined ? absolute : this.opts.absolute; + this.seen.add(e); + const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''; + // ok, we have what we need! + if (this.opts.withFileTypes) { + this.matchEmit(e); + } + else if (abs) { + const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath(); + this.matchEmit(abs + mark); + } + else { + const rel = this.opts.posix ? e.relativePosix() : e.relative(); + const pre = this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ? + '.' + this.#sep + : ''; + this.matchEmit(!rel ? '.' + mark : pre + rel + mark); + } + } + async match(e, absolute, ifDir) { + const p = await this.matchCheck(e, ifDir); + if (p) + this.matchFinish(p, absolute); + } + matchSync(e, absolute, ifDir) { + const p = this.matchCheckSync(e, ifDir); + if (p) + this.matchFinish(p, absolute); + } + walkCB(target, patterns, cb) { + /* c8 ignore start */ + if (this.signal?.aborted) + cb(); + /* c8 ignore stop */ + this.walkCB2(target, patterns, new Processor(this.opts), cb); + } + walkCB2(target, patterns, processor, cb) { + if (this.#childrenIgnored(target)) + return cb(); + if (this.signal?.aborted) + cb(); + if (this.paused) { + this.onResume(() => this.walkCB2(target, patterns, processor, cb)); + return; + } + processor.processPatterns(target, patterns); + // done processing. all of the above is sync, can be abstracted out. + // subwalks is a map of paths to the entry filters they need + // matches is a map of paths to [absolute, ifDir] tuples. + let tasks = 1; + const next = () => { + if (--tasks === 0) + cb(); + }; + for (const [m, absolute, ifDir] of processor.matches.entries()) { + if (this.#ignored(m)) + continue; + tasks++; + this.match(m, absolute, ifDir).then(() => next()); + } + for (const t of processor.subwalkTargets()) { + if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) { + continue; + } + tasks++; + const childrenCached = t.readdirCached(); + if (t.calledReaddir()) + this.walkCB3(t, childrenCached, processor, next); + else { + t.readdirCB((_, entries) => this.walkCB3(t, entries, processor, next), true); + } + } + next(); + } + walkCB3(target, entries, processor, cb) { + processor = processor.filterEntries(target, entries); + let tasks = 1; + const next = () => { + if (--tasks === 0) + cb(); + }; + for (const [m, absolute, ifDir] of processor.matches.entries()) { + if (this.#ignored(m)) + continue; + tasks++; + this.match(m, absolute, ifDir).then(() => next()); + } + for (const [target, patterns] of processor.subwalks.entries()) { + tasks++; + this.walkCB2(target, patterns, processor.child(), next); + } + next(); + } + walkCBSync(target, patterns, cb) { + /* c8 ignore start */ + if (this.signal?.aborted) + cb(); + /* c8 ignore stop */ + this.walkCB2Sync(target, patterns, new Processor(this.opts), cb); + } + walkCB2Sync(target, patterns, processor, cb) { + if (this.#childrenIgnored(target)) + return cb(); + if (this.signal?.aborted) + cb(); + if (this.paused) { + this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb)); + return; + } + processor.processPatterns(target, patterns); + // done processing. all of the above is sync, can be abstracted out. + // subwalks is a map of paths to the entry filters they need + // matches is a map of paths to [absolute, ifDir] tuples. + let tasks = 1; + const next = () => { + if (--tasks === 0) + cb(); + }; + for (const [m, absolute, ifDir] of processor.matches.entries()) { + if (this.#ignored(m)) + continue; + this.matchSync(m, absolute, ifDir); + } + for (const t of processor.subwalkTargets()) { + if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) { + continue; + } + tasks++; + const children = t.readdirSync(); + this.walkCB3Sync(t, children, processor, next); + } + next(); + } + walkCB3Sync(target, entries, processor, cb) { + processor = processor.filterEntries(target, entries); + let tasks = 1; + const next = () => { + if (--tasks === 0) + cb(); + }; + for (const [m, absolute, ifDir] of processor.matches.entries()) { + if (this.#ignored(m)) + continue; + this.matchSync(m, absolute, ifDir); + } + for (const [target, patterns] of processor.subwalks.entries()) { + tasks++; + this.walkCB2Sync(target, patterns, processor.child(), next); + } + next(); + } +} +export class GlobWalker extends GlobUtil { + matches = new Set(); + constructor(patterns, path, opts) { + super(patterns, path, opts); + } + matchEmit(e) { + this.matches.add(e); + } + async walk() { + if (this.signal?.aborted) + throw this.signal.reason; + if (this.path.isUnknown()) { + await this.path.lstat(); + } + await new Promise((res, rej) => { + this.walkCB(this.path, this.patterns, () => { + if (this.signal?.aborted) { + rej(this.signal.reason); + } + else { + res(this.matches); + } + }); + }); + return this.matches; + } + walkSync() { + if (this.signal?.aborted) + throw this.signal.reason; + if (this.path.isUnknown()) { + this.path.lstatSync(); + } + // nothing for the callback to do, because this never pauses + this.walkCBSync(this.path, this.patterns, () => { + if (this.signal?.aborted) + throw this.signal.reason; + }); + return this.matches; + } +} +export class GlobStream extends GlobUtil { + results; + constructor(patterns, path, opts) { + super(patterns, path, opts); + this.results = new Minipass({ + signal: this.signal, + objectMode: true, + }); + this.results.on('drain', () => this.resume()); + this.results.on('resume', () => this.resume()); + } + matchEmit(e) { + this.results.write(e); + if (!this.results.flowing) + this.pause(); + } + stream() { + const target = this.path; + if (target.isUnknown()) { + target.lstat().then(() => { + this.walkCB(target, this.patterns, () => this.results.end()); + }); + } + else { + this.walkCB(target, this.patterns, () => this.results.end()); + } + return this.results; + } + streamSync() { + if (this.path.isUnknown()) { + this.path.lstatSync(); + } + this.walkCBSync(this.path, this.patterns, () => this.results.end()); + return this.results; + } +} +//# sourceMappingURL=walker.js.map \ No newline at end of file diff --git a/node_modules/glob/dist/esm/walker.js.map b/node_modules/glob/dist/esm/walker.js.map new file mode 100644 index 0000000..daeeda6 --- /dev/null +++ b/node_modules/glob/dist/esm/walker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"walker.js","sourceRoot":"","sources":["../../src/walker.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,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AAC;CACF","sourcesContent":["/**\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 includeChildMatches?: 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 =\n O extends GWOFileTypesTrue ? Path\n : O extends GWOFileTypesFalse ? string\n : O extends GWOFileTypesUnset ? string\n : Path | string\n\nexport type Matches =\n O extends GWOFileTypesTrue ? Set\n : O extends GWOFileTypesFalse ? Set\n : O extends GWOFileTypesUnset ? Set\n : Set\n\nexport type MatchStream = Minipass<\n Result,\n Result\n>\n\nconst makeIgnore = (\n ignore: string | string[] | IgnoreLike,\n opts: GlobWalkerOpts,\n): IgnoreLike =>\n typeof ignore === 'string' ? new Ignore([ignore], opts)\n : Array.isArray(ignore) ? 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 includeChildMatches: boolean\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 this.includeChildMatches = opts.includeChildMatches !== false\n if (opts.ignore || !this.includeChildMatches) {\n this.#ignore = makeIgnore(opts.ignore ?? [], opts)\n if (\n !this.includeChildMatches &&\n typeof this.#ignore.add !== 'function'\n ) {\n const m = 'cannot ignore child matches, ignore lacks add() method.'\n throw new Error(m)\n }\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 const s = needStat ? await e.lstat() : e\n if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n const target = await s.realpath()\n /* c8 ignore start */\n if (target && (target.isUnknown() || this.opts.stat)) {\n await target.lstat()\n }\n /* c8 ignore stop */\n }\n return this.matchCheckTest(s, ifDir)\n }\n\n matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n return (\n e &&\n (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n (!ifDir || e.canReaddir()) &&\n (!this.opts.nodir || !e.isDirectory()) &&\n (!this.opts.nodir ||\n !this.opts.follow ||\n !e.isSymbolicLink() ||\n !e.realpathCached()?.isDirectory()) &&\n !this.#ignored(e)\n ) ?\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 const s = needStat ? e.lstatSync() : e\n if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n const target = s.realpathSync()\n if (target && (target?.isUnknown() || this.opts.stat)) {\n target.lstatSync()\n }\n }\n return this.matchCheckTest(s, 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 // we know we have an ignore if this is false, but TS doesn't\n if (!this.includeChildMatches && this.#ignore?.add) {\n const ign = `${e.relativePosix()}/**`\n this.#ignore.add(ign)\n }\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 = new Set>()\n\n constructor(patterns: Pattern[], path: Path, opts: O) {\n super(patterns, path, opts)\n }\n\n matchEmit(e: Result): 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(): Set> {\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: Minipass, Result>\n\n constructor(patterns: Pattern[], path: Path, opts: O) {\n super(patterns, path, opts)\n this.results = new Minipass, Result>({\n signal: this.signal,\n objectMode: true,\n })\n this.results.on('drain', () => this.resume())\n this.results.on('resume', () => this.resume())\n }\n\n matchEmit(e: Result): 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"]} \ No newline at end of file diff --git a/node_modules/glob/package.json b/node_modules/glob/package.json new file mode 100644 index 0000000..6d4893b --- /dev/null +++ b/node_modules/glob/package.json @@ -0,0 +1,99 @@ +{ + "author": "Isaac Z. Schlueter (https://blog.izs.me/)", + "publishConfig": { + "tag": "legacy-v10" + }, + "name": "glob", + "description": "the most correct and second fastest glob implementation in JavaScript", + "version": "10.4.5", + "type": "module", + "tshy": { + "main": true, + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "bin": "./dist/esm/bin.mjs", + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-glob.git" + }, + "files": [ + "dist" + ], + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --log-level warn", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts", + "prepublish": "npm run benchclean", + "profclean": "rm -f v8.log profile.txt", + "test-regen": "npm run profclean && TEST_REGEN=1 node --no-warnings --loader ts-node/esm test/00-setup.ts", + "prebench": "npm run prepare", + "bench": "bash benchmark.sh", + "preprof": "npm run prepare", + "prof": "bash prof.sh", + "benchclean": "node benchclean.cjs" + }, + "prettier": { + "experimentalTernaries": true, + "semi": false, + "printWidth": 75, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "devDependencies": { + "@types/node": "^20.11.30", + "memfs": "^3.4.13", + "mkdirp": "^3.0.1", + "prettier": "^3.2.5", + "rimraf": "^5.0.7", + "sync-content": "^1.0.2", + "tap": "^19.0.0", + "tshy": "^1.14.0", + "typedoc": "^0.25.12" + }, + "tap": { + "before": "test/00-setup.ts" + }, + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "module": "./dist/esm/index.js" +} diff --git a/node_modules/hasown/.eslintrc b/node_modules/hasown/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/node_modules/hasown/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/hasown/.github/FUNDING.yml b/node_modules/hasown/.github/FUNDING.yml new file mode 100644 index 0000000..d68c8b7 --- /dev/null +++ b/node_modules/hasown/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/hasown +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/hasown/.nycrc b/node_modules/hasown/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/hasown/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/hasown/CHANGELOG.md b/node_modules/hasown/CHANGELOG.md new file mode 100644 index 0000000..2b0a980 --- /dev/null +++ b/node_modules/hasown/CHANGELOG.md @@ -0,0 +1,40 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v2.0.2](https://github.com/inspect-js/hasOwn/compare/v2.0.1...v2.0.2) - 2024-03-10 + +### Commits + +- [types] use shared config [`68e9d4d`](https://github.com/inspect-js/hasOwn/commit/68e9d4dab6facb4f05f02c6baea94a3f2a4e44b2) +- [actions] remove redundant finisher; use reusable workflow [`241a68e`](https://github.com/inspect-js/hasOwn/commit/241a68e13ea1fe52bec5ba7f74144befc31fae7b) +- [Tests] increase coverage [`4125c0d`](https://github.com/inspect-js/hasOwn/commit/4125c0d6121db56ae30e38346dfb0c000b04f0a7) +- [Tests] skip `npm ls` in old node due to TS [`01b9282`](https://github.com/inspect-js/hasOwn/commit/01b92822f9971dea031eafdd14767df41d61c202) +- [types] improve predicate type [`d340f85`](https://github.com/inspect-js/hasOwn/commit/d340f85ce02e286ef61096cbbb6697081d40a12b) +- [Dev Deps] update `tape` [`70089fc`](https://github.com/inspect-js/hasOwn/commit/70089fcf544e64acc024cbe60f5a9b00acad86de) +- [Tests] use `@arethetypeswrong/cli` [`50b272c`](https://github.com/inspect-js/hasOwn/commit/50b272c829f40d053a3dd91c9796e0ac0b2af084) + +## [v2.0.1](https://github.com/inspect-js/hasOwn/compare/v2.0.0...v2.0.1) - 2024-02-10 + +### Commits + +- [types] use a handwritten d.ts file; fix exported type [`012b989`](https://github.com/inspect-js/hasOwn/commit/012b9898ccf91dc441e2ebf594ff70270a5fda58) +- [Dev Deps] update `@types/function-bind`, `@types/mock-property`, `@types/tape`, `aud`, `mock-property`, `npmignore`, `tape`, `typescript` [`977a56f`](https://github.com/inspect-js/hasOwn/commit/977a56f51a1f8b20566f3c471612137894644025) +- [meta] add `sideEffects` flag [`3a60b7b`](https://github.com/inspect-js/hasOwn/commit/3a60b7bf42fccd8c605e5f145a6fcc83b13cb46f) + +## [v2.0.0](https://github.com/inspect-js/hasOwn/compare/v1.0.1...v2.0.0) - 2023-10-19 + +### Commits + +- revamped implementation, tests, readme [`72bf8b3`](https://github.com/inspect-js/hasOwn/commit/72bf8b338e77a638f0a290c63ffaed18339c36b4) +- [meta] revamp package.json [`079775f`](https://github.com/inspect-js/hasOwn/commit/079775fb1ec72c1c6334069593617a0be3847458) +- Only apps should have lockfiles [`6640e23`](https://github.com/inspect-js/hasOwn/commit/6640e233d1bb8b65260880f90787637db157d215) + +## v1.0.1 - 2023-10-10 + +### Commits + +- Initial commit [`8dbfde6`](https://github.com/inspect-js/hasOwn/commit/8dbfde6e8fb0ebb076fab38d138f2984eb340a62) diff --git a/node_modules/hasown/LICENSE b/node_modules/hasown/LICENSE new file mode 100644 index 0000000..0314929 --- /dev/null +++ b/node_modules/hasown/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Jordan Harband and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/hasown/README.md b/node_modules/hasown/README.md new file mode 100644 index 0000000..f759b8a --- /dev/null +++ b/node_modules/hasown/README.md @@ -0,0 +1,40 @@ +# hasown [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +A robust, ES3 compatible, "has own property" predicate. + +## Example + +```js +const assert = require('assert'); +const hasOwn = require('hasown'); + +assert.equal(hasOwn({}, 'toString'), false); +assert.equal(hasOwn([], 'length'), true); +assert.equal(hasOwn({ a: 42 }, 'a'), true); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/hasown +[npm-version-svg]: https://versionbadg.es/inspect-js/hasown.svg +[deps-svg]: https://david-dm.org/inspect-js/hasOwn.svg +[deps-url]: https://david-dm.org/inspect-js/hasOwn +[dev-deps-svg]: https://david-dm.org/inspect-js/hasOwn/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/hasOwn#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/hasown.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/hasown.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/hasown.svg +[downloads-url]: https://npm-stat.com/charts.html?package=hasown +[codecov-image]: https://codecov.io/gh/inspect-js/hasOwn/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/hasOwn/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/hasOwn +[actions-url]: https://github.com/inspect-js/hasOwn/actions diff --git a/node_modules/hasown/index.d.ts b/node_modules/hasown/index.d.ts new file mode 100644 index 0000000..aafdf3b --- /dev/null +++ b/node_modules/hasown/index.d.ts @@ -0,0 +1,3 @@ +declare function hasOwn(o: O, p: K): o is O & Record; + +export = hasOwn; diff --git a/node_modules/hasown/index.js b/node_modules/hasown/index.js new file mode 100644 index 0000000..34e6059 --- /dev/null +++ b/node_modules/hasown/index.js @@ -0,0 +1,8 @@ +'use strict'; + +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = require('function-bind'); + +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); diff --git a/node_modules/hasown/package.json b/node_modules/hasown/package.json new file mode 100644 index 0000000..8502e13 --- /dev/null +++ b/node_modules/hasown/package.json @@ -0,0 +1,92 @@ +{ + "name": "hasown", + "version": "2.0.2", + "description": "A robust, ES3 compatible, \"has own property\" predicate.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "index.d.ts", + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "npm run tsc", + "pretest": "npm run lint", + "tsc": "tsc -p .", + "posttsc": "attw -P", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/hasOwn.git" + }, + "keywords": [ + "has", + "hasOwnProperty", + "hasOwn", + "has-own", + "own", + "has", + "property", + "in", + "javascript", + "ecmascript" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/hasOwn/issues" + }, + "homepage": "https://github.com/inspect-js/hasOwn#readme", + "dependencies": { + "function-bind": "^1.1.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.15.1", + "@ljharb/eslint-config": "^21.1.0", + "@ljharb/tsconfig": "^0.2.0", + "@types/function-bind": "^1.1.10", + "@types/mock-property": "^1.0.2", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "mock-property": "^1.0.3", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "test" + ] + } +} diff --git a/node_modules/hasown/tsconfig.json b/node_modules/hasown/tsconfig.json new file mode 100644 index 0000000..0930c56 --- /dev/null +++ b/node_modules/hasown/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "@ljharb/tsconfig", + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/is-binary-path/index.d.ts b/node_modules/is-binary-path/index.d.ts new file mode 100644 index 0000000..19dcd43 --- /dev/null +++ b/node_modules/is-binary-path/index.d.ts @@ -0,0 +1,17 @@ +/** +Check if a file path is a binary file. + +@example +``` +import isBinaryPath = require('is-binary-path'); + +isBinaryPath('source/unicorn.png'); +//=> true + +isBinaryPath('source/unicorn.txt'); +//=> false +``` +*/ +declare function isBinaryPath(filePath: string): boolean; + +export = isBinaryPath; diff --git a/node_modules/is-binary-path/index.js b/node_modules/is-binary-path/index.js new file mode 100644 index 0000000..ef7548c --- /dev/null +++ b/node_modules/is-binary-path/index.js @@ -0,0 +1,7 @@ +'use strict'; +const path = require('path'); +const binaryExtensions = require('binary-extensions'); + +const extensions = new Set(binaryExtensions); + +module.exports = filePath => extensions.has(path.extname(filePath).slice(1).toLowerCase()); diff --git a/node_modules/is-binary-path/license b/node_modules/is-binary-path/license new file mode 100644 index 0000000..401b1c7 --- /dev/null +++ b/node_modules/is-binary-path/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2019 Sindre Sorhus (https://sindresorhus.com), Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/is-binary-path/package.json b/node_modules/is-binary-path/package.json new file mode 100644 index 0000000..a8d005a --- /dev/null +++ b/node_modules/is-binary-path/package.json @@ -0,0 +1,40 @@ +{ + "name": "is-binary-path", + "version": "2.1.0", + "description": "Check if a file path is a binary file", + "license": "MIT", + "repository": "sindresorhus/is-binary-path", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "binary", + "extensions", + "extension", + "file", + "path", + "check", + "detect", + "is" + ], + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/is-binary-path/readme.md b/node_modules/is-binary-path/readme.md new file mode 100644 index 0000000..b4ab025 --- /dev/null +++ b/node_modules/is-binary-path/readme.md @@ -0,0 +1,34 @@ +# is-binary-path [![Build Status](https://travis-ci.org/sindresorhus/is-binary-path.svg?branch=master)](https://travis-ci.org/sindresorhus/is-binary-path) + +> Check if a file path is a binary file + + +## Install + +``` +$ npm install is-binary-path +``` + + +## Usage + +```js +const isBinaryPath = require('is-binary-path'); + +isBinaryPath('source/unicorn.png'); +//=> true + +isBinaryPath('source/unicorn.txt'); +//=> false +``` + + +## Related + +- [binary-extensions](https://github.com/sindresorhus/binary-extensions) - List of binary file extensions +- [is-text-path](https://github.com/sindresorhus/is-text-path) - Check if a filepath is a text file + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com), [Paul Miller](https://paulmillr.com) diff --git a/node_modules/is-core-module/.eslintrc b/node_modules/is-core-module/.eslintrc new file mode 100644 index 0000000..f2e0726 --- /dev/null +++ b/node_modules/is-core-module/.eslintrc @@ -0,0 +1,18 @@ +{ + "extends": "@ljharb", + "root": true, + "rules": { + "func-style": 1, + }, + "overrides": [ + { + "files": "test/**", + "rules": { + "global-require": 0, + "max-depth": 0, + "max-lines-per-function": 0, + "no-negated-condition": 0, + }, + }, + ], +} diff --git a/node_modules/is-core-module/.nycrc b/node_modules/is-core-module/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/is-core-module/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/is-core-module/CHANGELOG.md b/node_modules/is-core-module/CHANGELOG.md new file mode 100644 index 0000000..0177c82 --- /dev/null +++ b/node_modules/is-core-module/CHANGELOG.md @@ -0,0 +1,218 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v2.16.1](https://github.com/inspect-js/is-core-module/compare/v2.16.0...v2.16.1) - 2024-12-21 + +### Fixed + +- [Fix] `node:sqlite` is available in node ^22.13 [`#17`](https://github.com/inspect-js/is-core-module/issues/17) + +## [v2.16.0](https://github.com/inspect-js/is-core-module/compare/v2.15.1...v2.16.0) - 2024-12-13 + +### Commits + +- [New] add `node:sqlite` [`1ee94d2`](https://github.com/inspect-js/is-core-module/commit/1ee94d20857e22cdb24e9b4bb1a2097f2e03e26f) +- [Dev Deps] update `auto-changelog`, `tape` [`aa84aa3`](https://github.com/inspect-js/is-core-module/commit/aa84aa34face677f14e08ec1c737f0c4bba27260) + +## [v2.15.1](https://github.com/inspect-js/is-core-module/compare/v2.15.0...v2.15.1) - 2024-08-21 + +### Commits + +- [Tests] add `process.getBuiltinModule` tests [`28c7791`](https://github.com/inspect-js/is-core-module/commit/28c7791c196d58c64cfdf638b7e68ed1b62a4da0) +- [Fix] `test/mock_loader` is no longer exposed as of v22.7 [`68b08b0`](https://github.com/inspect-js/is-core-module/commit/68b08b0d7963447dbffa5142e8810dca550383af) +- [Tests] replace `aud` with `npm audit` [`32f8060`](https://github.com/inspect-js/is-core-module/commit/32f806026dac14f9016be4401a643851240c76b9) +- [Dev Deps] update `mock-property` [`f7d3c8f`](https://github.com/inspect-js/is-core-module/commit/f7d3c8f01e922be49621683eb41477c4f50522e1) +- [Dev Deps] add missing peer dep [`eaee885`](https://github.com/inspect-js/is-core-module/commit/eaee885b67238819e9c8ed5bd2098766e1d05331) + +## [v2.15.0](https://github.com/inspect-js/is-core-module/compare/v2.14.0...v2.15.0) - 2024-07-17 + +### Commits + +- [New] add `node:sea` [`2819fb3`](https://github.com/inspect-js/is-core-module/commit/2819fb3eae312fa64643bc5430ebd06ec0f3fb88) + +## [v2.14.0](https://github.com/inspect-js/is-core-module/compare/v2.13.1...v2.14.0) - 2024-06-20 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `mock-property`, `npmignore`, `tape` [`0e43200`](https://github.com/inspect-js/is-core-module/commit/0e432006d97237cc082d41e6a593e87c81068364) +- [meta] add missing `engines.node` [`4ea3af8`](https://github.com/inspect-js/is-core-module/commit/4ea3af88891a1d4f96026f0ec0ef08c67cd1bd24) +- [New] add `test/mock_loader` [`e9fbd29`](https://github.com/inspect-js/is-core-module/commit/e9fbd2951383be070aeffb9ebbf3715237282610) +- [Deps] update `hasown` [`57f1940`](https://github.com/inspect-js/is-core-module/commit/57f1940947b3e368abdf529232d2f17d88909358) + +## [v2.13.1](https://github.com/inspect-js/is-core-module/compare/v2.13.0...v2.13.1) - 2023-10-20 + +### Commits + +- [Refactor] use `hasown` instead of `has` [`0e52096`](https://github.com/inspect-js/is-core-module/commit/0e520968b0a725276b67420ab4b877486b243ae0) +- [Dev Deps] update `mock-property`, `tape` [`8736b35`](https://github.com/inspect-js/is-core-module/commit/8736b35464d0f297b55da2c6b30deee04b8303c5) + +## [v2.13.0](https://github.com/inspect-js/is-core-module/compare/v2.12.1...v2.13.0) - 2023-08-05 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `semver`, `tape` [`c75b263`](https://github.com/inspect-js/is-core-module/commit/c75b263d047cb53430c3970107e5eb64d6cd6c0c) +- [New] `node:test/reporters` and `wasi`/`node:wasi` are in v18.17 [`d76cbf8`](https://github.com/inspect-js/is-core-module/commit/d76cbf8e9b208acfd98913fed5a5f45cb15fe5dc) + +## [v2.12.1](https://github.com/inspect-js/is-core-module/compare/v2.12.0...v2.12.1) - 2023-05-16 + +### Commits + +- [Fix] `test/reporters` now requires the `node:` prefix as of v20.2 [`12183d0`](https://github.com/inspect-js/is-core-module/commit/12183d0d8e4edf56b6ce18a1b3be54bfce10175b) + +## [v2.12.0](https://github.com/inspect-js/is-core-module/compare/v2.11.0...v2.12.0) - 2023-04-10 + +### Commits + +- [actions] update rebase action to use reusable workflow [`c0a7251`](https://github.com/inspect-js/is-core-module/commit/c0a7251f734f3c621932c5fcdfd1bf966b42ca32) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`9ae8b7f`](https://github.com/inspect-js/is-core-module/commit/9ae8b7fac03c369861d0991b4a2ce8d4848e6a7d) +- [New] `test/reporters` added in v19.9, `wasi` added in v20 [`9d5341a`](https://github.com/inspect-js/is-core-module/commit/9d5341ab32053f25b7fa7db3c0e18461db24a79c) +- [Dev Deps] add missing `in-publish` dep [`5980245`](https://github.com/inspect-js/is-core-module/commit/59802456e9ac919fa748f53be9d8fbf304a197df) + +## [v2.11.0](https://github.com/inspect-js/is-core-module/compare/v2.10.0...v2.11.0) - 2022-10-18 + +### Commits + +- [meta] use `npmignore` to autogenerate an npmignore file [`3360011`](https://github.com/inspect-js/is-core-module/commit/33600118857b46177178072fba2affcdeb009d12) +- [Dev Deps] update `aud`, `tape` [`651c6b0`](https://github.com/inspect-js/is-core-module/commit/651c6b0cc2799d4130866cf43ad333dcade3d26c) +- [New] `inspector/promises` and `node:inspector/promises` is now available in node 19 [`22d332f`](https://github.com/inspect-js/is-core-module/commit/22d332fe22ac050305444e0781ff85af819abcb0) + +## [v2.10.0](https://github.com/inspect-js/is-core-module/compare/v2.9.0...v2.10.0) - 2022-08-03 + +### Commits + +- [New] `node:test` is now available in node ^16.17 [`e8fd36e`](https://github.com/inspect-js/is-core-module/commit/e8fd36e9b86c917775a07cc473b62a3294f459f2) +- [Tests] improve skip message [`c014a4c`](https://github.com/inspect-js/is-core-module/commit/c014a4c0cd6eb15fff573ae4709191775e70cab4) + +## [v2.9.0](https://github.com/inspect-js/is-core-module/compare/v2.8.1...v2.9.0) - 2022-04-19 + +### Commits + +- [New] add `node:test`, in node 18+ [`f853eca`](https://github.com/inspect-js/is-core-module/commit/f853eca801d0a7d4e1dbb670f1b6d9837d9533c5) +- [Tests] use `mock-property` [`03b3644`](https://github.com/inspect-js/is-core-module/commit/03b3644dff4417f4ba5a7d0aa0138f5f6b3e5c46) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`7c0e2d0`](https://github.com/inspect-js/is-core-module/commit/7c0e2d06ed2a89acf53abe2ab34d703ed5b03455) +- [meta] simplify "exports" [`d6ed201`](https://github.com/inspect-js/is-core-module/commit/d6ed201eba7fbba0e59814a9050fc49a6e9878c8) + +## [v2.8.1](https://github.com/inspect-js/is-core-module/compare/v2.8.0...v2.8.1) - 2022-01-05 + +### Commits + +- [actions] reuse common workflows [`cd2cf9b`](https://github.com/inspect-js/is-core-module/commit/cd2cf9b3b66c8d328f65610efe41e9325db7716d) +- [Fix] update node 0.4 results [`062195d`](https://github.com/inspect-js/is-core-module/commit/062195d89f0876a88b95d378b43f7fcc1205bc5b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`0790b62`](https://github.com/inspect-js/is-core-module/commit/0790b6222848c6167132f9f73acc3520fa8d1298) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`7d139a6`](https://github.com/inspect-js/is-core-module/commit/7d139a6d767709eabf0a0251e074ec1fb230c06e) +- [Tests] run `nyc` in `tests-only`, not `test` [`780e8a0`](https://github.com/inspect-js/is-core-module/commit/780e8a049951c71cf78b1707f0871c48a28bde14) + +## [v2.8.0](https://github.com/inspect-js/is-core-module/compare/v2.7.0...v2.8.0) - 2021-10-14 + +### Commits + +- [actions] update codecov uploader [`0cfe94e`](https://github.com/inspect-js/is-core-module/commit/0cfe94e106a7d005ea03e008c0a21dec13a77904) +- [New] add `readline/promises` to node v17+ [`4f78c30`](https://github.com/inspect-js/is-core-module/commit/4f78c3008b1b58b4db6dc91d99610b1bc859da7e) +- [Tests] node ^14.18 supports `node:` prefixes for CJS [`43e2f17`](https://github.com/inspect-js/is-core-module/commit/43e2f177452cea2f0eaf34f61b5407217bbdb6f4) + +## [v2.7.0](https://github.com/inspect-js/is-core-module/compare/v2.6.0...v2.7.0) - 2021-09-27 + +### Commits + +- [New] node `v14.18` added `node:`-prefixed core modules to `require` [`6d943ab`](https://github.com/inspect-js/is-core-module/commit/6d943abe81382b9bbe344384d80fbfebe1cc0526) +- [Tests] add coverage for Object.prototype pollution [`c6baf5f`](https://github.com/inspect-js/is-core-module/commit/c6baf5f942311a1945c1af41167bb80b84df2af7) +- [Dev Deps] update `@ljharb/eslint-config` [`6717f00`](https://github.com/inspect-js/is-core-module/commit/6717f000d063ea57beb772bded36c2f056ac404c) +- [eslint] fix linter warning [`594c10b`](https://github.com/inspect-js/is-core-module/commit/594c10bb7d39d7eb00925c90924199ff596184b2) +- [meta] add `sideEffects` flag [`c32cfa5`](https://github.com/inspect-js/is-core-module/commit/c32cfa5195632944c4dd4284a142b8476e75be13) + +## [v2.6.0](https://github.com/inspect-js/is-core-module/compare/v2.5.0...v2.6.0) - 2021-08-17 + +### Commits + +- [Dev Deps] update `eslint`, `tape` [`6cc928f`](https://github.com/inspect-js/is-core-module/commit/6cc928f8a4bba66aeeccc4f6beeac736d4bd3081) +- [New] add `stream/consumers` to node `>= 16.7` [`a1a423e`](https://github.com/inspect-js/is-core-module/commit/a1a423e467e4cc27df180234fad5bab45943e67d) +- [Refactor] Remove duplicated `&&` operand [`86faea7`](https://github.com/inspect-js/is-core-module/commit/86faea738213a2433c62d1098488dc9314dca832) +- [Tests] include prereleases [`a4da7a6`](https://github.com/inspect-js/is-core-module/commit/a4da7a6abf7568e2aa4fd98e69452179f1850963) + +## [v2.5.0](https://github.com/inspect-js/is-core-module/compare/v2.4.0...v2.5.0) - 2021-07-12 + +### Commits + +- [Dev Deps] update `auto-changelog`, `eslint` [`6334cc9`](https://github.com/inspect-js/is-core-module/commit/6334cc94f3af7469685bd8f236740991baaf2705) +- [New] add `stream/web` to node v16.5+ [`17ac59b`](https://github.com/inspect-js/is-core-module/commit/17ac59b662d63e220a2e5728625f005c24f177b2) + +## [v2.4.0](https://github.com/inspect-js/is-core-module/compare/v2.3.0...v2.4.0) - 2021-05-09 + +### Commits + +- [readme] add actions and codecov badges [`82b7faa`](https://github.com/inspect-js/is-core-module/commit/82b7faa12b56dbe47fbea67e1a5b9e447027ba40) +- [Dev Deps] update `@ljharb/eslint-config`, `aud` [`8096868`](https://github.com/inspect-js/is-core-module/commit/8096868c024a161ccd4d44110b136763e92eace8) +- [Dev Deps] update `eslint` [`6726824`](https://github.com/inspect-js/is-core-module/commit/67268249b88230018c510f6532a8046d7326346f) +- [New] add `diagnostics_channel` to node `^14.17` [`86c6563`](https://github.com/inspect-js/is-core-module/commit/86c65634201b8ff9b3e48a9a782594579c7f5c3c) +- [meta] fix prepublish script [`697a01e`](https://github.com/inspect-js/is-core-module/commit/697a01e3c9c0be074066520954f30fb28532ec57) + +## [v2.3.0](https://github.com/inspect-js/is-core-module/compare/v2.2.0...v2.3.0) - 2021-04-24 + +### Commits + +- [meta] do not publish github action workflow files [`060d4bb`](https://github.com/inspect-js/is-core-module/commit/060d4bb971a29451c19ff336eb56bee27f9fa95a) +- [New] add support for `node:` prefix, in node 16+ [`7341223`](https://github.com/inspect-js/is-core-module/commit/73412230a769f6e81c05eea50b6520cebf54ed2f) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`016269a`](https://github.com/inspect-js/is-core-module/commit/016269abae9f6657a5254adfbb813f09a05067f9) +- [patch] remove unneeded `.0` in version ranges [`cb466a6`](https://github.com/inspect-js/is-core-module/commit/cb466a6d89e52b8389e5c12715efcd550c41cea3) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`c9f9c39`](https://github.com/inspect-js/is-core-module/commit/c9f9c396ace60ef81906f98059c064e6452473ed) +- [actions] update workflows [`3ee4a89`](https://github.com/inspect-js/is-core-module/commit/3ee4a89fd5a02fccd43882d905448ea6a98e9a3c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`dee4fed`](https://github.com/inspect-js/is-core-module/commit/dee4fed79690c1d43a22f7fa9426abebdc6d727f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`7d046ba`](https://github.com/inspect-js/is-core-module/commit/7d046ba07ae8c9292e43652694ca808d7b309de8) +- [meta] use `prepublishOnly` script for npm 7+ [`149e677`](https://github.com/inspect-js/is-core-module/commit/149e6771a5ede6d097e71785b467a9c4b4977cc7) +- [readme] remove travis badge [`903b51d`](https://github.com/inspect-js/is-core-module/commit/903b51d6b69b98abeabfbc3695c345b02646f19c) + +## [v2.2.0](https://github.com/inspect-js/is-core-module/compare/v2.1.0...v2.2.0) - 2020-11-26 + +### Commits + +- [Tests] migrate tests to Github Actions [`c919f57`](https://github.com/inspect-js/is-core-module/commit/c919f573c0a92d10a0acad0b650b5aecb033d426) +- [patch] `core.json`: %s/ /\t/g [`db3f685`](https://github.com/inspect-js/is-core-module/commit/db3f68581f53e73cc09cd675955eb1bdd6a5a39b) +- [Tests] run `nyc` on all tests [`b2f925f`](https://github.com/inspect-js/is-core-module/commit/b2f925f8866f210ef441f39fcc8cc42692ab89b1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`; add `safe-publish-latest` [`89f02a2`](https://github.com/inspect-js/is-core-module/commit/89f02a2b4162246dea303a6ee31bb9a550b05c72) +- [New] add `path/posix`, `path/win32`, `util/types` [`77f94f1`](https://github.com/inspect-js/is-core-module/commit/77f94f1e90ffd7c0be2a3f1aa8574ebf7fd981b3) + +## [v2.1.0](https://github.com/inspect-js/is-core-module/compare/v2.0.0...v2.1.0) - 2020-11-04 + +### Commits + +- [Dev Deps] update `eslint` [`5e0034e`](https://github.com/inspect-js/is-core-module/commit/5e0034eae57c09c8f1bd769f502486a00f56c6e4) +- [New] Add `diagnostics_channel` [`c2d83d0`](https://github.com/inspect-js/is-core-module/commit/c2d83d0a0225a1a658945d9bab7036ea347d29ec) + +## [v2.0.0](https://github.com/inspect-js/is-core-module/compare/v1.0.2...v2.0.0) - 2020-09-29 + +### Commits + +- v2 implementation [`865aeb5`](https://github.com/inspect-js/is-core-module/commit/865aeb5ca0e90248a3dfff5d7622e4751fdeb9cd) +- Only apps should have lockfiles [`5a5e660`](https://github.com/inspect-js/is-core-module/commit/5a5e660d568e37eb44e17fb1ebb12a105205fc2b) +- Initial commit for v2 [`5a51524`](https://github.com/inspect-js/is-core-module/commit/5a51524e06f92adece5fbb138c69b7b9748a2348) +- Tests [`116eae4`](https://github.com/inspect-js/is-core-module/commit/116eae4fccd01bc72c1fd3cc4b7561c387afc496) +- [meta] add `auto-changelog` [`c24388b`](https://github.com/inspect-js/is-core-module/commit/c24388bee828d223040519d1f5b226ca35beee63) +- [actions] add "Automatic Rebase" and "require allow edits" actions [`34292db`](https://github.com/inspect-js/is-core-module/commit/34292dbcbadae0868aff03c22dbd8b7b8a11558a) +- [Tests] add `npm run lint` [`4f9eeee`](https://github.com/inspect-js/is-core-module/commit/4f9eeee7ddff10698bbf528620f4dc8d4fa3e697) +- [readme] fix travis badges, https all URLs [`e516a73`](https://github.com/inspect-js/is-core-module/commit/e516a73b0dccce20938c432b1ba512eae8eff9e9) +- [meta] create FUNDING.yml [`1aabebc`](https://github.com/inspect-js/is-core-module/commit/1aabebca98d01f8a04e46bc2e2520fa93cf21ac6) +- [Fix] `domain`: domain landed sometime > v0.7.7 and <= v0.7.12 [`2df7d37`](https://github.com/inspect-js/is-core-module/commit/2df7d37595d41b15eeada732b706b926c2771655) +- [Fix] `sys`: worked in 0.6, not 0.7, and 0.8+ [`a75c134`](https://github.com/inspect-js/is-core-module/commit/a75c134229e1e9441801f6b73f6a52489346eb65) + +## [v1.0.2](https://github.com/inspect-js/is-core-module/compare/v1.0.1...v1.0.2) - 2014-09-28 + +### Commits + +- simpler [`66fe90f`](https://github.com/inspect-js/is-core-module/commit/66fe90f9771581b9adc0c3900baa52c21b5baea2) + +## [v1.0.1](https://github.com/inspect-js/is-core-module/compare/v1.0.0...v1.0.1) - 2014-09-28 + +### Commits + +- remove stupid [`f21f906`](https://github.com/inspect-js/is-core-module/commit/f21f906f882c2bd656a5fc5ed6fbe48ddaffb2ac) +- update readme [`1eff0ec`](https://github.com/inspect-js/is-core-module/commit/1eff0ec69798d1ec65771552d1562911e90a8027) + +## v1.0.0 - 2014-09-28 + +### Commits + +- init [`48e5e76`](https://github.com/inspect-js/is-core-module/commit/48e5e76cac378fddb8c1f7d4055b8dfc943d6b96) diff --git a/node_modules/is-core-module/LICENSE b/node_modules/is-core-module/LICENSE new file mode 100644 index 0000000..2e50287 --- /dev/null +++ b/node_modules/is-core-module/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Dave Justice + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/is-core-module/README.md b/node_modules/is-core-module/README.md new file mode 100644 index 0000000..062d906 --- /dev/null +++ b/node_modules/is-core-module/README.md @@ -0,0 +1,40 @@ +# is-core-module [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Is this specifier a node.js core module? Optionally provide a node version to check; defaults to the current node version. + +## Example + +```js +var isCore = require('is-core-module'); +var assert = require('assert'); +assert(isCore('fs')); +assert(!isCore('butts')); +``` + +## Tests +Clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-core-module +[2]: https://versionbadg.es/inspect-js/is-core-module.svg +[5]: https://david-dm.org/inspect-js/is-core-module.svg +[6]: https://david-dm.org/inspect-js/is-core-module +[7]: https://david-dm.org/inspect-js/is-core-module/dev-status.svg +[8]: https://david-dm.org/inspect-js/is-core-module#info=devDependencies +[11]: https://nodei.co/npm/is-core-module.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/is-core-module.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/is-core-module.svg +[downloads-url]: https://npm-stat.com/charts.html?package=is-core-module +[codecov-image]: https://codecov.io/gh/inspect-js/is-core-module/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/is-core-module/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-core-module +[actions-url]: https://github.com/inspect-js/is-core-module/actions diff --git a/node_modules/is-core-module/core.json b/node_modules/is-core-module/core.json new file mode 100644 index 0000000..930ec68 --- /dev/null +++ b/node_modules/is-core-module/core.json @@ -0,0 +1,162 @@ +{ + "assert": true, + "node:assert": [">= 14.18 && < 15", ">= 16"], + "assert/strict": ">= 15", + "node:assert/strict": ">= 16", + "async_hooks": ">= 8", + "node:async_hooks": [">= 14.18 && < 15", ">= 16"], + "buffer_ieee754": ">= 0.5 && < 0.9.7", + "buffer": true, + "node:buffer": [">= 14.18 && < 15", ">= 16"], + "child_process": true, + "node:child_process": [">= 14.18 && < 15", ">= 16"], + "cluster": ">= 0.5", + "node:cluster": [">= 14.18 && < 15", ">= 16"], + "console": true, + "node:console": [">= 14.18 && < 15", ">= 16"], + "constants": true, + "node:constants": [">= 14.18 && < 15", ">= 16"], + "crypto": true, + "node:crypto": [">= 14.18 && < 15", ">= 16"], + "_debug_agent": ">= 1 && < 8", + "_debugger": "< 8", + "dgram": true, + "node:dgram": [">= 14.18 && < 15", ">= 16"], + "diagnostics_channel": [">= 14.17 && < 15", ">= 15.1"], + "node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"], + "dns": true, + "node:dns": [">= 14.18 && < 15", ">= 16"], + "dns/promises": ">= 15", + "node:dns/promises": ">= 16", + "domain": ">= 0.7.12", + "node:domain": [">= 14.18 && < 15", ">= 16"], + "events": true, + "node:events": [">= 14.18 && < 15", ">= 16"], + "freelist": "< 6", + "fs": true, + "node:fs": [">= 14.18 && < 15", ">= 16"], + "fs/promises": [">= 10 && < 10.1", ">= 14"], + "node:fs/promises": [">= 14.18 && < 15", ">= 16"], + "_http_agent": ">= 0.11.1", + "node:_http_agent": [">= 14.18 && < 15", ">= 16"], + "_http_client": ">= 0.11.1", + "node:_http_client": [">= 14.18 && < 15", ">= 16"], + "_http_common": ">= 0.11.1", + "node:_http_common": [">= 14.18 && < 15", ">= 16"], + "_http_incoming": ">= 0.11.1", + "node:_http_incoming": [">= 14.18 && < 15", ">= 16"], + "_http_outgoing": ">= 0.11.1", + "node:_http_outgoing": [">= 14.18 && < 15", ">= 16"], + "_http_server": ">= 0.11.1", + "node:_http_server": [">= 14.18 && < 15", ">= 16"], + "http": true, + "node:http": [">= 14.18 && < 15", ">= 16"], + "http2": ">= 8.8", + "node:http2": [">= 14.18 && < 15", ">= 16"], + "https": true, + "node:https": [">= 14.18 && < 15", ">= 16"], + "inspector": ">= 8", + "node:inspector": [">= 14.18 && < 15", ">= 16"], + "inspector/promises": [">= 19"], + "node:inspector/promises": [">= 19"], + "_linklist": "< 8", + "module": true, + "node:module": [">= 14.18 && < 15", ">= 16"], + "net": true, + "node:net": [">= 14.18 && < 15", ">= 16"], + "node-inspect/lib/_inspect": ">= 7.6 && < 12", + "node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12", + "node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12", + "os": true, + "node:os": [">= 14.18 && < 15", ">= 16"], + "path": true, + "node:path": [">= 14.18 && < 15", ">= 16"], + "path/posix": ">= 15.3", + "node:path/posix": ">= 16", + "path/win32": ">= 15.3", + "node:path/win32": ">= 16", + "perf_hooks": ">= 8.5", + "node:perf_hooks": [">= 14.18 && < 15", ">= 16"], + "process": ">= 1", + "node:process": [">= 14.18 && < 15", ">= 16"], + "punycode": ">= 0.5", + "node:punycode": [">= 14.18 && < 15", ">= 16"], + "querystring": true, + "node:querystring": [">= 14.18 && < 15", ">= 16"], + "readline": true, + "node:readline": [">= 14.18 && < 15", ">= 16"], + "readline/promises": ">= 17", + "node:readline/promises": ">= 17", + "repl": true, + "node:repl": [">= 14.18 && < 15", ">= 16"], + "node:sea": [">= 20.12 && < 21", ">= 21.7"], + "smalloc": ">= 0.11.5 && < 3", + "node:sqlite": [">= 22.13 && < 23", ">= 23.4"], + "_stream_duplex": ">= 0.9.4", + "node:_stream_duplex": [">= 14.18 && < 15", ">= 16"], + "_stream_transform": ">= 0.9.4", + "node:_stream_transform": [">= 14.18 && < 15", ">= 16"], + "_stream_wrap": ">= 1.4.1", + "node:_stream_wrap": [">= 14.18 && < 15", ">= 16"], + "_stream_passthrough": ">= 0.9.4", + "node:_stream_passthrough": [">= 14.18 && < 15", ">= 16"], + "_stream_readable": ">= 0.9.4", + "node:_stream_readable": [">= 14.18 && < 15", ">= 16"], + "_stream_writable": ">= 0.9.4", + "node:_stream_writable": [">= 14.18 && < 15", ">= 16"], + "stream": true, + "node:stream": [">= 14.18 && < 15", ">= 16"], + "stream/consumers": ">= 16.7", + "node:stream/consumers": ">= 16.7", + "stream/promises": ">= 15", + "node:stream/promises": ">= 16", + "stream/web": ">= 16.5", + "node:stream/web": ">= 16.5", + "string_decoder": true, + "node:string_decoder": [">= 14.18 && < 15", ">= 16"], + "sys": [">= 0.4 && < 0.7", ">= 0.8"], + "node:sys": [">= 14.18 && < 15", ">= 16"], + "test/reporters": ">= 19.9 && < 20.2", + "node:test/reporters": [">= 18.17 && < 19", ">= 19.9", ">= 20"], + "test/mock_loader": ">= 22.3 && < 22.7", + "node:test/mock_loader": ">= 22.3 && < 22.7", + "node:test": [">= 16.17 && < 17", ">= 18"], + "timers": true, + "node:timers": [">= 14.18 && < 15", ">= 16"], + "timers/promises": ">= 15", + "node:timers/promises": ">= 16", + "_tls_common": ">= 0.11.13", + "node:_tls_common": [">= 14.18 && < 15", ">= 16"], + "_tls_legacy": ">= 0.11.3 && < 10", + "_tls_wrap": ">= 0.11.3", + "node:_tls_wrap": [">= 14.18 && < 15", ">= 16"], + "tls": true, + "node:tls": [">= 14.18 && < 15", ">= 16"], + "trace_events": ">= 10", + "node:trace_events": [">= 14.18 && < 15", ">= 16"], + "tty": true, + "node:tty": [">= 14.18 && < 15", ">= 16"], + "url": true, + "node:url": [">= 14.18 && < 15", ">= 16"], + "util": true, + "node:util": [">= 14.18 && < 15", ">= 16"], + "util/types": ">= 15.3", + "node:util/types": ">= 16", + "v8/tools/arguments": ">= 10 && < 12", + "v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8": ">= 1", + "node:v8": [">= 14.18 && < 15", ">= 16"], + "vm": true, + "node:vm": [">= 14.18 && < 15", ">= 16"], + "wasi": [">= 13.4 && < 13.5", ">= 18.17 && < 19", ">= 20"], + "node:wasi": [">= 18.17 && < 19", ">= 20"], + "worker_threads": ">= 11.7", + "node:worker_threads": [">= 14.18 && < 15", ">= 16"], + "zlib": ">= 0.5", + "node:zlib": [">= 14.18 && < 15", ">= 16"] +} diff --git a/node_modules/is-core-module/index.js b/node_modules/is-core-module/index.js new file mode 100644 index 0000000..423e20c --- /dev/null +++ b/node_modules/is-core-module/index.js @@ -0,0 +1,69 @@ +'use strict'; + +var hasOwn = require('hasown'); + +function specifierIncluded(current, specifier) { + var nodeParts = current.split('.'); + var parts = specifier.split(' '); + var op = parts.length > 1 ? parts[0] : '='; + var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); + + for (var i = 0; i < 3; ++i) { + var cur = parseInt(nodeParts[i] || 0, 10); + var ver = parseInt(versionParts[i] || 0, 10); + if (cur === ver) { + continue; // eslint-disable-line no-restricted-syntax, no-continue + } + if (op === '<') { + return cur < ver; + } + if (op === '>=') { + return cur >= ver; + } + return false; + } + return op === '>='; +} + +function matchesRange(current, range) { + var specifiers = range.split(/ ?&& ?/); + if (specifiers.length === 0) { + return false; + } + for (var i = 0; i < specifiers.length; ++i) { + if (!specifierIncluded(current, specifiers[i])) { + return false; + } + } + return true; +} + +function versionIncluded(nodeVersion, specifierValue) { + if (typeof specifierValue === 'boolean') { + return specifierValue; + } + + var current = typeof nodeVersion === 'undefined' + ? process.versions && process.versions.node + : nodeVersion; + + if (typeof current !== 'string') { + throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); + } + + if (specifierValue && typeof specifierValue === 'object') { + for (var i = 0; i < specifierValue.length; ++i) { + if (matchesRange(current, specifierValue[i])) { + return true; + } + } + return false; + } + return matchesRange(current, specifierValue); +} + +var data = require('./core.json'); + +module.exports = function isCore(x, nodeVersion) { + return hasOwn(data, x) && versionIncluded(nodeVersion, data[x]); +}; diff --git a/node_modules/is-core-module/package.json b/node_modules/is-core-module/package.json new file mode 100644 index 0000000..2668256 --- /dev/null +++ b/node_modules/is-core-module/package.json @@ -0,0 +1,76 @@ +{ + "name": "is-core-module", + "version": "2.16.1", + "description": "Is this specifier a node.js core module?", + "main": "index.js", + "sideEffects": false, + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "lint": "eslint .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/is-core-module.git" + }, + "keywords": [ + "core", + "modules", + "module", + "npm", + "node", + "dependencies" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/is-core-module/issues" + }, + "homepage": "https://github.com/inspect-js/is-core-module", + "dependencies": { + "hasown": "^2.0.2" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.1", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "mock-property": "^1.1.0", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "semver": "^6.3.1", + "tape": "^5.9.0" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/is-core-module/test/index.js b/node_modules/is-core-module/test/index.js new file mode 100644 index 0000000..7a81e1c --- /dev/null +++ b/node_modules/is-core-module/test/index.js @@ -0,0 +1,157 @@ +'use strict'; + +var test = require('tape'); +var keys = require('object-keys'); +var semver = require('semver'); +var mockProperty = require('mock-property'); + +var isCore = require('../'); +var data = require('../core.json'); + +var supportsNodePrefix = semver.satisfies(process.versions.node, '^14.18 || >= 16', { includePrerelease: true }); + +test('core modules', function (t) { + t.test('isCore()', function (st) { + st.ok(isCore('fs')); + st.ok(isCore('net')); + st.ok(isCore('http')); + + st.ok(!isCore('seq')); + st.ok(!isCore('../')); + + st.ok(!isCore('toString')); + + st.end(); + }); + + t.test('core list', function (st) { + var cores = keys(data); + st.plan(cores.length); + + for (var i = 0; i < cores.length; ++i) { + var mod = cores[i]; + var requireFunc = function () { require(mod); }; // eslint-disable-line no-loop-func + if (isCore(mod)) { + st.doesNotThrow(requireFunc, mod + ' supported; requiring does not throw'); + } else { + st['throws'](requireFunc, mod + ' not supported; requiring throws'); + } + } + + st.end(); + }); + + t.test('core via repl module', { skip: !data.repl }, function (st) { + var libs = require('repl')._builtinLibs; // eslint-disable-line no-underscore-dangle + if (!libs) { + st.skip('repl._builtinLibs does not exist'); + } else { + for (var i = 0; i < libs.length; ++i) { + var mod = libs[i]; + st.ok(data[mod], mod + ' is a core module'); + st.doesNotThrow( + function () { require(mod); }, // eslint-disable-line no-loop-func + 'requiring ' + mod + ' does not throw' + ); + if (mod.slice(0, 5) !== 'node:') { + if (supportsNodePrefix) { + st.doesNotThrow( + function () { require('node:' + mod); }, // eslint-disable-line no-loop-func + 'requiring node:' + mod + ' does not throw' + ); + } else { + st['throws']( + function () { require('node:' + mod); }, // eslint-disable-line no-loop-func + 'requiring node:' + mod + ' throws' + ); + } + } + } + } + st.end(); + }); + + t.test('core via builtinModules list', { skip: !data.module }, function (st) { + var Module = require('module'); + var libs = Module.builtinModules; + if (!libs) { + st.skip('module.builtinModules does not exist'); + } else { + var excludeList = [ + '_debug_agent', + 'v8/tools/tickprocessor-driver', + 'v8/tools/SourceMap', + 'v8/tools/tickprocessor', + 'v8/tools/profile' + ]; + + // see https://github.com/nodejs/node/issues/42785 + if (semver.satisfies(process.version, '>= 18')) { + libs = libs.concat('node:test'); + } + if (semver.satisfies(process.version, '^20.12 || >= 21.7')) { + libs = libs.concat('node:sea'); + } + if (semver.satisfies(process.version, '>= 23.4')) { + libs = libs.concat('node:sqlite'); + } + + for (var i = 0; i < libs.length; ++i) { + var mod = libs[i]; + if (excludeList.indexOf(mod) === -1) { + st.ok(data[mod], mod + ' is a core module'); + + if (Module.isBuiltin) { + st.ok(Module.isBuiltin(mod), 'module.isBuiltin(' + mod + ') is true'); + } + + st.doesNotThrow( + function () { require(mod); }, // eslint-disable-line no-loop-func + 'requiring ' + mod + ' does not throw' + ); + + if (process.getBuiltinModule) { + st.equal( + process.getBuiltinModule(mod), + require(mod), + 'process.getBuiltinModule(' + mod + ') === require(' + mod + ')' + ); + } + + if (mod.slice(0, 5) !== 'node:') { + if (supportsNodePrefix) { + st.doesNotThrow( + function () { require('node:' + mod); }, // eslint-disable-line no-loop-func + 'requiring node:' + mod + ' does not throw' + ); + } else { + st['throws']( + function () { require('node:' + mod); }, // eslint-disable-line no-loop-func + 'requiring node:' + mod + ' throws' + ); + } + } + } + } + } + + st.end(); + }); + + t.test('Object.prototype pollution', function (st) { + var nonKey = 'not a core module'; + st.teardown(mockProperty(Object.prototype, 'fs', { value: false })); + st.teardown(mockProperty(Object.prototype, 'path', { value: '>= 999999999' })); + st.teardown(mockProperty(Object.prototype, 'http', { value: data.http })); + st.teardown(mockProperty(Object.prototype, nonKey, { value: true })); + + st.equal(isCore('fs'), true, 'fs is a core module even if Object.prototype lies'); + st.equal(isCore('path'), true, 'path is a core module even if Object.prototype lies'); + st.equal(isCore('http'), true, 'path is a core module even if Object.prototype matches data'); + st.equal(isCore(nonKey), false, '"' + nonKey + '" is not a core module even if Object.prototype lies'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/is-extglob/LICENSE b/node_modules/is-extglob/LICENSE new file mode 100644 index 0000000..842218c --- /dev/null +++ b/node_modules/is-extglob/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2016, Jon Schlinkert + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/is-extglob/README.md b/node_modules/is-extglob/README.md new file mode 100644 index 0000000..0416af5 --- /dev/null +++ b/node_modules/is-extglob/README.md @@ -0,0 +1,107 @@ +# is-extglob [![NPM version](https://img.shields.io/npm/v/is-extglob.svg?style=flat)](https://www.npmjs.com/package/is-extglob) [![NPM downloads](https://img.shields.io/npm/dm/is-extglob.svg?style=flat)](https://npmjs.org/package/is-extglob) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-extglob.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-extglob) + +> Returns true if a string has an extglob. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save is-extglob +``` + +## Usage + +```js +var isExtglob = require('is-extglob'); +``` + +**True** + +```js +isExtglob('?(abc)'); +isExtglob('@(abc)'); +isExtglob('!(abc)'); +isExtglob('*(abc)'); +isExtglob('+(abc)'); +``` + +**False** + +Escaped extglobs: + +```js +isExtglob('\\?(abc)'); +isExtglob('\\@(abc)'); +isExtglob('\\!(abc)'); +isExtglob('\\*(abc)'); +isExtglob('\\+(abc)'); +``` + +Everything else... + +```js +isExtglob('foo.js'); +isExtglob('!foo.js'); +isExtglob('*.js'); +isExtglob('**/abc.js'); +isExtglob('abc/*.js'); +isExtglob('abc/(aaa|bbb).js'); +isExtglob('abc/[a-z].js'); +isExtglob('abc/{a,b}.js'); +isExtglob('abc/?.js'); +isExtglob('abc.js'); +isExtglob('abc/def/ghi.js'); +``` + +## History + +**v2.0** + +Adds support for escaping. Escaped exglobs no longer return true. + +## About + +### Related projects + +* [has-glob](https://www.npmjs.com/package/has-glob): Returns `true` if an array has a glob pattern. | [homepage](https://github.com/jonschlinkert/has-glob "Returns `true` if an array has a glob pattern.") +* [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") +* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") + +### Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +### Building docs + +_(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ + +To generate the readme and API documentation with [verb](https://github.com/verbose/verb): + +```sh +$ npm install -g verb verb-generate-readme && verb +``` + +### Running tests + +Install dev dependencies: + +```sh +$ npm install -d && npm test +``` + +### Author + +**Jon Schlinkert** + +* [github/jonschlinkert](https://github.com/jonschlinkert) +* [twitter/jonschlinkert](http://twitter.com/jonschlinkert) + +### License + +Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT license](https://github.com/jonschlinkert/is-extglob/blob/master/LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ \ No newline at end of file diff --git a/node_modules/is-extglob/index.js b/node_modules/is-extglob/index.js new file mode 100644 index 0000000..c1d986f --- /dev/null +++ b/node_modules/is-extglob/index.js @@ -0,0 +1,20 @@ +/*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + +module.exports = function isExtglob(str) { + if (typeof str !== 'string' || str === '') { + return false; + } + + var match; + while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + + return false; +}; diff --git a/node_modules/is-extglob/package.json b/node_modules/is-extglob/package.json new file mode 100644 index 0000000..7a90836 --- /dev/null +++ b/node_modules/is-extglob/package.json @@ -0,0 +1,69 @@ +{ + "name": "is-extglob", + "description": "Returns true if a string has an extglob.", + "version": "2.1.1", + "homepage": "https://github.com/jonschlinkert/is-extglob", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "repository": "jonschlinkert/is-extglob", + "bugs": { + "url": "https://github.com/jonschlinkert/is-extglob/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "gulp-format-md": "^0.1.10", + "mocha": "^3.0.2" + }, + "keywords": [ + "bash", + "braces", + "check", + "exec", + "expression", + "extglob", + "glob", + "globbing", + "globstar", + "is", + "match", + "matches", + "pattern", + "regex", + "regular", + "string", + "test" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "related": { + "list": [ + "has-glob", + "is-glob", + "micromatch" + ] + }, + "reflinks": [ + "verb", + "verb-generate-readme" + ], + "lint": { + "reflinks": true + } + } +} diff --git a/node_modules/is-glob/LICENSE b/node_modules/is-glob/LICENSE new file mode 100644 index 0000000..3f2eca1 --- /dev/null +++ b/node_modules/is-glob/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2017, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/is-glob/README.md b/node_modules/is-glob/README.md new file mode 100644 index 0000000..740724b --- /dev/null +++ b/node_modules/is-glob/README.md @@ -0,0 +1,206 @@ +# is-glob [![NPM version](https://img.shields.io/npm/v/is-glob.svg?style=flat)](https://www.npmjs.com/package/is-glob) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![NPM total downloads](https://img.shields.io/npm/dt/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![Build Status](https://img.shields.io/github/workflow/status/micromatch/is-glob/dev)](https://github.com/micromatch/is-glob/actions) + +> Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save is-glob +``` + +You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). + +## Usage + +```js +var isGlob = require('is-glob'); +``` + +### Default behavior + +**True** + +Patterns that have glob characters or regex patterns will return `true`: + +```js +isGlob('!foo.js'); +isGlob('*.js'); +isGlob('**/abc.js'); +isGlob('abc/*.js'); +isGlob('abc/(aaa|bbb).js'); +isGlob('abc/[a-z].js'); +isGlob('abc/{a,b}.js'); +//=> true +``` + +Extglobs + +```js +isGlob('abc/@(a).js'); +isGlob('abc/!(a).js'); +isGlob('abc/+(a).js'); +isGlob('abc/*(a).js'); +isGlob('abc/?(a).js'); +//=> true +``` + +**False** + +Escaped globs or extglobs return `false`: + +```js +isGlob('abc/\\@(a).js'); +isGlob('abc/\\!(a).js'); +isGlob('abc/\\+(a).js'); +isGlob('abc/\\*(a).js'); +isGlob('abc/\\?(a).js'); +isGlob('\\!foo.js'); +isGlob('\\*.js'); +isGlob('\\*\\*/abc.js'); +isGlob('abc/\\*.js'); +isGlob('abc/\\(aaa|bbb).js'); +isGlob('abc/\\[a-z].js'); +isGlob('abc/\\{a,b}.js'); +//=> false +``` + +Patterns that do not have glob patterns return `false`: + +```js +isGlob('abc.js'); +isGlob('abc/def/ghi.js'); +isGlob('foo.js'); +isGlob('abc/@.js'); +isGlob('abc/+.js'); +isGlob('abc/?.js'); +isGlob(); +isGlob(null); +//=> false +``` + +Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): + +```js +isGlob(['**/*.js']); +isGlob(['foo.js']); +//=> false +``` + +### Option strict + +When `options.strict === false` the behavior is less strict in determining if a pattern is a glob. Meaning that +some patterns that would return `false` may return `true`. This is done so that matching libraries like [micromatch](https://github.com/micromatch/micromatch) have a chance at determining if the pattern is a glob or not. + +**True** + +Patterns that have glob characters or regex patterns will return `true`: + +```js +isGlob('!foo.js', {strict: false}); +isGlob('*.js', {strict: false}); +isGlob('**/abc.js', {strict: false}); +isGlob('abc/*.js', {strict: false}); +isGlob('abc/(aaa|bbb).js', {strict: false}); +isGlob('abc/[a-z].js', {strict: false}); +isGlob('abc/{a,b}.js', {strict: false}); +//=> true +``` + +Extglobs + +```js +isGlob('abc/@(a).js', {strict: false}); +isGlob('abc/!(a).js', {strict: false}); +isGlob('abc/+(a).js', {strict: false}); +isGlob('abc/*(a).js', {strict: false}); +isGlob('abc/?(a).js', {strict: false}); +//=> true +``` + +**False** + +Escaped globs or extglobs return `false`: + +```js +isGlob('\\!foo.js', {strict: false}); +isGlob('\\*.js', {strict: false}); +isGlob('\\*\\*/abc.js', {strict: false}); +isGlob('abc/\\*.js', {strict: false}); +isGlob('abc/\\(aaa|bbb).js', {strict: false}); +isGlob('abc/\\[a-z].js', {strict: false}); +isGlob('abc/\\{a,b}.js', {strict: false}); +//=> false +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") +* [base](https://www.npmjs.com/package/base): Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks | [homepage](https://github.com/node-base/base "Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks") +* [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") +* [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 47 | [jonschlinkert](https://github.com/jonschlinkert) | +| 5 | [doowb](https://github.com/doowb) | +| 1 | [phated](https://github.com/phated) | +| 1 | [danhper](https://github.com/danhper) | +| 1 | [paulmillr](https://github.com/paulmillr) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 27, 2019._ \ No newline at end of file diff --git a/node_modules/is-glob/index.js b/node_modules/is-glob/index.js new file mode 100644 index 0000000..620f563 --- /dev/null +++ b/node_modules/is-glob/index.js @@ -0,0 +1,150 @@ +/*! + * is-glob + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +var isExtglob = require('is-extglob'); +var chars = { '{': '}', '(': ')', '[': ']'}; +var strictCheck = function(str) { + if (str[0] === '!') { + return true; + } + var index = 0; + var pipeIndex = -2; + var closeSquareIndex = -2; + var closeCurlyIndex = -2; + var closeParenIndex = -2; + var backSlashIndex = -2; + while (index < str.length) { + if (str[index] === '*') { + return true; + } + + if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) { + return true; + } + + if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') { + if (closeSquareIndex < index) { + closeSquareIndex = str.indexOf(']', index); + } + if (closeSquareIndex > index) { + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { + return true; + } + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { + return true; + } + } + } + + if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') { + closeCurlyIndex = str.indexOf('}', index); + if (closeCurlyIndex > index) { + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) { + return true; + } + } + } + + if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') { + closeParenIndex = str.indexOf(')', index); + if (closeParenIndex > index) { + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { + return true; + } + } + } + + if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') { + if (pipeIndex < index) { + pipeIndex = str.indexOf('|', index); + } + if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') { + closeParenIndex = str.indexOf(')', pipeIndex); + if (closeParenIndex > pipeIndex) { + backSlashIndex = str.indexOf('\\', pipeIndex); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { + return true; + } + } + } + } + + if (str[index] === '\\') { + var open = str[index + 1]; + index += 2; + var close = chars[open]; + + if (close) { + var n = str.indexOf(close, index); + if (n !== -1) { + index = n + 1; + } + } + + if (str[index] === '!') { + return true; + } + } else { + index++; + } + } + return false; +}; + +var relaxedCheck = function(str) { + if (str[0] === '!') { + return true; + } + var index = 0; + while (index < str.length) { + if (/[*?{}()[\]]/.test(str[index])) { + return true; + } + + if (str[index] === '\\') { + var open = str[index + 1]; + index += 2; + var close = chars[open]; + + if (close) { + var n = str.indexOf(close, index); + if (n !== -1) { + index = n + 1; + } + } + + if (str[index] === '!') { + return true; + } + } else { + index++; + } + } + return false; +}; + +module.exports = function isGlob(str, options) { + if (typeof str !== 'string' || str === '') { + return false; + } + + if (isExtglob(str)) { + return true; + } + + var check = strictCheck; + + // optionally relax check + if (options && options.strict === false) { + check = relaxedCheck; + } + + return check(str); +}; diff --git a/node_modules/is-glob/package.json b/node_modules/is-glob/package.json new file mode 100644 index 0000000..858af03 --- /dev/null +++ b/node_modules/is-glob/package.json @@ -0,0 +1,81 @@ +{ + "name": "is-glob", + "description": "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience.", + "version": "4.0.3", + "homepage": "https://github.com/micromatch/is-glob", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Brian Woodward (https://twitter.com/doowb)", + "Daniel Perez (https://tuvistavie.com)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)" + ], + "repository": "micromatch/is-glob", + "bugs": { + "url": "https://github.com/micromatch/is-glob/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha && node benchmark.js" + }, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "devDependencies": { + "gulp-format-md": "^0.1.10", + "mocha": "^3.0.2" + }, + "keywords": [ + "bash", + "braces", + "check", + "exec", + "expression", + "extglob", + "glob", + "globbing", + "globstar", + "is", + "match", + "matches", + "pattern", + "regex", + "regular", + "string", + "test" + ], + "verb": { + "layout": "default", + "plugins": [ + "gulp-format-md" + ], + "related": { + "list": [ + "assemble", + "base", + "update", + "verb" + ] + }, + "reflinks": [ + "assemble", + "bach", + "base", + "composer", + "gulp", + "has-glob", + "is-valid-glob", + "micromatch", + "npm", + "scaffold", + "verb", + "vinyl" + ] + } +} diff --git a/node_modules/is-number/LICENSE b/node_modules/is-number/LICENSE new file mode 100644 index 0000000..9af4a67 --- /dev/null +++ b/node_modules/is-number/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/is-number/README.md b/node_modules/is-number/README.md new file mode 100644 index 0000000..eb8149e --- /dev/null +++ b/node_modules/is-number/README.md @@ -0,0 +1,187 @@ +# is-number [![NPM version](https://img.shields.io/npm/v/is-number.svg?style=flat)](https://www.npmjs.com/package/is-number) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-number.svg?style=flat)](https://npmjs.org/package/is-number) [![NPM total downloads](https://img.shields.io/npm/dt/is-number.svg?style=flat)](https://npmjs.org/package/is-number) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-number.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-number) + +> Returns true if the value is a finite number. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save is-number +``` + +## Why is this needed? + +In JavaScript, it's not always as straightforward as it should be to reliably check if a value is a number. It's common for devs to use `+`, `-`, or `Number()` to cast a string value to a number (for example, when values are returned from user input, regex matches, parsers, etc). But there are many non-intuitive edge cases that yield unexpected results: + +```js +console.log(+[]); //=> 0 +console.log(+''); //=> 0 +console.log(+' '); //=> 0 +console.log(typeof NaN); //=> 'number' +``` + +This library offers a performant way to smooth out edge cases like these. + +## Usage + +```js +const isNumber = require('is-number'); +``` + +See the [tests](./test.js) for more examples. + +### true + +```js +isNumber(5e3); // true +isNumber(0xff); // true +isNumber(-1.1); // true +isNumber(0); // true +isNumber(1); // true +isNumber(1.1); // true +isNumber(10); // true +isNumber(10.10); // true +isNumber(100); // true +isNumber('-1.1'); // true +isNumber('0'); // true +isNumber('012'); // true +isNumber('0xff'); // true +isNumber('1'); // true +isNumber('1.1'); // true +isNumber('10'); // true +isNumber('10.10'); // true +isNumber('100'); // true +isNumber('5e3'); // true +isNumber(parseInt('012')); // true +isNumber(parseFloat('012')); // true +``` + +### False + +Everything else is false, as you would expect: + +```js +isNumber(Infinity); // false +isNumber(NaN); // false +isNumber(null); // false +isNumber(undefined); // false +isNumber(''); // false +isNumber(' '); // false +isNumber('foo'); // false +isNumber([1]); // false +isNumber([]); // false +isNumber(function () {}); // false +isNumber({}); // false +``` + +## Release history + +### 7.0.0 + +* Refactor. Now uses `.isFinite` if it exists. +* Performance is about the same as v6.0 when the value is a string or number. But it's now 3x-4x faster when the value is not a string or number. + +### 6.0.0 + +* Optimizations, thanks to @benaadams. + +### 5.0.0 + +**Breaking changes** + +* removed support for `instanceof Number` and `instanceof String` + +## Benchmarks + +As with all benchmarks, take these with a grain of salt. See the [benchmarks](./benchmark/index.js) for more detail. + +``` +# all +v7.0 x 413,222 ops/sec ±2.02% (86 runs sampled) +v6.0 x 111,061 ops/sec ±1.29% (85 runs sampled) +parseFloat x 317,596 ops/sec ±1.36% (86 runs sampled) +fastest is 'v7.0' + +# string +v7.0 x 3,054,496 ops/sec ±1.05% (89 runs sampled) +v6.0 x 2,957,781 ops/sec ±0.98% (88 runs sampled) +parseFloat x 3,071,060 ops/sec ±1.13% (88 runs sampled) +fastest is 'parseFloat,v7.0' + +# number +v7.0 x 3,146,895 ops/sec ±0.89% (89 runs sampled) +v6.0 x 3,214,038 ops/sec ±1.07% (89 runs sampled) +parseFloat x 3,077,588 ops/sec ±1.07% (87 runs sampled) +fastest is 'v6.0' +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") +* [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") +* [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") +* [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 49 | [jonschlinkert](https://github.com/jonschlinkert) | +| 5 | [charlike-old](https://github.com/charlike-old) | +| 1 | [benaadams](https://github.com/benaadams) | +| 1 | [realityking](https://github.com/realityking) | + +### Author + +**Jon Schlinkert** + +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) + +### License + +Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 15, 2018._ \ No newline at end of file diff --git a/node_modules/is-number/index.js b/node_modules/is-number/index.js new file mode 100644 index 0000000..27f19b7 --- /dev/null +++ b/node_modules/is-number/index.js @@ -0,0 +1,18 @@ +/*! + * is-number + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + +'use strict'; + +module.exports = function(num) { + if (typeof num === 'number') { + return num - num === 0; + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); + } + return false; +}; diff --git a/node_modules/is-number/package.json b/node_modules/is-number/package.json new file mode 100644 index 0000000..3715072 --- /dev/null +++ b/node_modules/is-number/package.json @@ -0,0 +1,82 @@ +{ + "name": "is-number", + "description": "Returns true if a number or string value is a finite number. Useful for regex matches, parsing, user input, etc.", + "version": "7.0.0", + "homepage": "https://github.com/jonschlinkert/is-number", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Jon Schlinkert (http://twitter.com/jonschlinkert)", + "Olsten Larck (https://i.am.charlike.online)", + "Rouven Weßling (www.rouvenwessling.de)" + ], + "repository": "jonschlinkert/is-number", + "bugs": { + "url": "https://github.com/jonschlinkert/is-number/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=0.12.0" + }, + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "ansi": "^0.3.1", + "benchmark": "^2.1.4", + "gulp-format-md": "^1.0.0", + "mocha": "^3.5.3" + }, + "keywords": [ + "cast", + "check", + "coerce", + "coercion", + "finite", + "integer", + "is", + "isnan", + "is-nan", + "is-num", + "is-number", + "isnumber", + "isfinite", + "istype", + "kind", + "math", + "nan", + "num", + "number", + "numeric", + "parseFloat", + "parseInt", + "test", + "type", + "typeof", + "value" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "related": { + "list": [ + "is-plain-object", + "is-primitive", + "isobject", + "kind-of" + ] + }, + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + } + } +} diff --git a/node_modules/isexe/.npmignore b/node_modules/isexe/.npmignore new file mode 100644 index 0000000..c1cb757 --- /dev/null +++ b/node_modules/isexe/.npmignore @@ -0,0 +1,2 @@ +.nyc_output/ +coverage/ diff --git a/node_modules/isexe/LICENSE b/node_modules/isexe/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/isexe/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/isexe/README.md b/node_modules/isexe/README.md new file mode 100644 index 0000000..35769e8 --- /dev/null +++ b/node_modules/isexe/README.md @@ -0,0 +1,51 @@ +# isexe + +Minimal module to check if a file is executable, and a normal file. + +Uses `fs.stat` and tests against the `PATHEXT` environment variable on +Windows. + +## USAGE + +```javascript +var isexe = require('isexe') +isexe('some-file-name', function (err, isExe) { + if (err) { + console.error('probably file does not exist or something', err) + } else if (isExe) { + console.error('this thing can be run') + } else { + console.error('cannot be run') + } +}) + +// same thing but synchronous, throws errors +var isExe = isexe.sync('some-file-name') + +// treat errors as just "not executable" +isexe('maybe-missing-file', { ignoreErrors: true }, callback) +var isExe = isexe.sync('maybe-missing-file', { ignoreErrors: true }) +``` + +## API + +### `isexe(path, [options], [callback])` + +Check if the path is executable. If no callback provided, and a +global `Promise` object is available, then a Promise will be returned. + +Will raise whatever errors may be raised by `fs.stat`, unless +`options.ignoreErrors` is set to true. + +### `isexe.sync(path, [options])` + +Same as `isexe` but returns the value and throws any errors raised. + +### Options + +* `ignoreErrors` Treat all errors as "no, this is not executable", but + don't raise them. +* `uid` Number to use as the user id +* `gid` Number to use as the group id +* `pathExt` List of path extensions to use instead of `PATHEXT` + environment variable on Windows. diff --git a/node_modules/isexe/index.js b/node_modules/isexe/index.js new file mode 100644 index 0000000..553fb32 --- /dev/null +++ b/node_modules/isexe/index.js @@ -0,0 +1,57 @@ +var fs = require('fs') +var core +if (process.platform === 'win32' || global.TESTING_WINDOWS) { + core = require('./windows.js') +} else { + core = require('./mode.js') +} + +module.exports = isexe +isexe.sync = sync + +function isexe (path, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} + } + + if (!cb) { + if (typeof Promise !== 'function') { + throw new TypeError('callback not provided') + } + + return new Promise(function (resolve, reject) { + isexe(path, options || {}, function (er, is) { + if (er) { + reject(er) + } else { + resolve(is) + } + }) + }) + } + + core(path, options || {}, function (er, is) { + // ignore EACCES because that just means we aren't allowed to run it + if (er) { + if (er.code === 'EACCES' || options && options.ignoreErrors) { + er = null + is = false + } + } + cb(er, is) + }) +} + +function sync (path, options) { + // my kingdom for a filtered catch + try { + return core.sync(path, options || {}) + } catch (er) { + if (options && options.ignoreErrors || er.code === 'EACCES') { + return false + } else { + throw er + } + } +} diff --git a/node_modules/isexe/mode.js b/node_modules/isexe/mode.js new file mode 100644 index 0000000..1995ea4 --- /dev/null +++ b/node_modules/isexe/mode.js @@ -0,0 +1,41 @@ +module.exports = isexe +isexe.sync = sync + +var fs = require('fs') + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), options) +} + +function checkStat (stat, options) { + return stat.isFile() && checkMode(stat, options) +} + +function checkMode (stat, options) { + var mod = stat.mode + var uid = stat.uid + var gid = stat.gid + + var myUid = options.uid !== undefined ? + options.uid : process.getuid && process.getuid() + var myGid = options.gid !== undefined ? + options.gid : process.getgid && process.getgid() + + var u = parseInt('100', 8) + var g = parseInt('010', 8) + var o = parseInt('001', 8) + var ug = u | g + + var ret = (mod & o) || + (mod & g) && gid === myGid || + (mod & u) && uid === myUid || + (mod & ug) && myUid === 0 + + return ret +} diff --git a/node_modules/isexe/package.json b/node_modules/isexe/package.json new file mode 100644 index 0000000..e452689 --- /dev/null +++ b/node_modules/isexe/package.json @@ -0,0 +1,31 @@ +{ + "name": "isexe", + "version": "2.0.0", + "description": "Minimal module to check if a file is executable.", + "main": "index.js", + "directories": { + "test": "test" + }, + "devDependencies": { + "mkdirp": "^0.5.1", + "rimraf": "^2.5.0", + "tap": "^10.3.0" + }, + "scripts": { + "test": "tap test/*.js --100", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/isexe.git" + }, + "keywords": [], + "bugs": { + "url": "https://github.com/isaacs/isexe/issues" + }, + "homepage": "https://github.com/isaacs/isexe#readme" +} diff --git a/node_modules/isexe/test/basic.js b/node_modules/isexe/test/basic.js new file mode 100644 index 0000000..d926df6 --- /dev/null +++ b/node_modules/isexe/test/basic.js @@ -0,0 +1,221 @@ +var t = require('tap') +var fs = require('fs') +var path = require('path') +var fixture = path.resolve(__dirname, 'fixtures') +var meow = fixture + '/meow.cat' +var mine = fixture + '/mine.cat' +var ours = fixture + '/ours.cat' +var fail = fixture + '/fail.false' +var noent = fixture + '/enoent.exe' +var mkdirp = require('mkdirp') +var rimraf = require('rimraf') + +var isWindows = process.platform === 'win32' +var hasAccess = typeof fs.access === 'function' +var winSkip = isWindows && 'windows' +var accessSkip = !hasAccess && 'no fs.access function' +var hasPromise = typeof Promise === 'function' +var promiseSkip = !hasPromise && 'no global Promise' + +function reset () { + delete require.cache[require.resolve('../')] + return require('../') +} + +t.test('setup fixtures', function (t) { + rimraf.sync(fixture) + mkdirp.sync(fixture) + fs.writeFileSync(meow, '#!/usr/bin/env cat\nmeow\n') + fs.chmodSync(meow, parseInt('0755', 8)) + fs.writeFileSync(fail, '#!/usr/bin/env false\n') + fs.chmodSync(fail, parseInt('0644', 8)) + fs.writeFileSync(mine, '#!/usr/bin/env cat\nmine\n') + fs.chmodSync(mine, parseInt('0744', 8)) + fs.writeFileSync(ours, '#!/usr/bin/env cat\nours\n') + fs.chmodSync(ours, parseInt('0754', 8)) + t.end() +}) + +t.test('promise', { skip: promiseSkip }, function (t) { + var isexe = reset() + t.test('meow async', function (t) { + isexe(meow).then(function (is) { + t.ok(is) + t.end() + }) + }) + t.test('fail async', function (t) { + isexe(fail).then(function (is) { + t.notOk(is) + t.end() + }) + }) + t.test('noent async', function (t) { + isexe(noent).catch(function (er) { + t.ok(er) + t.end() + }) + }) + t.test('noent ignore async', function (t) { + isexe(noent, { ignoreErrors: true }).then(function (is) { + t.notOk(is) + t.end() + }) + }) + t.end() +}) + +t.test('no promise', function (t) { + global.Promise = null + var isexe = reset() + t.throws('try to meow a promise', function () { + isexe(meow) + }) + t.end() +}) + +t.test('access', { skip: accessSkip || winSkip }, function (t) { + runTest(t) +}) + +t.test('mode', { skip: winSkip }, function (t) { + delete fs.access + delete fs.accessSync + var isexe = reset() + t.ok(isexe.sync(ours, { uid: 0, gid: 0 })) + t.ok(isexe.sync(mine, { uid: 0, gid: 0 })) + runTest(t) +}) + +t.test('windows', function (t) { + global.TESTING_WINDOWS = true + var pathExt = '.EXE;.CAT;.CMD;.COM' + t.test('pathExt option', function (t) { + runTest(t, { pathExt: '.EXE;.CAT;.CMD;.COM' }) + }) + t.test('pathExt env', function (t) { + process.env.PATHEXT = pathExt + runTest(t) + }) + t.test('no pathExt', function (t) { + // with a pathExt of '', any filename is fine. + // so the "fail" one would still pass. + runTest(t, { pathExt: '', skipFail: true }) + }) + t.test('pathext with empty entry', function (t) { + // with a pathExt of '', any filename is fine. + // so the "fail" one would still pass. + runTest(t, { pathExt: ';' + pathExt, skipFail: true }) + }) + t.end() +}) + +t.test('cleanup', function (t) { + rimraf.sync(fixture) + t.end() +}) + +function runTest (t, options) { + var isexe = reset() + + var optionsIgnore = Object.create(options || {}) + optionsIgnore.ignoreErrors = true + + if (!options || !options.skipFail) { + t.notOk(isexe.sync(fail, options)) + } + t.notOk(isexe.sync(noent, optionsIgnore)) + if (!options) { + t.ok(isexe.sync(meow)) + } else { + t.ok(isexe.sync(meow, options)) + } + + t.ok(isexe.sync(mine, options)) + t.ok(isexe.sync(ours, options)) + t.throws(function () { + isexe.sync(noent, options) + }) + + t.test('meow async', function (t) { + if (!options) { + isexe(meow, function (er, is) { + if (er) { + throw er + } + t.ok(is) + t.end() + }) + } else { + isexe(meow, options, function (er, is) { + if (er) { + throw er + } + t.ok(is) + t.end() + }) + } + }) + + t.test('mine async', function (t) { + isexe(mine, options, function (er, is) { + if (er) { + throw er + } + t.ok(is) + t.end() + }) + }) + + t.test('ours async', function (t) { + isexe(ours, options, function (er, is) { + if (er) { + throw er + } + t.ok(is) + t.end() + }) + }) + + if (!options || !options.skipFail) { + t.test('fail async', function (t) { + isexe(fail, options, function (er, is) { + if (er) { + throw er + } + t.notOk(is) + t.end() + }) + }) + } + + t.test('noent async', function (t) { + isexe(noent, options, function (er, is) { + t.ok(er) + t.notOk(is) + t.end() + }) + }) + + t.test('noent ignore async', function (t) { + isexe(noent, optionsIgnore, function (er, is) { + if (er) { + throw er + } + t.notOk(is) + t.end() + }) + }) + + t.test('directory is not executable', function (t) { + isexe(__dirname, options, function (er, is) { + if (er) { + throw er + } + t.notOk(is) + t.end() + }) + }) + + t.end() +} diff --git a/node_modules/isexe/windows.js b/node_modules/isexe/windows.js new file mode 100644 index 0000000..3499673 --- /dev/null +++ b/node_modules/isexe/windows.js @@ -0,0 +1,42 @@ +module.exports = isexe +isexe.sync = sync + +var fs = require('fs') + +function checkPathExt (path, options) { + var pathext = options.pathExt !== undefined ? + options.pathExt : process.env.PATHEXT + + if (!pathext) { + return true + } + + pathext = pathext.split(';') + if (pathext.indexOf('') !== -1) { + return true + } + for (var i = 0; i < pathext.length; i++) { + var p = pathext[i].toLowerCase() + if (p && path.substr(-p.length).toLowerCase() === p) { + return true + } + } + return false +} + +function checkStat (stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false + } + return checkPathExt(path, options) +} + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, path, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), path, options) +} diff --git a/node_modules/jackspeak/LICENSE.md b/node_modules/jackspeak/LICENSE.md new file mode 100644 index 0000000..8cb5cc6 --- /dev/null +++ b/node_modules/jackspeak/LICENSE.md @@ -0,0 +1,55 @@ +# Blue Oak Model License + +Version 1.0.0 + +## Purpose + +This license gives everyone as much permission to work with +this software as possible, while protecting contributors +from liability. + +## Acceptance + +In order to receive this license, you must agree to its +rules. The rules of this license are both obligations +under that agreement and conditions to your license. +You must not do anything with this software that triggers +a rule that you cannot or will not follow. + +## Copyright + +Each contributor licenses you to do everything with this +software that would otherwise infringe that contributor's +copyright in it. + +## Notices + +You must ensure that everyone who gets a copy of +any part of this software from you, with or without +changes, also gets the text of this license or a link to +. + +## Excuse + +If anyone notifies you in writing that you have not +complied with [Notices](#notices), you can keep your +license by taking all practical steps to comply within 30 +days after the notice. If you do not do so, your license +ends immediately. + +## Patent + +Each contributor licenses you to do everything with this +software that would otherwise infringe any patent claims +they can license or become able to license. + +## Reliability + +No contributor can revoke this license. + +## No Liability + +**_As far as the law allows, this software comes as is, +without any warranty or condition, and no contributor +will be liable to anyone for any damages related to this +software or this license, under any kind of legal claim._** diff --git a/node_modules/jackspeak/README.md b/node_modules/jackspeak/README.md new file mode 100644 index 0000000..4ffea4b --- /dev/null +++ b/node_modules/jackspeak/README.md @@ -0,0 +1,357 @@ +# jackspeak + +A very strict and proper argument parser. + +Validate string, boolean, and number options, from the command +line and the environment. + +Call the `jack` method with a config object, and then chain +methods off of it. + +At the end, call the `.parse()` method, and you'll get an object +with `positionals` and `values` members. + +Any unrecognized configs or invalid values will throw an error. + +As long as you define configs using object literals, types will +be properly inferred and TypeScript will know what kinds of +things you got. + +If you give it a prefix for environment variables, then defaults +will be read from the environment, and parsed values written back +to it, so you can easily pass configs through to child processes. + +Automatically generates a `usage`/`help` banner by calling the +`.usage()` method. + +Unless otherwise noted, all methods return the object itself. + +## USAGE + +```js +import { jack } from 'jackspeak' +// this works too: +// const { jack } = require('jackspeak') + +const { positionals, values } = jack({ envPrefix: 'FOO' }) + .flag({ + asdf: { description: 'sets the asfd flag', short: 'a', default: true }, + 'no-asdf': { description: 'unsets the asdf flag', short: 'A' }, + foo: { description: 'another boolean', short: 'f' }, + }) + .optList({ + 'ip-addrs': { + description: 'addresses to ip things', + delim: ',', // defaults to '\n' + default: ['127.0.0.1'], + }, + }) + .parse([ + 'some', + 'positional', + '--ip-addrs', + '192.168.0.1', + '--ip-addrs', + '1.1.1.1', + 'args', + '--foo', // sets the foo flag + '-A', // short for --no-asdf, sets asdf flag to false + ]) + +console.log(process.env.FOO_ASDF) // '0' +console.log(process.env.FOO_FOO) // '1' +console.log(values) // { +// 'ip-addrs': ['192.168.0.1', '1.1.1.1'], +// foo: true, +// asdf: false, +// } +console.log(process.env.FOO_IP_ADDRS) // '192.168.0.1,1.1.1.1' +console.log(positionals) // ['some', 'positional', 'args'] +``` + +## `jack(options: JackOptions = {}) => Jack` + +Returns a `Jack` object that can be used to chain and add +field definitions. The other methods (apart from `validate()`, +`parse()`, and `usage()` obviously) return the same Jack object, +updated with the new types, so they can be chained together as +shown in the code examples. + +Options: + +- `allowPositionals` Defaults to true. Set to `false` to not + allow any positional arguments. + +- `envPrefix` Set to a string to write configs to and read + configs from the environment. For example, if set to `MY_APP` + then the `foo-bar` config will default based on the value of + `env.MY_APP_FOO_BAR` and will write back to that when parsed. + + Boolean values are written as `'1'` and `'0'`, and will be + treated as `true` if they're `'1'` or false otherwise. + + Number values are written with their `toString()` + representation. + + Strings are just strings. + + Any value with `multiple: true` will be represented in the + environment split by a delimiter, which defaults to `\n`. + +- `env` The place to read/write environment variables. Defaults + to `process.env`. + +- `usage` A short usage string to print at the top of the help + banner. + +- `stopAtPositional` Boolean, default false. Stop parsing opts + and flags at the first positional argument. This is useful if + you want to pass certain options to subcommands, like some + programs do, so you can stop parsing and pass the positionals + to the subcommand to parse. + +- `stopAtPositionalTest` Conditional `stopAtPositional`. Provide + a function that takes a positional argument string and returns + boolean. If it returns `true`, then parsing will stop. Useful + when _some_ subcommands should parse the rest of the command + line options, and others should not. + +### `Jack.heading(text: string, level?: 1 | 2 | 3 | 4 | 5 | 6)` + +Define a short string heading, used in the `usage()` output. + +Indentation of the heading and subsequent description/config +usage entries (up until the next heading) is set by the heading +level. + +If the first usage item defined is a heading, it is always +treated as level 1, regardless of the argument provided. + +Headings level 1 and 2 will have a line of padding underneath +them. Headings level 3 through 6 will not. + +### `Jack.description(text: string, { pre?: boolean } = {})` + +Define a long string description, used in the `usage()` output. + +If the `pre` option is set to `true`, then whitespace will not be +normalized. However, if any line is too long for the width +allotted, it will still be wrapped. + +## Option Definitions + +Configs are defined by calling the appropriate field definition +method with an object where the keys are the long option name, +and the value defines the config. + +Options: + +- `type` Only needed for the `addFields` method, as the others + set it implicitly. Can be `'string'`, `'boolean'`, or + `'number'`. +- `multiple` Only needed for the `addFields` method, as the + others set it implicitly. Set to `true` to define an array + type. This means that it can be set on the CLI multiple times, + set as an array in the `values` + and it is represented in the environment as a delimited string. +- `short` A one-character shorthand for the option. +- `description` Some words to describe what this option is and + why you'd set it. +- `hint` (Only relevant for non-boolean types) The thing to show + in the usage output, like `--option=` +- `validate` A function that returns false (or throws) if an + option value is invalid. +- `validOptions` An array of strings or numbers that define the + valid values that can be set. This is not allowed on `boolean` + (flag) options. May be used along with a `validate()` method. +- `default` A default value for the field. Note that this may be + overridden by an environment variable, if present. + +### `Jack.flag({ [option: string]: definition, ... })` + +Define one or more boolean fields. + +Boolean options may be set to `false` by using a +`--no-${optionName}` argument, which will be implicitly created +if it's not defined to be something else. + +If a boolean option named `no-${optionName}` with the same +`multiple` setting is in the configuration, then that will be +treated as a negating flag. + +### `Jack.flagList({ [option: string]: definition, ... })` + +Define one or more boolean array fields. + +### `Jack.num({ [option: string]: definition, ... })` + +Define one or more number fields. These will be set in the +environment as a stringified number, and included in the `values` +object as a number. + +### `Jack.numList({ [option: string]: definition, ... })` + +Define one or more number list fields. These will be set in the +environment as a delimited set of stringified numbers, and +included in the `values` as a number array. + +### `Jack.opt({ [option: string]: definition, ... })` + +Define one or more string option fields. + +### `Jack.optList({ [option: string]: definition, ... })` + +Define one or more string list fields. + +### `Jack.addFields({ [option: string]: definition, ... })` + +Define one or more fields of any type. Note that `type` and +`multiple` must be set explicitly on each definition when using +this method. + +## Actions + +Use these methods on a Jack object that's already had its config +fields defined. + +### `Jack.parse(args: string[] = process.argv): { positionals: string[], values: OptionsResults }` + +Parse the arguments list, write to the environment if `envPrefix` +is set, and returned the parsed values and remaining positional +arguments. + +### `Jack.validate(o: any): asserts o is OptionsResults` + +Throws an error if the object provided is not a valid result set, +for the configurations defined thusfar. + +### `Jack.usage(): string` + +Returns the compiled `usage` string, with all option descriptions +and heading/description text, wrapped to the appropriate width +for the terminal. + +### `Jack.setConfigValues(options: OptionsResults, src?: string)` + +Validate the `options` argument, and set the default value for +each field that appears in the options. + +Values provided will be overridden by environment variables or +command line arguments. + +### `Jack.usageMarkdown(): string` + +Returns the compiled `usage` string, with all option descriptions +and heading/description text, but as markdown instead of +formatted for a terminal, for generating HTML documentation for +your CLI. + +## Some Example Code + +Also see [the examples +folder](https://github.com/isaacs/jackspeak/tree/master/examples) + +```js +import { jack } from 'jackspeak' + +const j = jack({ + // Optional + // This will be auto-generated from the descriptions if not supplied + // top level usage line, printed by -h + // will be auto-generated if not specified + usage: 'foo [options] ', +}) + .heading('The best Foo that ever Fooed') + .description( + ` + Executes all the files and interprets their output as + TAP formatted test result data. + + To parse TAP data from stdin, specify "-" as a filename. + `, + ) + + // flags don't take a value, they're boolean on or off, and can be + // turned off by prefixing with `--no-` + // so this adds support for -b to mean --bail, or -B to mean --no-bail + .flag({ + flag: { + // specify a short value if you like. this must be a single char + short: 'f', + // description is optional as well. + description: `Make the flags wave`, + // default value for flags is 'false', unless you change it + default: true, + }, + 'no-flag': { + // you can can always negate a flag with `--no-flag` + // specifying a negate option will let you define a short + // single-char option for negation. + short: 'F', + description: `Do not wave the flags`, + }, + }) + + // Options that take a value are specified with `opt()` + .opt({ + reporter: { + short: 'R', + description: 'the style of report to display', + }, + }) + + // if you want a number, say so, and jackspeak will enforce it + .num({ + jobs: { + short: 'j', + description: 'how many jobs to run in parallel', + default: 1, + }, + }) + + // A list is an option that can be specified multiple times, + // to expand into an array of all the settings. Normal opts + // will just give you the last value specified. + .optList({ + 'node-arg': {}, + }) + + // a flagList is an array of booleans, so `-ddd` is [true, true, true] + // count the `true` values to treat it as a counter. + .flagList({ + debug: { short: 'd' }, + }) + + // opts take a value, and is set to the string in the results + // you can combine multiple short-form flags together, but + // an opt will end the combine chain, posix-style. So, + // -bofilename would be like --bail --output-file=filename + .opt({ + 'output-file': { + short: 'o', + // optional: make it -o in the help output insead of -o + hint: 'file', + description: `Send the raw output to the specified file.`, + }, + }) + +// now we can parse argv like this: +const { values, positionals } = j.parse(process.argv) + +// or decide to show the usage banner +console.log(j.usage()) + +// or validate an object config we got from somewhere else +try { + j.validate(someConfig) +} catch (er) { + console.error('someConfig is not valid!', er) +} +``` + +## Name + +The inspiration for this module is [yargs](http://npm.im/yargs), which +is pirate talk themed. Yargs has all the features, and is infinitely +flexible. "Jackspeak" is the slang of the royal navy. This module +does not have all the features. It is declarative and rigid by design. diff --git a/node_modules/jackspeak/dist/commonjs/index.d.ts b/node_modules/jackspeak/dist/commonjs/index.d.ts new file mode 100644 index 0000000..d28bcc1 --- /dev/null +++ b/node_modules/jackspeak/dist/commonjs/index.d.ts @@ -0,0 +1,315 @@ +/// +export type ConfigType = 'number' | 'string' | 'boolean'; +/** + * Given a Jack object, get the typeof its ConfigSet + */ +export type Unwrap = J extends Jack ? C : never; +import { inspect, InspectOptions } from 'node:util'; +/** + * Defines the type of value that is valid, given a config definition's + * {@link ConfigType} and boolean multiple setting + */ +export type ValidValue = [ + T, + M +] extends ['number', true] ? number[] : [T, M] extends ['string', true] ? string[] : [T, M] extends ['boolean', true] ? boolean[] : [T, M] extends ['number', false] ? number : [T, M] extends ['string', false] ? string : [T, M] extends ['boolean', false] ? boolean : [T, M] extends ['string', boolean] ? string | string[] : [T, M] extends ['boolean', boolean] ? boolean | boolean[] : [T, M] extends ['number', boolean] ? number | number[] : [T, M] extends [ConfigType, false] ? string | number | boolean : [T, M] extends [ConfigType, true] ? string[] | number[] | boolean[] : string | number | boolean | string[] | number[] | boolean[]; +/** + * The meta information for a config option definition, when the + * type and multiple values can be inferred by the method being used + */ +export type ConfigOptionMeta = { + default?: undefined | (ValidValue & (O extends number[] | string[] ? M extends false ? O[number] : O[number][] : unknown)); + validOptions?: O; + description?: string; + validate?: ((v: unknown) => v is ValidValue) | ((v: unknown) => boolean); + short?: string | undefined; + type?: T; + hint?: T extends 'boolean' ? never : string; + delim?: M extends true ? string : never; +} & (M extends false ? { + multiple?: false | undefined; +} : M extends true ? { + multiple: true; +} : { + multiple?: boolean; +}); +/** + * A set of {@link ConfigOptionMeta} fields, referenced by their longOption + * string values. + */ +export type ConfigMetaSet = { + [longOption: string]: ConfigOptionMeta; +}; +/** + * Infer {@link ConfigSet} fields from a given {@link ConfigMetaSet} + */ +export type ConfigSetFromMetaSet> = { + [longOption in keyof S]: ConfigOptionBase; +}; +/** + * Fields that can be set on a {@link ConfigOptionBase} or + * {@link ConfigOptionMeta} based on whether or not the field is known to be + * multiple. + */ +export type MultiType = M extends true ? { + multiple: true; + delim?: string | undefined; +} : M extends false ? { + multiple?: false | undefined; + delim?: undefined; +} : { + multiple?: boolean | undefined; + delim?: string | undefined; +}; +/** + * A config field definition, in its full representation. + */ +export type ConfigOptionBase = { + type: T; + short?: string | undefined; + default?: ValidValue | undefined; + description?: string; + hint?: T extends 'boolean' ? undefined : string | undefined; + validate?: (v: unknown) => v is ValidValue; + validOptions?: T extends 'boolean' ? undefined : T extends 'string' ? readonly string[] : T extends 'number' ? readonly number[] : readonly number[] | readonly string[]; +} & MultiType; +export declare const isConfigType: (t: string) => t is ConfigType; +export declare const isConfigOption: (o: any, type: T, multi: M) => o is ConfigOptionBase; +/** + * A set of {@link ConfigOptionBase} objects, referenced by their longOption + * string values. + */ +export type ConfigSet = { + [longOption: string]: ConfigOptionBase; +}; +/** + * The 'values' field returned by {@link Jack#parse} + */ +export type OptionsResults = { + [k in keyof T]?: T[k]['validOptions'] extends (readonly string[] | readonly number[]) ? T[k] extends ConfigOptionBase<'string' | 'number', false> ? T[k]['validOptions'][number] : T[k] extends ConfigOptionBase<'string' | 'number', true> ? T[k]['validOptions'][number][] : never : T[k] extends ConfigOptionBase<'string', false> ? string : T[k] extends ConfigOptionBase<'string', true> ? string[] : T[k] extends ConfigOptionBase<'number', false> ? number : T[k] extends ConfigOptionBase<'number', true> ? number[] : T[k] extends ConfigOptionBase<'boolean', false> ? boolean : T[k] extends ConfigOptionBase<'boolean', true> ? boolean[] : never; +}; +/** + * The object retured by {@link Jack#parse} + */ +export type Parsed = { + values: OptionsResults; + positionals: string[]; +}; +/** + * A row used when generating the {@link Jack#usage} string + */ +export interface Row { + left?: string; + text: string; + skipLine?: boolean; + type?: string; +} +/** + * A heading for a section in the usage, created by the jack.heading() + * method. + * + * First heading is always level 1, subsequent headings default to 2. + * + * The level of the nearest heading level sets the indentation of the + * description that follows. + */ +export interface Heading extends Row { + type: 'heading'; + text: string; + left?: ''; + skipLine?: boolean; + level: number; + pre?: boolean; +} +/** + * An arbitrary blob of text describing some stuff, set by the + * jack.description() method. + * + * Indentation determined by level of the nearest header. + */ +export interface Description extends Row { + type: 'description'; + text: string; + left?: ''; + skipLine?: boolean; + pre?: boolean; +} +/** + * A heading or description row used when generating the {@link Jack#usage} + * string + */ +export type TextRow = Heading | Description; +/** + * Either a {@link TextRow} or a reference to a {@link ConfigOptionBase} + */ +export type UsageField = TextRow | { + type: 'config'; + name: string; + value: ConfigOptionBase; +}; +/** + * Options provided to the {@link Jack} constructor + */ +export interface JackOptions { + /** + * Whether to allow positional arguments + * + * @default true + */ + allowPositionals?: boolean; + /** + * Prefix to use when reading/writing the environment variables + * + * If not specified, environment behavior will not be available. + */ + envPrefix?: string; + /** + * Environment object to read/write. Defaults `process.env`. + * No effect if `envPrefix` is not set. + */ + env?: { + [k: string]: string | undefined; + }; + /** + * A short usage string. If not provided, will be generated from the + * options provided, but that can of course be rather verbose if + * there are a lot of options. + */ + usage?: string; + /** + * Stop parsing flags and opts at the first positional argument. + * This is to support cases like `cmd [flags] [options]`, where + * each subcommand may have different options. This effectively treats + * any positional as a `--` argument. Only relevant if `allowPositionals` + * is true. + * + * To do subcommands, set this option, look at the first positional, and + * parse the remaining positionals as appropriate. + * + * @default false + */ + stopAtPositional?: boolean; + /** + * Conditional `stopAtPositional`. If set to a `(string)=>boolean` function, + * will be called with each positional argument encountered. If the function + * returns true, then parsing will stop at that point. + */ + stopAtPositionalTest?: (arg: string) => boolean; +} +/** + * Class returned by the {@link jack} function and all configuration + * definition methods. This is what gets chained together. + */ +export declare class Jack { + #private; + constructor(options?: JackOptions); + /** + * Set the default value (which will still be overridden by env or cli) + * as if from a parsed config file. The optional `source` param, if + * provided, will be included in error messages if a value is invalid or + * unknown. + */ + setConfigValues(values: OptionsResults, source?: string): this; + /** + * Parse a string of arguments, and return the resulting + * `{ values, positionals }` object. + * + * If an {@link JackOptions#envPrefix} is set, then it will read default + * values from the environment, and write the resulting values back + * to the environment as well. + * + * Environment values always take precedence over any other value, except + * an explicit CLI setting. + */ + parse(args?: string[]): Parsed; + loadEnvDefaults(): void; + applyDefaults(p: Parsed): void; + /** + * Only parse the command line arguments passed in. + * Does not strip off the `node script.js` bits, so it must be just the + * arguments you wish to have parsed. + * Does not read from or write to the environment, or set defaults. + */ + parseRaw(args: string[]): Parsed; + /** + * Validate that any arbitrary object is a valid configuration `values` + * object. Useful when loading config files or other sources. + */ + validate(o: unknown): asserts o is Parsed['values']; + writeEnv(p: Parsed): void; + /** + * Add a heading to the usage output banner + */ + heading(text: string, level?: 1 | 2 | 3 | 4 | 5 | 6, { pre }?: { + pre?: boolean; + }): Jack; + /** + * Add a long-form description to the usage output at this position. + */ + description(text: string, { pre }?: { + pre?: boolean; + }): Jack; + /** + * Add one or more number fields. + */ + num>(fields: F): Jack>; + /** + * Add one or more multiple number fields. + */ + numList>(fields: F): Jack>; + /** + * Add one or more string option fields. + */ + opt>(fields: F): Jack>; + /** + * Add one or more multiple string option fields. + */ + optList>(fields: F): Jack>; + /** + * Add one or more flag fields. + */ + flag>(fields: F): Jack>; + /** + * Add one or more multiple flag fields. + */ + flagList>(fields: F): Jack>; + /** + * Generic field definition method. Similar to flag/flagList/number/etc, + * but you must specify the `type` (and optionally `multiple` and `delim`) + * fields on each one, or Jack won't know how to define them. + */ + addFields(fields: F): Jack; + /** + * Return the usage banner for the given configuration + */ + usage(): string; + /** + * Return the usage banner markdown for the given configuration + */ + usageMarkdown(): string; + /** + * Return the configuration options as a plain object + */ + toJSON(): { + [k: string]: { + hint?: string | undefined; + default?: string | number | boolean | string[] | number[] | boolean[] | undefined; + validOptions?: readonly number[] | readonly string[] | undefined; + validate?: ((v: unknown) => v is string | number | boolean | string[] | number[] | boolean[]) | undefined; + description?: string | undefined; + short?: string | undefined; + delim?: string | undefined; + multiple?: boolean | undefined; + type: ConfigType; + }; + }; + /** + * Custom printer for `util.inspect` + */ + [inspect.custom](_: number, options: InspectOptions): string; +} +/** + * Main entry point. Create and return a {@link Jack} object. + */ +export declare const jack: (options?: JackOptions) => Jack<{}>; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/jackspeak/dist/commonjs/index.d.ts.map b/node_modules/jackspeak/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000..faf9ddd --- /dev/null +++ b/node_modules/jackspeak/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.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,MAAM;;;;;;;;;;;;;IAqBN;;OAEG;IACH,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc;CAGpD;AAsED;;GAEG;AACH,eAAO,MAAM,IAAI,aAAa,WAAW,aAA2B,CAAA"} \ No newline at end of file diff --git a/node_modules/jackspeak/dist/commonjs/index.js b/node_modules/jackspeak/dist/commonjs/index.js new file mode 100644 index 0000000..f7fc9cb --- /dev/null +++ b/node_modules/jackspeak/dist/commonjs/index.js @@ -0,0 +1,1010 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.jack = exports.Jack = exports.isConfigOption = exports.isConfigType = void 0; +const node_util_1 = require("node:util"); +const parse_args_js_1 = require("./parse-args.js"); +// it's a tiny API, just cast it inline, it's fine +//@ts-ignore +const cliui_1 = __importDefault(require("@isaacs/cliui")); +const node_path_1 = require("node:path"); +const width = Math.min((process && process.stdout && process.stdout.columns) || 80, 80); +// indentation spaces from heading level +const indent = (n) => (n - 1) * 2; +const toEnvKey = (pref, key) => { + return [pref, key.replace(/[^a-zA-Z0-9]+/g, ' ')] + .join(' ') + .trim() + .toUpperCase() + .replace(/ /g, '_'); +}; +const toEnvVal = (value, delim = '\n') => { + const str = typeof value === 'string' ? value + : typeof value === 'boolean' ? + value ? '1' + : '0' + : typeof value === 'number' ? String(value) + : Array.isArray(value) ? + value.map((v) => toEnvVal(v)).join(delim) + : /* c8 ignore start */ undefined; + if (typeof str !== 'string') { + throw new Error(`could not serialize value to environment: ${JSON.stringify(value)}`); + } + /* c8 ignore stop */ + return str; +}; +const fromEnvVal = (env, type, multiple, delim = '\n') => (multiple ? + env ? env.split(delim).map(v => fromEnvVal(v, type, false)) + : [] + : type === 'string' ? env + : type === 'boolean' ? env === '1' + : +env.trim()); +const isConfigType = (t) => typeof t === 'string' && + (t === 'string' || t === 'number' || t === 'boolean'); +exports.isConfigType = isConfigType; +const undefOrType = (v, t) => v === undefined || typeof v === t; +const undefOrTypeArray = (v, t) => v === undefined || (Array.isArray(v) && v.every(x => typeof x === t)); +const isValidOption = (v, vo) => Array.isArray(v) ? v.every(x => isValidOption(x, vo)) : vo.includes(v); +// print the value type, for error message reporting +const valueType = (v) => typeof v === 'string' ? 'string' + : typeof v === 'boolean' ? 'boolean' + : typeof v === 'number' ? 'number' + : Array.isArray(v) ? + joinTypes([...new Set(v.map(v => valueType(v)))]) + '[]' + : `${v.type}${v.multiple ? '[]' : ''}`; +const joinTypes = (types) => types.length === 1 && typeof types[0] === 'string' ? + types[0] + : `(${types.join('|')})`; +const isValidValue = (v, type, multi) => { + if (multi) { + if (!Array.isArray(v)) + return false; + return !v.some((v) => !isValidValue(v, type, false)); + } + if (Array.isArray(v)) + return false; + return typeof v === type; +}; +const isConfigOption = (o, type, multi) => !!o && + typeof o === 'object' && + (0, exports.isConfigType)(o.type) && + o.type === type && + undefOrType(o.short, 'string') && + undefOrType(o.description, 'string') && + undefOrType(o.hint, 'string') && + undefOrType(o.validate, 'function') && + (o.type === 'boolean' ? + o.validOptions === undefined + : undefOrTypeArray(o.validOptions, o.type)) && + (o.default === undefined || isValidValue(o.default, type, multi)) && + !!o.multiple === multi; +exports.isConfigOption = isConfigOption; +function num(o = {}) { + const { default: def, validate: val, validOptions, ...rest } = o; + if (def !== undefined && !isValidValue(def, 'number', false)) { + throw new TypeError('invalid default value', { + cause: { + found: def, + wanted: 'number', + }, + }); + } + if (!undefOrTypeArray(validOptions, 'number')) { + throw new TypeError('invalid validOptions', { + cause: { + found: validOptions, + wanted: 'number[]', + }, + }); + } + const validate = val ? + val + : undefined; + return { + ...rest, + default: def, + validate, + validOptions, + type: 'number', + multiple: false, + }; +} +function numList(o = {}) { + const { default: def, validate: val, validOptions, ...rest } = o; + if (def !== undefined && !isValidValue(def, 'number', true)) { + throw new TypeError('invalid default value', { + cause: { + found: def, + wanted: 'number[]', + }, + }); + } + if (!undefOrTypeArray(validOptions, 'number')) { + throw new TypeError('invalid validOptions', { + cause: { + found: validOptions, + wanted: 'number[]', + }, + }); + } + const validate = val ? + val + : undefined; + return { + ...rest, + default: def, + validate, + validOptions, + type: 'number', + multiple: true, + }; +} +function opt(o = {}) { + const { default: def, validate: val, validOptions, ...rest } = o; + if (def !== undefined && !isValidValue(def, 'string', false)) { + throw new TypeError('invalid default value', { + cause: { + found: def, + wanted: 'string', + }, + }); + } + if (!undefOrTypeArray(validOptions, 'string')) { + throw new TypeError('invalid validOptions', { + cause: { + found: validOptions, + wanted: 'string[]', + }, + }); + } + const validate = val ? + val + : undefined; + return { + ...rest, + default: def, + validate, + validOptions, + type: 'string', + multiple: false, + }; +} +function optList(o = {}) { + const { default: def, validate: val, validOptions, ...rest } = o; + if (def !== undefined && !isValidValue(def, 'string', true)) { + throw new TypeError('invalid default value', { + cause: { + found: def, + wanted: 'string[]', + }, + }); + } + if (!undefOrTypeArray(validOptions, 'string')) { + throw new TypeError('invalid validOptions', { + cause: { + found: validOptions, + wanted: 'string[]', + }, + }); + } + const validate = val ? + val + : undefined; + return { + ...rest, + default: def, + validate, + validOptions, + type: 'string', + multiple: true, + }; +} +function flag(o = {}) { + const { hint, default: def, validate: val, ...rest } = o; + delete rest.validOptions; + if (def !== undefined && !isValidValue(def, 'boolean', false)) { + throw new TypeError('invalid default value'); + } + const validate = val ? + val + : undefined; + if (hint !== undefined) { + throw new TypeError('cannot provide hint for flag'); + } + return { + ...rest, + default: def, + validate, + type: 'boolean', + multiple: false, + }; +} +function flagList(o = {}) { + const { hint, default: def, validate: val, ...rest } = o; + delete rest.validOptions; + if (def !== undefined && !isValidValue(def, 'boolean', true)) { + throw new TypeError('invalid default value'); + } + const validate = val ? + val + : undefined; + if (hint !== undefined) { + throw new TypeError('cannot provide hint for flag list'); + } + return { + ...rest, + default: def, + validate, + type: 'boolean', + multiple: true, + }; +} +const toParseArgsOptionsConfig = (options) => { + const c = {}; + for (const longOption in options) { + const config = options[longOption]; + /* c8 ignore start */ + if (!config) { + throw new Error('config must be an object: ' + longOption); + } + /* c8 ignore start */ + if ((0, exports.isConfigOption)(config, 'number', true)) { + c[longOption] = { + type: 'string', + multiple: true, + default: config.default?.map(c => String(c)), + }; + } + else if ((0, exports.isConfigOption)(config, 'number', false)) { + c[longOption] = { + type: 'string', + multiple: false, + default: config.default === undefined ? + undefined + : String(config.default), + }; + } + else { + const conf = config; + c[longOption] = { + type: conf.type, + multiple: !!conf.multiple, + default: conf.default, + }; + } + const clo = c[longOption]; + if (typeof config.short === 'string') { + clo.short = config.short; + } + if (config.type === 'boolean' && + !longOption.startsWith('no-') && + !options[`no-${longOption}`]) { + c[`no-${longOption}`] = { + type: 'boolean', + multiple: config.multiple, + }; + } + } + return c; +}; +const isHeading = (r) => r.type === 'heading'; +const isDescription = (r) => r.type === 'description'; +/** + * Class returned by the {@link jack} function and all configuration + * definition methods. This is what gets chained together. + */ +class Jack { + #configSet; + #shorts; + #options; + #fields = []; + #env; + #envPrefix; + #allowPositionals; + #usage; + #usageMarkdown; + constructor(options = {}) { + this.#options = options; + this.#allowPositionals = options.allowPositionals !== false; + this.#env = + this.#options.env === undefined ? process.env : this.#options.env; + this.#envPrefix = options.envPrefix; + // We need to fib a little, because it's always the same object, but it + // starts out as having an empty config set. Then each method that adds + // fields returns `this as Jack` + this.#configSet = Object.create(null); + this.#shorts = Object.create(null); + } + /** + * Set the default value (which will still be overridden by env or cli) + * as if from a parsed config file. The optional `source` param, if + * provided, will be included in error messages if a value is invalid or + * unknown. + */ + setConfigValues(values, source = '') { + try { + this.validate(values); + } + catch (er) { + const e = er; + if (source && e && typeof e === 'object') { + if (e.cause && typeof e.cause === 'object') { + Object.assign(e.cause, { path: source }); + } + else { + e.cause = { path: source }; + } + } + throw e; + } + for (const [field, value] of Object.entries(values)) { + const my = this.#configSet[field]; + // already validated, just for TS's benefit + /* c8 ignore start */ + if (!my) { + throw new Error('unexpected field in config set: ' + field, { + cause: { found: field }, + }); + } + /* c8 ignore stop */ + my.default = value; + } + return this; + } + /** + * Parse a string of arguments, and return the resulting + * `{ values, positionals }` object. + * + * If an {@link JackOptions#envPrefix} is set, then it will read default + * values from the environment, and write the resulting values back + * to the environment as well. + * + * Environment values always take precedence over any other value, except + * an explicit CLI setting. + */ + parse(args = process.argv) { + this.loadEnvDefaults(); + const p = this.parseRaw(args); + this.applyDefaults(p); + this.writeEnv(p); + return p; + } + loadEnvDefaults() { + if (this.#envPrefix) { + for (const [field, my] of Object.entries(this.#configSet)) { + const ek = toEnvKey(this.#envPrefix, field); + const env = this.#env[ek]; + if (env !== undefined) { + my.default = fromEnvVal(env, my.type, !!my.multiple, my.delim); + } + } + } + } + applyDefaults(p) { + for (const [field, c] of Object.entries(this.#configSet)) { + if (c.default !== undefined && !(field in p.values)) { + //@ts-ignore + p.values[field] = c.default; + } + } + } + /** + * Only parse the command line arguments passed in. + * Does not strip off the `node script.js` bits, so it must be just the + * arguments you wish to have parsed. + * Does not read from or write to the environment, or set defaults. + */ + parseRaw(args) { + if (args === process.argv) { + args = args.slice(process._eval !== undefined ? 1 : 2); + } + const options = toParseArgsOptionsConfig(this.#configSet); + const result = (0, parse_args_js_1.parseArgs)({ + args, + options, + // always strict, but using our own logic + strict: false, + allowPositionals: this.#allowPositionals, + tokens: true, + }); + const p = { + values: {}, + positionals: [], + }; + for (const token of result.tokens) { + if (token.kind === 'positional') { + p.positionals.push(token.value); + if (this.#options.stopAtPositional || + this.#options.stopAtPositionalTest?.(token.value)) { + p.positionals.push(...args.slice(token.index + 1)); + break; + } + } + else if (token.kind === 'option') { + let value = undefined; + if (token.name.startsWith('no-')) { + const my = this.#configSet[token.name]; + const pname = token.name.substring('no-'.length); + const pos = this.#configSet[pname]; + if (pos && + pos.type === 'boolean' && + (!my || + (my.type === 'boolean' && !!my.multiple === !!pos.multiple))) { + value = false; + token.name = pname; + } + } + const my = this.#configSet[token.name]; + if (!my) { + throw new Error(`Unknown option '${token.rawName}'. ` + + `To specify a positional argument starting with a '-', ` + + `place it at the end of the command after '--', as in ` + + `'-- ${token.rawName}'`, { + cause: { + found: token.rawName + (token.value ? `=${token.value}` : ''), + }, + }); + } + if (value === undefined) { + if (token.value === undefined) { + if (my.type !== 'boolean') { + throw new Error(`No value provided for ${token.rawName}, expected ${my.type}`, { + cause: { + name: token.rawName, + wanted: valueType(my), + }, + }); + } + value = true; + } + else { + if (my.type === 'boolean') { + throw new Error(`Flag ${token.rawName} does not take a value, received '${token.value}'`, { cause: { found: token } }); + } + if (my.type === 'string') { + value = token.value; + } + else { + value = +token.value; + if (value !== value) { + throw new Error(`Invalid value '${token.value}' provided for ` + + `'${token.rawName}' option, expected number`, { + cause: { + name: token.rawName, + found: token.value, + wanted: 'number', + }, + }); + } + } + } + } + if (my.multiple) { + const pv = p.values; + const tn = pv[token.name] ?? []; + pv[token.name] = tn; + tn.push(value); + } + else { + const pv = p.values; + pv[token.name] = value; + } + } + } + for (const [field, value] of Object.entries(p.values)) { + const valid = this.#configSet[field]?.validate; + const validOptions = this.#configSet[field]?.validOptions; + let cause; + if (validOptions && !isValidOption(value, validOptions)) { + cause = { name: field, found: value, validOptions: validOptions }; + } + if (valid && !valid(value)) { + cause = cause || { name: field, found: value }; + } + if (cause) { + throw new Error(`Invalid value provided for --${field}: ${JSON.stringify(value)}`, { cause }); + } + } + return p; + } + /** + * do not set fields as 'no-foo' if 'foo' exists and both are bools + * just set foo. + */ + #noNoFields(f, val, s = f) { + if (!f.startsWith('no-') || typeof val !== 'boolean') + return; + const yes = f.substring('no-'.length); + // recurse so we get the core config key we care about. + this.#noNoFields(yes, val, s); + if (this.#configSet[yes]?.type === 'boolean') { + throw new Error(`do not set '${s}', instead set '${yes}' as desired.`, { cause: { found: s, wanted: yes } }); + } + } + /** + * Validate that any arbitrary object is a valid configuration `values` + * object. Useful when loading config files or other sources. + */ + validate(o) { + if (!o || typeof o !== 'object') { + throw new Error('Invalid config: not an object', { + cause: { found: o }, + }); + } + const opts = o; + for (const field in o) { + const value = opts[field]; + /* c8 ignore next - for TS */ + if (value === undefined) + continue; + this.#noNoFields(field, value); + const config = this.#configSet[field]; + if (!config) { + throw new Error(`Unknown config option: ${field}`, { + cause: { found: field }, + }); + } + if (!isValidValue(value, config.type, !!config.multiple)) { + throw new Error(`Invalid value ${valueType(value)} for ${field}, expected ${valueType(config)}`, { + cause: { + name: field, + found: value, + wanted: valueType(config), + }, + }); + } + let cause; + if (config.validOptions && + !isValidOption(value, config.validOptions)) { + cause = { + name: field, + found: value, + validOptions: config.validOptions, + }; + } + if (config.validate && !config.validate(value)) { + cause = cause || { name: field, found: value }; + } + if (cause) { + throw new Error(`Invalid config value for ${field}: ${value}`, { + cause, + }); + } + } + } + writeEnv(p) { + if (!this.#env || !this.#envPrefix) + return; + for (const [field, value] of Object.entries(p.values)) { + const my = this.#configSet[field]; + this.#env[toEnvKey(this.#envPrefix, field)] = toEnvVal(value, my?.delim); + } + } + /** + * Add a heading to the usage output banner + */ + heading(text, level, { pre = false } = {}) { + if (level === undefined) { + level = this.#fields.some(r => isHeading(r)) ? 2 : 1; + } + this.#fields.push({ type: 'heading', text, level, pre }); + return this; + } + /** + * Add a long-form description to the usage output at this position. + */ + description(text, { pre } = {}) { + this.#fields.push({ type: 'description', text, pre }); + return this; + } + /** + * Add one or more number fields. + */ + num(fields) { + return this.#addFields(fields, num); + } + /** + * Add one or more multiple number fields. + */ + numList(fields) { + return this.#addFields(fields, numList); + } + /** + * Add one or more string option fields. + */ + opt(fields) { + return this.#addFields(fields, opt); + } + /** + * Add one or more multiple string option fields. + */ + optList(fields) { + return this.#addFields(fields, optList); + } + /** + * Add one or more flag fields. + */ + flag(fields) { + return this.#addFields(fields, flag); + } + /** + * Add one or more multiple flag fields. + */ + flagList(fields) { + return this.#addFields(fields, flagList); + } + /** + * Generic field definition method. Similar to flag/flagList/number/etc, + * but you must specify the `type` (and optionally `multiple` and `delim`) + * fields on each one, or Jack won't know how to define them. + */ + addFields(fields) { + const next = this; + for (const [name, field] of Object.entries(fields)) { + this.#validateName(name, field); + next.#fields.push({ + type: 'config', + name, + value: field, + }); + } + Object.assign(next.#configSet, fields); + return next; + } + #addFields(fields, fn) { + const next = this; + Object.assign(next.#configSet, Object.fromEntries(Object.entries(fields).map(([name, field]) => { + this.#validateName(name, field); + const option = fn(field); + next.#fields.push({ + type: 'config', + name, + value: option, + }); + return [name, option]; + }))); + return next; + } + #validateName(name, field) { + if (!/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(name)) { + throw new TypeError(`Invalid option name: ${name}, ` + + `must be '-' delimited ASCII alphanumeric`); + } + if (this.#configSet[name]) { + throw new TypeError(`Cannot redefine option ${field}`); + } + if (this.#shorts[name]) { + throw new TypeError(`Cannot redefine option ${name}, already ` + + `in use for ${this.#shorts[name]}`); + } + if (field.short) { + if (!/^[a-zA-Z0-9]$/.test(field.short)) { + throw new TypeError(`Invalid ${name} short option: ${field.short}, ` + + 'must be 1 ASCII alphanumeric character'); + } + if (this.#shorts[field.short]) { + throw new TypeError(`Invalid ${name} short option: ${field.short}, ` + + `already in use for ${this.#shorts[field.short]}`); + } + this.#shorts[field.short] = name; + this.#shorts[name] = name; + } + } + /** + * Return the usage banner for the given configuration + */ + usage() { + if (this.#usage) + return this.#usage; + let headingLevel = 1; + const ui = (0, cliui_1.default)({ width }); + const first = this.#fields[0]; + let start = first?.type === 'heading' ? 1 : 0; + if (first?.type === 'heading') { + ui.div({ + padding: [0, 0, 0, 0], + text: normalize(first.text), + }); + } + ui.div({ padding: [0, 0, 0, 0], text: 'Usage:' }); + if (this.#options.usage) { + ui.div({ + text: this.#options.usage, + padding: [0, 0, 0, 2], + }); + } + else { + const cmd = (0, node_path_1.basename)(String(process.argv[1])); + const shortFlags = []; + const shorts = []; + const flags = []; + const opts = []; + for (const [field, config] of Object.entries(this.#configSet)) { + if (config.short) { + if (config.type === 'boolean') + shortFlags.push(config.short); + else + shorts.push([config.short, config.hint || field]); + } + else { + if (config.type === 'boolean') + flags.push(field); + else + opts.push([field, config.hint || field]); + } + } + const sf = shortFlags.length ? ' -' + shortFlags.join('') : ''; + const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join(''); + const lf = flags.map(k => ` --${k}`).join(''); + const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join(''); + const usage = `${cmd}${sf}${so}${lf}${lo}`.trim(); + ui.div({ + text: usage, + padding: [0, 0, 0, 2], + }); + } + ui.div({ padding: [0, 0, 0, 0], text: '' }); + const maybeDesc = this.#fields[start]; + if (maybeDesc && isDescription(maybeDesc)) { + const print = normalize(maybeDesc.text, maybeDesc.pre); + start++; + ui.div({ padding: [0, 0, 0, 0], text: print }); + ui.div({ padding: [0, 0, 0, 0], text: '' }); + } + const { rows, maxWidth } = this.#usageRows(start); + // every heading/description after the first gets indented by 2 + // extra spaces. + for (const row of rows) { + if (row.left) { + // If the row is too long, don't wrap it + // Bump the right-hand side down a line to make room + const configIndent = indent(Math.max(headingLevel, 2)); + if (row.left.length > maxWidth - 3) { + ui.div({ text: row.left, padding: [0, 0, 0, configIndent] }); + ui.div({ text: row.text, padding: [0, 0, 0, maxWidth] }); + } + else { + ui.div({ + text: row.left, + padding: [0, 1, 0, configIndent], + width: maxWidth, + }, { padding: [0, 0, 0, 0], text: row.text }); + } + if (row.skipLine) { + ui.div({ padding: [0, 0, 0, 0], text: '' }); + } + } + else { + if (isHeading(row)) { + const { level } = row; + headingLevel = level; + // only h1 and h2 have bottom padding + // h3-h6 do not + const b = level <= 2 ? 1 : 0; + ui.div({ ...row, padding: [0, 0, b, indent(level)] }); + } + else { + ui.div({ ...row, padding: [0, 0, 1, indent(headingLevel + 1)] }); + } + } + } + return (this.#usage = ui.toString()); + } + /** + * Return the usage banner markdown for the given configuration + */ + usageMarkdown() { + if (this.#usageMarkdown) + return this.#usageMarkdown; + const out = []; + let headingLevel = 1; + const first = this.#fields[0]; + let start = first?.type === 'heading' ? 1 : 0; + if (first?.type === 'heading') { + out.push(`# ${normalizeOneLine(first.text)}`); + } + out.push('Usage:'); + if (this.#options.usage) { + out.push(normalizeMarkdown(this.#options.usage, true)); + } + else { + const cmd = (0, node_path_1.basename)(String(process.argv[1])); + const shortFlags = []; + const shorts = []; + const flags = []; + const opts = []; + for (const [field, config] of Object.entries(this.#configSet)) { + if (config.short) { + if (config.type === 'boolean') + shortFlags.push(config.short); + else + shorts.push([config.short, config.hint || field]); + } + else { + if (config.type === 'boolean') + flags.push(field); + else + opts.push([field, config.hint || field]); + } + } + const sf = shortFlags.length ? ' -' + shortFlags.join('') : ''; + const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join(''); + const lf = flags.map(k => ` --${k}`).join(''); + const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join(''); + const usage = `${cmd}${sf}${so}${lf}${lo}`.trim(); + out.push(normalizeMarkdown(usage, true)); + } + const maybeDesc = this.#fields[start]; + if (maybeDesc && isDescription(maybeDesc)) { + out.push(normalizeMarkdown(maybeDesc.text, maybeDesc.pre)); + start++; + } + const { rows } = this.#usageRows(start); + // heading level in markdown is number of # ahead of text + for (const row of rows) { + if (row.left) { + out.push('#'.repeat(headingLevel + 1) + + ' ' + + normalizeOneLine(row.left, true)); + if (row.text) + out.push(normalizeMarkdown(row.text)); + } + else if (isHeading(row)) { + const { level } = row; + headingLevel = level; + out.push(`${'#'.repeat(headingLevel)} ${normalizeOneLine(row.text, row.pre)}`); + } + else { + out.push(normalizeMarkdown(row.text, !!row.pre)); + } + } + return (this.#usageMarkdown = out.join('\n\n') + '\n'); + } + #usageRows(start) { + // turn each config type into a row, and figure out the width of the + // left hand indentation for the option descriptions. + let maxMax = Math.max(12, Math.min(26, Math.floor(width / 3))); + let maxWidth = 8; + let prev = undefined; + const rows = []; + for (const field of this.#fields.slice(start)) { + if (field.type !== 'config') { + if (prev?.type === 'config') + prev.skipLine = true; + prev = undefined; + field.text = normalize(field.text, !!field.pre); + rows.push(field); + continue; + } + const { value } = field; + const desc = value.description || ''; + const mult = value.multiple ? 'Can be set multiple times' : ''; + const opts = value.validOptions?.length ? + `Valid options:${value.validOptions.map(v => ` ${JSON.stringify(v)}`)}` + : ''; + const dmDelim = desc.includes('\n') ? '\n\n' : '\n'; + const extra = [opts, mult].join(dmDelim).trim(); + const text = (normalize(desc) + dmDelim + extra).trim(); + const hint = value.hint || + (value.type === 'number' ? 'n' + : value.type === 'string' ? field.name + : undefined); + const short = !value.short ? '' + : value.type === 'boolean' ? `-${value.short} ` + : `-${value.short}<${hint}> `; + const left = value.type === 'boolean' ? + `${short}--${field.name}` + : `${short}--${field.name}=<${hint}>`; + const row = { text, left, type: 'config' }; + if (text.length > width - maxMax) { + row.skipLine = true; + } + if (prev && left.length > maxMax) + prev.skipLine = true; + prev = row; + const len = left.length + 4; + if (len > maxWidth && len < maxMax) { + maxWidth = len; + } + rows.push(row); + } + return { rows, maxWidth }; + } + /** + * Return the configuration options as a plain object + */ + toJSON() { + return Object.fromEntries(Object.entries(this.#configSet).map(([field, def]) => [ + field, + { + type: def.type, + ...(def.multiple ? { multiple: true } : {}), + ...(def.delim ? { delim: def.delim } : {}), + ...(def.short ? { short: def.short } : {}), + ...(def.description ? + { description: normalize(def.description) } + : {}), + ...(def.validate ? { validate: def.validate } : {}), + ...(def.validOptions ? { validOptions: def.validOptions } : {}), + ...(def.default !== undefined ? { default: def.default } : {}), + ...(def.hint ? { hint: def.hint } : {}), + }, + ])); + } + /** + * Custom printer for `util.inspect` + */ + [node_util_1.inspect.custom](_, options) { + return `Jack ${(0, node_util_1.inspect)(this.toJSON(), options)}`; + } +} +exports.Jack = Jack; +// Unwrap and un-indent, so we can wrap description +// strings however makes them look nice in the code. +const normalize = (s, pre = false) => { + if (pre) + // prepend a ZWSP to each line so cliui doesn't strip it. + return s + .split('\n') + .map(l => `\u200b${l}`) + .join('\n'); + return s + .split(/^\s*```\s*$/gm) + .map((s, i) => { + if (i % 2 === 1) { + if (!s.trim()) { + return `\`\`\`\n\`\`\`\n`; + } + // outdent the ``` blocks, but preserve whitespace otherwise. + const split = s.split('\n'); + // throw out the \n at the start and end + split.pop(); + split.shift(); + const si = split.reduce((shortest, l) => { + /* c8 ignore next */ + const ind = l.match(/^\s*/)?.[0] ?? ''; + if (ind.length) + return Math.min(ind.length, shortest); + else + return shortest; + }, Infinity); + /* c8 ignore next */ + const i = isFinite(si) ? si : 0; + return ('\n```\n' + + split.map(s => `\u200b${s.substring(i)}`).join('\n') + + '\n```\n'); + } + return (s + // remove single line breaks, except for lists + .replace(/([^\n])\n[ \t]*([^\n])/g, (_, $1, $2) => !/^[-*]/.test($2) ? `${$1} ${$2}` : `${$1}\n${$2}`) + // normalize mid-line whitespace + .replace(/([^\n])[ \t]+([^\n])/g, '$1 $2') + // two line breaks are enough + .replace(/\n{3,}/g, '\n\n') + // remove any spaces at the start of a line + .replace(/\n[ \t]+/g, '\n') + .trim()); + }) + .join('\n'); +}; +// normalize for markdown printing, remove leading spaces on lines +const normalizeMarkdown = (s, pre = false) => { + const n = normalize(s, pre).replace(/\\/g, '\\\\'); + return pre ? + `\`\`\`\n${n.replace(/\u200b/g, '')}\n\`\`\`` + : n.replace(/\n +/g, '\n').trim(); +}; +const normalizeOneLine = (s, pre = false) => { + const n = normalize(s, pre) + .replace(/[\s\u200b]+/g, ' ') + .trim(); + return pre ? `\`${n}\`` : n; +}; +/** + * Main entry point. Create and return a {@link Jack} object. + */ +const jack = (options = {}) => new Jack(options); +exports.jack = jack; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/jackspeak/dist/commonjs/index.js.map b/node_modules/jackspeak/dist/commonjs/index.js.map new file mode 100644 index 0000000..4b2d1f6 --- /dev/null +++ b/node_modules/jackspeak/dist/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;AAOA,yCAAoE;AACpE,mDAA2C;AAE3C,kDAAkD;AAClD,YAAY;AACZ,0DAAiC;AACjC,yCAAoC;AAEpC,M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CAAC,CAAA;AAED;;GAEG;AACI,MAAM,IAAI,GAAG,CAAC,UAAuB,EAAE,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,CAAA;AAAvD,QAAA,IAAI,QAAmD","sourcesContent":["export type ConfigType = 'number' | 'string' | 'boolean'\n\n/**\n * Given a Jack object, get the typeof its ConfigSet\n */\nexport type Unwrap = J extends Jack ? C : never\n\nimport { inspect, InspectOptions, ParseArgsConfig } from 'node:util'\nimport { parseArgs } from './parse-args.js'\n\n// it's a tiny API, just cast it inline, it's fine\n//@ts-ignore\nimport cliui from '@isaacs/cliui'\nimport { basename } from 'node:path'\n\nconst width = Math.min(\n (process && process.stdout && process.stdout.columns) || 80,\n 80,\n)\n\n// indentation spaces from heading level\nconst indent = (n: number) => (n - 1) * 2\n\nconst toEnvKey = (pref: string, key: string): string => {\n return [pref, key.replace(/[^a-zA-Z0-9]+/g, ' ')]\n .join(' ')\n .trim()\n .toUpperCase()\n .replace(/ /g, '_')\n}\n\nconst toEnvVal = (\n value: string | boolean | number | string[] | boolean[] | number[],\n delim: string = '\\n',\n): string => {\n const str =\n typeof value === 'string' ? value\n : typeof value === 'boolean' ?\n value ? '1'\n : '0'\n : typeof value === 'number' ? String(value)\n : Array.isArray(value) ?\n value.map((v: string | number | boolean) => toEnvVal(v)).join(delim)\n : /* c8 ignore start */ undefined\n if (typeof str !== 'string') {\n throw new Error(\n `could not serialize value to environment: ${JSON.stringify(value)}`,\n )\n }\n /* c8 ignore stop */\n return str\n}\n\nconst fromEnvVal = (\n env: string,\n type: T,\n multiple: M,\n delim: string = '\\n',\n): ValidValue =>\n (multiple ?\n env ? env.split(delim).map(v => fromEnvVal(v, type, false))\n : []\n : type === 'string' ? env\n : type === 'boolean' ? env === '1'\n : +env.trim()) as ValidValue\n\n/**\n * Defines the type of value that is valid, given a config definition's\n * {@link ConfigType} and boolean multiple setting\n */\nexport type ValidValue<\n T extends ConfigType = ConfigType,\n M extends boolean = boolean,\n> =\n [T, M] extends ['number', true] ? number[]\n : [T, M] extends ['string', true] ? string[]\n : [T, M] extends ['boolean', true] ? boolean[]\n : [T, M] extends ['number', false] ? number\n : [T, M] extends ['string', false] ? string\n : [T, M] extends ['boolean', false] ? boolean\n : [T, M] extends ['string', boolean] ? string | string[]\n : [T, M] extends ['boolean', boolean] ? boolean | boolean[]\n : [T, M] extends ['number', boolean] ? number | number[]\n : [T, M] extends [ConfigType, false] ? string | number | boolean\n : [T, M] extends [ConfigType, true] ? string[] | number[] | boolean[]\n : string | number | boolean | string[] | number[] | boolean[]\n\n/**\n * The meta information for a config option definition, when the\n * type and multiple values can be inferred by the method being used\n */\nexport type ConfigOptionMeta<\n T extends ConfigType,\n M extends boolean = boolean,\n O extends\n | undefined\n | (T extends 'boolean' ? never\n : T extends 'string' ? readonly string[]\n : T extends 'number' ? readonly number[]\n : readonly number[] | readonly string[]) =\n | undefined\n | (T extends 'boolean' ? never\n : T extends 'string' ? readonly string[]\n : T extends 'number' ? readonly number[]\n : readonly number[] | readonly string[]),\n> = {\n default?:\n | undefined\n | (ValidValue &\n (O extends number[] | string[] ?\n M extends false ?\n O[number]\n : O[number][]\n : unknown))\n validOptions?: O\n description?: string\n validate?:\n | ((v: unknown) => v is ValidValue)\n | ((v: unknown) => boolean)\n short?: string | undefined\n type?: T\n hint?: T extends 'boolean' ? never : string\n delim?: M extends true ? string : never\n} & (M extends false ? { multiple?: false | undefined }\n: M extends true ? { multiple: true }\n: { multiple?: boolean })\n\n/**\n * A set of {@link ConfigOptionMeta} fields, referenced by their longOption\n * string values.\n */\nexport type ConfigMetaSet<\n T extends ConfigType,\n M extends boolean = boolean,\n> = {\n [longOption: string]: ConfigOptionMeta\n}\n\n/**\n * Infer {@link ConfigSet} fields from a given {@link ConfigMetaSet}\n */\nexport type ConfigSetFromMetaSet<\n T extends ConfigType,\n M extends boolean,\n S extends ConfigMetaSet,\n> = {\n [longOption in keyof S]: ConfigOptionBase\n}\n\n/**\n * Fields that can be set on a {@link ConfigOptionBase} or\n * {@link ConfigOptionMeta} based on whether or not the field is known to be\n * multiple.\n */\nexport type MultiType =\n M extends true ?\n {\n multiple: true\n delim?: string | undefined\n }\n : M extends false ?\n {\n multiple?: false | undefined\n delim?: undefined\n }\n : {\n multiple?: boolean | undefined\n delim?: string | undefined\n }\n\n/**\n * A config field definition, in its full representation.\n */\nexport type ConfigOptionBase<\n T extends ConfigType,\n M extends boolean = boolean,\n> = {\n type: T\n short?: string | undefined\n default?: ValidValue | undefined\n description?: string\n hint?: T extends 'boolean' ? undefined : string | undefined\n validate?: (v: unknown) => v is ValidValue\n validOptions?: T extends 'boolean' ? undefined\n : T extends 'string' ? readonly string[]\n : T extends 'number' ? readonly number[]\n : readonly number[] | readonly string[]\n} & MultiType\n\nexport const isConfigType = (t: string): t is ConfigType =>\n typeof t === 'string' &&\n (t === 'string' || t === 'number' || t === 'boolean')\n\nconst undefOrType = (v: unknown, t: string): boolean =>\n v === undefined || typeof v === t\nconst undefOrTypeArray = (v: unknown, t: string): boolean =>\n v === undefined || (Array.isArray(v) && v.every(x => typeof x === t))\n\nconst isValidOption = (v: unknown, vo: readonly unknown[]): boolean =>\n Array.isArray(v) ? v.every(x => isValidOption(x, vo)) : vo.includes(v)\n\n// print the value type, for error message reporting\nconst valueType = (\n v:\n | string\n | number\n | boolean\n | string[]\n | number[]\n | boolean[]\n | { type: ConfigType; multiple?: boolean },\n): string =>\n typeof v === 'string' ? 'string'\n : typeof v === 'boolean' ? 'boolean'\n : typeof v === 'number' ? 'number'\n : Array.isArray(v) ?\n joinTypes([...new Set(v.map(v => valueType(v)))]) + '[]'\n : `${v.type}${v.multiple ? '[]' : ''}`\n\nconst joinTypes = (types: string[]): string =>\n types.length === 1 && typeof types[0] === 'string' ?\n types[0]\n : `(${types.join('|')})`\n\nconst isValidValue = (\n v: unknown,\n type: T,\n multi: M,\n): v is ValidValue => {\n if (multi) {\n if (!Array.isArray(v)) return false\n return !v.some((v: unknown) => !isValidValue(v, type, false))\n }\n if (Array.isArray(v)) return false\n return typeof v === type\n}\n\nexport const isConfigOption = (\n o: any,\n type: T,\n multi: M,\n): o is ConfigOptionBase =>\n !!o &&\n typeof o === 'object' &&\n isConfigType(o.type) &&\n o.type === type &&\n undefOrType(o.short, 'string') &&\n undefOrType(o.description, 'string') &&\n undefOrType(o.hint, 'string') &&\n undefOrType(o.validate, 'function') &&\n (o.type === 'boolean' ?\n o.validOptions === undefined\n : undefOrTypeArray(o.validOptions, o.type)) &&\n (o.default === undefined || isValidValue(o.default, type, multi)) &&\n !!o.multiple === multi\n\n/**\n * A set of {@link ConfigOptionBase} objects, referenced by their longOption\n * string values.\n */\nexport type ConfigSet = {\n [longOption: string]: ConfigOptionBase\n}\n\n/**\n * The 'values' field returned by {@link Jack#parse}\n */\nexport type OptionsResults = {\n [k in keyof T]?: T[k]['validOptions'] extends (\n readonly string[] | readonly number[]\n ) ?\n T[k] extends ConfigOptionBase<'string' | 'number', false> ?\n T[k]['validOptions'][number]\n : T[k] extends ConfigOptionBase<'string' | 'number', true> ?\n T[k]['validOptions'][number][]\n : never\n : T[k] extends ConfigOptionBase<'string', false> ? string\n : T[k] extends ConfigOptionBase<'string', true> ? string[]\n : T[k] extends ConfigOptionBase<'number', false> ? number\n : T[k] extends ConfigOptionBase<'number', true> ? number[]\n : T[k] extends ConfigOptionBase<'boolean', false> ? boolean\n : T[k] extends ConfigOptionBase<'boolean', true> ? boolean[]\n : never\n}\n\n/**\n * The object retured by {@link Jack#parse}\n */\nexport type Parsed = {\n values: OptionsResults\n positionals: string[]\n}\n\nfunction num(\n o: ConfigOptionMeta<'number', false> = {},\n): ConfigOptionBase<'number', false> {\n const { default: def, validate: val, validOptions, ...rest } = o\n if (def !== undefined && !isValidValue(def, 'number', false)) {\n throw new TypeError('invalid default value', {\n cause: {\n found: def,\n wanted: 'number',\n },\n })\n }\n if (!undefOrTypeArray(validOptions, 'number')) {\n throw new TypeError('invalid validOptions', {\n cause: {\n found: validOptions,\n wanted: 'number[]',\n },\n })\n }\n const validate =\n val ?\n (val as (v: unknown) => v is ValidValue<'number', false>)\n : undefined\n return {\n ...rest,\n default: def,\n validate,\n validOptions,\n type: 'number',\n multiple: false,\n }\n}\n\nfunction numList(\n o: ConfigOptionMeta<'number'> = {},\n): ConfigOptionBase<'number', true> {\n const { default: def, validate: val, validOptions, ...rest } = o\n if (def !== undefined && !isValidValue(def, 'number', true)) {\n throw new TypeError('invalid default value', {\n cause: {\n found: def,\n wanted: 'number[]',\n },\n })\n }\n if (!undefOrTypeArray(validOptions, 'number')) {\n throw new TypeError('invalid validOptions', {\n cause: {\n found: validOptions,\n wanted: 'number[]',\n },\n })\n }\n const validate =\n val ?\n (val as (v: unknown) => v is ValidValue<'number', true>)\n : undefined\n return {\n ...rest,\n default: def,\n validate,\n validOptions,\n type: 'number',\n multiple: true,\n }\n}\n\nfunction opt(\n o: ConfigOptionMeta<'string', false> = {},\n): ConfigOptionBase<'string', false> {\n const { default: def, validate: val, validOptions, ...rest } = o\n if (def !== undefined && !isValidValue(def, 'string', false)) {\n throw new TypeError('invalid default value', {\n cause: {\n found: def,\n wanted: 'string',\n },\n })\n }\n if (!undefOrTypeArray(validOptions, 'string')) {\n throw new TypeError('invalid validOptions', {\n cause: {\n found: validOptions,\n wanted: 'string[]',\n },\n })\n }\n const validate =\n val ?\n (val as (v: unknown) => v is ValidValue<'string', false>)\n : undefined\n return {\n ...rest,\n default: def,\n validate,\n validOptions,\n type: 'string',\n multiple: false,\n }\n}\n\nfunction optList(\n o: ConfigOptionMeta<'string'> = {},\n): ConfigOptionBase<'string', true> {\n const { default: def, validate: val, validOptions, ...rest } = o\n if (def !== undefined && !isValidValue(def, 'string', true)) {\n throw new TypeError('invalid default value', {\n cause: {\n found: def,\n wanted: 'string[]',\n },\n })\n }\n if (!undefOrTypeArray(validOptions, 'string')) {\n throw new TypeError('invalid validOptions', {\n cause: {\n found: validOptions,\n wanted: 'string[]',\n },\n })\n }\n const validate =\n val ?\n (val as (v: unknown) => v is ValidValue<'string', true>)\n : undefined\n return {\n ...rest,\n default: def,\n validate,\n validOptions,\n type: 'string',\n multiple: true,\n }\n}\n\nfunction flag(\n o: ConfigOptionMeta<'boolean', false> = {},\n): ConfigOptionBase<'boolean', false> {\n const {\n hint,\n default: def,\n validate: val,\n ...rest\n } = o as ConfigOptionMeta<'boolean', false>\n delete (rest as ConfigOptionMeta<'string', false>).validOptions\n if (def !== undefined && !isValidValue(def, 'boolean', false)) {\n throw new TypeError('invalid default value')\n }\n const validate =\n val ?\n (val as (v: unknown) => v is ValidValue<'boolean', false>)\n : undefined\n if (hint !== undefined) {\n throw new TypeError('cannot provide hint for flag')\n }\n return {\n ...rest,\n default: def,\n validate,\n type: 'boolean',\n multiple: false,\n }\n}\n\nfunction flagList(\n o: ConfigOptionMeta<'boolean'> = {},\n): ConfigOptionBase<'boolean', true> {\n const {\n hint,\n default: def,\n validate: val,\n ...rest\n } = o as ConfigOptionMeta<'boolean', false>\n delete (rest as ConfigOptionMeta<'string', false>).validOptions\n if (def !== undefined && !isValidValue(def, 'boolean', true)) {\n throw new TypeError('invalid default value')\n }\n const validate =\n val ?\n (val as (v: unknown) => v is ValidValue<'boolean', true>)\n : undefined\n if (hint !== undefined) {\n throw new TypeError('cannot provide hint for flag list')\n }\n return {\n ...rest,\n default: def,\n validate,\n type: 'boolean',\n multiple: true,\n }\n}\nconst toParseArgsOptionsConfig = (\n options: ConfigSet,\n): Exclude => {\n const c: Exclude = {}\n for (const longOption in options) {\n const config = options[longOption]\n /* c8 ignore start */\n if (!config) {\n throw new Error('config must be an object: ' + longOption)\n }\n /* c8 ignore start */\n if (isConfigOption(config, 'number', true)) {\n c[longOption] = {\n type: 'string',\n multiple: true,\n default: config.default?.map(c => String(c)),\n }\n } else if (isConfigOption(config, 'number', false)) {\n c[longOption] = {\n type: 'string',\n multiple: false,\n default:\n config.default === undefined ?\n undefined\n : String(config.default),\n }\n } else {\n const conf = config as\n | ConfigOptionBase<'string'>\n | ConfigOptionBase<'boolean'>\n c[longOption] = {\n type: conf.type,\n multiple: !!conf.multiple,\n default: conf.default,\n }\n }\n const clo = c[longOption] as ConfigOptionBase\n if (typeof config.short === 'string') {\n clo.short = config.short\n }\n\n if (\n config.type === 'boolean' &&\n !longOption.startsWith('no-') &&\n !options[`no-${longOption}`]\n ) {\n c[`no-${longOption}`] = {\n type: 'boolean',\n multiple: config.multiple,\n }\n }\n }\n return c\n}\n\n/**\n * A row used when generating the {@link Jack#usage} string\n */\nexport interface Row {\n left?: string\n text: string\n skipLine?: boolean\n type?: string\n}\n\n/**\n * A heading for a section in the usage, created by the jack.heading()\n * method.\n *\n * First heading is always level 1, subsequent headings default to 2.\n *\n * The level of the nearest heading level sets the indentation of the\n * description that follows.\n */\nexport interface Heading extends Row {\n type: 'heading'\n text: string\n left?: ''\n skipLine?: boolean\n level: number\n pre?: boolean\n}\nconst isHeading = (r: { type?: string }): r is Heading =>\n r.type === 'heading'\n\n/**\n * An arbitrary blob of text describing some stuff, set by the\n * jack.description() method.\n *\n * Indentation determined by level of the nearest header.\n */\nexport interface Description extends Row {\n type: 'description'\n text: string\n left?: ''\n skipLine?: boolean\n pre?: boolean\n}\n\nconst isDescription = (r: { type?: string }): r is Description =>\n r.type === 'description'\n\n/**\n * A heading or description row used when generating the {@link Jack#usage}\n * string\n */\nexport type TextRow = Heading | Description\n\n/**\n * Either a {@link TextRow} or a reference to a {@link ConfigOptionBase}\n */\nexport type UsageField =\n | TextRow\n | {\n type: 'config'\n name: string\n value: ConfigOptionBase\n }\n\n/**\n * Options provided to the {@link Jack} constructor\n */\nexport interface JackOptions {\n /**\n * Whether to allow positional arguments\n *\n * @default true\n */\n allowPositionals?: boolean\n\n /**\n * Prefix to use when reading/writing the environment variables\n *\n * If not specified, environment behavior will not be available.\n */\n envPrefix?: string\n\n /**\n * Environment object to read/write. Defaults `process.env`.\n * No effect if `envPrefix` is not set.\n */\n env?: { [k: string]: string | undefined }\n\n /**\n * A short usage string. If not provided, will be generated from the\n * options provided, but that can of course be rather verbose if\n * there are a lot of options.\n */\n usage?: string\n\n /**\n * Stop parsing flags and opts at the first positional argument.\n * This is to support cases like `cmd [flags] [options]`, where\n * each subcommand may have different options. This effectively treats\n * any positional as a `--` argument. Only relevant if `allowPositionals`\n * is true.\n *\n * To do subcommands, set this option, look at the first positional, and\n * parse the remaining positionals as appropriate.\n *\n * @default false\n */\n stopAtPositional?: boolean\n\n /**\n * Conditional `stopAtPositional`. If set to a `(string)=>boolean` function,\n * will be called with each positional argument encountered. If the function\n * returns true, then parsing will stop at that point.\n */\n stopAtPositionalTest?: (arg: string) => boolean\n}\n\n/**\n * Class returned by the {@link jack} function and all configuration\n * definition methods. This is what gets chained together.\n */\nexport class Jack {\n #configSet: C\n #shorts: { [k: string]: string }\n #options: JackOptions\n #fields: UsageField[] = []\n #env: { [k: string]: string | undefined }\n #envPrefix?: string\n #allowPositionals: boolean\n #usage?: string\n #usageMarkdown?: string\n\n constructor(options: JackOptions = {}) {\n this.#options = options\n this.#allowPositionals = options.allowPositionals !== false\n this.#env =\n this.#options.env === undefined ? process.env : this.#options.env\n this.#envPrefix = options.envPrefix\n // We need to fib a little, because it's always the same object, but it\n // starts out as having an empty config set. Then each method that adds\n // fields returns `this as Jack`\n this.#configSet = Object.create(null) as C\n this.#shorts = Object.create(null)\n }\n\n /**\n * Set the default value (which will still be overridden by env or cli)\n * as if from a parsed config file. The optional `source` param, if\n * provided, will be included in error messages if a value is invalid or\n * unknown.\n */\n setConfigValues(values: OptionsResults, source = '') {\n try {\n this.validate(values)\n } catch (er) {\n const e = er as Error\n if (source && e && typeof e === 'object') {\n if (e.cause && typeof e.cause === 'object') {\n Object.assign(e.cause, { path: source })\n } else {\n e.cause = { path: source }\n }\n }\n throw e\n }\n for (const [field, value] of Object.entries(values)) {\n const my = this.#configSet[field]\n // already validated, just for TS's benefit\n /* c8 ignore start */\n if (!my) {\n throw new Error('unexpected field in config set: ' + field, {\n cause: { found: field },\n })\n }\n /* c8 ignore stop */\n my.default = value\n }\n return this\n }\n\n /**\n * Parse a string of arguments, and return the resulting\n * `{ values, positionals }` object.\n *\n * If an {@link JackOptions#envPrefix} is set, then it will read default\n * values from the environment, and write the resulting values back\n * to the environment as well.\n *\n * Environment values always take precedence over any other value, except\n * an explicit CLI setting.\n */\n parse(args: string[] = process.argv): Parsed {\n this.loadEnvDefaults()\n const p = this.parseRaw(args)\n this.applyDefaults(p)\n this.writeEnv(p)\n return p\n }\n\n loadEnvDefaults() {\n if (this.#envPrefix) {\n for (const [field, my] of Object.entries(this.#configSet)) {\n const ek = toEnvKey(this.#envPrefix, field)\n const env = this.#env[ek]\n if (env !== undefined) {\n my.default = fromEnvVal(env, my.type, !!my.multiple, my.delim)\n }\n }\n }\n }\n\n applyDefaults(p: Parsed) {\n for (const [field, c] of Object.entries(this.#configSet)) {\n if (c.default !== undefined && !(field in p.values)) {\n //@ts-ignore\n p.values[field] = c.default\n }\n }\n }\n\n /**\n * Only parse the command line arguments passed in.\n * Does not strip off the `node script.js` bits, so it must be just the\n * arguments you wish to have parsed.\n * Does not read from or write to the environment, or set defaults.\n */\n parseRaw(args: string[]): Parsed {\n if (args === process.argv) {\n args = args.slice(\n (process as { _eval?: string })._eval !== undefined ? 1 : 2,\n )\n }\n\n const options = toParseArgsOptionsConfig(this.#configSet)\n const result = parseArgs({\n args,\n options,\n // always strict, but using our own logic\n strict: false,\n allowPositionals: this.#allowPositionals,\n tokens: true,\n })\n\n const p: Parsed = {\n values: {},\n positionals: [],\n }\n for (const token of result.tokens) {\n if (token.kind === 'positional') {\n p.positionals.push(token.value)\n if (\n this.#options.stopAtPositional ||\n this.#options.stopAtPositionalTest?.(token.value)\n ) {\n p.positionals.push(...args.slice(token.index + 1))\n break\n }\n } else if (token.kind === 'option') {\n let value: string | number | boolean | undefined = undefined\n if (token.name.startsWith('no-')) {\n const my = this.#configSet[token.name]\n const pname = token.name.substring('no-'.length)\n const pos = this.#configSet[pname]\n if (\n pos &&\n pos.type === 'boolean' &&\n (!my ||\n (my.type === 'boolean' && !!my.multiple === !!pos.multiple))\n ) {\n value = false\n token.name = pname\n }\n }\n const my = this.#configSet[token.name]\n if (!my) {\n throw new Error(\n `Unknown option '${token.rawName}'. ` +\n `To specify a positional argument starting with a '-', ` +\n `place it at the end of the command after '--', as in ` +\n `'-- ${token.rawName}'`,\n {\n cause: {\n found:\n token.rawName + (token.value ? `=${token.value}` : ''),\n },\n },\n )\n }\n if (value === undefined) {\n if (token.value === undefined) {\n if (my.type !== 'boolean') {\n throw new Error(\n `No value provided for ${token.rawName}, expected ${my.type}`,\n {\n cause: {\n name: token.rawName,\n wanted: valueType(my),\n },\n },\n )\n }\n value = true\n } else {\n if (my.type === 'boolean') {\n throw new Error(\n `Flag ${token.rawName} does not take a value, received '${token.value}'`,\n { cause: { found: token } },\n )\n }\n if (my.type === 'string') {\n value = token.value\n } else {\n value = +token.value\n if (value !== value) {\n throw new Error(\n `Invalid value '${token.value}' provided for ` +\n `'${token.rawName}' option, expected number`,\n {\n cause: {\n name: token.rawName,\n found: token.value,\n wanted: 'number',\n },\n },\n )\n }\n }\n }\n }\n if (my.multiple) {\n const pv = p.values as {\n [k: string]: (string | number | boolean)[]\n }\n const tn = pv[token.name] ?? []\n pv[token.name] = tn\n tn.push(value)\n } else {\n const pv = p.values as { [k: string]: string | number | boolean }\n pv[token.name] = value\n }\n }\n }\n\n for (const [field, value] of Object.entries(p.values)) {\n const valid = this.#configSet[field]?.validate\n const validOptions = this.#configSet[field]?.validOptions\n let cause:\n | undefined\n | {\n name: string\n found: unknown\n validOptions?: readonly string[] | readonly number[]\n }\n if (validOptions && !isValidOption(value, validOptions)) {\n cause = { name: field, found: value, validOptions: validOptions }\n }\n if (valid && !valid(value)) {\n cause = cause || { name: field, found: value }\n }\n if (cause) {\n throw new Error(\n `Invalid value provided for --${field}: ${JSON.stringify(\n value,\n )}`,\n { cause },\n )\n }\n }\n\n return p\n }\n\n /**\n * do not set fields as 'no-foo' if 'foo' exists and both are bools\n * just set foo.\n */\n #noNoFields(f: string, val: unknown, s: string = f) {\n if (!f.startsWith('no-') || typeof val !== 'boolean') return\n const yes = f.substring('no-'.length)\n // recurse so we get the core config key we care about.\n this.#noNoFields(yes, val, s)\n if (this.#configSet[yes]?.type === 'boolean') {\n throw new Error(\n `do not set '${s}', instead set '${yes}' as desired.`,\n { cause: { found: s, wanted: yes } },\n )\n }\n }\n\n /**\n * Validate that any arbitrary object is a valid configuration `values`\n * object. Useful when loading config files or other sources.\n */\n validate(o: unknown): asserts o is Parsed['values'] {\n if (!o || typeof o !== 'object') {\n throw new Error('Invalid config: not an object', {\n cause: { found: o },\n })\n }\n const opts = o as Record\n for (const field in o) {\n const value = opts[field]\n /* c8 ignore next - for TS */\n if (value === undefined) continue\n this.#noNoFields(field, value)\n const config = this.#configSet[field]\n if (!config) {\n throw new Error(`Unknown config option: ${field}`, {\n cause: { found: field },\n })\n }\n if (!isValidValue(value, config.type, !!config.multiple)) {\n throw new Error(\n `Invalid value ${valueType(\n value,\n )} for ${field}, expected ${valueType(config)}`,\n {\n cause: {\n name: field,\n found: value,\n wanted: valueType(config),\n },\n },\n )\n }\n let cause:\n | undefined\n | {\n name: string\n found: any\n validOptions?: readonly string[] | readonly number[]\n }\n if (\n config.validOptions &&\n !isValidOption(value, config.validOptions)\n ) {\n cause = {\n name: field,\n found: value,\n validOptions: config.validOptions,\n }\n }\n if (config.validate && !config.validate(value)) {\n cause = cause || { name: field, found: value }\n }\n if (cause) {\n throw new Error(`Invalid config value for ${field}: ${value}`, {\n cause,\n })\n }\n }\n }\n\n writeEnv(p: Parsed) {\n if (!this.#env || !this.#envPrefix) return\n for (const [field, value] of Object.entries(p.values)) {\n const my = this.#configSet[field]\n this.#env[toEnvKey(this.#envPrefix, field)] = toEnvVal(\n value,\n my?.delim,\n )\n }\n }\n\n /**\n * Add a heading to the usage output banner\n */\n heading(\n text: string,\n level?: 1 | 2 | 3 | 4 | 5 | 6,\n { pre = false }: { pre?: boolean } = {},\n ): Jack {\n if (level === undefined) {\n level = this.#fields.some(r => isHeading(r)) ? 2 : 1\n }\n this.#fields.push({ type: 'heading', text, level, pre })\n return this\n }\n\n /**\n * Add a long-form description to the usage output at this position.\n */\n description(text: string, { pre }: { pre?: boolean } = {}): Jack {\n this.#fields.push({ type: 'description', text, pre })\n return this\n }\n\n /**\n * Add one or more number fields.\n */\n num>(\n fields: F,\n ): Jack> {\n return this.#addFields(fields, num)\n }\n\n /**\n * Add one or more multiple number fields.\n */\n numList>(\n fields: F,\n ): Jack> {\n return this.#addFields(fields, numList)\n }\n\n /**\n * Add one or more string option fields.\n */\n opt>(\n fields: F,\n ): Jack> {\n return this.#addFields(fields, opt)\n }\n\n /**\n * Add one or more multiple string option fields.\n */\n optList>(\n fields: F,\n ): Jack> {\n return this.#addFields(fields, optList)\n }\n\n /**\n * Add one or more flag fields.\n */\n flag>(\n fields: F,\n ): Jack> {\n return this.#addFields(fields, flag)\n }\n\n /**\n * Add one or more multiple flag fields.\n */\n flagList>(\n fields: F,\n ): Jack> {\n return this.#addFields(fields, flagList)\n }\n\n /**\n * Generic field definition method. Similar to flag/flagList/number/etc,\n * but you must specify the `type` (and optionally `multiple` and `delim`)\n * fields on each one, or Jack won't know how to define them.\n */\n addFields(fields: F): Jack {\n const next = this as unknown as Jack\n for (const [name, field] of Object.entries(fields)) {\n this.#validateName(name, field)\n next.#fields.push({\n type: 'config',\n name,\n value: field as ConfigOptionBase,\n })\n }\n Object.assign(next.#configSet, fields)\n return next\n }\n\n #addFields<\n T extends ConfigType,\n M extends boolean,\n F extends ConfigMetaSet,\n >(\n fields: F,\n fn: (m: ConfigOptionMeta) => ConfigOptionBase,\n ): Jack> {\n type NextC = C & ConfigSetFromMetaSet\n const next = this as unknown as Jack\n Object.assign(\n next.#configSet,\n Object.fromEntries(\n Object.entries(fields).map(([name, field]) => {\n this.#validateName(name, field)\n const option = fn(field)\n next.#fields.push({\n type: 'config',\n name,\n value: option as ConfigOptionBase,\n })\n return [name, option]\n }),\n ),\n )\n return next\n }\n\n #validateName(name: string, field: { short?: string }) {\n if (!/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(name)) {\n throw new TypeError(\n `Invalid option name: ${name}, ` +\n `must be '-' delimited ASCII alphanumeric`,\n )\n }\n if (this.#configSet[name]) {\n throw new TypeError(`Cannot redefine option ${field}`)\n }\n if (this.#shorts[name]) {\n throw new TypeError(\n `Cannot redefine option ${name}, already ` +\n `in use for ${this.#shorts[name]}`,\n )\n }\n if (field.short) {\n if (!/^[a-zA-Z0-9]$/.test(field.short)) {\n throw new TypeError(\n `Invalid ${name} short option: ${field.short}, ` +\n 'must be 1 ASCII alphanumeric character',\n )\n }\n if (this.#shorts[field.short]) {\n throw new TypeError(\n `Invalid ${name} short option: ${field.short}, ` +\n `already in use for ${this.#shorts[field.short]}`,\n )\n }\n this.#shorts[field.short] = name\n this.#shorts[name] = name\n }\n }\n\n /**\n * Return the usage banner for the given configuration\n */\n usage(): string {\n if (this.#usage) return this.#usage\n\n let headingLevel = 1\n const ui = cliui({ width })\n const first = this.#fields[0]\n let start = first?.type === 'heading' ? 1 : 0\n if (first?.type === 'heading') {\n ui.div({\n padding: [0, 0, 0, 0],\n text: normalize(first.text),\n })\n }\n ui.div({ padding: [0, 0, 0, 0], text: 'Usage:' })\n if (this.#options.usage) {\n ui.div({\n text: this.#options.usage,\n padding: [0, 0, 0, 2],\n })\n } else {\n const cmd = basename(String(process.argv[1]))\n const shortFlags: string[] = []\n const shorts: string[][] = []\n const flags: string[] = []\n const opts: string[][] = []\n for (const [field, config] of Object.entries(this.#configSet)) {\n if (config.short) {\n if (config.type === 'boolean') shortFlags.push(config.short)\n else shorts.push([config.short, config.hint || field])\n } else {\n if (config.type === 'boolean') flags.push(field)\n else opts.push([field, config.hint || field])\n }\n }\n const sf = shortFlags.length ? ' -' + shortFlags.join('') : ''\n const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join('')\n const lf = flags.map(k => ` --${k}`).join('')\n const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join('')\n const usage = `${cmd}${sf}${so}${lf}${lo}`.trim()\n ui.div({\n text: usage,\n padding: [0, 0, 0, 2],\n })\n }\n\n ui.div({ padding: [0, 0, 0, 0], text: '' })\n const maybeDesc = this.#fields[start]\n if (maybeDesc && isDescription(maybeDesc)) {\n const print = normalize(maybeDesc.text, maybeDesc.pre)\n start++\n ui.div({ padding: [0, 0, 0, 0], text: print })\n ui.div({ padding: [0, 0, 0, 0], text: '' })\n }\n\n const { rows, maxWidth } = this.#usageRows(start)\n\n // every heading/description after the first gets indented by 2\n // extra spaces.\n for (const row of rows) {\n if (row.left) {\n // If the row is too long, don't wrap it\n // Bump the right-hand side down a line to make room\n const configIndent = indent(Math.max(headingLevel, 2))\n if (row.left.length > maxWidth - 3) {\n ui.div({ text: row.left, padding: [0, 0, 0, configIndent] })\n ui.div({ text: row.text, padding: [0, 0, 0, maxWidth] })\n } else {\n ui.div(\n {\n text: row.left,\n padding: [0, 1, 0, configIndent],\n width: maxWidth,\n },\n { padding: [0, 0, 0, 0], text: row.text },\n )\n }\n if (row.skipLine) {\n ui.div({ padding: [0, 0, 0, 0], text: '' })\n }\n } else {\n if (isHeading(row)) {\n const { level } = row\n headingLevel = level\n // only h1 and h2 have bottom padding\n // h3-h6 do not\n const b = level <= 2 ? 1 : 0\n ui.div({ ...row, padding: [0, 0, b, indent(level)] })\n } else {\n ui.div({ ...row, padding: [0, 0, 1, indent(headingLevel + 1)] })\n }\n }\n }\n\n return (this.#usage = ui.toString())\n }\n\n /**\n * Return the usage banner markdown for the given configuration\n */\n usageMarkdown(): string {\n if (this.#usageMarkdown) return this.#usageMarkdown\n\n const out: string[] = []\n\n let headingLevel = 1\n const first = this.#fields[0]\n let start = first?.type === 'heading' ? 1 : 0\n if (first?.type === 'heading') {\n out.push(`# ${normalizeOneLine(first.text)}`)\n }\n out.push('Usage:')\n if (this.#options.usage) {\n out.push(normalizeMarkdown(this.#options.usage, true))\n } else {\n const cmd = basename(String(process.argv[1]))\n const shortFlags: string[] = []\n const shorts: string[][] = []\n const flags: string[] = []\n const opts: string[][] = []\n for (const [field, config] of Object.entries(this.#configSet)) {\n if (config.short) {\n if (config.type === 'boolean') shortFlags.push(config.short)\n else shorts.push([config.short, config.hint || field])\n } else {\n if (config.type === 'boolean') flags.push(field)\n else opts.push([field, config.hint || field])\n }\n }\n const sf = shortFlags.length ? ' -' + shortFlags.join('') : ''\n const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join('')\n const lf = flags.map(k => ` --${k}`).join('')\n const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join('')\n const usage = `${cmd}${sf}${so}${lf}${lo}`.trim()\n out.push(normalizeMarkdown(usage, true))\n }\n\n const maybeDesc = this.#fields[start]\n if (maybeDesc && isDescription(maybeDesc)) {\n out.push(normalizeMarkdown(maybeDesc.text, maybeDesc.pre))\n start++\n }\n\n const { rows } = this.#usageRows(start)\n\n // heading level in markdown is number of # ahead of text\n for (const row of rows) {\n if (row.left) {\n out.push(\n '#'.repeat(headingLevel + 1) +\n ' ' +\n normalizeOneLine(row.left, true),\n )\n if (row.text) out.push(normalizeMarkdown(row.text))\n } else if (isHeading(row)) {\n const { level } = row\n headingLevel = level\n out.push(\n `${'#'.repeat(headingLevel)} ${normalizeOneLine(\n row.text,\n row.pre,\n )}`,\n )\n } else {\n out.push(normalizeMarkdown(row.text, !!(row as Description).pre))\n }\n }\n\n return (this.#usageMarkdown = out.join('\\n\\n') + '\\n')\n }\n\n #usageRows(start: number) {\n // turn each config type into a row, and figure out the width of the\n // left hand indentation for the option descriptions.\n let maxMax = Math.max(12, Math.min(26, Math.floor(width / 3)))\n let maxWidth = 8\n let prev: Row | TextRow | undefined = undefined\n const rows: (Row | TextRow)[] = []\n for (const field of this.#fields.slice(start)) {\n if (field.type !== 'config') {\n if (prev?.type === 'config') prev.skipLine = true\n prev = undefined\n field.text = normalize(field.text, !!field.pre)\n rows.push(field)\n continue\n }\n const { value } = field\n const desc = value.description || ''\n const mult = value.multiple ? 'Can be set multiple times' : ''\n const opts =\n value.validOptions?.length ?\n `Valid options:${value.validOptions.map(\n v => ` ${JSON.stringify(v)}`,\n )}`\n : ''\n const dmDelim = desc.includes('\\n') ? '\\n\\n' : '\\n'\n const extra = [opts, mult].join(dmDelim).trim()\n const text = (normalize(desc) + dmDelim + extra).trim()\n const hint =\n value.hint ||\n (value.type === 'number' ? 'n'\n : value.type === 'string' ? field.name\n : undefined)\n const short =\n !value.short ? ''\n : value.type === 'boolean' ? `-${value.short} `\n : `-${value.short}<${hint}> `\n const left =\n value.type === 'boolean' ?\n `${short}--${field.name}`\n : `${short}--${field.name}=<${hint}>`\n const row: Row = { text, left, type: 'config' }\n if (text.length > width - maxMax) {\n row.skipLine = true\n }\n if (prev && left.length > maxMax) prev.skipLine = true\n prev = row\n const len = left.length + 4\n if (len > maxWidth && len < maxMax) {\n maxWidth = len\n }\n\n rows.push(row)\n }\n\n return { rows, maxWidth }\n }\n\n /**\n * Return the configuration options as a plain object\n */\n toJSON() {\n return Object.fromEntries(\n Object.entries(this.#configSet).map(([field, def]) => [\n field,\n {\n type: def.type,\n ...(def.multiple ? { multiple: true } : {}),\n ...(def.delim ? { delim: def.delim } : {}),\n ...(def.short ? { short: def.short } : {}),\n ...(def.description ?\n { description: normalize(def.description) }\n : {}),\n ...(def.validate ? { validate: def.validate } : {}),\n ...(def.validOptions ? { validOptions: def.validOptions } : {}),\n ...(def.default !== undefined ? { default: def.default } : {}),\n ...(def.hint ? { hint: def.hint } : {}),\n },\n ]),\n )\n }\n\n /**\n * Custom printer for `util.inspect`\n */\n [inspect.custom](_: number, options: InspectOptions) {\n return `Jack ${inspect(this.toJSON(), options)}`\n }\n}\n\n// Unwrap and un-indent, so we can wrap description\n// strings however makes them look nice in the code.\nconst normalize = (s: string, pre = false) => {\n if (pre)\n // prepend a ZWSP to each line so cliui doesn't strip it.\n return s\n .split('\\n')\n .map(l => `\\u200b${l}`)\n .join('\\n')\n return s\n .split(/^\\s*```\\s*$/gm)\n .map((s, i) => {\n if (i % 2 === 1) {\n if (!s.trim()) {\n return `\\`\\`\\`\\n\\`\\`\\`\\n`\n }\n // outdent the ``` blocks, but preserve whitespace otherwise.\n const split = s.split('\\n')\n // throw out the \\n at the start and end\n split.pop()\n split.shift()\n const si = split.reduce((shortest, l) => {\n /* c8 ignore next */\n const ind = l.match(/^\\s*/)?.[0] ?? ''\n if (ind.length) return Math.min(ind.length, shortest)\n else return shortest\n }, Infinity)\n /* c8 ignore next */\n const i = isFinite(si) ? si : 0\n return (\n '\\n```\\n' +\n split.map(s => `\\u200b${s.substring(i)}`).join('\\n') +\n '\\n```\\n'\n )\n }\n return (\n s\n // remove single line breaks, except for lists\n .replace(/([^\\n])\\n[ \\t]*([^\\n])/g, (_, $1, $2) =>\n !/^[-*]/.test($2) ? `${$1} ${$2}` : `${$1}\\n${$2}`,\n )\n // normalize mid-line whitespace\n .replace(/([^\\n])[ \\t]+([^\\n])/g, '$1 $2')\n // two line breaks are enough\n .replace(/\\n{3,}/g, '\\n\\n')\n // remove any spaces at the start of a line\n .replace(/\\n[ \\t]+/g, '\\n')\n .trim()\n )\n })\n .join('\\n')\n}\n\n// normalize for markdown printing, remove leading spaces on lines\nconst normalizeMarkdown = (s: string, pre: boolean = false): string => {\n const n = normalize(s, pre).replace(/\\\\/g, '\\\\\\\\')\n return pre ?\n `\\`\\`\\`\\n${n.replace(/\\u200b/g, '')}\\n\\`\\`\\``\n : n.replace(/\\n +/g, '\\n').trim()\n}\n\nconst normalizeOneLine = (s: string, pre: boolean = false) => {\n const n = normalize(s, pre)\n .replace(/[\\s\\u200b]+/g, ' ')\n .trim()\n return pre ? `\\`${n}\\`` : n\n}\n\n/**\n * Main entry point. Create and return a {@link Jack} object.\n */\nexport const jack = (options: JackOptions = {}) => new Jack(options)\n"]} \ No newline at end of file diff --git a/node_modules/jackspeak/dist/commonjs/package.json b/node_modules/jackspeak/dist/commonjs/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/node_modules/jackspeak/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/jackspeak/dist/commonjs/parse-args-cjs.cjs.map b/node_modules/jackspeak/dist/commonjs/parse-args-cjs.cjs.map new file mode 100644 index 0000000..0a4a369 --- /dev/null +++ b/node_modules/jackspeak/dist/commonjs/parse-args-cjs.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"parse-args-cjs.cjs","sourceRoot":"","sources":["../../src/parse-args-cjs.cts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAA4B;AAE5B,MAAM,EAAE,GACN,CACE,OAAO,OAAO,KAAK,QAAQ;IAC3B,CAAC,CAAC,OAAO;IACT,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,CACpC,CAAC,CAAC;IACD,OAAO,CAAC,OAAO;IACjB,CAAC,CAAC,QAAQ,CAAA;AACZ,MAAM,GAAG,GAAG,EAAE;KACX,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC;KACjB,KAAK,CAAC,GAAG,CAAC;KACV,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAA;AAE5B,qBAAqB;AACrB,MAAM,CAAC,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,GAAG,GAAG,CAAA;AAClC,oBAAoB;AAEpB,IAAI,EAAE,SAAS,EAAE,EAAE,EAAE,GAAG,IAAI,CAAA;AAC5B,qBAAqB;AACrB,IACE,CAAC,EAAE;IACH,KAAK,GAAG,EAAE;IACV,CAAC,KAAK,KAAK,EAAE,IAAI,KAAK,GAAG,EAAE,CAAC;IAC5B,CAAC,KAAK,KAAK,EAAE,IAAI,KAAK,GAAG,EAAE,CAAC,EAC5B,CAAC;IACD,oBAAoB;IACpB,EAAE,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC,SAAS,CAAA;AAC5C,CAAC;AAEY,QAAA,SAAS,GAAG,EAAE,CAAA","sourcesContent":["import * as util from 'util'\n\nconst pv =\n (\n typeof process === 'object' &&\n !!process &&\n typeof process.version === 'string'\n ) ?\n process.version\n : 'v0.0.0'\nconst pvs = pv\n .replace(/^v/, '')\n .split('.')\n .map(s => parseInt(s, 10))\n\n/* c8 ignore start */\nconst [major = 0, minor = 0] = pvs\n/* c8 ignore stop */\n\nlet { parseArgs: pa } = util\n/* c8 ignore start */\nif (\n !pa ||\n major < 16 ||\n (major === 18 && minor < 11) ||\n (major === 16 && minor < 19)\n) {\n /* c8 ignore stop */\n pa = require('@pkgjs/parseargs').parseArgs\n}\n\nexport const parseArgs = pa\n"]} \ No newline at end of file diff --git a/node_modules/jackspeak/dist/commonjs/parse-args-cjs.d.cts.map b/node_modules/jackspeak/dist/commonjs/parse-args-cjs.d.cts.map new file mode 100644 index 0000000..066287c --- /dev/null +++ b/node_modules/jackspeak/dist/commonjs/parse-args-cjs.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"parse-args-cjs.d.cts","sourceRoot":"","sources":["../../src/parse-args-cjs.cts"],"names":[],"mappings":";AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AA+B5B,eAAO,MAAM,SAAS,uBAAK,CAAA"} \ No newline at end of file diff --git a/node_modules/jackspeak/dist/commonjs/parse-args.d.ts b/node_modules/jackspeak/dist/commonjs/parse-args.d.ts new file mode 100644 index 0000000..07f995c --- /dev/null +++ b/node_modules/jackspeak/dist/commonjs/parse-args.d.ts @@ -0,0 +1,4 @@ +/// +import * as util from 'util'; +export declare const parseArgs: typeof util.parseArgs; +//# sourceMappingURL=parse-args-cjs.d.cts.map \ No newline at end of file diff --git a/node_modules/jackspeak/dist/commonjs/parse-args.js b/node_modules/jackspeak/dist/commonjs/parse-args.js new file mode 100644 index 0000000..fc918a4 --- /dev/null +++ b/node_modules/jackspeak/dist/commonjs/parse-args.js @@ -0,0 +1,50 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseArgs = void 0; +const util = __importStar(require("util")); +const pv = (typeof process === 'object' && + !!process && + typeof process.version === 'string') ? + process.version + : 'v0.0.0'; +const pvs = pv + .replace(/^v/, '') + .split('.') + .map(s => parseInt(s, 10)); +/* c8 ignore start */ +const [major = 0, minor = 0] = pvs; +/* c8 ignore stop */ +let { parseArgs: pa } = util; +/* c8 ignore start */ +if (!pa || + major < 16 || + (major === 18 && minor < 11) || + (major === 16 && minor < 19)) { + /* c8 ignore stop */ + pa = require('@pkgjs/parseargs').parseArgs; +} +exports.parseArgs = pa; +//# sourceMappingURL=parse-args-cjs.cjs.map \ No newline at end of file diff --git a/node_modules/jackspeak/dist/esm/index.d.ts b/node_modules/jackspeak/dist/esm/index.d.ts new file mode 100644 index 0000000..214a177 --- /dev/null +++ b/node_modules/jackspeak/dist/esm/index.d.ts @@ -0,0 +1,315 @@ +/// +export type ConfigType = 'number' | 'string' | 'boolean'; +/** + * Given a Jack object, get the typeof its ConfigSet + */ +export type Unwrap = J extends Jack ? C : never; +import { inspect, InspectOptions } from 'node:util'; +/** + * Defines the type of value that is valid, given a config definition's + * {@link ConfigType} and boolean multiple setting + */ +export type ValidValue = [ + T, + M +] extends ['number', true] ? number[] : [T, M] extends ['string', true] ? string[] : [T, M] extends ['boolean', true] ? boolean[] : [T, M] extends ['number', false] ? number : [T, M] extends ['string', false] ? string : [T, M] extends ['boolean', false] ? boolean : [T, M] extends ['string', boolean] ? string | string[] : [T, M] extends ['boolean', boolean] ? boolean | boolean[] : [T, M] extends ['number', boolean] ? number | number[] : [T, M] extends [ConfigType, false] ? string | number | boolean : [T, M] extends [ConfigType, true] ? string[] | number[] | boolean[] : string | number | boolean | string[] | number[] | boolean[]; +/** + * The meta information for a config option definition, when the + * type and multiple values can be inferred by the method being used + */ +export type ConfigOptionMeta = { + default?: undefined | (ValidValue & (O extends number[] | string[] ? M extends false ? O[number] : O[number][] : unknown)); + validOptions?: O; + description?: string; + validate?: ((v: unknown) => v is ValidValue) | ((v: unknown) => boolean); + short?: string | undefined; + type?: T; + hint?: T extends 'boolean' ? never : string; + delim?: M extends true ? string : never; +} & (M extends false ? { + multiple?: false | undefined; +} : M extends true ? { + multiple: true; +} : { + multiple?: boolean; +}); +/** + * A set of {@link ConfigOptionMeta} fields, referenced by their longOption + * string values. + */ +export type ConfigMetaSet = { + [longOption: string]: ConfigOptionMeta; +}; +/** + * Infer {@link ConfigSet} fields from a given {@link ConfigMetaSet} + */ +export type ConfigSetFromMetaSet> = { + [longOption in keyof S]: ConfigOptionBase; +}; +/** + * Fields that can be set on a {@link ConfigOptionBase} or + * {@link ConfigOptionMeta} based on whether or not the field is known to be + * multiple. + */ +export type MultiType = M extends true ? { + multiple: true; + delim?: string | undefined; +} : M extends false ? { + multiple?: false | undefined; + delim?: undefined; +} : { + multiple?: boolean | undefined; + delim?: string | undefined; +}; +/** + * A config field definition, in its full representation. + */ +export type ConfigOptionBase = { + type: T; + short?: string | undefined; + default?: ValidValue | undefined; + description?: string; + hint?: T extends 'boolean' ? undefined : string | undefined; + validate?: (v: unknown) => v is ValidValue; + validOptions?: T extends 'boolean' ? undefined : T extends 'string' ? readonly string[] : T extends 'number' ? readonly number[] : readonly number[] | readonly string[]; +} & MultiType; +export declare const isConfigType: (t: string) => t is ConfigType; +export declare const isConfigOption: (o: any, type: T, multi: M) => o is ConfigOptionBase; +/** + * A set of {@link ConfigOptionBase} objects, referenced by their longOption + * string values. + */ +export type ConfigSet = { + [longOption: string]: ConfigOptionBase; +}; +/** + * The 'values' field returned by {@link Jack#parse} + */ +export type OptionsResults = { + [k in keyof T]?: T[k]['validOptions'] extends (readonly string[] | readonly number[]) ? T[k] extends ConfigOptionBase<'string' | 'number', false> ? T[k]['validOptions'][number] : T[k] extends ConfigOptionBase<'string' | 'number', true> ? T[k]['validOptions'][number][] : never : T[k] extends ConfigOptionBase<'string', false> ? string : T[k] extends ConfigOptionBase<'string', true> ? string[] : T[k] extends ConfigOptionBase<'number', false> ? number : T[k] extends ConfigOptionBase<'number', true> ? number[] : T[k] extends ConfigOptionBase<'boolean', false> ? boolean : T[k] extends ConfigOptionBase<'boolean', true> ? boolean[] : never; +}; +/** + * The object retured by {@link Jack#parse} + */ +export type Parsed = { + values: OptionsResults; + positionals: string[]; +}; +/** + * A row used when generating the {@link Jack#usage} string + */ +export interface Row { + left?: string; + text: string; + skipLine?: boolean; + type?: string; +} +/** + * A heading for a section in the usage, created by the jack.heading() + * method. + * + * First heading is always level 1, subsequent headings default to 2. + * + * The level of the nearest heading level sets the indentation of the + * description that follows. + */ +export interface Heading extends Row { + type: 'heading'; + text: string; + left?: ''; + skipLine?: boolean; + level: number; + pre?: boolean; +} +/** + * An arbitrary blob of text describing some stuff, set by the + * jack.description() method. + * + * Indentation determined by level of the nearest header. + */ +export interface Description extends Row { + type: 'description'; + text: string; + left?: ''; + skipLine?: boolean; + pre?: boolean; +} +/** + * A heading or description row used when generating the {@link Jack#usage} + * string + */ +export type TextRow = Heading | Description; +/** + * Either a {@link TextRow} or a reference to a {@link ConfigOptionBase} + */ +export type UsageField = TextRow | { + type: 'config'; + name: string; + value: ConfigOptionBase; +}; +/** + * Options provided to the {@link Jack} constructor + */ +export interface JackOptions { + /** + * Whether to allow positional arguments + * + * @default true + */ + allowPositionals?: boolean; + /** + * Prefix to use when reading/writing the environment variables + * + * If not specified, environment behavior will not be available. + */ + envPrefix?: string; + /** + * Environment object to read/write. Defaults `process.env`. + * No effect if `envPrefix` is not set. + */ + env?: { + [k: string]: string | undefined; + }; + /** + * A short usage string. If not provided, will be generated from the + * options provided, but that can of course be rather verbose if + * there are a lot of options. + */ + usage?: string; + /** + * Stop parsing flags and opts at the first positional argument. + * This is to support cases like `cmd [flags] [options]`, where + * each subcommand may have different options. This effectively treats + * any positional as a `--` argument. Only relevant if `allowPositionals` + * is true. + * + * To do subcommands, set this option, look at the first positional, and + * parse the remaining positionals as appropriate. + * + * @default false + */ + stopAtPositional?: boolean; + /** + * Conditional `stopAtPositional`. If set to a `(string)=>boolean` function, + * will be called with each positional argument encountered. If the function + * returns true, then parsing will stop at that point. + */ + stopAtPositionalTest?: (arg: string) => boolean; +} +/** + * Class returned by the {@link jack} function and all configuration + * definition methods. This is what gets chained together. + */ +export declare class Jack { + #private; + constructor(options?: JackOptions); + /** + * Set the default value (which will still be overridden by env or cli) + * as if from a parsed config file. The optional `source` param, if + * provided, will be included in error messages if a value is invalid or + * unknown. + */ + setConfigValues(values: OptionsResults, source?: string): this; + /** + * Parse a string of arguments, and return the resulting + * `{ values, positionals }` object. + * + * If an {@link JackOptions#envPrefix} is set, then it will read default + * values from the environment, and write the resulting values back + * to the environment as well. + * + * Environment values always take precedence over any other value, except + * an explicit CLI setting. + */ + parse(args?: string[]): Parsed; + loadEnvDefaults(): void; + applyDefaults(p: Parsed): void; + /** + * Only parse the command line arguments passed in. + * Does not strip off the `node script.js` bits, so it must be just the + * arguments you wish to have parsed. + * Does not read from or write to the environment, or set defaults. + */ + parseRaw(args: string[]): Parsed; + /** + * Validate that any arbitrary object is a valid configuration `values` + * object. Useful when loading config files or other sources. + */ + validate(o: unknown): asserts o is Parsed['values']; + writeEnv(p: Parsed): void; + /** + * Add a heading to the usage output banner + */ + heading(text: string, level?: 1 | 2 | 3 | 4 | 5 | 6, { pre }?: { + pre?: boolean; + }): Jack; + /** + * Add a long-form description to the usage output at this position. + */ + description(text: string, { pre }?: { + pre?: boolean; + }): Jack; + /** + * Add one or more number fields. + */ + num>(fields: F): Jack>; + /** + * Add one or more multiple number fields. + */ + numList>(fields: F): Jack>; + /** + * Add one or more string option fields. + */ + opt>(fields: F): Jack>; + /** + * Add one or more multiple string option fields. + */ + optList>(fields: F): Jack>; + /** + * Add one or more flag fields. + */ + flag>(fields: F): Jack>; + /** + * Add one or more multiple flag fields. + */ + flagList>(fields: F): Jack>; + /** + * Generic field definition method. Similar to flag/flagList/number/etc, + * but you must specify the `type` (and optionally `multiple` and `delim`) + * fields on each one, or Jack won't know how to define them. + */ + addFields(fields: F): Jack; + /** + * Return the usage banner for the given configuration + */ + usage(): string; + /** + * Return the usage banner markdown for the given configuration + */ + usageMarkdown(): string; + /** + * Return the configuration options as a plain object + */ + toJSON(): { + [k: string]: { + hint?: string | undefined; + default?: string | number | boolean | string[] | number[] | boolean[] | undefined; + validOptions?: readonly number[] | readonly string[] | undefined; + validate?: ((v: unknown) => v is string | number | boolean | string[] | number[] | boolean[]) | undefined; + description?: string | undefined; + short?: string | undefined; + delim?: string | undefined; + multiple?: boolean | undefined; + type: ConfigType; + }; + }; + /** + * Custom printer for `util.inspect` + */ + [inspect.custom](_: number, options: InspectOptions): string; +} +/** + * Main entry point. Create and return a {@link Jack} object. + */ +export declare const jack: (options?: JackOptions) => Jack<{}>; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/jackspeak/dist/esm/index.d.ts.map b/node_modules/jackspeak/dist/esm/index.d.ts.map new file mode 100644 index 0000000..faf9ddd --- /dev/null +++ b/node_modules/jackspeak/dist/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";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;;;IAqBN;;OAEG;IACH,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc;CAGpD;AAsED;;GAEG;AACH,eAAO,MAAM,IAAI,aAAa,WAAW,aAA2B,CAAA"} \ No newline at end of file diff --git a/node_modules/jackspeak/dist/esm/index.js b/node_modules/jackspeak/dist/esm/index.js new file mode 100644 index 0000000..78fdfa8 --- /dev/null +++ b/node_modules/jackspeak/dist/esm/index.js @@ -0,0 +1,1000 @@ +import { inspect } from 'node:util'; +import { parseArgs } from './parse-args.js'; +// it's a tiny API, just cast it inline, it's fine +//@ts-ignore +import cliui from '@isaacs/cliui'; +import { basename } from 'node:path'; +const width = Math.min((process && process.stdout && process.stdout.columns) || 80, 80); +// indentation spaces from heading level +const indent = (n) => (n - 1) * 2; +const toEnvKey = (pref, key) => { + return [pref, key.replace(/[^a-zA-Z0-9]+/g, ' ')] + .join(' ') + .trim() + .toUpperCase() + .replace(/ /g, '_'); +}; +const toEnvVal = (value, delim = '\n') => { + const str = typeof value === 'string' ? value + : typeof value === 'boolean' ? + value ? '1' + : '0' + : typeof value === 'number' ? String(value) + : Array.isArray(value) ? + value.map((v) => toEnvVal(v)).join(delim) + : /* c8 ignore start */ undefined; + if (typeof str !== 'string') { + throw new Error(`could not serialize value to environment: ${JSON.stringify(value)}`); + } + /* c8 ignore stop */ + return str; +}; +const fromEnvVal = (env, type, multiple, delim = '\n') => (multiple ? + env ? env.split(delim).map(v => fromEnvVal(v, type, false)) + : [] + : type === 'string' ? env + : type === 'boolean' ? env === '1' + : +env.trim()); +export const isConfigType = (t) => typeof t === 'string' && + (t === 'string' || t === 'number' || t === 'boolean'); +const undefOrType = (v, t) => v === undefined || typeof v === t; +const undefOrTypeArray = (v, t) => v === undefined || (Array.isArray(v) && v.every(x => typeof x === t)); +const isValidOption = (v, vo) => Array.isArray(v) ? v.every(x => isValidOption(x, vo)) : vo.includes(v); +// print the value type, for error message reporting +const valueType = (v) => typeof v === 'string' ? 'string' + : typeof v === 'boolean' ? 'boolean' + : typeof v === 'number' ? 'number' + : Array.isArray(v) ? + joinTypes([...new Set(v.map(v => valueType(v)))]) + '[]' + : `${v.type}${v.multiple ? '[]' : ''}`; +const joinTypes = (types) => types.length === 1 && typeof types[0] === 'string' ? + types[0] + : `(${types.join('|')})`; +const isValidValue = (v, type, multi) => { + if (multi) { + if (!Array.isArray(v)) + return false; + return !v.some((v) => !isValidValue(v, type, false)); + } + if (Array.isArray(v)) + return false; + return typeof v === type; +}; +export const isConfigOption = (o, type, multi) => !!o && + typeof o === 'object' && + isConfigType(o.type) && + o.type === type && + undefOrType(o.short, 'string') && + undefOrType(o.description, 'string') && + undefOrType(o.hint, 'string') && + undefOrType(o.validate, 'function') && + (o.type === 'boolean' ? + o.validOptions === undefined + : undefOrTypeArray(o.validOptions, o.type)) && + (o.default === undefined || isValidValue(o.default, type, multi)) && + !!o.multiple === multi; +function num(o = {}) { + const { default: def, validate: val, validOptions, ...rest } = o; + if (def !== undefined && !isValidValue(def, 'number', false)) { + throw new TypeError('invalid default value', { + cause: { + found: def, + wanted: 'number', + }, + }); + } + if (!undefOrTypeArray(validOptions, 'number')) { + throw new TypeError('invalid validOptions', { + cause: { + found: validOptions, + wanted: 'number[]', + }, + }); + } + const validate = val ? + val + : undefined; + return { + ...rest, + default: def, + validate, + validOptions, + type: 'number', + multiple: false, + }; +} +function numList(o = {}) { + const { default: def, validate: val, validOptions, ...rest } = o; + if (def !== undefined && !isValidValue(def, 'number', true)) { + throw new TypeError('invalid default value', { + cause: { + found: def, + wanted: 'number[]', + }, + }); + } + if (!undefOrTypeArray(validOptions, 'number')) { + throw new TypeError('invalid validOptions', { + cause: { + found: validOptions, + wanted: 'number[]', + }, + }); + } + const validate = val ? + val + : undefined; + return { + ...rest, + default: def, + validate, + validOptions, + type: 'number', + multiple: true, + }; +} +function opt(o = {}) { + const { default: def, validate: val, validOptions, ...rest } = o; + if (def !== undefined && !isValidValue(def, 'string', false)) { + throw new TypeError('invalid default value', { + cause: { + found: def, + wanted: 'string', + }, + }); + } + if (!undefOrTypeArray(validOptions, 'string')) { + throw new TypeError('invalid validOptions', { + cause: { + found: validOptions, + wanted: 'string[]', + }, + }); + } + const validate = val ? + val + : undefined; + return { + ...rest, + default: def, + validate, + validOptions, + type: 'string', + multiple: false, + }; +} +function optList(o = {}) { + const { default: def, validate: val, validOptions, ...rest } = o; + if (def !== undefined && !isValidValue(def, 'string', true)) { + throw new TypeError('invalid default value', { + cause: { + found: def, + wanted: 'string[]', + }, + }); + } + if (!undefOrTypeArray(validOptions, 'string')) { + throw new TypeError('invalid validOptions', { + cause: { + found: validOptions, + wanted: 'string[]', + }, + }); + } + const validate = val ? + val + : undefined; + return { + ...rest, + default: def, + validate, + validOptions, + type: 'string', + multiple: true, + }; +} +function flag(o = {}) { + const { hint, default: def, validate: val, ...rest } = o; + delete rest.validOptions; + if (def !== undefined && !isValidValue(def, 'boolean', false)) { + throw new TypeError('invalid default value'); + } + const validate = val ? + val + : undefined; + if (hint !== undefined) { + throw new TypeError('cannot provide hint for flag'); + } + return { + ...rest, + default: def, + validate, + type: 'boolean', + multiple: false, + }; +} +function flagList(o = {}) { + const { hint, default: def, validate: val, ...rest } = o; + delete rest.validOptions; + if (def !== undefined && !isValidValue(def, 'boolean', true)) { + throw new TypeError('invalid default value'); + } + const validate = val ? + val + : undefined; + if (hint !== undefined) { + throw new TypeError('cannot provide hint for flag list'); + } + return { + ...rest, + default: def, + validate, + type: 'boolean', + multiple: true, + }; +} +const toParseArgsOptionsConfig = (options) => { + const c = {}; + for (const longOption in options) { + const config = options[longOption]; + /* c8 ignore start */ + if (!config) { + throw new Error('config must be an object: ' + longOption); + } + /* c8 ignore start */ + if (isConfigOption(config, 'number', true)) { + c[longOption] = { + type: 'string', + multiple: true, + default: config.default?.map(c => String(c)), + }; + } + else if (isConfigOption(config, 'number', false)) { + c[longOption] = { + type: 'string', + multiple: false, + default: config.default === undefined ? + undefined + : String(config.default), + }; + } + else { + const conf = config; + c[longOption] = { + type: conf.type, + multiple: !!conf.multiple, + default: conf.default, + }; + } + const clo = c[longOption]; + if (typeof config.short === 'string') { + clo.short = config.short; + } + if (config.type === 'boolean' && + !longOption.startsWith('no-') && + !options[`no-${longOption}`]) { + c[`no-${longOption}`] = { + type: 'boolean', + multiple: config.multiple, + }; + } + } + return c; +}; +const isHeading = (r) => r.type === 'heading'; +const isDescription = (r) => r.type === 'description'; +/** + * Class returned by the {@link jack} function and all configuration + * definition methods. This is what gets chained together. + */ +export class Jack { + #configSet; + #shorts; + #options; + #fields = []; + #env; + #envPrefix; + #allowPositionals; + #usage; + #usageMarkdown; + constructor(options = {}) { + this.#options = options; + this.#allowPositionals = options.allowPositionals !== false; + this.#env = + this.#options.env === undefined ? process.env : this.#options.env; + this.#envPrefix = options.envPrefix; + // We need to fib a little, because it's always the same object, but it + // starts out as having an empty config set. Then each method that adds + // fields returns `this as Jack` + this.#configSet = Object.create(null); + this.#shorts = Object.create(null); + } + /** + * Set the default value (which will still be overridden by env or cli) + * as if from a parsed config file. The optional `source` param, if + * provided, will be included in error messages if a value is invalid or + * unknown. + */ + setConfigValues(values, source = '') { + try { + this.validate(values); + } + catch (er) { + const e = er; + if (source && e && typeof e === 'object') { + if (e.cause && typeof e.cause === 'object') { + Object.assign(e.cause, { path: source }); + } + else { + e.cause = { path: source }; + } + } + throw e; + } + for (const [field, value] of Object.entries(values)) { + const my = this.#configSet[field]; + // already validated, just for TS's benefit + /* c8 ignore start */ + if (!my) { + throw new Error('unexpected field in config set: ' + field, { + cause: { found: field }, + }); + } + /* c8 ignore stop */ + my.default = value; + } + return this; + } + /** + * Parse a string of arguments, and return the resulting + * `{ values, positionals }` object. + * + * If an {@link JackOptions#envPrefix} is set, then it will read default + * values from the environment, and write the resulting values back + * to the environment as well. + * + * Environment values always take precedence over any other value, except + * an explicit CLI setting. + */ + parse(args = process.argv) { + this.loadEnvDefaults(); + const p = this.parseRaw(args); + this.applyDefaults(p); + this.writeEnv(p); + return p; + } + loadEnvDefaults() { + if (this.#envPrefix) { + for (const [field, my] of Object.entries(this.#configSet)) { + const ek = toEnvKey(this.#envPrefix, field); + const env = this.#env[ek]; + if (env !== undefined) { + my.default = fromEnvVal(env, my.type, !!my.multiple, my.delim); + } + } + } + } + applyDefaults(p) { + for (const [field, c] of Object.entries(this.#configSet)) { + if (c.default !== undefined && !(field in p.values)) { + //@ts-ignore + p.values[field] = c.default; + } + } + } + /** + * Only parse the command line arguments passed in. + * Does not strip off the `node script.js` bits, so it must be just the + * arguments you wish to have parsed. + * Does not read from or write to the environment, or set defaults. + */ + parseRaw(args) { + if (args === process.argv) { + args = args.slice(process._eval !== undefined ? 1 : 2); + } + const options = toParseArgsOptionsConfig(this.#configSet); + const result = parseArgs({ + args, + options, + // always strict, but using our own logic + strict: false, + allowPositionals: this.#allowPositionals, + tokens: true, + }); + const p = { + values: {}, + positionals: [], + }; + for (const token of result.tokens) { + if (token.kind === 'positional') { + p.positionals.push(token.value); + if (this.#options.stopAtPositional || + this.#options.stopAtPositionalTest?.(token.value)) { + p.positionals.push(...args.slice(token.index + 1)); + break; + } + } + else if (token.kind === 'option') { + let value = undefined; + if (token.name.startsWith('no-')) { + const my = this.#configSet[token.name]; + const pname = token.name.substring('no-'.length); + const pos = this.#configSet[pname]; + if (pos && + pos.type === 'boolean' && + (!my || + (my.type === 'boolean' && !!my.multiple === !!pos.multiple))) { + value = false; + token.name = pname; + } + } + const my = this.#configSet[token.name]; + if (!my) { + throw new Error(`Unknown option '${token.rawName}'. ` + + `To specify a positional argument starting with a '-', ` + + `place it at the end of the command after '--', as in ` + + `'-- ${token.rawName}'`, { + cause: { + found: token.rawName + (token.value ? `=${token.value}` : ''), + }, + }); + } + if (value === undefined) { + if (token.value === undefined) { + if (my.type !== 'boolean') { + throw new Error(`No value provided for ${token.rawName}, expected ${my.type}`, { + cause: { + name: token.rawName, + wanted: valueType(my), + }, + }); + } + value = true; + } + else { + if (my.type === 'boolean') { + throw new Error(`Flag ${token.rawName} does not take a value, received '${token.value}'`, { cause: { found: token } }); + } + if (my.type === 'string') { + value = token.value; + } + else { + value = +token.value; + if (value !== value) { + throw new Error(`Invalid value '${token.value}' provided for ` + + `'${token.rawName}' option, expected number`, { + cause: { + name: token.rawName, + found: token.value, + wanted: 'number', + }, + }); + } + } + } + } + if (my.multiple) { + const pv = p.values; + const tn = pv[token.name] ?? []; + pv[token.name] = tn; + tn.push(value); + } + else { + const pv = p.values; + pv[token.name] = value; + } + } + } + for (const [field, value] of Object.entries(p.values)) { + const valid = this.#configSet[field]?.validate; + const validOptions = this.#configSet[field]?.validOptions; + let cause; + if (validOptions && !isValidOption(value, validOptions)) { + cause = { name: field, found: value, validOptions: validOptions }; + } + if (valid && !valid(value)) { + cause = cause || { name: field, found: value }; + } + if (cause) { + throw new Error(`Invalid value provided for --${field}: ${JSON.stringify(value)}`, { cause }); + } + } + return p; + } + /** + * do not set fields as 'no-foo' if 'foo' exists and both are bools + * just set foo. + */ + #noNoFields(f, val, s = f) { + if (!f.startsWith('no-') || typeof val !== 'boolean') + return; + const yes = f.substring('no-'.length); + // recurse so we get the core config key we care about. + this.#noNoFields(yes, val, s); + if (this.#configSet[yes]?.type === 'boolean') { + throw new Error(`do not set '${s}', instead set '${yes}' as desired.`, { cause: { found: s, wanted: yes } }); + } + } + /** + * Validate that any arbitrary object is a valid configuration `values` + * object. Useful when loading config files or other sources. + */ + validate(o) { + if (!o || typeof o !== 'object') { + throw new Error('Invalid config: not an object', { + cause: { found: o }, + }); + } + const opts = o; + for (const field in o) { + const value = opts[field]; + /* c8 ignore next - for TS */ + if (value === undefined) + continue; + this.#noNoFields(field, value); + const config = this.#configSet[field]; + if (!config) { + throw new Error(`Unknown config option: ${field}`, { + cause: { found: field }, + }); + } + if (!isValidValue(value, config.type, !!config.multiple)) { + throw new Error(`Invalid value ${valueType(value)} for ${field}, expected ${valueType(config)}`, { + cause: { + name: field, + found: value, + wanted: valueType(config), + }, + }); + } + let cause; + if (config.validOptions && + !isValidOption(value, config.validOptions)) { + cause = { + name: field, + found: value, + validOptions: config.validOptions, + }; + } + if (config.validate && !config.validate(value)) { + cause = cause || { name: field, found: value }; + } + if (cause) { + throw new Error(`Invalid config value for ${field}: ${value}`, { + cause, + }); + } + } + } + writeEnv(p) { + if (!this.#env || !this.#envPrefix) + return; + for (const [field, value] of Object.entries(p.values)) { + const my = this.#configSet[field]; + this.#env[toEnvKey(this.#envPrefix, field)] = toEnvVal(value, my?.delim); + } + } + /** + * Add a heading to the usage output banner + */ + heading(text, level, { pre = false } = {}) { + if (level === undefined) { + level = this.#fields.some(r => isHeading(r)) ? 2 : 1; + } + this.#fields.push({ type: 'heading', text, level, pre }); + return this; + } + /** + * Add a long-form description to the usage output at this position. + */ + description(text, { pre } = {}) { + this.#fields.push({ type: 'description', text, pre }); + return this; + } + /** + * Add one or more number fields. + */ + num(fields) { + return this.#addFields(fields, num); + } + /** + * Add one or more multiple number fields. + */ + numList(fields) { + return this.#addFields(fields, numList); + } + /** + * Add one or more string option fields. + */ + opt(fields) { + return this.#addFields(fields, opt); + } + /** + * Add one or more multiple string option fields. + */ + optList(fields) { + return this.#addFields(fields, optList); + } + /** + * Add one or more flag fields. + */ + flag(fields) { + return this.#addFields(fields, flag); + } + /** + * Add one or more multiple flag fields. + */ + flagList(fields) { + return this.#addFields(fields, flagList); + } + /** + * Generic field definition method. Similar to flag/flagList/number/etc, + * but you must specify the `type` (and optionally `multiple` and `delim`) + * fields on each one, or Jack won't know how to define them. + */ + addFields(fields) { + const next = this; + for (const [name, field] of Object.entries(fields)) { + this.#validateName(name, field); + next.#fields.push({ + type: 'config', + name, + value: field, + }); + } + Object.assign(next.#configSet, fields); + return next; + } + #addFields(fields, fn) { + const next = this; + Object.assign(next.#configSet, Object.fromEntries(Object.entries(fields).map(([name, field]) => { + this.#validateName(name, field); + const option = fn(field); + next.#fields.push({ + type: 'config', + name, + value: option, + }); + return [name, option]; + }))); + return next; + } + #validateName(name, field) { + if (!/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(name)) { + throw new TypeError(`Invalid option name: ${name}, ` + + `must be '-' delimited ASCII alphanumeric`); + } + if (this.#configSet[name]) { + throw new TypeError(`Cannot redefine option ${field}`); + } + if (this.#shorts[name]) { + throw new TypeError(`Cannot redefine option ${name}, already ` + + `in use for ${this.#shorts[name]}`); + } + if (field.short) { + if (!/^[a-zA-Z0-9]$/.test(field.short)) { + throw new TypeError(`Invalid ${name} short option: ${field.short}, ` + + 'must be 1 ASCII alphanumeric character'); + } + if (this.#shorts[field.short]) { + throw new TypeError(`Invalid ${name} short option: ${field.short}, ` + + `already in use for ${this.#shorts[field.short]}`); + } + this.#shorts[field.short] = name; + this.#shorts[name] = name; + } + } + /** + * Return the usage banner for the given configuration + */ + usage() { + if (this.#usage) + return this.#usage; + let headingLevel = 1; + const ui = cliui({ width }); + const first = this.#fields[0]; + let start = first?.type === 'heading' ? 1 : 0; + if (first?.type === 'heading') { + ui.div({ + padding: [0, 0, 0, 0], + text: normalize(first.text), + }); + } + ui.div({ padding: [0, 0, 0, 0], text: 'Usage:' }); + if (this.#options.usage) { + ui.div({ + text: this.#options.usage, + padding: [0, 0, 0, 2], + }); + } + else { + const cmd = basename(String(process.argv[1])); + const shortFlags = []; + const shorts = []; + const flags = []; + const opts = []; + for (const [field, config] of Object.entries(this.#configSet)) { + if (config.short) { + if (config.type === 'boolean') + shortFlags.push(config.short); + else + shorts.push([config.short, config.hint || field]); + } + else { + if (config.type === 'boolean') + flags.push(field); + else + opts.push([field, config.hint || field]); + } + } + const sf = shortFlags.length ? ' -' + shortFlags.join('') : ''; + const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join(''); + const lf = flags.map(k => ` --${k}`).join(''); + const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join(''); + const usage = `${cmd}${sf}${so}${lf}${lo}`.trim(); + ui.div({ + text: usage, + padding: [0, 0, 0, 2], + }); + } + ui.div({ padding: [0, 0, 0, 0], text: '' }); + const maybeDesc = this.#fields[start]; + if (maybeDesc && isDescription(maybeDesc)) { + const print = normalize(maybeDesc.text, maybeDesc.pre); + start++; + ui.div({ padding: [0, 0, 0, 0], text: print }); + ui.div({ padding: [0, 0, 0, 0], text: '' }); + } + const { rows, maxWidth } = this.#usageRows(start); + // every heading/description after the first gets indented by 2 + // extra spaces. + for (const row of rows) { + if (row.left) { + // If the row is too long, don't wrap it + // Bump the right-hand side down a line to make room + const configIndent = indent(Math.max(headingLevel, 2)); + if (row.left.length > maxWidth - 3) { + ui.div({ text: row.left, padding: [0, 0, 0, configIndent] }); + ui.div({ text: row.text, padding: [0, 0, 0, maxWidth] }); + } + else { + ui.div({ + text: row.left, + padding: [0, 1, 0, configIndent], + width: maxWidth, + }, { padding: [0, 0, 0, 0], text: row.text }); + } + if (row.skipLine) { + ui.div({ padding: [0, 0, 0, 0], text: '' }); + } + } + else { + if (isHeading(row)) { + const { level } = row; + headingLevel = level; + // only h1 and h2 have bottom padding + // h3-h6 do not + const b = level <= 2 ? 1 : 0; + ui.div({ ...row, padding: [0, 0, b, indent(level)] }); + } + else { + ui.div({ ...row, padding: [0, 0, 1, indent(headingLevel + 1)] }); + } + } + } + return (this.#usage = ui.toString()); + } + /** + * Return the usage banner markdown for the given configuration + */ + usageMarkdown() { + if (this.#usageMarkdown) + return this.#usageMarkdown; + const out = []; + let headingLevel = 1; + const first = this.#fields[0]; + let start = first?.type === 'heading' ? 1 : 0; + if (first?.type === 'heading') { + out.push(`# ${normalizeOneLine(first.text)}`); + } + out.push('Usage:'); + if (this.#options.usage) { + out.push(normalizeMarkdown(this.#options.usage, true)); + } + else { + const cmd = basename(String(process.argv[1])); + const shortFlags = []; + const shorts = []; + const flags = []; + const opts = []; + for (const [field, config] of Object.entries(this.#configSet)) { + if (config.short) { + if (config.type === 'boolean') + shortFlags.push(config.short); + else + shorts.push([config.short, config.hint || field]); + } + else { + if (config.type === 'boolean') + flags.push(field); + else + opts.push([field, config.hint || field]); + } + } + const sf = shortFlags.length ? ' -' + shortFlags.join('') : ''; + const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join(''); + const lf = flags.map(k => ` --${k}`).join(''); + const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join(''); + const usage = `${cmd}${sf}${so}${lf}${lo}`.trim(); + out.push(normalizeMarkdown(usage, true)); + } + const maybeDesc = this.#fields[start]; + if (maybeDesc && isDescription(maybeDesc)) { + out.push(normalizeMarkdown(maybeDesc.text, maybeDesc.pre)); + start++; + } + const { rows } = this.#usageRows(start); + // heading level in markdown is number of # ahead of text + for (const row of rows) { + if (row.left) { + out.push('#'.repeat(headingLevel + 1) + + ' ' + + normalizeOneLine(row.left, true)); + if (row.text) + out.push(normalizeMarkdown(row.text)); + } + else if (isHeading(row)) { + const { level } = row; + headingLevel = level; + out.push(`${'#'.repeat(headingLevel)} ${normalizeOneLine(row.text, row.pre)}`); + } + else { + out.push(normalizeMarkdown(row.text, !!row.pre)); + } + } + return (this.#usageMarkdown = out.join('\n\n') + '\n'); + } + #usageRows(start) { + // turn each config type into a row, and figure out the width of the + // left hand indentation for the option descriptions. + let maxMax = Math.max(12, Math.min(26, Math.floor(width / 3))); + let maxWidth = 8; + let prev = undefined; + const rows = []; + for (const field of this.#fields.slice(start)) { + if (field.type !== 'config') { + if (prev?.type === 'config') + prev.skipLine = true; + prev = undefined; + field.text = normalize(field.text, !!field.pre); + rows.push(field); + continue; + } + const { value } = field; + const desc = value.description || ''; + const mult = value.multiple ? 'Can be set multiple times' : ''; + const opts = value.validOptions?.length ? + `Valid options:${value.validOptions.map(v => ` ${JSON.stringify(v)}`)}` + : ''; + const dmDelim = desc.includes('\n') ? '\n\n' : '\n'; + const extra = [opts, mult].join(dmDelim).trim(); + const text = (normalize(desc) + dmDelim + extra).trim(); + const hint = value.hint || + (value.type === 'number' ? 'n' + : value.type === 'string' ? field.name + : undefined); + const short = !value.short ? '' + : value.type === 'boolean' ? `-${value.short} ` + : `-${value.short}<${hint}> `; + const left = value.type === 'boolean' ? + `${short}--${field.name}` + : `${short}--${field.name}=<${hint}>`; + const row = { text, left, type: 'config' }; + if (text.length > width - maxMax) { + row.skipLine = true; + } + if (prev && left.length > maxMax) + prev.skipLine = true; + prev = row; + const len = left.length + 4; + if (len > maxWidth && len < maxMax) { + maxWidth = len; + } + rows.push(row); + } + return { rows, maxWidth }; + } + /** + * Return the configuration options as a plain object + */ + toJSON() { + return Object.fromEntries(Object.entries(this.#configSet).map(([field, def]) => [ + field, + { + type: def.type, + ...(def.multiple ? { multiple: true } : {}), + ...(def.delim ? { delim: def.delim } : {}), + ...(def.short ? { short: def.short } : {}), + ...(def.description ? + { description: normalize(def.description) } + : {}), + ...(def.validate ? { validate: def.validate } : {}), + ...(def.validOptions ? { validOptions: def.validOptions } : {}), + ...(def.default !== undefined ? { default: def.default } : {}), + ...(def.hint ? { hint: def.hint } : {}), + }, + ])); + } + /** + * Custom printer for `util.inspect` + */ + [inspect.custom](_, options) { + return `Jack ${inspect(this.toJSON(), options)}`; + } +} +// Unwrap and un-indent, so we can wrap description +// strings however makes them look nice in the code. +const normalize = (s, pre = false) => { + if (pre) + // prepend a ZWSP to each line so cliui doesn't strip it. + return s + .split('\n') + .map(l => `\u200b${l}`) + .join('\n'); + return s + .split(/^\s*```\s*$/gm) + .map((s, i) => { + if (i % 2 === 1) { + if (!s.trim()) { + return `\`\`\`\n\`\`\`\n`; + } + // outdent the ``` blocks, but preserve whitespace otherwise. + const split = s.split('\n'); + // throw out the \n at the start and end + split.pop(); + split.shift(); + const si = split.reduce((shortest, l) => { + /* c8 ignore next */ + const ind = l.match(/^\s*/)?.[0] ?? ''; + if (ind.length) + return Math.min(ind.length, shortest); + else + return shortest; + }, Infinity); + /* c8 ignore next */ + const i = isFinite(si) ? si : 0; + return ('\n```\n' + + split.map(s => `\u200b${s.substring(i)}`).join('\n') + + '\n```\n'); + } + return (s + // remove single line breaks, except for lists + .replace(/([^\n])\n[ \t]*([^\n])/g, (_, $1, $2) => !/^[-*]/.test($2) ? `${$1} ${$2}` : `${$1}\n${$2}`) + // normalize mid-line whitespace + .replace(/([^\n])[ \t]+([^\n])/g, '$1 $2') + // two line breaks are enough + .replace(/\n{3,}/g, '\n\n') + // remove any spaces at the start of a line + .replace(/\n[ \t]+/g, '\n') + .trim()); + }) + .join('\n'); +}; +// normalize for markdown printing, remove leading spaces on lines +const normalizeMarkdown = (s, pre = false) => { + const n = normalize(s, pre).replace(/\\/g, '\\\\'); + return pre ? + `\`\`\`\n${n.replace(/\u200b/g, '')}\n\`\`\`` + : n.replace(/\n +/g, '\n').trim(); +}; +const normalizeOneLine = (s, pre = false) => { + const n = normalize(s, pre) + .replace(/[\s\u200b]+/g, ' ') + .trim(); + return pre ? `\`${n}\`` : n; +}; +/** + * Main entry point. Create and return a {@link Jack} object. + */ +export const jack = (options = {}) => new Jack(options); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/jackspeak/dist/esm/index.js.map b/node_modules/jackspeak/dist/esm/index.js.map new file mode 100644 index 0000000..1ca796a --- /dev/null +++ b/node_modules/jackspeak/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,OAAO,EAAmC,MAAM,WAAW,CAAA;AACpE,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAE3C,kDAAkD;AAClD,YAAY;AACZ,OAAO,KAAK,MAAM,eAAe,CAAA;AACjC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAEpC,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CACpB,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,EAC3D,EAAE,CACH,CAAA;AAED,wCAAwC;AACxC,MAAM,MAAM,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,C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AA6B;aAC5B,OAAO,CAAC,SAAS,EAAE,MAAM,CAAC;YAC3B,2CAA2C;aAC1C,OAAO,CAAC,WAAW,EAAE,IAAI,CAAC;aAC1B,IAAI,EAAE,CACV,CAAA;IACH,CAAC,CAAC;SACD,IAAI,CAAC,IAAI,CAAC,CAAA;AACf,CAAC,CAAA;AAED,kEAAkE;AAClE,MAAM,iBAAiB,GAAG,CAAC,CAAS,EAAE,MAAe,KAAK,EAAU,EAAE;IACpE,MAAM,CAAC,GAAG,SAAS,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,CAAA;IAClD,OAAO,GAAG,CAAC,CAAC;QACR,WAAW,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC,UAAU;QAC/C,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,IAAI,EAAE,CAAA;AACrC,CAAC,CAAA;AAED,MAAM,gBAAgB,GAAG,CAAC,CAAS,EAAE,MAAe,KAAK,EAAE,EAAE;IAC3D,MAAM,CAAC,GAAG,SAAS,CAAC,CAAC,EAAE,GAAG,CAAC;SACxB,OAAO,CAAC,cAAc,EAAE,GAAG,CAAC;SAC5B,IAAI,EAAE,CAAA;IACT,OAAO,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;AAC7B,CAAC,CAAA;AAED;;GAEG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAAC,UAAuB,EAAE,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,CAAA","sourcesContent":["export type ConfigType = 'number' | 'string' | 'boolean'\n\n/**\n * Given a Jack object, get the typeof its ConfigSet\n */\nexport type Unwrap = J extends Jack ? C : never\n\nimport { inspect, InspectOptions, ParseArgsConfig } from 'node:util'\nimport { parseArgs } from './parse-args.js'\n\n// it's a tiny API, just cast it inline, it's fine\n//@ts-ignore\nimport cliui from '@isaacs/cliui'\nimport { basename } from 'node:path'\n\nconst width = Math.min(\n (process && process.stdout && process.stdout.columns) || 80,\n 80,\n)\n\n// indentation spaces from heading level\nconst indent = (n: number) => (n - 1) * 2\n\nconst toEnvKey = (pref: string, key: string): string => {\n return [pref, key.replace(/[^a-zA-Z0-9]+/g, ' ')]\n .join(' ')\n .trim()\n .toUpperCase()\n .replace(/ /g, '_')\n}\n\nconst toEnvVal = (\n value: string | boolean | number | string[] | boolean[] | number[],\n delim: string = '\\n',\n): string => {\n const str =\n typeof value === 'string' ? value\n : typeof value === 'boolean' ?\n value ? '1'\n : '0'\n : typeof value === 'number' ? String(value)\n : Array.isArray(value) ?\n value.map((v: string | number | boolean) => toEnvVal(v)).join(delim)\n : /* c8 ignore start */ undefined\n if (typeof str !== 'string') {\n throw new Error(\n `could not serialize value to environment: ${JSON.stringify(value)}`,\n )\n }\n /* c8 ignore stop */\n return str\n}\n\nconst fromEnvVal = (\n env: string,\n type: T,\n multiple: M,\n delim: string = '\\n',\n): ValidValue =>\n (multiple ?\n env ? env.split(delim).map(v => fromEnvVal(v, type, false))\n : []\n : type === 'string' ? env\n : type === 'boolean' ? env === '1'\n : +env.trim()) as ValidValue\n\n/**\n * Defines the type of value that is valid, given a config definition's\n * {@link ConfigType} and boolean multiple setting\n */\nexport type ValidValue<\n T extends ConfigType = ConfigType,\n M extends boolean = boolean,\n> =\n [T, M] extends ['number', true] ? number[]\n : [T, M] extends ['string', true] ? string[]\n : [T, M] extends ['boolean', true] ? boolean[]\n : [T, M] extends ['number', false] ? number\n : [T, M] extends ['string', false] ? string\n : [T, M] extends ['boolean', false] ? boolean\n : [T, M] extends ['string', boolean] ? string | string[]\n : [T, M] extends ['boolean', boolean] ? boolean | boolean[]\n : [T, M] extends ['number', boolean] ? number | number[]\n : [T, M] extends [ConfigType, false] ? string | number | boolean\n : [T, M] extends [ConfigType, true] ? string[] | number[] | boolean[]\n : string | number | boolean | string[] | number[] | boolean[]\n\n/**\n * The meta information for a config option definition, when the\n * type and multiple values can be inferred by the method being used\n */\nexport type ConfigOptionMeta<\n T extends ConfigType,\n M extends boolean = boolean,\n O extends\n | undefined\n | (T extends 'boolean' ? never\n : T extends 'string' ? readonly string[]\n : T extends 'number' ? readonly number[]\n : readonly number[] | readonly string[]) =\n | undefined\n | (T extends 'boolean' ? never\n : T extends 'string' ? readonly string[]\n : T extends 'number' ? readonly number[]\n : readonly number[] | readonly string[]),\n> = {\n default?:\n | undefined\n | (ValidValue &\n (O extends number[] | string[] ?\n M extends false ?\n O[number]\n : O[number][]\n : unknown))\n validOptions?: O\n description?: string\n validate?:\n | ((v: unknown) => v is ValidValue)\n | ((v: unknown) => boolean)\n short?: string | undefined\n type?: T\n hint?: T extends 'boolean' ? never : string\n delim?: M extends true ? string : never\n} & (M extends false ? { multiple?: false | undefined }\n: M extends true ? { multiple: true }\n: { multiple?: boolean })\n\n/**\n * A set of {@link ConfigOptionMeta} fields, referenced by their longOption\n * string values.\n */\nexport type ConfigMetaSet<\n T extends ConfigType,\n M extends boolean = boolean,\n> = {\n [longOption: string]: ConfigOptionMeta\n}\n\n/**\n * Infer {@link ConfigSet} fields from a given {@link ConfigMetaSet}\n */\nexport type ConfigSetFromMetaSet<\n T extends ConfigType,\n M extends boolean,\n S extends ConfigMetaSet,\n> = {\n [longOption in keyof S]: ConfigOptionBase\n}\n\n/**\n * Fields that can be set on a {@link ConfigOptionBase} or\n * {@link ConfigOptionMeta} based on whether or not the field is known to be\n * multiple.\n */\nexport type MultiType =\n M extends true ?\n {\n multiple: true\n delim?: string | undefined\n }\n : M extends false ?\n {\n multiple?: false | undefined\n delim?: undefined\n }\n : {\n multiple?: boolean | undefined\n delim?: string | undefined\n }\n\n/**\n * A config field definition, in its full representation.\n */\nexport type ConfigOptionBase<\n T extends ConfigType,\n M extends boolean = boolean,\n> = {\n type: T\n short?: string | undefined\n default?: ValidValue | undefined\n description?: string\n hint?: T extends 'boolean' ? undefined : string | undefined\n validate?: (v: unknown) => v is ValidValue\n validOptions?: T extends 'boolean' ? undefined\n : T extends 'string' ? readonly string[]\n : T extends 'number' ? readonly number[]\n : readonly number[] | readonly string[]\n} & MultiType\n\nexport const isConfigType = (t: string): t is ConfigType =>\n typeof t === 'string' &&\n (t === 'string' || t === 'number' || t === 'boolean')\n\nconst undefOrType = (v: unknown, t: string): boolean =>\n v === undefined || typeof v === t\nconst undefOrTypeArray = (v: unknown, t: string): boolean =>\n v === undefined || (Array.isArray(v) && v.every(x => typeof x === t))\n\nconst isValidOption = (v: unknown, vo: readonly unknown[]): boolean =>\n Array.isArray(v) ? v.every(x => isValidOption(x, vo)) : vo.includes(v)\n\n// print the value type, for error message reporting\nconst valueType = (\n v:\n | string\n | number\n | boolean\n | string[]\n | number[]\n | boolean[]\n | { type: ConfigType; multiple?: boolean },\n): string =>\n typeof v === 'string' ? 'string'\n : typeof v === 'boolean' ? 'boolean'\n : typeof v === 'number' ? 'number'\n : Array.isArray(v) ?\n joinTypes([...new Set(v.map(v => valueType(v)))]) + '[]'\n : `${v.type}${v.multiple ? '[]' : ''}`\n\nconst joinTypes = (types: string[]): string =>\n types.length === 1 && typeof types[0] === 'string' ?\n types[0]\n : `(${types.join('|')})`\n\nconst isValidValue = (\n v: unknown,\n type: T,\n multi: M,\n): v is ValidValue => {\n if (multi) {\n if (!Array.isArray(v)) return false\n return !v.some((v: unknown) => !isValidValue(v, type, false))\n }\n if (Array.isArray(v)) return false\n return typeof v === type\n}\n\nexport const isConfigOption = (\n o: any,\n type: T,\n multi: M,\n): o is ConfigOptionBase =>\n !!o &&\n typeof o === 'object' &&\n isConfigType(o.type) &&\n o.type === type &&\n undefOrType(o.short, 'string') &&\n undefOrType(o.description, 'string') &&\n undefOrType(o.hint, 'string') &&\n undefOrType(o.validate, 'function') &&\n (o.type === 'boolean' ?\n o.validOptions === undefined\n : undefOrTypeArray(o.validOptions, o.type)) &&\n (o.default === undefined || isValidValue(o.default, type, multi)) &&\n !!o.multiple === multi\n\n/**\n * A set of {@link ConfigOptionBase} objects, referenced by their longOption\n * string values.\n */\nexport type ConfigSet = {\n [longOption: string]: ConfigOptionBase\n}\n\n/**\n * The 'values' field returned by {@link Jack#parse}\n */\nexport type OptionsResults = {\n [k in keyof T]?: T[k]['validOptions'] extends (\n readonly string[] | readonly number[]\n ) ?\n T[k] extends ConfigOptionBase<'string' | 'number', false> ?\n T[k]['validOptions'][number]\n : T[k] extends ConfigOptionBase<'string' | 'number', true> ?\n T[k]['validOptions'][number][]\n : never\n : T[k] extends ConfigOptionBase<'string', false> ? string\n : T[k] extends ConfigOptionBase<'string', true> ? string[]\n : T[k] extends ConfigOptionBase<'number', false> ? number\n : T[k] extends ConfigOptionBase<'number', true> ? number[]\n : T[k] extends ConfigOptionBase<'boolean', false> ? boolean\n : T[k] extends ConfigOptionBase<'boolean', true> ? boolean[]\n : never\n}\n\n/**\n * The object retured by {@link Jack#parse}\n */\nexport type Parsed = {\n values: OptionsResults\n positionals: string[]\n}\n\nfunction num(\n o: ConfigOptionMeta<'number', false> = {},\n): ConfigOptionBase<'number', false> {\n const { default: def, validate: val, validOptions, ...rest } = o\n if (def !== undefined && !isValidValue(def, 'number', false)) {\n throw new TypeError('invalid default value', {\n cause: {\n found: def,\n wanted: 'number',\n },\n })\n }\n if (!undefOrTypeArray(validOptions, 'number')) {\n throw new TypeError('invalid validOptions', {\n cause: {\n found: validOptions,\n wanted: 'number[]',\n },\n })\n }\n const validate =\n val ?\n (val as (v: unknown) => v is ValidValue<'number', false>)\n : undefined\n return {\n ...rest,\n default: def,\n validate,\n validOptions,\n type: 'number',\n multiple: false,\n }\n}\n\nfunction numList(\n o: ConfigOptionMeta<'number'> = {},\n): ConfigOptionBase<'number', true> {\n const { default: def, validate: val, validOptions, ...rest } = o\n if (def !== undefined && !isValidValue(def, 'number', true)) {\n throw new TypeError('invalid default value', {\n cause: {\n found: def,\n wanted: 'number[]',\n },\n })\n }\n if (!undefOrTypeArray(validOptions, 'number')) {\n throw new TypeError('invalid validOptions', {\n cause: {\n found: validOptions,\n wanted: 'number[]',\n },\n })\n }\n const validate =\n val ?\n (val as (v: unknown) => v is ValidValue<'number', true>)\n : undefined\n return {\n ...rest,\n default: def,\n validate,\n validOptions,\n type: 'number',\n multiple: true,\n }\n}\n\nfunction opt(\n o: ConfigOptionMeta<'string', false> = {},\n): ConfigOptionBase<'string', false> {\n const { default: def, validate: val, validOptions, ...rest } = o\n if (def !== undefined && !isValidValue(def, 'string', false)) {\n throw new TypeError('invalid default value', {\n cause: {\n found: def,\n wanted: 'string',\n },\n })\n }\n if (!undefOrTypeArray(validOptions, 'string')) {\n throw new TypeError('invalid validOptions', {\n cause: {\n found: validOptions,\n wanted: 'string[]',\n },\n })\n }\n const validate =\n val ?\n (val as (v: unknown) => v is ValidValue<'string', false>)\n : undefined\n return {\n ...rest,\n default: def,\n validate,\n validOptions,\n type: 'string',\n multiple: false,\n }\n}\n\nfunction optList(\n o: ConfigOptionMeta<'string'> = {},\n): ConfigOptionBase<'string', true> {\n const { default: def, validate: val, validOptions, ...rest } = o\n if (def !== undefined && !isValidValue(def, 'string', true)) {\n throw new TypeError('invalid default value', {\n cause: {\n found: def,\n wanted: 'string[]',\n },\n })\n }\n if (!undefOrTypeArray(validOptions, 'string')) {\n throw new TypeError('invalid validOptions', {\n cause: {\n found: validOptions,\n wanted: 'string[]',\n },\n })\n }\n const validate =\n val ?\n (val as (v: unknown) => v is ValidValue<'string', true>)\n : undefined\n return {\n ...rest,\n default: def,\n validate,\n validOptions,\n type: 'string',\n multiple: true,\n }\n}\n\nfunction flag(\n o: ConfigOptionMeta<'boolean', false> = {},\n): ConfigOptionBase<'boolean', false> {\n const {\n hint,\n default: def,\n validate: val,\n ...rest\n } = o as ConfigOptionMeta<'boolean', false>\n delete (rest as ConfigOptionMeta<'string', false>).validOptions\n if (def !== undefined && !isValidValue(def, 'boolean', false)) {\n throw new TypeError('invalid default value')\n }\n const validate =\n val ?\n (val as (v: unknown) => v is ValidValue<'boolean', false>)\n : undefined\n if (hint !== undefined) {\n throw new TypeError('cannot provide hint for flag')\n }\n return {\n ...rest,\n default: def,\n validate,\n type: 'boolean',\n multiple: false,\n }\n}\n\nfunction flagList(\n o: ConfigOptionMeta<'boolean'> = {},\n): ConfigOptionBase<'boolean', true> {\n const {\n hint,\n default: def,\n validate: val,\n ...rest\n } = o as ConfigOptionMeta<'boolean', false>\n delete (rest as ConfigOptionMeta<'string', false>).validOptions\n if (def !== undefined && !isValidValue(def, 'boolean', true)) {\n throw new TypeError('invalid default value')\n }\n const validate =\n val ?\n (val as (v: unknown) => v is ValidValue<'boolean', true>)\n : undefined\n if (hint !== undefined) {\n throw new TypeError('cannot provide hint for flag list')\n }\n return {\n ...rest,\n default: def,\n validate,\n type: 'boolean',\n multiple: true,\n }\n}\nconst toParseArgsOptionsConfig = (\n options: ConfigSet,\n): Exclude => {\n const c: Exclude = {}\n for (const longOption in options) {\n const config = options[longOption]\n /* c8 ignore start */\n if (!config) {\n throw new Error('config must be an object: ' + longOption)\n }\n /* c8 ignore start */\n if (isConfigOption(config, 'number', true)) {\n c[longOption] = {\n type: 'string',\n multiple: true,\n default: config.default?.map(c => String(c)),\n }\n } else if (isConfigOption(config, 'number', false)) {\n c[longOption] = {\n type: 'string',\n multiple: false,\n default:\n config.default === undefined ?\n undefined\n : String(config.default),\n }\n } else {\n const conf = config as\n | ConfigOptionBase<'string'>\n | ConfigOptionBase<'boolean'>\n c[longOption] = {\n type: conf.type,\n multiple: !!conf.multiple,\n default: conf.default,\n }\n }\n const clo = c[longOption] as ConfigOptionBase\n if (typeof config.short === 'string') {\n clo.short = config.short\n }\n\n if (\n config.type === 'boolean' &&\n !longOption.startsWith('no-') &&\n !options[`no-${longOption}`]\n ) {\n c[`no-${longOption}`] = {\n type: 'boolean',\n multiple: config.multiple,\n }\n }\n }\n return c\n}\n\n/**\n * A row used when generating the {@link Jack#usage} string\n */\nexport interface Row {\n left?: string\n text: string\n skipLine?: boolean\n type?: string\n}\n\n/**\n * A heading for a section in the usage, created by the jack.heading()\n * method.\n *\n * First heading is always level 1, subsequent headings default to 2.\n *\n * The level of the nearest heading level sets the indentation of the\n * description that follows.\n */\nexport interface Heading extends Row {\n type: 'heading'\n text: string\n left?: ''\n skipLine?: boolean\n level: number\n pre?: boolean\n}\nconst isHeading = (r: { type?: string }): r is Heading =>\n r.type === 'heading'\n\n/**\n * An arbitrary blob of text describing some stuff, set by the\n * jack.description() method.\n *\n * Indentation determined by level of the nearest header.\n */\nexport interface Description extends Row {\n type: 'description'\n text: string\n left?: ''\n skipLine?: boolean\n pre?: boolean\n}\n\nconst isDescription = (r: { type?: string }): r is Description =>\n r.type === 'description'\n\n/**\n * A heading or description row used when generating the {@link Jack#usage}\n * string\n */\nexport type TextRow = Heading | Description\n\n/**\n * Either a {@link TextRow} or a reference to a {@link ConfigOptionBase}\n */\nexport type UsageField =\n | TextRow\n | {\n type: 'config'\n name: string\n value: ConfigOptionBase\n }\n\n/**\n * Options provided to the {@link Jack} constructor\n */\nexport interface JackOptions {\n /**\n * Whether to allow positional arguments\n *\n * @default true\n */\n allowPositionals?: boolean\n\n /**\n * Prefix to use when reading/writing the environment variables\n *\n * If not specified, environment behavior will not be available.\n */\n envPrefix?: string\n\n /**\n * Environment object to read/write. Defaults `process.env`.\n * No effect if `envPrefix` is not set.\n */\n env?: { [k: string]: string | undefined }\n\n /**\n * A short usage string. If not provided, will be generated from the\n * options provided, but that can of course be rather verbose if\n * there are a lot of options.\n */\n usage?: string\n\n /**\n * Stop parsing flags and opts at the first positional argument.\n * This is to support cases like `cmd [flags] [options]`, where\n * each subcommand may have different options. This effectively treats\n * any positional as a `--` argument. Only relevant if `allowPositionals`\n * is true.\n *\n * To do subcommands, set this option, look at the first positional, and\n * parse the remaining positionals as appropriate.\n *\n * @default false\n */\n stopAtPositional?: boolean\n\n /**\n * Conditional `stopAtPositional`. If set to a `(string)=>boolean` function,\n * will be called with each positional argument encountered. If the function\n * returns true, then parsing will stop at that point.\n */\n stopAtPositionalTest?: (arg: string) => boolean\n}\n\n/**\n * Class returned by the {@link jack} function and all configuration\n * definition methods. This is what gets chained together.\n */\nexport class Jack {\n #configSet: C\n #shorts: { [k: string]: string }\n #options: JackOptions\n #fields: UsageField[] = []\n #env: { [k: string]: string | undefined }\n #envPrefix?: string\n #allowPositionals: boolean\n #usage?: string\n #usageMarkdown?: string\n\n constructor(options: JackOptions = {}) {\n this.#options = options\n this.#allowPositionals = options.allowPositionals !== false\n this.#env =\n this.#options.env === undefined ? process.env : this.#options.env\n this.#envPrefix = options.envPrefix\n // We need to fib a little, because it's always the same object, but it\n // starts out as having an empty config set. Then each method that adds\n // fields returns `this as Jack`\n this.#configSet = Object.create(null) as C\n this.#shorts = Object.create(null)\n }\n\n /**\n * Set the default value (which will still be overridden by env or cli)\n * as if from a parsed config file. The optional `source` param, if\n * provided, will be included in error messages if a value is invalid or\n * unknown.\n */\n setConfigValues(values: OptionsResults, source = '') {\n try {\n this.validate(values)\n } catch (er) {\n const e = er as Error\n if (source && e && typeof e === 'object') {\n if (e.cause && typeof e.cause === 'object') {\n Object.assign(e.cause, { path: source })\n } else {\n e.cause = { path: source }\n }\n }\n throw e\n }\n for (const [field, value] of Object.entries(values)) {\n const my = this.#configSet[field]\n // already validated, just for TS's benefit\n /* c8 ignore start */\n if (!my) {\n throw new Error('unexpected field in config set: ' + field, {\n cause: { found: field },\n })\n }\n /* c8 ignore stop */\n my.default = value\n }\n return this\n }\n\n /**\n * Parse a string of arguments, and return the resulting\n * `{ values, positionals }` object.\n *\n * If an {@link JackOptions#envPrefix} is set, then it will read default\n * values from the environment, and write the resulting values back\n * to the environment as well.\n *\n * Environment values always take precedence over any other value, except\n * an explicit CLI setting.\n */\n parse(args: string[] = process.argv): Parsed {\n this.loadEnvDefaults()\n const p = this.parseRaw(args)\n this.applyDefaults(p)\n this.writeEnv(p)\n return p\n }\n\n loadEnvDefaults() {\n if (this.#envPrefix) {\n for (const [field, my] of Object.entries(this.#configSet)) {\n const ek = toEnvKey(this.#envPrefix, field)\n const env = this.#env[ek]\n if (env !== undefined) {\n my.default = fromEnvVal(env, my.type, !!my.multiple, my.delim)\n }\n }\n }\n }\n\n applyDefaults(p: Parsed) {\n for (const [field, c] of Object.entries(this.#configSet)) {\n if (c.default !== undefined && !(field in p.values)) {\n //@ts-ignore\n p.values[field] = c.default\n }\n }\n }\n\n /**\n * Only parse the command line arguments passed in.\n * Does not strip off the `node script.js` bits, so it must be just the\n * arguments you wish to have parsed.\n * Does not read from or write to the environment, or set defaults.\n */\n parseRaw(args: string[]): Parsed {\n if (args === process.argv) {\n args = args.slice(\n (process as { _eval?: string })._eval !== undefined ? 1 : 2,\n )\n }\n\n const options = toParseArgsOptionsConfig(this.#configSet)\n const result = parseArgs({\n args,\n options,\n // always strict, but using our own logic\n strict: false,\n allowPositionals: this.#allowPositionals,\n tokens: true,\n })\n\n const p: Parsed = {\n values: {},\n positionals: [],\n }\n for (const token of result.tokens) {\n if (token.kind === 'positional') {\n p.positionals.push(token.value)\n if (\n this.#options.stopAtPositional ||\n this.#options.stopAtPositionalTest?.(token.value)\n ) {\n p.positionals.push(...args.slice(token.index + 1))\n break\n }\n } else if (token.kind === 'option') {\n let value: string | number | boolean | undefined = undefined\n if (token.name.startsWith('no-')) {\n const my = this.#configSet[token.name]\n const pname = token.name.substring('no-'.length)\n const pos = this.#configSet[pname]\n if (\n pos &&\n pos.type === 'boolean' &&\n (!my ||\n (my.type === 'boolean' && !!my.multiple === !!pos.multiple))\n ) {\n value = false\n token.name = pname\n }\n }\n const my = this.#configSet[token.name]\n if (!my) {\n throw new Error(\n `Unknown option '${token.rawName}'. ` +\n `To specify a positional argument starting with a '-', ` +\n `place it at the end of the command after '--', as in ` +\n `'-- ${token.rawName}'`,\n {\n cause: {\n found:\n token.rawName + (token.value ? `=${token.value}` : ''),\n },\n },\n )\n }\n if (value === undefined) {\n if (token.value === undefined) {\n if (my.type !== 'boolean') {\n throw new Error(\n `No value provided for ${token.rawName}, expected ${my.type}`,\n {\n cause: {\n name: token.rawName,\n wanted: valueType(my),\n },\n },\n )\n }\n value = true\n } else {\n if (my.type === 'boolean') {\n throw new Error(\n `Flag ${token.rawName} does not take a value, received '${token.value}'`,\n { cause: { found: token } },\n )\n }\n if (my.type === 'string') {\n value = token.value\n } else {\n value = +token.value\n if (value !== value) {\n throw new Error(\n `Invalid value '${token.value}' provided for ` +\n `'${token.rawName}' option, expected number`,\n {\n cause: {\n name: token.rawName,\n found: token.value,\n wanted: 'number',\n },\n },\n )\n }\n }\n }\n }\n if (my.multiple) {\n const pv = p.values as {\n [k: string]: (string | number | boolean)[]\n }\n const tn = pv[token.name] ?? []\n pv[token.name] = tn\n tn.push(value)\n } else {\n const pv = p.values as { [k: string]: string | number | boolean }\n pv[token.name] = value\n }\n }\n }\n\n for (const [field, value] of Object.entries(p.values)) {\n const valid = this.#configSet[field]?.validate\n const validOptions = this.#configSet[field]?.validOptions\n let cause:\n | undefined\n | {\n name: string\n found: unknown\n validOptions?: readonly string[] | readonly number[]\n }\n if (validOptions && !isValidOption(value, validOptions)) {\n cause = { name: field, found: value, validOptions: validOptions }\n }\n if (valid && !valid(value)) {\n cause = cause || { name: field, found: value }\n }\n if (cause) {\n throw new Error(\n `Invalid value provided for --${field}: ${JSON.stringify(\n value,\n )}`,\n { cause },\n )\n }\n }\n\n return p\n }\n\n /**\n * do not set fields as 'no-foo' if 'foo' exists and both are bools\n * just set foo.\n */\n #noNoFields(f: string, val: unknown, s: string = f) {\n if (!f.startsWith('no-') || typeof val !== 'boolean') return\n const yes = f.substring('no-'.length)\n // recurse so we get the core config key we care about.\n this.#noNoFields(yes, val, s)\n if (this.#configSet[yes]?.type === 'boolean') {\n throw new Error(\n `do not set '${s}', instead set '${yes}' as desired.`,\n { cause: { found: s, wanted: yes } },\n )\n }\n }\n\n /**\n * Validate that any arbitrary object is a valid configuration `values`\n * object. Useful when loading config files or other sources.\n */\n validate(o: unknown): asserts o is Parsed['values'] {\n if (!o || typeof o !== 'object') {\n throw new Error('Invalid config: not an object', {\n cause: { found: o },\n })\n }\n const opts = o as Record\n for (const field in o) {\n const value = opts[field]\n /* c8 ignore next - for TS */\n if (value === undefined) continue\n this.#noNoFields(field, value)\n const config = this.#configSet[field]\n if (!config) {\n throw new Error(`Unknown config option: ${field}`, {\n cause: { found: field },\n })\n }\n if (!isValidValue(value, config.type, !!config.multiple)) {\n throw new Error(\n `Invalid value ${valueType(\n value,\n )} for ${field}, expected ${valueType(config)}`,\n {\n cause: {\n name: field,\n found: value,\n wanted: valueType(config),\n },\n },\n )\n }\n let cause:\n | undefined\n | {\n name: string\n found: any\n validOptions?: readonly string[] | readonly number[]\n }\n if (\n config.validOptions &&\n !isValidOption(value, config.validOptions)\n ) {\n cause = {\n name: field,\n found: value,\n validOptions: config.validOptions,\n }\n }\n if (config.validate && !config.validate(value)) {\n cause = cause || { name: field, found: value }\n }\n if (cause) {\n throw new Error(`Invalid config value for ${field}: ${value}`, {\n cause,\n })\n }\n }\n }\n\n writeEnv(p: Parsed) {\n if (!this.#env || !this.#envPrefix) return\n for (const [field, value] of Object.entries(p.values)) {\n const my = this.#configSet[field]\n this.#env[toEnvKey(this.#envPrefix, field)] = toEnvVal(\n value,\n my?.delim,\n )\n }\n }\n\n /**\n * Add a heading to the usage output banner\n */\n heading(\n text: string,\n level?: 1 | 2 | 3 | 4 | 5 | 6,\n { pre = false }: { pre?: boolean } = {},\n ): Jack {\n if (level === undefined) {\n level = this.#fields.some(r => isHeading(r)) ? 2 : 1\n }\n this.#fields.push({ type: 'heading', text, level, pre })\n return this\n }\n\n /**\n * Add a long-form description to the usage output at this position.\n */\n description(text: string, { pre }: { pre?: boolean } = {}): Jack {\n this.#fields.push({ type: 'description', text, pre })\n return this\n }\n\n /**\n * Add one or more number fields.\n */\n num>(\n fields: F,\n ): Jack> {\n return this.#addFields(fields, num)\n }\n\n /**\n * Add one or more multiple number fields.\n */\n numList>(\n fields: F,\n ): Jack> {\n return this.#addFields(fields, numList)\n }\n\n /**\n * Add one or more string option fields.\n */\n opt>(\n fields: F,\n ): Jack> {\n return this.#addFields(fields, opt)\n }\n\n /**\n * Add one or more multiple string option fields.\n */\n optList>(\n fields: F,\n ): Jack> {\n return this.#addFields(fields, optList)\n }\n\n /**\n * Add one or more flag fields.\n */\n flag>(\n fields: F,\n ): Jack> {\n return this.#addFields(fields, flag)\n }\n\n /**\n * Add one or more multiple flag fields.\n */\n flagList>(\n fields: F,\n ): Jack> {\n return this.#addFields(fields, flagList)\n }\n\n /**\n * Generic field definition method. Similar to flag/flagList/number/etc,\n * but you must specify the `type` (and optionally `multiple` and `delim`)\n * fields on each one, or Jack won't know how to define them.\n */\n addFields(fields: F): Jack {\n const next = this as unknown as Jack\n for (const [name, field] of Object.entries(fields)) {\n this.#validateName(name, field)\n next.#fields.push({\n type: 'config',\n name,\n value: field as ConfigOptionBase,\n })\n }\n Object.assign(next.#configSet, fields)\n return next\n }\n\n #addFields<\n T extends ConfigType,\n M extends boolean,\n F extends ConfigMetaSet,\n >(\n fields: F,\n fn: (m: ConfigOptionMeta) => ConfigOptionBase,\n ): Jack> {\n type NextC = C & ConfigSetFromMetaSet\n const next = this as unknown as Jack\n Object.assign(\n next.#configSet,\n Object.fromEntries(\n Object.entries(fields).map(([name, field]) => {\n this.#validateName(name, field)\n const option = fn(field)\n next.#fields.push({\n type: 'config',\n name,\n value: option as ConfigOptionBase,\n })\n return [name, option]\n }),\n ),\n )\n return next\n }\n\n #validateName(name: string, field: { short?: string }) {\n if (!/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(name)) {\n throw new TypeError(\n `Invalid option name: ${name}, ` +\n `must be '-' delimited ASCII alphanumeric`,\n )\n }\n if (this.#configSet[name]) {\n throw new TypeError(`Cannot redefine option ${field}`)\n }\n if (this.#shorts[name]) {\n throw new TypeError(\n `Cannot redefine option ${name}, already ` +\n `in use for ${this.#shorts[name]}`,\n )\n }\n if (field.short) {\n if (!/^[a-zA-Z0-9]$/.test(field.short)) {\n throw new TypeError(\n `Invalid ${name} short option: ${field.short}, ` +\n 'must be 1 ASCII alphanumeric character',\n )\n }\n if (this.#shorts[field.short]) {\n throw new TypeError(\n `Invalid ${name} short option: ${field.short}, ` +\n `already in use for ${this.#shorts[field.short]}`,\n )\n }\n this.#shorts[field.short] = name\n this.#shorts[name] = name\n }\n }\n\n /**\n * Return the usage banner for the given configuration\n */\n usage(): string {\n if (this.#usage) return this.#usage\n\n let headingLevel = 1\n const ui = cliui({ width })\n const first = this.#fields[0]\n let start = first?.type === 'heading' ? 1 : 0\n if (first?.type === 'heading') {\n ui.div({\n padding: [0, 0, 0, 0],\n text: normalize(first.text),\n })\n }\n ui.div({ padding: [0, 0, 0, 0], text: 'Usage:' })\n if (this.#options.usage) {\n ui.div({\n text: this.#options.usage,\n padding: [0, 0, 0, 2],\n })\n } else {\n const cmd = basename(String(process.argv[1]))\n const shortFlags: string[] = []\n const shorts: string[][] = []\n const flags: string[] = []\n const opts: string[][] = []\n for (const [field, config] of Object.entries(this.#configSet)) {\n if (config.short) {\n if (config.type === 'boolean') shortFlags.push(config.short)\n else shorts.push([config.short, config.hint || field])\n } else {\n if (config.type === 'boolean') flags.push(field)\n else opts.push([field, config.hint || field])\n }\n }\n const sf = shortFlags.length ? ' -' + shortFlags.join('') : ''\n const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join('')\n const lf = flags.map(k => ` --${k}`).join('')\n const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join('')\n const usage = `${cmd}${sf}${so}${lf}${lo}`.trim()\n ui.div({\n text: usage,\n padding: [0, 0, 0, 2],\n })\n }\n\n ui.div({ padding: [0, 0, 0, 0], text: '' })\n const maybeDesc = this.#fields[start]\n if (maybeDesc && isDescription(maybeDesc)) {\n const print = normalize(maybeDesc.text, maybeDesc.pre)\n start++\n ui.div({ padding: [0, 0, 0, 0], text: print })\n ui.div({ padding: [0, 0, 0, 0], text: '' })\n }\n\n const { rows, maxWidth } = this.#usageRows(start)\n\n // every heading/description after the first gets indented by 2\n // extra spaces.\n for (const row of rows) {\n if (row.left) {\n // If the row is too long, don't wrap it\n // Bump the right-hand side down a line to make room\n const configIndent = indent(Math.max(headingLevel, 2))\n if (row.left.length > maxWidth - 3) {\n ui.div({ text: row.left, padding: [0, 0, 0, configIndent] })\n ui.div({ text: row.text, padding: [0, 0, 0, maxWidth] })\n } else {\n ui.div(\n {\n text: row.left,\n padding: [0, 1, 0, configIndent],\n width: maxWidth,\n },\n { padding: [0, 0, 0, 0], text: row.text },\n )\n }\n if (row.skipLine) {\n ui.div({ padding: [0, 0, 0, 0], text: '' })\n }\n } else {\n if (isHeading(row)) {\n const { level } = row\n headingLevel = level\n // only h1 and h2 have bottom padding\n // h3-h6 do not\n const b = level <= 2 ? 1 : 0\n ui.div({ ...row, padding: [0, 0, b, indent(level)] })\n } else {\n ui.div({ ...row, padding: [0, 0, 1, indent(headingLevel + 1)] })\n }\n }\n }\n\n return (this.#usage = ui.toString())\n }\n\n /**\n * Return the usage banner markdown for the given configuration\n */\n usageMarkdown(): string {\n if (this.#usageMarkdown) return this.#usageMarkdown\n\n const out: string[] = []\n\n let headingLevel = 1\n const first = this.#fields[0]\n let start = first?.type === 'heading' ? 1 : 0\n if (first?.type === 'heading') {\n out.push(`# ${normalizeOneLine(first.text)}`)\n }\n out.push('Usage:')\n if (this.#options.usage) {\n out.push(normalizeMarkdown(this.#options.usage, true))\n } else {\n const cmd = basename(String(process.argv[1]))\n const shortFlags: string[] = []\n const shorts: string[][] = []\n const flags: string[] = []\n const opts: string[][] = []\n for (const [field, config] of Object.entries(this.#configSet)) {\n if (config.short) {\n if (config.type === 'boolean') shortFlags.push(config.short)\n else shorts.push([config.short, config.hint || field])\n } else {\n if (config.type === 'boolean') flags.push(field)\n else opts.push([field, config.hint || field])\n }\n }\n const sf = shortFlags.length ? ' -' + shortFlags.join('') : ''\n const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join('')\n const lf = flags.map(k => ` --${k}`).join('')\n const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join('')\n const usage = `${cmd}${sf}${so}${lf}${lo}`.trim()\n out.push(normalizeMarkdown(usage, true))\n }\n\n const maybeDesc = this.#fields[start]\n if (maybeDesc && isDescription(maybeDesc)) {\n out.push(normalizeMarkdown(maybeDesc.text, maybeDesc.pre))\n start++\n }\n\n const { rows } = this.#usageRows(start)\n\n // heading level in markdown is number of # ahead of text\n for (const row of rows) {\n if (row.left) {\n out.push(\n '#'.repeat(headingLevel + 1) +\n ' ' +\n normalizeOneLine(row.left, true),\n )\n if (row.text) out.push(normalizeMarkdown(row.text))\n } else if (isHeading(row)) {\n const { level } = row\n headingLevel = level\n out.push(\n `${'#'.repeat(headingLevel)} ${normalizeOneLine(\n row.text,\n row.pre,\n )}`,\n )\n } else {\n out.push(normalizeMarkdown(row.text, !!(row as Description).pre))\n }\n }\n\n return (this.#usageMarkdown = out.join('\\n\\n') + '\\n')\n }\n\n #usageRows(start: number) {\n // turn each config type into a row, and figure out the width of the\n // left hand indentation for the option descriptions.\n let maxMax = Math.max(12, Math.min(26, Math.floor(width / 3)))\n let maxWidth = 8\n let prev: Row | TextRow | undefined = undefined\n const rows: (Row | TextRow)[] = []\n for (const field of this.#fields.slice(start)) {\n if (field.type !== 'config') {\n if (prev?.type === 'config') prev.skipLine = true\n prev = undefined\n field.text = normalize(field.text, !!field.pre)\n rows.push(field)\n continue\n }\n const { value } = field\n const desc = value.description || ''\n const mult = value.multiple ? 'Can be set multiple times' : ''\n const opts =\n value.validOptions?.length ?\n `Valid options:${value.validOptions.map(\n v => ` ${JSON.stringify(v)}`,\n )}`\n : ''\n const dmDelim = desc.includes('\\n') ? '\\n\\n' : '\\n'\n const extra = [opts, mult].join(dmDelim).trim()\n const text = (normalize(desc) + dmDelim + extra).trim()\n const hint =\n value.hint ||\n (value.type === 'number' ? 'n'\n : value.type === 'string' ? field.name\n : undefined)\n const short =\n !value.short ? ''\n : value.type === 'boolean' ? `-${value.short} `\n : `-${value.short}<${hint}> `\n const left =\n value.type === 'boolean' ?\n `${short}--${field.name}`\n : `${short}--${field.name}=<${hint}>`\n const row: Row = { text, left, type: 'config' }\n if (text.length > width - maxMax) {\n row.skipLine = true\n }\n if (prev && left.length > maxMax) prev.skipLine = true\n prev = row\n const len = left.length + 4\n if (len > maxWidth && len < maxMax) {\n maxWidth = len\n }\n\n rows.push(row)\n }\n\n return { rows, maxWidth }\n }\n\n /**\n * Return the configuration options as a plain object\n */\n toJSON() {\n return Object.fromEntries(\n Object.entries(this.#configSet).map(([field, def]) => [\n field,\n {\n type: def.type,\n ...(def.multiple ? { multiple: true } : {}),\n ...(def.delim ? { delim: def.delim } : {}),\n ...(def.short ? { short: def.short } : {}),\n ...(def.description ?\n { description: normalize(def.description) }\n : {}),\n ...(def.validate ? { validate: def.validate } : {}),\n ...(def.validOptions ? { validOptions: def.validOptions } : {}),\n ...(def.default !== undefined ? { default: def.default } : {}),\n ...(def.hint ? { hint: def.hint } : {}),\n },\n ]),\n )\n }\n\n /**\n * Custom printer for `util.inspect`\n */\n [inspect.custom](_: number, options: InspectOptions) {\n return `Jack ${inspect(this.toJSON(), options)}`\n }\n}\n\n// Unwrap and un-indent, so we can wrap description\n// strings however makes them look nice in the code.\nconst normalize = (s: string, pre = false) => {\n if (pre)\n // prepend a ZWSP to each line so cliui doesn't strip it.\n return s\n .split('\\n')\n .map(l => `\\u200b${l}`)\n .join('\\n')\n return s\n .split(/^\\s*```\\s*$/gm)\n .map((s, i) => {\n if (i % 2 === 1) {\n if (!s.trim()) {\n return `\\`\\`\\`\\n\\`\\`\\`\\n`\n }\n // outdent the ``` blocks, but preserve whitespace otherwise.\n const split = s.split('\\n')\n // throw out the \\n at the start and end\n split.pop()\n split.shift()\n const si = split.reduce((shortest, l) => {\n /* c8 ignore next */\n const ind = l.match(/^\\s*/)?.[0] ?? ''\n if (ind.length) return Math.min(ind.length, shortest)\n else return shortest\n }, Infinity)\n /* c8 ignore next */\n const i = isFinite(si) ? si : 0\n return (\n '\\n```\\n' +\n split.map(s => `\\u200b${s.substring(i)}`).join('\\n') +\n '\\n```\\n'\n )\n }\n return (\n s\n // remove single line breaks, except for lists\n .replace(/([^\\n])\\n[ \\t]*([^\\n])/g, (_, $1, $2) =>\n !/^[-*]/.test($2) ? `${$1} ${$2}` : `${$1}\\n${$2}`,\n )\n // normalize mid-line whitespace\n .replace(/([^\\n])[ \\t]+([^\\n])/g, '$1 $2')\n // two line breaks are enough\n .replace(/\\n{3,}/g, '\\n\\n')\n // remove any spaces at the start of a line\n .replace(/\\n[ \\t]+/g, '\\n')\n .trim()\n )\n })\n .join('\\n')\n}\n\n// normalize for markdown printing, remove leading spaces on lines\nconst normalizeMarkdown = (s: string, pre: boolean = false): string => {\n const n = normalize(s, pre).replace(/\\\\/g, '\\\\\\\\')\n return pre ?\n `\\`\\`\\`\\n${n.replace(/\\u200b/g, '')}\\n\\`\\`\\``\n : n.replace(/\\n +/g, '\\n').trim()\n}\n\nconst normalizeOneLine = (s: string, pre: boolean = false) => {\n const n = normalize(s, pre)\n .replace(/[\\s\\u200b]+/g, ' ')\n .trim()\n return pre ? `\\`${n}\\`` : n\n}\n\n/**\n * Main entry point. Create and return a {@link Jack} object.\n */\nexport const jack = (options: JackOptions = {}) => new Jack(options)\n"]} \ No newline at end of file diff --git a/node_modules/jackspeak/dist/esm/package.json b/node_modules/jackspeak/dist/esm/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/node_modules/jackspeak/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/jackspeak/dist/esm/parse-args.d.ts b/node_modules/jackspeak/dist/esm/parse-args.d.ts new file mode 100644 index 0000000..498d114 --- /dev/null +++ b/node_modules/jackspeak/dist/esm/parse-args.d.ts @@ -0,0 +1,4 @@ +/// +import * as util from 'util'; +export declare const parseArgs: typeof util.parseArgs; +//# sourceMappingURL=parse-args.d.ts.map \ No newline at end of file diff --git a/node_modules/jackspeak/dist/esm/parse-args.d.ts.map b/node_modules/jackspeak/dist/esm/parse-args.d.ts.map new file mode 100644 index 0000000..d56cb69 --- /dev/null +++ b/node_modules/jackspeak/dist/esm/parse-args.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parse-args.d.ts","sourceRoot":"","sources":["../../src/parse-args.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAoC5B,eAAO,MAAM,SAAS,uBAA6C,CAAA"} \ No newline at end of file diff --git a/node_modules/jackspeak/dist/esm/parse-args.js b/node_modules/jackspeak/dist/esm/parse-args.js new file mode 100644 index 0000000..a4be715 --- /dev/null +++ b/node_modules/jackspeak/dist/esm/parse-args.js @@ -0,0 +1,26 @@ +import * as util from 'util'; +const pv = (typeof process === 'object' && + !!process && + typeof process.version === 'string') ? + process.version + : 'v0.0.0'; +const pvs = pv + .replace(/^v/, '') + .split('.') + .map(s => parseInt(s, 10)); +/* c8 ignore start */ +const [major = 0, minor = 0] = pvs; +/* c8 ignore stop */ +let { parseArgs: pa, } = util; +/* c8 ignore start - version specific */ +if (!pa || + major < 16 || + (major === 18 && minor < 11) || + (major === 16 && minor < 19)) { + // Ignore because we will clobber it for commonjs + //@ts-ignore + pa = (await import('@pkgjs/parseargs')).parseArgs; +} +/* c8 ignore stop */ +export const parseArgs = pa; +//# sourceMappingURL=parse-args.js.map \ No newline at end of file diff --git a/node_modules/jackspeak/dist/esm/parse-args.js.map b/node_modules/jackspeak/dist/esm/parse-args.js.map new file mode 100644 index 0000000..48017f0 --- /dev/null +++ b/node_modules/jackspeak/dist/esm/parse-args.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parse-args.js","sourceRoot":"","sources":["../../src/parse-args.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAE5B,MAAM,EAAE,GACN,CACE,OAAO,OAAO,KAAK,QAAQ;IAC3B,CAAC,CAAC,OAAO;IACT,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,CACpC,CAAC,CAAC;IACD,OAAO,CAAC,OAAO;IACjB,CAAC,CAAC,QAAQ,CAAA;AACZ,MAAM,GAAG,GAAG,EAAE;KACX,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC;KACjB,KAAK,CAAC,GAAG,CAAC;KACV,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAA;AAE5B,qBAAqB;AACrB,MAAM,CAAC,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,GAAG,GAAG,CAAA;AAClC,oBAAoB;AAEpB,IAAI,EACF,SAAS,EAAE,EAAE,GACd,GAA8D,IAAI,CAAA;AAEnE,wCAAwC;AACxC,IACE,CAAC,EAAE;IACH,KAAK,GAAG,EAAE;IACV,CAAC,KAAK,KAAK,EAAE,IAAI,KAAK,GAAG,EAAE,CAAC;IAC5B,CAAC,KAAK,KAAK,EAAE,IAAI,KAAK,GAAG,EAAE,CAAC,EAC5B,CAAC;IACD,iDAAiD;IACjD,YAAY;IACZ,EAAE,GAAG,CAAC,MAAM,MAAM,CAAC,kBAAkB,CAAC,CAAC,CAAC,SAAS,CAAA;AACnD,CAAC;AACD,oBAAoB;AAEpB,MAAM,CAAC,MAAM,SAAS,GAAG,EAA0C,CAAA","sourcesContent":["import * as util from 'util'\n\nconst pv =\n (\n typeof process === 'object' &&\n !!process &&\n typeof process.version === 'string'\n ) ?\n process.version\n : 'v0.0.0'\nconst pvs = pv\n .replace(/^v/, '')\n .split('.')\n .map(s => parseInt(s, 10))\n\n/* c8 ignore start */\nconst [major = 0, minor = 0] = pvs\n/* c8 ignore stop */\n\nlet {\n parseArgs: pa,\n}: typeof import('util') | typeof import('@pkgjs/parseargs') = util\n\n/* c8 ignore start - version specific */\nif (\n !pa ||\n major < 16 ||\n (major === 18 && minor < 11) ||\n (major === 16 && minor < 19)\n) {\n // Ignore because we will clobber it for commonjs\n //@ts-ignore\n pa = (await import('@pkgjs/parseargs')).parseArgs\n}\n/* c8 ignore stop */\n\nexport const parseArgs = pa as (typeof import('util'))['parseArgs']\n"]} \ No newline at end of file diff --git a/node_modules/jackspeak/package.json b/node_modules/jackspeak/package.json new file mode 100644 index 0000000..51eaabd --- /dev/null +++ b/node_modules/jackspeak/package.json @@ -0,0 +1,95 @@ +{ + "name": "jackspeak", + "publishConfig": { + "tag": "v3-legacy" + }, + "version": "3.4.3", + "description": "A very strict and proper argument parser.", + "tshy": { + "main": true, + "exports": { + "./package.json": "./package.json", + ".": "./src/index.js" + } + }, + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "type": "module", + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "files": [ + "dist" + ], + "scripts": { + "build-examples": "for i in examples/*.js ; do node $i -h > ${i/.js/.txt}; done", + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --log-level warn", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" + }, + "license": "BlueOak-1.0.0", + "prettier": { + "experimentalTernaries": true, + "semi": false, + "printWidth": 75, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "devDependencies": { + "@types/node": "^20.7.0", + "@types/pkgjs__parseargs": "^0.10.1", + "prettier": "^3.2.5", + "tap": "^18.8.0", + "tshy": "^1.14.0", + "typedoc": "^0.25.1", + "typescript": "^5.2.2" + }, + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/jackspeak.git" + }, + "keywords": [ + "argument", + "parser", + "args", + "option", + "flag", + "cli", + "command", + "line", + "parse", + "parsing" + ], + "author": "Isaac Z. Schlueter ", + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } +} diff --git a/node_modules/lilconfig/LICENSE b/node_modules/lilconfig/LICENSE new file mode 100644 index 0000000..fd866f4 --- /dev/null +++ b/node_modules/lilconfig/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Anton Kastritskiy + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/lilconfig/package.json b/node_modules/lilconfig/package.json new file mode 100644 index 0000000..b64e55c --- /dev/null +++ b/node_modules/lilconfig/package.json @@ -0,0 +1,42 @@ +{ + "name": "lilconfig", + "version": "3.1.3", + "description": "A zero-dependency alternative to cosmiconfig", + "main": "src/index.js", + "types": "src/index.d.ts", + "scripts": { + "test": "NODE_OPTIONS=--experimental-vm-modules ./node_modules/.bin/jest --coverage", + "lint": "biome ci ./src", + "types": "tsc" + }, + "keywords": [ + "cosmiconfig", + "config", + "configuration", + "search" + ], + "files": [ + "src/index.*" + ], + "repository": { + "type": "git", + "url": "https://github.com/antonk52/lilconfig" + }, + "bugs": "https://github.com/antonk52/lilconfig/issues", + "author": "antonk52", + "license": "MIT", + "devDependencies": { + "@biomejs/biome": "^1.6.0", + "@types/jest": "^29.5.12", + "@types/node": "^14.18.63", + "@types/webpack-env": "^1.18.5", + "cosmiconfig": "^8.3.6", + "jest": "^29.7.0", + "typescript": "^5.3.3", + "uvu": "^0.5.6" + }, + "funding": "https://github.com/sponsors/antonk52", + "engines": { + "node": ">=14" + } +} diff --git a/node_modules/lilconfig/readme.md b/node_modules/lilconfig/readme.md new file mode 100644 index 0000000..99c4262 --- /dev/null +++ b/node_modules/lilconfig/readme.md @@ -0,0 +1,98 @@ +# Lilconfig ⚙️ +[![npm version](https://badge.fury.io/js/lilconfig.svg)](https://badge.fury.io/js/lilconfig) +[![install size](https://packagephobia.now.sh/badge?p=lilconfig)](https://packagephobia.now.sh/result?p=lilconfig) +[![Coverage Status](https://coveralls.io/repos/github/antonk52/lilconfig/badge.svg)](https://coveralls.io/github/antonk52/lilconfig) + +A zero-dependency alternative to [cosmiconfig](https://www.npmjs.com/package/cosmiconfig) with the same API. + +## Installation + +```sh +npm install lilconfig +``` + +## Usage + +```js +import {lilconfig, lilconfigSync} from 'lilconfig'; + +// all keys are optional +const options = { + stopDir: '/Users/you/some/dir', + searchPlaces: ['package.json', 'myapp.conf.js'], + ignoreEmptySearchPlaces: false +} + +lilconfig( + 'myapp', + options // optional +).search() // Promise + +lilconfigSync( + 'myapp', + options // optional +).load(pathToConfig) // LilconfigResult + +/** + * LilconfigResult + * { + * config: any; // your config + * filepath: string; + * } + */ +``` + +## ESM + +ESM configs can be loaded with **async API only**. Specifically `js` files in projects with `"type": "module"` in `package.json` or `mjs` files. + +## Difference to `cosmiconfig` +Lilconfig does not intend to be 100% compatible with `cosmiconfig` but tries to mimic it where possible. The key difference is **no** support for yaml files out of the box(`lilconfig` attempts to parse files with no extension as JSON instead of YAML). You can still add the support for YAML files by providing a loader, see an [example](#yaml-loader) below. + +### Options difference between the two. + +|cosmiconfig option | lilconfig | +|------------------------|-----------| +|cache | ✅ | +|loaders | ✅ | +|ignoreEmptySearchPlaces | ✅ | +|packageProp | ✅ | +|searchPlaces | ✅ | +|stopDir | ✅ | +|transform | ✅ | + +## Loaders examples + +### Yaml loader + +If you need the YAML support you can provide your own loader + +```js +import {lilconfig} from 'lilconfig'; +import yaml from 'yaml'; + +function loadYaml(filepath, content) { + return yaml.parse(content); +} + +const options = { + loaders: { + '.yaml': loadYaml, + '.yml': loadYaml, + // loader for files with no extension + noExt: loadYaml + } +}; + +lilconfig('myapp', options) + .search() + .then(result => { + result // {config, filepath} + }); +``` + +## Version correlation + +- lilconig v1 → cosmiconfig v6 +- lilconig v2 → cosmiconfig v7 +- lilconig v3 → cosmiconfig v8 diff --git a/node_modules/lilconfig/src/index.d.ts b/node_modules/lilconfig/src/index.d.ts new file mode 100644 index 0000000..fa1146b --- /dev/null +++ b/node_modules/lilconfig/src/index.d.ts @@ -0,0 +1,54 @@ +export type LilconfigResult = null | { + filepath: string; + config: any; + isEmpty?: boolean; +}; +interface OptionsBase { + cache?: boolean; + stopDir?: string; + searchPlaces?: string[]; + ignoreEmptySearchPlaces?: boolean; + packageProp?: string | string[]; +} +export type Transform = + | TransformSync + | ((result: LilconfigResult) => Promise); +export type TransformSync = (result: LilconfigResult) => LilconfigResult; +type LoaderResult = any; +export type LoaderSync = (filepath: string, content: string) => LoaderResult; +export type Loader = + | LoaderSync + | ((filepath: string, content: string) => Promise); +export type Loaders = Record; +export type LoadersSync = Record; +export interface Options extends OptionsBase { + loaders?: Loaders; + transform?: Transform; +} +export interface OptionsSync extends OptionsBase { + loaders?: LoadersSync; + transform?: TransformSync; +} +export declare const defaultLoadersSync: LoadersSync; +export declare const defaultLoaders: Loaders; +type ClearCaches = { + clearLoadCache: () => void; + clearSearchCache: () => void; + clearCaches: () => void; +}; +type AsyncSearcher = { + search(searchFrom?: string): Promise; + load(filepath: string): Promise; +} & ClearCaches; +export declare function lilconfig( + name: string, + options?: Partial, +): AsyncSearcher; +type SyncSearcher = { + search(searchFrom?: string): LilconfigResult; + load(filepath: string): LilconfigResult; +} & ClearCaches; +export declare function lilconfigSync( + name: string, + options?: OptionsSync, +): SyncSearcher; diff --git a/node_modules/lilconfig/src/index.js b/node_modules/lilconfig/src/index.js new file mode 100644 index 0000000..af7bf47 --- /dev/null +++ b/node_modules/lilconfig/src/index.js @@ -0,0 +1,460 @@ +// @ts-check +const path = require('path'); +const fs = require('fs'); +const os = require('os'); +const url = require('url'); + +const fsReadFileAsync = fs.promises.readFile; + +/** @type {(name: string, sync: boolean) => string[]} */ +function getDefaultSearchPlaces(name, sync) { + return [ + 'package.json', + `.${name}rc.json`, + `.${name}rc.js`, + `.${name}rc.cjs`, + ...(sync ? [] : [`.${name}rc.mjs`]), + `.config/${name}rc`, + `.config/${name}rc.json`, + `.config/${name}rc.js`, + `.config/${name}rc.cjs`, + ...(sync ? [] : [`.config/${name}rc.mjs`]), + `${name}.config.js`, + `${name}.config.cjs`, + ...(sync ? [] : [`${name}.config.mjs`]), + ]; +} + +/** + * @type {(p: string) => string} + * + * see #17 + * On *nix, if cwd is not under homedir, + * the last path will be '', ('/build' -> '') + * but it should be '/' actually. + * And on Windows, this will never happen. ('C:\build' -> 'C:') + */ +function parentDir(p) { + return path.dirname(p) || path.sep; +} + +/** @type {import('./index').LoaderSync} */ +const jsonLoader = (_, content) => JSON.parse(content); +// Use plain require in webpack context for dynamic import +const requireFunc = + typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require; +/** @type {import('./index').LoadersSync} */ +const defaultLoadersSync = Object.freeze({ + '.js': requireFunc, + '.json': requireFunc, + '.cjs': requireFunc, + noExt: jsonLoader, +}); +module.exports.defaultLoadersSync = defaultLoadersSync; + +/** @type {import('./index').Loader} */ +const dynamicImport = async id => { + try { + const fileUrl = url.pathToFileURL(id).href; + const mod = await import(/* webpackIgnore: true */ fileUrl); + + return mod.default; + } catch (e) { + try { + return requireFunc(id); + } catch (/** @type {any} */ requireE) { + if ( + requireE.code === 'ERR_REQUIRE_ESM' || + (requireE instanceof SyntaxError && + requireE + .toString() + .includes('Cannot use import statement outside a module')) + ) { + throw e; + } + throw requireE; + } + } +}; + +/** @type {import('./index').Loaders} */ +const defaultLoaders = Object.freeze({ + '.js': dynamicImport, + '.mjs': dynamicImport, + '.cjs': dynamicImport, + '.json': jsonLoader, + noExt: jsonLoader, +}); +module.exports.defaultLoaders = defaultLoaders; + +/** + * @param {string} name + * @param {import('./index').Options | import('./index').OptionsSync} options + * @param {boolean} sync + * @returns {Required} + */ +function getOptions(name, options, sync) { + /** @type {Required} */ + const conf = { + stopDir: os.homedir(), + searchPlaces: getDefaultSearchPlaces(name, sync), + ignoreEmptySearchPlaces: true, + cache: true, + transform: x => x, + packageProp: [name], + ...options, + loaders: { + ...(sync ? defaultLoadersSync : defaultLoaders), + ...options.loaders, + }, + }; + conf.searchPlaces.forEach(place => { + const key = path.extname(place) || 'noExt'; + const loader = conf.loaders[key]; + if (!loader) { + throw new Error(`Missing loader for extension "${place}"`); + } + + if (typeof loader !== 'function') { + throw new Error( + `Loader for extension "${place}" is not a function: Received ${typeof loader}.`, + ); + } + }); + + return conf; +} + +/** @type {(props: string | string[], obj: Record) => unknown} */ +function getPackageProp(props, obj) { + if (typeof props === 'string' && props in obj) return obj[props]; + return ( + (Array.isArray(props) ? props : props.split('.')).reduce( + (acc, prop) => (acc === undefined ? acc : acc[prop]), + obj, + ) || null + ); +} + +/** @param {string} filepath */ +function validateFilePath(filepath) { + if (!filepath) throw new Error('load must pass a non-empty string'); +} + +/** @type {(loader: import('./index').Loader, ext: string) => void} */ +function validateLoader(loader, ext) { + if (!loader) throw new Error(`No loader specified for extension "${ext}"`); + if (typeof loader !== 'function') throw new Error('loader is not a function'); +} + +/** @type {(enableCache: boolean) => (c: Map, filepath: string, res: T) => T} */ +const makeEmplace = enableCache => (c, filepath, res) => { + if (enableCache) c.set(filepath, res); + return res; +}; + +/** @type {import('./index').lilconfig} */ +module.exports.lilconfig = function lilconfig(name, options) { + const { + ignoreEmptySearchPlaces, + loaders, + packageProp, + searchPlaces, + stopDir, + transform, + cache, + } = getOptions(name, options ?? {}, false); + const searchCache = new Map(); + const loadCache = new Map(); + const emplace = makeEmplace(cache); + + return { + async search(searchFrom = process.cwd()) { + /** @type {import('./index').LilconfigResult} */ + const result = { + config: null, + filepath: '', + }; + + /** @type {Set} */ + const visited = new Set(); + let dir = searchFrom; + dirLoop: while (true) { + if (cache) { + const r = searchCache.get(dir); + if (r !== undefined) { + for (const p of visited) searchCache.set(p, r); + return r; + } + visited.add(dir); + } + + for (const searchPlace of searchPlaces) { + const filepath = path.join(dir, searchPlace); + try { + await fs.promises.access(filepath); + } catch { + continue; + } + const content = String(await fsReadFileAsync(filepath)); + const loaderKey = path.extname(searchPlace) || 'noExt'; + const loader = loaders[loaderKey]; + + // handle package.json + if (searchPlace === 'package.json') { + const pkg = await loader(filepath, content); + const maybeConfig = getPackageProp(packageProp, pkg); + if (maybeConfig != null) { + result.config = maybeConfig; + result.filepath = filepath; + break dirLoop; + } + + continue; + } + + // handle other type of configs + const isEmpty = content.trim() === ''; + if (isEmpty && ignoreEmptySearchPlaces) continue; + + if (isEmpty) { + result.isEmpty = true; + result.config = undefined; + } else { + validateLoader(loader, loaderKey); + result.config = await loader(filepath, content); + } + result.filepath = filepath; + break dirLoop; + } + if (dir === stopDir || dir === parentDir(dir)) break dirLoop; + dir = parentDir(dir); + } + + const transformed = + // not found + result.filepath === '' && result.config === null + ? transform(null) + : transform(result); + + if (cache) { + for (const p of visited) searchCache.set(p, transformed); + } + + return transformed; + }, + async load(filepath) { + validateFilePath(filepath); + const absPath = path.resolve(process.cwd(), filepath); + if (cache && loadCache.has(absPath)) { + return loadCache.get(absPath); + } + const {base, ext} = path.parse(absPath); + const loaderKey = ext || 'noExt'; + const loader = loaders[loaderKey]; + validateLoader(loader, loaderKey); + const content = String(await fsReadFileAsync(absPath)); + + if (base === 'package.json') { + const pkg = await loader(absPath, content); + return emplace( + loadCache, + absPath, + transform({ + config: getPackageProp(packageProp, pkg), + filepath: absPath, + }), + ); + } + /** @type {import('./index').LilconfigResult} */ + const result = { + config: null, + filepath: absPath, + }; + // handle other type of configs + const isEmpty = content.trim() === ''; + if (isEmpty && ignoreEmptySearchPlaces) + return emplace( + loadCache, + absPath, + transform({ + config: undefined, + filepath: absPath, + isEmpty: true, + }), + ); + + // cosmiconfig returns undefined for empty files + result.config = isEmpty ? undefined : await loader(absPath, content); + + return emplace( + loadCache, + absPath, + transform(isEmpty ? {...result, isEmpty, config: undefined} : result), + ); + }, + clearLoadCache() { + if (cache) loadCache.clear(); + }, + clearSearchCache() { + if (cache) searchCache.clear(); + }, + clearCaches() { + if (cache) { + loadCache.clear(); + searchCache.clear(); + } + }, + }; +}; + +/** @type {import('./index').lilconfigSync} */ +module.exports.lilconfigSync = function lilconfigSync(name, options) { + const { + ignoreEmptySearchPlaces, + loaders, + packageProp, + searchPlaces, + stopDir, + transform, + cache, + } = getOptions(name, options ?? {}, true); + const searchCache = new Map(); + const loadCache = new Map(); + const emplace = makeEmplace(cache); + + return { + search(searchFrom = process.cwd()) { + /** @type {import('./index').LilconfigResult} */ + const result = { + config: null, + filepath: '', + }; + + /** @type {Set} */ + const visited = new Set(); + let dir = searchFrom; + dirLoop: while (true) { + if (cache) { + const r = searchCache.get(dir); + if (r !== undefined) { + for (const p of visited) searchCache.set(p, r); + return r; + } + visited.add(dir); + } + + for (const searchPlace of searchPlaces) { + const filepath = path.join(dir, searchPlace); + try { + fs.accessSync(filepath); + } catch { + continue; + } + const loaderKey = path.extname(searchPlace) || 'noExt'; + const loader = loaders[loaderKey]; + const content = String(fs.readFileSync(filepath)); + + // handle package.json + if (searchPlace === 'package.json') { + const pkg = loader(filepath, content); + const maybeConfig = getPackageProp(packageProp, pkg); + if (maybeConfig != null) { + result.config = maybeConfig; + result.filepath = filepath; + break dirLoop; + } + + continue; + } + + // handle other type of configs + const isEmpty = content.trim() === ''; + if (isEmpty && ignoreEmptySearchPlaces) continue; + + if (isEmpty) { + result.isEmpty = true; + result.config = undefined; + } else { + validateLoader(loader, loaderKey); + result.config = loader(filepath, content); + } + result.filepath = filepath; + break dirLoop; + } + if (dir === stopDir || dir === parentDir(dir)) break dirLoop; + dir = parentDir(dir); + } + + const transformed = + // not found + result.filepath === '' && result.config === null + ? transform(null) + : transform(result); + + if (cache) { + for (const p of visited) searchCache.set(p, transformed); + } + + return transformed; + }, + load(filepath) { + validateFilePath(filepath); + const absPath = path.resolve(process.cwd(), filepath); + if (cache && loadCache.has(absPath)) { + return loadCache.get(absPath); + } + const {base, ext} = path.parse(absPath); + const loaderKey = ext || 'noExt'; + const loader = loaders[loaderKey]; + validateLoader(loader, loaderKey); + + const content = String(fs.readFileSync(absPath)); + + if (base === 'package.json') { + const pkg = loader(absPath, content); + return transform({ + config: getPackageProp(packageProp, pkg), + filepath: absPath, + }); + } + const result = { + config: null, + filepath: absPath, + }; + // handle other type of configs + const isEmpty = content.trim() === ''; + if (isEmpty && ignoreEmptySearchPlaces) + return emplace( + loadCache, + absPath, + transform({ + filepath: absPath, + config: undefined, + isEmpty: true, + }), + ); + + // cosmiconfig returns undefined for empty files + result.config = isEmpty ? undefined : loader(absPath, content); + + return emplace( + loadCache, + absPath, + transform(isEmpty ? {...result, isEmpty, config: undefined} : result), + ); + }, + clearLoadCache() { + if (cache) loadCache.clear(); + }, + clearSearchCache() { + if (cache) searchCache.clear(); + }, + clearCaches() { + if (cache) { + loadCache.clear(); + searchCache.clear(); + } + }, + }; +}; diff --git a/node_modules/lines-and-columns/LICENSE b/node_modules/lines-and-columns/LICENSE new file mode 100644 index 0000000..12978ec --- /dev/null +++ b/node_modules/lines-and-columns/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Brian Donovan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/lines-and-columns/README.md b/node_modules/lines-and-columns/README.md new file mode 100644 index 0000000..fa90223 --- /dev/null +++ b/node_modules/lines-and-columns/README.md @@ -0,0 +1,33 @@ +# lines-and-columns + +Maps lines and columns to character offsets and back. This is useful for parsers +and other text processors that deal in character ranges but process text with +meaningful lines and columns. + +## Install + +``` +$ npm install [--save] lines-and-columns +``` + +## Usage + +```js +import { LinesAndColumns } from 'lines-and-columns' + +const lines = new LinesAndColumns( + `table { + border: 0 +}` +) + +lines.locationForIndex(9) +// { line: 1, column: 1 } + +lines.indexForLocation({ line: 1, column: 2 }) +// 10 +``` + +## License + +MIT diff --git a/node_modules/lines-and-columns/build/index.d.ts b/node_modules/lines-and-columns/build/index.d.ts new file mode 100644 index 0000000..459bc1f --- /dev/null +++ b/node_modules/lines-and-columns/build/index.d.ts @@ -0,0 +1,13 @@ +export declare type SourceLocation = { + line: number; + column: number; +}; +export declare class LinesAndColumns { + private string; + private offsets; + constructor(string: string); + locationForIndex(index: number): SourceLocation | null; + indexForLocation(location: SourceLocation): number | null; + private lengthOfLine; +} +export default LinesAndColumns; diff --git a/node_modules/lines-and-columns/build/index.js b/node_modules/lines-and-columns/build/index.js new file mode 100644 index 0000000..5117cad --- /dev/null +++ b/node_modules/lines-and-columns/build/index.js @@ -0,0 +1,62 @@ +"use strict"; +exports.__esModule = true; +exports.LinesAndColumns = void 0; +var LF = '\n'; +var CR = '\r'; +var LinesAndColumns = /** @class */ (function () { + function LinesAndColumns(string) { + this.string = string; + var offsets = [0]; + for (var offset = 0; offset < string.length;) { + switch (string[offset]) { + case LF: + offset += LF.length; + offsets.push(offset); + break; + case CR: + offset += CR.length; + if (string[offset] === LF) { + offset += LF.length; + } + offsets.push(offset); + break; + default: + offset++; + break; + } + } + this.offsets = offsets; + } + LinesAndColumns.prototype.locationForIndex = function (index) { + if (index < 0 || index > this.string.length) { + return null; + } + var line = 0; + var offsets = this.offsets; + while (offsets[line + 1] <= index) { + line++; + } + var column = index - offsets[line]; + return { line: line, column: column }; + }; + LinesAndColumns.prototype.indexForLocation = function (location) { + var line = location.line, column = location.column; + if (line < 0 || line >= this.offsets.length) { + return null; + } + if (column < 0 || column > this.lengthOfLine(line)) { + return null; + } + return this.offsets[line] + column; + }; + LinesAndColumns.prototype.lengthOfLine = function (line) { + var offset = this.offsets[line]; + var nextOffset = line === this.offsets.length - 1 + ? this.string.length + : this.offsets[line + 1]; + return nextOffset - offset; + }; + return LinesAndColumns; +}()); +exports.LinesAndColumns = LinesAndColumns; +exports["default"] = LinesAndColumns; diff --git a/node_modules/lines-and-columns/package.json b/node_modules/lines-and-columns/package.json new file mode 100644 index 0000000..a12eb6b --- /dev/null +++ b/node_modules/lines-and-columns/package.json @@ -0,0 +1,49 @@ +{ + "name": "lines-and-columns", + "version": "1.2.4", + "description": "Maps lines and columns to character offsets and back.", + "keywords": [ + "lines", + "columns", + "parser" + ], + "homepage": "https://github.com/eventualbuddha/lines-and-columns#readme", + "bugs": { + "url": "https://github.com/eventualbuddha/lines-and-columns/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/eventualbuddha/lines-and-columns.git" + }, + "license": "MIT", + "author": "Brian Donovan ", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "files": [ + "build" + ], + "scripts": { + "build:watch": "tsc --build tsconfig.build.json --watch", + "lint": "eslint .", + "lint:fix": "eslint . --fix", + "test": "is-ci test:coverage test:watch", + "test:coverage": "jest --coverage", + "test:watch": "jest --watch" + }, + "devDependencies": { + "@types/jest": "^27.0.3", + "@types/node": "^16.11.9", + "@typescript-eslint/eslint-plugin": "^5.4.0", + "@typescript-eslint/parser": "^5.4.0", + "esbuild": "^0.13.15", + "esbuild-runner": "^2.2.1", + "eslint": "^8.2.0", + "eslint-config-prettier": "^8.3.0", + "eslint-plugin-prettier": "^4.0.0", + "is-ci-cli": "^2.2.0", + "jest": "^27.3.1", + "prettier": "^2.4.1", + "semantic-release": "^18.0.0", + "typescript": "^4.5.2" + } +} diff --git a/node_modules/lru-cache/LICENSE b/node_modules/lru-cache/LICENSE new file mode 100644 index 0000000..f785757 --- /dev/null +++ b/node_modules/lru-cache/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2010-2023 Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/lru-cache/README.md b/node_modules/lru-cache/README.md new file mode 100644 index 0000000..931822f --- /dev/null +++ b/node_modules/lru-cache/README.md @@ -0,0 +1,331 @@ +# lru-cache + +A cache object that deletes the least-recently-used items. + +Specify a max number of the most recently used items that you +want to keep, and this cache will keep that many of the most +recently accessed items. + +This is not primarily a TTL cache, and does not make strong TTL +guarantees. There is no preemptive pruning of expired items by +default, but you _may_ set a TTL on the cache or on a single +`set`. If you do so, it will treat expired items as missing, and +delete them when fetched. If you are more interested in TTL +caching than LRU caching, check out +[@isaacs/ttlcache](http://npm.im/@isaacs/ttlcache). + +As of version 7, this is one of the most performant LRU +implementations available in JavaScript, and supports a wide +diversity of use cases. However, note that using some of the +features will necessarily impact performance, by causing the +cache to have to do more work. See the "Performance" section +below. + +## Installation + +```bash +npm install lru-cache --save +``` + +## Usage + +```js +// hybrid module, either works +import { LRUCache } from 'lru-cache' +// or: +const { LRUCache } = require('lru-cache') +// or in minified form for web browsers: +import { LRUCache } from 'http://unpkg.com/lru-cache@9/dist/mjs/index.min.mjs' + +// At least one of 'max', 'ttl', or 'maxSize' is required, to prevent +// unsafe unbounded storage. +// +// In most cases, it's best to specify a max for performance, so all +// the required memory allocation is done up-front. +// +// All the other options are optional, see the sections below for +// documentation on what each one does. Most of them can be +// overridden for specific items in get()/set() +const options = { + max: 500, + + // for use with tracking overall storage size + maxSize: 5000, + sizeCalculation: (value, key) => { + return 1 + }, + + // for use when you need to clean up something when objects + // are evicted from the cache + dispose: (value, key) => { + freeFromMemoryOrWhatever(value) + }, + + // how long to live in ms + ttl: 1000 * 60 * 5, + + // return stale items before removing from cache? + allowStale: false, + + updateAgeOnGet: false, + updateAgeOnHas: false, + + // async method to use for cache.fetch(), for + // stale-while-revalidate type of behavior + fetchMethod: async ( + key, + staleValue, + { options, signal, context } + ) => {}, +} + +const cache = new LRUCache(options) + +cache.set('key', 'value') +cache.get('key') // "value" + +// non-string keys ARE fully supported +// but note that it must be THE SAME object, not +// just a JSON-equivalent object. +var someObject = { a: 1 } +cache.set(someObject, 'a value') +// Object keys are not toString()-ed +cache.set('[object Object]', 'a different value') +assert.equal(cache.get(someObject), 'a value') +// A similar object with same keys/values won't work, +// because it's a different object identity +assert.equal(cache.get({ a: 1 }), undefined) + +cache.clear() // empty the cache +``` + +If you put more stuff in the cache, then less recently used items +will fall out. That's what an LRU cache is. + +For full description of the API and all options, please see [the +LRUCache typedocs](https://isaacs.github.io/node-lru-cache/) + +## Storage Bounds Safety + +This implementation aims to be as flexible as possible, within +the limits of safe memory consumption and optimal performance. + +At initial object creation, storage is allocated for `max` items. +If `max` is set to zero, then some performance is lost, and item +count is unbounded. Either `maxSize` or `ttl` _must_ be set if +`max` is not specified. + +If `maxSize` is set, then this creates a safe limit on the +maximum storage consumed, but without the performance benefits of +pre-allocation. When `maxSize` is set, every item _must_ provide +a size, either via the `sizeCalculation` method provided to the +constructor, or via a `size` or `sizeCalculation` option provided +to `cache.set()`. The size of every item _must_ be a positive +integer. + +If neither `max` nor `maxSize` are set, then `ttl` tracking must +be enabled. Note that, even when tracking item `ttl`, items are +_not_ preemptively deleted when they become stale, unless +`ttlAutopurge` is enabled. Instead, they are only purged the +next time the key is requested. Thus, if `ttlAutopurge`, `max`, +and `maxSize` are all not set, then the cache will potentially +grow unbounded. + +In this case, a warning is printed to standard error. Future +versions may require the use of `ttlAutopurge` if `max` and +`maxSize` are not specified. + +If you truly wish to use a cache that is bound _only_ by TTL +expiration, consider using a `Map` object, and calling +`setTimeout` to delete entries when they expire. It will perform +much better than an LRU cache. + +Here is an implementation you may use, under the same +[license](./LICENSE) as this package: + +```js +// a storage-unbounded ttl cache that is not an lru-cache +const cache = { + data: new Map(), + timers: new Map(), + set: (k, v, ttl) => { + if (cache.timers.has(k)) { + clearTimeout(cache.timers.get(k)) + } + cache.timers.set( + k, + setTimeout(() => cache.delete(k), ttl) + ) + cache.data.set(k, v) + }, + get: k => cache.data.get(k), + has: k => cache.data.has(k), + delete: k => { + if (cache.timers.has(k)) { + clearTimeout(cache.timers.get(k)) + } + cache.timers.delete(k) + return cache.data.delete(k) + }, + clear: () => { + cache.data.clear() + for (const v of cache.timers.values()) { + clearTimeout(v) + } + cache.timers.clear() + }, +} +``` + +If that isn't to your liking, check out +[@isaacs/ttlcache](http://npm.im/@isaacs/ttlcache). + +## Storing Undefined Values + +This cache never stores undefined values, as `undefined` is used +internally in a few places to indicate that a key is not in the +cache. + +You may call `cache.set(key, undefined)`, but this is just +an alias for `cache.delete(key)`. Note that this has the effect +that `cache.has(key)` will return _false_ after setting it to +undefined. + +```js +cache.set(myKey, undefined) +cache.has(myKey) // false! +``` + +If you need to track `undefined` values, and still note that the +key is in the cache, an easy workaround is to use a sigil object +of your own. + +```js +import { LRUCache } from 'lru-cache' +const undefinedValue = Symbol('undefined') +const cache = new LRUCache(...) +const mySet = (key, value) => + cache.set(key, value === undefined ? undefinedValue : value) +const myGet = (key, value) => { + const v = cache.get(key) + return v === undefinedValue ? undefined : v +} +``` + +## Performance + +As of January 2022, version 7 of this library is one of the most +performant LRU cache implementations in JavaScript. + +Benchmarks can be extremely difficult to get right. In +particular, the performance of set/get/delete operations on +objects will vary _wildly_ depending on the type of key used. V8 +is highly optimized for objects with keys that are short strings, +especially integer numeric strings. Thus any benchmark which +tests _solely_ using numbers as keys will tend to find that an +object-based approach performs the best. + +Note that coercing _anything_ to strings to use as object keys is +unsafe, unless you can be 100% certain that no other type of +value will be used. For example: + +```js +const myCache = {} +const set = (k, v) => (myCache[k] = v) +const get = k => myCache[k] + +set({}, 'please hang onto this for me') +set('[object Object]', 'oopsie') +``` + +Also beware of "Just So" stories regarding performance. Garbage +collection of large (especially: deep) object graphs can be +incredibly costly, with several "tipping points" where it +increases exponentially. As a result, putting that off until +later can make it much worse, and less predictable. If a library +performs well, but only in a scenario where the object graph is +kept shallow, then that won't help you if you are using large +objects as keys. + +In general, when attempting to use a library to improve +performance (such as a cache like this one), it's best to choose +an option that will perform well in the sorts of scenarios where +you'll actually use it. + +This library is optimized for repeated gets and minimizing +eviction time, since that is the expected need of a LRU. Set +operations are somewhat slower on average than a few other +options, in part because of that optimization. It is assumed +that you'll be caching some costly operation, ideally as rarely +as possible, so optimizing set over get would be unwise. + +If performance matters to you: + +1. If it's at all possible to use small integer values as keys, + and you can guarantee that no other types of values will be + used as keys, then do that, and use a cache such as + [lru-fast](https://npmjs.com/package/lru-fast), or + [mnemonist's + LRUCache](https://yomguithereal.github.io/mnemonist/lru-cache) + which uses an Object as its data store. + +2. Failing that, if at all possible, use short non-numeric + strings (ie, less than 256 characters) as your keys, and use + [mnemonist's + LRUCache](https://yomguithereal.github.io/mnemonist/lru-cache). + +3. If the types of your keys will be anything else, especially + long strings, strings that look like floats, objects, or some + mix of types, or if you aren't sure, then this library will + work well for you. + + If you do not need the features that this library provides + (like asynchronous fetching, a variety of TTL staleness + options, and so on), then [mnemonist's + LRUMap](https://yomguithereal.github.io/mnemonist/lru-map) is + a very good option, and just slightly faster than this module + (since it does considerably less). + +4. Do not use a `dispose` function, size tracking, or especially + ttl behavior, unless absolutely needed. These features are + convenient, and necessary in some use cases, and every attempt + has been made to make the performance impact minimal, but it + isn't nothing. + +## Breaking Changes in Version 7 + +This library changed to a different algorithm and internal data +structure in version 7, yielding significantly better +performance, albeit with some subtle changes as a result. + +If you were relying on the internals of LRUCache in version 6 or +before, it probably will not work in version 7 and above. + +## Breaking Changes in Version 8 + +- The `fetchContext` option was renamed to `context`, and may no + longer be set on the cache instance itself. +- Rewritten in TypeScript, so pretty much all the types moved + around a lot. +- The AbortController/AbortSignal polyfill was removed. For this + reason, **Node version 16.14.0 or higher is now required**. +- Internal properties were moved to actual private class + properties. +- Keys and values must not be `null` or `undefined`. +- Minified export available at `'lru-cache/min'`, for both CJS + and MJS builds. + +## Breaking Changes in Version 9 + +- Named export only, no default export. +- AbortController polyfill returned, albeit with a warning when + used. + +## Breaking Changes in Version 10 + +- `cache.fetch()` return type is now `Promise` + instead of `Promise`. This is an irrelevant change + practically speaking, but can require changes for TypeScript + users. + +For more info, see the [change log](CHANGELOG.md). diff --git a/node_modules/lru-cache/dist/commonjs/index.d.ts b/node_modules/lru-cache/dist/commonjs/index.d.ts new file mode 100644 index 0000000..f59de76 --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/index.d.ts @@ -0,0 +1,1277 @@ +/** + * @module LRUCache + */ +declare const TYPE: unique symbol; +export type PosInt = number & { + [TYPE]: 'Positive Integer'; +}; +export type Index = number & { + [TYPE]: 'LRUCache Index'; +}; +export type UintArray = Uint8Array | Uint16Array | Uint32Array; +export type NumberArray = UintArray | number[]; +declare class ZeroArray extends Array { + constructor(size: number); +} +export type { ZeroArray }; +export type { Stack }; +export type StackLike = Stack | Index[]; +declare class Stack { + #private; + heap: NumberArray; + length: number; + static create(max: number): StackLike; + constructor(max: number, HeapCls: { + new (n: number): NumberArray; + }); + push(n: Index): void; + pop(): Index; +} +/** + * Promise representing an in-progress {@link LRUCache#fetch} call + */ +export type BackgroundFetch = Promise & { + __returned: BackgroundFetch | undefined; + __abortController: AbortController; + __staleWhileFetching: V | undefined; +}; +export type DisposeTask = [ + value: V, + key: K, + reason: LRUCache.DisposeReason +]; +export declare namespace LRUCache { + /** + * An integer greater than 0, reflecting the calculated size of items + */ + type Size = number; + /** + * Integer greater than 0, representing some number of milliseconds, or the + * time at which a TTL started counting from. + */ + type Milliseconds = number; + /** + * An integer greater than 0, reflecting a number of items + */ + type Count = number; + /** + * The reason why an item was removed from the cache, passed + * to the {@link Disposer} methods. + * + * - `evict`: The item was evicted because it is the least recently used, + * and the cache is full. + * - `set`: A new value was set, overwriting the old value being disposed. + * - `delete`: The item was explicitly deleted, either by calling + * {@link LRUCache#delete}, {@link LRUCache#clear}, or + * {@link LRUCache#set} with an undefined value. + * - `expire`: The item was removed due to exceeding its TTL. + * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned + * `undefined` or was aborted, causing the item to be deleted. + */ + type DisposeReason = 'evict' | 'set' | 'delete' | 'expire' | 'fetch'; + /** + * A method called upon item removal, passed as the + * {@link OptionsBase.dispose} and/or + * {@link OptionsBase.disposeAfter} options. + */ + type Disposer = (value: V, key: K, reason: DisposeReason) => void; + /** + * A function that returns the effective calculated size + * of an entry in the cache. + */ + type SizeCalculator = (value: V, key: K) => Size; + /** + * Options provided to the + * {@link OptionsBase.fetchMethod} function. + */ + interface FetcherOptions { + signal: AbortSignal; + options: FetcherFetchOptions; + /** + * Object provided in the {@link FetchOptions.context} option to + * {@link LRUCache#fetch} + */ + context: FC; + } + /** + * Occasionally, it may be useful to track the internal behavior of the + * cache, particularly for logging, debugging, or for behavior within the + * `fetchMethod`. To do this, you can pass a `status` object to the + * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set}, + * {@link LRUCache#memo}, and {@link LRUCache#has} methods. + * + * The `status` option should be a plain JavaScript object. The following + * fields will be set on it appropriately, depending on the situation. + */ + interface Status { + /** + * The status of a set() operation. + * + * - add: the item was not found in the cache, and was added + * - update: the item was in the cache, with the same value provided + * - replace: the item was in the cache, and replaced + * - miss: the item was not added to the cache for some reason + */ + set?: 'add' | 'update' | 'replace' | 'miss'; + /** + * the ttl stored for the item, or undefined if ttls are not used. + */ + ttl?: Milliseconds; + /** + * the start time for the item, or undefined if ttls are not used. + */ + start?: Milliseconds; + /** + * The timestamp used for TTL calculation + */ + now?: Milliseconds; + /** + * the remaining ttl for the item, or undefined if ttls are not used. + */ + remainingTTL?: Milliseconds; + /** + * The calculated size for the item, if sizes are used. + */ + entrySize?: Size; + /** + * The total calculated size of the cache, if sizes are used. + */ + totalCalculatedSize?: Size; + /** + * A flag indicating that the item was not stored, due to exceeding the + * {@link OptionsBase.maxEntrySize} + */ + maxEntrySizeExceeded?: true; + /** + * The old value, specified in the case of `set:'update'` or + * `set:'replace'` + */ + oldValue?: V; + /** + * The results of a {@link LRUCache#has} operation + * + * - hit: the item was found in the cache + * - stale: the item was found in the cache, but is stale + * - miss: the item was not found in the cache + */ + has?: 'hit' | 'stale' | 'miss'; + /** + * The status of a {@link LRUCache#fetch} operation. + * Note that this can change as the underlying fetch() moves through + * various states. + * + * - inflight: there is another fetch() for this key which is in process + * - get: there is no {@link OptionsBase.fetchMethod}, so + * {@link LRUCache#get} was called. + * - miss: the item is not in cache, and will be fetched. + * - hit: the item is in the cache, and was resolved immediately. + * - stale: the item is in the cache, but stale. + * - refresh: the item is in the cache, and not stale, but + * {@link FetchOptions.forceRefresh} was specified. + */ + fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'; + /** + * The {@link OptionsBase.fetchMethod} was called + */ + fetchDispatched?: true; + /** + * The cached value was updated after a successful call to + * {@link OptionsBase.fetchMethod} + */ + fetchUpdated?: true; + /** + * The reason for a fetch() rejection. Either the error raised by the + * {@link OptionsBase.fetchMethod}, or the reason for an + * AbortSignal. + */ + fetchError?: Error; + /** + * The fetch received an abort signal + */ + fetchAborted?: true; + /** + * The abort signal received was ignored, and the fetch was allowed to + * continue. + */ + fetchAbortIgnored?: true; + /** + * The fetchMethod promise resolved successfully + */ + fetchResolved?: true; + /** + * The fetchMethod promise was rejected + */ + fetchRejected?: true; + /** + * The status of a {@link LRUCache#get} operation. + * + * - fetching: The item is currently being fetched. If a previous value + * is present and allowed, that will be returned. + * - stale: The item is in the cache, and is stale. + * - hit: the item is in the cache + * - miss: the item is not in the cache + */ + get?: 'stale' | 'hit' | 'miss'; + /** + * A fetch or get operation returned a stale value. + */ + returnedStale?: true; + } + /** + * options which override the options set in the LRUCache constructor + * when calling {@link LRUCache#fetch}. + * + * This is the union of {@link GetOptions} and {@link SetOptions}, plus + * {@link OptionsBase.noDeleteOnFetchRejection}, + * {@link OptionsBase.allowStaleOnFetchRejection}, + * {@link FetchOptions.forceRefresh}, and + * {@link FetcherOptions.context} + * + * Any of these may be modified in the {@link OptionsBase.fetchMethod} + * function, but the {@link GetOptions} fields will of course have no + * effect, as the {@link LRUCache#get} call already happened by the time + * the fetchMethod is called. + */ + interface FetcherFetchOptions extends Pick, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet' | 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL' | 'noDeleteOnFetchRejection' | 'allowStaleOnFetchRejection' | 'ignoreFetchAbort' | 'allowStaleOnFetchAbort'> { + status?: Status; + size?: Size; + } + /** + * Options that may be passed to the {@link LRUCache#fetch} method. + */ + interface FetchOptions extends FetcherFetchOptions { + /** + * Set to true to force a re-load of the existing data, even if it + * is not yet stale. + */ + forceRefresh?: boolean; + /** + * Context provided to the {@link OptionsBase.fetchMethod} as + * the {@link FetcherOptions.context} param. + * + * If the FC type is specified as unknown (the default), + * undefined or void, then this is optional. Otherwise, it will + * be required. + */ + context?: FC; + signal?: AbortSignal; + status?: Status; + } + /** + * Options provided to {@link LRUCache#fetch} when the FC type is something + * other than `unknown`, `undefined`, or `void` + */ + interface FetchOptionsWithContext extends FetchOptions { + context: FC; + } + /** + * Options provided to {@link LRUCache#fetch} when the FC type is + * `undefined` or `void` + */ + interface FetchOptionsNoContext extends FetchOptions { + context?: undefined; + } + interface MemoOptions extends Pick, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet' | 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL' | 'noDeleteOnFetchRejection' | 'allowStaleOnFetchRejection' | 'ignoreFetchAbort' | 'allowStaleOnFetchAbort'> { + /** + * Set to true to force a re-load of the existing data, even if it + * is not yet stale. + */ + forceRefresh?: boolean; + /** + * Context provided to the {@link OptionsBase.memoMethod} as + * the {@link MemoizerOptions.context} param. + * + * If the FC type is specified as unknown (the default), + * undefined or void, then this is optional. Otherwise, it will + * be required. + */ + context?: FC; + status?: Status; + } + /** + * Options provided to {@link LRUCache#memo} when the FC type is something + * other than `unknown`, `undefined`, or `void` + */ + interface MemoOptionsWithContext extends MemoOptions { + context: FC; + } + /** + * Options provided to {@link LRUCache#memo} when the FC type is + * `undefined` or `void` + */ + interface MemoOptionsNoContext extends MemoOptions { + context?: undefined; + } + /** + * Options provided to the + * {@link OptionsBase.memoMethod} function. + */ + interface MemoizerOptions { + options: MemoizerMemoOptions; + /** + * Object provided in the {@link MemoOptions.context} option to + * {@link LRUCache#memo} + */ + context: FC; + } + /** + * options which override the options set in the LRUCache constructor + * when calling {@link LRUCache#memo}. + * + * This is the union of {@link GetOptions} and {@link SetOptions}, plus + * {@link MemoOptions.forceRefresh}, and + * {@link MemoerOptions.context} + * + * Any of these may be modified in the {@link OptionsBase.memoMethod} + * function, but the {@link GetOptions} fields will of course have no + * effect, as the {@link LRUCache#get} call already happened by the time + * the memoMethod is called. + */ + interface MemoizerMemoOptions extends Pick, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet' | 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'> { + status?: Status; + size?: Size; + start?: Milliseconds; + } + /** + * Options that may be passed to the {@link LRUCache#has} method. + */ + interface HasOptions extends Pick, 'updateAgeOnHas'> { + status?: Status; + } + /** + * Options that may be passed to the {@link LRUCache#get} method. + */ + interface GetOptions extends Pick, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'> { + status?: Status; + } + /** + * Options that may be passed to the {@link LRUCache#peek} method. + */ + interface PeekOptions extends Pick, 'allowStale'> { + } + /** + * Options that may be passed to the {@link LRUCache#set} method. + */ + interface SetOptions extends Pick, 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'> { + /** + * If size tracking is enabled, then setting an explicit size + * in the {@link LRUCache#set} call will prevent calling the + * {@link OptionsBase.sizeCalculation} function. + */ + size?: Size; + /** + * If TTL tracking is enabled, then setting an explicit start + * time in the {@link LRUCache#set} call will override the + * default time from `performance.now()` or `Date.now()`. + * + * Note that it must be a valid value for whichever time-tracking + * method is in use. + */ + start?: Milliseconds; + status?: Status; + } + /** + * The type signature for the {@link OptionsBase.fetchMethod} option. + */ + type Fetcher = (key: K, staleValue: V | undefined, options: FetcherOptions) => Promise | V | undefined | void; + /** + * the type signature for the {@link OptionsBase.memoMethod} option. + */ + type Memoizer = (key: K, staleValue: V | undefined, options: MemoizerOptions) => V; + /** + * Options which may be passed to the {@link LRUCache} constructor. + * + * Most of these may be overridden in the various options that use + * them. + * + * Despite all being technically optional, the constructor requires that + * a cache is at minimum limited by one or more of {@link OptionsBase.max}, + * {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}. + * + * If {@link OptionsBase.ttl} is used alone, then it is strongly advised + * (and in fact required by the type definitions here) that the cache + * also set {@link OptionsBase.ttlAutopurge}, to prevent potentially + * unbounded storage. + * + * All options are also available on the {@link LRUCache} instance, making + * it safe to pass an LRUCache instance as the options argumemnt to + * make another empty cache of the same type. + * + * Some options are marked as read-only, because changing them after + * instantiation is not safe. Changing any of the other options will of + * course only have an effect on subsequent method calls. + */ + interface OptionsBase { + /** + * The maximum number of items to store in the cache before evicting + * old entries. This is read-only on the {@link LRUCache} instance, + * and may not be overridden. + * + * If set, then storage space will be pre-allocated at construction + * time, and the cache will perform significantly faster. + * + * Note that significantly fewer items may be stored, if + * {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also + * set. + * + * **It is strongly recommended to set a `max` to prevent unbounded growth + * of the cache.** + */ + max?: Count; + /** + * Max time in milliseconds for items to live in cache before they are + * considered stale. Note that stale items are NOT preemptively removed by + * default, and MAY live in the cache, contributing to its LRU max, long + * after they have expired, unless {@link OptionsBase.ttlAutopurge} is + * set. + * + * If set to `0` (the default value), then that means "do not track + * TTL", not "expire immediately". + * + * Also, as this cache is optimized for LRU/MRU operations, some of + * the staleness/TTL checks will reduce performance, as they will incur + * overhead by deleting items. + * + * This is not primarily a TTL cache, and does not make strong TTL + * guarantees. There is no pre-emptive pruning of expired items, but you + * _may_ set a TTL on the cache, and it will treat expired items as missing + * when they are fetched, and delete them. + * + * Optional, but must be a non-negative integer in ms if specified. + * + * This may be overridden by passing an options object to `cache.set()`. + * + * At least one of `max`, `maxSize`, or `TTL` is required. This must be a + * positive integer if set. + * + * Even if ttl tracking is enabled, **it is strongly recommended to set a + * `max` to prevent unbounded growth of the cache.** + * + * If ttl tracking is enabled, and `max` and `maxSize` are not set, + * and `ttlAutopurge` is not set, then a warning will be emitted + * cautioning about the potential for unbounded memory consumption. + * (The TypeScript definitions will also discourage this.) + */ + ttl?: Milliseconds; + /** + * Minimum amount of time in ms in which to check for staleness. + * Defaults to 1, which means that the current time is checked + * at most once per millisecond. + * + * Set to 0 to check the current time every time staleness is tested. + * (This reduces performance, and is theoretically unnecessary.) + * + * Setting this to a higher value will improve performance somewhat + * while using ttl tracking, albeit at the expense of keeping stale + * items around a bit longer than their TTLs would indicate. + * + * @default 1 + */ + ttlResolution?: Milliseconds; + /** + * Preemptively remove stale items from the cache. + * + * Note that this may *significantly* degrade performance, especially if + * the cache is storing a large number of items. It is almost always best + * to just leave the stale items in the cache, and let them fall out as new + * items are added. + * + * Note that this means that {@link OptionsBase.allowStale} is a bit + * pointless, as stale items will be deleted almost as soon as they + * expire. + * + * Use with caution! + */ + ttlAutopurge?: boolean; + /** + * When using time-expiring entries with `ttl`, setting this to `true` will + * make each item's age reset to 0 whenever it is retrieved from cache with + * {@link LRUCache#get}, causing it to not expire. (It can still fall out + * of cache based on recency of use, of course.) + * + * Has no effect if {@link OptionsBase.ttl} is not set. + * + * This may be overridden by passing an options object to `cache.get()`. + */ + updateAgeOnGet?: boolean; + /** + * When using time-expiring entries with `ttl`, setting this to `true` will + * make each item's age reset to 0 whenever its presence in the cache is + * checked with {@link LRUCache#has}, causing it to not expire. (It can + * still fall out of cache based on recency of use, of course.) + * + * Has no effect if {@link OptionsBase.ttl} is not set. + */ + updateAgeOnHas?: boolean; + /** + * Allow {@link LRUCache#get} and {@link LRUCache#fetch} calls to return + * stale data, if available. + * + * By default, if you set `ttl`, stale items will only be deleted from the + * cache when you `get(key)`. That is, it's not preemptively pruning items, + * unless {@link OptionsBase.ttlAutopurge} is set. + * + * If you set `allowStale:true`, it'll return the stale value *as well as* + * deleting it. If you don't set this, then it'll return `undefined` when + * you try to get a stale entry. + * + * Note that when a stale entry is fetched, _even if it is returned due to + * `allowStale` being set_, it is removed from the cache immediately. You + * can suppress this behavior by setting + * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in + * the options provided to {@link LRUCache#get}. + * + * This may be overridden by passing an options object to `cache.get()`. + * The `cache.has()` method will always return `false` for stale items. + * + * Only relevant if a ttl is set. + */ + allowStale?: boolean; + /** + * Function that is called on items when they are dropped from the + * cache, as `dispose(value, key, reason)`. + * + * This can be handy if you want to close file descriptors or do + * other cleanup tasks when items are no longer stored in the cache. + * + * **NOTE**: It is called _before_ the item has been fully removed + * from the cache, so if you want to put it right back in, you need + * to wait until the next tick. If you try to add it back in during + * the `dispose()` function call, it will break things in subtle and + * weird ways. + * + * Unlike several other options, this may _not_ be overridden by + * passing an option to `set()`, for performance reasons. + * + * The `reason` will be one of the following strings, corresponding + * to the reason for the item's deletion: + * + * - `evict` Item was evicted to make space for a new addition + * - `set` Item was overwritten by a new value + * - `expire` Item expired its TTL + * - `fetch` Item was deleted due to a failed or aborted fetch, or a + * fetchMethod returning `undefined. + * - `delete` Item was removed by explicit `cache.delete(key)`, + * `cache.clear()`, or `cache.set(key, undefined)`. + */ + dispose?: Disposer; + /** + * The same as {@link OptionsBase.dispose}, but called *after* the entry + * is completely removed and the cache is once again in a clean state. + * + * It is safe to add an item right back into the cache at this point. + * However, note that it is *very* easy to inadvertently create infinite + * recursion this way. + */ + disposeAfter?: Disposer; + /** + * Set to true to suppress calling the + * {@link OptionsBase.dispose} function if the entry key is + * still accessible within the cache. + * + * This may be overridden by passing an options object to + * {@link LRUCache#set}. + * + * Only relevant if `dispose` or `disposeAfter` are set. + */ + noDisposeOnSet?: boolean; + /** + * Boolean flag to tell the cache to not update the TTL when setting a new + * value for an existing key (ie, when updating a value rather than + * inserting a new value). Note that the TTL value is _always_ set (if + * provided) when adding a new entry into the cache. + * + * Has no effect if a {@link OptionsBase.ttl} is not set. + * + * May be passed as an option to {@link LRUCache#set}. + */ + noUpdateTTL?: boolean; + /** + * Set to a positive integer to track the sizes of items added to the + * cache, and automatically evict items in order to stay below this size. + * Note that this may result in fewer than `max` items being stored. + * + * Attempting to add an item to the cache whose calculated size is greater + * that this amount will be a no-op. The item will not be cached, and no + * other items will be evicted. + * + * Optional, must be a positive integer if provided. + * + * Sets `maxEntrySize` to the same value, unless a different value is + * provided for `maxEntrySize`. + * + * At least one of `max`, `maxSize`, or `TTL` is required. This must be a + * positive integer if set. + * + * Even if size tracking is enabled, **it is strongly recommended to set a + * `max` to prevent unbounded growth of the cache.** + * + * Note also that size tracking can negatively impact performance, + * though for most cases, only minimally. + */ + maxSize?: Size; + /** + * The maximum allowed size for any single item in the cache. + * + * If a larger item is passed to {@link LRUCache#set} or returned by a + * {@link OptionsBase.fetchMethod} or {@link OptionsBase.memoMethod}, then + * it will not be stored in the cache. + * + * Attempting to add an item whose calculated size is greater than + * this amount will not cache the item or evict any old items, but + * WILL delete an existing value if one is already present. + * + * Optional, must be a positive integer if provided. Defaults to + * the value of `maxSize` if provided. + */ + maxEntrySize?: Size; + /** + * A function that returns a number indicating the item's size. + * + * Requires {@link OptionsBase.maxSize} to be set. + * + * If not provided, and {@link OptionsBase.maxSize} or + * {@link OptionsBase.maxEntrySize} are set, then all + * {@link LRUCache#set} calls **must** provide an explicit + * {@link SetOptions.size} or sizeCalculation param. + */ + sizeCalculation?: SizeCalculator; + /** + * Method that provides the implementation for {@link LRUCache#fetch} + * + * ```ts + * fetchMethod(key, staleValue, { signal, options, context }) + * ``` + * + * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent + * to `Promise.resolve(cache.get(key))`. + * + * If at any time, `signal.aborted` is set to `true`, or if the + * `signal.onabort` method is called, or if it emits an `'abort'` event + * which you can listen to with `addEventListener`, then that means that + * the fetch should be abandoned. This may be passed along to async + * functions aware of AbortController/AbortSignal behavior. + * + * The `fetchMethod` should **only** return `undefined` or a Promise + * resolving to `undefined` if the AbortController signaled an `abort` + * event. In all other cases, it should return or resolve to a value + * suitable for adding to the cache. + * + * The `options` object is a union of the options that may be provided to + * `set()` and `get()`. If they are modified, then that will result in + * modifying the settings to `cache.set()` when the value is resolved, and + * in the case of + * {@link OptionsBase.noDeleteOnFetchRejection} and + * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of + * `fetchMethod` failures. + * + * For example, a DNS cache may update the TTL based on the value returned + * from a remote DNS server by changing `options.ttl` in the `fetchMethod`. + */ + fetchMethod?: Fetcher; + /** + * Method that provides the implementation for {@link LRUCache#memo} + */ + memoMethod?: Memoizer; + /** + * Set to true to suppress the deletion of stale data when a + * {@link OptionsBase.fetchMethod} returns a rejected promise. + */ + noDeleteOnFetchRejection?: boolean; + /** + * Do not delete stale items when they are retrieved with + * {@link LRUCache#get}. + * + * Note that the `get` return value will still be `undefined` + * unless {@link OptionsBase.allowStale} is true. + * + * When using time-expiring entries with `ttl`, by default stale + * items will be removed from the cache when the key is accessed + * with `cache.get()`. + * + * Setting this option will cause stale items to remain in the cache, until + * they are explicitly deleted with `cache.delete(key)`, or retrieved with + * `noDeleteOnStaleGet` set to `false`. + * + * This may be overridden by passing an options object to `cache.get()`. + * + * Only relevant if a ttl is used. + */ + noDeleteOnStaleGet?: boolean; + /** + * Set to true to allow returning stale data when a + * {@link OptionsBase.fetchMethod} throws an error or returns a rejected + * promise. + * + * This differs from using {@link OptionsBase.allowStale} in that stale + * data will ONLY be returned in the case that the {@link LRUCache#fetch} + * fails, not any other times. + * + * If a `fetchMethod` fails, and there is no stale value available, the + * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are + * suppressed. + * + * Implies `noDeleteOnFetchRejection`. + * + * This may be set in calls to `fetch()`, or defaulted on the constructor, + * or overridden by modifying the options object in the `fetchMethod`. + */ + allowStaleOnFetchRejection?: boolean; + /** + * Set to true to return a stale value from the cache when the + * `AbortSignal` passed to the {@link OptionsBase.fetchMethod} dispatches + * an `'abort'` event, whether user-triggered, or due to internal cache + * behavior. + * + * Unless {@link OptionsBase.ignoreFetchAbort} is also set, the underlying + * {@link OptionsBase.fetchMethod} will still be considered canceled, and + * any value it returns will be ignored and not cached. + * + * Caveat: since fetches are aborted when a new value is explicitly + * set in the cache, this can lead to fetch returning a stale value, + * since that was the fallback value _at the moment the `fetch()` was + * initiated_, even though the new updated value is now present in + * the cache. + * + * For example: + * + * ```ts + * const cache = new LRUCache({ + * ttl: 100, + * fetchMethod: async (url, oldValue, { signal }) => { + * const res = await fetch(url, { signal }) + * return await res.json() + * } + * }) + * cache.set('https://example.com/', { some: 'data' }) + * // 100ms go by... + * const result = cache.fetch('https://example.com/') + * cache.set('https://example.com/', { other: 'thing' }) + * console.log(await result) // { some: 'data' } + * console.log(cache.get('https://example.com/')) // { other: 'thing' } + * ``` + */ + allowStaleOnFetchAbort?: boolean; + /** + * Set to true to ignore the `abort` event emitted by the `AbortSignal` + * object passed to {@link OptionsBase.fetchMethod}, and still cache the + * resulting resolution value, as long as it is not `undefined`. + * + * When used on its own, this means aborted {@link LRUCache#fetch} calls + * are not immediately resolved or rejected when they are aborted, and + * instead take the full time to await. + * + * When used with {@link OptionsBase.allowStaleOnFetchAbort}, aborted + * {@link LRUCache#fetch} calls will resolve immediately to their stale + * cached value or `undefined`, and will continue to process and eventually + * update the cache when they resolve, as long as the resulting value is + * not `undefined`, thus supporting a "return stale on timeout while + * refreshing" mechanism by passing `AbortSignal.timeout(n)` as the signal. + * + * For example: + * + * ```ts + * const c = new LRUCache({ + * ttl: 100, + * ignoreFetchAbort: true, + * allowStaleOnFetchAbort: true, + * fetchMethod: async (key, oldValue, { signal }) => { + * // note: do NOT pass the signal to fetch()! + * // let's say this fetch can take a long time. + * const res = await fetch(`https://slow-backend-server/${key}`) + * return await res.json() + * }, + * }) + * + * // this will return the stale value after 100ms, while still + * // updating in the background for next time. + * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) }) + * ``` + * + * **Note**: regardless of this setting, an `abort` event _is still + * emitted on the `AbortSignal` object_, so may result in invalid results + * when passed to other underlying APIs that use AbortSignals. + * + * This may be overridden in the {@link OptionsBase.fetchMethod} or the + * call to {@link LRUCache#fetch}. + */ + ignoreFetchAbort?: boolean; + } + interface OptionsMaxLimit extends OptionsBase { + max: Count; + } + interface OptionsTTLLimit extends OptionsBase { + ttl: Milliseconds; + ttlAutopurge: boolean; + } + interface OptionsSizeLimit extends OptionsBase { + maxSize: Size; + } + /** + * The valid safe options for the {@link LRUCache} constructor + */ + type Options = OptionsMaxLimit | OptionsSizeLimit | OptionsTTLLimit; + /** + * Entry objects used by {@link LRUCache#load} and {@link LRUCache#dump}, + * and returned by {@link LRUCache#info}. + */ + interface Entry { + value: V; + ttl?: Milliseconds; + size?: Size; + start?: Milliseconds; + } +} +/** + * Default export, the thing you're using this module to get. + * + * The `K` and `V` types define the key and value types, respectively. The + * optional `FC` type defines the type of the `context` object passed to + * `cache.fetch()` and `cache.memo()`. + * + * Keys and values **must not** be `null` or `undefined`. + * + * All properties from the options object (with the exception of `max`, + * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are + * added as normal public members. (The listed options are read-only getters.) + * + * Changing any of these will alter the defaults for subsequent method calls. + */ +export declare class LRUCache implements Map { + #private; + /** + * {@link LRUCache.OptionsBase.ttl} + */ + ttl: LRUCache.Milliseconds; + /** + * {@link LRUCache.OptionsBase.ttlResolution} + */ + ttlResolution: LRUCache.Milliseconds; + /** + * {@link LRUCache.OptionsBase.ttlAutopurge} + */ + ttlAutopurge: boolean; + /** + * {@link LRUCache.OptionsBase.updateAgeOnGet} + */ + updateAgeOnGet: boolean; + /** + * {@link LRUCache.OptionsBase.updateAgeOnHas} + */ + updateAgeOnHas: boolean; + /** + * {@link LRUCache.OptionsBase.allowStale} + */ + allowStale: boolean; + /** + * {@link LRUCache.OptionsBase.noDisposeOnSet} + */ + noDisposeOnSet: boolean; + /** + * {@link LRUCache.OptionsBase.noUpdateTTL} + */ + noUpdateTTL: boolean; + /** + * {@link LRUCache.OptionsBase.maxEntrySize} + */ + maxEntrySize: LRUCache.Size; + /** + * {@link LRUCache.OptionsBase.sizeCalculation} + */ + sizeCalculation?: LRUCache.SizeCalculator; + /** + * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection} + */ + noDeleteOnFetchRejection: boolean; + /** + * {@link LRUCache.OptionsBase.noDeleteOnStaleGet} + */ + noDeleteOnStaleGet: boolean; + /** + * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort} + */ + allowStaleOnFetchAbort: boolean; + /** + * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} + */ + allowStaleOnFetchRejection: boolean; + /** + * {@link LRUCache.OptionsBase.ignoreFetchAbort} + */ + ignoreFetchAbort: boolean; + /** + * Do not call this method unless you need to inspect the + * inner workings of the cache. If anything returned by this + * object is modified in any way, strange breakage may occur. + * + * These fields are private for a reason! + * + * @internal + */ + static unsafeExposeInternals(c: LRUCache): { + starts: ZeroArray | undefined; + ttls: ZeroArray | undefined; + sizes: ZeroArray | undefined; + keyMap: Map; + keyList: (K | undefined)[]; + valList: (V | BackgroundFetch | undefined)[]; + next: NumberArray; + prev: NumberArray; + readonly head: Index; + readonly tail: Index; + free: StackLike; + isBackgroundFetch: (p: any) => boolean; + backgroundFetch: (k: K, index: number | undefined, options: LRUCache.FetchOptions, context: any) => BackgroundFetch; + moveToTail: (index: number) => void; + indexes: (options?: { + allowStale: boolean; + }) => Generator; + rindexes: (options?: { + allowStale: boolean; + }) => Generator; + isStale: (index: number | undefined) => boolean; + }; + /** + * {@link LRUCache.OptionsBase.max} (read-only) + */ + get max(): LRUCache.Count; + /** + * {@link LRUCache.OptionsBase.maxSize} (read-only) + */ + get maxSize(): LRUCache.Count; + /** + * The total computed size of items in the cache (read-only) + */ + get calculatedSize(): LRUCache.Size; + /** + * The number of items stored in the cache (read-only) + */ + get size(): LRUCache.Count; + /** + * {@link LRUCache.OptionsBase.fetchMethod} (read-only) + */ + get fetchMethod(): LRUCache.Fetcher | undefined; + get memoMethod(): LRUCache.Memoizer | undefined; + /** + * {@link LRUCache.OptionsBase.dispose} (read-only) + */ + get dispose(): LRUCache.Disposer | undefined; + /** + * {@link LRUCache.OptionsBase.disposeAfter} (read-only) + */ + get disposeAfter(): LRUCache.Disposer | undefined; + constructor(options: LRUCache.Options | LRUCache); + /** + * Return the number of ms left in the item's TTL. If item is not in cache, + * returns `0`. Returns `Infinity` if item is in cache without a defined TTL. + */ + getRemainingTTL(key: K): number; + /** + * Return a generator yielding `[key, value]` pairs, + * in order from most recently used to least recently used. + */ + entries(): Generator<[K, V], void, unknown>; + /** + * Inverse order version of {@link LRUCache.entries} + * + * Return a generator yielding `[key, value]` pairs, + * in order from least recently used to most recently used. + */ + rentries(): Generator<(K | V | BackgroundFetch | undefined)[], void, unknown>; + /** + * Return a generator yielding the keys in the cache, + * in order from most recently used to least recently used. + */ + keys(): Generator; + /** + * Inverse order version of {@link LRUCache.keys} + * + * Return a generator yielding the keys in the cache, + * in order from least recently used to most recently used. + */ + rkeys(): Generator; + /** + * Return a generator yielding the values in the cache, + * in order from most recently used to least recently used. + */ + values(): Generator; + /** + * Inverse order version of {@link LRUCache.values} + * + * Return a generator yielding the values in the cache, + * in order from least recently used to most recently used. + */ + rvalues(): Generator | undefined, void, unknown>; + /** + * Iterating over the cache itself yields the same results as + * {@link LRUCache.entries} + */ + [Symbol.iterator](): Generator<[K, V], void, unknown>; + /** + * A String value that is used in the creation of the default string + * description of an object. Called by the built-in method + * `Object.prototype.toString`. + */ + [Symbol.toStringTag]: string; + /** + * Find a value for which the supplied fn method returns a truthy value, + * similar to `Array.find()`. fn is called as `fn(value, key, cache)`. + */ + find(fn: (v: V, k: K, self: LRUCache) => boolean, getOptions?: LRUCache.GetOptions): V | undefined; + /** + * Call the supplied function on each item in the cache, in order from most + * recently used to least recently used. + * + * `fn` is called as `fn(value, key, cache)`. + * + * If `thisp` is provided, function will be called in the `this`-context of + * the provided object, or the cache if no `thisp` object is provided. + * + * Does not update age or recenty of use, or iterate over stale values. + */ + forEach(fn: (v: V, k: K, self: LRUCache) => any, thisp?: any): void; + /** + * The same as {@link LRUCache.forEach} but items are iterated over in + * reverse order. (ie, less recently used items are iterated over first.) + */ + rforEach(fn: (v: V, k: K, self: LRUCache) => any, thisp?: any): void; + /** + * Delete any stale entries. Returns true if anything was removed, + * false otherwise. + */ + purgeStale(): boolean; + /** + * Get the extended info about a given entry, to get its value, size, and + * TTL info simultaneously. Returns `undefined` if the key is not present. + * + * Unlike {@link LRUCache#dump}, which is designed to be portable and survive + * serialization, the `start` value is always the current timestamp, and the + * `ttl` is a calculated remaining time to live (negative if expired). + * + * Always returns stale values, if their info is found in the cache, so be + * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl}) + * if relevant. + */ + info(key: K): LRUCache.Entry | undefined; + /** + * Return an array of [key, {@link LRUCache.Entry}] tuples which can be + * passed to {@link LRLUCache#load}. + * + * The `start` fields are calculated relative to a portable `Date.now()` + * timestamp, even if `performance.now()` is available. + * + * Stale entries are always included in the `dump`, even if + * {@link LRUCache.OptionsBase.allowStale} is false. + * + * Note: this returns an actual array, not a generator, so it can be more + * easily passed around. + */ + dump(): [K, LRUCache.Entry][]; + /** + * Reset the cache and load in the items in entries in the order listed. + * + * The shape of the resulting cache may be different if the same options are + * not used in both caches. + * + * The `start` fields are assumed to be calculated relative to a portable + * `Date.now()` timestamp, even if `performance.now()` is available. + */ + load(arr: [K, LRUCache.Entry][]): void; + /** + * Add a value to the cache. + * + * Note: if `undefined` is specified as a value, this is an alias for + * {@link LRUCache#delete} + * + * Fields on the {@link LRUCache.SetOptions} options param will override + * their corresponding values in the constructor options for the scope + * of this single `set()` operation. + * + * If `start` is provided, then that will set the effective start + * time for the TTL calculation. Note that this must be a previous + * value of `performance.now()` if supported, or a previous value of + * `Date.now()` if not. + * + * Options object may also include `size`, which will prevent + * calling the `sizeCalculation` function and just use the specified + * number if it is a positive integer, and `noDisposeOnSet` which + * will prevent calling a `dispose` function in the case of + * overwrites. + * + * If the `size` (or return value of `sizeCalculation`) for a given + * entry is greater than `maxEntrySize`, then the item will not be + * added to the cache. + * + * Will update the recency of the entry. + * + * If the value is `undefined`, then this is an alias for + * `cache.delete(key)`. `undefined` is never stored in the cache. + */ + set(k: K, v: V | BackgroundFetch | undefined, setOptions?: LRUCache.SetOptions): this; + /** + * Evict the least recently used item, returning its value or + * `undefined` if cache is empty. + */ + pop(): V | undefined; + /** + * Check if a key is in the cache, without updating the recency of use. + * Will return false if the item is stale, even though it is technically + * in the cache. + * + * Check if a key is in the cache, without updating the recency of + * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set + * to `true` in either the options or the constructor. + * + * Will return `false` if the item is stale, even though it is technically in + * the cache. The difference can be determined (if it matters) by using a + * `status` argument, and inspecting the `has` field. + * + * Will not update item age unless + * {@link LRUCache.OptionsBase.updateAgeOnHas} is set. + */ + has(k: K, hasOptions?: LRUCache.HasOptions): boolean; + /** + * Like {@link LRUCache#get} but doesn't update recency or delete stale + * items. + * + * Returns `undefined` if the item is stale, unless + * {@link LRUCache.OptionsBase.allowStale} is set. + */ + peek(k: K, peekOptions?: LRUCache.PeekOptions): V | undefined; + /** + * Make an asynchronous cached fetch using the + * {@link LRUCache.OptionsBase.fetchMethod} function. + * + * If the value is in the cache and not stale, then the returned + * Promise resolves to the value. + * + * If not in the cache, or beyond its TTL staleness, then + * `fetchMethod(key, staleValue, { options, signal, context })` is + * called, and the value returned will be added to the cache once + * resolved. + * + * If called with `allowStale`, and an asynchronous fetch is + * currently in progress to reload a stale value, then the former + * stale value will be returned. + * + * If called with `forceRefresh`, then the cached item will be + * re-fetched, even if it is not stale. However, if `allowStale` is also + * set, then the old value will still be returned. This is useful + * in cases where you want to force a reload of a cached value. If + * a background fetch is already in progress, then `forceRefresh` + * has no effect. + * + * If multiple fetches for the same key are issued, then they will all be + * coalesced into a single call to fetchMethod. + * + * Note that this means that handling options such as + * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}, + * {@link LRUCache.FetchOptions.signal}, + * and {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} will be + * determined by the FIRST fetch() call for a given key. + * + * This is a known (fixable) shortcoming which will be addresed on when + * someone complains about it, as the fix would involve added complexity and + * may not be worth the costs for this edge case. + * + * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is + * effectively an alias for `Promise.resolve(cache.get(key))`. + * + * When the fetch method resolves to a value, if the fetch has not + * been aborted due to deletion, eviction, or being overwritten, + * then it is added to the cache using the options provided. + * + * If the key is evicted or deleted before the `fetchMethod` + * resolves, then the AbortSignal passed to the `fetchMethod` will + * receive an `abort` event, and the promise returned by `fetch()` + * will reject with the reason for the abort. + * + * If a `signal` is passed to the `fetch()` call, then aborting the + * signal will abort the fetch and cause the `fetch()` promise to + * reject with the reason provided. + * + * **Setting `context`** + * + * If an `FC` type is set to a type other than `unknown`, `void`, or + * `undefined` in the {@link LRUCache} constructor, then all + * calls to `cache.fetch()` _must_ provide a `context` option. If + * set to `undefined` or `void`, then calls to fetch _must not_ + * provide a `context` option. + * + * The `context` param allows you to provide arbitrary data that + * might be relevant in the course of fetching the data. It is only + * relevant for the course of a single `fetch()` operation, and + * discarded afterwards. + * + * **Note: `fetch()` calls are inflight-unique** + * + * If you call `fetch()` multiple times with the same key value, + * then every call after the first will resolve on the same + * promise1, + * _even if they have different settings that would otherwise change + * the behavior of the fetch_, such as `noDeleteOnFetchRejection` + * or `ignoreFetchAbort`. + * + * In most cases, this is not a problem (in fact, only fetching + * something once is what you probably want, if you're caching in + * the first place). If you are changing the fetch() options + * dramatically between runs, there's a good chance that you might + * be trying to fit divergent semantics into a single object, and + * would be better off with multiple cache instances. + * + * **1**: Ie, they're not the "same Promise", but they resolve at + * the same time, because they're both waiting on the same + * underlying fetchMethod response. + */ + fetch(k: K, fetchOptions: unknown extends FC ? LRUCache.FetchOptions : FC extends undefined | void ? LRUCache.FetchOptionsNoContext : LRUCache.FetchOptionsWithContext): Promise; + fetch(k: unknown extends FC ? K : FC extends undefined | void ? K : never, fetchOptions?: unknown extends FC ? LRUCache.FetchOptions : FC extends undefined | void ? LRUCache.FetchOptionsNoContext : never): Promise; + /** + * In some cases, `cache.fetch()` may resolve to `undefined`, either because + * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning + * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or + * because `ignoreFetchAbort` was specified (either to the constructor or + * in the {@link LRUCache.FetchOptions}). Also, the + * {@link OptionsBase.fetchMethod} may return `undefined` or `void`, making + * the test even more complicated. + * + * Because inferring the cases where `undefined` might be returned are so + * cumbersome, but testing for `undefined` can also be annoying, this method + * can be used, which will reject if `this.fetch()` resolves to undefined. + */ + forceFetch(k: K, fetchOptions: unknown extends FC ? LRUCache.FetchOptions : FC extends undefined | void ? LRUCache.FetchOptionsNoContext : LRUCache.FetchOptionsWithContext): Promise; + forceFetch(k: unknown extends FC ? K : FC extends undefined | void ? K : never, fetchOptions?: unknown extends FC ? LRUCache.FetchOptions : FC extends undefined | void ? LRUCache.FetchOptionsNoContext : never): Promise; + /** + * If the key is found in the cache, then this is equivalent to + * {@link LRUCache#get}. If not, in the cache, then calculate the value using + * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache. + * + * If an `FC` type is set to a type other than `unknown`, `void`, or + * `undefined` in the LRUCache constructor, then all calls to `cache.memo()` + * _must_ provide a `context` option. If set to `undefined` or `void`, then + * calls to memo _must not_ provide a `context` option. + * + * The `context` param allows you to provide arbitrary data that might be + * relevant in the course of fetching the data. It is only relevant for the + * course of a single `memo()` operation, and discarded afterwards. + */ + memo(k: K, memoOptions: unknown extends FC ? LRUCache.MemoOptions : FC extends undefined | void ? LRUCache.MemoOptionsNoContext : LRUCache.MemoOptionsWithContext): V; + memo(k: unknown extends FC ? K : FC extends undefined | void ? K : never, memoOptions?: unknown extends FC ? LRUCache.MemoOptions : FC extends undefined | void ? LRUCache.MemoOptionsNoContext : never): V; + /** + * Return a value from the cache. Will update the recency of the cache + * entry found. + * + * If the key is not found, get() will return `undefined`. + */ + get(k: K, getOptions?: LRUCache.GetOptions): V | undefined; + /** + * Deletes a key out of the cache. + * + * Returns true if the key was deleted, false otherwise. + */ + delete(k: K): boolean; + /** + * Clear the cache entirely, throwing away all values. + */ + clear(): void; +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/commonjs/index.d.ts.map b/node_modules/lru-cache/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000..34d60c5 --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AA0FH,QAAA,MAAM,IAAI,eAAiB,CAAA;AAC3B,MAAM,MAAM,MAAM,GAAG,MAAM,GAAG;IAAE,CAAC,IAAI,CAAC,EAAE,kBAAkB,CAAA;CAAE,CAAA;AAC5D,MAAM,MAAM,KAAK,GAAG,MAAM,GAAG;IAAE,CAAC,IAAI,CAAC,EAAE,gBAAgB,CAAA;CAAE,CAAA;AAKzD,MAAM,MAAM,SAAS,GAAG,UAAU,GAAG,WAAW,GAAG,WAAW,CAAA;AAC9D,MAAM,MAAM,WAAW,GAAG,SAAS,GAAG,MAAM,EAAE,CAAA;AAyB9C,cAAM,SAAU,SAAQ,KAAK,CAAC,MAAM,CAAC;gBACvB,IAAI,EAAE,MAAM;CAIzB;AACD,YAAY,EAAE,SAAS,EAAE,CAAA;AACzB,YAAY,EAAE,KAAK,EAAE,CAAA;AAErB,MAAM,MAAM,SAAS,GAAG,KAAK,GAAG,KAAK,EAAE,CAAA;AACvC,cAAM,KAAK;;IACT,IAAI,EAAE,WAAW,CAAA;IACjB,MAAM,EAAE,MAAM,CAAA;IAGd,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS;gBASnC,GAAG,EAAE,MAAM,EACX,OAAO,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,GAAG,WAAW,CAAA;KAAE;IAU3C,IAAI,CAAC,CAAC,EAAE,KAAK;IAGb,GAAG,IAAI,KAAK;CAGb;AAED;;GAEG;AACH,MA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B,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAC5C,CAAC;IAEJ,IAAI,CACF,CAAC,EAAE,OAAO,SAAS,EAAE,GACjB,CAAC,GACD,EAAE,SAAS,SAAS,GAAG,IAAI,GAC3B,CAAC,GACD,KAAK,EACT,WAAW,CAAC,EAAE,OAAO,SAAS,EAAE,GAC5B,QAAQ,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAC9B,EAAE,SAAS,SAAS,GAAG,IAAI,GAC3B,QAAQ,CAAC,oBAAoB,CAAC,CAAC,EAAE,CAAC,CAAC,GACnC,KAAK,GACR,CAAC;IAiBJ;;;;;OAKG;IACH,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,UAAU,GAAE,QAAQ,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAM;IAgFxD;;;;OAIG;IACH,MAAM,CAAC,CAAC,EAAE,CAAC;IAqDX;;OAEG;IACH,KAAK;CA0CN"} \ No newline at end of file diff --git a/node_modules/lru-cache/dist/commonjs/index.js b/node_modules/lru-cache/dist/commonjs/index.js new file mode 100644 index 0000000..0589231 --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/index.js @@ -0,0 +1,1546 @@ +"use strict"; +/** + * @module LRUCache + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LRUCache = void 0; +const perf = typeof performance === 'object' && + performance && + typeof performance.now === 'function' + ? performance + : Date; +const warned = new Set(); +/* c8 ignore start */ +const PROCESS = (typeof process === 'object' && !!process ? process : {}); +/* c8 ignore start */ +const emitWarning = (msg, type, code, fn) => { + typeof PROCESS.emitWarning === 'function' + ? PROCESS.emitWarning(msg, type, code, fn) + : console.error(`[${code}] ${type}: ${msg}`); +}; +let AC = globalThis.AbortController; +let AS = globalThis.AbortSignal; +/* c8 ignore start */ +if (typeof AC === 'undefined') { + //@ts-ignore + AS = class AbortSignal { + onabort; + _onabort = []; + reason; + aborted = false; + addEventListener(_, fn) { + this._onabort.push(fn); + } + }; + //@ts-ignore + AC = class AbortController { + constructor() { + warnACPolyfill(); + } + signal = new AS(); + abort(reason) { + if (this.signal.aborted) + return; + //@ts-ignore + this.signal.reason = reason; + //@ts-ignore + this.signal.aborted = true; + //@ts-ignore + for (const fn of this.signal._onabort) { + fn(reason); + } + this.signal.onabort?.(reason); + } + }; + let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'; + const warnACPolyfill = () => { + if (!printACPolyfillWarning) + return; + printACPolyfillWarning = false; + emitWarning('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', warnACPolyfill); + }; +} +/* c8 ignore stop */ +const shouldWarn = (code) => !warned.has(code); +const TYPE = Symbol('type'); +const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n); +/* c8 ignore start */ +// This is a little bit ridiculous, tbh. +// The maximum array length is 2^32-1 or thereabouts on most JS impls. +// And well before that point, you're caching the entire world, I mean, +// that's ~32GB of just integers for the next/prev links, plus whatever +// else to hold that many keys and values. Just filling the memory with +// zeroes at init time is brutal when you get that big. +// But why not be complete? +// Maybe in the future, these limits will have expanded. +const getUintArray = (max) => !isPosInt(max) + ? null + : max <= Math.pow(2, 8) + ? Uint8Array + : max <= Math.pow(2, 16) + ? Uint16Array + : max <= Math.pow(2, 32) + ? Uint32Array + : max <= Number.MAX_SAFE_INTEGER + ? ZeroArray + : null; +/* c8 ignore stop */ +class ZeroArray extends Array { + constructor(size) { + super(size); + this.fill(0); + } +} +class Stack { + heap; + length; + // private constructor + static #constructing = false; + static create(max) { + const HeapCls = getUintArray(max); + if (!HeapCls) + return []; + Stack.#constructing = true; + const s = new Stack(max, HeapCls); + Stack.#constructing = false; + return s; + } + constructor(max, HeapCls) { + /* c8 ignore start */ + if (!Stack.#constructing) { + throw new TypeError('instantiate Stack using Stack.create(n)'); + } + /* c8 ignore stop */ + this.heap = new HeapCls(max); + this.length = 0; + } + push(n) { + this.heap[this.length++] = n; + } + pop() { + return this.heap[--this.length]; + } +} +/** + * Default export, the thing you're using this module to get. + * + * The `K` and `V` types define the key and value types, respectively. The + * optional `FC` type defines the type of the `context` object passed to + * `cache.fetch()` and `cache.memo()`. + * + * Keys and values **must not** be `null` or `undefined`. + * + * All properties from the options object (with the exception of `max`, + * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are + * added as normal public members. (The listed options are read-only getters.) + * + * Changing any of these will alter the defaults for subsequent method calls. + */ +class LRUCache { + // options that cannot be changed without disaster + #max; + #maxSize; + #dispose; + #disposeAfter; + #fetchMethod; + #memoMethod; + /** + * {@link LRUCache.OptionsBase.ttl} + */ + ttl; + /** + * {@link LRUCache.OptionsBase.ttlResolution} + */ + ttlResolution; + /** + * {@link LRUCache.OptionsBase.ttlAutopurge} + */ + ttlAutopurge; + /** + * {@link LRUCache.OptionsBase.updateAgeOnGet} + */ + updateAgeOnGet; + /** + * {@link LRUCache.OptionsBase.updateAgeOnHas} + */ + updateAgeOnHas; + /** + * {@link LRUCache.OptionsBase.allowStale} + */ + allowStale; + /** + * {@link LRUCache.OptionsBase.noDisposeOnSet} + */ + noDisposeOnSet; + /** + * {@link LRUCache.OptionsBase.noUpdateTTL} + */ + noUpdateTTL; + /** + * {@link LRUCache.OptionsBase.maxEntrySize} + */ + maxEntrySize; + /** + * {@link LRUCache.OptionsBase.sizeCalculation} + */ + sizeCalculation; + /** + * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection} + */ + noDeleteOnFetchRejection; + /** + * {@link LRUCache.OptionsBase.noDeleteOnStaleGet} + */ + noDeleteOnStaleGet; + /** + * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort} + */ + allowStaleOnFetchAbort; + /** + * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} + */ + allowStaleOnFetchRejection; + /** + * {@link LRUCache.OptionsBase.ignoreFetchAbort} + */ + ignoreFetchAbort; + // computed properties + #size; + #calculatedSize; + #keyMap; + #keyList; + #valList; + #next; + #prev; + #head; + #tail; + #free; + #disposed; + #sizes; + #starts; + #ttls; + #hasDispose; + #hasFetchMethod; + #hasDisposeAfter; + /** + * Do not call this method unless you need to inspect the + * inner workings of the cache. If anything returned by this + * object is modified in any way, strange breakage may occur. + * + * These fields are private for a reason! + * + * @internal + */ + static unsafeExposeInternals(c) { + return { + // properties + starts: c.#starts, + ttls: c.#ttls, + sizes: c.#sizes, + keyMap: c.#keyMap, + keyList: c.#keyList, + valList: c.#valList, + next: c.#next, + prev: c.#prev, + get head() { + return c.#head; + }, + get tail() { + return c.#tail; + }, + free: c.#free, + // methods + isBackgroundFetch: (p) => c.#isBackgroundFetch(p), + backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context), + moveToTail: (index) => c.#moveToTail(index), + indexes: (options) => c.#indexes(options), + rindexes: (options) => c.#rindexes(options), + isStale: (index) => c.#isStale(index), + }; + } + // Protected read-only members + /** + * {@link LRUCache.OptionsBase.max} (read-only) + */ + get max() { + return this.#max; + } + /** + * {@link LRUCache.OptionsBase.maxSize} (read-only) + */ + get maxSize() { + return this.#maxSize; + } + /** + * The total computed size of items in the cache (read-only) + */ + get calculatedSize() { + return this.#calculatedSize; + } + /** + * The number of items stored in the cache (read-only) + */ + get size() { + return this.#size; + } + /** + * {@link LRUCache.OptionsBase.fetchMethod} (read-only) + */ + get fetchMethod() { + return this.#fetchMethod; + } + get memoMethod() { + return this.#memoMethod; + } + /** + * {@link LRUCache.OptionsBase.dispose} (read-only) + */ + get dispose() { + return this.#dispose; + } + /** + * {@link LRUCache.OptionsBase.disposeAfter} (read-only) + */ + get disposeAfter() { + return this.#disposeAfter; + } + constructor(options) { + const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options; + if (max !== 0 && !isPosInt(max)) { + throw new TypeError('max option must be a nonnegative integer'); + } + const UintArray = max ? getUintArray(max) : Array; + if (!UintArray) { + throw new Error('invalid max value: ' + max); + } + this.#max = max; + this.#maxSize = maxSize; + this.maxEntrySize = maxEntrySize || this.#maxSize; + this.sizeCalculation = sizeCalculation; + if (this.sizeCalculation) { + if (!this.#maxSize && !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 (memoMethod !== undefined && + typeof memoMethod !== 'function') { + throw new TypeError('memoMethod must be a function if defined'); + } + this.#memoMethod = memoMethod; + if (fetchMethod !== undefined && + typeof fetchMethod !== 'function') { + throw new TypeError('fetchMethod must be a function if specified'); + } + this.#fetchMethod = fetchMethod; + this.#hasFetchMethod = !!fetchMethod; + this.#keyMap = new Map(); + this.#keyList = new Array(max).fill(undefined); + this.#valList = new Array(max).fill(undefined); + this.#next = new UintArray(max); + this.#prev = new UintArray(max); + this.#head = 0; + this.#tail = 0; + this.#free = Stack.create(max); + this.#size = 0; + this.#calculatedSize = 0; + if (typeof dispose === 'function') { + this.#dispose = dispose; + } + if (typeof disposeAfter === 'function') { + this.#disposeAfter = disposeAfter; + this.#disposed = []; + } + else { + this.#disposeAfter = undefined; + this.#disposed = undefined; + } + this.#hasDispose = !!this.#dispose; + this.#hasDisposeAfter = !!this.#disposeAfter; + this.noDisposeOnSet = !!noDisposeOnSet; + this.noUpdateTTL = !!noUpdateTTL; + this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection; + this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection; + this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort; + this.ignoreFetchAbort = !!ignoreFetchAbort; + // NB: maxEntrySize is set to maxSize if it's set + if (this.maxEntrySize !== 0) { + if (this.#maxSize !== 0) { + if (!isPosInt(this.#maxSize)) { + throw new TypeError('maxSize must be a positive integer if specified'); + } + } + if (!isPosInt(this.maxEntrySize)) { + throw new TypeError('maxEntrySize must be a positive integer if specified'); + } + this.#initializeSizeTracking(); + } + this.allowStale = !!allowStale; + this.noDeleteOnStaleGet = !!noDeleteOnStaleGet; + this.updateAgeOnGet = !!updateAgeOnGet; + this.updateAgeOnHas = !!updateAgeOnHas; + this.ttlResolution = + isPosInt(ttlResolution) || ttlResolution === 0 + ? ttlResolution + : 1; + this.ttlAutopurge = !!ttlAutopurge; + this.ttl = ttl || 0; + if (this.ttl) { + if (!isPosInt(this.ttl)) { + throw new TypeError('ttl must be a positive integer if specified'); + } + this.#initializeTTLTracking(); + } + // do not allow completely unbounded caches + if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) { + throw new TypeError('At least one of max, maxSize, or ttl is required'); + } + if (!this.ttlAutopurge && !this.#max && !this.#maxSize) { + const code = 'LRU_CACHE_UNBOUNDED'; + if (shouldWarn(code)) { + warned.add(code); + const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' + + 'result in unbounded memory consumption.'; + emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache); + } + } + } + /** + * Return the number of ms left in the item's TTL. If item is not in cache, + * returns `0`. Returns `Infinity` if item is in cache without a defined TTL. + */ + getRemainingTTL(key) { + return this.#keyMap.has(key) ? Infinity : 0; + } + #initializeTTLTracking() { + const ttls = new ZeroArray(this.#max); + const starts = new ZeroArray(this.#max); + this.#ttls = ttls; + this.#starts = starts; + this.#setItemTTL = (index, ttl, start = perf.now()) => { + starts[index] = ttl !== 0 ? start : 0; + ttls[index] = ttl; + if (ttl !== 0 && this.ttlAutopurge) { + const t = setTimeout(() => { + if (this.#isStale(index)) { + this.#delete(this.#keyList[index], 'expire'); + } + }, ttl + 1); + // unref() not supported on all platforms + /* c8 ignore start */ + if (t.unref) { + t.unref(); + } + /* c8 ignore stop */ + } + }; + this.#updateItemAge = index => { + starts[index] = ttls[index] !== 0 ? perf.now() : 0; + }; + this.#statusTTL = (status, index) => { + if (ttls[index]) { + const ttl = ttls[index]; + const start = starts[index]; + /* c8 ignore next */ + if (!ttl || !start) + return; + status.ttl = ttl; + status.start = start; + status.now = cachedNow || getNow(); + const age = status.now - start; + status.remainingTTL = ttl - age; + } + }; + // debounce calls to perf.now() to 1s so we're not hitting + // that costly call repeatedly. + let cachedNow = 0; + const getNow = () => { + const n = perf.now(); + if (this.ttlResolution > 0) { + cachedNow = n; + const t = setTimeout(() => (cachedNow = 0), this.ttlResolution); + // not available on all platforms + /* c8 ignore start */ + if (t.unref) { + t.unref(); + } + /* c8 ignore stop */ + } + return n; + }; + this.getRemainingTTL = key => { + const index = this.#keyMap.get(key); + if (index === undefined) { + return 0; + } + const ttl = ttls[index]; + const start = starts[index]; + if (!ttl || !start) { + return Infinity; + } + const age = (cachedNow || getNow()) - start; + return ttl - age; + }; + this.#isStale = index => { + const s = starts[index]; + const t = ttls[index]; + return !!t && !!s && (cachedNow || getNow()) - s > t; + }; + } + // conditionally set private methods related to TTL + #updateItemAge = () => { }; + #statusTTL = () => { }; + #setItemTTL = () => { }; + /* c8 ignore stop */ + #isStale = () => false; + #initializeSizeTracking() { + const sizes = new ZeroArray(this.#max); + this.#calculatedSize = 0; + this.#sizes = sizes; + this.#removeItemSize = index => { + this.#calculatedSize -= sizes[index]; + sizes[index] = 0; + }; + this.#requireSize = (k, v, size, sizeCalculation) => { + // provisionally accept background fetches. + // actual value size will be checked when they return. + if (this.#isBackgroundFetch(v)) { + return 0; + } + if (!isPosInt(size)) { + if (sizeCalculation) { + if (typeof sizeCalculation !== 'function') { + throw new TypeError('sizeCalculation must be a function'); + } + size = sizeCalculation(v, k); + if (!isPosInt(size)) { + 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 size; + }; + this.#addItemSize = (index, size, status) => { + sizes[index] = size; + if (this.#maxSize) { + const maxSize = this.#maxSize - sizes[index]; + while (this.#calculatedSize > maxSize) { + this.#evict(true); + } + } + this.#calculatedSize += sizes[index]; + if (status) { + status.entrySize = size; + status.totalCalculatedSize = this.#calculatedSize; + } + }; + } + #removeItemSize = _i => { }; + #addItemSize = (_i, _s, _st) => { }; + #requireSize = (_k, _v, size, sizeCalculation) => { + if (size || sizeCalculation) { + throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache'); + } + return 0; + }; + *#indexes({ allowStale = this.allowStale } = {}) { + if (this.#size) { + for (let i = this.#tail; true;) { + if (!this.#isValidIndex(i)) { + break; + } + if (allowStale || !this.#isStale(i)) { + yield i; + } + if (i === this.#head) { + break; + } + else { + i = this.#prev[i]; + } + } + } + } + *#rindexes({ allowStale = this.allowStale } = {}) { + if (this.#size) { + for (let i = this.#head; true;) { + if (!this.#isValidIndex(i)) { + break; + } + if (allowStale || !this.#isStale(i)) { + yield i; + } + if (i === this.#tail) { + break; + } + else { + i = this.#next[i]; + } + } + } + } + #isValidIndex(index) { + return (index !== undefined && + this.#keyMap.get(this.#keyList[index]) === index); + } + /** + * Return a generator yielding `[key, value]` pairs, + * in order from most recently used to least recently used. + */ + *entries() { + for (const i of this.#indexes()) { + if (this.#valList[i] !== undefined && + this.#keyList[i] !== undefined && + !this.#isBackgroundFetch(this.#valList[i])) { + yield [this.#keyList[i], this.#valList[i]]; + } + } + } + /** + * Inverse order version of {@link LRUCache.entries} + * + * Return a generator yielding `[key, value]` pairs, + * in order from least recently used to most recently used. + */ + *rentries() { + for (const i of this.#rindexes()) { + if (this.#valList[i] !== undefined && + this.#keyList[i] !== undefined && + !this.#isBackgroundFetch(this.#valList[i])) { + yield [this.#keyList[i], this.#valList[i]]; + } + } + } + /** + * Return a generator yielding the keys in the cache, + * in order from most recently used to least recently used. + */ + *keys() { + for (const i of this.#indexes()) { + const k = this.#keyList[i]; + if (k !== undefined && + !this.#isBackgroundFetch(this.#valList[i])) { + yield k; + } + } + } + /** + * Inverse order version of {@link LRUCache.keys} + * + * Return a generator yielding the keys in the cache, + * in order from least recently used to most recently used. + */ + *rkeys() { + for (const i of this.#rindexes()) { + const k = this.#keyList[i]; + if (k !== undefined && + !this.#isBackgroundFetch(this.#valList[i])) { + yield k; + } + } + } + /** + * Return a generator yielding the values in the cache, + * in order from most recently used to least recently used. + */ + *values() { + for (const i of this.#indexes()) { + const v = this.#valList[i]; + if (v !== undefined && + !this.#isBackgroundFetch(this.#valList[i])) { + yield this.#valList[i]; + } + } + } + /** + * Inverse order version of {@link LRUCache.values} + * + * Return a generator yielding the values in the cache, + * in order from least recently used to most recently used. + */ + *rvalues() { + for (const i of this.#rindexes()) { + const v = this.#valList[i]; + if (v !== undefined && + !this.#isBackgroundFetch(this.#valList[i])) { + yield this.#valList[i]; + } + } + } + /** + * Iterating over the cache itself yields the same results as + * {@link LRUCache.entries} + */ + [Symbol.iterator]() { + return this.entries(); + } + /** + * A String value that is used in the creation of the default string + * description of an object. Called by the built-in method + * `Object.prototype.toString`. + */ + [Symbol.toStringTag] = 'LRUCache'; + /** + * Find a value for which the supplied fn method returns a truthy value, + * similar to `Array.find()`. fn is called as `fn(value, key, cache)`. + */ + find(fn, getOptions = {}) { + for (const i of this.#indexes()) { + const v = this.#valList[i]; + const value = this.#isBackgroundFetch(v) + ? v.__staleWhileFetching + : v; + if (value === undefined) + continue; + if (fn(value, this.#keyList[i], this)) { + return this.get(this.#keyList[i], getOptions); + } + } + } + /** + * Call the supplied function on each item in the cache, in order from most + * recently used to least recently used. + * + * `fn` is called as `fn(value, key, cache)`. + * + * If `thisp` is provided, function will be called in the `this`-context of + * the provided object, or the cache if no `thisp` object is provided. + * + * Does not update age or recenty of use, or iterate over stale values. + */ + forEach(fn, thisp = this) { + for (const i of this.#indexes()) { + const v = this.#valList[i]; + const value = this.#isBackgroundFetch(v) + ? v.__staleWhileFetching + : v; + if (value === undefined) + continue; + fn.call(thisp, value, this.#keyList[i], this); + } + } + /** + * The same as {@link LRUCache.forEach} but items are iterated over in + * reverse order. (ie, less recently used items are iterated over first.) + */ + rforEach(fn, thisp = this) { + for (const i of this.#rindexes()) { + const v = this.#valList[i]; + const value = this.#isBackgroundFetch(v) + ? v.__staleWhileFetching + : v; + if (value === undefined) + continue; + fn.call(thisp, value, this.#keyList[i], this); + } + } + /** + * Delete any stale entries. Returns true if anything was removed, + * false otherwise. + */ + purgeStale() { + let deleted = false; + for (const i of this.#rindexes({ allowStale: true })) { + if (this.#isStale(i)) { + this.#delete(this.#keyList[i], 'expire'); + deleted = true; + } + } + return deleted; + } + /** + * Get the extended info about a given entry, to get its value, size, and + * TTL info simultaneously. Returns `undefined` if the key is not present. + * + * Unlike {@link LRUCache#dump}, which is designed to be portable and survive + * serialization, the `start` value is always the current timestamp, and the + * `ttl` is a calculated remaining time to live (negative if expired). + * + * Always returns stale values, if their info is found in the cache, so be + * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl}) + * if relevant. + */ + info(key) { + const i = this.#keyMap.get(key); + if (i === undefined) + return undefined; + const v = this.#valList[i]; + const value = this.#isBackgroundFetch(v) + ? v.__staleWhileFetching + : v; + if (value === undefined) + return undefined; + const entry = { value }; + if (this.#ttls && this.#starts) { + const ttl = this.#ttls[i]; + const start = this.#starts[i]; + if (ttl && start) { + const remain = ttl - (perf.now() - start); + entry.ttl = remain; + entry.start = Date.now(); + } + } + if (this.#sizes) { + entry.size = this.#sizes[i]; + } + return entry; + } + /** + * Return an array of [key, {@link LRUCache.Entry}] tuples which can be + * passed to {@link LRLUCache#load}. + * + * The `start` fields are calculated relative to a portable `Date.now()` + * timestamp, even if `performance.now()` is available. + * + * Stale entries are always included in the `dump`, even if + * {@link LRUCache.OptionsBase.allowStale} is false. + * + * Note: this returns an actual array, not a generator, so it can be more + * easily passed around. + */ + dump() { + const arr = []; + for (const i of this.#indexes({ allowStale: true })) { + const key = this.#keyList[i]; + const v = this.#valList[i]; + const value = this.#isBackgroundFetch(v) + ? v.__staleWhileFetching + : v; + if (value === undefined || key === undefined) + continue; + const entry = { value }; + if (this.#ttls && this.#starts) { + entry.ttl = this.#ttls[i]; + // always dump the start relative to a portable timestamp + // it's ok for this to be a bit slow, it's a rare operation. + const age = perf.now() - this.#starts[i]; + entry.start = Math.floor(Date.now() - age); + } + if (this.#sizes) { + entry.size = this.#sizes[i]; + } + arr.unshift([key, entry]); + } + return arr; + } + /** + * Reset the cache and load in the items in entries in the order listed. + * + * The shape of the resulting cache may be different if the same options are + * not used in both caches. + * + * The `start` fields are assumed to be calculated relative to a portable + * `Date.now()` timestamp, even if `performance.now()` is available. + */ + load(arr) { + this.clear(); + for (const [key, entry] of arr) { + if (entry.start) { + // entry.start is a portable timestamp, but we may be using + // node's performance.now(), so calculate the offset, so that + // we get the intended remaining TTL, no matter how long it's + // been on ice. + // + // it's ok for this to be a bit slow, it's a rare operation. + const age = Date.now() - entry.start; + entry.start = perf.now() - age; + } + this.set(key, entry.value, entry); + } + } + /** + * Add a value to the cache. + * + * Note: if `undefined` is specified as a value, this is an alias for + * {@link LRUCache#delete} + * + * Fields on the {@link LRUCache.SetOptions} options param will override + * their corresponding values in the constructor options for the scope + * of this single `set()` operation. + * + * If `start` is provided, then that will set the effective start + * time for the TTL calculation. Note that this must be a previous + * value of `performance.now()` if supported, or a previous value of + * `Date.now()` if not. + * + * Options object may also include `size`, which will prevent + * calling the `sizeCalculation` function and just use the specified + * number if it is a positive integer, and `noDisposeOnSet` which + * will prevent calling a `dispose` function in the case of + * overwrites. + * + * If the `size` (or return value of `sizeCalculation`) for a given + * entry is greater than `maxEntrySize`, then the item will not be + * added to the cache. + * + * Will update the recency of the entry. + * + * If the value is `undefined`, then this is an alias for + * `cache.delete(key)`. `undefined` is never stored in the cache. + */ + set(k, v, setOptions = {}) { + if (v === undefined) { + this.delete(k); + return this; + } + const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions; + let { noUpdateTTL = this.noUpdateTTL } = setOptions; + const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation); + // if the item doesn't fit, don't do anything + // NB: maxEntrySize set to maxSize by default + if (this.maxEntrySize && size > this.maxEntrySize) { + if (status) { + status.set = 'miss'; + status.maxEntrySizeExceeded = true; + } + // have to delete, in case something is there already. + this.#delete(k, 'set'); + return this; + } + let index = this.#size === 0 ? undefined : this.#keyMap.get(k); + if (index === undefined) { + // addition + index = (this.#size === 0 + ? this.#tail + : this.#free.length !== 0 + ? this.#free.pop() + : this.#size === this.#max + ? this.#evict(false) + : this.#size); + this.#keyList[index] = k; + this.#valList[index] = v; + this.#keyMap.set(k, index); + this.#next[this.#tail] = index; + this.#prev[index] = this.#tail; + this.#tail = index; + this.#size++; + this.#addItemSize(index, size, status); + if (status) + status.set = 'add'; + noUpdateTTL = false; + } + else { + // update + this.#moveToTail(index); + const oldVal = this.#valList[index]; + if (v !== oldVal) { + if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) { + oldVal.__abortController.abort(new Error('replaced')); + const { __staleWhileFetching: s } = oldVal; + if (s !== undefined && !noDisposeOnSet) { + if (this.#hasDispose) { + this.#dispose?.(s, k, 'set'); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([s, k, 'set']); + } + } + } + else if (!noDisposeOnSet) { + if (this.#hasDispose) { + this.#dispose?.(oldVal, k, 'set'); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([oldVal, k, 'set']); + } + } + this.#removeItemSize(index); + this.#addItemSize(index, size, status); + this.#valList[index] = v; + if (status) { + status.set = 'replace'; + const oldValue = oldVal && this.#isBackgroundFetch(oldVal) + ? oldVal.__staleWhileFetching + : oldVal; + if (oldValue !== undefined) + status.oldValue = oldValue; + } + } + else if (status) { + status.set = 'update'; + } + } + if (ttl !== 0 && !this.#ttls) { + this.#initializeTTLTracking(); + } + if (this.#ttls) { + if (!noUpdateTTL) { + this.#setItemTTL(index, ttl, start); + } + if (status) + this.#statusTTL(status, index); + } + if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) { + const dt = this.#disposed; + let task; + while ((task = dt?.shift())) { + this.#disposeAfter?.(...task); + } + } + return this; + } + /** + * Evict the least recently used item, returning its value or + * `undefined` if cache is empty. + */ + pop() { + try { + while (this.#size) { + const val = this.#valList[this.#head]; + this.#evict(true); + if (this.#isBackgroundFetch(val)) { + if (val.__staleWhileFetching) { + return val.__staleWhileFetching; + } + } + else if (val !== undefined) { + return val; + } + } + } + finally { + if (this.#hasDisposeAfter && this.#disposed) { + const dt = this.#disposed; + let task; + while ((task = dt?.shift())) { + this.#disposeAfter?.(...task); + } + } + } + } + #evict(free) { + const head = this.#head; + const k = this.#keyList[head]; + const v = this.#valList[head]; + if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) { + v.__abortController.abort(new Error('evicted')); + } + else if (this.#hasDispose || this.#hasDisposeAfter) { + if (this.#hasDispose) { + this.#dispose?.(v, k, 'evict'); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([v, k, 'evict']); + } + } + this.#removeItemSize(head); + // if we aren't about to use the index, then null these out + if (free) { + this.#keyList[head] = undefined; + this.#valList[head] = undefined; + this.#free.push(head); + } + if (this.#size === 1) { + this.#head = this.#tail = 0; + this.#free.length = 0; + } + else { + this.#head = this.#next[head]; + } + this.#keyMap.delete(k); + this.#size--; + return head; + } + /** + * Check if a key is in the cache, without updating the recency of use. + * Will return false if the item is stale, even though it is technically + * in the cache. + * + * Check if a key is in the cache, without updating the recency of + * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set + * to `true` in either the options or the constructor. + * + * Will return `false` if the item is stale, even though it is technically in + * the cache. The difference can be determined (if it matters) by using a + * `status` argument, and inspecting the `has` field. + * + * Will not update item age unless + * {@link LRUCache.OptionsBase.updateAgeOnHas} is set. + */ + has(k, hasOptions = {}) { + const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions; + const index = this.#keyMap.get(k); + if (index !== undefined) { + const v = this.#valList[index]; + if (this.#isBackgroundFetch(v) && + v.__staleWhileFetching === undefined) { + return false; + } + if (!this.#isStale(index)) { + if (updateAgeOnHas) { + this.#updateItemAge(index); + } + if (status) { + status.has = 'hit'; + this.#statusTTL(status, index); + } + return true; + } + else if (status) { + status.has = 'stale'; + this.#statusTTL(status, index); + } + } + else if (status) { + status.has = 'miss'; + } + return false; + } + /** + * Like {@link LRUCache#get} but doesn't update recency or delete stale + * items. + * + * Returns `undefined` if the item is stale, unless + * {@link LRUCache.OptionsBase.allowStale} is set. + */ + peek(k, peekOptions = {}) { + const { allowStale = this.allowStale } = peekOptions; + const index = this.#keyMap.get(k); + if (index === undefined || + (!allowStale && this.#isStale(index))) { + return; + } + const v = this.#valList[index]; + // either stale and allowed, or forcing a refresh of non-stale value + return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; + } + #backgroundFetch(k, index, options, context) { + const v = index === undefined ? undefined : this.#valList[index]; + if (this.#isBackgroundFetch(v)) { + return v; + } + const ac = new AC(); + const { signal } = options; + // when/if our AC signals, then stop listening to theirs. + signal?.addEventListener('abort', () => ac.abort(signal.reason), { + signal: ac.signal, + }); + const fetchOpts = { + signal: ac.signal, + options, + context, + }; + const cb = (v, updateCache = false) => { + const { aborted } = ac.signal; + const ignoreAbort = options.ignoreFetchAbort && v !== undefined; + if (options.status) { + if (aborted && !updateCache) { + options.status.fetchAborted = true; + options.status.fetchError = ac.signal.reason; + if (ignoreAbort) + options.status.fetchAbortIgnored = true; + } + else { + options.status.fetchResolved = true; + } + } + if (aborted && !ignoreAbort && !updateCache) { + return fetchFail(ac.signal.reason); + } + // either we didn't abort, and are still here, or we did, and ignored + const bf = p; + if (this.#valList[index] === p) { + if (v === undefined) { + if (bf.__staleWhileFetching) { + this.#valList[index] = bf.__staleWhileFetching; + } + else { + this.#delete(k, 'fetch'); + } + } + else { + if (options.status) + options.status.fetchUpdated = true; + this.set(k, v, fetchOpts.options); + } + } + return v; + }; + const eb = (er) => { + if (options.status) { + options.status.fetchRejected = true; + options.status.fetchError = er; + } + return fetchFail(er); + }; + const fetchFail = (er) => { + const { aborted } = ac.signal; + const allowStaleAborted = aborted && options.allowStaleOnFetchAbort; + const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection; + const noDelete = allowStale || options.noDeleteOnFetchRejection; + const bf = p; + if (this.#valList[index] === p) { + // if we allow stale on fetch rejections, then we need to ensure that + // the stale value is not removed from the cache when the fetch fails. + const del = !noDelete || bf.__staleWhileFetching === undefined; + if (del) { + this.#delete(k, 'fetch'); + } + else if (!allowStaleAborted) { + // still replace the *promise* with the stale value, + // since we are done with the promise at this point. + // leave it untouched if we're still waiting for an + // aborted background fetch that hasn't yet returned. + this.#valList[index] = bf.__staleWhileFetching; + } + } + if (allowStale) { + if (options.status && bf.__staleWhileFetching !== undefined) { + options.status.returnedStale = true; + } + return bf.__staleWhileFetching; + } + else if (bf.__returned === bf) { + throw er; + } + }; + const pcall = (res, rej) => { + const fmp = this.#fetchMethod?.(k, v, fetchOpts); + if (fmp && fmp instanceof Promise) { + fmp.then(v => res(v === undefined ? undefined : v), rej); + } + // ignored, we go until we finish, regardless. + // defer check until we are actually aborting, + // so fetchMethod can override. + ac.signal.addEventListener('abort', () => { + if (!options.ignoreFetchAbort || + options.allowStaleOnFetchAbort) { + res(undefined); + // when it eventually resolves, update the cache. + if (options.allowStaleOnFetchAbort) { + res = v => cb(v, true); + } + } + }); + }; + if (options.status) + options.status.fetchDispatched = true; + const p = new Promise(pcall).then(cb, eb); + const bf = Object.assign(p, { + __abortController: ac, + __staleWhileFetching: v, + __returned: undefined, + }); + if (index === undefined) { + // internal, don't expose status. + this.set(k, bf, { ...fetchOpts.options, status: undefined }); + index = this.#keyMap.get(k); + } + else { + this.#valList[index] = bf; + } + return bf; + } + #isBackgroundFetch(p) { + if (!this.#hasFetchMethod) + return false; + const b = p; + return (!!b && + b instanceof Promise && + b.hasOwnProperty('__staleWhileFetching') && + b.__abortController instanceof AC); + } + async fetch(k, fetchOptions = {}) { + const { + // get options + allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, + // set options + ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL, + // fetch exclusive options + noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions; + if (!this.#hasFetchMethod) { + if (status) + status.fetch = 'get'; + return this.get(k, { + allowStale, + updateAgeOnGet, + noDeleteOnStaleGet, + status, + }); + } + const options = { + allowStale, + updateAgeOnGet, + noDeleteOnStaleGet, + ttl, + noDisposeOnSet, + size, + sizeCalculation, + noUpdateTTL, + noDeleteOnFetchRejection, + allowStaleOnFetchRejection, + allowStaleOnFetchAbort, + ignoreFetchAbort, + status, + signal, + }; + let index = this.#keyMap.get(k); + if (index === undefined) { + if (status) + status.fetch = 'miss'; + const p = this.#backgroundFetch(k, index, options, context); + return (p.__returned = p); + } + else { + // in cache, maybe already fetching + const v = this.#valList[index]; + if (this.#isBackgroundFetch(v)) { + const stale = allowStale && v.__staleWhileFetching !== undefined; + if (status) { + status.fetch = 'inflight'; + if (stale) + status.returnedStale = true; + } + return stale ? v.__staleWhileFetching : (v.__returned = v); + } + // if we force a refresh, that means do NOT serve the cached value, + // unless we are already in the process of refreshing the cache. + const isStale = this.#isStale(index); + if (!forceRefresh && !isStale) { + if (status) + status.fetch = 'hit'; + this.#moveToTail(index); + if (updateAgeOnGet) { + this.#updateItemAge(index); + } + if (status) + this.#statusTTL(status, index); + return v; + } + // ok, it is stale or a forced refresh, and not already fetching. + // refresh the cache. + const p = this.#backgroundFetch(k, index, options, context); + const hasStale = p.__staleWhileFetching !== undefined; + const staleVal = hasStale && allowStale; + if (status) { + status.fetch = isStale ? 'stale' : 'refresh'; + if (staleVal && isStale) + status.returnedStale = true; + } + return staleVal ? p.__staleWhileFetching : (p.__returned = p); + } + } + async forceFetch(k, fetchOptions = {}) { + const v = await this.fetch(k, fetchOptions); + if (v === undefined) + throw new Error('fetch() returned undefined'); + return v; + } + memo(k, memoOptions = {}) { + const memoMethod = this.#memoMethod; + if (!memoMethod) { + throw new Error('no memoMethod provided to constructor'); + } + const { context, forceRefresh, ...options } = memoOptions; + const v = this.get(k, options); + if (!forceRefresh && v !== undefined) + return v; + const vv = memoMethod(k, v, { + options, + context, + }); + this.set(k, vv, options); + return vv; + } + /** + * Return a value from the cache. Will update the recency of the cache + * entry found. + * + * If the key is not found, get() will return `undefined`. + */ + get(k, getOptions = {}) { + const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions; + const index = this.#keyMap.get(k); + if (index !== undefined) { + const value = this.#valList[index]; + const fetching = this.#isBackgroundFetch(value); + if (status) + this.#statusTTL(status, index); + if (this.#isStale(index)) { + if (status) + status.get = 'stale'; + // delete only if not an in-flight background fetch + if (!fetching) { + if (!noDeleteOnStaleGet) { + this.#delete(k, 'expire'); + } + if (status && allowStale) + status.returnedStale = true; + return allowStale ? value : undefined; + } + else { + if (status && + allowStale && + value.__staleWhileFetching !== undefined) { + status.returnedStale = true; + } + return allowStale ? value.__staleWhileFetching : undefined; + } + } + else { + if (status) + status.get = 'hit'; + // if we're currently fetching it, we don't actually have it yet + // it's not stale, which means this isn't a staleWhileRefetching. + // If it's not stale, and fetching, AND has a __staleWhileFetching + // value, then that means the user fetched with {forceRefresh:true}, + // so it's safe to return that value. + if (fetching) { + return value.__staleWhileFetching; + } + this.#moveToTail(index); + if (updateAgeOnGet) { + this.#updateItemAge(index); + } + return value; + } + } + else if (status) { + status.get = 'miss'; + } + } + #connect(p, n) { + this.#prev[n] = p; + this.#next[p] = n; + } + #moveToTail(index) { + // if tail already, nothing to do + // if head, move head to next[index] + // else + // move next[prev[index]] to next[index] (head has no prev) + // move prev[next[index]] to prev[index] + // prev[index] = tail + // next[tail] = index + // tail = index + if (index !== this.#tail) { + if (index === this.#head) { + this.#head = this.#next[index]; + } + else { + this.#connect(this.#prev[index], this.#next[index]); + } + this.#connect(this.#tail, index); + this.#tail = index; + } + } + /** + * Deletes a key out of the cache. + * + * Returns true if the key was deleted, false otherwise. + */ + delete(k) { + return this.#delete(k, 'delete'); + } + #delete(k, reason) { + let deleted = false; + if (this.#size !== 0) { + const index = this.#keyMap.get(k); + if (index !== undefined) { + deleted = true; + if (this.#size === 1) { + this.#clear(reason); + } + else { + this.#removeItemSize(index); + const v = this.#valList[index]; + if (this.#isBackgroundFetch(v)) { + v.__abortController.abort(new Error('deleted')); + } + else if (this.#hasDispose || this.#hasDisposeAfter) { + if (this.#hasDispose) { + this.#dispose?.(v, k, reason); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([v, k, reason]); + } + } + this.#keyMap.delete(k); + this.#keyList[index] = undefined; + this.#valList[index] = undefined; + if (index === this.#tail) { + this.#tail = this.#prev[index]; + } + else if (index === this.#head) { + this.#head = this.#next[index]; + } + else { + const pi = this.#prev[index]; + this.#next[pi] = this.#next[index]; + const ni = this.#next[index]; + this.#prev[ni] = this.#prev[index]; + } + this.#size--; + this.#free.push(index); + } + } + } + if (this.#hasDisposeAfter && this.#disposed?.length) { + const dt = this.#disposed; + let task; + while ((task = dt?.shift())) { + this.#disposeAfter?.(...task); + } + } + return deleted; + } + /** + * Clear the cache entirely, throwing away all values. + */ + clear() { + return this.#clear('delete'); + } + #clear(reason) { + for (const index of this.#rindexes({ allowStale: true })) { + const v = this.#valList[index]; + if (this.#isBackgroundFetch(v)) { + v.__abortController.abort(new Error('deleted')); + } + else { + const k = this.#keyList[index]; + if (this.#hasDispose) { + this.#dispose?.(v, k, reason); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([v, k, reason]); + } + } + } + this.#keyMap.clear(); + this.#valList.fill(undefined); + this.#keyList.fill(undefined); + if (this.#ttls && this.#starts) { + this.#ttls.fill(0); + this.#starts.fill(0); + } + if (this.#sizes) { + this.#sizes.fill(0); + } + this.#head = 0; + this.#tail = 0; + this.#free.length = 0; + this.#calculatedSize = 0; + this.#size = 0; + if (this.#hasDisposeAfter && this.#disposed) { + const dt = this.#disposed; + let task; + while ((task = dt?.shift())) { + this.#disposeAfter?.(...task); + } + } + } +} +exports.LRUCache = LRUCache; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/commonjs/index.js.map b/node_modules/lru-cache/dist/commonjs/index.js.map new file mode 100644 index 0000000..557c616 --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;GAEG;;;AAIH,MAAM,IAAI,GACR,OAAO,WAAW,KAAK,QAAQ;IAC/B,WAAW;IACX,OAAO,WAAW,CAAC,GAAG,KAAK,UAAU;IACnC,CAAC,CAAC,WAAW;IACb,CAAC,CAAC,IAAI,CAAA;AAEV,MAAM,MAAM,GAAG,IAAI,GAAG,EAAU,CAAA;AAKhC,qBAAqB;AACrB,MAAM,OAAO,GAAG,CACd,OAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAChC,CAAA;AACzB,qBAAqB;AAErB,MAAM,WAAW,GAAG,CAClB,GAAW,EACX,IAAY,EACZ,IAAY,EACZ,EAAQ,EACR,EAAE;IACF,OAAO,OAAO,CAAC,WAAW,KAAK,UAAU;QACvC,CAAC,CAAC,O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IAAI,IAAI,CAAC,SAAS,EAAE;YAC3C,MAAM,EAAE,GAAG,IAAI,CAAC,SAAS,CAAA;YACzB,IAAI,IAAmC,CAAA;YACvC,OAAO,CAAC,IAAI,GAAG,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE;gBAC3B,IAAI,CAAC,aAAa,EAAE,CAAC,GAAG,IAAI,CAAC,CAAA;aAC9B;SACF;IACH,CAAC;CACF;AAxwDD,4BAwwDC","sourcesContent":["/**\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 * - `evict`: The item was evicted because it is the least recently used,\n * and the cache is full.\n * - `set`: A new value was set, overwriting the old value being disposed.\n * - `delete`: The item was explicitly deleted, either by calling\n * {@link LRUCache#delete}, {@link LRUCache#clear}, or\n * {@link LRUCache#set} with an undefined value.\n * - `expire`: The item was removed due to exceeding its TTL.\n * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned\n * `undefined` or was aborted, causing the item to be deleted.\n */\n export type DisposeReason =\n | 'evict'\n | 'set'\n | 'delete'\n | 'expire'\n | 'fetch'\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 * Occasionally, it may be useful to track the internal behavior of the\n * cache, particularly for logging, debugging, or for behavior within the\n * `fetchMethod`. To do this, you can pass a `status` object to the\n * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set},\n * {@link LRUCache#memo}, and {@link LRUCache#has} methods.\n *\n * The `status` option should be a plain JavaScript object. The following\n * fields will be set on it appropriately, depending on the situation.\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 {@link OptionsBase.fetchMethod}, so\n * {@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 export interface MemoOptions\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 /**\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.memoMethod} as\n * the {@link MemoizerOptions.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 status?: Status\n }\n /**\n * Options provided to {@link LRUCache#memo} when the FC type is something\n * other than `unknown`, `undefined`, or `void`\n */\n export interface MemoOptionsWithContext\n extends MemoOptions {\n context: FC\n }\n /**\n * Options provided to {@link LRUCache#memo} when the FC type is\n * `undefined` or `void`\n */\n export interface MemoOptionsNoContext\n extends MemoOptions {\n context?: undefined\n }\n\n /**\n * Options provided to the\n * {@link OptionsBase.memoMethod} function.\n */\n export interface MemoizerOptions {\n options: MemoizerMemoOptions\n /**\n * Object provided in the {@link MemoOptions.context} option to\n * {@link LRUCache#memo}\n */\n context: FC\n }\n\n /**\n * options which override the options set in the LRUCache constructor\n * when calling {@link LRUCache#memo}.\n *\n * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n * {@link MemoOptions.forceRefresh}, and\n * {@link MemoerOptions.context}\n *\n * Any of these may be modified in the {@link OptionsBase.memoMethod}\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 memoMethod is called.\n */\n export interface MemoizerMemoOptions\n extends Pick<\n OptionsBase,\n | 'allowStale'\n | 'updateAgeOnGet'\n | 'noDeleteOnStaleGet'\n | 'sizeCalculation'\n | 'ttl'\n | 'noDisposeOnSet'\n | 'noUpdateTTL'\n > {\n status?: Status\n size?: Size\n start?: Milliseconds\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 * the type signature for the {@link OptionsBase.memoMethod} option.\n */\n export type Memoizer = (\n key: K,\n staleValue: V | undefined,\n options: MemoizerOptions\n ) => V\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 * All options are also available on the {@link LRUCache} instance, making\n * it safe to pass an LRUCache instance as the options argumemnt to\n * make another empty cache of the same type.\n *\n * Some options are marked as read-only, because changing them after\n * instantiation is not safe. Changing any of the other options will of\n * course only have an effect on subsequent method calls.\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 * **It is strongly recommended to set a `max` to prevent unbounded growth\n * of the cache.**\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 by\n * default, and MAY live in the cache, contributing to its LRU max, long\n * after they have expired, unless {@link OptionsBase.ttlAutopurge} is\n * set.\n *\n * If set to `0` (the default value), then that means \"do not track\n * TTL\", not \"expire immediately\".\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 * This is not primarily a TTL cache, and does not make strong TTL\n * guarantees. There is no pre-emptive pruning of expired items, but you\n * _may_ set a TTL on the cache, and it will treat expired items as missing\n * when they are fetched, and delete them.\n *\n * Optional, but must be a non-negative integer in ms if specified.\n *\n * This may be overridden by passing an options object to `cache.set()`.\n *\n * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n * positive integer if set.\n *\n * Even if ttl tracking is enabled, **it is strongly recommended to set a\n * `max` to prevent unbounded growth of the cache.**\n *\n * If ttl tracking is enabled, and `max` and `maxSize` are not set,\n * and `ttlAutopurge` is not set, then a warning will be emitted\n * cautioning about the potential for unbounded memory consumption.\n * (The TypeScript definitions will also discourage this.)\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 *\n * Note that this may *significantly* degrade performance, especially if\n * the cache is storing a large number of items. It is almost always best\n * to just leave the stale items in the cache, and let them fall out as new\n * 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 * Use with caution!\n */\n ttlAutopurge?: boolean\n\n /**\n * When using time-expiring entries with `ttl`, setting this to `true` will\n * make each item's age reset to 0 whenever it is retrieved from cache with\n * {@link LRUCache#get}, causing it to not expire. (It can still fall out\n * of cache based on recency of use, of course.)\n *\n * Has no effect if {@link OptionsBase.ttl} is not set.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n */\n updateAgeOnGet?: boolean\n\n /**\n * When using time-expiring entries with `ttl`, setting this to `true` will\n * make each item's age reset to 0 whenever its presence in the cache is\n * checked with {@link LRUCache#has}, causing it to not expire. (It can\n * still fall out of cache based on recency of use, of course.)\n *\n * Has no effect if {@link OptionsBase.ttl} is not set.\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 * By default, if you set `ttl`, stale items will only be deleted from the\n * cache when you `get(key)`. That is, it's not preemptively pruning items,\n * unless {@link OptionsBase.ttlAutopurge} is set.\n *\n * If you set `allowStale:true`, it'll return the stale value *as well as*\n * deleting it. If you don't set this, then it'll return `undefined` when\n * you try to get a stale entry.\n *\n * Note that when a stale entry is fetched, _even if it is returned due to\n * `allowStale` being set_, it is removed from the cache immediately. You\n * can suppress this behavior by setting\n * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in\n * the options provided to {@link LRUCache#get}.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n * The `cache.has()` method will always return `false` for stale items.\n *\n * Only relevant if a ttl is set.\n */\n allowStale?: boolean\n\n /**\n * Function that is called on items when they are dropped from the\n * cache, as `dispose(value, key, reason)`.\n *\n * This can be handy if you want to close file descriptors or do\n * other cleanup tasks when items are no longer stored in the cache.\n *\n * **NOTE**: It is called _before_ the item has been fully removed\n * from the cache, so if you want to put it right back in, you need\n * to wait until the next tick. If you try to add it back in during\n * the `dispose()` function call, it will break things in subtle and\n * weird ways.\n *\n * Unlike several other options, this may _not_ be overridden by\n * passing an option to `set()`, for performance reasons.\n *\n * The `reason` will be one of the following strings, corresponding\n * to the reason for the item's deletion:\n *\n * - `evict` Item was evicted to make space for a new addition\n * - `set` Item was overwritten by a new value\n * - `expire` Item expired its TTL\n * - `fetch` Item was deleted due to a failed or aborted fetch, or a\n * fetchMethod returning `undefined.\n * - `delete` Item was removed by explicit `cache.delete(key)`,\n * `cache.clear()`, or `cache.set(key, undefined)`.\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 *\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 *\n * This may be overridden by passing an options object to\n * {@link LRUCache#set}.\n *\n * Only relevant if `dispose` or `disposeAfter` are set.\n */\n noDisposeOnSet?: boolean\n\n /**\n * Boolean flag to tell the cache to not update the TTL when setting a new\n * value for an existing key (ie, when updating a value rather than\n * inserting a new value). Note that the TTL value is _always_ set (if\n * provided) when adding a new entry into the cache.\n *\n * Has no effect if a {@link OptionsBase.ttl} is not set.\n *\n * May be passed as an option to {@link LRUCache#set}.\n */\n noUpdateTTL?: boolean\n\n /**\n * Set to a positive integer to track the sizes of items added to the\n * cache, and automatically evict items in order to stay below this size.\n * Note that this may result in fewer than `max` items being stored.\n *\n * Attempting to add an item to the cache whose calculated size is greater\n * that this amount will be a no-op. The item will not be cached, and no\n * other items will be evicted.\n *\n * Optional, must be a positive integer if provided.\n *\n * Sets `maxEntrySize` to the same value, unless a different value is\n * provided for `maxEntrySize`.\n *\n * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n * positive integer if set.\n *\n * Even if size tracking is enabled, **it is strongly recommended to set a\n * `max` to prevent unbounded growth of the cache.**\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} or {@link OptionsBase.memoMethod}, then\n * it will not be stored in the cache.\n *\n * Attempting to add an item whose calculated size is greater than\n * this amount will not cache the item or evict any old items, but\n * WILL delete an existing value if one is already present.\n *\n * Optional, must be a positive integer if provided. Defaults to\n * the value of `maxSize` if provided.\n */\n maxEntrySize?: Size\n\n /**\n * A function that returns a number indicating the item's size.\n *\n * Requires {@link OptionsBase.maxSize} to be set.\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 * ```ts\n * fetchMethod(key, staleValue, { signal, options, context })\n * ```\n *\n * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent\n * to `Promise.resolve(cache.get(key))`.\n *\n * If at any time, `signal.aborted` is set to `true`, or if the\n * `signal.onabort` method is called, or if it emits an `'abort'` event\n * which you can listen to with `addEventListener`, then that means that\n * the fetch should be abandoned. This may be passed along to async\n * functions aware of AbortController/AbortSignal behavior.\n *\n * The `fetchMethod` should **only** return `undefined` or a Promise\n * resolving to `undefined` if the AbortController signaled an `abort`\n * event. In all other cases, it should return or resolve to a value\n * suitable for adding to the cache.\n *\n * The `options` object is a union of the options that may be provided to\n * `set()` and `get()`. If they are modified, then that will result in\n * modifying the settings to `cache.set()` when the value is resolved, and\n * in the case of\n * {@link OptionsBase.noDeleteOnFetchRejection} and\n * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of\n * `fetchMethod` failures.\n *\n * For example, a DNS cache may update the TTL based on the value returned\n * from a remote DNS server by changing `options.ttl` in the `fetchMethod`.\n */\n fetchMethod?: Fetcher\n\n /**\n * Method that provides the implementation for {@link LRUCache#memo}\n */\n memoMethod?: Memoizer\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 * When using time-expiring entries with `ttl`, by default stale\n * items will be removed from the cache when the key is accessed\n * with `cache.get()`.\n *\n * Setting this option will cause stale items to remain in the cache, until\n * they are explicitly deleted with `cache.delete(key)`, or retrieved with\n * `noDeleteOnStaleGet` set to `false`.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n *\n * Only relevant if a ttl is used.\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 {@link LRUCache#fetch}\n * fails, not any other times.\n *\n * If a `fetchMethod` fails, and there is no stale value available, the\n * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are\n * suppressed.\n *\n * Implies `noDeleteOnFetchRejection`.\n *\n * This may be set in calls to `fetch()`, or defaulted on the constructor,\n * or overridden by modifying the options object in the `fetchMethod`.\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\n * an `'abort'` event, whether user-triggered, or due to internal cache\n * 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\n * are not immediately resolved or rejected when they are aborted, and\n * instead 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 * For example:\n *\n * ```ts\n * const c = new LRUCache({\n * ttl: 100,\n * ignoreFetchAbort: true,\n * allowStaleOnFetchAbort: true,\n * fetchMethod: async (key, oldValue, { signal }) => {\n * // note: do NOT pass the signal to fetch()!\n * // let's say this fetch can take a long time.\n * const res = await fetch(`https://slow-backend-server/${key}`)\n * return await res.json()\n * },\n * })\n *\n * // this will return the stale value after 100ms, while still\n * // updating in the background for next time.\n * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) })\n * ```\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 * The `K` and `V` types define the key and value types, respectively. The\n * optional `FC` type defines the type of the `context` object passed to\n * `cache.fetch()` and `cache.memo()`.\n *\n * Keys and values **must not** be `null` or `undefined`.\n *\n * All properties from the options object (with the exception of `max`,\n * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are\n * added as normal public members. (The listed options are read-only getters.)\n *\n * Changing any of these will alter the defaults for subsequent method calls.\n */\nexport class LRUCache\n implements Map\n{\n // options that cannot be changed without disaster\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 readonly #memoMethod?: LRUCache.Memoizer\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 get memoMethod(): LRUCache.Memoizer | undefined {\n return this.#memoMethod\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 memoMethod,\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 memoMethod !== undefined &&\n typeof memoMethod !== 'function'\n ) {\n throw new TypeError('memoMethod must be a function if defined')\n }\n this.#memoMethod = memoMethod\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 number of ms left in the item's TTL. If item is not in cache,\n * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.\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, 'expire')\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\n * description of an object. Called by the built-in method\n * `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 most\n * recently used to least recently used.\n *\n * `fn` is called as `fn(value, key, cache)`.\n *\n * If `thisp` is provided, function will be called in the `this`-context of\n * the provided object, or the cache if no `thisp` object is provided.\n *\n * Does not update age or recenty of use, or 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, 'expire')\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. Returns `undefined` if the key is not present.\n *\n * Unlike {@link LRUCache#dump}, which is designed to be portable and survive\n * serialization, the `start` value is always the current timestamp, and the\n * `ttl` is a calculated remaining time to live (negative if expired).\n *\n * Always returns stale values, if their info is found in the cache, so be\n * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})\n * 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 {@link LRLUCache#load}.\n *\n * The `start` fields are calculated relative to a portable `Date.now()`\n * timestamp, even if `performance.now()` is available.\n *\n * Stale entries are always included in the `dump`, even if\n * {@link LRUCache.OptionsBase.allowStale} is false.\n *\n * Note: this returns an actual array, not a generator, so it can be more\n * easily passed around.\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 *\n * The shape of the resulting cache may be different if the same options are\n * not used in both caches.\n *\n * The `start` fields are assumed to be calculated relative to a portable\n * `Date.now()` timestamp, even if `performance.now()` is available.\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 * Fields on the {@link LRUCache.SetOptions} options param will override\n * their corresponding values in the constructor options for the scope\n * of this single `set()` operation.\n *\n * If `start` is provided, then that will set the effective start\n * time for the TTL calculation. Note that this must be a previous\n * value of `performance.now()` if supported, or a previous value of\n * `Date.now()` if not.\n *\n * Options object may also include `size`, which will prevent\n * calling the `sizeCalculation` function and just use the specified\n * number if it is a positive integer, and `noDisposeOnSet` which\n * will prevent calling a `dispose` function in the case of\n * overwrites.\n *\n * If the `size` (or return value of `sizeCalculation`) for a given\n * entry is greater than `maxEntrySize`, then the item will not be\n * added to the cache.\n *\n * Will update the recency of the entry.\n *\n * If the value is `undefined`, then this is an alias for\n * `cache.delete(key)`. `undefined` is never stored in the cache.\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, 'set')\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 * Check if a key is in the cache, without updating the recency of\n * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set\n * to `true` in either the options or the constructor.\n *\n * Will return `false` if the item is stale, even though it is technically in\n * the cache. The difference can be determined (if it matters) by using a\n * `status` argument, and inspecting the `has` field.\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, 'fetch')\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, 'fetch')\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 the value is in the cache and not stale, then the returned\n * Promise resolves to the value.\n *\n * If not in the cache, or beyond its TTL staleness, then\n * `fetchMethod(key, staleValue, { options, signal, context })` is\n * called, and the value returned will be added to the cache once\n * resolved.\n *\n * If called with `allowStale`, and an asynchronous fetch is\n * currently in progress to reload a stale value, then the former\n * stale value will be returned.\n *\n * If called with `forceRefresh`, then the cached item will be\n * re-fetched, even if it is not stale. However, if `allowStale` is also\n * set, then the old value will still be returned. This is useful\n * in cases where you want to force a reload of a cached value. If\n * a background fetch is already in progress, then `forceRefresh`\n * has no effect.\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 * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is\n * effectively an alias for `Promise.resolve(cache.get(key))`.\n *\n * When the fetch method resolves to a value, if the fetch has not\n * been aborted due to deletion, eviction, or being overwritten,\n * then it is added to the cache using the options provided.\n *\n * If the key is evicted or deleted before the `fetchMethod`\n * resolves, then the AbortSignal passed to the `fetchMethod` will\n * receive an `abort` event, and the promise returned by `fetch()`\n * will reject with the reason for the abort.\n *\n * If a `signal` is passed to the `fetch()` call, then aborting the\n * signal will abort the fetch and cause the `fetch()` promise to\n * reject with the reason provided.\n *\n * **Setting `context`**\n *\n * If an `FC` type is set to a type other than `unknown`, `void`, or\n * `undefined` in the {@link LRUCache} constructor, then all\n * calls to `cache.fetch()` _must_ provide a `context` option. If\n * set to `undefined` or `void`, then calls to fetch _must not_\n * provide a `context` option.\n *\n * The `context` param allows you to provide arbitrary data that\n * might be relevant in the course of fetching the data. It is only\n * relevant for the course of a single `fetch()` operation, and\n * discarded afterwards.\n *\n * **Note: `fetch()` calls are inflight-unique**\n *\n * If you call `fetch()` multiple times with the same key value,\n * then every call after the first will resolve on the same\n * promise1,\n * _even if they have different settings that would otherwise change\n * the behavior of the fetch_, such as `noDeleteOnFetchRejection`\n * or `ignoreFetchAbort`.\n *\n * In most cases, this is not a problem (in fact, only fetching\n * something once is what you probably want, if you're caching in\n * the first place). If you are changing the fetch() options\n * dramatically between runs, there's a good chance that you might\n * be trying to fit divergent semantics into a single object, and\n * would be better off with multiple cache instances.\n *\n * **1**: Ie, they're not the \"same Promise\", but they resolve at\n * the same time, because they're both waiting on the same\n * underlying fetchMethod response.\n */\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\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\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 * In some cases, `cache.fetch()` may resolve to `undefined`, either because\n * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning\n * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or\n * because `ignoreFetchAbort` was specified (either to the constructor or\n * in the {@link LRUCache.FetchOptions}). Also, the\n * {@link OptionsBase.fetchMethod} may return `undefined` or `void`, making\n * the test even more complicated.\n *\n * Because inferring the cases where `undefined` might be returned are so\n * cumbersome, but testing for `undefined` can also be annoying, this method\n * can be used, which will reject if `this.fetch()` resolves to undefined.\n */\n forceFetch(\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 forceFetch(\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 forceFetch(\n k: K,\n fetchOptions: LRUCache.FetchOptions = {}\n ): Promise {\n const v = await this.fetch(\n k,\n fetchOptions as unknown extends FC\n ? LRUCache.FetchOptions\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext\n : LRUCache.FetchOptionsWithContext\n )\n if (v === undefined) throw new Error('fetch() returned undefined')\n return v\n }\n\n /**\n * If the key is found in the cache, then this is equivalent to\n * {@link LRUCache#get}. If not, in the cache, then calculate the value using\n * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache.\n *\n * If an `FC` type is set to a type other than `unknown`, `void`, or\n * `undefined` in the LRUCache constructor, then all calls to `cache.memo()`\n * _must_ provide a `context` option. If set to `undefined` or `void`, then\n * calls to memo _must not_ provide a `context` option.\n *\n * The `context` param allows you to provide arbitrary data that might be\n * relevant in the course of fetching the data. It is only relevant for the\n * course of a single `memo()` operation, and discarded afterwards.\n */\n memo(\n k: K,\n memoOptions: unknown extends FC\n ? LRUCache.MemoOptions\n : FC extends undefined | void\n ? LRUCache.MemoOptionsNoContext\n : LRUCache.MemoOptionsWithContext\n ): V\n // this overload not allowed if context is required\n memo(\n k: unknown extends FC\n ? K\n : FC extends undefined | void\n ? K\n : never,\n memoOptions?: unknown extends FC\n ? LRUCache.MemoOptions\n : FC extends undefined | void\n ? LRUCache.MemoOptionsNoContext\n : never\n ): V\n memo(k: K, memoOptions: LRUCache.MemoOptions = {}) {\n const memoMethod = this.#memoMethod\n if (!memoMethod) {\n throw new Error('no memoMethod provided to constructor')\n }\n const { context, forceRefresh, ...options } = memoOptions\n const v = this.get(k, options)\n if (!forceRefresh && v !== undefined) return v\n const vv = memoMethod(k, v, {\n options,\n context,\n } as LRUCache.MemoizerOptions)\n this.set(k, vv, options)\n return vv\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, 'expire')\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 *\n * Returns true if the key was deleted, false otherwise.\n */\n delete(k: K) {\n return this.#delete(k, 'delete')\n }\n\n #delete(k: K, reason: LRUCache.DisposeReason) {\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(reason)\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, reason)\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v as V, k, reason])\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 return this.#clear('delete')\n }\n #clear(reason: LRUCache.DisposeReason) {\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, reason)\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v as V, k as K, reason])\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"]} \ No newline at end of file diff --git a/node_modules/lru-cache/dist/commonjs/index.min.js b/node_modules/lru-cache/dist/commonjs/index.min.js new file mode 100644 index 0000000..ad643b0 --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/index.min.js @@ -0,0 +1,2 @@ +"use strict";var G=(l,t,e)=>{if(!t.has(l))throw TypeError("Cannot "+e)};var j=(l,t,e)=>(G(l,t,"read from private field"),e?e.call(l):t.get(l)),I=(l,t,e)=>{if(t.has(l))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(l):t.set(l,e)},x=(l,t,e,i)=>(G(l,t,"write to private field"),i?i.call(l,e):t.set(l,e),e);Object.defineProperty(exports,"__esModule",{value:!0});exports.LRUCache=void 0;var T=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,P=new Set,U=typeof process=="object"&&process?process:{},H=(l,t,e,i)=>{typeof U.emitWarning=="function"?U.emitWarning(l,t,e,i):console.error(`[${e}] ${t}: ${l}`)},D=globalThis.AbortController,N=globalThis.AbortSignal;if(typeof D>"u"){N=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(i,s){this._onabort.push(s)}},D=class{constructor(){t()}signal=new N;abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=!0;for(let s of this.signal._onabort)s(i);this.signal.onabort?.(i)}}};let l=U.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{l&&(l=!1,H("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 V=l=>!P.has(l),Y=Symbol("type"),A=l=>l&&l===Math.floor(l)&&l>0&&isFinite(l),k=l=>A(l)?l<=Math.pow(2,8)?Uint8Array:l<=Math.pow(2,16)?Uint16Array:l<=Math.pow(2,32)?Uint32Array:l<=Number.MAX_SAFE_INTEGER?E:null:null,E=class extends Array{constructor(t){super(t),this.fill(0)}},v,O=class{heap;length;static create(t){let e=k(t);if(!e)return[];x(O,v,!0);let i=new O(t,e);return x(O,v,!1),i}constructor(t,e){if(!j(O,v))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]}},W=O;v=new WeakMap,I(W,v,!1);var C=class{#g;#f;#p;#w;#R;#W;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#n;#S;#s;#i;#t;#l;#c;#o;#h;#_;#r;#b;#m;#u;#y;#E;#a;static unsafeExposeInternals(t){return{starts:t.#m,ttls:t.#u,sizes:t.#b,keyMap:t.#s,keyList:t.#i,valList:t.#t,next:t.#l,prev:t.#c,get head(){return t.#o},get tail(){return t.#h},free:t.#_,isBackgroundFetch:e=>t.#e(e),backgroundFetch:(e,i,s,n)=>t.#x(e,i,s,n),moveToTail:e=>t.#C(e),indexes:e=>t.#A(e),rindexes:e=>t.#F(e),isStale:e=>t.#d(e)}}get max(){return this.#g}get maxSize(){return this.#f}get calculatedSize(){return this.#S}get size(){return this.#n}get fetchMethod(){return this.#R}get memoMethod(){return this.#W}get dispose(){return this.#p}get disposeAfter(){return this.#w}constructor(t){let{max:e=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:h,updateAgeOnHas:o,allowStale:r,dispose:g,disposeAfter:b,noDisposeOnSet:f,noUpdateTTL:u,maxSize:c=0,maxEntrySize:F=0,sizeCalculation:d,fetchMethod:S,memoMethod:a,noDeleteOnFetchRejection:w,noDeleteOnStaleGet:m,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:_,ignoreFetchAbort:z}=t;if(e!==0&&!A(e))throw new TypeError("max option must be a nonnegative integer");let y=e?k(e):Array;if(!y)throw new Error("invalid max value: "+e);if(this.#g=e,this.#f=c,this.maxEntrySize=F||this.#f,this.sizeCalculation=d,this.sizeCalculation){if(!this.#f&&!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(a!==void 0&&typeof a!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#W=a,S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#R=S,this.#E=!!S,this.#s=new Map,this.#i=new Array(e).fill(void 0),this.#t=new Array(e).fill(void 0),this.#l=new y(e),this.#c=new y(e),this.#o=0,this.#h=0,this.#_=W.create(e),this.#n=0,this.#S=0,typeof g=="function"&&(this.#p=g),typeof b=="function"?(this.#w=b,this.#r=[]):(this.#w=void 0,this.#r=void 0),this.#y=!!this.#p,this.#a=!!this.#w,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!w,this.allowStaleOnFetchRejection=!!p,this.allowStaleOnFetchAbort=!!_,this.ignoreFetchAbort=!!z,this.maxEntrySize!==0){if(this.#f!==0&&!A(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!A(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#P()}if(this.allowStale=!!r,this.noDeleteOnStaleGet=!!m,this.updateAgeOnGet=!!h,this.updateAgeOnHas=!!o,this.ttlResolution=A(s)||s===0?s:1,this.ttlAutopurge=!!n,this.ttl=i||0,this.ttl){if(!A(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#U()}if(this.#g===0&&this.ttl===0&&this.#f===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#g&&!this.#f){let R="LRU_CACHE_UNBOUNDED";V(R)&&(P.add(R),H("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",R,C))}}getRemainingTTL(t){return this.#s.has(t)?1/0:0}#U(){let t=new E(this.#g),e=new E(this.#g);this.#u=t,this.#m=e,this.#M=(n,h,o=T.now())=>{if(e[n]=h!==0?o:0,t[n]=h,h!==0&&this.ttlAutopurge){let r=setTimeout(()=>{this.#d(n)&&this.#T(this.#i[n],"expire")},h+1);r.unref&&r.unref()}},this.#v=n=>{e[n]=t[n]!==0?T.now():0},this.#O=(n,h)=>{if(t[h]){let o=t[h],r=e[h];if(!o||!r)return;n.ttl=o,n.start=r,n.now=i||s();let g=n.now-r;n.remainingTTL=o-g}};let i=0,s=()=>{let n=T.now();if(this.ttlResolution>0){i=n;let h=setTimeout(()=>i=0,this.ttlResolution);h.unref&&h.unref()}return n};this.getRemainingTTL=n=>{let h=this.#s.get(n);if(h===void 0)return 0;let o=t[h],r=e[h];if(!o||!r)return 1/0;let g=(i||s())-r;return o-g},this.#d=n=>{let h=e[n],o=t[n];return!!o&&!!h&&(i||s())-h>o}}#v=()=>{};#O=()=>{};#M=()=>{};#d=()=>!1;#P(){let t=new E(this.#g);this.#S=0,this.#b=t,this.#z=e=>{this.#S-=t[e],t[e]=0},this.#G=(e,i,s,n)=>{if(this.#e(i))return 0;if(!A(s))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(s=n(i,e),!A(s))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 s},this.#D=(e,i,s)=>{if(t[e]=i,this.#f){let n=this.#f-t[e];for(;this.#S>n;)this.#L(!0)}this.#S+=t[e],s&&(s.entrySize=i,s.totalCalculatedSize=this.#S)}}#z=t=>{};#D=(t,e,i)=>{};#G=(t,e,i,s)=>{if(i||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#h;!(!this.#j(e)||((t||!this.#d(e))&&(yield e),e===this.#o));)e=this.#c[e]}*#F({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#o;!(!this.#j(e)||((t||!this.#d(e))&&(yield e),e===this.#h));)e=this.#l[e]}#j(t){return t!==void 0&&this.#s.get(this.#i[t])===t}*entries(){for(let t of this.#A())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*rentries(){for(let t of this.#F())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*keys(){for(let t of this.#A()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*rkeys(){for(let t of this.#F()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*values(){for(let t of this.#A())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}*rvalues(){for(let t of this.#F())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;if(n!==void 0&&t(n,this.#i[i],this))return this.get(this.#i[i],e)}}forEach(t,e=this){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(e,n,this.#i[i],this)}}rforEach(t,e=this){for(let i of this.#F()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(e,n,this.#i[i],this)}}purgeStale(){let t=!1;for(let e of this.#F({allowStale:!0}))this.#d(e)&&(this.#T(this.#i[e],"expire"),t=!0);return t}info(t){let e=this.#s.get(t);if(e===void 0)return;let i=this.#t[e],s=this.#e(i)?i.__staleWhileFetching:i;if(s===void 0)return;let n={value:s};if(this.#u&&this.#m){let h=this.#u[e],o=this.#m[e];if(h&&o){let r=h-(T.now()-o);n.ttl=r,n.start=Date.now()}}return this.#b&&(n.size=this.#b[e]),n}dump(){let t=[];for(let e of this.#A({allowStale:!0})){let i=this.#i[e],s=this.#t[e],n=this.#e(s)?s.__staleWhileFetching:s;if(n===void 0||i===void 0)continue;let h={value:n};if(this.#u&&this.#m){h.ttl=this.#u[e];let o=T.now()-this.#m[e];h.start=Math.floor(Date.now()-o)}this.#b&&(h.size=this.#b[e]),t.unshift([i,h])}return t}load(t){this.clear();for(let[e,i]of t){if(i.start){let s=Date.now()-i.start;i.start=T.now()-s}this.set(e,i.value,i)}}set(t,e,i={}){if(e===void 0)return this.delete(t),this;let{ttl:s=this.ttl,start:n,noDisposeOnSet:h=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:r}=i,{noUpdateTTL:g=this.noUpdateTTL}=i,b=this.#G(t,e,i.size||0,o);if(this.maxEntrySize&&b>this.maxEntrySize)return r&&(r.set="miss",r.maxEntrySizeExceeded=!0),this.#T(t,"set"),this;let f=this.#n===0?void 0:this.#s.get(t);if(f===void 0)f=this.#n===0?this.#h:this.#_.length!==0?this.#_.pop():this.#n===this.#g?this.#L(!1):this.#n,this.#i[f]=t,this.#t[f]=e,this.#s.set(t,f),this.#l[this.#h]=f,this.#c[f]=this.#h,this.#h=f,this.#n++,this.#D(f,b,r),r&&(r.set="add"),g=!1;else{this.#C(f);let u=this.#t[f];if(e!==u){if(this.#E&&this.#e(u)){u.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:c}=u;c!==void 0&&!h&&(this.#y&&this.#p?.(c,t,"set"),this.#a&&this.#r?.push([c,t,"set"]))}else h||(this.#y&&this.#p?.(u,t,"set"),this.#a&&this.#r?.push([u,t,"set"]));if(this.#z(f),this.#D(f,b,r),this.#t[f]=e,r){r.set="replace";let c=u&&this.#e(u)?u.__staleWhileFetching:u;c!==void 0&&(r.oldValue=c)}}else r&&(r.set="update")}if(s!==0&&!this.#u&&this.#U(),this.#u&&(g||this.#M(f,s,n),r&&this.#O(r,f)),!h&&this.#a&&this.#r){let u=this.#r,c;for(;c=u?.shift();)this.#w?.(...c)}return this}pop(){try{for(;this.#n;){let t=this.#t[this.#o];if(this.#L(!0),this.#e(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#a&&this.#r){let t=this.#r,e;for(;e=t?.shift();)this.#w?.(...e)}}}#L(t){let e=this.#o,i=this.#i[e],s=this.#t[e];return this.#E&&this.#e(s)?s.__abortController.abort(new Error("evicted")):(this.#y||this.#a)&&(this.#y&&this.#p?.(s,i,"evict"),this.#a&&this.#r?.push([s,i,"evict"])),this.#z(e),t&&(this.#i[e]=void 0,this.#t[e]=void 0,this.#_.push(e)),this.#n===1?(this.#o=this.#h=0,this.#_.length=0):this.#o=this.#l[e],this.#s.delete(i),this.#n--,e}has(t,e={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=e,n=this.#s.get(t);if(n!==void 0){let h=this.#t[n];if(this.#e(h)&&h.__staleWhileFetching===void 0)return!1;if(this.#d(n))s&&(s.has="stale",this.#O(s,n));else return i&&this.#v(n),s&&(s.has="hit",this.#O(s,n)),!0}else s&&(s.has="miss");return!1}peek(t,e={}){let{allowStale:i=this.allowStale}=e,s=this.#s.get(t);if(s===void 0||!i&&this.#d(s))return;let n=this.#t[s];return this.#e(n)?n.__staleWhileFetching:n}#x(t,e,i,s){let n=e===void 0?void 0:this.#t[e];if(this.#e(n))return n;let h=new D,{signal:o}=i;o?.addEventListener("abort",()=>h.abort(o.reason),{signal:h.signal});let r={signal:h.signal,options:i,context:s},g=(d,S=!1)=>{let{aborted:a}=h.signal,w=i.ignoreFetchAbort&&d!==void 0;if(i.status&&(a&&!S?(i.status.fetchAborted=!0,i.status.fetchError=h.signal.reason,w&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),a&&!w&&!S)return f(h.signal.reason);let m=c;return this.#t[e]===c&&(d===void 0?m.__staleWhileFetching?this.#t[e]=m.__staleWhileFetching:this.#T(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.set(t,d,r.options))),d},b=d=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=d),f(d)),f=d=>{let{aborted:S}=h.signal,a=S&&i.allowStaleOnFetchAbort,w=a||i.allowStaleOnFetchRejection,m=w||i.noDeleteOnFetchRejection,p=c;if(this.#t[e]===c&&(!m||p.__staleWhileFetching===void 0?this.#T(t,"fetch"):a||(this.#t[e]=p.__staleWhileFetching)),w)return i.status&&p.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),p.__staleWhileFetching;if(p.__returned===p)throw d},u=(d,S)=>{let a=this.#R?.(t,n,r);a&&a instanceof Promise&&a.then(w=>d(w===void 0?void 0:w),S),h.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(d(void 0),i.allowStaleOnFetchAbort&&(d=w=>g(w,!0)))})};i.status&&(i.status.fetchDispatched=!0);let c=new Promise(u).then(g,b),F=Object.assign(c,{__abortController:h,__staleWhileFetching:n,__returned:void 0});return e===void 0?(this.set(t,F,{...r.options,status:void 0}),e=this.#s.get(t)):this.#t[e]=F,F}#e(t){if(!this.#E)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof D}async fetch(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:h=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:r=0,sizeCalculation:g=this.sizeCalculation,noUpdateTTL:b=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:u=this.allowStaleOnFetchRejection,ignoreFetchAbort:c=this.ignoreFetchAbort,allowStaleOnFetchAbort:F=this.allowStaleOnFetchAbort,context:d,forceRefresh:S=!1,status:a,signal:w}=e;if(!this.#E)return a&&(a.fetch="get"),this.get(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:a});let m={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:h,noDisposeOnSet:o,size:r,sizeCalculation:g,noUpdateTTL:b,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:F,ignoreFetchAbort:c,status:a,signal:w},p=this.#s.get(t);if(p===void 0){a&&(a.fetch="miss");let _=this.#x(t,p,m,d);return _.__returned=_}else{let _=this.#t[p];if(this.#e(_)){let M=i&&_.__staleWhileFetching!==void 0;return a&&(a.fetch="inflight",M&&(a.returnedStale=!0)),M?_.__staleWhileFetching:_.__returned=_}let z=this.#d(p);if(!S&&!z)return a&&(a.fetch="hit"),this.#C(p),s&&this.#v(p),a&&this.#O(a,p),_;let y=this.#x(t,p,m,d),L=y.__staleWhileFetching!==void 0&&i;return a&&(a.fetch=z?"stale":"refresh",L&&z&&(a.returnedStale=!0)),L?y.__staleWhileFetching:y.__returned=y}}async forceFetch(t,e={}){let i=await this.fetch(t,e);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(t,e={}){let i=this.#W;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,forceRefresh:n,...h}=e,o=this.get(t,h);if(!n&&o!==void 0)return o;let r=i(t,o,{options:h,context:s});return this.set(t,r,h),r}get(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:h}=e,o=this.#s.get(t);if(o!==void 0){let r=this.#t[o],g=this.#e(r);return h&&this.#O(h,o),this.#d(o)?(h&&(h.get="stale"),g?(h&&i&&r.__staleWhileFetching!==void 0&&(h.returnedStale=!0),i?r.__staleWhileFetching:void 0):(n||this.#T(t,"expire"),h&&i&&(h.returnedStale=!0),i?r:void 0)):(h&&(h.get="hit"),g?r.__staleWhileFetching:(this.#C(o),s&&this.#v(o),r))}else h&&(h.get="miss")}#I(t,e){this.#c[e]=t,this.#l[t]=e}#C(t){t!==this.#h&&(t===this.#o?this.#o=this.#l[t]:this.#I(this.#c[t],this.#l[t]),this.#I(this.#h,t),this.#h=t)}delete(t){return this.#T(t,"delete")}#T(t,e){let i=!1;if(this.#n!==0){let s=this.#s.get(t);if(s!==void 0)if(i=!0,this.#n===1)this.#N(e);else{this.#z(s);let n=this.#t[s];if(this.#e(n)?n.__abortController.abort(new Error("deleted")):(this.#y||this.#a)&&(this.#y&&this.#p?.(n,t,e),this.#a&&this.#r?.push([n,t,e])),this.#s.delete(t),this.#i[s]=void 0,this.#t[s]=void 0,s===this.#h)this.#h=this.#c[s];else if(s===this.#o)this.#o=this.#l[s];else{let h=this.#c[s];this.#l[h]=this.#l[s];let o=this.#l[s];this.#c[o]=this.#c[s]}this.#n--,this.#_.push(s)}}if(this.#a&&this.#r?.length){let s=this.#r,n;for(;n=s?.shift();)this.#w?.(...n)}return i}clear(){return this.#N("delete")}#N(t){for(let e of this.#F({allowStale:!0})){let i=this.#t[e];if(this.#e(i))i.__abortController.abort(new Error("deleted"));else{let s=this.#i[e];this.#y&&this.#p?.(i,s,t),this.#a&&this.#r?.push([i,s,t])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#u&&this.#m&&(this.#u.fill(0),this.#m.fill(0)),this.#b&&this.#b.fill(0),this.#o=0,this.#h=0,this.#_.length=0,this.#S=0,this.#n=0,this.#a&&this.#r){let e=this.#r,i;for(;i=e?.shift();)this.#w?.(...i)}}};exports.LRUCache=C; +//# sourceMappingURL=index.min.js.map diff --git a/node_modules/lru-cache/dist/commonjs/index.min.js.map b/node_modules/lru-cache/dist/commonjs/index.min.js.map new file mode 100644 index 0000000..11b43a0 --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/index.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../src/index.ts"], + "sourcesContent": ["/**\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 * - `evict`: The item was evicted because it is the least recently used,\n * and the cache is full.\n * - `set`: A new value was set, overwriting the old value being disposed.\n * - `delete`: The item was explicitly deleted, either by calling\n * {@link LRUCache#delete}, {@link LRUCache#clear}, or\n * {@link LRUCache#set} with an undefined value.\n * - `expire`: The item was removed due to exceeding its TTL.\n * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned\n * `undefined` or was aborted, causing the item to be deleted.\n */\n export type DisposeReason =\n | 'evict'\n | 'set'\n | 'delete'\n | 'expire'\n | 'fetch'\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 * Occasionally, it may be useful to track the internal behavior of the\n * cache, particularly for logging, debugging, or for behavior within the\n * `fetchMethod`. To do this, you can pass a `status` object to the\n * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set},\n * {@link LRUCache#memo}, and {@link LRUCache#has} methods.\n *\n * The `status` option should be a plain JavaScript object. The following\n * fields will be set on it appropriately, depending on the situation.\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 {@link OptionsBase.fetchMethod}, so\n * {@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 export interface MemoOptions\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 /**\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.memoMethod} as\n * the {@link MemoizerOptions.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 status?: Status\n }\n /**\n * Options provided to {@link LRUCache#memo} when the FC type is something\n * other than `unknown`, `undefined`, or `void`\n */\n export interface MemoOptionsWithContext\n extends MemoOptions {\n context: FC\n }\n /**\n * Options provided to {@link LRUCache#memo} when the FC type is\n * `undefined` or `void`\n */\n export interface MemoOptionsNoContext\n extends MemoOptions {\n context?: undefined\n }\n\n /**\n * Options provided to the\n * {@link OptionsBase.memoMethod} function.\n */\n export interface MemoizerOptions {\n options: MemoizerMemoOptions\n /**\n * Object provided in the {@link MemoOptions.context} option to\n * {@link LRUCache#memo}\n */\n context: FC\n }\n\n /**\n * options which override the options set in the LRUCache constructor\n * when calling {@link LRUCache#memo}.\n *\n * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n * {@link MemoOptions.forceRefresh}, and\n * {@link MemoerOptions.context}\n *\n * Any of these may be modified in the {@link OptionsBase.memoMethod}\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 memoMethod is called.\n */\n export interface MemoizerMemoOptions\n extends Pick<\n OptionsBase,\n | 'allowStale'\n | 'updateAgeOnGet'\n | 'noDeleteOnStaleGet'\n | 'sizeCalculation'\n | 'ttl'\n | 'noDisposeOnSet'\n | 'noUpdateTTL'\n > {\n status?: Status\n size?: Size\n start?: Milliseconds\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 * the type signature for the {@link OptionsBase.memoMethod} option.\n */\n export type Memoizer = (\n key: K,\n staleValue: V | undefined,\n options: MemoizerOptions\n ) => V\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 * All options are also available on the {@link LRUCache} instance, making\n * it safe to pass an LRUCache instance as the options argumemnt to\n * make another empty cache of the same type.\n *\n * Some options are marked as read-only, because changing them after\n * instantiation is not safe. Changing any of the other options will of\n * course only have an effect on subsequent method calls.\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 * **It is strongly recommended to set a `max` to prevent unbounded growth\n * of the cache.**\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 by\n * default, and MAY live in the cache, contributing to its LRU max, long\n * after they have expired, unless {@link OptionsBase.ttlAutopurge} is\n * set.\n *\n * If set to `0` (the default value), then that means \"do not track\n * TTL\", not \"expire immediately\".\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 * This is not primarily a TTL cache, and does not make strong TTL\n * guarantees. There is no pre-emptive pruning of expired items, but you\n * _may_ set a TTL on the cache, and it will treat expired items as missing\n * when they are fetched, and delete them.\n *\n * Optional, but must be a non-negative integer in ms if specified.\n *\n * This may be overridden by passing an options object to `cache.set()`.\n *\n * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n * positive integer if set.\n *\n * Even if ttl tracking is enabled, **it is strongly recommended to set a\n * `max` to prevent unbounded growth of the cache.**\n *\n * If ttl tracking is enabled, and `max` and `maxSize` are not set,\n * and `ttlAutopurge` is not set, then a warning will be emitted\n * cautioning about the potential for unbounded memory consumption.\n * (The TypeScript definitions will also discourage this.)\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 *\n * Note that this may *significantly* degrade performance, especially if\n * the cache is storing a large number of items. It is almost always best\n * to just leave the stale items in the cache, and let them fall out as new\n * 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 * Use with caution!\n */\n ttlAutopurge?: boolean\n\n /**\n * When using time-expiring entries with `ttl`, setting this to `true` will\n * make each item's age reset to 0 whenever it is retrieved from cache with\n * {@link LRUCache#get}, causing it to not expire. (It can still fall out\n * of cache based on recency of use, of course.)\n *\n * Has no effect if {@link OptionsBase.ttl} is not set.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n */\n updateAgeOnGet?: boolean\n\n /**\n * When using time-expiring entries with `ttl`, setting this to `true` will\n * make each item's age reset to 0 whenever its presence in the cache is\n * checked with {@link LRUCache#has}, causing it to not expire. (It can\n * still fall out of cache based on recency of use, of course.)\n *\n * Has no effect if {@link OptionsBase.ttl} is not set.\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 * By default, if you set `ttl`, stale items will only be deleted from the\n * cache when you `get(key)`. That is, it's not preemptively pruning items,\n * unless {@link OptionsBase.ttlAutopurge} is set.\n *\n * If you set `allowStale:true`, it'll return the stale value *as well as*\n * deleting it. If you don't set this, then it'll return `undefined` when\n * you try to get a stale entry.\n *\n * Note that when a stale entry is fetched, _even if it is returned due to\n * `allowStale` being set_, it is removed from the cache immediately. You\n * can suppress this behavior by setting\n * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in\n * the options provided to {@link LRUCache#get}.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n * The `cache.has()` method will always return `false` for stale items.\n *\n * Only relevant if a ttl is set.\n */\n allowStale?: boolean\n\n /**\n * Function that is called on items when they are dropped from the\n * cache, as `dispose(value, key, reason)`.\n *\n * This can be handy if you want to close file descriptors or do\n * other cleanup tasks when items are no longer stored in the cache.\n *\n * **NOTE**: It is called _before_ the item has been fully removed\n * from the cache, so if you want to put it right back in, you need\n * to wait until the next tick. If you try to add it back in during\n * the `dispose()` function call, it will break things in subtle and\n * weird ways.\n *\n * Unlike several other options, this may _not_ be overridden by\n * passing an option to `set()`, for performance reasons.\n *\n * The `reason` will be one of the following strings, corresponding\n * to the reason for the item's deletion:\n *\n * - `evict` Item was evicted to make space for a new addition\n * - `set` Item was overwritten by a new value\n * - `expire` Item expired its TTL\n * - `fetch` Item was deleted due to a failed or aborted fetch, or a\n * fetchMethod returning `undefined.\n * - `delete` Item was removed by explicit `cache.delete(key)`,\n * `cache.clear()`, or `cache.set(key, undefined)`.\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 *\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 *\n * This may be overridden by passing an options object to\n * {@link LRUCache#set}.\n *\n * Only relevant if `dispose` or `disposeAfter` are set.\n */\n noDisposeOnSet?: boolean\n\n /**\n * Boolean flag to tell the cache to not update the TTL when setting a new\n * value for an existing key (ie, when updating a value rather than\n * inserting a new value). Note that the TTL value is _always_ set (if\n * provided) when adding a new entry into the cache.\n *\n * Has no effect if a {@link OptionsBase.ttl} is not set.\n *\n * May be passed as an option to {@link LRUCache#set}.\n */\n noUpdateTTL?: boolean\n\n /**\n * Set to a positive integer to track the sizes of items added to the\n * cache, and automatically evict items in order to stay below this size.\n * Note that this may result in fewer than `max` items being stored.\n *\n * Attempting to add an item to the cache whose calculated size is greater\n * that this amount will be a no-op. The item will not be cached, and no\n * other items will be evicted.\n *\n * Optional, must be a positive integer if provided.\n *\n * Sets `maxEntrySize` to the same value, unless a different value is\n * provided for `maxEntrySize`.\n *\n * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n * positive integer if set.\n *\n * Even if size tracking is enabled, **it is strongly recommended to set a\n * `max` to prevent unbounded growth of the cache.**\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} or {@link OptionsBase.memoMethod}, then\n * it will not be stored in the cache.\n *\n * Attempting to add an item whose calculated size is greater than\n * this amount will not cache the item or evict any old items, but\n * WILL delete an existing value if one is already present.\n *\n * Optional, must be a positive integer if provided. Defaults to\n * the value of `maxSize` if provided.\n */\n maxEntrySize?: Size\n\n /**\n * A function that returns a number indicating the item's size.\n *\n * Requires {@link OptionsBase.maxSize} to be set.\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 * ```ts\n * fetchMethod(key, staleValue, { signal, options, context })\n * ```\n *\n * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent\n * to `Promise.resolve(cache.get(key))`.\n *\n * If at any time, `signal.aborted` is set to `true`, or if the\n * `signal.onabort` method is called, or if it emits an `'abort'` event\n * which you can listen to with `addEventListener`, then that means that\n * the fetch should be abandoned. This may be passed along to async\n * functions aware of AbortController/AbortSignal behavior.\n *\n * The `fetchMethod` should **only** return `undefined` or a Promise\n * resolving to `undefined` if the AbortController signaled an `abort`\n * event. In all other cases, it should return or resolve to a value\n * suitable for adding to the cache.\n *\n * The `options` object is a union of the options that may be provided to\n * `set()` and `get()`. If they are modified, then that will result in\n * modifying the settings to `cache.set()` when the value is resolved, and\n * in the case of\n * {@link OptionsBase.noDeleteOnFetchRejection} and\n * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of\n * `fetchMethod` failures.\n *\n * For example, a DNS cache may update the TTL based on the value returned\n * from a remote DNS server by changing `options.ttl` in the `fetchMethod`.\n */\n fetchMethod?: Fetcher\n\n /**\n * Method that provides the implementation for {@link LRUCache#memo}\n */\n memoMethod?: Memoizer\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 * When using time-expiring entries with `ttl`, by default stale\n * items will be removed from the cache when the key is accessed\n * with `cache.get()`.\n *\n * Setting this option will cause stale items to remain in the cache, until\n * they are explicitly deleted with `cache.delete(key)`, or retrieved with\n * `noDeleteOnStaleGet` set to `false`.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n *\n * Only relevant if a ttl is used.\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 {@link LRUCache#fetch}\n * fails, not any other times.\n *\n * If a `fetchMethod` fails, and there is no stale value available, the\n * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are\n * suppressed.\n *\n * Implies `noDeleteOnFetchRejection`.\n *\n * This may be set in calls to `fetch()`, or defaulted on the constructor,\n * or overridden by modifying the options object in the `fetchMethod`.\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\n * an `'abort'` event, whether user-triggered, or due to internal cache\n * 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\n * are not immediately resolved or rejected when they are aborted, and\n * instead 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 * For example:\n *\n * ```ts\n * const c = new LRUCache({\n * ttl: 100,\n * ignoreFetchAbort: true,\n * allowStaleOnFetchAbort: true,\n * fetchMethod: async (key, oldValue, { signal }) => {\n * // note: do NOT pass the signal to fetch()!\n * // let's say this fetch can take a long time.\n * const res = await fetch(`https://slow-backend-server/${key}`)\n * return await res.json()\n * },\n * })\n *\n * // this will return the stale value after 100ms, while still\n * // updating in the background for next time.\n * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) })\n * ```\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 * The `K` and `V` types define the key and value types, respectively. The\n * optional `FC` type defines the type of the `context` object passed to\n * `cache.fetch()` and `cache.memo()`.\n *\n * Keys and values **must not** be `null` or `undefined`.\n *\n * All properties from the options object (with the exception of `max`,\n * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are\n * added as normal public members. (The listed options are read-only getters.)\n *\n * Changing any of these will alter the defaults for subsequent method calls.\n */\nexport class LRUCache\n implements Map\n{\n // options that cannot be changed without disaster\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 readonly #memoMethod?: LRUCache.Memoizer\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 get memoMethod(): LRUCache.Memoizer | undefined {\n return this.#memoMethod\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 memoMethod,\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 memoMethod !== undefined &&\n typeof memoMethod !== 'function'\n ) {\n throw new TypeError('memoMethod must be a function if defined')\n }\n this.#memoMethod = memoMethod\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 number of ms left in the item's TTL. If item is not in cache,\n * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.\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, 'expire')\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\n * description of an object. Called by the built-in method\n * `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 most\n * recently used to least recently used.\n *\n * `fn` is called as `fn(value, key, cache)`.\n *\n * If `thisp` is provided, function will be called in the `this`-context of\n * the provided object, or the cache if no `thisp` object is provided.\n *\n * Does not update age or recenty of use, or 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, 'expire')\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. Returns `undefined` if the key is not present.\n *\n * Unlike {@link LRUCache#dump}, which is designed to be portable and survive\n * serialization, the `start` value is always the current timestamp, and the\n * `ttl` is a calculated remaining time to live (negative if expired).\n *\n * Always returns stale values, if their info is found in the cache, so be\n * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})\n * 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 {@link LRLUCache#load}.\n *\n * The `start` fields are calculated relative to a portable `Date.now()`\n * timestamp, even if `performance.now()` is available.\n *\n * Stale entries are always included in the `dump`, even if\n * {@link LRUCache.OptionsBase.allowStale} is false.\n *\n * Note: this returns an actual array, not a generator, so it can be more\n * easily passed around.\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 *\n * The shape of the resulting cache may be different if the same options are\n * not used in both caches.\n *\n * The `start` fields are assumed to be calculated relative to a portable\n * `Date.now()` timestamp, even if `performance.now()` is available.\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 * Fields on the {@link LRUCache.SetOptions} options param will override\n * their corresponding values in the constructor options for the scope\n * of this single `set()` operation.\n *\n * If `start` is provided, then that will set the effective start\n * time for the TTL calculation. Note that this must be a previous\n * value of `performance.now()` if supported, or a previous value of\n * `Date.now()` if not.\n *\n * Options object may also include `size`, which will prevent\n * calling the `sizeCalculation` function and just use the specified\n * number if it is a positive integer, and `noDisposeOnSet` which\n * will prevent calling a `dispose` function in the case of\n * overwrites.\n *\n * If the `size` (or return value of `sizeCalculation`) for a given\n * entry is greater than `maxEntrySize`, then the item will not be\n * added to the cache.\n *\n * Will update the recency of the entry.\n *\n * If the value is `undefined`, then this is an alias for\n * `cache.delete(key)`. `undefined` is never stored in the cache.\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, 'set')\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 * Check if a key is in the cache, without updating the recency of\n * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set\n * to `true` in either the options or the constructor.\n *\n * Will return `false` if the item is stale, even though it is technically in\n * the cache. The difference can be determined (if it matters) by using a\n * `status` argument, and inspecting the `has` field.\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, 'fetch')\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, 'fetch')\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 the value is in the cache and not stale, then the returned\n * Promise resolves to the value.\n *\n * If not in the cache, or beyond its TTL staleness, then\n * `fetchMethod(key, staleValue, { options, signal, context })` is\n * called, and the value returned will be added to the cache once\n * resolved.\n *\n * If called with `allowStale`, and an asynchronous fetch is\n * currently in progress to reload a stale value, then the former\n * stale value will be returned.\n *\n * If called with `forceRefresh`, then the cached item will be\n * re-fetched, even if it is not stale. However, if `allowStale` is also\n * set, then the old value will still be returned. This is useful\n * in cases where you want to force a reload of a cached value. If\n * a background fetch is already in progress, then `forceRefresh`\n * has no effect.\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 * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is\n * effectively an alias for `Promise.resolve(cache.get(key))`.\n *\n * When the fetch method resolves to a value, if the fetch has not\n * been aborted due to deletion, eviction, or being overwritten,\n * then it is added to the cache using the options provided.\n *\n * If the key is evicted or deleted before the `fetchMethod`\n * resolves, then the AbortSignal passed to the `fetchMethod` will\n * receive an `abort` event, and the promise returned by `fetch()`\n * will reject with the reason for the abort.\n *\n * If a `signal` is passed to the `fetch()` call, then aborting the\n * signal will abort the fetch and cause the `fetch()` promise to\n * reject with the reason provided.\n *\n * **Setting `context`**\n *\n * If an `FC` type is set to a type other than `unknown`, `void`, or\n * `undefined` in the {@link LRUCache} constructor, then all\n * calls to `cache.fetch()` _must_ provide a `context` option. If\n * set to `undefined` or `void`, then calls to fetch _must not_\n * provide a `context` option.\n *\n * The `context` param allows you to provide arbitrary data that\n * might be relevant in the course of fetching the data. It is only\n * relevant for the course of a single `fetch()` operation, and\n * discarded afterwards.\n *\n * **Note: `fetch()` calls are inflight-unique**\n *\n * If you call `fetch()` multiple times with the same key value,\n * then every call after the first will resolve on the same\n * promise1,\n * _even if they have different settings that would otherwise change\n * the behavior of the fetch_, such as `noDeleteOnFetchRejection`\n * or `ignoreFetchAbort`.\n *\n * In most cases, this is not a problem (in fact, only fetching\n * something once is what you probably want, if you're caching in\n * the first place). If you are changing the fetch() options\n * dramatically between runs, there's a good chance that you might\n * be trying to fit divergent semantics into a single object, and\n * would be better off with multiple cache instances.\n *\n * **1**: Ie, they're not the \"same Promise\", but they resolve at\n * the same time, because they're both waiting on the same\n * underlying fetchMethod response.\n */\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\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\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 * In some cases, `cache.fetch()` may resolve to `undefined`, either because\n * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning\n * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or\n * because `ignoreFetchAbort` was specified (either to the constructor or\n * in the {@link LRUCache.FetchOptions}). Also, the\n * {@link OptionsBase.fetchMethod} may return `undefined` or `void`, making\n * the test even more complicated.\n *\n * Because inferring the cases where `undefined` might be returned are so\n * cumbersome, but testing for `undefined` can also be annoying, this method\n * can be used, which will reject if `this.fetch()` resolves to undefined.\n */\n forceFetch(\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 forceFetch(\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 forceFetch(\n k: K,\n fetchOptions: LRUCache.FetchOptions = {}\n ): Promise {\n const v = await this.fetch(\n k,\n fetchOptions as unknown extends FC\n ? LRUCache.FetchOptions\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext\n : LRUCache.FetchOptionsWithContext\n )\n if (v === undefined) throw new Error('fetch() returned undefined')\n return v\n }\n\n /**\n * If the key is found in the cache, then this is equivalent to\n * {@link LRUCache#get}. If not, in the cache, then calculate the value using\n * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache.\n *\n * If an `FC` type is set to a type other than `unknown`, `void`, or\n * `undefined` in the LRUCache constructor, then all calls to `cache.memo()`\n * _must_ provide a `context` option. If set to `undefined` or `void`, then\n * calls to memo _must not_ provide a `context` option.\n *\n * The `context` param allows you to provide arbitrary data that might be\n * relevant in the course of fetching the data. It is only relevant for the\n * course of a single `memo()` operation, and discarded afterwards.\n */\n memo(\n k: K,\n memoOptions: unknown extends FC\n ? LRUCache.MemoOptions\n : FC extends undefined | void\n ? LRUCache.MemoOptionsNoContext\n : LRUCache.MemoOptionsWithContext\n ): V\n // this overload not allowed if context is required\n memo(\n k: unknown extends FC\n ? K\n : FC extends undefined | void\n ? K\n : never,\n memoOptions?: unknown extends FC\n ? LRUCache.MemoOptions\n : FC extends undefined | void\n ? LRUCache.MemoOptionsNoContext\n : never\n ): V\n memo(k: K, memoOptions: LRUCache.MemoOptions = {}) {\n const memoMethod = this.#memoMethod\n if (!memoMethod) {\n throw new Error('no memoMethod provided to constructor')\n }\n const { context, forceRefresh, ...options } = memoOptions\n const v = this.get(k, options)\n if (!forceRefresh && v !== undefined) return v\n const vv = memoMethod(k, v, {\n options,\n context,\n } as LRUCache.MemoizerOptions)\n this.set(k, vv, options)\n return vv\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, 'expire')\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 *\n * Returns true if the key was deleted, false otherwise.\n */\n delete(k: K) {\n return this.#delete(k, 'delete')\n }\n\n #delete(k: K, reason: LRUCache.DisposeReason) {\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(reason)\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, reason)\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v as V, k, reason])\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 return this.#clear('delete')\n }\n #clear(reason: LRUCache.DisposeReason) {\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, reason)\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v as V, k as K, reason])\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"], + "mappings": "+aAMA,IAAMA,EACJ,OAAO,aAAgB,UACvB,aACA,OAAO,YAAY,KAAQ,WACvB,YACA,KAEAC,EAAS,IAAI,IAMbC,EACJ,OAAO,SAAY,UAAc,QAAU,QAAU,CAAA,EAIjDC,EAAc,CAClBC,EACAC,EACAC,EACAC,IACE,CACF,OAAOL,EAAQ,aAAgB,WAC3BA,EAAQ,YAAYE,EAAKC,EAAMC,EAAMC,CAAE,EACvC,QAAQ,MAAM,IAAID,MAASD,MAASD,GAAK,CAC/C,EAEII,EAAK,WAAW,gBAChBC,EAAK,WAAW,YAGpB,GAAI,OAAOD,EAAO,IAAa,CAE7BC,EAAK,KAAiB,CACpB,QACA,SAAqC,CAAA,EACrC,OACA,QAAmB,GACnB,iBAAiBC,EAAWH,EAAwB,CAClD,KAAK,SAAS,KAAKA,CAAE,CACvB,GAGFC,EAAK,KAAqB,CACxB,aAAA,CACEG,EAAc,CAChB,CACA,OAAS,IAAIF,EACb,MAAMG,EAAW,CACf,GAAI,MAAK,OAAO,QAEhB,MAAK,OAAO,OAASA,EAErB,KAAK,OAAO,QAAU,GAEtB,QAAWL,KAAM,KAAK,OAAO,SAC3BA,EAAGK,CAAM,EAEX,KAAK,OAAO,UAAUA,CAAM,EAC9B,GAEF,IAAIC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AC,GAEjB,KAAKD,IACP,KAAKA,GAAO,KAAK,CAAC,EAEpB,KAAKJ,GAAQ,EACb,KAAKC,GAAQ,EACb,KAAKC,GAAM,OAAS,EACpB,KAAKR,GAAkB,EACvB,KAAKD,GAAQ,EACT,KAAKgB,IAAoB,KAAKN,GAAW,CAC3C,IAAM8E,EAAK,KAAK9E,GACZ+E,EACJ,KAAQA,EAAOD,GAAI,MAAK,GACtB,KAAK3F,KAAgB,GAAG4F,CAAI,EAGlC,GAvwDF,QAAA,SAAAhG", + "names": ["perf", "warned", "PROCESS", "emitWarning", "msg", "type", "code", "fn", "AC", "AS", "_", "warnACPolyfill", "reason", "printACPolyfillWarning", "shouldWarn", "TYPE", "isPosInt", "n", "getUintArray", "max", "ZeroArray", "size", "_Stack", "HeapCls", "__privateSet", "_constructing", "s", "__privateGet", "Stack", "__privateAdd", "LRUCache", "#max", "#maxSize", "#dispose", "#disposeAfter", "#fetchMethod", "#memoMethod", "#size", "#calculatedSize", "#keyMap", "#keyList", "#valList", "#next", "#prev", "#head", "#tail", "#free", "#disposed", "#sizes", "#starts", "#ttls", "#hasDispose", "#hasFetchMethod", "#hasDisposeAfter", "c", "p", "#isBackgroundFetch", "k", "index", "options", "context", "#backgroundFetch", "#moveToTail", "#indexes", "#rindexes", "#isStale", "ttl", "ttlResolution", "ttlAutopurge", "updateAgeOnGet", "updateAgeOnHas", "allowStale", "dispose", "disposeAfter", "noDisposeOnSet", "noUpdateTTL", "maxSize", "maxEntrySize", "sizeCalculation", "fetchMethod", "memoMethod", "noDeleteOnFetchRejection", "noDeleteOnStaleGet", "allowStaleOnFetchRejection", "allowStaleOnFetchAbort", "ignoreFetchAbort", "UintArray", "#initializeSizeTracking", "#initializeTTLTracking", "key", "ttls", "starts", "#setItemTTL", "start", "t", "#delete", "#updateItemAge", "#statusTTL", "status", "cachedNow", "getNow", "age", "sizes", "#removeItemSize", "#requireSize", "v", "#addItemSize", "#evict", "_i", "_s", "_st", "_k", "_v", "i", "#isValidIndex", "getOptions", "value", "thisp", "deleted", "entry", "remain", "arr", "setOptions", "oldVal", "oldValue", "dt", "task", "val", "free", "head", "hasOptions", "peekOptions", "ac", "signal", "fetchOpts", "cb", "updateCache", "aborted", "ignoreAbort", "fetchFail", "bf", "eb", "er", "allowStaleAborted", "noDelete", "pcall", "res", "rej", "fmp", "b", "fetchOptions", "forceRefresh", "stale", "isStale", "staleVal", "memoOptions", "vv", "fetching", "#connect", "#clear", "pi", "ni"] +} diff --git a/node_modules/lru-cache/dist/commonjs/package.json b/node_modules/lru-cache/dist/commonjs/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/node_modules/lru-cache/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/lru-cache/dist/esm/index.d.ts b/node_modules/lru-cache/dist/esm/index.d.ts new file mode 100644 index 0000000..f59de76 --- /dev/null +++ b/node_modules/lru-cache/dist/esm/index.d.ts @@ -0,0 +1,1277 @@ +/** + * @module LRUCache + */ +declare const TYPE: unique symbol; +export type PosInt = number & { + [TYPE]: 'Positive Integer'; +}; +export type Index = number & { + [TYPE]: 'LRUCache Index'; +}; +export type UintArray = Uint8Array | Uint16Array | Uint32Array; +export type NumberArray = UintArray | number[]; +declare class ZeroArray extends Array { + constructor(size: number); +} +export type { ZeroArray }; +export type { Stack }; +export type StackLike = Stack | Index[]; +declare class Stack { + #private; + heap: NumberArray; + length: number; + static create(max: number): StackLike; + constructor(max: number, HeapCls: { + new (n: number): NumberArray; + }); + push(n: Index): void; + pop(): Index; +} +/** + * Promise representing an in-progress {@link LRUCache#fetch} call + */ +export type BackgroundFetch = Promise & { + __returned: BackgroundFetch | undefined; + __abortController: AbortController; + __staleWhileFetching: V | undefined; +}; +export type DisposeTask = [ + value: V, + key: K, + reason: LRUCache.DisposeReason +]; +export declare namespace LRUCache { + /** + * An integer greater than 0, reflecting the calculated size of items + */ + type Size = number; + /** + * Integer greater than 0, representing some number of milliseconds, or the + * time at which a TTL started counting from. + */ + type Milliseconds = number; + /** + * An integer greater than 0, reflecting a number of items + */ + type Count = number; + /** + * The reason why an item was removed from the cache, passed + * to the {@link Disposer} methods. + * + * - `evict`: The item was evicted because it is the least recently used, + * and the cache is full. + * - `set`: A new value was set, overwriting the old value being disposed. + * - `delete`: The item was explicitly deleted, either by calling + * {@link LRUCache#delete}, {@link LRUCache#clear}, or + * {@link LRUCache#set} with an undefined value. + * - `expire`: The item was removed due to exceeding its TTL. + * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned + * `undefined` or was aborted, causing the item to be deleted. + */ + type DisposeReason = 'evict' | 'set' | 'delete' | 'expire' | 'fetch'; + /** + * A method called upon item removal, passed as the + * {@link OptionsBase.dispose} and/or + * {@link OptionsBase.disposeAfter} options. + */ + type Disposer = (value: V, key: K, reason: DisposeReason) => void; + /** + * A function that returns the effective calculated size + * of an entry in the cache. + */ + type SizeCalculator = (value: V, key: K) => Size; + /** + * Options provided to the + * {@link OptionsBase.fetchMethod} function. + */ + interface FetcherOptions { + signal: AbortSignal; + options: FetcherFetchOptions; + /** + * Object provided in the {@link FetchOptions.context} option to + * {@link LRUCache#fetch} + */ + context: FC; + } + /** + * Occasionally, it may be useful to track the internal behavior of the + * cache, particularly for logging, debugging, or for behavior within the + * `fetchMethod`. To do this, you can pass a `status` object to the + * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set}, + * {@link LRUCache#memo}, and {@link LRUCache#has} methods. + * + * The `status` option should be a plain JavaScript object. The following + * fields will be set on it appropriately, depending on the situation. + */ + interface Status { + /** + * The status of a set() operation. + * + * - add: the item was not found in the cache, and was added + * - update: the item was in the cache, with the same value provided + * - replace: the item was in the cache, and replaced + * - miss: the item was not added to the cache for some reason + */ + set?: 'add' | 'update' | 'replace' | 'miss'; + /** + * the ttl stored for the item, or undefined if ttls are not used. + */ + ttl?: Milliseconds; + /** + * the start time for the item, or undefined if ttls are not used. + */ + start?: Milliseconds; + /** + * The timestamp used for TTL calculation + */ + now?: Milliseconds; + /** + * the remaining ttl for the item, or undefined if ttls are not used. + */ + remainingTTL?: Milliseconds; + /** + * The calculated size for the item, if sizes are used. + */ + entrySize?: Size; + /** + * The total calculated size of the cache, if sizes are used. + */ + totalCalculatedSize?: Size; + /** + * A flag indicating that the item was not stored, due to exceeding the + * {@link OptionsBase.maxEntrySize} + */ + maxEntrySizeExceeded?: true; + /** + * The old value, specified in the case of `set:'update'` or + * `set:'replace'` + */ + oldValue?: V; + /** + * The results of a {@link LRUCache#has} operation + * + * - hit: the item was found in the cache + * - stale: the item was found in the cache, but is stale + * - miss: the item was not found in the cache + */ + has?: 'hit' | 'stale' | 'miss'; + /** + * The status of a {@link LRUCache#fetch} operation. + * Note that this can change as the underlying fetch() moves through + * various states. + * + * - inflight: there is another fetch() for this key which is in process + * - get: there is no {@link OptionsBase.fetchMethod}, so + * {@link LRUCache#get} was called. + * - miss: the item is not in cache, and will be fetched. + * - hit: the item is in the cache, and was resolved immediately. + * - stale: the item is in the cache, but stale. + * - refresh: the item is in the cache, and not stale, but + * {@link FetchOptions.forceRefresh} was specified. + */ + fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'; + /** + * The {@link OptionsBase.fetchMethod} was called + */ + fetchDispatched?: true; + /** + * The cached value was updated after a successful call to + * {@link OptionsBase.fetchMethod} + */ + fetchUpdated?: true; + /** + * The reason for a fetch() rejection. Either the error raised by the + * {@link OptionsBase.fetchMethod}, or the reason for an + * AbortSignal. + */ + fetchError?: Error; + /** + * The fetch received an abort signal + */ + fetchAborted?: true; + /** + * The abort signal received was ignored, and the fetch was allowed to + * continue. + */ + fetchAbortIgnored?: true; + /** + * The fetchMethod promise resolved successfully + */ + fetchResolved?: true; + /** + * The fetchMethod promise was rejected + */ + fetchRejected?: true; + /** + * The status of a {@link LRUCache#get} operation. + * + * - fetching: The item is currently being fetched. If a previous value + * is present and allowed, that will be returned. + * - stale: The item is in the cache, and is stale. + * - hit: the item is in the cache + * - miss: the item is not in the cache + */ + get?: 'stale' | 'hit' | 'miss'; + /** + * A fetch or get operation returned a stale value. + */ + returnedStale?: true; + } + /** + * options which override the options set in the LRUCache constructor + * when calling {@link LRUCache#fetch}. + * + * This is the union of {@link GetOptions} and {@link SetOptions}, plus + * {@link OptionsBase.noDeleteOnFetchRejection}, + * {@link OptionsBase.allowStaleOnFetchRejection}, + * {@link FetchOptions.forceRefresh}, and + * {@link FetcherOptions.context} + * + * Any of these may be modified in the {@link OptionsBase.fetchMethod} + * function, but the {@link GetOptions} fields will of course have no + * effect, as the {@link LRUCache#get} call already happened by the time + * the fetchMethod is called. + */ + interface FetcherFetchOptions extends Pick, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet' | 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL' | 'noDeleteOnFetchRejection' | 'allowStaleOnFetchRejection' | 'ignoreFetchAbort' | 'allowStaleOnFetchAbort'> { + status?: Status; + size?: Size; + } + /** + * Options that may be passed to the {@link LRUCache#fetch} method. + */ + interface FetchOptions extends FetcherFetchOptions { + /** + * Set to true to force a re-load of the existing data, even if it + * is not yet stale. + */ + forceRefresh?: boolean; + /** + * Context provided to the {@link OptionsBase.fetchMethod} as + * the {@link FetcherOptions.context} param. + * + * If the FC type is specified as unknown (the default), + * undefined or void, then this is optional. Otherwise, it will + * be required. + */ + context?: FC; + signal?: AbortSignal; + status?: Status; + } + /** + * Options provided to {@link LRUCache#fetch} when the FC type is something + * other than `unknown`, `undefined`, or `void` + */ + interface FetchOptionsWithContext extends FetchOptions { + context: FC; + } + /** + * Options provided to {@link LRUCache#fetch} when the FC type is + * `undefined` or `void` + */ + interface FetchOptionsNoContext extends FetchOptions { + context?: undefined; + } + interface MemoOptions extends Pick, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet' | 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL' | 'noDeleteOnFetchRejection' | 'allowStaleOnFetchRejection' | 'ignoreFetchAbort' | 'allowStaleOnFetchAbort'> { + /** + * Set to true to force a re-load of the existing data, even if it + * is not yet stale. + */ + forceRefresh?: boolean; + /** + * Context provided to the {@link OptionsBase.memoMethod} as + * the {@link MemoizerOptions.context} param. + * + * If the FC type is specified as unknown (the default), + * undefined or void, then this is optional. Otherwise, it will + * be required. + */ + context?: FC; + status?: Status; + } + /** + * Options provided to {@link LRUCache#memo} when the FC type is something + * other than `unknown`, `undefined`, or `void` + */ + interface MemoOptionsWithContext extends MemoOptions { + context: FC; + } + /** + * Options provided to {@link LRUCache#memo} when the FC type is + * `undefined` or `void` + */ + interface MemoOptionsNoContext extends MemoOptions { + context?: undefined; + } + /** + * Options provided to the + * {@link OptionsBase.memoMethod} function. + */ + interface MemoizerOptions { + options: MemoizerMemoOptions; + /** + * Object provided in the {@link MemoOptions.context} option to + * {@link LRUCache#memo} + */ + context: FC; + } + /** + * options which override the options set in the LRUCache constructor + * when calling {@link LRUCache#memo}. + * + * This is the union of {@link GetOptions} and {@link SetOptions}, plus + * {@link MemoOptions.forceRefresh}, and + * {@link MemoerOptions.context} + * + * Any of these may be modified in the {@link OptionsBase.memoMethod} + * function, but the {@link GetOptions} fields will of course have no + * effect, as the {@link LRUCache#get} call already happened by the time + * the memoMethod is called. + */ + interface MemoizerMemoOptions extends Pick, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet' | 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'> { + status?: Status; + size?: Size; + start?: Milliseconds; + } + /** + * Options that may be passed to the {@link LRUCache#has} method. + */ + interface HasOptions extends Pick, 'updateAgeOnHas'> { + status?: Status; + } + /** + * Options that may be passed to the {@link LRUCache#get} method. + */ + interface GetOptions extends Pick, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'> { + status?: Status; + } + /** + * Options that may be passed to the {@link LRUCache#peek} method. + */ + interface PeekOptions extends Pick, 'allowStale'> { + } + /** + * Options that may be passed to the {@link LRUCache#set} method. + */ + interface SetOptions extends Pick, 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'> { + /** + * If size tracking is enabled, then setting an explicit size + * in the {@link LRUCache#set} call will prevent calling the + * {@link OptionsBase.sizeCalculation} function. + */ + size?: Size; + /** + * If TTL tracking is enabled, then setting an explicit start + * time in the {@link LRUCache#set} call will override the + * default time from `performance.now()` or `Date.now()`. + * + * Note that it must be a valid value for whichever time-tracking + * method is in use. + */ + start?: Milliseconds; + status?: Status; + } + /** + * The type signature for the {@link OptionsBase.fetchMethod} option. + */ + type Fetcher = (key: K, staleValue: V | undefined, options: FetcherOptions) => Promise | V | undefined | void; + /** + * the type signature for the {@link OptionsBase.memoMethod} option. + */ + type Memoizer = (key: K, staleValue: V | undefined, options: MemoizerOptions) => V; + /** + * Options which may be passed to the {@link LRUCache} constructor. + * + * Most of these may be overridden in the various options that use + * them. + * + * Despite all being technically optional, the constructor requires that + * a cache is at minimum limited by one or more of {@link OptionsBase.max}, + * {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}. + * + * If {@link OptionsBase.ttl} is used alone, then it is strongly advised + * (and in fact required by the type definitions here) that the cache + * also set {@link OptionsBase.ttlAutopurge}, to prevent potentially + * unbounded storage. + * + * All options are also available on the {@link LRUCache} instance, making + * it safe to pass an LRUCache instance as the options argumemnt to + * make another empty cache of the same type. + * + * Some options are marked as read-only, because changing them after + * instantiation is not safe. Changing any of the other options will of + * course only have an effect on subsequent method calls. + */ + interface OptionsBase { + /** + * The maximum number of items to store in the cache before evicting + * old entries. This is read-only on the {@link LRUCache} instance, + * and may not be overridden. + * + * If set, then storage space will be pre-allocated at construction + * time, and the cache will perform significantly faster. + * + * Note that significantly fewer items may be stored, if + * {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also + * set. + * + * **It is strongly recommended to set a `max` to prevent unbounded growth + * of the cache.** + */ + max?: Count; + /** + * Max time in milliseconds for items to live in cache before they are + * considered stale. Note that stale items are NOT preemptively removed by + * default, and MAY live in the cache, contributing to its LRU max, long + * after they have expired, unless {@link OptionsBase.ttlAutopurge} is + * set. + * + * If set to `0` (the default value), then that means "do not track + * TTL", not "expire immediately". + * + * Also, as this cache is optimized for LRU/MRU operations, some of + * the staleness/TTL checks will reduce performance, as they will incur + * overhead by deleting items. + * + * This is not primarily a TTL cache, and does not make strong TTL + * guarantees. There is no pre-emptive pruning of expired items, but you + * _may_ set a TTL on the cache, and it will treat expired items as missing + * when they are fetched, and delete them. + * + * Optional, but must be a non-negative integer in ms if specified. + * + * This may be overridden by passing an options object to `cache.set()`. + * + * At least one of `max`, `maxSize`, or `TTL` is required. This must be a + * positive integer if set. + * + * Even if ttl tracking is enabled, **it is strongly recommended to set a + * `max` to prevent unbounded growth of the cache.** + * + * If ttl tracking is enabled, and `max` and `maxSize` are not set, + * and `ttlAutopurge` is not set, then a warning will be emitted + * cautioning about the potential for unbounded memory consumption. + * (The TypeScript definitions will also discourage this.) + */ + ttl?: Milliseconds; + /** + * Minimum amount of time in ms in which to check for staleness. + * Defaults to 1, which means that the current time is checked + * at most once per millisecond. + * + * Set to 0 to check the current time every time staleness is tested. + * (This reduces performance, and is theoretically unnecessary.) + * + * Setting this to a higher value will improve performance somewhat + * while using ttl tracking, albeit at the expense of keeping stale + * items around a bit longer than their TTLs would indicate. + * + * @default 1 + */ + ttlResolution?: Milliseconds; + /** + * Preemptively remove stale items from the cache. + * + * Note that this may *significantly* degrade performance, especially if + * the cache is storing a large number of items. It is almost always best + * to just leave the stale items in the cache, and let them fall out as new + * items are added. + * + * Note that this means that {@link OptionsBase.allowStale} is a bit + * pointless, as stale items will be deleted almost as soon as they + * expire. + * + * Use with caution! + */ + ttlAutopurge?: boolean; + /** + * When using time-expiring entries with `ttl`, setting this to `true` will + * make each item's age reset to 0 whenever it is retrieved from cache with + * {@link LRUCache#get}, causing it to not expire. (It can still fall out + * of cache based on recency of use, of course.) + * + * Has no effect if {@link OptionsBase.ttl} is not set. + * + * This may be overridden by passing an options object to `cache.get()`. + */ + updateAgeOnGet?: boolean; + /** + * When using time-expiring entries with `ttl`, setting this to `true` will + * make each item's age reset to 0 whenever its presence in the cache is + * checked with {@link LRUCache#has}, causing it to not expire. (It can + * still fall out of cache based on recency of use, of course.) + * + * Has no effect if {@link OptionsBase.ttl} is not set. + */ + updateAgeOnHas?: boolean; + /** + * Allow {@link LRUCache#get} and {@link LRUCache#fetch} calls to return + * stale data, if available. + * + * By default, if you set `ttl`, stale items will only be deleted from the + * cache when you `get(key)`. That is, it's not preemptively pruning items, + * unless {@link OptionsBase.ttlAutopurge} is set. + * + * If you set `allowStale:true`, it'll return the stale value *as well as* + * deleting it. If you don't set this, then it'll return `undefined` when + * you try to get a stale entry. + * + * Note that when a stale entry is fetched, _even if it is returned due to + * `allowStale` being set_, it is removed from the cache immediately. You + * can suppress this behavior by setting + * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in + * the options provided to {@link LRUCache#get}. + * + * This may be overridden by passing an options object to `cache.get()`. + * The `cache.has()` method will always return `false` for stale items. + * + * Only relevant if a ttl is set. + */ + allowStale?: boolean; + /** + * Function that is called on items when they are dropped from the + * cache, as `dispose(value, key, reason)`. + * + * This can be handy if you want to close file descriptors or do + * other cleanup tasks when items are no longer stored in the cache. + * + * **NOTE**: It is called _before_ the item has been fully removed + * from the cache, so if you want to put it right back in, you need + * to wait until the next tick. If you try to add it back in during + * the `dispose()` function call, it will break things in subtle and + * weird ways. + * + * Unlike several other options, this may _not_ be overridden by + * passing an option to `set()`, for performance reasons. + * + * The `reason` will be one of the following strings, corresponding + * to the reason for the item's deletion: + * + * - `evict` Item was evicted to make space for a new addition + * - `set` Item was overwritten by a new value + * - `expire` Item expired its TTL + * - `fetch` Item was deleted due to a failed or aborted fetch, or a + * fetchMethod returning `undefined. + * - `delete` Item was removed by explicit `cache.delete(key)`, + * `cache.clear()`, or `cache.set(key, undefined)`. + */ + dispose?: Disposer; + /** + * The same as {@link OptionsBase.dispose}, but called *after* the entry + * is completely removed and the cache is once again in a clean state. + * + * It is safe to add an item right back into the cache at this point. + * However, note that it is *very* easy to inadvertently create infinite + * recursion this way. + */ + disposeAfter?: Disposer; + /** + * Set to true to suppress calling the + * {@link OptionsBase.dispose} function if the entry key is + * still accessible within the cache. + * + * This may be overridden by passing an options object to + * {@link LRUCache#set}. + * + * Only relevant if `dispose` or `disposeAfter` are set. + */ + noDisposeOnSet?: boolean; + /** + * Boolean flag to tell the cache to not update the TTL when setting a new + * value for an existing key (ie, when updating a value rather than + * inserting a new value). Note that the TTL value is _always_ set (if + * provided) when adding a new entry into the cache. + * + * Has no effect if a {@link OptionsBase.ttl} is not set. + * + * May be passed as an option to {@link LRUCache#set}. + */ + noUpdateTTL?: boolean; + /** + * Set to a positive integer to track the sizes of items added to the + * cache, and automatically evict items in order to stay below this size. + * Note that this may result in fewer than `max` items being stored. + * + * Attempting to add an item to the cache whose calculated size is greater + * that this amount will be a no-op. The item will not be cached, and no + * other items will be evicted. + * + * Optional, must be a positive integer if provided. + * + * Sets `maxEntrySize` to the same value, unless a different value is + * provided for `maxEntrySize`. + * + * At least one of `max`, `maxSize`, or `TTL` is required. This must be a + * positive integer if set. + * + * Even if size tracking is enabled, **it is strongly recommended to set a + * `max` to prevent unbounded growth of the cache.** + * + * Note also that size tracking can negatively impact performance, + * though for most cases, only minimally. + */ + maxSize?: Size; + /** + * The maximum allowed size for any single item in the cache. + * + * If a larger item is passed to {@link LRUCache#set} or returned by a + * {@link OptionsBase.fetchMethod} or {@link OptionsBase.memoMethod}, then + * it will not be stored in the cache. + * + * Attempting to add an item whose calculated size is greater than + * this amount will not cache the item or evict any old items, but + * WILL delete an existing value if one is already present. + * + * Optional, must be a positive integer if provided. Defaults to + * the value of `maxSize` if provided. + */ + maxEntrySize?: Size; + /** + * A function that returns a number indicating the item's size. + * + * Requires {@link OptionsBase.maxSize} to be set. + * + * If not provided, and {@link OptionsBase.maxSize} or + * {@link OptionsBase.maxEntrySize} are set, then all + * {@link LRUCache#set} calls **must** provide an explicit + * {@link SetOptions.size} or sizeCalculation param. + */ + sizeCalculation?: SizeCalculator; + /** + * Method that provides the implementation for {@link LRUCache#fetch} + * + * ```ts + * fetchMethod(key, staleValue, { signal, options, context }) + * ``` + * + * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent + * to `Promise.resolve(cache.get(key))`. + * + * If at any time, `signal.aborted` is set to `true`, or if the + * `signal.onabort` method is called, or if it emits an `'abort'` event + * which you can listen to with `addEventListener`, then that means that + * the fetch should be abandoned. This may be passed along to async + * functions aware of AbortController/AbortSignal behavior. + * + * The `fetchMethod` should **only** return `undefined` or a Promise + * resolving to `undefined` if the AbortController signaled an `abort` + * event. In all other cases, it should return or resolve to a value + * suitable for adding to the cache. + * + * The `options` object is a union of the options that may be provided to + * `set()` and `get()`. If they are modified, then that will result in + * modifying the settings to `cache.set()` when the value is resolved, and + * in the case of + * {@link OptionsBase.noDeleteOnFetchRejection} and + * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of + * `fetchMethod` failures. + * + * For example, a DNS cache may update the TTL based on the value returned + * from a remote DNS server by changing `options.ttl` in the `fetchMethod`. + */ + fetchMethod?: Fetcher; + /** + * Method that provides the implementation for {@link LRUCache#memo} + */ + memoMethod?: Memoizer; + /** + * Set to true to suppress the deletion of stale data when a + * {@link OptionsBase.fetchMethod} returns a rejected promise. + */ + noDeleteOnFetchRejection?: boolean; + /** + * Do not delete stale items when they are retrieved with + * {@link LRUCache#get}. + * + * Note that the `get` return value will still be `undefined` + * unless {@link OptionsBase.allowStale} is true. + * + * When using time-expiring entries with `ttl`, by default stale + * items will be removed from the cache when the key is accessed + * with `cache.get()`. + * + * Setting this option will cause stale items to remain in the cache, until + * they are explicitly deleted with `cache.delete(key)`, or retrieved with + * `noDeleteOnStaleGet` set to `false`. + * + * This may be overridden by passing an options object to `cache.get()`. + * + * Only relevant if a ttl is used. + */ + noDeleteOnStaleGet?: boolean; + /** + * Set to true to allow returning stale data when a + * {@link OptionsBase.fetchMethod} throws an error or returns a rejected + * promise. + * + * This differs from using {@link OptionsBase.allowStale} in that stale + * data will ONLY be returned in the case that the {@link LRUCache#fetch} + * fails, not any other times. + * + * If a `fetchMethod` fails, and there is no stale value available, the + * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are + * suppressed. + * + * Implies `noDeleteOnFetchRejection`. + * + * This may be set in calls to `fetch()`, or defaulted on the constructor, + * or overridden by modifying the options object in the `fetchMethod`. + */ + allowStaleOnFetchRejection?: boolean; + /** + * Set to true to return a stale value from the cache when the + * `AbortSignal` passed to the {@link OptionsBase.fetchMethod} dispatches + * an `'abort'` event, whether user-triggered, or due to internal cache + * behavior. + * + * Unless {@link OptionsBase.ignoreFetchAbort} is also set, the underlying + * {@link OptionsBase.fetchMethod} will still be considered canceled, and + * any value it returns will be ignored and not cached. + * + * Caveat: since fetches are aborted when a new value is explicitly + * set in the cache, this can lead to fetch returning a stale value, + * since that was the fallback value _at the moment the `fetch()` was + * initiated_, even though the new updated value is now present in + * the cache. + * + * For example: + * + * ```ts + * const cache = new LRUCache({ + * ttl: 100, + * fetchMethod: async (url, oldValue, { signal }) => { + * const res = await fetch(url, { signal }) + * return await res.json() + * } + * }) + * cache.set('https://example.com/', { some: 'data' }) + * // 100ms go by... + * const result = cache.fetch('https://example.com/') + * cache.set('https://example.com/', { other: 'thing' }) + * console.log(await result) // { some: 'data' } + * console.log(cache.get('https://example.com/')) // { other: 'thing' } + * ``` + */ + allowStaleOnFetchAbort?: boolean; + /** + * Set to true to ignore the `abort` event emitted by the `AbortSignal` + * object passed to {@link OptionsBase.fetchMethod}, and still cache the + * resulting resolution value, as long as it is not `undefined`. + * + * When used on its own, this means aborted {@link LRUCache#fetch} calls + * are not immediately resolved or rejected when they are aborted, and + * instead take the full time to await. + * + * When used with {@link OptionsBase.allowStaleOnFetchAbort}, aborted + * {@link LRUCache#fetch} calls will resolve immediately to their stale + * cached value or `undefined`, and will continue to process and eventually + * update the cache when they resolve, as long as the resulting value is + * not `undefined`, thus supporting a "return stale on timeout while + * refreshing" mechanism by passing `AbortSignal.timeout(n)` as the signal. + * + * For example: + * + * ```ts + * const c = new LRUCache({ + * ttl: 100, + * ignoreFetchAbort: true, + * allowStaleOnFetchAbort: true, + * fetchMethod: async (key, oldValue, { signal }) => { + * // note: do NOT pass the signal to fetch()! + * // let's say this fetch can take a long time. + * const res = await fetch(`https://slow-backend-server/${key}`) + * return await res.json() + * }, + * }) + * + * // this will return the stale value after 100ms, while still + * // updating in the background for next time. + * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) }) + * ``` + * + * **Note**: regardless of this setting, an `abort` event _is still + * emitted on the `AbortSignal` object_, so may result in invalid results + * when passed to other underlying APIs that use AbortSignals. + * + * This may be overridden in the {@link OptionsBase.fetchMethod} or the + * call to {@link LRUCache#fetch}. + */ + ignoreFetchAbort?: boolean; + } + interface OptionsMaxLimit extends OptionsBase { + max: Count; + } + interface OptionsTTLLimit extends OptionsBase { + ttl: Milliseconds; + ttlAutopurge: boolean; + } + interface OptionsSizeLimit extends OptionsBase { + maxSize: Size; + } + /** + * The valid safe options for the {@link LRUCache} constructor + */ + type Options = OptionsMaxLimit | OptionsSizeLimit | OptionsTTLLimit; + /** + * Entry objects used by {@link LRUCache#load} and {@link LRUCache#dump}, + * and returned by {@link LRUCache#info}. + */ + interface Entry { + value: V; + ttl?: Milliseconds; + size?: Size; + start?: Milliseconds; + } +} +/** + * Default export, the thing you're using this module to get. + * + * The `K` and `V` types define the key and value types, respectively. The + * optional `FC` type defines the type of the `context` object passed to + * `cache.fetch()` and `cache.memo()`. + * + * Keys and values **must not** be `null` or `undefined`. + * + * All properties from the options object (with the exception of `max`, + * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are + * added as normal public members. (The listed options are read-only getters.) + * + * Changing any of these will alter the defaults for subsequent method calls. + */ +export declare class LRUCache implements Map { + #private; + /** + * {@link LRUCache.OptionsBase.ttl} + */ + ttl: LRUCache.Milliseconds; + /** + * {@link LRUCache.OptionsBase.ttlResolution} + */ + ttlResolution: LRUCache.Milliseconds; + /** + * {@link LRUCache.OptionsBase.ttlAutopurge} + */ + ttlAutopurge: boolean; + /** + * {@link LRUCache.OptionsBase.updateAgeOnGet} + */ + updateAgeOnGet: boolean; + /** + * {@link LRUCache.OptionsBase.updateAgeOnHas} + */ + updateAgeOnHas: boolean; + /** + * {@link LRUCache.OptionsBase.allowStale} + */ + allowStale: boolean; + /** + * {@link LRUCache.OptionsBase.noDisposeOnSet} + */ + noDisposeOnSet: boolean; + /** + * {@link LRUCache.OptionsBase.noUpdateTTL} + */ + noUpdateTTL: boolean; + /** + * {@link LRUCache.OptionsBase.maxEntrySize} + */ + maxEntrySize: LRUCache.Size; + /** + * {@link LRUCache.OptionsBase.sizeCalculation} + */ + sizeCalculation?: LRUCache.SizeCalculator; + /** + * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection} + */ + noDeleteOnFetchRejection: boolean; + /** + * {@link LRUCache.OptionsBase.noDeleteOnStaleGet} + */ + noDeleteOnStaleGet: boolean; + /** + * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort} + */ + allowStaleOnFetchAbort: boolean; + /** + * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} + */ + allowStaleOnFetchRejection: boolean; + /** + * {@link LRUCache.OptionsBase.ignoreFetchAbort} + */ + ignoreFetchAbort: boolean; + /** + * Do not call this method unless you need to inspect the + * inner workings of the cache. If anything returned by this + * object is modified in any way, strange breakage may occur. + * + * These fields are private for a reason! + * + * @internal + */ + static unsafeExposeInternals(c: LRUCache): { + starts: ZeroArray | undefined; + ttls: ZeroArray | undefined; + sizes: ZeroArray | undefined; + keyMap: Map; + keyList: (K | undefined)[]; + valList: (V | BackgroundFetch | undefined)[]; + next: NumberArray; + prev: NumberArray; + readonly head: Index; + readonly tail: Index; + free: StackLike; + isBackgroundFetch: (p: any) => boolean; + backgroundFetch: (k: K, index: number | undefined, options: LRUCache.FetchOptions, context: any) => BackgroundFetch; + moveToTail: (index: number) => void; + indexes: (options?: { + allowStale: boolean; + }) => Generator; + rindexes: (options?: { + allowStale: boolean; + }) => Generator; + isStale: (index: number | undefined) => boolean; + }; + /** + * {@link LRUCache.OptionsBase.max} (read-only) + */ + get max(): LRUCache.Count; + /** + * {@link LRUCache.OptionsBase.maxSize} (read-only) + */ + get maxSize(): LRUCache.Count; + /** + * The total computed size of items in the cache (read-only) + */ + get calculatedSize(): LRUCache.Size; + /** + * The number of items stored in the cache (read-only) + */ + get size(): LRUCache.Count; + /** + * {@link LRUCache.OptionsBase.fetchMethod} (read-only) + */ + get fetchMethod(): LRUCache.Fetcher | undefined; + get memoMethod(): LRUCache.Memoizer | undefined; + /** + * {@link LRUCache.OptionsBase.dispose} (read-only) + */ + get dispose(): LRUCache.Disposer | undefined; + /** + * {@link LRUCache.OptionsBase.disposeAfter} (read-only) + */ + get disposeAfter(): LRUCache.Disposer | undefined; + constructor(options: LRUCache.Options | LRUCache); + /** + * Return the number of ms left in the item's TTL. If item is not in cache, + * returns `0`. Returns `Infinity` if item is in cache without a defined TTL. + */ + getRemainingTTL(key: K): number; + /** + * Return a generator yielding `[key, value]` pairs, + * in order from most recently used to least recently used. + */ + entries(): Generator<[K, V], void, unknown>; + /** + * Inverse order version of {@link LRUCache.entries} + * + * Return a generator yielding `[key, value]` pairs, + * in order from least recently used to most recently used. + */ + rentries(): Generator<(K | V | BackgroundFetch | undefined)[], void, unknown>; + /** + * Return a generator yielding the keys in the cache, + * in order from most recently used to least recently used. + */ + keys(): Generator; + /** + * Inverse order version of {@link LRUCache.keys} + * + * Return a generator yielding the keys in the cache, + * in order from least recently used to most recently used. + */ + rkeys(): Generator; + /** + * Return a generator yielding the values in the cache, + * in order from most recently used to least recently used. + */ + values(): Generator; + /** + * Inverse order version of {@link LRUCache.values} + * + * Return a generator yielding the values in the cache, + * in order from least recently used to most recently used. + */ + rvalues(): Generator | undefined, void, unknown>; + /** + * Iterating over the cache itself yields the same results as + * {@link LRUCache.entries} + */ + [Symbol.iterator](): Generator<[K, V], void, unknown>; + /** + * A String value that is used in the creation of the default string + * description of an object. Called by the built-in method + * `Object.prototype.toString`. + */ + [Symbol.toStringTag]: string; + /** + * Find a value for which the supplied fn method returns a truthy value, + * similar to `Array.find()`. fn is called as `fn(value, key, cache)`. + */ + find(fn: (v: V, k: K, self: LRUCache) => boolean, getOptions?: LRUCache.GetOptions): V | undefined; + /** + * Call the supplied function on each item in the cache, in order from most + * recently used to least recently used. + * + * `fn` is called as `fn(value, key, cache)`. + * + * If `thisp` is provided, function will be called in the `this`-context of + * the provided object, or the cache if no `thisp` object is provided. + * + * Does not update age or recenty of use, or iterate over stale values. + */ + forEach(fn: (v: V, k: K, self: LRUCache) => any, thisp?: any): void; + /** + * The same as {@link LRUCache.forEach} but items are iterated over in + * reverse order. (ie, less recently used items are iterated over first.) + */ + rforEach(fn: (v: V, k: K, self: LRUCache) => any, thisp?: any): void; + /** + * Delete any stale entries. Returns true if anything was removed, + * false otherwise. + */ + purgeStale(): boolean; + /** + * Get the extended info about a given entry, to get its value, size, and + * TTL info simultaneously. Returns `undefined` if the key is not present. + * + * Unlike {@link LRUCache#dump}, which is designed to be portable and survive + * serialization, the `start` value is always the current timestamp, and the + * `ttl` is a calculated remaining time to live (negative if expired). + * + * Always returns stale values, if their info is found in the cache, so be + * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl}) + * if relevant. + */ + info(key: K): LRUCache.Entry | undefined; + /** + * Return an array of [key, {@link LRUCache.Entry}] tuples which can be + * passed to {@link LRLUCache#load}. + * + * The `start` fields are calculated relative to a portable `Date.now()` + * timestamp, even if `performance.now()` is available. + * + * Stale entries are always included in the `dump`, even if + * {@link LRUCache.OptionsBase.allowStale} is false. + * + * Note: this returns an actual array, not a generator, so it can be more + * easily passed around. + */ + dump(): [K, LRUCache.Entry][]; + /** + * Reset the cache and load in the items in entries in the order listed. + * + * The shape of the resulting cache may be different if the same options are + * not used in both caches. + * + * The `start` fields are assumed to be calculated relative to a portable + * `Date.now()` timestamp, even if `performance.now()` is available. + */ + load(arr: [K, LRUCache.Entry][]): void; + /** + * Add a value to the cache. + * + * Note: if `undefined` is specified as a value, this is an alias for + * {@link LRUCache#delete} + * + * Fields on the {@link LRUCache.SetOptions} options param will override + * their corresponding values in the constructor options for the scope + * of this single `set()` operation. + * + * If `start` is provided, then that will set the effective start + * time for the TTL calculation. Note that this must be a previous + * value of `performance.now()` if supported, or a previous value of + * `Date.now()` if not. + * + * Options object may also include `size`, which will prevent + * calling the `sizeCalculation` function and just use the specified + * number if it is a positive integer, and `noDisposeOnSet` which + * will prevent calling a `dispose` function in the case of + * overwrites. + * + * If the `size` (or return value of `sizeCalculation`) for a given + * entry is greater than `maxEntrySize`, then the item will not be + * added to the cache. + * + * Will update the recency of the entry. + * + * If the value is `undefined`, then this is an alias for + * `cache.delete(key)`. `undefined` is never stored in the cache. + */ + set(k: K, v: V | BackgroundFetch | undefined, setOptions?: LRUCache.SetOptions): this; + /** + * Evict the least recently used item, returning its value or + * `undefined` if cache is empty. + */ + pop(): V | undefined; + /** + * Check if a key is in the cache, without updating the recency of use. + * Will return false if the item is stale, even though it is technically + * in the cache. + * + * Check if a key is in the cache, without updating the recency of + * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set + * to `true` in either the options or the constructor. + * + * Will return `false` if the item is stale, even though it is technically in + * the cache. The difference can be determined (if it matters) by using a + * `status` argument, and inspecting the `has` field. + * + * Will not update item age unless + * {@link LRUCache.OptionsBase.updateAgeOnHas} is set. + */ + has(k: K, hasOptions?: LRUCache.HasOptions): boolean; + /** + * Like {@link LRUCache#get} but doesn't update recency or delete stale + * items. + * + * Returns `undefined` if the item is stale, unless + * {@link LRUCache.OptionsBase.allowStale} is set. + */ + peek(k: K, peekOptions?: LRUCache.PeekOptions): V | undefined; + /** + * Make an asynchronous cached fetch using the + * {@link LRUCache.OptionsBase.fetchMethod} function. + * + * If the value is in the cache and not stale, then the returned + * Promise resolves to the value. + * + * If not in the cache, or beyond its TTL staleness, then + * `fetchMethod(key, staleValue, { options, signal, context })` is + * called, and the value returned will be added to the cache once + * resolved. + * + * If called with `allowStale`, and an asynchronous fetch is + * currently in progress to reload a stale value, then the former + * stale value will be returned. + * + * If called with `forceRefresh`, then the cached item will be + * re-fetched, even if it is not stale. However, if `allowStale` is also + * set, then the old value will still be returned. This is useful + * in cases where you want to force a reload of a cached value. If + * a background fetch is already in progress, then `forceRefresh` + * has no effect. + * + * If multiple fetches for the same key are issued, then they will all be + * coalesced into a single call to fetchMethod. + * + * Note that this means that handling options such as + * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}, + * {@link LRUCache.FetchOptions.signal}, + * and {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} will be + * determined by the FIRST fetch() call for a given key. + * + * This is a known (fixable) shortcoming which will be addresed on when + * someone complains about it, as the fix would involve added complexity and + * may not be worth the costs for this edge case. + * + * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is + * effectively an alias for `Promise.resolve(cache.get(key))`. + * + * When the fetch method resolves to a value, if the fetch has not + * been aborted due to deletion, eviction, or being overwritten, + * then it is added to the cache using the options provided. + * + * If the key is evicted or deleted before the `fetchMethod` + * resolves, then the AbortSignal passed to the `fetchMethod` will + * receive an `abort` event, and the promise returned by `fetch()` + * will reject with the reason for the abort. + * + * If a `signal` is passed to the `fetch()` call, then aborting the + * signal will abort the fetch and cause the `fetch()` promise to + * reject with the reason provided. + * + * **Setting `context`** + * + * If an `FC` type is set to a type other than `unknown`, `void`, or + * `undefined` in the {@link LRUCache} constructor, then all + * calls to `cache.fetch()` _must_ provide a `context` option. If + * set to `undefined` or `void`, then calls to fetch _must not_ + * provide a `context` option. + * + * The `context` param allows you to provide arbitrary data that + * might be relevant in the course of fetching the data. It is only + * relevant for the course of a single `fetch()` operation, and + * discarded afterwards. + * + * **Note: `fetch()` calls are inflight-unique** + * + * If you call `fetch()` multiple times with the same key value, + * then every call after the first will resolve on the same + * promise1, + * _even if they have different settings that would otherwise change + * the behavior of the fetch_, such as `noDeleteOnFetchRejection` + * or `ignoreFetchAbort`. + * + * In most cases, this is not a problem (in fact, only fetching + * something once is what you probably want, if you're caching in + * the first place). If you are changing the fetch() options + * dramatically between runs, there's a good chance that you might + * be trying to fit divergent semantics into a single object, and + * would be better off with multiple cache instances. + * + * **1**: Ie, they're not the "same Promise", but they resolve at + * the same time, because they're both waiting on the same + * underlying fetchMethod response. + */ + fetch(k: K, fetchOptions: unknown extends FC ? LRUCache.FetchOptions : FC extends undefined | void ? LRUCache.FetchOptionsNoContext : LRUCache.FetchOptionsWithContext): Promise; + fetch(k: unknown extends FC ? K : FC extends undefined | void ? K : never, fetchOptions?: unknown extends FC ? LRUCache.FetchOptions : FC extends undefined | void ? LRUCache.FetchOptionsNoContext : never): Promise; + /** + * In some cases, `cache.fetch()` may resolve to `undefined`, either because + * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning + * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or + * because `ignoreFetchAbort` was specified (either to the constructor or + * in the {@link LRUCache.FetchOptions}). Also, the + * {@link OptionsBase.fetchMethod} may return `undefined` or `void`, making + * the test even more complicated. + * + * Because inferring the cases where `undefined` might be returned are so + * cumbersome, but testing for `undefined` can also be annoying, this method + * can be used, which will reject if `this.fetch()` resolves to undefined. + */ + forceFetch(k: K, fetchOptions: unknown extends FC ? LRUCache.FetchOptions : FC extends undefined | void ? LRUCache.FetchOptionsNoContext : LRUCache.FetchOptionsWithContext): Promise; + forceFetch(k: unknown extends FC ? K : FC extends undefined | void ? K : never, fetchOptions?: unknown extends FC ? LRUCache.FetchOptions : FC extends undefined | void ? LRUCache.FetchOptionsNoContext : never): Promise; + /** + * If the key is found in the cache, then this is equivalent to + * {@link LRUCache#get}. If not, in the cache, then calculate the value using + * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache. + * + * If an `FC` type is set to a type other than `unknown`, `void`, or + * `undefined` in the LRUCache constructor, then all calls to `cache.memo()` + * _must_ provide a `context` option. If set to `undefined` or `void`, then + * calls to memo _must not_ provide a `context` option. + * + * The `context` param allows you to provide arbitrary data that might be + * relevant in the course of fetching the data. It is only relevant for the + * course of a single `memo()` operation, and discarded afterwards. + */ + memo(k: K, memoOptions: unknown extends FC ? LRUCache.MemoOptions : FC extends undefined | void ? LRUCache.MemoOptionsNoContext : LRUCache.MemoOptionsWithContext): V; + memo(k: unknown extends FC ? K : FC extends undefined | void ? K : never, memoOptions?: unknown extends FC ? LRUCache.MemoOptions : FC extends undefined | void ? LRUCache.MemoOptionsNoContext : never): V; + /** + * Return a value from the cache. Will update the recency of the cache + * entry found. + * + * If the key is not found, get() will return `undefined`. + */ + get(k: K, getOptions?: LRUCache.GetOptions): V | undefined; + /** + * Deletes a key out of the cache. + * + * Returns true if the key was deleted, false otherwise. + */ + delete(k: K): boolean; + /** + * Clear the cache entirely, throwing away all values. + */ + clear(): void; +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/esm/index.d.ts.map b/node_modules/lru-cache/dist/esm/index.d.ts.map new file mode 100644 index 0000000..34d60c5 --- /dev/null +++ b/node_modules/lru-cache/dist/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AA0FH,QAAA,MAAM,IAAI,eAAiB,CAAA;AAC3B,MAAM,MAAM,MAAM,GAAG,MAAM,GAAG;IAAE,CAAC,IAAI,CAAC,EAAE,kBAAkB,CAAA;CAAE,CAAA;AAC5D,MAAM,MAAM,KAAK,GAAG,MAAM,GAAG;IAAE,CAAC,IAAI,CAAC,EAAE,gBAAgB,CAAA;CAAE,CAAA;AAKzD,MAAM,MAAM,SAAS,GAAG,UAAU,GAAG,WAAW,GAAG,WAAW,CAAA;AAC9D,MAAM,MAAM,WAAW,GAAG,SAAS,GAAG,MAAM,EAAE,CAAA;AAyB9C,cAAM,SAAU,SAAQ,KAAK,CAAC,MAAM,CAAC;g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AQ,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAC/B,EAAE,SAAS,SAAS,GAAG,IAAI,GAC3B,QAAQ,CAAC,qBAAqB,CAAC,CAAC,EAAE,CAAC,CAAC,GACpC,KAAK,GACR,OAAO,CAAC,CAAC,CAAC;IAiBb;;;;;;;;;;;;;OAaG;IACH,IAAI,CACF,CAAC,EAAE,CAAC,EACJ,WAAW,EAAE,OAAO,SAAS,EAAE,GAC3B,QAAQ,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAC9B,EAAE,SAAS,SAAS,GAAG,IAAI,GAC3B,QAAQ,CAAC,oBAAoB,CAAC,CAAC,EAAE,CAAC,CAAC,GACnC,QAAQ,CAAC,sBAAsB,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAC5C,CAAC;IAEJ,IAAI,CACF,CAAC,EAAE,OAAO,SAAS,EAAE,GACjB,CAAC,GACD,EAAE,SAAS,SAAS,GAAG,IAAI,GAC3B,CAAC,GACD,KAAK,EACT,WAAW,CAAC,EAAE,OAAO,SAAS,EAAE,GAC5B,QAAQ,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAC9B,EAAE,SAAS,SAAS,GAAG,IAAI,GAC3B,QAAQ,CAAC,oBAAoB,CAAC,CAAC,EAAE,CAAC,CAAC,GACnC,KAAK,GACR,CAAC;IAiBJ;;;;;OAKG;IACH,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,UAAU,GAAE,QAAQ,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAM;IAgFxD;;;;OAIG;IACH,MAAM,CAAC,CAAC,EAAE,CAAC;IAqDX;;OAEG;IACH,KAAK;CA0CN"} \ No newline at end of file diff --git a/node_modules/lru-cache/dist/esm/index.js b/node_modules/lru-cache/dist/esm/index.js new file mode 100644 index 0000000..555654a --- /dev/null +++ b/node_modules/lru-cache/dist/esm/index.js @@ -0,0 +1,1542 @@ +/** + * @module LRUCache + */ +const perf = typeof performance === 'object' && + performance && + typeof performance.now === 'function' + ? performance + : Date; +const warned = new Set(); +/* c8 ignore start */ +const PROCESS = (typeof process === 'object' && !!process ? process : {}); +/* c8 ignore start */ +const emitWarning = (msg, type, code, fn) => { + typeof PROCESS.emitWarning === 'function' + ? PROCESS.emitWarning(msg, type, code, fn) + : console.error(`[${code}] ${type}: ${msg}`); +}; +let AC = globalThis.AbortController; +let AS = globalThis.AbortSignal; +/* c8 ignore start */ +if (typeof AC === 'undefined') { + //@ts-ignore + AS = class AbortSignal { + onabort; + _onabort = []; + reason; + aborted = false; + addEventListener(_, fn) { + this._onabort.push(fn); + } + }; + //@ts-ignore + AC = class AbortController { + constructor() { + warnACPolyfill(); + } + signal = new AS(); + abort(reason) { + if (this.signal.aborted) + return; + //@ts-ignore + this.signal.reason = reason; + //@ts-ignore + this.signal.aborted = true; + //@ts-ignore + for (const fn of this.signal._onabort) { + fn(reason); + } + this.signal.onabort?.(reason); + } + }; + let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'; + const warnACPolyfill = () => { + if (!printACPolyfillWarning) + return; + printACPolyfillWarning = false; + emitWarning('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', warnACPolyfill); + }; +} +/* c8 ignore stop */ +const shouldWarn = (code) => !warned.has(code); +const TYPE = Symbol('type'); +const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n); +/* c8 ignore start */ +// This is a little bit ridiculous, tbh. +// The maximum array length is 2^32-1 or thereabouts on most JS impls. +// And well before that point, you're caching the entire world, I mean, +// that's ~32GB of just integers for the next/prev links, plus whatever +// else to hold that many keys and values. Just filling the memory with +// zeroes at init time is brutal when you get that big. +// But why not be complete? +// Maybe in the future, these limits will have expanded. +const getUintArray = (max) => !isPosInt(max) + ? null + : max <= Math.pow(2, 8) + ? Uint8Array + : max <= Math.pow(2, 16) + ? Uint16Array + : max <= Math.pow(2, 32) + ? Uint32Array + : max <= Number.MAX_SAFE_INTEGER + ? ZeroArray + : null; +/* c8 ignore stop */ +class ZeroArray extends Array { + constructor(size) { + super(size); + this.fill(0); + } +} +class Stack { + heap; + length; + // private constructor + static #constructing = false; + static create(max) { + const HeapCls = getUintArray(max); + if (!HeapCls) + return []; + Stack.#constructing = true; + const s = new Stack(max, HeapCls); + Stack.#constructing = false; + return s; + } + constructor(max, HeapCls) { + /* c8 ignore start */ + if (!Stack.#constructing) { + throw new TypeError('instantiate Stack using Stack.create(n)'); + } + /* c8 ignore stop */ + this.heap = new HeapCls(max); + this.length = 0; + } + push(n) { + this.heap[this.length++] = n; + } + pop() { + return this.heap[--this.length]; + } +} +/** + * Default export, the thing you're using this module to get. + * + * The `K` and `V` types define the key and value types, respectively. The + * optional `FC` type defines the type of the `context` object passed to + * `cache.fetch()` and `cache.memo()`. + * + * Keys and values **must not** be `null` or `undefined`. + * + * All properties from the options object (with the exception of `max`, + * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are + * added as normal public members. (The listed options are read-only getters.) + * + * Changing any of these will alter the defaults for subsequent method calls. + */ +export class LRUCache { + // options that cannot be changed without disaster + #max; + #maxSize; + #dispose; + #disposeAfter; + #fetchMethod; + #memoMethod; + /** + * {@link LRUCache.OptionsBase.ttl} + */ + ttl; + /** + * {@link LRUCache.OptionsBase.ttlResolution} + */ + ttlResolution; + /** + * {@link LRUCache.OptionsBase.ttlAutopurge} + */ + ttlAutopurge; + /** + * {@link LRUCache.OptionsBase.updateAgeOnGet} + */ + updateAgeOnGet; + /** + * {@link LRUCache.OptionsBase.updateAgeOnHas} + */ + updateAgeOnHas; + /** + * {@link LRUCache.OptionsBase.allowStale} + */ + allowStale; + /** + * {@link LRUCache.OptionsBase.noDisposeOnSet} + */ + noDisposeOnSet; + /** + * {@link LRUCache.OptionsBase.noUpdateTTL} + */ + noUpdateTTL; + /** + * {@link LRUCache.OptionsBase.maxEntrySize} + */ + maxEntrySize; + /** + * {@link LRUCache.OptionsBase.sizeCalculation} + */ + sizeCalculation; + /** + * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection} + */ + noDeleteOnFetchRejection; + /** + * {@link LRUCache.OptionsBase.noDeleteOnStaleGet} + */ + noDeleteOnStaleGet; + /** + * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort} + */ + allowStaleOnFetchAbort; + /** + * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} + */ + allowStaleOnFetchRejection; + /** + * {@link LRUCache.OptionsBase.ignoreFetchAbort} + */ + ignoreFetchAbort; + // computed properties + #size; + #calculatedSize; + #keyMap; + #keyList; + #valList; + #next; + #prev; + #head; + #tail; + #free; + #disposed; + #sizes; + #starts; + #ttls; + #hasDispose; + #hasFetchMethod; + #hasDisposeAfter; + /** + * Do not call this method unless you need to inspect the + * inner workings of the cache. If anything returned by this + * object is modified in any way, strange breakage may occur. + * + * These fields are private for a reason! + * + * @internal + */ + static unsafeExposeInternals(c) { + return { + // properties + starts: c.#starts, + ttls: c.#ttls, + sizes: c.#sizes, + keyMap: c.#keyMap, + keyList: c.#keyList, + valList: c.#valList, + next: c.#next, + prev: c.#prev, + get head() { + return c.#head; + }, + get tail() { + return c.#tail; + }, + free: c.#free, + // methods + isBackgroundFetch: (p) => c.#isBackgroundFetch(p), + backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context), + moveToTail: (index) => c.#moveToTail(index), + indexes: (options) => c.#indexes(options), + rindexes: (options) => c.#rindexes(options), + isStale: (index) => c.#isStale(index), + }; + } + // Protected read-only members + /** + * {@link LRUCache.OptionsBase.max} (read-only) + */ + get max() { + return this.#max; + } + /** + * {@link LRUCache.OptionsBase.maxSize} (read-only) + */ + get maxSize() { + return this.#maxSize; + } + /** + * The total computed size of items in the cache (read-only) + */ + get calculatedSize() { + return this.#calculatedSize; + } + /** + * The number of items stored in the cache (read-only) + */ + get size() { + return this.#size; + } + /** + * {@link LRUCache.OptionsBase.fetchMethod} (read-only) + */ + get fetchMethod() { + return this.#fetchMethod; + } + get memoMethod() { + return this.#memoMethod; + } + /** + * {@link LRUCache.OptionsBase.dispose} (read-only) + */ + get dispose() { + return this.#dispose; + } + /** + * {@link LRUCache.OptionsBase.disposeAfter} (read-only) + */ + get disposeAfter() { + return this.#disposeAfter; + } + constructor(options) { + const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options; + if (max !== 0 && !isPosInt(max)) { + throw new TypeError('max option must be a nonnegative integer'); + } + const UintArray = max ? getUintArray(max) : Array; + if (!UintArray) { + throw new Error('invalid max value: ' + max); + } + this.#max = max; + this.#maxSize = maxSize; + this.maxEntrySize = maxEntrySize || this.#maxSize; + this.sizeCalculation = sizeCalculation; + if (this.sizeCalculation) { + if (!this.#maxSize && !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 (memoMethod !== undefined && + typeof memoMethod !== 'function') { + throw new TypeError('memoMethod must be a function if defined'); + } + this.#memoMethod = memoMethod; + if (fetchMethod !== undefined && + typeof fetchMethod !== 'function') { + throw new TypeError('fetchMethod must be a function if specified'); + } + this.#fetchMethod = fetchMethod; + this.#hasFetchMethod = !!fetchMethod; + this.#keyMap = new Map(); + this.#keyList = new Array(max).fill(undefined); + this.#valList = new Array(max).fill(undefined); + this.#next = new UintArray(max); + this.#prev = new UintArray(max); + this.#head = 0; + this.#tail = 0; + this.#free = Stack.create(max); + this.#size = 0; + this.#calculatedSize = 0; + if (typeof dispose === 'function') { + this.#dispose = dispose; + } + if (typeof disposeAfter === 'function') { + this.#disposeAfter = disposeAfter; + this.#disposed = []; + } + else { + this.#disposeAfter = undefined; + this.#disposed = undefined; + } + this.#hasDispose = !!this.#dispose; + this.#hasDisposeAfter = !!this.#disposeAfter; + this.noDisposeOnSet = !!noDisposeOnSet; + this.noUpdateTTL = !!noUpdateTTL; + this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection; + this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection; + this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort; + this.ignoreFetchAbort = !!ignoreFetchAbort; + // NB: maxEntrySize is set to maxSize if it's set + if (this.maxEntrySize !== 0) { + if (this.#maxSize !== 0) { + if (!isPosInt(this.#maxSize)) { + throw new TypeError('maxSize must be a positive integer if specified'); + } + } + if (!isPosInt(this.maxEntrySize)) { + throw new TypeError('maxEntrySize must be a positive integer if specified'); + } + this.#initializeSizeTracking(); + } + this.allowStale = !!allowStale; + this.noDeleteOnStaleGet = !!noDeleteOnStaleGet; + this.updateAgeOnGet = !!updateAgeOnGet; + this.updateAgeOnHas = !!updateAgeOnHas; + this.ttlResolution = + isPosInt(ttlResolution) || ttlResolution === 0 + ? ttlResolution + : 1; + this.ttlAutopurge = !!ttlAutopurge; + this.ttl = ttl || 0; + if (this.ttl) { + if (!isPosInt(this.ttl)) { + throw new TypeError('ttl must be a positive integer if specified'); + } + this.#initializeTTLTracking(); + } + // do not allow completely unbounded caches + if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) { + throw new TypeError('At least one of max, maxSize, or ttl is required'); + } + if (!this.ttlAutopurge && !this.#max && !this.#maxSize) { + const code = 'LRU_CACHE_UNBOUNDED'; + if (shouldWarn(code)) { + warned.add(code); + const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' + + 'result in unbounded memory consumption.'; + emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache); + } + } + } + /** + * Return the number of ms left in the item's TTL. If item is not in cache, + * returns `0`. Returns `Infinity` if item is in cache without a defined TTL. + */ + getRemainingTTL(key) { + return this.#keyMap.has(key) ? Infinity : 0; + } + #initializeTTLTracking() { + const ttls = new ZeroArray(this.#max); + const starts = new ZeroArray(this.#max); + this.#ttls = ttls; + this.#starts = starts; + this.#setItemTTL = (index, ttl, start = perf.now()) => { + starts[index] = ttl !== 0 ? start : 0; + ttls[index] = ttl; + if (ttl !== 0 && this.ttlAutopurge) { + const t = setTimeout(() => { + if (this.#isStale(index)) { + this.#delete(this.#keyList[index], 'expire'); + } + }, ttl + 1); + // unref() not supported on all platforms + /* c8 ignore start */ + if (t.unref) { + t.unref(); + } + /* c8 ignore stop */ + } + }; + this.#updateItemAge = index => { + starts[index] = ttls[index] !== 0 ? perf.now() : 0; + }; + this.#statusTTL = (status, index) => { + if (ttls[index]) { + const ttl = ttls[index]; + const start = starts[index]; + /* c8 ignore next */ + if (!ttl || !start) + return; + status.ttl = ttl; + status.start = start; + status.now = cachedNow || getNow(); + const age = status.now - start; + status.remainingTTL = ttl - age; + } + }; + // debounce calls to perf.now() to 1s so we're not hitting + // that costly call repeatedly. + let cachedNow = 0; + const getNow = () => { + const n = perf.now(); + if (this.ttlResolution > 0) { + cachedNow = n; + const t = setTimeout(() => (cachedNow = 0), this.ttlResolution); + // not available on all platforms + /* c8 ignore start */ + if (t.unref) { + t.unref(); + } + /* c8 ignore stop */ + } + return n; + }; + this.getRemainingTTL = key => { + const index = this.#keyMap.get(key); + if (index === undefined) { + return 0; + } + const ttl = ttls[index]; + const start = starts[index]; + if (!ttl || !start) { + return Infinity; + } + const age = (cachedNow || getNow()) - start; + return ttl - age; + }; + this.#isStale = index => { + const s = starts[index]; + const t = ttls[index]; + return !!t && !!s && (cachedNow || getNow()) - s > t; + }; + } + // conditionally set private methods related to TTL + #updateItemAge = () => { }; + #statusTTL = () => { }; + #setItemTTL = () => { }; + /* c8 ignore stop */ + #isStale = () => false; + #initializeSizeTracking() { + const sizes = new ZeroArray(this.#max); + this.#calculatedSize = 0; + this.#sizes = sizes; + this.#removeItemSize = index => { + this.#calculatedSize -= sizes[index]; + sizes[index] = 0; + }; + this.#requireSize = (k, v, size, sizeCalculation) => { + // provisionally accept background fetches. + // actual value size will be checked when they return. + if (this.#isBackgroundFetch(v)) { + return 0; + } + if (!isPosInt(size)) { + if (sizeCalculation) { + if (typeof sizeCalculation !== 'function') { + throw new TypeError('sizeCalculation must be a function'); + } + size = sizeCalculation(v, k); + if (!isPosInt(size)) { + 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 size; + }; + this.#addItemSize = (index, size, status) => { + sizes[index] = size; + if (this.#maxSize) { + const maxSize = this.#maxSize - sizes[index]; + while (this.#calculatedSize > maxSize) { + this.#evict(true); + } + } + this.#calculatedSize += sizes[index]; + if (status) { + status.entrySize = size; + status.totalCalculatedSize = this.#calculatedSize; + } + }; + } + #removeItemSize = _i => { }; + #addItemSize = (_i, _s, _st) => { }; + #requireSize = (_k, _v, size, sizeCalculation) => { + if (size || sizeCalculation) { + throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache'); + } + return 0; + }; + *#indexes({ allowStale = this.allowStale } = {}) { + if (this.#size) { + for (let i = this.#tail; true;) { + if (!this.#isValidIndex(i)) { + break; + } + if (allowStale || !this.#isStale(i)) { + yield i; + } + if (i === this.#head) { + break; + } + else { + i = this.#prev[i]; + } + } + } + } + *#rindexes({ allowStale = this.allowStale } = {}) { + if (this.#size) { + for (let i = this.#head; true;) { + if (!this.#isValidIndex(i)) { + break; + } + if (allowStale || !this.#isStale(i)) { + yield i; + } + if (i === this.#tail) { + break; + } + else { + i = this.#next[i]; + } + } + } + } + #isValidIndex(index) { + return (index !== undefined && + this.#keyMap.get(this.#keyList[index]) === index); + } + /** + * Return a generator yielding `[key, value]` pairs, + * in order from most recently used to least recently used. + */ + *entries() { + for (const i of this.#indexes()) { + if (this.#valList[i] !== undefined && + this.#keyList[i] !== undefined && + !this.#isBackgroundFetch(this.#valList[i])) { + yield [this.#keyList[i], this.#valList[i]]; + } + } + } + /** + * Inverse order version of {@link LRUCache.entries} + * + * Return a generator yielding `[key, value]` pairs, + * in order from least recently used to most recently used. + */ + *rentries() { + for (const i of this.#rindexes()) { + if (this.#valList[i] !== undefined && + this.#keyList[i] !== undefined && + !this.#isBackgroundFetch(this.#valList[i])) { + yield [this.#keyList[i], this.#valList[i]]; + } + } + } + /** + * Return a generator yielding the keys in the cache, + * in order from most recently used to least recently used. + */ + *keys() { + for (const i of this.#indexes()) { + const k = this.#keyList[i]; + if (k !== undefined && + !this.#isBackgroundFetch(this.#valList[i])) { + yield k; + } + } + } + /** + * Inverse order version of {@link LRUCache.keys} + * + * Return a generator yielding the keys in the cache, + * in order from least recently used to most recently used. + */ + *rkeys() { + for (const i of this.#rindexes()) { + const k = this.#keyList[i]; + if (k !== undefined && + !this.#isBackgroundFetch(this.#valList[i])) { + yield k; + } + } + } + /** + * Return a generator yielding the values in the cache, + * in order from most recently used to least recently used. + */ + *values() { + for (const i of this.#indexes()) { + const v = this.#valList[i]; + if (v !== undefined && + !this.#isBackgroundFetch(this.#valList[i])) { + yield this.#valList[i]; + } + } + } + /** + * Inverse order version of {@link LRUCache.values} + * + * Return a generator yielding the values in the cache, + * in order from least recently used to most recently used. + */ + *rvalues() { + for (const i of this.#rindexes()) { + const v = this.#valList[i]; + if (v !== undefined && + !this.#isBackgroundFetch(this.#valList[i])) { + yield this.#valList[i]; + } + } + } + /** + * Iterating over the cache itself yields the same results as + * {@link LRUCache.entries} + */ + [Symbol.iterator]() { + return this.entries(); + } + /** + * A String value that is used in the creation of the default string + * description of an object. Called by the built-in method + * `Object.prototype.toString`. + */ + [Symbol.toStringTag] = 'LRUCache'; + /** + * Find a value for which the supplied fn method returns a truthy value, + * similar to `Array.find()`. fn is called as `fn(value, key, cache)`. + */ + find(fn, getOptions = {}) { + for (const i of this.#indexes()) { + const v = this.#valList[i]; + const value = this.#isBackgroundFetch(v) + ? v.__staleWhileFetching + : v; + if (value === undefined) + continue; + if (fn(value, this.#keyList[i], this)) { + return this.get(this.#keyList[i], getOptions); + } + } + } + /** + * Call the supplied function on each item in the cache, in order from most + * recently used to least recently used. + * + * `fn` is called as `fn(value, key, cache)`. + * + * If `thisp` is provided, function will be called in the `this`-context of + * the provided object, or the cache if no `thisp` object is provided. + * + * Does not update age or recenty of use, or iterate over stale values. + */ + forEach(fn, thisp = this) { + for (const i of this.#indexes()) { + const v = this.#valList[i]; + const value = this.#isBackgroundFetch(v) + ? v.__staleWhileFetching + : v; + if (value === undefined) + continue; + fn.call(thisp, value, this.#keyList[i], this); + } + } + /** + * The same as {@link LRUCache.forEach} but items are iterated over in + * reverse order. (ie, less recently used items are iterated over first.) + */ + rforEach(fn, thisp = this) { + for (const i of this.#rindexes()) { + const v = this.#valList[i]; + const value = this.#isBackgroundFetch(v) + ? v.__staleWhileFetching + : v; + if (value === undefined) + continue; + fn.call(thisp, value, this.#keyList[i], this); + } + } + /** + * Delete any stale entries. Returns true if anything was removed, + * false otherwise. + */ + purgeStale() { + let deleted = false; + for (const i of this.#rindexes({ allowStale: true })) { + if (this.#isStale(i)) { + this.#delete(this.#keyList[i], 'expire'); + deleted = true; + } + } + return deleted; + } + /** + * Get the extended info about a given entry, to get its value, size, and + * TTL info simultaneously. Returns `undefined` if the key is not present. + * + * Unlike {@link LRUCache#dump}, which is designed to be portable and survive + * serialization, the `start` value is always the current timestamp, and the + * `ttl` is a calculated remaining time to live (negative if expired). + * + * Always returns stale values, if their info is found in the cache, so be + * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl}) + * if relevant. + */ + info(key) { + const i = this.#keyMap.get(key); + if (i === undefined) + return undefined; + const v = this.#valList[i]; + const value = this.#isBackgroundFetch(v) + ? v.__staleWhileFetching + : v; + if (value === undefined) + return undefined; + const entry = { value }; + if (this.#ttls && this.#starts) { + const ttl = this.#ttls[i]; + const start = this.#starts[i]; + if (ttl && start) { + const remain = ttl - (perf.now() - start); + entry.ttl = remain; + entry.start = Date.now(); + } + } + if (this.#sizes) { + entry.size = this.#sizes[i]; + } + return entry; + } + /** + * Return an array of [key, {@link LRUCache.Entry}] tuples which can be + * passed to {@link LRLUCache#load}. + * + * The `start` fields are calculated relative to a portable `Date.now()` + * timestamp, even if `performance.now()` is available. + * + * Stale entries are always included in the `dump`, even if + * {@link LRUCache.OptionsBase.allowStale} is false. + * + * Note: this returns an actual array, not a generator, so it can be more + * easily passed around. + */ + dump() { + const arr = []; + for (const i of this.#indexes({ allowStale: true })) { + const key = this.#keyList[i]; + const v = this.#valList[i]; + const value = this.#isBackgroundFetch(v) + ? v.__staleWhileFetching + : v; + if (value === undefined || key === undefined) + continue; + const entry = { value }; + if (this.#ttls && this.#starts) { + entry.ttl = this.#ttls[i]; + // always dump the start relative to a portable timestamp + // it's ok for this to be a bit slow, it's a rare operation. + const age = perf.now() - this.#starts[i]; + entry.start = Math.floor(Date.now() - age); + } + if (this.#sizes) { + entry.size = this.#sizes[i]; + } + arr.unshift([key, entry]); + } + return arr; + } + /** + * Reset the cache and load in the items in entries in the order listed. + * + * The shape of the resulting cache may be different if the same options are + * not used in both caches. + * + * The `start` fields are assumed to be calculated relative to a portable + * `Date.now()` timestamp, even if `performance.now()` is available. + */ + load(arr) { + this.clear(); + for (const [key, entry] of arr) { + if (entry.start) { + // entry.start is a portable timestamp, but we may be using + // node's performance.now(), so calculate the offset, so that + // we get the intended remaining TTL, no matter how long it's + // been on ice. + // + // it's ok for this to be a bit slow, it's a rare operation. + const age = Date.now() - entry.start; + entry.start = perf.now() - age; + } + this.set(key, entry.value, entry); + } + } + /** + * Add a value to the cache. + * + * Note: if `undefined` is specified as a value, this is an alias for + * {@link LRUCache#delete} + * + * Fields on the {@link LRUCache.SetOptions} options param will override + * their corresponding values in the constructor options for the scope + * of this single `set()` operation. + * + * If `start` is provided, then that will set the effective start + * time for the TTL calculation. Note that this must be a previous + * value of `performance.now()` if supported, or a previous value of + * `Date.now()` if not. + * + * Options object may also include `size`, which will prevent + * calling the `sizeCalculation` function and just use the specified + * number if it is a positive integer, and `noDisposeOnSet` which + * will prevent calling a `dispose` function in the case of + * overwrites. + * + * If the `size` (or return value of `sizeCalculation`) for a given + * entry is greater than `maxEntrySize`, then the item will not be + * added to the cache. + * + * Will update the recency of the entry. + * + * If the value is `undefined`, then this is an alias for + * `cache.delete(key)`. `undefined` is never stored in the cache. + */ + set(k, v, setOptions = {}) { + if (v === undefined) { + this.delete(k); + return this; + } + const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions; + let { noUpdateTTL = this.noUpdateTTL } = setOptions; + const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation); + // if the item doesn't fit, don't do anything + // NB: maxEntrySize set to maxSize by default + if (this.maxEntrySize && size > this.maxEntrySize) { + if (status) { + status.set = 'miss'; + status.maxEntrySizeExceeded = true; + } + // have to delete, in case something is there already. + this.#delete(k, 'set'); + return this; + } + let index = this.#size === 0 ? undefined : this.#keyMap.get(k); + if (index === undefined) { + // addition + index = (this.#size === 0 + ? this.#tail + : this.#free.length !== 0 + ? this.#free.pop() + : this.#size === this.#max + ? this.#evict(false) + : this.#size); + this.#keyList[index] = k; + this.#valList[index] = v; + this.#keyMap.set(k, index); + this.#next[this.#tail] = index; + this.#prev[index] = this.#tail; + this.#tail = index; + this.#size++; + this.#addItemSize(index, size, status); + if (status) + status.set = 'add'; + noUpdateTTL = false; + } + else { + // update + this.#moveToTail(index); + const oldVal = this.#valList[index]; + if (v !== oldVal) { + if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) { + oldVal.__abortController.abort(new Error('replaced')); + const { __staleWhileFetching: s } = oldVal; + if (s !== undefined && !noDisposeOnSet) { + if (this.#hasDispose) { + this.#dispose?.(s, k, 'set'); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([s, k, 'set']); + } + } + } + else if (!noDisposeOnSet) { + if (this.#hasDispose) { + this.#dispose?.(oldVal, k, 'set'); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([oldVal, k, 'set']); + } + } + this.#removeItemSize(index); + this.#addItemSize(index, size, status); + this.#valList[index] = v; + if (status) { + status.set = 'replace'; + const oldValue = oldVal && this.#isBackgroundFetch(oldVal) + ? oldVal.__staleWhileFetching + : oldVal; + if (oldValue !== undefined) + status.oldValue = oldValue; + } + } + else if (status) { + status.set = 'update'; + } + } + if (ttl !== 0 && !this.#ttls) { + this.#initializeTTLTracking(); + } + if (this.#ttls) { + if (!noUpdateTTL) { + this.#setItemTTL(index, ttl, start); + } + if (status) + this.#statusTTL(status, index); + } + if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) { + const dt = this.#disposed; + let task; + while ((task = dt?.shift())) { + this.#disposeAfter?.(...task); + } + } + return this; + } + /** + * Evict the least recently used item, returning its value or + * `undefined` if cache is empty. + */ + pop() { + try { + while (this.#size) { + const val = this.#valList[this.#head]; + this.#evict(true); + if (this.#isBackgroundFetch(val)) { + if (val.__staleWhileFetching) { + return val.__staleWhileFetching; + } + } + else if (val !== undefined) { + return val; + } + } + } + finally { + if (this.#hasDisposeAfter && this.#disposed) { + const dt = this.#disposed; + let task; + while ((task = dt?.shift())) { + this.#disposeAfter?.(...task); + } + } + } + } + #evict(free) { + const head = this.#head; + const k = this.#keyList[head]; + const v = this.#valList[head]; + if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) { + v.__abortController.abort(new Error('evicted')); + } + else if (this.#hasDispose || this.#hasDisposeAfter) { + if (this.#hasDispose) { + this.#dispose?.(v, k, 'evict'); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([v, k, 'evict']); + } + } + this.#removeItemSize(head); + // if we aren't about to use the index, then null these out + if (free) { + this.#keyList[head] = undefined; + this.#valList[head] = undefined; + this.#free.push(head); + } + if (this.#size === 1) { + this.#head = this.#tail = 0; + this.#free.length = 0; + } + else { + this.#head = this.#next[head]; + } + this.#keyMap.delete(k); + this.#size--; + return head; + } + /** + * Check if a key is in the cache, without updating the recency of use. + * Will return false if the item is stale, even though it is technically + * in the cache. + * + * Check if a key is in the cache, without updating the recency of + * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set + * to `true` in either the options or the constructor. + * + * Will return `false` if the item is stale, even though it is technically in + * the cache. The difference can be determined (if it matters) by using a + * `status` argument, and inspecting the `has` field. + * + * Will not update item age unless + * {@link LRUCache.OptionsBase.updateAgeOnHas} is set. + */ + has(k, hasOptions = {}) { + const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions; + const index = this.#keyMap.get(k); + if (index !== undefined) { + const v = this.#valList[index]; + if (this.#isBackgroundFetch(v) && + v.__staleWhileFetching === undefined) { + return false; + } + if (!this.#isStale(index)) { + if (updateAgeOnHas) { + this.#updateItemAge(index); + } + if (status) { + status.has = 'hit'; + this.#statusTTL(status, index); + } + return true; + } + else if (status) { + status.has = 'stale'; + this.#statusTTL(status, index); + } + } + else if (status) { + status.has = 'miss'; + } + return false; + } + /** + * Like {@link LRUCache#get} but doesn't update recency or delete stale + * items. + * + * Returns `undefined` if the item is stale, unless + * {@link LRUCache.OptionsBase.allowStale} is set. + */ + peek(k, peekOptions = {}) { + const { allowStale = this.allowStale } = peekOptions; + const index = this.#keyMap.get(k); + if (index === undefined || + (!allowStale && this.#isStale(index))) { + return; + } + const v = this.#valList[index]; + // either stale and allowed, or forcing a refresh of non-stale value + return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; + } + #backgroundFetch(k, index, options, context) { + const v = index === undefined ? undefined : this.#valList[index]; + if (this.#isBackgroundFetch(v)) { + return v; + } + const ac = new AC(); + const { signal } = options; + // when/if our AC signals, then stop listening to theirs. + signal?.addEventListener('abort', () => ac.abort(signal.reason), { + signal: ac.signal, + }); + const fetchOpts = { + signal: ac.signal, + options, + context, + }; + const cb = (v, updateCache = false) => { + const { aborted } = ac.signal; + const ignoreAbort = options.ignoreFetchAbort && v !== undefined; + if (options.status) { + if (aborted && !updateCache) { + options.status.fetchAborted = true; + options.status.fetchError = ac.signal.reason; + if (ignoreAbort) + options.status.fetchAbortIgnored = true; + } + else { + options.status.fetchResolved = true; + } + } + if (aborted && !ignoreAbort && !updateCache) { + return fetchFail(ac.signal.reason); + } + // either we didn't abort, and are still here, or we did, and ignored + const bf = p; + if (this.#valList[index] === p) { + if (v === undefined) { + if (bf.__staleWhileFetching) { + this.#valList[index] = bf.__staleWhileFetching; + } + else { + this.#delete(k, 'fetch'); + } + } + else { + if (options.status) + options.status.fetchUpdated = true; + this.set(k, v, fetchOpts.options); + } + } + return v; + }; + const eb = (er) => { + if (options.status) { + options.status.fetchRejected = true; + options.status.fetchError = er; + } + return fetchFail(er); + }; + const fetchFail = (er) => { + const { aborted } = ac.signal; + const allowStaleAborted = aborted && options.allowStaleOnFetchAbort; + const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection; + const noDelete = allowStale || options.noDeleteOnFetchRejection; + const bf = p; + if (this.#valList[index] === p) { + // if we allow stale on fetch rejections, then we need to ensure that + // the stale value is not removed from the cache when the fetch fails. + const del = !noDelete || bf.__staleWhileFetching === undefined; + if (del) { + this.#delete(k, 'fetch'); + } + else if (!allowStaleAborted) { + // still replace the *promise* with the stale value, + // since we are done with the promise at this point. + // leave it untouched if we're still waiting for an + // aborted background fetch that hasn't yet returned. + this.#valList[index] = bf.__staleWhileFetching; + } + } + if (allowStale) { + if (options.status && bf.__staleWhileFetching !== undefined) { + options.status.returnedStale = true; + } + return bf.__staleWhileFetching; + } + else if (bf.__returned === bf) { + throw er; + } + }; + const pcall = (res, rej) => { + const fmp = this.#fetchMethod?.(k, v, fetchOpts); + if (fmp && fmp instanceof Promise) { + fmp.then(v => res(v === undefined ? undefined : v), rej); + } + // ignored, we go until we finish, regardless. + // defer check until we are actually aborting, + // so fetchMethod can override. + ac.signal.addEventListener('abort', () => { + if (!options.ignoreFetchAbort || + options.allowStaleOnFetchAbort) { + res(undefined); + // when it eventually resolves, update the cache. + if (options.allowStaleOnFetchAbort) { + res = v => cb(v, true); + } + } + }); + }; + if (options.status) + options.status.fetchDispatched = true; + const p = new Promise(pcall).then(cb, eb); + const bf = Object.assign(p, { + __abortController: ac, + __staleWhileFetching: v, + __returned: undefined, + }); + if (index === undefined) { + // internal, don't expose status. + this.set(k, bf, { ...fetchOpts.options, status: undefined }); + index = this.#keyMap.get(k); + } + else { + this.#valList[index] = bf; + } + return bf; + } + #isBackgroundFetch(p) { + if (!this.#hasFetchMethod) + return false; + const b = p; + return (!!b && + b instanceof Promise && + b.hasOwnProperty('__staleWhileFetching') && + b.__abortController instanceof AC); + } + async fetch(k, fetchOptions = {}) { + const { + // get options + allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, + // set options + ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL, + // fetch exclusive options + noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions; + if (!this.#hasFetchMethod) { + if (status) + status.fetch = 'get'; + return this.get(k, { + allowStale, + updateAgeOnGet, + noDeleteOnStaleGet, + status, + }); + } + const options = { + allowStale, + updateAgeOnGet, + noDeleteOnStaleGet, + ttl, + noDisposeOnSet, + size, + sizeCalculation, + noUpdateTTL, + noDeleteOnFetchRejection, + allowStaleOnFetchRejection, + allowStaleOnFetchAbort, + ignoreFetchAbort, + status, + signal, + }; + let index = this.#keyMap.get(k); + if (index === undefined) { + if (status) + status.fetch = 'miss'; + const p = this.#backgroundFetch(k, index, options, context); + return (p.__returned = p); + } + else { + // in cache, maybe already fetching + const v = this.#valList[index]; + if (this.#isBackgroundFetch(v)) { + const stale = allowStale && v.__staleWhileFetching !== undefined; + if (status) { + status.fetch = 'inflight'; + if (stale) + status.returnedStale = true; + } + return stale ? v.__staleWhileFetching : (v.__returned = v); + } + // if we force a refresh, that means do NOT serve the cached value, + // unless we are already in the process of refreshing the cache. + const isStale = this.#isStale(index); + if (!forceRefresh && !isStale) { + if (status) + status.fetch = 'hit'; + this.#moveToTail(index); + if (updateAgeOnGet) { + this.#updateItemAge(index); + } + if (status) + this.#statusTTL(status, index); + return v; + } + // ok, it is stale or a forced refresh, and not already fetching. + // refresh the cache. + const p = this.#backgroundFetch(k, index, options, context); + const hasStale = p.__staleWhileFetching !== undefined; + const staleVal = hasStale && allowStale; + if (status) { + status.fetch = isStale ? 'stale' : 'refresh'; + if (staleVal && isStale) + status.returnedStale = true; + } + return staleVal ? p.__staleWhileFetching : (p.__returned = p); + } + } + async forceFetch(k, fetchOptions = {}) { + const v = await this.fetch(k, fetchOptions); + if (v === undefined) + throw new Error('fetch() returned undefined'); + return v; + } + memo(k, memoOptions = {}) { + const memoMethod = this.#memoMethod; + if (!memoMethod) { + throw new Error('no memoMethod provided to constructor'); + } + const { context, forceRefresh, ...options } = memoOptions; + const v = this.get(k, options); + if (!forceRefresh && v !== undefined) + return v; + const vv = memoMethod(k, v, { + options, + context, + }); + this.set(k, vv, options); + return vv; + } + /** + * Return a value from the cache. Will update the recency of the cache + * entry found. + * + * If the key is not found, get() will return `undefined`. + */ + get(k, getOptions = {}) { + const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions; + const index = this.#keyMap.get(k); + if (index !== undefined) { + const value = this.#valList[index]; + const fetching = this.#isBackgroundFetch(value); + if (status) + this.#statusTTL(status, index); + if (this.#isStale(index)) { + if (status) + status.get = 'stale'; + // delete only if not an in-flight background fetch + if (!fetching) { + if (!noDeleteOnStaleGet) { + this.#delete(k, 'expire'); + } + if (status && allowStale) + status.returnedStale = true; + return allowStale ? value : undefined; + } + else { + if (status && + allowStale && + value.__staleWhileFetching !== undefined) { + status.returnedStale = true; + } + return allowStale ? value.__staleWhileFetching : undefined; + } + } + else { + if (status) + status.get = 'hit'; + // if we're currently fetching it, we don't actually have it yet + // it's not stale, which means this isn't a staleWhileRefetching. + // If it's not stale, and fetching, AND has a __staleWhileFetching + // value, then that means the user fetched with {forceRefresh:true}, + // so it's safe to return that value. + if (fetching) { + return value.__staleWhileFetching; + } + this.#moveToTail(index); + if (updateAgeOnGet) { + this.#updateItemAge(index); + } + return value; + } + } + else if (status) { + status.get = 'miss'; + } + } + #connect(p, n) { + this.#prev[n] = p; + this.#next[p] = n; + } + #moveToTail(index) { + // if tail already, nothing to do + // if head, move head to next[index] + // else + // move next[prev[index]] to next[index] (head has no prev) + // move prev[next[index]] to prev[index] + // prev[index] = tail + // next[tail] = index + // tail = index + if (index !== this.#tail) { + if (index === this.#head) { + this.#head = this.#next[index]; + } + else { + this.#connect(this.#prev[index], this.#next[index]); + } + this.#connect(this.#tail, index); + this.#tail = index; + } + } + /** + * Deletes a key out of the cache. + * + * Returns true if the key was deleted, false otherwise. + */ + delete(k) { + return this.#delete(k, 'delete'); + } + #delete(k, reason) { + let deleted = false; + if (this.#size !== 0) { + const index = this.#keyMap.get(k); + if (index !== undefined) { + deleted = true; + if (this.#size === 1) { + this.#clear(reason); + } + else { + this.#removeItemSize(index); + const v = this.#valList[index]; + if (this.#isBackgroundFetch(v)) { + v.__abortController.abort(new Error('deleted')); + } + else if (this.#hasDispose || this.#hasDisposeAfter) { + if (this.#hasDispose) { + this.#dispose?.(v, k, reason); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([v, k, reason]); + } + } + this.#keyMap.delete(k); + this.#keyList[index] = undefined; + this.#valList[index] = undefined; + if (index === this.#tail) { + this.#tail = this.#prev[index]; + } + else if (index === this.#head) { + this.#head = this.#next[index]; + } + else { + const pi = this.#prev[index]; + this.#next[pi] = this.#next[index]; + const ni = this.#next[index]; + this.#prev[ni] = this.#prev[index]; + } + this.#size--; + this.#free.push(index); + } + } + } + if (this.#hasDisposeAfter && this.#disposed?.length) { + const dt = this.#disposed; + let task; + while ((task = dt?.shift())) { + this.#disposeAfter?.(...task); + } + } + return deleted; + } + /** + * Clear the cache entirely, throwing away all values. + */ + clear() { + return this.#clear('delete'); + } + #clear(reason) { + for (const index of this.#rindexes({ allowStale: true })) { + const v = this.#valList[index]; + if (this.#isBackgroundFetch(v)) { + v.__abortController.abort(new Error('deleted')); + } + else { + const k = this.#keyList[index]; + if (this.#hasDispose) { + this.#dispose?.(v, k, reason); + } + if (this.#hasDisposeAfter) { + this.#disposed?.push([v, k, reason]); + } + } + } + this.#keyMap.clear(); + this.#valList.fill(undefined); + this.#keyList.fill(undefined); + if (this.#ttls && this.#starts) { + this.#ttls.fill(0); + this.#starts.fill(0); + } + if (this.#sizes) { + this.#sizes.fill(0); + } + this.#head = 0; + this.#tail = 0; + this.#free.length = 0; + this.#calculatedSize = 0; + this.#size = 0; + if (this.#hasDisposeAfter && this.#disposed) { + const dt = this.#disposed; + let task; + while ((task = dt?.shift())) { + this.#disposeAfter?.(...task); + } + } + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/lru-cache/dist/esm/index.js.map b/node_modules/lru-cache/dist/esm/index.js.map new file mode 100644 index 0000000..8f7ac53 --- /dev/null +++ b/node_modules/lru-cache/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,MAAM,IAAI,GACR,OAAO,WAAW,KAAK,QAAQ;IAC/B,WAAW;IACX,OAAO,WAAW,CAAC,GAAG,KAAK,UAAU;IACnC,CAAC,CAAC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,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;SACrB;QACD,IAAI,IAAI,CAAC,MAAM,EAAE;YACf,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;SACpB;QACD,IAAI,CAAC,KAAK,GAAG,CAAU,CAAA;QACvB,IAAI,CAAC,KAAK,GAAG,CAAU,CAAA;QACvB,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAA;QACrB,IAAI,CAAC,eAAe,GAAG,CAAC,CAAA;QACxB,IAAI,CAAC,KAAK,GAAG,CAAC,CAAA;QACd,IAAI,IAAI,CAAC,gBAAgB,IAAI,IAAI,CAAC,SAAS,EAAE;YAC3C,MAAM,EAAE,GAAG,IAAI,CAAC,SAAS,CAAA;YACzB,IAAI,IAAmC,CAAA;YACvC,OAAO,CAAC,IAAI,GAAG,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE;gBAC3B,IAAI,CAAC,aAAa,EAAE,CAAC,GAAG,IAAI,CAAC,CAAA;aAC9B;SACF;IACH,CAAC;CACF","sourcesContent":["/**\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 * - `evict`: The item was evicted because it is the least recently used,\n * and the cache is full.\n * - `set`: A new value was set, overwriting the old value being disposed.\n * - `delete`: The item was explicitly deleted, either by calling\n * {@link LRUCache#delete}, {@link LRUCache#clear}, or\n * {@link LRUCache#set} with an undefined value.\n * - `expire`: The item was removed due to exceeding its TTL.\n * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned\n * `undefined` or was aborted, causing the item to be deleted.\n */\n export type DisposeReason =\n | 'evict'\n | 'set'\n | 'delete'\n | 'expire'\n | 'fetch'\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 * Occasionally, it may be useful to track the internal behavior of the\n * cache, particularly for logging, debugging, or for behavior within the\n * `fetchMethod`. To do this, you can pass a `status` object to the\n * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set},\n * {@link LRUCache#memo}, and {@link LRUCache#has} methods.\n *\n * The `status` option should be a plain JavaScript object. The following\n * fields will be set on it appropriately, depending on the situation.\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 {@link OptionsBase.fetchMethod}, so\n * {@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 export interface MemoOptions\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 /**\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.memoMethod} as\n * the {@link MemoizerOptions.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 status?: Status\n }\n /**\n * Options provided to {@link LRUCache#memo} when the FC type is something\n * other than `unknown`, `undefined`, or `void`\n */\n export interface MemoOptionsWithContext\n extends MemoOptions {\n context: FC\n }\n /**\n * Options provided to {@link LRUCache#memo} when the FC type is\n * `undefined` or `void`\n */\n export interface MemoOptionsNoContext\n extends MemoOptions {\n context?: undefined\n }\n\n /**\n * Options provided to the\n * {@link OptionsBase.memoMethod} function.\n */\n export interface MemoizerOptions {\n options: MemoizerMemoOptions\n /**\n * Object provided in the {@link MemoOptions.context} option to\n * {@link LRUCache#memo}\n */\n context: FC\n }\n\n /**\n * options which override the options set in the LRUCache constructor\n * when calling {@link LRUCache#memo}.\n *\n * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n * {@link MemoOptions.forceRefresh}, and\n * {@link MemoerOptions.context}\n *\n * Any of these may be modified in the {@link OptionsBase.memoMethod}\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 memoMethod is called.\n */\n export interface MemoizerMemoOptions\n extends Pick<\n OptionsBase,\n | 'allowStale'\n | 'updateAgeOnGet'\n | 'noDeleteOnStaleGet'\n | 'sizeCalculation'\n | 'ttl'\n | 'noDisposeOnSet'\n | 'noUpdateTTL'\n > {\n status?: Status\n size?: Size\n start?: Milliseconds\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 * the type signature for the {@link OptionsBase.memoMethod} option.\n */\n export type Memoizer = (\n key: K,\n staleValue: V | undefined,\n options: MemoizerOptions\n ) => V\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 * All options are also available on the {@link LRUCache} instance, making\n * it safe to pass an LRUCache instance as the options argumemnt to\n * make another empty cache of the same type.\n *\n * Some options are marked as read-only, because changing them after\n * instantiation is not safe. Changing any of the other options will of\n * course only have an effect on subsequent method calls.\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 * **It is strongly recommended to set a `max` to prevent unbounded growth\n * of the cache.**\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 by\n * default, and MAY live in the cache, contributing to its LRU max, long\n * after they have expired, unless {@link OptionsBase.ttlAutopurge} is\n * set.\n *\n * If set to `0` (the default value), then that means \"do not track\n * TTL\", not \"expire immediately\".\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 * This is not primarily a TTL cache, and does not make strong TTL\n * guarantees. There is no pre-emptive pruning of expired items, but you\n * _may_ set a TTL on the cache, and it will treat expired items as missing\n * when they are fetched, and delete them.\n *\n * Optional, but must be a non-negative integer in ms if specified.\n *\n * This may be overridden by passing an options object to `cache.set()`.\n *\n * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n * positive integer if set.\n *\n * Even if ttl tracking is enabled, **it is strongly recommended to set a\n * `max` to prevent unbounded growth of the cache.**\n *\n * If ttl tracking is enabled, and `max` and `maxSize` are not set,\n * and `ttlAutopurge` is not set, then a warning will be emitted\n * cautioning about the potential for unbounded memory consumption.\n * (The TypeScript definitions will also discourage this.)\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 *\n * Note that this may *significantly* degrade performance, especially if\n * the cache is storing a large number of items. It is almost always best\n * to just leave the stale items in the cache, and let them fall out as new\n * 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 * Use with caution!\n */\n ttlAutopurge?: boolean\n\n /**\n * When using time-expiring entries with `ttl`, setting this to `true` will\n * make each item's age reset to 0 whenever it is retrieved from cache with\n * {@link LRUCache#get}, causing it to not expire. (It can still fall out\n * of cache based on recency of use, of course.)\n *\n * Has no effect if {@link OptionsBase.ttl} is not set.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n */\n updateAgeOnGet?: boolean\n\n /**\n * When using time-expiring entries with `ttl`, setting this to `true` will\n * make each item's age reset to 0 whenever its presence in the cache is\n * checked with {@link LRUCache#has}, causing it to not expire. (It can\n * still fall out of cache based on recency of use, of course.)\n *\n * Has no effect if {@link OptionsBase.ttl} is not set.\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 * By default, if you set `ttl`, stale items will only be deleted from the\n * cache when you `get(key)`. That is, it's not preemptively pruning items,\n * unless {@link OptionsBase.ttlAutopurge} is set.\n *\n * If you set `allowStale:true`, it'll return the stale value *as well as*\n * deleting it. If you don't set this, then it'll return `undefined` when\n * you try to get a stale entry.\n *\n * Note that when a stale entry is fetched, _even if it is returned due to\n * `allowStale` being set_, it is removed from the cache immediately. You\n * can suppress this behavior by setting\n * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in\n * the options provided to {@link LRUCache#get}.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n * The `cache.has()` method will always return `false` for stale items.\n *\n * Only relevant if a ttl is set.\n */\n allowStale?: boolean\n\n /**\n * Function that is called on items when they are dropped from the\n * cache, as `dispose(value, key, reason)`.\n *\n * This can be handy if you want to close file descriptors or do\n * other cleanup tasks when items are no longer stored in the cache.\n *\n * **NOTE**: It is called _before_ the item has been fully removed\n * from the cache, so if you want to put it right back in, you need\n * to wait until the next tick. If you try to add it back in during\n * the `dispose()` function call, it will break things in subtle and\n * weird ways.\n *\n * Unlike several other options, this may _not_ be overridden by\n * passing an option to `set()`, for performance reasons.\n *\n * The `reason` will be one of the following strings, corresponding\n * to the reason for the item's deletion:\n *\n * - `evict` Item was evicted to make space for a new addition\n * - `set` Item was overwritten by a new value\n * - `expire` Item expired its TTL\n * - `fetch` Item was deleted due to a failed or aborted fetch, or a\n * fetchMethod returning `undefined.\n * - `delete` Item was removed by explicit `cache.delete(key)`,\n * `cache.clear()`, or `cache.set(key, undefined)`.\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 *\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 *\n * This may be overridden by passing an options object to\n * {@link LRUCache#set}.\n *\n * Only relevant if `dispose` or `disposeAfter` are set.\n */\n noDisposeOnSet?: boolean\n\n /**\n * Boolean flag to tell the cache to not update the TTL when setting a new\n * value for an existing key (ie, when updating a value rather than\n * inserting a new value). Note that the TTL value is _always_ set (if\n * provided) when adding a new entry into the cache.\n *\n * Has no effect if a {@link OptionsBase.ttl} is not set.\n *\n * May be passed as an option to {@link LRUCache#set}.\n */\n noUpdateTTL?: boolean\n\n /**\n * Set to a positive integer to track the sizes of items added to the\n * cache, and automatically evict items in order to stay below this size.\n * Note that this may result in fewer than `max` items being stored.\n *\n * Attempting to add an item to the cache whose calculated size is greater\n * that this amount will be a no-op. The item will not be cached, and no\n * other items will be evicted.\n *\n * Optional, must be a positive integer if provided.\n *\n * Sets `maxEntrySize` to the same value, unless a different value is\n * provided for `maxEntrySize`.\n *\n * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n * positive integer if set.\n *\n * Even if size tracking is enabled, **it is strongly recommended to set a\n * `max` to prevent unbounded growth of the cache.**\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} or {@link OptionsBase.memoMethod}, then\n * it will not be stored in the cache.\n *\n * Attempting to add an item whose calculated size is greater than\n * this amount will not cache the item or evict any old items, but\n * WILL delete an existing value if one is already present.\n *\n * Optional, must be a positive integer if provided. Defaults to\n * the value of `maxSize` if provided.\n */\n maxEntrySize?: Size\n\n /**\n * A function that returns a number indicating the item's size.\n *\n * Requires {@link OptionsBase.maxSize} to be set.\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 * ```ts\n * fetchMethod(key, staleValue, { signal, options, context })\n * ```\n *\n * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent\n * to `Promise.resolve(cache.get(key))`.\n *\n * If at any time, `signal.aborted` is set to `true`, or if the\n * `signal.onabort` method is called, or if it emits an `'abort'` event\n * which you can listen to with `addEventListener`, then that means that\n * the fetch should be abandoned. This may be passed along to async\n * functions aware of AbortController/AbortSignal behavior.\n *\n * The `fetchMethod` should **only** return `undefined` or a Promise\n * resolving to `undefined` if the AbortController signaled an `abort`\n * event. In all other cases, it should return or resolve to a value\n * suitable for adding to the cache.\n *\n * The `options` object is a union of the options that may be provided to\n * `set()` and `get()`. If they are modified, then that will result in\n * modifying the settings to `cache.set()` when the value is resolved, and\n * in the case of\n * {@link OptionsBase.noDeleteOnFetchRejection} and\n * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of\n * `fetchMethod` failures.\n *\n * For example, a DNS cache may update the TTL based on the value returned\n * from a remote DNS server by changing `options.ttl` in the `fetchMethod`.\n */\n fetchMethod?: Fetcher\n\n /**\n * Method that provides the implementation for {@link LRUCache#memo}\n */\n memoMethod?: Memoizer\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 * When using time-expiring entries with `ttl`, by default stale\n * items will be removed from the cache when the key is accessed\n * with `cache.get()`.\n *\n * Setting this option will cause stale items to remain in the cache, until\n * they are explicitly deleted with `cache.delete(key)`, or retrieved with\n * `noDeleteOnStaleGet` set to `false`.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n *\n * Only relevant if a ttl is used.\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 {@link LRUCache#fetch}\n * fails, not any other times.\n *\n * If a `fetchMethod` fails, and there is no stale value available, the\n * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are\n * suppressed.\n *\n * Implies `noDeleteOnFetchRejection`.\n *\n * This may be set in calls to `fetch()`, or defaulted on the constructor,\n * or overridden by modifying the options object in the `fetchMethod`.\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\n * an `'abort'` event, whether user-triggered, or due to internal cache\n * 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\n * are not immediately resolved or rejected when they are aborted, and\n * instead 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 * For example:\n *\n * ```ts\n * const c = new LRUCache({\n * ttl: 100,\n * ignoreFetchAbort: true,\n * allowStaleOnFetchAbort: true,\n * fetchMethod: async (key, oldValue, { signal }) => {\n * // note: do NOT pass the signal to fetch()!\n * // let's say this fetch can take a long time.\n * const res = await fetch(`https://slow-backend-server/${key}`)\n * return await res.json()\n * },\n * })\n *\n * // this will return the stale value after 100ms, while still\n * // updating in the background for next time.\n * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) })\n * ```\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 * The `K` and `V` types define the key and value types, respectively. The\n * optional `FC` type defines the type of the `context` object passed to\n * `cache.fetch()` and `cache.memo()`.\n *\n * Keys and values **must not** be `null` or `undefined`.\n *\n * All properties from the options object (with the exception of `max`,\n * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are\n * added as normal public members. (The listed options are read-only getters.)\n *\n * Changing any of these will alter the defaults for subsequent method calls.\n */\nexport class LRUCache\n implements Map\n{\n // options that cannot be changed without disaster\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 readonly #memoMethod?: LRUCache.Memoizer\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 get memoMethod(): LRUCache.Memoizer | undefined {\n return this.#memoMethod\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 memoMethod,\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 memoMethod !== undefined &&\n typeof memoMethod !== 'function'\n ) {\n throw new TypeError('memoMethod must be a function if defined')\n }\n this.#memoMethod = memoMethod\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 number of ms left in the item's TTL. If item is not in cache,\n * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.\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, 'expire')\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\n * description of an object. Called by the built-in method\n * `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 most\n * recently used to least recently used.\n *\n * `fn` is called as `fn(value, key, cache)`.\n *\n * If `thisp` is provided, function will be called in the `this`-context of\n * the provided object, or the cache if no `thisp` object is provided.\n *\n * Does not update age or recenty of use, or 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, 'expire')\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. Returns `undefined` if the key is not present.\n *\n * Unlike {@link LRUCache#dump}, which is designed to be portable and survive\n * serialization, the `start` value is always the current timestamp, and the\n * `ttl` is a calculated remaining time to live (negative if expired).\n *\n * Always returns stale values, if their info is found in the cache, so be\n * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})\n * 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 {@link LRLUCache#load}.\n *\n * The `start` fields are calculated relative to a portable `Date.now()`\n * timestamp, even if `performance.now()` is available.\n *\n * Stale entries are always included in the `dump`, even if\n * {@link LRUCache.OptionsBase.allowStale} is false.\n *\n * Note: this returns an actual array, not a generator, so it can be more\n * easily passed around.\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 *\n * The shape of the resulting cache may be different if the same options are\n * not used in both caches.\n *\n * The `start` fields are assumed to be calculated relative to a portable\n * `Date.now()` timestamp, even if `performance.now()` is available.\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 * Fields on the {@link LRUCache.SetOptions} options param will override\n * their corresponding values in the constructor options for the scope\n * of this single `set()` operation.\n *\n * If `start` is provided, then that will set the effective start\n * time for the TTL calculation. Note that this must be a previous\n * value of `performance.now()` if supported, or a previous value of\n * `Date.now()` if not.\n *\n * Options object may also include `size`, which will prevent\n * calling the `sizeCalculation` function and just use the specified\n * number if it is a positive integer, and `noDisposeOnSet` which\n * will prevent calling a `dispose` function in the case of\n * overwrites.\n *\n * If the `size` (or return value of `sizeCalculation`) for a given\n * entry is greater than `maxEntrySize`, then the item will not be\n * added to the cache.\n *\n * Will update the recency of the entry.\n *\n * If the value is `undefined`, then this is an alias for\n * `cache.delete(key)`. `undefined` is never stored in the cache.\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, 'set')\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 * Check if a key is in the cache, without updating the recency of\n * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set\n * to `true` in either the options or the constructor.\n *\n * Will return `false` if the item is stale, even though it is technically in\n * the cache. The difference can be determined (if it matters) by using a\n * `status` argument, and inspecting the `has` field.\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, 'fetch')\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, 'fetch')\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 the value is in the cache and not stale, then the returned\n * Promise resolves to the value.\n *\n * If not in the cache, or beyond its TTL staleness, then\n * `fetchMethod(key, staleValue, { options, signal, context })` is\n * called, and the value returned will be added to the cache once\n * resolved.\n *\n * If called with `allowStale`, and an asynchronous fetch is\n * currently in progress to reload a stale value, then the former\n * stale value will be returned.\n *\n * If called with `forceRefresh`, then the cached item will be\n * re-fetched, even if it is not stale. However, if `allowStale` is also\n * set, then the old value will still be returned. This is useful\n * in cases where you want to force a reload of a cached value. If\n * a background fetch is already in progress, then `forceRefresh`\n * has no effect.\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 * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is\n * effectively an alias for `Promise.resolve(cache.get(key))`.\n *\n * When the fetch method resolves to a value, if the fetch has not\n * been aborted due to deletion, eviction, or being overwritten,\n * then it is added to the cache using the options provided.\n *\n * If the key is evicted or deleted before the `fetchMethod`\n * resolves, then the AbortSignal passed to the `fetchMethod` will\n * receive an `abort` event, and the promise returned by `fetch()`\n * will reject with the reason for the abort.\n *\n * If a `signal` is passed to the `fetch()` call, then aborting the\n * signal will abort the fetch and cause the `fetch()` promise to\n * reject with the reason provided.\n *\n * **Setting `context`**\n *\n * If an `FC` type is set to a type other than `unknown`, `void`, or\n * `undefined` in the {@link LRUCache} constructor, then all\n * calls to `cache.fetch()` _must_ provide a `context` option. If\n * set to `undefined` or `void`, then calls to fetch _must not_\n * provide a `context` option.\n *\n * The `context` param allows you to provide arbitrary data that\n * might be relevant in the course of fetching the data. It is only\n * relevant for the course of a single `fetch()` operation, and\n * discarded afterwards.\n *\n * **Note: `fetch()` calls are inflight-unique**\n *\n * If you call `fetch()` multiple times with the same key value,\n * then every call after the first will resolve on the same\n * promise1,\n * _even if they have different settings that would otherwise change\n * the behavior of the fetch_, such as `noDeleteOnFetchRejection`\n * or `ignoreFetchAbort`.\n *\n * In most cases, this is not a problem (in fact, only fetching\n * something once is what you probably want, if you're caching in\n * the first place). If you are changing the fetch() options\n * dramatically between runs, there's a good chance that you might\n * be trying to fit divergent semantics into a single object, and\n * would be better off with multiple cache instances.\n *\n * **1**: Ie, they're not the \"same Promise\", but they resolve at\n * the same time, because they're both waiting on the same\n * underlying fetchMethod response.\n */\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\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\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 * In some cases, `cache.fetch()` may resolve to `undefined`, either because\n * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning\n * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or\n * because `ignoreFetchAbort` was specified (either to the constructor or\n * in the {@link LRUCache.FetchOptions}). Also, the\n * {@link OptionsBase.fetchMethod} may return `undefined` or `void`, making\n * the test even more complicated.\n *\n * Because inferring the cases where `undefined` might be returned are so\n * cumbersome, but testing for `undefined` can also be annoying, this method\n * can be used, which will reject if `this.fetch()` resolves to undefined.\n */\n forceFetch(\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 forceFetch(\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 forceFetch(\n k: K,\n fetchOptions: LRUCache.FetchOptions = {}\n ): Promise {\n const v = await this.fetch(\n k,\n fetchOptions as unknown extends FC\n ? LRUCache.FetchOptions\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext\n : LRUCache.FetchOptionsWithContext\n )\n if (v === undefined) throw new Error('fetch() returned undefined')\n return v\n }\n\n /**\n * If the key is found in the cache, then this is equivalent to\n * {@link LRUCache#get}. If not, in the cache, then calculate the value using\n * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache.\n *\n * If an `FC` type is set to a type other than `unknown`, `void`, or\n * `undefined` in the LRUCache constructor, then all calls to `cache.memo()`\n * _must_ provide a `context` option. If set to `undefined` or `void`, then\n * calls to memo _must not_ provide a `context` option.\n *\n * The `context` param allows you to provide arbitrary data that might be\n * relevant in the course of fetching the data. It is only relevant for the\n * course of a single `memo()` operation, and discarded afterwards.\n */\n memo(\n k: K,\n memoOptions: unknown extends FC\n ? LRUCache.MemoOptions\n : FC extends undefined | void\n ? LRUCache.MemoOptionsNoContext\n : LRUCache.MemoOptionsWithContext\n ): V\n // this overload not allowed if context is required\n memo(\n k: unknown extends FC\n ? K\n : FC extends undefined | void\n ? K\n : never,\n memoOptions?: unknown extends FC\n ? LRUCache.MemoOptions\n : FC extends undefined | void\n ? LRUCache.MemoOptionsNoContext\n : never\n ): V\n memo(k: K, memoOptions: LRUCache.MemoOptions = {}) {\n const memoMethod = this.#memoMethod\n if (!memoMethod) {\n throw new Error('no memoMethod provided to constructor')\n }\n const { context, forceRefresh, ...options } = memoOptions\n const v = this.get(k, options)\n if (!forceRefresh && v !== undefined) return v\n const vv = memoMethod(k, v, {\n options,\n context,\n } as LRUCache.MemoizerOptions)\n this.set(k, vv, options)\n return vv\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, 'expire')\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 *\n * Returns true if the key was deleted, false otherwise.\n */\n delete(k: K) {\n return this.#delete(k, 'delete')\n }\n\n #delete(k: K, reason: LRUCache.DisposeReason) {\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(reason)\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, reason)\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v as V, k, reason])\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 return this.#clear('delete')\n }\n #clear(reason: LRUCache.DisposeReason) {\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, reason)\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v as V, k as K, reason])\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"]} \ No newline at end of file diff --git a/node_modules/lru-cache/dist/esm/index.min.js b/node_modules/lru-cache/dist/esm/index.min.js new file mode 100644 index 0000000..4571d02 --- /dev/null +++ b/node_modules/lru-cache/dist/esm/index.min.js @@ -0,0 +1,2 @@ +var G=(l,t,e)=>{if(!t.has(l))throw TypeError("Cannot "+e)};var I=(l,t,e)=>(G(l,t,"read from private field"),e?e.call(l):t.get(l)),j=(l,t,e)=>{if(t.has(l))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(l):t.set(l,e)},x=(l,t,e,i)=>(G(l,t,"write to private field"),i?i.call(l,e):t.set(l,e),e);var T=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,P=new Set,M=typeof process=="object"&&process?process:{},H=(l,t,e,i)=>{typeof M.emitWarning=="function"?M.emitWarning(l,t,e,i):console.error(`[${e}] ${t}: ${l}`)},W=globalThis.AbortController,N=globalThis.AbortSignal;if(typeof W>"u"){N=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(i,s){this._onabort.push(s)}},W=class{constructor(){t()}signal=new N;abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=!0;for(let s of this.signal._onabort)s(i);this.signal.onabort?.(i)}}};let l=M.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{l&&(l=!1,H("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 V=l=>!P.has(l),Y=Symbol("type"),A=l=>l&&l===Math.floor(l)&&l>0&&isFinite(l),k=l=>A(l)?l<=Math.pow(2,8)?Uint8Array:l<=Math.pow(2,16)?Uint16Array:l<=Math.pow(2,32)?Uint32Array:l<=Number.MAX_SAFE_INTEGER?O:null:null,O=class extends Array{constructor(t){super(t),this.fill(0)}},z,E=class{heap;length;static create(t){let e=k(t);if(!e)return[];x(E,z,!0);let i=new E(t,e);return x(E,z,!1),i}constructor(t,e){if(!I(E,z))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]}},R=E;z=new WeakMap,j(R,z,!1);var D=class{#g;#f;#p;#w;#R;#W;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#n;#S;#s;#i;#t;#l;#c;#o;#h;#_;#r;#m;#b;#u;#y;#O;#a;static unsafeExposeInternals(t){return{starts:t.#b,ttls:t.#u,sizes:t.#m,keyMap:t.#s,keyList:t.#i,valList:t.#t,next:t.#l,prev:t.#c,get head(){return t.#o},get tail(){return t.#h},free:t.#_,isBackgroundFetch:e=>t.#e(e),backgroundFetch:(e,i,s,n)=>t.#x(e,i,s,n),moveToTail:e=>t.#C(e),indexes:e=>t.#A(e),rindexes:e=>t.#F(e),isStale:e=>t.#d(e)}}get max(){return this.#g}get maxSize(){return this.#f}get calculatedSize(){return this.#S}get size(){return this.#n}get fetchMethod(){return this.#R}get memoMethod(){return this.#W}get dispose(){return this.#p}get disposeAfter(){return this.#w}constructor(t){let{max:e=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:h,updateAgeOnHas:o,allowStale:r,dispose:g,disposeAfter:m,noDisposeOnSet:f,noUpdateTTL:u,maxSize:c=0,maxEntrySize:F=0,sizeCalculation:d,fetchMethod:S,memoMethod:a,noDeleteOnFetchRejection:w,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:_,ignoreFetchAbort:v}=t;if(e!==0&&!A(e))throw new TypeError("max option must be a nonnegative integer");let y=e?k(e):Array;if(!y)throw new Error("invalid max value: "+e);if(this.#g=e,this.#f=c,this.maxEntrySize=F||this.#f,this.sizeCalculation=d,this.sizeCalculation){if(!this.#f&&!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(a!==void 0&&typeof a!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#W=a,S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#R=S,this.#O=!!S,this.#s=new Map,this.#i=new Array(e).fill(void 0),this.#t=new Array(e).fill(void 0),this.#l=new y(e),this.#c=new y(e),this.#o=0,this.#h=0,this.#_=R.create(e),this.#n=0,this.#S=0,typeof g=="function"&&(this.#p=g),typeof m=="function"?(this.#w=m,this.#r=[]):(this.#w=void 0,this.#r=void 0),this.#y=!!this.#p,this.#a=!!this.#w,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!w,this.allowStaleOnFetchRejection=!!p,this.allowStaleOnFetchAbort=!!_,this.ignoreFetchAbort=!!v,this.maxEntrySize!==0){if(this.#f!==0&&!A(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!A(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#P()}if(this.allowStale=!!r,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!h,this.updateAgeOnHas=!!o,this.ttlResolution=A(s)||s===0?s:1,this.ttlAutopurge=!!n,this.ttl=i||0,this.ttl){if(!A(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#M()}if(this.#g===0&&this.ttl===0&&this.#f===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#g&&!this.#f){let C="LRU_CACHE_UNBOUNDED";V(C)&&(P.add(C),H("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",C,D))}}getRemainingTTL(t){return this.#s.has(t)?1/0:0}#M(){let t=new O(this.#g),e=new O(this.#g);this.#u=t,this.#b=e,this.#U=(n,h,o=T.now())=>{if(e[n]=h!==0?o:0,t[n]=h,h!==0&&this.ttlAutopurge){let r=setTimeout(()=>{this.#d(n)&&this.#T(this.#i[n],"expire")},h+1);r.unref&&r.unref()}},this.#z=n=>{e[n]=t[n]!==0?T.now():0},this.#E=(n,h)=>{if(t[h]){let o=t[h],r=e[h];if(!o||!r)return;n.ttl=o,n.start=r,n.now=i||s();let g=n.now-r;n.remainingTTL=o-g}};let i=0,s=()=>{let n=T.now();if(this.ttlResolution>0){i=n;let h=setTimeout(()=>i=0,this.ttlResolution);h.unref&&h.unref()}return n};this.getRemainingTTL=n=>{let h=this.#s.get(n);if(h===void 0)return 0;let o=t[h],r=e[h];if(!o||!r)return 1/0;let g=(i||s())-r;return o-g},this.#d=n=>{let h=e[n],o=t[n];return!!o&&!!h&&(i||s())-h>o}}#z=()=>{};#E=()=>{};#U=()=>{};#d=()=>!1;#P(){let t=new O(this.#g);this.#S=0,this.#m=t,this.#v=e=>{this.#S-=t[e],t[e]=0},this.#G=(e,i,s,n)=>{if(this.#e(i))return 0;if(!A(s))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(s=n(i,e),!A(s))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 s},this.#D=(e,i,s)=>{if(t[e]=i,this.#f){let n=this.#f-t[e];for(;this.#S>n;)this.#L(!0)}this.#S+=t[e],s&&(s.entrySize=i,s.totalCalculatedSize=this.#S)}}#v=t=>{};#D=(t,e,i)=>{};#G=(t,e,i,s)=>{if(i||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#h;!(!this.#I(e)||((t||!this.#d(e))&&(yield e),e===this.#o));)e=this.#c[e]}*#F({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#o;!(!this.#I(e)||((t||!this.#d(e))&&(yield e),e===this.#h));)e=this.#l[e]}#I(t){return t!==void 0&&this.#s.get(this.#i[t])===t}*entries(){for(let t of this.#A())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*rentries(){for(let t of this.#F())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*keys(){for(let t of this.#A()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*rkeys(){for(let t of this.#F()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*values(){for(let t of this.#A())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}*rvalues(){for(let t of this.#F())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;if(n!==void 0&&t(n,this.#i[i],this))return this.get(this.#i[i],e)}}forEach(t,e=this){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(e,n,this.#i[i],this)}}rforEach(t,e=this){for(let i of this.#F()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(e,n,this.#i[i],this)}}purgeStale(){let t=!1;for(let e of this.#F({allowStale:!0}))this.#d(e)&&(this.#T(this.#i[e],"expire"),t=!0);return t}info(t){let e=this.#s.get(t);if(e===void 0)return;let i=this.#t[e],s=this.#e(i)?i.__staleWhileFetching:i;if(s===void 0)return;let n={value:s};if(this.#u&&this.#b){let h=this.#u[e],o=this.#b[e];if(h&&o){let r=h-(T.now()-o);n.ttl=r,n.start=Date.now()}}return this.#m&&(n.size=this.#m[e]),n}dump(){let t=[];for(let e of this.#A({allowStale:!0})){let i=this.#i[e],s=this.#t[e],n=this.#e(s)?s.__staleWhileFetching:s;if(n===void 0||i===void 0)continue;let h={value:n};if(this.#u&&this.#b){h.ttl=this.#u[e];let o=T.now()-this.#b[e];h.start=Math.floor(Date.now()-o)}this.#m&&(h.size=this.#m[e]),t.unshift([i,h])}return t}load(t){this.clear();for(let[e,i]of t){if(i.start){let s=Date.now()-i.start;i.start=T.now()-s}this.set(e,i.value,i)}}set(t,e,i={}){if(e===void 0)return this.delete(t),this;let{ttl:s=this.ttl,start:n,noDisposeOnSet:h=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:r}=i,{noUpdateTTL:g=this.noUpdateTTL}=i,m=this.#G(t,e,i.size||0,o);if(this.maxEntrySize&&m>this.maxEntrySize)return r&&(r.set="miss",r.maxEntrySizeExceeded=!0),this.#T(t,"set"),this;let f=this.#n===0?void 0:this.#s.get(t);if(f===void 0)f=this.#n===0?this.#h:this.#_.length!==0?this.#_.pop():this.#n===this.#g?this.#L(!1):this.#n,this.#i[f]=t,this.#t[f]=e,this.#s.set(t,f),this.#l[this.#h]=f,this.#c[f]=this.#h,this.#h=f,this.#n++,this.#D(f,m,r),r&&(r.set="add"),g=!1;else{this.#C(f);let u=this.#t[f];if(e!==u){if(this.#O&&this.#e(u)){u.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:c}=u;c!==void 0&&!h&&(this.#y&&this.#p?.(c,t,"set"),this.#a&&this.#r?.push([c,t,"set"]))}else h||(this.#y&&this.#p?.(u,t,"set"),this.#a&&this.#r?.push([u,t,"set"]));if(this.#v(f),this.#D(f,m,r),this.#t[f]=e,r){r.set="replace";let c=u&&this.#e(u)?u.__staleWhileFetching:u;c!==void 0&&(r.oldValue=c)}}else r&&(r.set="update")}if(s!==0&&!this.#u&&this.#M(),this.#u&&(g||this.#U(f,s,n),r&&this.#E(r,f)),!h&&this.#a&&this.#r){let u=this.#r,c;for(;c=u?.shift();)this.#w?.(...c)}return this}pop(){try{for(;this.#n;){let t=this.#t[this.#o];if(this.#L(!0),this.#e(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#a&&this.#r){let t=this.#r,e;for(;e=t?.shift();)this.#w?.(...e)}}}#L(t){let e=this.#o,i=this.#i[e],s=this.#t[e];return this.#O&&this.#e(s)?s.__abortController.abort(new Error("evicted")):(this.#y||this.#a)&&(this.#y&&this.#p?.(s,i,"evict"),this.#a&&this.#r?.push([s,i,"evict"])),this.#v(e),t&&(this.#i[e]=void 0,this.#t[e]=void 0,this.#_.push(e)),this.#n===1?(this.#o=this.#h=0,this.#_.length=0):this.#o=this.#l[e],this.#s.delete(i),this.#n--,e}has(t,e={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=e,n=this.#s.get(t);if(n!==void 0){let h=this.#t[n];if(this.#e(h)&&h.__staleWhileFetching===void 0)return!1;if(this.#d(n))s&&(s.has="stale",this.#E(s,n));else return i&&this.#z(n),s&&(s.has="hit",this.#E(s,n)),!0}else s&&(s.has="miss");return!1}peek(t,e={}){let{allowStale:i=this.allowStale}=e,s=this.#s.get(t);if(s===void 0||!i&&this.#d(s))return;let n=this.#t[s];return this.#e(n)?n.__staleWhileFetching:n}#x(t,e,i,s){let n=e===void 0?void 0:this.#t[e];if(this.#e(n))return n;let h=new W,{signal:o}=i;o?.addEventListener("abort",()=>h.abort(o.reason),{signal:h.signal});let r={signal:h.signal,options:i,context:s},g=(d,S=!1)=>{let{aborted:a}=h.signal,w=i.ignoreFetchAbort&&d!==void 0;if(i.status&&(a&&!S?(i.status.fetchAborted=!0,i.status.fetchError=h.signal.reason,w&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),a&&!w&&!S)return f(h.signal.reason);let b=c;return this.#t[e]===c&&(d===void 0?b.__staleWhileFetching?this.#t[e]=b.__staleWhileFetching:this.#T(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.set(t,d,r.options))),d},m=d=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=d),f(d)),f=d=>{let{aborted:S}=h.signal,a=S&&i.allowStaleOnFetchAbort,w=a||i.allowStaleOnFetchRejection,b=w||i.noDeleteOnFetchRejection,p=c;if(this.#t[e]===c&&(!b||p.__staleWhileFetching===void 0?this.#T(t,"fetch"):a||(this.#t[e]=p.__staleWhileFetching)),w)return i.status&&p.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),p.__staleWhileFetching;if(p.__returned===p)throw d},u=(d,S)=>{let a=this.#R?.(t,n,r);a&&a instanceof Promise&&a.then(w=>d(w===void 0?void 0:w),S),h.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(d(void 0),i.allowStaleOnFetchAbort&&(d=w=>g(w,!0)))})};i.status&&(i.status.fetchDispatched=!0);let c=new Promise(u).then(g,m),F=Object.assign(c,{__abortController:h,__staleWhileFetching:n,__returned:void 0});return e===void 0?(this.set(t,F,{...r.options,status:void 0}),e=this.#s.get(t)):this.#t[e]=F,F}#e(t){if(!this.#O)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof W}async fetch(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:h=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:r=0,sizeCalculation:g=this.sizeCalculation,noUpdateTTL:m=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:u=this.allowStaleOnFetchRejection,ignoreFetchAbort:c=this.ignoreFetchAbort,allowStaleOnFetchAbort:F=this.allowStaleOnFetchAbort,context:d,forceRefresh:S=!1,status:a,signal:w}=e;if(!this.#O)return a&&(a.fetch="get"),this.get(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:a});let b={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:h,noDisposeOnSet:o,size:r,sizeCalculation:g,noUpdateTTL:m,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:F,ignoreFetchAbort:c,status:a,signal:w},p=this.#s.get(t);if(p===void 0){a&&(a.fetch="miss");let _=this.#x(t,p,b,d);return _.__returned=_}else{let _=this.#t[p];if(this.#e(_)){let U=i&&_.__staleWhileFetching!==void 0;return a&&(a.fetch="inflight",U&&(a.returnedStale=!0)),U?_.__staleWhileFetching:_.__returned=_}let v=this.#d(p);if(!S&&!v)return a&&(a.fetch="hit"),this.#C(p),s&&this.#z(p),a&&this.#E(a,p),_;let y=this.#x(t,p,b,d),L=y.__staleWhileFetching!==void 0&&i;return a&&(a.fetch=v?"stale":"refresh",L&&v&&(a.returnedStale=!0)),L?y.__staleWhileFetching:y.__returned=y}}async forceFetch(t,e={}){let i=await this.fetch(t,e);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(t,e={}){let i=this.#W;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,forceRefresh:n,...h}=e,o=this.get(t,h);if(!n&&o!==void 0)return o;let r=i(t,o,{options:h,context:s});return this.set(t,r,h),r}get(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:h}=e,o=this.#s.get(t);if(o!==void 0){let r=this.#t[o],g=this.#e(r);return h&&this.#E(h,o),this.#d(o)?(h&&(h.get="stale"),g?(h&&i&&r.__staleWhileFetching!==void 0&&(h.returnedStale=!0),i?r.__staleWhileFetching:void 0):(n||this.#T(t,"expire"),h&&i&&(h.returnedStale=!0),i?r:void 0)):(h&&(h.get="hit"),g?r.__staleWhileFetching:(this.#C(o),s&&this.#z(o),r))}else h&&(h.get="miss")}#j(t,e){this.#c[e]=t,this.#l[t]=e}#C(t){t!==this.#h&&(t===this.#o?this.#o=this.#l[t]:this.#j(this.#c[t],this.#l[t]),this.#j(this.#h,t),this.#h=t)}delete(t){return this.#T(t,"delete")}#T(t,e){let i=!1;if(this.#n!==0){let s=this.#s.get(t);if(s!==void 0)if(i=!0,this.#n===1)this.#N(e);else{this.#v(s);let n=this.#t[s];if(this.#e(n)?n.__abortController.abort(new Error("deleted")):(this.#y||this.#a)&&(this.#y&&this.#p?.(n,t,e),this.#a&&this.#r?.push([n,t,e])),this.#s.delete(t),this.#i[s]=void 0,this.#t[s]=void 0,s===this.#h)this.#h=this.#c[s];else if(s===this.#o)this.#o=this.#l[s];else{let h=this.#c[s];this.#l[h]=this.#l[s];let o=this.#l[s];this.#c[o]=this.#c[s]}this.#n--,this.#_.push(s)}}if(this.#a&&this.#r?.length){let s=this.#r,n;for(;n=s?.shift();)this.#w?.(...n)}return i}clear(){return this.#N("delete")}#N(t){for(let e of this.#F({allowStale:!0})){let i=this.#t[e];if(this.#e(i))i.__abortController.abort(new Error("deleted"));else{let s=this.#i[e];this.#y&&this.#p?.(i,s,t),this.#a&&this.#r?.push([i,s,t])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#u&&this.#b&&(this.#u.fill(0),this.#b.fill(0)),this.#m&&this.#m.fill(0),this.#o=0,this.#h=0,this.#_.length=0,this.#S=0,this.#n=0,this.#a&&this.#r){let e=this.#r,i;for(;i=e?.shift();)this.#w?.(...i)}}};export{D as LRUCache}; +//# sourceMappingURL=index.min.js.map diff --git a/node_modules/lru-cache/dist/esm/index.min.js.map b/node_modules/lru-cache/dist/esm/index.min.js.map new file mode 100644 index 0000000..117a9de --- /dev/null +++ b/node_modules/lru-cache/dist/esm/index.min.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../src/index.ts"], + "sourcesContent": ["/**\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 * - `evict`: The item was evicted because it is the least recently used,\n * and the cache is full.\n * - `set`: A new value was set, overwriting the old value being disposed.\n * - `delete`: The item was explicitly deleted, either by calling\n * {@link LRUCache#delete}, {@link LRUCache#clear}, or\n * {@link LRUCache#set} with an undefined value.\n * - `expire`: The item was removed due to exceeding its TTL.\n * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned\n * `undefined` or was aborted, causing the item to be deleted.\n */\n export type DisposeReason =\n | 'evict'\n | 'set'\n | 'delete'\n | 'expire'\n | 'fetch'\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 * Occasionally, it may be useful to track the internal behavior of the\n * cache, particularly for logging, debugging, or for behavior within the\n * `fetchMethod`. To do this, you can pass a `status` object to the\n * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set},\n * {@link LRUCache#memo}, and {@link LRUCache#has} methods.\n *\n * The `status` option should be a plain JavaScript object. The following\n * fields will be set on it appropriately, depending on the situation.\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 {@link OptionsBase.fetchMethod}, so\n * {@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 export interface MemoOptions\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 /**\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.memoMethod} as\n * the {@link MemoizerOptions.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 status?: Status\n }\n /**\n * Options provided to {@link LRUCache#memo} when the FC type is something\n * other than `unknown`, `undefined`, or `void`\n */\n export interface MemoOptionsWithContext\n extends MemoOptions {\n context: FC\n }\n /**\n * Options provided to {@link LRUCache#memo} when the FC type is\n * `undefined` or `void`\n */\n export interface MemoOptionsNoContext\n extends MemoOptions {\n context?: undefined\n }\n\n /**\n * Options provided to the\n * {@link OptionsBase.memoMethod} function.\n */\n export interface MemoizerOptions {\n options: MemoizerMemoOptions\n /**\n * Object provided in the {@link MemoOptions.context} option to\n * {@link LRUCache#memo}\n */\n context: FC\n }\n\n /**\n * options which override the options set in the LRUCache constructor\n * when calling {@link LRUCache#memo}.\n *\n * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n * {@link MemoOptions.forceRefresh}, and\n * {@link MemoerOptions.context}\n *\n * Any of these may be modified in the {@link OptionsBase.memoMethod}\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 memoMethod is called.\n */\n export interface MemoizerMemoOptions\n extends Pick<\n OptionsBase,\n | 'allowStale'\n | 'updateAgeOnGet'\n | 'noDeleteOnStaleGet'\n | 'sizeCalculation'\n | 'ttl'\n | 'noDisposeOnSet'\n | 'noUpdateTTL'\n > {\n status?: Status\n size?: Size\n start?: Milliseconds\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 * the type signature for the {@link OptionsBase.memoMethod} option.\n */\n export type Memoizer = (\n key: K,\n staleValue: V | undefined,\n options: MemoizerOptions\n ) => V\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 * All options are also available on the {@link LRUCache} instance, making\n * it safe to pass an LRUCache instance as the options argumemnt to\n * make another empty cache of the same type.\n *\n * Some options are marked as read-only, because changing them after\n * instantiation is not safe. Changing any of the other options will of\n * course only have an effect on subsequent method calls.\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 * **It is strongly recommended to set a `max` to prevent unbounded growth\n * of the cache.**\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 by\n * default, and MAY live in the cache, contributing to its LRU max, long\n * after they have expired, unless {@link OptionsBase.ttlAutopurge} is\n * set.\n *\n * If set to `0` (the default value), then that means \"do not track\n * TTL\", not \"expire immediately\".\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 * This is not primarily a TTL cache, and does not make strong TTL\n * guarantees. There is no pre-emptive pruning of expired items, but you\n * _may_ set a TTL on the cache, and it will treat expired items as missing\n * when they are fetched, and delete them.\n *\n * Optional, but must be a non-negative integer in ms if specified.\n *\n * This may be overridden by passing an options object to `cache.set()`.\n *\n * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n * positive integer if set.\n *\n * Even if ttl tracking is enabled, **it is strongly recommended to set a\n * `max` to prevent unbounded growth of the cache.**\n *\n * If ttl tracking is enabled, and `max` and `maxSize` are not set,\n * and `ttlAutopurge` is not set, then a warning will be emitted\n * cautioning about the potential for unbounded memory consumption.\n * (The TypeScript definitions will also discourage this.)\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 *\n * Note that this may *significantly* degrade performance, especially if\n * the cache is storing a large number of items. It is almost always best\n * to just leave the stale items in the cache, and let them fall out as new\n * 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 * Use with caution!\n */\n ttlAutopurge?: boolean\n\n /**\n * When using time-expiring entries with `ttl`, setting this to `true` will\n * make each item's age reset to 0 whenever it is retrieved from cache with\n * {@link LRUCache#get}, causing it to not expire. (It can still fall out\n * of cache based on recency of use, of course.)\n *\n * Has no effect if {@link OptionsBase.ttl} is not set.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n */\n updateAgeOnGet?: boolean\n\n /**\n * When using time-expiring entries with `ttl`, setting this to `true` will\n * make each item's age reset to 0 whenever its presence in the cache is\n * checked with {@link LRUCache#has}, causing it to not expire. (It can\n * still fall out of cache based on recency of use, of course.)\n *\n * Has no effect if {@link OptionsBase.ttl} is not set.\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 * By default, if you set `ttl`, stale items will only be deleted from the\n * cache when you `get(key)`. That is, it's not preemptively pruning items,\n * unless {@link OptionsBase.ttlAutopurge} is set.\n *\n * If you set `allowStale:true`, it'll return the stale value *as well as*\n * deleting it. If you don't set this, then it'll return `undefined` when\n * you try to get a stale entry.\n *\n * Note that when a stale entry is fetched, _even if it is returned due to\n * `allowStale` being set_, it is removed from the cache immediately. You\n * can suppress this behavior by setting\n * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in\n * the options provided to {@link LRUCache#get}.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n * The `cache.has()` method will always return `false` for stale items.\n *\n * Only relevant if a ttl is set.\n */\n allowStale?: boolean\n\n /**\n * Function that is called on items when they are dropped from the\n * cache, as `dispose(value, key, reason)`.\n *\n * This can be handy if you want to close file descriptors or do\n * other cleanup tasks when items are no longer stored in the cache.\n *\n * **NOTE**: It is called _before_ the item has been fully removed\n * from the cache, so if you want to put it right back in, you need\n * to wait until the next tick. If you try to add it back in during\n * the `dispose()` function call, it will break things in subtle and\n * weird ways.\n *\n * Unlike several other options, this may _not_ be overridden by\n * passing an option to `set()`, for performance reasons.\n *\n * The `reason` will be one of the following strings, corresponding\n * to the reason for the item's deletion:\n *\n * - `evict` Item was evicted to make space for a new addition\n * - `set` Item was overwritten by a new value\n * - `expire` Item expired its TTL\n * - `fetch` Item was deleted due to a failed or aborted fetch, or a\n * fetchMethod returning `undefined.\n * - `delete` Item was removed by explicit `cache.delete(key)`,\n * `cache.clear()`, or `cache.set(key, undefined)`.\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 *\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 *\n * This may be overridden by passing an options object to\n * {@link LRUCache#set}.\n *\n * Only relevant if `dispose` or `disposeAfter` are set.\n */\n noDisposeOnSet?: boolean\n\n /**\n * Boolean flag to tell the cache to not update the TTL when setting a new\n * value for an existing key (ie, when updating a value rather than\n * inserting a new value). Note that the TTL value is _always_ set (if\n * provided) when adding a new entry into the cache.\n *\n * Has no effect if a {@link OptionsBase.ttl} is not set.\n *\n * May be passed as an option to {@link LRUCache#set}.\n */\n noUpdateTTL?: boolean\n\n /**\n * Set to a positive integer to track the sizes of items added to the\n * cache, and automatically evict items in order to stay below this size.\n * Note that this may result in fewer than `max` items being stored.\n *\n * Attempting to add an item to the cache whose calculated size is greater\n * that this amount will be a no-op. The item will not be cached, and no\n * other items will be evicted.\n *\n * Optional, must be a positive integer if provided.\n *\n * Sets `maxEntrySize` to the same value, unless a different value is\n * provided for `maxEntrySize`.\n *\n * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n * positive integer if set.\n *\n * Even if size tracking is enabled, **it is strongly recommended to set a\n * `max` to prevent unbounded growth of the cache.**\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} or {@link OptionsBase.memoMethod}, then\n * it will not be stored in the cache.\n *\n * Attempting to add an item whose calculated size is greater than\n * this amount will not cache the item or evict any old items, but\n * WILL delete an existing value if one is already present.\n *\n * Optional, must be a positive integer if provided. Defaults to\n * the value of `maxSize` if provided.\n */\n maxEntrySize?: Size\n\n /**\n * A function that returns a number indicating the item's size.\n *\n * Requires {@link OptionsBase.maxSize} to be set.\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 * ```ts\n * fetchMethod(key, staleValue, { signal, options, context })\n * ```\n *\n * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent\n * to `Promise.resolve(cache.get(key))`.\n *\n * If at any time, `signal.aborted` is set to `true`, or if the\n * `signal.onabort` method is called, or if it emits an `'abort'` event\n * which you can listen to with `addEventListener`, then that means that\n * the fetch should be abandoned. This may be passed along to async\n * functions aware of AbortController/AbortSignal behavior.\n *\n * The `fetchMethod` should **only** return `undefined` or a Promise\n * resolving to `undefined` if the AbortController signaled an `abort`\n * event. In all other cases, it should return or resolve to a value\n * suitable for adding to the cache.\n *\n * The `options` object is a union of the options that may be provided to\n * `set()` and `get()`. If they are modified, then that will result in\n * modifying the settings to `cache.set()` when the value is resolved, and\n * in the case of\n * {@link OptionsBase.noDeleteOnFetchRejection} and\n * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of\n * `fetchMethod` failures.\n *\n * For example, a DNS cache may update the TTL based on the value returned\n * from a remote DNS server by changing `options.ttl` in the `fetchMethod`.\n */\n fetchMethod?: Fetcher\n\n /**\n * Method that provides the implementation for {@link LRUCache#memo}\n */\n memoMethod?: Memoizer\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 * When using time-expiring entries with `ttl`, by default stale\n * items will be removed from the cache when the key is accessed\n * with `cache.get()`.\n *\n * Setting this option will cause stale items to remain in the cache, until\n * they are explicitly deleted with `cache.delete(key)`, or retrieved with\n * `noDeleteOnStaleGet` set to `false`.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n *\n * Only relevant if a ttl is used.\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 {@link LRUCache#fetch}\n * fails, not any other times.\n *\n * If a `fetchMethod` fails, and there is no stale value available, the\n * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are\n * suppressed.\n *\n * Implies `noDeleteOnFetchRejection`.\n *\n * This may be set in calls to `fetch()`, or defaulted on the constructor,\n * or overridden by modifying the options object in the `fetchMethod`.\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\n * an `'abort'` event, whether user-triggered, or due to internal cache\n * 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\n * are not immediately resolved or rejected when they are aborted, and\n * instead 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 * For example:\n *\n * ```ts\n * const c = new LRUCache({\n * ttl: 100,\n * ignoreFetchAbort: true,\n * allowStaleOnFetchAbort: true,\n * fetchMethod: async (key, oldValue, { signal }) => {\n * // note: do NOT pass the signal to fetch()!\n * // let's say this fetch can take a long time.\n * const res = await fetch(`https://slow-backend-server/${key}`)\n * return await res.json()\n * },\n * })\n *\n * // this will return the stale value after 100ms, while still\n * // updating in the background for next time.\n * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) })\n * ```\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 * The `K` and `V` types define the key and value types, respectively. The\n * optional `FC` type defines the type of the `context` object passed to\n * `cache.fetch()` and `cache.memo()`.\n *\n * Keys and values **must not** be `null` or `undefined`.\n *\n * All properties from the options object (with the exception of `max`,\n * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are\n * added as normal public members. (The listed options are read-only getters.)\n *\n * Changing any of these will alter the defaults for subsequent method calls.\n */\nexport class LRUCache\n implements Map\n{\n // options that cannot be changed without disaster\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 readonly #memoMethod?: LRUCache.Memoizer\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 get memoMethod(): LRUCache.Memoizer | undefined {\n return this.#memoMethod\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 memoMethod,\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 memoMethod !== undefined &&\n typeof memoMethod !== 'function'\n ) {\n throw new TypeError('memoMethod must be a function if defined')\n }\n this.#memoMethod = memoMethod\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 number of ms left in the item's TTL. If item is not in cache,\n * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.\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, 'expire')\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\n * description of an object. Called by the built-in method\n * `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 most\n * recently used to least recently used.\n *\n * `fn` is called as `fn(value, key, cache)`.\n *\n * If `thisp` is provided, function will be called in the `this`-context of\n * the provided object, or the cache if no `thisp` object is provided.\n *\n * Does not update age or recenty of use, or 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, 'expire')\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. Returns `undefined` if the key is not present.\n *\n * Unlike {@link LRUCache#dump}, which is designed to be portable and survive\n * serialization, the `start` value is always the current timestamp, and the\n * `ttl` is a calculated remaining time to live (negative if expired).\n *\n * Always returns stale values, if their info is found in the cache, so be\n * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})\n * 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 {@link LRLUCache#load}.\n *\n * The `start` fields are calculated relative to a portable `Date.now()`\n * timestamp, even if `performance.now()` is available.\n *\n * Stale entries are always included in the `dump`, even if\n * {@link LRUCache.OptionsBase.allowStale} is false.\n *\n * Note: this returns an actual array, not a generator, so it can be more\n * easily passed around.\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 *\n * The shape of the resulting cache may be different if the same options are\n * not used in both caches.\n *\n * The `start` fields are assumed to be calculated relative to a portable\n * `Date.now()` timestamp, even if `performance.now()` is available.\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 * Fields on the {@link LRUCache.SetOptions} options param will override\n * their corresponding values in the constructor options for the scope\n * of this single `set()` operation.\n *\n * If `start` is provided, then that will set the effective start\n * time for the TTL calculation. Note that this must be a previous\n * value of `performance.now()` if supported, or a previous value of\n * `Date.now()` if not.\n *\n * Options object may also include `size`, which will prevent\n * calling the `sizeCalculation` function and just use the specified\n * number if it is a positive integer, and `noDisposeOnSet` which\n * will prevent calling a `dispose` function in the case of\n * overwrites.\n *\n * If the `size` (or return value of `sizeCalculation`) for a given\n * entry is greater than `maxEntrySize`, then the item will not be\n * added to the cache.\n *\n * Will update the recency of the entry.\n *\n * If the value is `undefined`, then this is an alias for\n * `cache.delete(key)`. `undefined` is never stored in the cache.\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, 'set')\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 * Check if a key is in the cache, without updating the recency of\n * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set\n * to `true` in either the options or the constructor.\n *\n * Will return `false` if the item is stale, even though it is technically in\n * the cache. The difference can be determined (if it matters) by using a\n * `status` argument, and inspecting the `has` field.\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, 'fetch')\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, 'fetch')\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 the value is in the cache and not stale, then the returned\n * Promise resolves to the value.\n *\n * If not in the cache, or beyond its TTL staleness, then\n * `fetchMethod(key, staleValue, { options, signal, context })` is\n * called, and the value returned will be added to the cache once\n * resolved.\n *\n * If called with `allowStale`, and an asynchronous fetch is\n * currently in progress to reload a stale value, then the former\n * stale value will be returned.\n *\n * If called with `forceRefresh`, then the cached item will be\n * re-fetched, even if it is not stale. However, if `allowStale` is also\n * set, then the old value will still be returned. This is useful\n * in cases where you want to force a reload of a cached value. If\n * a background fetch is already in progress, then `forceRefresh`\n * has no effect.\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 * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is\n * effectively an alias for `Promise.resolve(cache.get(key))`.\n *\n * When the fetch method resolves to a value, if the fetch has not\n * been aborted due to deletion, eviction, or being overwritten,\n * then it is added to the cache using the options provided.\n *\n * If the key is evicted or deleted before the `fetchMethod`\n * resolves, then the AbortSignal passed to the `fetchMethod` will\n * receive an `abort` event, and the promise returned by `fetch()`\n * will reject with the reason for the abort.\n *\n * If a `signal` is passed to the `fetch()` call, then aborting the\n * signal will abort the fetch and cause the `fetch()` promise to\n * reject with the reason provided.\n *\n * **Setting `context`**\n *\n * If an `FC` type is set to a type other than `unknown`, `void`, or\n * `undefined` in the {@link LRUCache} constructor, then all\n * calls to `cache.fetch()` _must_ provide a `context` option. If\n * set to `undefined` or `void`, then calls to fetch _must not_\n * provide a `context` option.\n *\n * The `context` param allows you to provide arbitrary data that\n * might be relevant in the course of fetching the data. It is only\n * relevant for the course of a single `fetch()` operation, and\n * discarded afterwards.\n *\n * **Note: `fetch()` calls are inflight-unique**\n *\n * If you call `fetch()` multiple times with the same key value,\n * then every call after the first will resolve on the same\n * promise1,\n * _even if they have different settings that would otherwise change\n * the behavior of the fetch_, such as `noDeleteOnFetchRejection`\n * or `ignoreFetchAbort`.\n *\n * In most cases, this is not a problem (in fact, only fetching\n * something once is what you probably want, if you're caching in\n * the first place). If you are changing the fetch() options\n * dramatically between runs, there's a good chance that you might\n * be trying to fit divergent semantics into a single object, and\n * would be better off with multiple cache instances.\n *\n * **1**: Ie, they're not the \"same Promise\", but they resolve at\n * the same time, because they're both waiting on the same\n * underlying fetchMethod response.\n */\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\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\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 * In some cases, `cache.fetch()` may resolve to `undefined`, either because\n * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning\n * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or\n * because `ignoreFetchAbort` was specified (either to the constructor or\n * in the {@link LRUCache.FetchOptions}). Also, the\n * {@link OptionsBase.fetchMethod} may return `undefined` or `void`, making\n * the test even more complicated.\n *\n * Because inferring the cases where `undefined` might be returned are so\n * cumbersome, but testing for `undefined` can also be annoying, this method\n * can be used, which will reject if `this.fetch()` resolves to undefined.\n */\n forceFetch(\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 forceFetch(\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 forceFetch(\n k: K,\n fetchOptions: LRUCache.FetchOptions = {}\n ): Promise {\n const v = await this.fetch(\n k,\n fetchOptions as unknown extends FC\n ? LRUCache.FetchOptions\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext\n : LRUCache.FetchOptionsWithContext\n )\n if (v === undefined) throw new Error('fetch() returned undefined')\n return v\n }\n\n /**\n * If the key is found in the cache, then this is equivalent to\n * {@link LRUCache#get}. If not, in the cache, then calculate the value using\n * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache.\n *\n * If an `FC` type is set to a type other than `unknown`, `void`, or\n * `undefined` in the LRUCache constructor, then all calls to `cache.memo()`\n * _must_ provide a `context` option. If set to `undefined` or `void`, then\n * calls to memo _must not_ provide a `context` option.\n *\n * The `context` param allows you to provide arbitrary data that might be\n * relevant in the course of fetching the data. It is only relevant for the\n * course of a single `memo()` operation, and discarded afterwards.\n */\n memo(\n k: K,\n memoOptions: unknown extends FC\n ? LRUCache.MemoOptions\n : FC extends undefined | void\n ? LRUCache.MemoOptionsNoContext\n : LRUCache.MemoOptionsWithContext\n ): V\n // this overload not allowed if context is required\n memo(\n k: unknown extends FC\n ? K\n : FC extends undefined | void\n ? K\n : never,\n memoOptions?: unknown extends FC\n ? LRUCache.MemoOptions\n : FC extends undefined | void\n ? LRUCache.MemoOptionsNoContext\n : never\n ): V\n memo(k: K, memoOptions: LRUCache.MemoOptions = {}) {\n const memoMethod = this.#memoMethod\n if (!memoMethod) {\n throw new Error('no memoMethod provided to constructor')\n }\n const { context, forceRefresh, ...options } = memoOptions\n const v = this.get(k, options)\n if (!forceRefresh && v !== undefined) return v\n const vv = memoMethod(k, v, {\n options,\n context,\n } as LRUCache.MemoizerOptions)\n this.set(k, vv, options)\n return vv\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, 'expire')\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 *\n * Returns true if the key was deleted, false otherwise.\n */\n delete(k: K) {\n return this.#delete(k, 'delete')\n }\n\n #delete(k: K, reason: LRUCache.DisposeReason) {\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(reason)\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, reason)\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v as V, k, reason])\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 return this.#clear('delete')\n }\n #clear(reason: LRUCache.DisposeReason) {\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, reason)\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v as V, k as K, reason])\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"], + "mappings": "mVAMA,IAAMA,EACJ,OAAO,aAAgB,UACvB,aACA,OAAO,YAAY,KAAQ,WACvB,YACA,KAEAC,EAAS,IAAI,IAMbC,EACJ,OAAO,SAAY,UAAc,QAAU,QAAU,CAAA,EAIjDC,EAAc,CAClBC,EACAC,EACAC,EACAC,IACE,CACF,OAAOL,EAAQ,aAAgB,WAC3BA,EAAQ,YAAYE,EAAKC,EAAMC,EAAMC,CAAE,EACvC,QAAQ,MAAM,IAAID,MAASD,MAASD,GAAK,CAC/C,EAEII,EAAK,WAAW,gBAChBC,EAAK,WAAW,YAGpB,GAAI,OAAOD,EAAO,IAAa,CAE7BC,EAAK,KAAiB,CACpB,QACA,SAAqC,CAAA,EACrC,OACA,QAAmB,GACnB,iBAAiBC,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K,EACzB,KAAKP,IACP,KAAKlB,KAAWwE,EAAQhD,EAAQ7C,CAAM,EAEpC,KAAKyC,IACP,KAAKN,IAAW,KAAK,CAAC0D,EAAQhD,EAAQ7C,CAAM,CAAC,GAoBnD,GAfA,KAAK2B,GAAQ,MAAK,EAClB,KAAKE,GAAS,KAAK,MAAS,EAC5B,KAAKD,GAAS,KAAK,MAAS,EACxB,KAAKU,IAAS,KAAKD,KACrB,KAAKC,GAAM,KAAK,CAAC,EACjB,KAAKD,GAAQ,KAAK,CAAC,GAEjB,KAAKD,IACP,KAAKA,GAAO,KAAK,CAAC,EAEpB,KAAKJ,GAAQ,EACb,KAAKC,GAAQ,EACb,KAAKC,GAAM,OAAS,EACpB,KAAKR,GAAkB,EACvB,KAAKD,GAAQ,EACT,KAAKgB,IAAoB,KAAKN,GAAW,CAC3C,IAAM8E,EAAK,KAAK9E,GACZ+E,EACJ,KAAQA,EAAOD,GAAI,MAAK,GACtB,KAAK3F,KAAgB,GAAG4F,CAAI,EAGlC", + "names": ["perf", "warned", "PROCESS", "emitWarning", "msg", "type", "code", "fn", "AC", "AS", "_", "warnACPolyfill", "reason", "printACPolyfillWarning", "shouldWarn", "TYPE", "isPosInt", "n", "getUintArray", "max", "ZeroArray", "size", "_constructing", "_Stack", "HeapCls", "__privateSet", "s", "__privateGet", "Stack", "__privateAdd", "LRUCache", "#max", "#maxSize", "#dispose", "#disposeAfter", "#fetchMethod", "#memoMethod", "#size", "#calculatedSize", "#keyMap", "#keyList", "#valList", "#next", "#prev", "#head", "#tail", "#free", "#disposed", "#sizes", "#starts", "#ttls", "#hasDispose", "#hasFetchMethod", "#hasDisposeAfter", "c", "p", "#isBackgroundFetch", "k", "index", "options", "context", "#backgroundFetch", "#moveToTail", "#indexes", "#rindexes", "#isStale", "ttl", "ttlResolution", "ttlAutopurge", "updateAgeOnGet", "updateAgeOnHas", "allowStale", "dispose", "disposeAfter", "noDisposeOnSet", "noUpdateTTL", "maxSize", "maxEntrySize", "sizeCalculation", "fetchMethod", "memoMethod", "noDeleteOnFetchRejection", "noDeleteOnStaleGet", "allowStaleOnFetchRejection", "allowStaleOnFetchAbort", "ignoreFetchAbort", "UintArray", "#initializeSizeTracking", "#initializeTTLTracking", "key", "ttls", "starts", "#setItemTTL", "start", "t", "#delete", "#updateItemAge", "#statusTTL", "status", "cachedNow", "getNow", "age", "sizes", "#removeItemSize", "#requireSize", "v", "#addItemSize", "#evict", "_i", "_s", "_st", "_k", "_v", "i", "#isValidIndex", "getOptions", "value", "thisp", "deleted", "entry", "remain", "arr", "setOptions", "oldVal", "oldValue", "dt", "task", "val", "free", "head", "hasOptions", "peekOptions", "ac", "signal", "fetchOpts", "cb", "updateCache", "aborted", "ignoreAbort", "fetchFail", "bf", "eb", "er", "allowStaleAborted", "noDelete", "pcall", "res", "rej", "fmp", "b", "fetchOptions", "forceRefresh", "stale", "isStale", "staleVal", "memoOptions", "vv", "fetching", "#connect", "#clear", "pi", "ni"] +} diff --git a/node_modules/lru-cache/dist/esm/package.json b/node_modules/lru-cache/dist/esm/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/node_modules/lru-cache/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/lru-cache/package.json b/node_modules/lru-cache/package.json new file mode 100644 index 0000000..f3cd4c0 --- /dev/null +++ b/node_modules/lru-cache/package.json @@ -0,0 +1,116 @@ +{ + "name": "lru-cache", + "publishConfig": { + "tag": "legacy-v10" + }, + "description": "A cache object that deletes the least-recently-used items.", + "version": "10.4.3", + "author": "Isaac Z. Schlueter ", + "keywords": [ + "mru", + "lru", + "cache" + ], + "sideEffects": false, + "scripts": { + "build": "npm run prepare", + "prepare": "tshy && bash fixup.sh", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "format": "prettier --write .", + "typedoc": "typedoc --tsconfig ./.tshy/esm.json ./src/*.ts", + "benchmark-results-typedoc": "bash scripts/benchmark-results-typedoc.sh", + "prebenchmark": "npm run prepare", + "benchmark": "make -C benchmark", + "preprofile": "npm run prepare", + "profile": "make -C benchmark profile" + }, + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "tshy": { + "exports": { + ".": "./src/index.ts", + "./min": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.min.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.min.js" + } + } + } + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-lru-cache.git" + }, + "devDependencies": { + "@types/node": "^20.2.5", + "@types/tap": "^15.0.6", + "benchmark": "^2.1.4", + "esbuild": "^0.17.11", + "eslint-config-prettier": "^8.5.0", + "marked": "^4.2.12", + "mkdirp": "^2.1.5", + "prettier": "^2.6.2", + "tap": "^20.0.3", + "tshy": "^2.0.0", + "tslib": "^2.4.0", + "typedoc": "^0.25.3", + "typescript": "^5.2.2" + }, + "license": "ISC", + "files": [ + "dist" + ], + "prettier": { + "semi": false, + "printWidth": 70, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "tap": { + "node-arg": [ + "--expose-gc" + ], + "plugin": [ + "@tapjs/clock" + ] + }, + "exports": { + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + }, + "./min": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.min.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.min.js" + } + } + }, + "type": "module", + "module": "./dist/esm/index.js" +} diff --git a/node_modules/merge2/LICENSE b/node_modules/merge2/LICENSE new file mode 100644 index 0000000..31dd9c7 --- /dev/null +++ b/node_modules/merge2/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2020 Teambition + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/merge2/README.md b/node_modules/merge2/README.md new file mode 100644 index 0000000..27f8eb9 --- /dev/null +++ b/node_modules/merge2/README.md @@ -0,0 +1,144 @@ +# merge2 + +Merge multiple streams into one stream in sequence or parallel. + +[![NPM version][npm-image]][npm-url] +[![Build Status][travis-image]][travis-url] +[![Downloads][downloads-image]][downloads-url] + +## Install + +Install with [npm](https://npmjs.org/package/merge2) + +```sh +npm install merge2 +``` + +## Usage + +```js +const gulp = require('gulp') +const merge2 = require('merge2') +const concat = require('gulp-concat') +const minifyHtml = require('gulp-minify-html') +const ngtemplate = require('gulp-ngtemplate') + +gulp.task('app-js', function () { + return merge2( + gulp.src('static/src/tpl/*.html') + .pipe(minifyHtml({empty: true})) + .pipe(ngtemplate({ + module: 'genTemplates', + standalone: true + }) + ), gulp.src([ + 'static/src/js/app.js', + 'static/src/js/locale_zh-cn.js', + 'static/src/js/router.js', + 'static/src/js/tools.js', + 'static/src/js/services.js', + 'static/src/js/filters.js', + 'static/src/js/directives.js', + 'static/src/js/controllers.js' + ]) + ) + .pipe(concat('app.js')) + .pipe(gulp.dest('static/dist/js/')) +}) +``` + +```js +const stream = merge2([stream1, stream2], stream3, {end: false}) +//... +stream.add(stream4, stream5) +//.. +stream.end() +``` + +```js +// equal to merge2([stream1, stream2], stream3) +const stream = merge2() +stream.add([stream1, stream2]) +stream.add(stream3) +``` + +```js +// merge order: +// 1. merge `stream1`; +// 2. merge `stream2` and `stream3` in parallel after `stream1` merged; +// 3. merge 'stream4' after `stream2` and `stream3` merged; +const stream = merge2(stream1, [stream2, stream3], stream4) + +// merge order: +// 1. merge `stream5` and `stream6` in parallel after `stream4` merged; +// 2. merge 'stream7' after `stream5` and `stream6` merged; +stream.add([stream5, stream6], stream7) +``` + +```js +// nest merge +// equal to merge2(stream1, stream2, stream6, stream3, [stream4, stream5]); +const streamA = merge2(stream1, stream2) +const streamB = merge2(stream3, [stream4, stream5]) +const stream = merge2(streamA, streamB) +streamA.add(stream6) +``` + +## API + +```js +const merge2 = require('merge2') +``` + +### merge2() + +### merge2(options) + +### merge2(stream1, stream2, ..., streamN) + +### merge2(stream1, stream2, ..., streamN, options) + +### merge2(stream1, [stream2, stream3, ...], streamN, options) + +return a duplex stream (mergedStream). streams in array will be merged in parallel. + +### mergedStream.add(stream) + +### mergedStream.add(stream1, [stream2, stream3, ...], ...) + +return the mergedStream. + +### mergedStream.on('queueDrain', function() {}) + +It will emit 'queueDrain' when all streams merged. If you set `end === false` in options, this event give you a notice that should add more streams to merge or end the mergedStream. + +#### stream + +*option* +Type: `Readable` or `Duplex` or `Transform` stream. + +#### options + +*option* +Type: `Object`. + +* **end** - `Boolean` - if `end === false` then mergedStream will not be auto ended, you should end by yourself. **Default:** `undefined` + +* **pipeError** - `Boolean` - if `pipeError === true` then mergedStream will emit `error` event from source streams. **Default:** `undefined` + +* **objectMode** - `Boolean` . **Default:** `true` + +`objectMode` and other options(`highWaterMark`, `defaultEncoding` ...) is same as Node.js `Stream`. + +## License + +MIT © [Teambition](https://www.teambition.com) + +[npm-url]: https://npmjs.org/package/merge2 +[npm-image]: http://img.shields.io/npm/v/merge2.svg + +[travis-url]: https://travis-ci.org/teambition/merge2 +[travis-image]: http://img.shields.io/travis/teambition/merge2.svg + +[downloads-url]: https://npmjs.org/package/merge2 +[downloads-image]: http://img.shields.io/npm/dm/merge2.svg?style=flat-square diff --git a/node_modules/merge2/index.js b/node_modules/merge2/index.js new file mode 100644 index 0000000..78a61ed --- /dev/null +++ b/node_modules/merge2/index.js @@ -0,0 +1,144 @@ +'use strict' +/* + * merge2 + * https://github.com/teambition/merge2 + * + * Copyright (c) 2014-2020 Teambition + * Licensed under the MIT license. + */ +const Stream = require('stream') +const PassThrough = Stream.PassThrough +const slice = Array.prototype.slice + +module.exports = merge2 + +function merge2 () { + const streamsQueue = [] + const args = slice.call(arguments) + let merging = false + let options = args[args.length - 1] + + if (options && !Array.isArray(options) && options.pipe == null) { + args.pop() + } else { + options = {} + } + + const doEnd = options.end !== false + const doPipeError = options.pipeError === true + if (options.objectMode == null) { + options.objectMode = true + } + if (options.highWaterMark == null) { + options.highWaterMark = 64 * 1024 + } + const mergedStream = PassThrough(options) + + function addStream () { + for (let i = 0, len = arguments.length; i < len; i++) { + streamsQueue.push(pauseStreams(arguments[i], options)) + } + mergeStream() + return this + } + + function mergeStream () { + if (merging) { + return + } + merging = true + + let streams = streamsQueue.shift() + if (!streams) { + process.nextTick(endStream) + return + } + if (!Array.isArray(streams)) { + streams = [streams] + } + + let pipesCount = streams.length + 1 + + function next () { + if (--pipesCount > 0) { + return + } + merging = false + mergeStream() + } + + function pipe (stream) { + function onend () { + stream.removeListener('merge2UnpipeEnd', onend) + stream.removeListener('end', onend) + if (doPipeError) { + stream.removeListener('error', onerror) + } + next() + } + function onerror (err) { + mergedStream.emit('error', err) + } + // skip ended stream + if (stream._readableState.endEmitted) { + return next() + } + + stream.on('merge2UnpipeEnd', onend) + stream.on('end', onend) + + if (doPipeError) { + stream.on('error', onerror) + } + + stream.pipe(mergedStream, { end: false }) + // compatible for old stream + stream.resume() + } + + for (let i = 0; i < streams.length; i++) { + pipe(streams[i]) + } + + next() + } + + function endStream () { + merging = false + // emit 'queueDrain' when all streams merged. + mergedStream.emit('queueDrain') + if (doEnd) { + mergedStream.end() + } + } + + mergedStream.setMaxListeners(0) + mergedStream.add = addStream + mergedStream.on('unpipe', function (stream) { + stream.emit('merge2UnpipeEnd') + }) + + if (args.length) { + addStream.apply(null, args) + } + return mergedStream +} + +// check and pause streams for pipe. +function pauseStreams (streams, options) { + if (!Array.isArray(streams)) { + // Backwards-compat with old-style streams + if (!streams._readableState && streams.pipe) { + streams = streams.pipe(PassThrough(options)) + } + if (!streams._readableState || !streams.pause || !streams.pipe) { + throw new Error('Only readable stream can be merged.') + } + streams.pause() + } else { + for (let i = 0, len = streams.length; i < len; i++) { + streams[i] = pauseStreams(streams[i], options) + } + } + return streams +} diff --git a/node_modules/merge2/package.json b/node_modules/merge2/package.json new file mode 100644 index 0000000..7777307 --- /dev/null +++ b/node_modules/merge2/package.json @@ -0,0 +1,43 @@ +{ + "name": "merge2", + "description": "Merge multiple streams into one stream in sequence or parallel.", + "authors": [ + "Yan Qing " + ], + "license": "MIT", + "version": "1.4.1", + "main": "./index.js", + "repository": { + "type": "git", + "url": "git@github.com:teambition/merge2.git" + }, + "homepage": "https://github.com/teambition/merge2", + "keywords": [ + "merge2", + "multiple", + "sequence", + "parallel", + "merge", + "stream", + "merge stream", + "sync" + ], + "engines": { + "node": ">= 8" + }, + "dependencies": {}, + "devDependencies": { + "standard": "^14.3.4", + "through2": "^3.0.1", + "thunks": "^4.9.6", + "tman": "^1.10.0", + "to-through": "^2.0.0" + }, + "scripts": { + "test": "standard && tman" + }, + "files": [ + "README.md", + "index.js" + ] +} diff --git a/node_modules/micromatch/LICENSE b/node_modules/micromatch/LICENSE new file mode 100644 index 0000000..9af4a67 --- /dev/null +++ b/node_modules/micromatch/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/micromatch/README.md b/node_modules/micromatch/README.md new file mode 100644 index 0000000..d72a059 --- /dev/null +++ b/node_modules/micromatch/README.md @@ -0,0 +1,1024 @@ +# micromatch [![NPM version](https://img.shields.io/npm/v/micromatch.svg?style=flat)](https://www.npmjs.com/package/micromatch) [![NPM monthly downloads](https://img.shields.io/npm/dm/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![NPM total downloads](https://img.shields.io/npm/dt/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![Tests](https://github.com/micromatch/micromatch/actions/workflows/test.yml/badge.svg)](https://github.com/micromatch/micromatch/actions/workflows/test.yml) + +> Glob matching for javascript/node.js. A replacement and faster alternative to minimatch and multimatch. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Table of Contents + +
+Details + + * [Install](#install) +- [Sponsors](#sponsors) + * [Gold Sponsors](#gold-sponsors) + * [Quickstart](#quickstart) + * [Why use micromatch?](#why-use-micromatch) + + [Matching features](#matching-features) + * [Switching to micromatch](#switching-to-micromatch) + + [From minimatch](#from-minimatch) + + [From multimatch](#from-multimatch) + * [API](#api) + * [Options](#options) + * [Options Examples](#options-examples) + + [options.basename](#optionsbasename) + + [options.bash](#optionsbash) + + [options.expandRange](#optionsexpandrange) + + [options.format](#optionsformat) + + [options.ignore](#optionsignore) + + [options.matchBase](#optionsmatchbase) + + [options.noextglob](#optionsnoextglob) + + [options.nonegate](#optionsnonegate) + + [options.noglobstar](#optionsnoglobstar) + + [options.nonull](#optionsnonull) + + [options.nullglob](#optionsnullglob) + + [options.onIgnore](#optionsonignore) + + [options.onMatch](#optionsonmatch) + + [options.onResult](#optionsonresult) + + [options.posixSlashes](#optionsposixslashes) + + [options.unescape](#optionsunescape) + * [Extended globbing](#extended-globbing) + + [Extglobs](#extglobs) + + [Braces](#braces) + + [Regex character classes](#regex-character-classes) + + [Regex groups](#regex-groups) + + [POSIX bracket expressions](#posix-bracket-expressions) + * [Notes](#notes) + + [Bash 4.3 parity](#bash-43-parity) + + [Backslashes](#backslashes) + * [Benchmarks](#benchmarks) + + [Running benchmarks](#running-benchmarks) + + [Latest results](#latest-results) + * [Contributing](#contributing) + * [About](#about) + +
+ +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save micromatch +``` + +
+ +# Sponsors + +[Become a Sponsor](https://github.com/sponsors/jonschlinkert) to add your logo to this README, or any of [my other projects](https://github.com/jonschlinkert?tab=repositories&q=&type=&language=&sort=stargazers) + +
+ +## Quickstart + +```js +const micromatch = require('micromatch'); +// micromatch(list, patterns[, options]); +``` + +The [main export](#micromatch) takes a list of strings and one or more glob patterns: + +```js +console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['f*', 'b*'])) //=> ['foo', 'bar', 'baz'] +console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['*', '!b*'])) //=> ['foo', 'qux'] +``` + +Use [.isMatch()](#ismatch) to for boolean matching: + +```js +console.log(micromatch.isMatch('foo', 'f*')) //=> true +console.log(micromatch.isMatch('foo', ['b*', 'f*'])) //=> true +``` + +[Switching](#switching-to-micromatch) from minimatch and multimatch is easy! + +
+ +## Why use micromatch? + +> micromatch is a [replacement](#switching-to-micromatch) for minimatch and multimatch + +* Supports all of the same matching features as [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch) +* More complete support for the Bash 4.3 specification than minimatch and multimatch. Micromatch passes _all of the spec tests_ from bash, including some that bash still fails. +* **Fast & Performant** - Loads in about 5ms and performs [fast matches](#benchmarks). +* **Glob matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories +* **[Advanced globbing](#extended-globbing)** - Supports [extglobs](#extglobs), [braces](#braces-1), and [POSIX brackets](#posix-bracket-expressions), and support for escaping special characters with `\` or quotes. +* **Accurate** - Covers more scenarios [than minimatch](https://github.com/yarnpkg/yarn/pull/3339) +* **Well tested** - More than 5,000 [test assertions](./test) +* **Windows support** - More reliable windows support than minimatch and multimatch. +* **[Safe](https://github.com/micromatch/braces#braces-is-safe)** - Micromatch is not subject to DoS with brace patterns like minimatch and multimatch. + +### Matching features + +* Support for multiple glob patterns (no need for wrappers like multimatch) +* Wildcards (`**`, `*.js`) +* Negation (`'!a/*.js'`, `'*!(b).js'`) +* [extglobs](#extglobs) (`+(x|y)`, `!(a|b)`) +* [POSIX character classes](#posix-bracket-expressions) (`[[:alpha:][:digit:]]`) +* [brace expansion](https://github.com/micromatch/braces) (`foo/{1..5}.md`, `bar/{a,b,c}.js`) +* regex character classes (`foo-[1-5].js`) +* regex logical "or" (`foo/(abc|xyz).js`) + +You can mix and match these features to create whatever patterns you need! + +## Switching to micromatch + +_(There is one notable difference between micromatch and minimatch in regards to how backslashes are handled. See [the notes about backslashes](#backslashes) for more information.)_ + +### From minimatch + +Use [micromatch.isMatch()](#ismatch) instead of `minimatch()`: + +```js +console.log(micromatch.isMatch('foo', 'b*')); //=> false +``` + +Use [micromatch.match()](#match) instead of `minimatch.match()`: + +```js +console.log(micromatch.match(['foo', 'bar'], 'b*')); //=> 'bar' +``` + +### From multimatch + +Same signature: + +```js +console.log(micromatch(['foo', 'bar', 'baz'], ['f*', '*z'])); //=> ['foo', 'baz'] +``` + +## API + +**Params** + +* `list` **{String|Array}**: List of strings to match. +* `patterns` **{String|Array}**: One or more glob patterns to use for matching. +* `options` **{Object}**: See available [options](#options) +* `returns` **{Array}**: Returns an array of matches + +**Example** + +```js +const mm = require('micromatch'); +// mm(list, patterns[, options]); + +console.log(mm(['a.js', 'a.txt'], ['*.js'])); +//=> [ 'a.js' ] +``` + +### [.matcher](index.js#L109) + +Returns a matcher function from the given glob `pattern` and `options`. The returned function takes a string to match as its only argument and returns true if the string is a match. + +**Params** + +* `pattern` **{String}**: Glob pattern +* `options` **{Object}** +* `returns` **{Function}**: Returns a matcher function. + +**Example** + +```js +const mm = require('micromatch'); +// mm.matcher(pattern[, options]); + +const isMatch = mm.matcher('*.!(*a)'); +console.log(isMatch('a.a')); //=> false +console.log(isMatch('a.b')); //=> true +``` + +### [.isMatch](index.js#L128) + +Returns true if **any** of the given glob `patterns` match the specified `string`. + +**Params** + +* `str` **{String}**: The string to test. +* `patterns` **{String|Array}**: One or more glob patterns to use for matching. +* `[options]` **{Object}**: See available [options](#options). +* `returns` **{Boolean}**: Returns true if any patterns match `str` + +**Example** + +```js +const mm = require('micromatch'); +// mm.isMatch(string, patterns[, options]); + +console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true +console.log(mm.isMatch('a.a', 'b.*')); //=> false +``` + +### [.not](index.js#L153) + +Returns a list of strings that _**do not match any**_ of the given `patterns`. + +**Params** + +* `list` **{Array}**: Array of strings to match. +* `patterns` **{String|Array}**: One or more glob pattern to use for matching. +* `options` **{Object}**: See available [options](#options) for changing how matches are performed +* `returns` **{Array}**: Returns an array of strings that **do not match** the given patterns. + +**Example** + +```js +const mm = require('micromatch'); +// mm.not(list, patterns[, options]); + +console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); +//=> ['b.b', 'c.c'] +``` + +### [.contains](index.js#L193) + +Returns true if the given `string` contains the given pattern. Similar to [.isMatch](#isMatch) but the pattern can match any part of the string. + +**Params** + +* `str` **{String}**: The string to match. +* `patterns` **{String|Array}**: Glob pattern to use for matching. +* `options` **{Object}**: See available [options](#options) for changing how matches are performed +* `returns` **{Boolean}**: Returns true if any of the patterns matches any part of `str`. + +**Example** + +```js +var mm = require('micromatch'); +// mm.contains(string, pattern[, options]); + +console.log(mm.contains('aa/bb/cc', '*b')); +//=> true +console.log(mm.contains('aa/bb/cc', '*d')); +//=> false +``` + +### [.matchKeys](index.js#L235) + +Filter the keys of the given object with the given `glob` pattern and `options`. Does not attempt to match nested keys. If you need this feature, use [glob-object](https://github.com/jonschlinkert/glob-object) instead. + +**Params** + +* `object` **{Object}**: The object with keys to filter. +* `patterns` **{String|Array}**: One or more glob patterns to use for matching. +* `options` **{Object}**: See available [options](#options) for changing how matches are performed +* `returns` **{Object}**: Returns an object with only keys that match the given patterns. + +**Example** + +```js +const mm = require('micromatch'); +// mm.matchKeys(object, patterns[, options]); + +const obj = { aa: 'a', ab: 'b', ac: 'c' }; +console.log(mm.matchKeys(obj, '*b')); +//=> { ab: 'b' } +``` + +### [.some](index.js#L264) + +Returns true if some of the strings in the given `list` match any of the given glob `patterns`. + +**Params** + +* `list` **{String|Array}**: The string or array of strings to test. Returns as soon as the first match is found. +* `patterns` **{String|Array}**: One or more glob patterns to use for matching. +* `options` **{Object}**: See available [options](#options) for changing how matches are performed +* `returns` **{Boolean}**: Returns true if any `patterns` matches any of the strings in `list` + +**Example** + +```js +const mm = require('micromatch'); +// mm.some(list, patterns[, options]); + +console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); +// true +console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); +// false +``` + +### [.every](index.js#L300) + +Returns true if every string in the given `list` matches any of the given glob `patterns`. + +**Params** + +* `list` **{String|Array}**: The string or array of strings to test. +* `patterns` **{String|Array}**: One or more glob patterns to use for matching. +* `options` **{Object}**: See available [options](#options) for changing how matches are performed +* `returns` **{Boolean}**: Returns true if all `patterns` matches all of the strings in `list` + +**Example** + +```js +const mm = require('micromatch'); +// mm.every(list, patterns[, options]); + +console.log(mm.every('foo.js', ['foo.js'])); +// true +console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); +// true +console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); +// false +console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); +// false +``` + +### [.all](index.js#L339) + +Returns true if **all** of the given `patterns` match the specified string. + +**Params** + +* `str` **{String|Array}**: The string to test. +* `patterns` **{String|Array}**: One or more glob patterns to use for matching. +* `options` **{Object}**: See available [options](#options) for changing how matches are performed +* `returns` **{Boolean}**: Returns true if any patterns match `str` + +**Example** + +```js +const mm = require('micromatch'); +// mm.all(string, patterns[, options]); + +console.log(mm.all('foo.js', ['foo.js'])); +// true + +console.log(mm.all('foo.js', ['*.js', '!foo.js'])); +// false + +console.log(mm.all('foo.js', ['*.js', 'foo.js'])); +// true + +console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); +// true +``` + +### [.capture](index.js#L366) + +Returns an array of matches captured by `pattern` in `string, or`null` if the pattern did not match. + +**Params** + +* `glob` **{String}**: Glob pattern to use for matching. +* `input` **{String}**: String to match +* `options` **{Object}**: See available [options](#options) for changing how matches are performed +* `returns` **{Array|null}**: Returns an array of captures if the input matches the glob pattern, otherwise `null`. + +**Example** + +```js +const mm = require('micromatch'); +// mm.capture(pattern, string[, options]); + +console.log(mm.capture('test/*.js', 'test/foo.js')); +//=> ['foo'] +console.log(mm.capture('test/*.js', 'foo/bar.css')); +//=> null +``` + +### [.makeRe](index.js#L392) + +Create a regular expression from the given glob `pattern`. + +**Params** + +* `pattern` **{String}**: A glob pattern to convert to regex. +* `options` **{Object}** +* `returns` **{RegExp}**: Returns a regex created from the given pattern. + +**Example** + +```js +const mm = require('micromatch'); +// mm.makeRe(pattern[, options]); + +console.log(mm.makeRe('*.js')); +//=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ +``` + +### [.scan](index.js#L408) + +Scan a glob pattern to separate the pattern into segments. Used by the [split](#split) method. + +**Params** + +* `pattern` **{String}** +* `options` **{Object}** +* `returns` **{Object}**: Returns an object with + +**Example** + +```js +const mm = require('micromatch'); +const state = mm.scan(pattern[, options]); +``` + +### [.parse](index.js#L424) + +Parse a glob pattern to create the source string for a regular expression. + +**Params** + +* `glob` **{String}** +* `options` **{Object}** +* `returns` **{Object}**: Returns an object with useful properties and output to be used as regex source string. + +**Example** + +```js +const mm = require('micromatch'); +const state = mm.parse(pattern[, options]); +``` + +### [.braces](index.js#L451) + +Process the given brace `pattern`. + +**Params** + +* `pattern` **{String}**: String with brace pattern to process. +* `options` **{Object}**: Any [options](#options) to change how expansion is performed. See the [braces](https://github.com/micromatch/braces) library for all available options. +* `returns` **{Array}** + +**Example** + +```js +const { braces } = require('micromatch'); +console.log(braces('foo/{a,b,c}/bar')); +//=> [ 'foo/(a|b|c)/bar' ] + +console.log(braces('foo/{a,b,c}/bar', { expand: true })); +//=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] +``` + +## Options + +| **Option** | **Type** | **Default value** | **Description** | +| --- | --- | --- | --- | +| `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. | +| `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). | +| `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. | +| `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). | +| `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` | +| `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. | +| `dot` | `boolean` | `false` | Match dotfiles. Otherwise dotfiles are ignored unless a `.` is explicitly defined in the pattern. | +| `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. This option is overridden by the `expandBrace` option. | +| `failglob` | `boolean` | `false` | Similar to the `failglob` behavior in Bash, throws an error when no matches are found. Based on the bash option of the same name. | +| `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. | +| `flags` | `boolean` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. | +| [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. | +| `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. | +| `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. | +| `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. | +| `lookbehinds` | `boolean` | `true` | Support regex positive and negative lookbehinds. Note that you must be using Node 8.1.10 or higher to enable regex lookbehinds. | +| `matchBase` | `boolean` | `false` | Alias for `basename` | +| `maxLength` | `boolean` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. | +| `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. | +| `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. | +| `nocase` | `boolean` | `false` | Perform case-insensitive matching. Equivalent to the regex `i` flag. Note that this option is ignored when the `flags` option is defined. | +| `nodupes` | `boolean` | `true` | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. | +| `noext` | `boolean` | `false` | Alias for `noextglob` | +| `noextglob` | `boolean` | `false` | Disable support for matching with [extglobs](#extglobs) (like `+(a\|b)`) | +| `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) | +| `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` | +| `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. | +| [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. | +| [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. | +| [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. | +| `posix` | `boolean` | `false` | Support [POSIX character classes](#posix-bracket-expressions) ("posix brackets"). | +| `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself | +| `prepend` | `string` | `undefined` | String to prepend to the generated regex used for matching. | +| `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). | +| `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. | +| `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. | +| `unescape` | `boolean` | `undefined` | Remove preceding backslashes from escaped glob characters before creating the regular expression to perform matches. | +| `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatitibility. | + +## Options Examples + +### options.basename + +Allow glob patterns without slashes to match a file path based on its basename. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `matchBase`. + +**Type**: `Boolean` + +**Default**: `false` + +**Example** + +```js +micromatch(['a/b.js', 'a/c.md'], '*.js'); +//=> [] + +micromatch(['a/b.js', 'a/c.md'], '*.js', { basename: true }); +//=> ['a/b.js'] +``` + +### options.bash + +Enabled by default, this option enforces bash-like behavior with stars immediately following a bracket expression. Bash bracket expressions are similar to regex character classes, but unlike regex, a star following a bracket expression **does not repeat the bracketed characters**. Instead, the star is treated the same as any other star. + +**Type**: `Boolean` + +**Default**: `true` + +**Example** + +```js +const files = ['abc', 'ajz']; +console.log(micromatch(files, '[a-c]*')); +//=> ['abc', 'ajz'] + +console.log(micromatch(files, '[a-c]*', { bash: false })); +``` + +### options.expandRange + +**Type**: `function` + +**Default**: `undefined` + +Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need. + +**Example** + +The following example shows how to create a glob that matches a numeric folder name between `01` and `25`, with leading zeros. + +```js +const fill = require('fill-range'); +const regex = micromatch.makeRe('foo/{01..25}/bar', { + expandRange(a, b) { + return `(${fill(a, b, { toRegex: true })})`; + } +}); + +console.log(regex) +//=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/ + +console.log(regex.test('foo/00/bar')) // false +console.log(regex.test('foo/01/bar')) // true +console.log(regex.test('foo/10/bar')) // true +console.log(regex.test('foo/22/bar')) // true +console.log(regex.test('foo/25/bar')) // true +console.log(regex.test('foo/26/bar')) // false +``` + +### options.format + +**Type**: `function` + +**Default**: `undefined` + +Custom function for formatting strings before they're matched. + +**Example** + +```js +// strip leading './' from strings +const format = str => str.replace(/^\.\//, ''); +const isMatch = picomatch('foo/*.js', { format }); +console.log(isMatch('./foo/bar.js')) //=> true +``` + +### options.ignore + +String or array of glob patterns to match files to ignore. + +**Type**: `String|Array` + +**Default**: `undefined` + +```js +const isMatch = micromatch.matcher('*', { ignore: 'f*' }); +console.log(isMatch('foo')) //=> false +console.log(isMatch('bar')) //=> true +console.log(isMatch('baz')) //=> true +``` + +### options.matchBase + +Alias for [options.basename](#options-basename). + +### options.noextglob + +Disable extglob support, so that [extglobs](#extglobs) are regarded as literal characters. + +**Type**: `Boolean` + +**Default**: `undefined` + +**Examples** + +```js +console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)')); +//=> ['a/b', 'a/!(z)'] + +console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)', { noextglob: true })); +//=> ['a/!(z)'] (matches only as literal characters) +``` + +### options.nonegate + +Disallow negation (`!`) patterns, and treat leading `!` as a literal character to match. + +**Type**: `Boolean` + +**Default**: `undefined` + +### options.noglobstar + +Disable matching with globstars (`**`). + +**Type**: `Boolean` + +**Default**: `undefined` + +```js +micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**'); +//=> ['a/b', 'a/b/c', 'a/b/c/d'] + +micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**', {noglobstar: true}); +//=> ['a/b'] +``` + +### options.nonull + +Alias for [options.nullglob](#options-nullglob). + +### options.nullglob + +If `true`, when no matches are found the actual (arrayified) glob pattern is returned instead of an empty array. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `nonull`. + +**Type**: `Boolean` + +**Default**: `undefined` + +### options.onIgnore + +```js +const onIgnore = ({ glob, regex, input, output }) => { + console.log({ glob, regex, input, output }); + // { glob: '*', regex: /^(?:(?!\.)(?=.)[^\/]*?\/?)$/, input: 'foo', output: 'foo' } +}; + +const isMatch = micromatch.matcher('*', { onIgnore, ignore: 'f*' }); +isMatch('foo'); +isMatch('bar'); +isMatch('baz'); +``` + +### options.onMatch + +```js +const onMatch = ({ glob, regex, input, output }) => { + console.log({ input, output }); + // { input: 'some\\path', output: 'some/path' } + // { input: 'some\\path', output: 'some/path' } + // { input: 'some\\path', output: 'some/path' } +}; + +const isMatch = micromatch.matcher('**', { onMatch, posixSlashes: true }); +isMatch('some\\path'); +isMatch('some\\path'); +isMatch('some\\path'); +``` + +### options.onResult + +```js +const onResult = ({ glob, regex, input, output }) => { + console.log({ glob, regex, input, output }); +}; + +const isMatch = micromatch('*', { onResult, ignore: 'f*' }); +isMatch('foo'); +isMatch('bar'); +isMatch('baz'); +``` + +### options.posixSlashes + +Convert path separators on returned files to posix/unix-style forward slashes. Aliased as `unixify` for backwards compatibility. + +**Type**: `Boolean` + +**Default**: `true` on windows, `false` everywhere else. + +**Example** + +```js +console.log(micromatch.match(['a\\b\\c'], 'a/**')); +//=> ['a/b/c'] + +console.log(micromatch.match(['a\\b\\c'], { posixSlashes: false })); +//=> ['a\\b\\c'] +``` + +### options.unescape + +Remove backslashes from escaped glob characters before creating the regular expression to perform matches. + +**Type**: `Boolean` + +**Default**: `undefined` + +**Example** + +In this example we want to match a literal `*`: + +```js +console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c')); +//=> ['a\\*c'] + +console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c', { unescape: true })); +//=> ['a*c'] +``` + +
+
+ +## Extended globbing + +Micromatch supports the following extended globbing features. + +### Extglobs + +Extended globbing, as described by the bash man page: + +| **pattern** | **regex equivalent** | **description** | +| --- | --- | --- | +| `?(pattern)` | `(pattern)?` | Matches zero or one occurrence of the given patterns | +| `*(pattern)` | `(pattern)*` | Matches zero or more occurrences of the given patterns | +| `+(pattern)` | `(pattern)+` | Matches one or more occurrences of the given patterns | +| `@(pattern)` | `(pattern)` * | Matches one of the given patterns | +| `!(pattern)` | N/A (equivalent regex is much more complicated) | Matches anything except one of the given patterns | + +* Note that `@` isn't a regex character. + +### Braces + +Brace patterns can be used to match specific ranges or sets of characters. + +**Example** + +The pattern `{f,b}*/{1..3}/{b,q}*` would match any of following strings: + +``` +foo/1/bar +foo/2/bar +foo/3/bar +baz/1/qux +baz/2/qux +baz/3/qux +``` + +Visit [braces](https://github.com/micromatch/braces) to see the full range of features and options related to brace expansion, or to create brace matching or expansion related issues. + +### Regex character classes + +Given the list: `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: + +* `[ac].js`: matches both `a` and `c`, returning `['a.js', 'c.js']` +* `[b-d].js`: matches from `b` to `d`, returning `['b.js', 'c.js', 'd.js']` +* `a/[A-Z].js`: matches and uppercase letter, returning `['a/E.md']` + +Learn about [regex character classes](http://www.regular-expressions.info/charclass.html). + +### Regex groups + +Given `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: + +* `(a|c).js`: would match either `a` or `c`, returning `['a.js', 'c.js']` +* `(b|d).js`: would match either `b` or `d`, returning `['b.js', 'd.js']` +* `(b|[A-Z]).js`: would match either `b` or an uppercase letter, returning `['b.js', 'E.js']` + +As with regex, parens can be nested, so patterns like `((a|b)|c)/b` will work. Although brace expansion might be friendlier to use, depending on preference. + +### POSIX bracket expressions + +POSIX brackets are intended to be more user-friendly than regex character classes. This of course is in the eye of the beholder. + +**Example** + +```js +console.log(micromatch.isMatch('a1', '[[:alpha:][:digit:]]')) //=> true +console.log(micromatch.isMatch('a1', '[[:alpha:][:alpha:]]')) //=> false +``` + +*** + +## Notes + +### Bash 4.3 parity + +Whenever possible matching behavior is based on behavior Bash 4.3, which is mostly consistent with minimatch. + +However, it's suprising how many edge cases and rabbit holes there are with glob matching, and since there is no real glob specification, and micromatch is more accurate than both Bash and minimatch, there are cases where best-guesses were made for behavior. In a few cases where Bash had no answers, we used wildmatch (used by git) as a fallback. + +### Backslashes + +There is an important, notable difference between minimatch and micromatch _in regards to how backslashes are handled_ in glob patterns. + +* Micromatch exclusively and explicitly reserves backslashes for escaping characters in a glob pattern, even on windows, which is consistent with bash behavior. _More importantly, unescaping globs can result in unsafe regular expressions_. +* Minimatch converts all backslashes to forward slashes, which means you can't use backslashes to escape any characters in your glob patterns. + +We made this decision for micromatch for a couple of reasons: + +* Consistency with bash conventions. +* Glob patterns are not filepaths. They are a type of [regular language](https://en.wikipedia.org/wiki/Regular_language) that is converted to a JavaScript regular expression. Thus, when forward slashes are defined in a glob pattern, the resulting regular expression will match windows or POSIX path separators just fine. + +**A note about joining paths to globs** + +Note that when you pass something like `path.join('foo', '*')` to micromatch, you are creating a filepath and expecting it to still work as a glob pattern. This causes problems on windows, since the `path.sep` is `\\`. + +In other words, since `\\` is reserved as an escape character in globs, on windows `path.join('foo', '*')` would result in `foo\\*`, which tells micromatch to match `*` as a literal character. This is the same behavior as bash. + +To solve this, you might be inspired to do something like `'foo\\*'.replace(/\\/g, '/')`, but this causes another, potentially much more serious, problem. + +## Benchmarks + +### Running benchmarks + +Install dependencies for running benchmarks: + +```sh +$ cd bench && npm install +``` + +Run the benchmarks: + +```sh +$ npm run bench +``` + +### Latest results + +As of August 23, 2024 (longer bars are better): + +```sh +# .makeRe star + micromatch x 2,232,802 ops/sec ±2.34% (89 runs sampled)) + minimatch x 781,018 ops/sec ±6.74% (92 runs sampled)) + +# .makeRe star; dot=true + micromatch x 1,863,453 ops/sec ±0.74% (93 runs sampled) + minimatch x 723,105 ops/sec ±0.75% (93 runs sampled) + +# .makeRe globstar + micromatch x 1,624,179 ops/sec ±2.22% (91 runs sampled) + minimatch x 1,117,230 ops/sec ±2.78% (86 runs sampled)) + +# .makeRe globstars + micromatch x 1,658,642 ops/sec ±0.86% (92 runs sampled) + minimatch x 741,224 ops/sec ±1.24% (89 runs sampled)) + +# .makeRe with leading star + micromatch x 1,525,014 ops/sec ±1.63% (90 runs sampled) + minimatch x 561,074 ops/sec ±3.07% (89 runs sampled) + +# .makeRe - braces + micromatch x 172,478 ops/sec ±2.37% (78 runs sampled) + minimatch x 96,087 ops/sec ±2.34% (88 runs sampled))) + +# .makeRe braces - range (expanded) + micromatch x 26,973 ops/sec ±0.84% (89 runs sampled) + minimatch x 3,023 ops/sec ±0.99% (90 runs sampled)) + +# .makeRe braces - range (compiled) + micromatch x 152,892 ops/sec ±1.67% (83 runs sampled) + minimatch x 992 ops/sec ±3.50% (89 runs sampled)d)) + +# .makeRe braces - nested ranges (expanded) + micromatch x 15,816 ops/sec ±13.05% (80 runs sampled) + minimatch x 2,953 ops/sec ±1.64% (91 runs sampled) + +# .makeRe braces - nested ranges (compiled) + micromatch x 110,881 ops/sec ±1.85% (82 runs sampled) + minimatch x 1,008 ops/sec ±1.51% (91 runs sampled) + +# .makeRe braces - set (compiled) + micromatch x 134,930 ops/sec ±3.54% (63 runs sampled)) + minimatch x 43,242 ops/sec ±0.60% (93 runs sampled) + +# .makeRe braces - nested sets (compiled) + micromatch x 94,455 ops/sec ±1.74% (69 runs sampled)) + minimatch x 27,720 ops/sec ±1.84% (93 runs sampled)) +``` + +## Contributing + +All contributions are welcome! Please read [the contributing guide](.github/contributing.md) to get started. + +**Bug reports** + +Please create an issue if you encounter a bug or matching behavior that doesn't seem correct. If you find a matching-related issue, please: + +* [research existing issues first](../../issues) (open and closed) +* visit the [GNU Bash documentation](https://www.gnu.org/software/bash/manual/) to see how Bash deals with the pattern +* visit the [minimatch](https://github.com/isaacs/minimatch) documentation to cross-check expected behavior in node.js +* if all else fails, since there is no real specification for globs we will probably need to discuss expected behavior and decide how to resolve it. which means any detail you can provide to help with this discussion would be greatly appreciated. + +**Platform issues** + +It's important to us that micromatch work consistently on all platforms. If you encounter any platform-specific matching or path related issues, please let us know (pull requests are also greatly appreciated). + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [braces](https://www.npmjs.com/package/braces): Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support… [more](https://github.com/micromatch/braces) | [homepage](https://github.com/micromatch/braces "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.") +* [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/micromatch/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.") +* [extglob](https://www.npmjs.com/package/extglob): Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… [more](https://github.com/micromatch/extglob) | [homepage](https://github.com/micromatch/extglob "Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns.") +* [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") +* [nanomatch](https://www.npmjs.com/package/nanomatch): Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… [more](https://github.com/micromatch/nanomatch) | [homepage](https://github.com/micromatch/nanomatch "Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces)") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 523 | [jonschlinkert](https://github.com/jonschlinkert) | +| 12 | [es128](https://github.com/es128) | +| 9 | [danez](https://github.com/danez) | +| 8 | [doowb](https://github.com/doowb) | +| 6 | [paulmillr](https://github.com/paulmillr) | +| 5 | [mrmlnc](https://github.com/mrmlnc) | +| 3 | [DrPizza](https://github.com/DrPizza) | +| 2 | [Tvrqvoise](https://github.com/Tvrqvoise) | +| 2 | [antonyk](https://github.com/antonyk) | +| 2 | [MartinKolarik](https://github.com/MartinKolarik) | +| 2 | [Glazy](https://github.com/Glazy) | +| 2 | [mceIdo](https://github.com/mceIdo) | +| 2 | [TrySound](https://github.com/TrySound) | +| 1 | [yvele](https://github.com/yvele) | +| 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | +| 1 | [simlu](https://github.com/simlu) | +| 1 | [curbengh](https://github.com/curbengh) | +| 1 | [fidian](https://github.com/fidian) | +| 1 | [tomByrer](https://github.com/tomByrer) | +| 1 | [ZoomerTedJackson](https://github.com/ZoomerTedJackson) | +| 1 | [styfle](https://github.com/styfle) | +| 1 | [sebdeckers](https://github.com/sebdeckers) | +| 1 | [muescha](https://github.com/muescha) | +| 1 | [juszczykjakub](https://github.com/juszczykjakub) | +| 1 | [joyceerhl](https://github.com/joyceerhl) | +| 1 | [donatj](https://github.com/donatj) | +| 1 | [frangio](https://github.com/frangio) | +| 1 | [UltCombo](https://github.com/UltCombo) | +| 1 | [DianeLooney](https://github.com/DianeLooney) | +| 1 | [devongovett](https://github.com/devongovett) | +| 1 | [Cslove](https://github.com/Cslove) | +| 1 | [amilajack](https://github.com/amilajack) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2024, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on August 23, 2024._ \ No newline at end of file diff --git a/node_modules/micromatch/index.js b/node_modules/micromatch/index.js new file mode 100644 index 0000000..cb9d9ef --- /dev/null +++ b/node_modules/micromatch/index.js @@ -0,0 +1,474 @@ +'use strict'; + +const util = require('util'); +const braces = require('braces'); +const picomatch = require('picomatch'); +const utils = require('picomatch/lib/utils'); + +const isEmptyString = v => v === '' || v === './'; +const hasBraces = v => { + const index = v.indexOf('{'); + return index > -1 && v.indexOf('}', index) > -1; +}; + +/** + * Returns an array of strings that match one or more glob patterns. + * + * ```js + * const mm = require('micromatch'); + * // mm(list, patterns[, options]); + * + * console.log(mm(['a.js', 'a.txt'], ['*.js'])); + * //=> [ 'a.js' ] + * ``` + * @param {String|Array} `list` List of strings to match. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) + * @return {Array} Returns an array of matches + * @summary false + * @api public + */ + +const micromatch = (list, patterns, options) => { + patterns = [].concat(patterns); + list = [].concat(list); + + let omit = new Set(); + let keep = new Set(); + let items = new Set(); + let negatives = 0; + + let onResult = state => { + items.add(state.output); + if (options && options.onResult) { + options.onResult(state); + } + }; + + for (let i = 0; i < patterns.length; i++) { + let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true); + let negated = isMatch.state.negated || isMatch.state.negatedExtglob; + if (negated) negatives++; + + for (let item of list) { + let matched = isMatch(item, true); + + let match = negated ? !matched.isMatch : matched.isMatch; + if (!match) continue; + + if (negated) { + omit.add(matched.output); + } else { + omit.delete(matched.output); + keep.add(matched.output); + } + } + } + + let result = negatives === patterns.length ? [...items] : [...keep]; + let matches = result.filter(item => !omit.has(item)); + + if (options && matches.length === 0) { + if (options.failglob === true) { + throw new Error(`No matches found for "${patterns.join(', ')}"`); + } + + if (options.nonull === true || options.nullglob === true) { + return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; + } + } + + return matches; +}; + +/** + * Backwards compatibility + */ + +micromatch.match = micromatch; + +/** + * Returns a matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns + * true if the string is a match. + * + * ```js + * const mm = require('micromatch'); + * // mm.matcher(pattern[, options]); + * + * const isMatch = mm.matcher('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @param {String} `pattern` Glob pattern + * @param {Object} `options` + * @return {Function} Returns a matcher function. + * @api public + */ + +micromatch.matcher = (pattern, options) => picomatch(pattern, options); + +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const mm = require('micromatch'); + * // mm.isMatch(string, patterns[, options]); + * + * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(mm.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `[options]` See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); + +/** + * Backwards compatibility + */ + +micromatch.any = micromatch.isMatch; + +/** + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.not(list, patterns[, options]); + * + * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * //=> ['b.b', 'c.c'] + * ``` + * @param {Array} `list` Array of strings to match. + * @param {String|Array} `patterns` One or more glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of strings that **do not match** the given patterns. + * @api public + */ + +micromatch.not = (list, patterns, options = {}) => { + patterns = [].concat(patterns).map(String); + let result = new Set(); + let items = []; + + let onResult = state => { + if (options.onResult) options.onResult(state); + items.push(state.output); + }; + + let matches = new Set(micromatch(list, patterns, { ...options, onResult })); + + for (let item of items) { + if (!matches.has(item)) { + result.add(item); + } + } + return [...result]; +}; + +/** + * Returns true if the given `string` contains the given pattern. Similar + * to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * ```js + * var mm = require('micromatch'); + * // mm.contains(string, pattern[, options]); + * + * console.log(mm.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(mm.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String|Array} `patterns` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any of the patterns matches any part of `str`. + * @api public + */ + +micromatch.contains = (str, pattern, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util.inspect(str)}"`); + } + + if (Array.isArray(pattern)) { + return pattern.some(p => micromatch.contains(str, p, options)); + } + + if (typeof pattern === 'string') { + if (isEmptyString(str) || isEmptyString(pattern)) { + return false; + } + + if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) { + return true; + } + } + + return micromatch.isMatch(str, pattern, { ...options, contains: true }); +}; + +/** + * Filter the keys of the given object with the given `glob` pattern + * and `options`. Does not attempt to match nested keys. If you need this feature, + * use [glob-object][] instead. + * + * ```js + * const mm = require('micromatch'); + * // mm.matchKeys(object, patterns[, options]); + * + * const obj = { aa: 'a', ab: 'b', ac: 'c' }; + * console.log(mm.matchKeys(obj, '*b')); + * //=> { ab: 'b' } + * ``` + * @param {Object} `object` The object with keys to filter. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Object} Returns an object with only keys that match the given patterns. + * @api public + */ + +micromatch.matchKeys = (obj, patterns, options) => { + if (!utils.isObject(obj)) { + throw new TypeError('Expected the first argument to be an object'); + } + let keys = micromatch(Object.keys(obj), patterns, options); + let res = {}; + for (let key of keys) res[key] = obj[key]; + return res; +}; + +/** + * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.some(list, patterns[, options]); + * + * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // true + * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list` + * @api public + */ + +micromatch.some = (list, patterns, options) => { + let items = [].concat(list); + + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch(String(pattern), options); + if (items.some(item => isMatch(item))) { + return true; + } + } + return false; +}; + +/** + * Returns true if every string in the given `list` matches + * any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.every(list, patterns[, options]); + * + * console.log(mm.every('foo.js', ['foo.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // false + * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list` + * @api public + */ + +micromatch.every = (list, patterns, options) => { + let items = [].concat(list); + + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch(String(pattern), options); + if (!items.every(item => isMatch(item))) { + return false; + } + } + return true; +}; + +/** + * Returns true if **all** of the given `patterns` match + * the specified string. + * + * ```js + * const mm = require('micromatch'); + * // mm.all(string, patterns[, options]); + * + * console.log(mm.all('foo.js', ['foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); + * // false + * + * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * // true + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch.all = (str, patterns, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util.inspect(str)}"`); + } + + return [].concat(patterns).every(p => picomatch(p, options)(str)); +}; + +/** + * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. + * + * ```js + * const mm = require('micromatch'); + * // mm.capture(pattern, string[, options]); + * + * console.log(mm.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(mm.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `glob` Glob pattern to use for matching. + * @param {String} `input` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`. + * @api public + */ + +micromatch.capture = (glob, input, options) => { + let posix = utils.isWindows(options); + let regex = picomatch.makeRe(String(glob), { ...options, capture: true }); + let match = regex.exec(posix ? utils.toPosixSlashes(input) : input); + + if (match) { + return match.slice(1).map(v => v === void 0 ? '' : v); + } +}; + +/** + * Create a regular expression from the given glob `pattern`. + * + * ```js + * const mm = require('micromatch'); + * // mm.makeRe(pattern[, options]); + * + * console.log(mm.makeRe('*.js')); + * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ + * ``` + * @param {String} `pattern` A glob pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +micromatch.makeRe = (...args) => picomatch.makeRe(...args); + +/** + * Scan a glob pattern to separate the pattern into segments. Used + * by the [split](#split) method. + * + * ```js + * const mm = require('micromatch'); + * const state = mm.scan(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + +micromatch.scan = (...args) => picomatch.scan(...args); + +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const mm = require('micromatch'); + * const state = mm.parse(pattern[, options]); + * ``` + * @param {String} `glob` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as regex source string. + * @api public + */ + +micromatch.parse = (patterns, options) => { + let res = []; + for (let pattern of [].concat(patterns || [])) { + for (let str of braces(String(pattern), options)) { + res.push(picomatch.parse(str, options)); + } + } + return res; +}; + +/** + * Process the given brace `pattern`. + * + * ```js + * const { braces } = require('micromatch'); + * console.log(braces('foo/{a,b,c}/bar')); + * //=> [ 'foo/(a|b|c)/bar' ] + * + * console.log(braces('foo/{a,b,c}/bar', { expand: true })); + * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] + * ``` + * @param {String} `pattern` String with brace pattern to process. + * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. + * @return {Array} + * @api public + */ + +micromatch.braces = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + if ((options && options.nobrace === true) || !hasBraces(pattern)) { + return [pattern]; + } + return braces(pattern, options); +}; + +/** + * Expand braces + */ + +micromatch.braceExpand = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + return micromatch.braces(pattern, { ...options, expand: true }); +}; + +/** + * Expose micromatch + */ + +// exposed for tests +micromatch.hasBraces = hasBraces; +module.exports = micromatch; diff --git a/node_modules/micromatch/package.json b/node_modules/micromatch/package.json new file mode 100644 index 0000000..d5558bb --- /dev/null +++ b/node_modules/micromatch/package.json @@ -0,0 +1,119 @@ +{ + "name": "micromatch", + "description": "Glob matching for javascript/node.js. A replacement and faster alternative to minimatch and multimatch.", + "version": "4.0.8", + "homepage": "https://github.com/micromatch/micromatch", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "(https://github.com/DianeLooney)", + "Amila Welihinda (amilajack.com)", + "Bogdan Chadkin (https://github.com/TrySound)", + "Brian Woodward (https://twitter.com/doowb)", + "Devon Govett (http://badassjs.com)", + "Elan Shanker (https://github.com/es128)", + "Fabrício Matté (https://ultcombo.js.org)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)", + "Martin Kolárik (https://kolarik.sk)", + "Olsten Larck (https://i.am.charlike.online)", + "Paul Miller (paulmillr.com)", + "Tom Byrer (https://github.com/tomByrer)", + "Tyler Akins (http://rumkin.com)", + "Peter Bright (https://github.com/drpizza)", + "Kuba Juszczyk (https://github.com/ku8ar)" + ], + "repository": "micromatch/micromatch", + "bugs": { + "url": "https://github.com/micromatch/micromatch/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=8.6" + }, + "scripts": { + "test": "mocha" + }, + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "devDependencies": { + "fill-range": "^7.0.1", + "gulp-format-md": "^2.0.0", + "minimatch": "^5.0.1", + "mocha": "^9.2.2", + "time-require": "github:jonschlinkert/time-require" + }, + "keywords": [ + "bash", + "bracket", + "character-class", + "expand", + "expansion", + "expression", + "extglob", + "extglobs", + "file", + "files", + "filter", + "find", + "glob", + "globbing", + "globs", + "globstar", + "lookahead", + "lookaround", + "lookbehind", + "match", + "matcher", + "matches", + "matching", + "micromatch", + "minimatch", + "multimatch", + "negate", + "negation", + "path", + "pattern", + "patterns", + "posix", + "regex", + "regexp", + "regular", + "shell", + "star", + "wildcard" + ], + "verb": { + "toc": "collapsible", + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + }, + "related": { + "list": [ + "braces", + "expand-brackets", + "extglob", + "fill-range", + "nanomatch" + ] + }, + "reflinks": [ + "extglob", + "fill-range", + "glob-object", + "minimatch", + "multimatch" + ] + } +} diff --git a/node_modules/minimatch/LICENSE b/node_modules/minimatch/LICENSE new file mode 100644 index 0000000..1493534 --- /dev/null +++ b/node_modules/minimatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2011-2023 Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/minimatch/README.md b/node_modules/minimatch/README.md new file mode 100644 index 0000000..3c97a02 --- /dev/null +++ b/node_modules/minimatch/README.md @@ -0,0 +1,454 @@ +# minimatch + +A minimal matching utility. + +This is the matching library used internally by npm. + +It works by converting glob expressions into JavaScript `RegExp` +objects. + +## Usage + +```js +// hybrid module, load with require() or import +import { minimatch } from 'minimatch' +// or: +const { minimatch } = require('minimatch') + +minimatch('bar.foo', '*.foo') // true! +minimatch('bar.foo', '*.bar') // false! +minimatch('bar.foo', '*.+(bar|foo)', { debug: true }) // true, and noisy! +``` + +## Features + +Supports these glob features: + +- Brace Expansion +- Extended glob matching +- "Globstar" `**` matching +- [Posix character + classes](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html), + like `[[:alpha:]]`, supporting the full range of Unicode + characters. For example, `[[:alpha:]]` will match against + `'é'`, though `[a-zA-Z]` will not. Collating symbol and set + matching is not supported, so `[[=e=]]` will _not_ match `'é'` + and `[[.ch.]]` will not match `'ch'` in locales where `ch` is + considered a single character. + +See: + +- `man sh` +- `man bash` [Pattern + Matching](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) +- `man 3 fnmatch` +- `man 5 gitignore` + +## Windows + +**Please only use forward-slashes in glob expressions.** + +Though windows uses either `/` or `\` as its path separator, only `/` +characters are used by this glob implementation. You must use +forward-slashes **only** in glob expressions. Back-slashes in patterns +will always be interpreted as escape characters, not path separators. + +Note that `\` or `/` _will_ be interpreted as path separators in paths on +Windows, and will match against `/` in glob expressions. + +So just always use `/` in patterns. + +### UNC Paths + +On Windows, UNC paths like `//?/c:/...` or +`//ComputerName/Share/...` are handled specially. + +- Patterns starting with a double-slash followed by some + non-slash characters will preserve their double-slash. As a + result, a pattern like `//*` will match `//x`, but not `/x`. +- Patterns staring with `//?/:` will _not_ treat + the `?` as a wildcard character. Instead, it will be treated + as a normal string. +- Patterns starting with `//?/:/...` will match + file paths starting with `:/...`, and vice versa, + as if the `//?/` was not present. This behavior only is + present when the drive letters are a case-insensitive match to + one another. The remaining portions of the path/pattern are + compared case sensitively, unless `nocase:true` is set. + +Note that specifying a UNC path using `\` characters as path +separators is always allowed in the file path argument, but only +allowed in the pattern argument when `windowsPathsNoEscape: true` +is set in the options. + +## Minimatch Class + +Create a minimatch object by instantiating the `minimatch.Minimatch` class. + +```javascript +var Minimatch = require('minimatch').Minimatch +var mm = new Minimatch(pattern, options) +``` + +### Properties + +- `pattern` The original pattern the minimatch object represents. +- `options` The options supplied to the constructor. +- `set` A 2-dimensional array of regexp or string expressions. + Each row in the + array corresponds to a brace-expanded pattern. Each item in the row + corresponds to a single path-part. For example, the pattern + `{a,b/c}/d` would expand to a set of patterns like: + + [ [ a, d ] + , [ b, c, d ] ] + + If a portion of the pattern doesn't have any "magic" in it + (that is, it's something like `"foo"` rather than `fo*o?`), then it + will be left as a string rather than converted to a regular + expression. + +- `regexp` Created by the `makeRe` method. A single regular expression + expressing the entire pattern. This is useful in cases where you wish + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. +- `negate` True if the pattern is negated. +- `comment` True if the pattern is a comment. +- `empty` True if the pattern is `""`. + +### Methods + +- `makeRe()` Generate the `regexp` member if necessary, and return it. + Will return `false` if the pattern is invalid. +- `match(fname)` Return true if the filename matches the pattern, or + false otherwise. +- `matchOne(fileArray, patternArray, partial)` Take a `/`-split + filename, and match it against a single row in the `regExpSet`. This + method is mainly for internal use, but is exposed so that it can be + used by a glob-walker that needs to avoid excessive filesystem calls. +- `hasMagic()` Returns true if the parsed pattern contains any + magic characters. Returns false if all comparator parts are + string literals. If the `magicalBraces` option is set on the + constructor, then it will consider brace expansions which are + not otherwise magical to be magic. If not set, then a pattern + like `a{b,c}d` will return `false`, because neither `abd` nor + `acd` contain any special glob characters. + + This does **not** mean that the pattern string can be used as a + literal filename, as it may contain magic glob characters that + are escaped. For example, the pattern `\\*` or `[*]` would not + be considered to have magic, as the matching portion parses to + the literal string `'*'` and would match a path named `'*'`, + not `'\\*'` or `'[*]'`. The `minimatch.unescape()` method may + be used to remove escape characters. + +All other methods are internal, and will be called as necessary. + +### minimatch(path, pattern, options) + +Main export. Tests a path against the pattern using the options. + +```javascript +var isJS = minimatch(file, '*.js', { matchBase: true }) +``` + +### minimatch.filter(pattern, options) + +Returns a function that tests its +supplied argument, suitable for use with `Array.filter`. Example: + +```javascript +var javascripts = fileList.filter(minimatch.filter('*.js', { matchBase: true })) +``` + +### minimatch.escape(pattern, options = {}) + +Escape all magic characters in a glob pattern, so that it will +only ever match literal strings + +If the `windowsPathsNoEscape` option is used, then characters are +escaped by wrapping in `[]`, because a magic character wrapped in +a character class can only be satisfied by that exact character. + +Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot +be escaped or unescaped. + +### minimatch.unescape(pattern, options = {}) + +Un-escape a glob string that may contain some escaped characters. + +If the `windowsPathsNoEscape` option is used, then square-brace +escapes are removed, but not backslash escapes. For example, it +will turn the string `'[*]'` into `*`, but it will not turn +`'\\*'` into `'*'`, because `\` is a path separator in +`windowsPathsNoEscape` mode. + +When `windowsPathsNoEscape` is not set, then both brace escapes +and backslash escapes are removed. + +Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot +be escaped or unescaped. + +### minimatch.match(list, pattern, options) + +Match against the list of +files, in the style of fnmatch or glob. If nothing is matched, and +options.nonull is set, then return a list containing the pattern itself. + +```javascript +var javascripts = minimatch.match(fileList, '*.js', { matchBase: true }) +``` + +### minimatch.makeRe(pattern, options) + +Make a regular expression object from the pattern. + +## Options + +All options are `false` by default. + +### debug + +Dump a ton of stuff to stderr. + +### nobrace + +Do not expand `{a,b}` and `{1..3}` brace sets. + +### noglobstar + +Disable `**` matching against multiple folder names. + +### dot + +Allow patterns to match filenames starting with a period, even if +the pattern does not explicitly have a period in that spot. + +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` +is set. + +### noext + +Disable "extglob" style patterns like `+(a|b)`. + +### nocase + +Perform a case-insensitive match. + +### nocaseMagicOnly + +When used with `{nocase: true}`, create regular expressions that +are case-insensitive, but leave string match portions untouched. +Has no effect when used without `{nocase: true}` + +Useful when some other form of case-insensitive matching is used, +or if the original string representation is useful in some other +way. + +### nonull + +When a match is not found by `minimatch.match`, return a list containing +the pattern itself if this option is set. When not set, an empty list +is returned if there are no matches. + +### magicalBraces + +This only affects the results of the `Minimatch.hasMagic` method. + +If the pattern contains brace expansions, such as `a{b,c}d`, but +no other magic characters, then the `Minimatch.hasMagic()` method +will return `false` by default. When this option set, it will +return `true` for brace expansion as well as other magic glob +characters. + +### matchBase + +If set, then patterns without slashes will be matched +against the basename of the path if it contains slashes. For example, +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. + +### nocomment + +Suppress the behavior of treating `#` at the start of a pattern as a +comment. + +### nonegate + +Suppress the behavior of treating a leading `!` character as negation. + +### flipNegate + +Returns from negate expressions the same as if they were not negated. +(Ie, true on a hit, false on a miss.) + +### partial + +Compare a partial path to a pattern. As long as the parts of the path that +are present are not contradicted by the pattern, it will be treated as a +match. This is useful in applications where you're walking through a +folder structure, and don't yet have the full path, but want to ensure that +you do not walk down paths that can never be a match. + +For example, + +```js +minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d +minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d +minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a +``` + +### windowsPathsNoEscape + +Use `\\` as a path separator _only_, and _never_ as an escape +character. If set, all `\\` characters are replaced with `/` in +the pattern. Note that this makes it **impossible** to match +against paths containing literal glob pattern characters, but +allows matching with patterns constructed using `path.join()` and +`path.resolve()` on Windows platforms, mimicking the (buggy!) +behavior of earlier versions on Windows. Please use with +caution, and be mindful of [the caveat about Windows +paths](#windows). + +For legacy reasons, this is also set if +`options.allowWindowsEscape` is set to the exact value `false`. + +### windowsNoMagicRoot + +When a pattern starts with a UNC path or drive letter, and in +`nocase:true` mode, do not convert the root portions of the +pattern into a case-insensitive regular expression, and instead +leave them as strings. + +This is the default when the platform is `win32` and +`nocase:true` is set. + +### preserveMultipleSlashes + +By default, multiple `/` characters (other than the leading `//` +in a UNC path, see "UNC Paths" above) are treated as a single +`/`. + +That is, a pattern like `a///b` will match the file path `a/b`. + +Set `preserveMultipleSlashes: true` to suppress this behavior. + +### optimizationLevel + +A number indicating the level of optimization that should be done +to the pattern prior to parsing and using it for matches. + +Globstar parts `**` are always converted to `*` when `noglobstar` +is set, and multiple adjacent `**` parts are converted into a +single `**` (ie, `a/**/**/b` will be treated as `a/**/b`, as this +is equivalent in all cases). + +- `0` - Make no further changes. In this mode, `.` and `..` are + maintained in the pattern, meaning that they must also appear + in the same position in the test path string. Eg, a pattern + like `a/*/../c` will match the string `a/b/../c` but not the + string `a/c`. +- `1` - (default) Remove cases where a double-dot `..` follows a + pattern portion that is not `**`, `.`, `..`, or empty `''`. For + example, the pattern `./a/b/../*` is converted to `./a/*`, and + so it will match the path string `./a/c`, but not the path + string `./a/b/../c`. Dots and empty path portions in the + pattern are preserved. +- `2` (or higher) - Much more aggressive optimizations, suitable + for use with file-walking cases: + + - Remove cases where a double-dot `..` follows a pattern + portion that is not `**`, `.`, or empty `''`. Remove empty + and `.` portions of the pattern, where safe to do so (ie, + anywhere other than the last position, the first position, or + the second position in a pattern starting with `/`, as this + may indicate a UNC path on Windows). + - Convert patterns containing `
/**/../

/` into the + equivalent `

/{..,**}/

/`, where `

` is a + a pattern portion other than `.`, `..`, `**`, or empty + `''`. + - Dedupe patterns where a `**` portion is present in one and + omitted in another, and it is not the final path portion, and + they are otherwise equivalent. So `{a/**/b,a/b}` becomes + `a/**/b`, because `**` matches against an empty path portion. + - Dedupe patterns where a `*` portion is present in one, and a + non-dot pattern other than `**`, `.`, `..`, or `''` is in the + same position in the other. So `a/{*,x}/b` becomes `a/*/b`, + because `*` can match against `x`. + + While these optimizations improve the performance of + file-walking use cases such as [glob](http://npm.im/glob) (ie, + the reason this module exists), there are cases where it will + fail to match a literal string that would have been matched in + optimization level 1 or 0. + + Specifically, while the `Minimatch.match()` method will + optimize the file path string in the same ways, resulting in + the same matches, it will fail when tested with the regular + expression provided by `Minimatch.makeRe()`, unless the path + string is first processed with + `minimatch.levelTwoFileOptimize()` or similar. + +### platform + +When set to `win32`, this will trigger all windows-specific +behaviors (special handling for UNC paths, and treating `\` as +separators in file paths for comparison.) + +Defaults to the value of `process.platform`. + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a +worthwhile goal, some discrepancies exist between minimatch and +other implementations. Some are intentional, and some are +unavoidable. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.1, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then minimatch.match returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. + +Negated extglob patterns are handled as closely as possible to +Bash semantics, but there are some cases with negative extglobs +which are exceedingly difficult to express in a JavaScript +regular expression. In particular the negated pattern +`!(*|)*` will in bash match anything that does +not start with ``. However, +`!(*)*` _will_ match paths starting with +``, because the empty string can match against +the negated portion. In this library, `!(*|)*` +will _not_ match any pattern starting with ``, due to a +difference in precisely which patterns are considered "greedy" in +Regular Expressions vs bash path expansion. This may be fixable, +but not without incurring some complexity and performance costs, +and the trade-off seems to not be worth pursuing. + +Note that `fnmatch(3)` in libc is an extremely naive string comparison +matcher, which does not do anything special for slashes. This library is +designed to be used in glob searching and file walkers, and so it does do +special things with `/`. Thus, `foo*` will not match `foo/bar` in this +library, even though it would in `fnmatch(3)`. diff --git a/node_modules/minimatch/dist/commonjs/assert-valid-pattern.d.ts b/node_modules/minimatch/dist/commonjs/assert-valid-pattern.d.ts new file mode 100644 index 0000000..8e318b2 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/assert-valid-pattern.d.ts @@ -0,0 +1,2 @@ +export declare const assertValidPattern: (pattern: any) => void; +//# sourceMappingURL=assert-valid-pattern.d.ts.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/assert-valid-pattern.d.ts.map b/node_modules/minimatch/dist/commonjs/assert-valid-pattern.d.ts.map new file mode 100644 index 0000000..c61c031 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/assert-valid-pattern.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"assert-valid-pattern.d.ts","sourceRoot":"","sources":["../../src/assert-valid-pattern.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,kBAAkB,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,IAUlD,CAAA"} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js b/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js new file mode 100644 index 0000000..5fc86bb --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.assertValidPattern = void 0; +const MAX_PATTERN_LENGTH = 1024 * 64; +const assertValidPattern = (pattern) => { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern'); + } + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long'); + } +}; +exports.assertValidPattern = assertValidPattern; +//# sourceMappingURL=assert-valid-pattern.js.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js.map b/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js.map new file mode 100644 index 0000000..d43215c --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js.map @@ -0,0 +1 @@ +{"version":3,"file":"assert-valid-pattern.js","sourceRoot":"","sources":["../../src/assert-valid-pattern.ts"],"names":[],"mappings":";;;AAAA,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAE,CAAA;AAC7B,MAAM,kBAAkB,GAA2B,CACxD,OAAY,EACe,EAAE;IAC7B,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;QAC/B,MAAM,IAAI,SAAS,CAAC,iBAAiB,CAAC,CAAA;KACvC;IAED,IAAI,OAAO,CAAC,MAAM,GAAG,kBAAkB,EAAE;QACvC,MAAM,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAA;KAC3C;AACH,CAAC,CAAA;AAVY,QAAA,kBAAkB,sBAU9B","sourcesContent":["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"]} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/ast.d.ts b/node_modules/minimatch/dist/commonjs/ast.d.ts new file mode 100644 index 0000000..b8c1e54 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/ast.d.ts @@ -0,0 +1,20 @@ +import { MinimatchOptions, MMRegExp } from './index.js'; +export type ExtglobType = '!' | '?' | '+' | '*' | '@'; +export declare class AST { + #private; + type: ExtglobType | null; + constructor(type: ExtglobType | null, parent?: AST, options?: MinimatchOptions); + get hasMagic(): boolean | undefined; + toString(): string; + push(...parts: (string | AST)[]): void; + toJSON(): any[]; + isStart(): boolean; + isEnd(): boolean; + copyIn(part: AST | string): void; + clone(parent: AST): AST; + static fromGlob(pattern: string, options?: MinimatchOptions): AST; + toMMPattern(): MMRegExp | string; + get options(): MinimatchOptions; + toRegExpSource(allowDot?: boolean): [re: string, body: string, hasMagic: boolean, uflag: boolean]; +} +//# sourceMappingURL=ast.d.ts.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/ast.d.ts.map b/node_modules/minimatch/dist/commonjs/ast.d.ts.map new file mode 100644 index 0000000..9e7bfb9 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/ast.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../src/ast.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAwCvD,MAAM,MAAM,WAAW,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAA;AAkCrD,qBAAa,GAAG;;IACd,IAAI,EAAE,WAAW,GAAG,IAAI,CAAA;gBAiBtB,IAAI,EAAE,WAAW,GAAG,IAAI,EACxB,MAAM,CAAC,EAAE,GAAG,EACZ,OAAO,GAAE,gBAAqB;IAahC,IAAI,QAAQ,IAAI,OAAO,GAAG,SAAS,CAUlC;IAGD,QAAQ,IAAI,MAAM;IA+ClB,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,MAAM,GAAG,GAAG,CAAC,EAAE;IAY/B,MAAM;IAgBN,OAAO,IAAI,OAAO;IAgBlB,KAAK,IAAI,OAAO;IAYhB,MAAM,CAAC,IAAI,EAAE,GAAG,GAAG,MAAM;IAKzB,KAAK,CAAC,MAAM,EAAE,GAAG;IAsIjB,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB;IAQ/D,WAAW,IAAI,QAAQ,GAAG,MAAM;IA2BhC,IAAI,OAAO,qBAEV;IAuED,cAAc,CACZ,QAAQ,CAAC,EAAE,OAAO,GACjB,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC;CAiMjE"} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/ast.js b/node_modules/minimatch/dist/commonjs/ast.js new file mode 100644 index 0000000..7b21096 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/ast.js @@ -0,0 +1,592 @@ +"use strict"; +// parse a single path portion +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AST = void 0; +const brace_expressions_js_1 = require("./brace-expressions.js"); +const unescape_js_1 = require("./unescape.js"); +const types = new Set(['!', '?', '+', '*', '@']); +const isExtglobType = (c) => types.has(c); +// Patterns that get prepended to bind to the start of either the +// entire string, or just a single path portion, to prevent dots +// and/or traversal patterns, when needed. +// Exts don't need the ^ or / bit, because the root binds that already. +const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))'; +const startNoDot = '(?!\\.)'; +// characters that indicate a start of pattern needs the "no dots" bit, +// because a dot *might* be matched. ( is not in the list, because in +// the case of a child extglob, it will handle the prevention itself. +const addPatternStart = new Set(['[', '.']); +// cases where traversal is A-OK, no dot prevention needed +const justDots = new Set(['..', '.']); +const reSpecials = new Set('().*{}+?[]^$\\!'); +const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); +// any single thing other than / +const qmark = '[^/]'; +// * => any number of characters +const star = qmark + '*?'; +// use + when we need to ensure that *something* matches, because the * is +// the only thing in the path portion. +const starNoEmpty = qmark + '+?'; +// remove the \ chars that we added if we end up doing a nonmagic compare +// const deslash = (s: string) => s.replace(/\\(.)/g, '$1') +class AST { + type; + #root; + #hasMagic; + #uflag = false; + #parts = []; + #parent; + #parentIndex; + #negs; + #filledNegs = false; + #options; + #toString; + // set to true if it's an extglob with no children + // (which really means one child of '') + #emptyExt = false; + constructor(type, parent, options = {}) { + this.type = type; + // extglobs are inherently magical + if (type) + this.#hasMagic = true; + this.#parent = parent; + this.#root = this.#parent ? this.#parent.#root : this; + this.#options = this.#root === this ? options : this.#root.#options; + this.#negs = this.#root === this ? [] : this.#root.#negs; + if (type === '!' && !this.#root.#filledNegs) + this.#negs.push(this); + this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0; + } + get hasMagic() { + /* c8 ignore start */ + if (this.#hasMagic !== undefined) + return this.#hasMagic; + /* c8 ignore stop */ + for (const p of this.#parts) { + if (typeof p === 'string') + continue; + if (p.type || p.hasMagic) + return (this.#hasMagic = true); + } + // note: will be undefined until we generate the regexp src and find out + return this.#hasMagic; + } + // reconstructs the pattern + toString() { + if (this.#toString !== undefined) + return this.#toString; + if (!this.type) { + return (this.#toString = this.#parts.map(p => String(p)).join('')); + } + else { + return (this.#toString = + this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')'); + } + } + #fillNegs() { + /* c8 ignore start */ + if (this !== this.#root) + throw new Error('should only call on root'); + if (this.#filledNegs) + return this; + /* c8 ignore stop */ + // call toString() once to fill this out + this.toString(); + this.#filledNegs = true; + let n; + while ((n = this.#negs.pop())) { + if (n.type !== '!') + continue; + // walk up the tree, appending everthing that comes AFTER parentIndex + let p = n; + let pp = p.#parent; + while (pp) { + for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) { + for (const part of n.#parts) { + /* c8 ignore start */ + if (typeof part === 'string') { + throw new Error('string part in extglob AST??'); + } + /* c8 ignore stop */ + part.copyIn(pp.#parts[i]); + } + } + p = pp; + pp = p.#parent; + } + } + return this; + } + push(...parts) { + for (const p of parts) { + if (p === '') + continue; + /* c8 ignore start */ + if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) { + throw new Error('invalid part: ' + p); + } + /* c8 ignore stop */ + this.#parts.push(p); + } + } + toJSON() { + const ret = this.type === null + ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON())) + : [this.type, ...this.#parts.map(p => p.toJSON())]; + if (this.isStart() && !this.type) + ret.unshift([]); + if (this.isEnd() && + (this === this.#root || + (this.#root.#filledNegs && this.#parent?.type === '!'))) { + ret.push({}); + } + return ret; + } + isStart() { + if (this.#root === this) + return true; + // if (this.type) return !!this.#parent?.isStart() + if (!this.#parent?.isStart()) + return false; + if (this.#parentIndex === 0) + return true; + // if everything AHEAD of this is a negation, then it's still the "start" + const p = this.#parent; + for (let i = 0; i < this.#parentIndex; i++) { + const pp = p.#parts[i]; + if (!(pp instanceof AST && pp.type === '!')) { + return false; + } + } + return true; + } + isEnd() { + if (this.#root === this) + return true; + if (this.#parent?.type === '!') + return true; + if (!this.#parent?.isEnd()) + return false; + if (!this.type) + return this.#parent?.isEnd(); + // if not root, it'll always have a parent + /* c8 ignore start */ + const pl = this.#parent ? this.#parent.#parts.length : 0; + /* c8 ignore stop */ + return this.#parentIndex === pl - 1; + } + copyIn(part) { + if (typeof part === 'string') + this.push(part); + else + this.push(part.clone(this)); + } + clone(parent) { + const c = new AST(this.type, parent); + for (const p of this.#parts) { + c.copyIn(p); + } + return c; + } + static #parseAST(str, ast, pos, opt) { + let escaping = false; + let inBrace = false; + let braceStart = -1; + let braceNeg = false; + if (ast.type === null) { + // outside of a extglob, append until we find a start + let i = pos; + let acc = ''; + while (i < str.length) { + const c = str.charAt(i++); + // still accumulate escapes at this point, but we do ignore + // starts that are escaped + if (escaping || c === '\\') { + escaping = !escaping; + acc += c; + continue; + } + if (inBrace) { + if (i === braceStart + 1) { + if (c === '^' || c === '!') { + braceNeg = true; + } + } + else if (c === ']' && !(i === braceStart + 2 && braceNeg)) { + inBrace = false; + } + acc += c; + continue; + } + else if (c === '[') { + inBrace = true; + braceStart = i; + braceNeg = false; + acc += c; + continue; + } + if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') { + ast.push(acc); + acc = ''; + const ext = new AST(c, ast); + i = AST.#parseAST(str, ext, i, opt); + ast.push(ext); + continue; + } + acc += c; + } + ast.push(acc); + return i; + } + // some kind of extglob, pos is at the ( + // find the next | or ) + let i = pos + 1; + let part = new AST(null, ast); + const parts = []; + let acc = ''; + while (i < str.length) { + const c = str.charAt(i++); + // still accumulate escapes at this point, but we do ignore + // starts that are escaped + if (escaping || c === '\\') { + escaping = !escaping; + acc += c; + continue; + } + if (inBrace) { + if (i === braceStart + 1) { + if (c === '^' || c === '!') { + braceNeg = true; + } + } + else if (c === ']' && !(i === braceStart + 2 && braceNeg)) { + inBrace = false; + } + acc += c; + continue; + } + else if (c === '[') { + inBrace = true; + braceStart = i; + braceNeg = false; + acc += c; + continue; + } + if (isExtglobType(c) && str.charAt(i) === '(') { + part.push(acc); + acc = ''; + const ext = new AST(c, part); + part.push(ext); + i = AST.#parseAST(str, ext, i, opt); + continue; + } + if (c === '|') { + part.push(acc); + acc = ''; + parts.push(part); + part = new AST(null, ast); + continue; + } + if (c === ')') { + if (acc === '' && ast.#parts.length === 0) { + ast.#emptyExt = true; + } + part.push(acc); + acc = ''; + ast.push(...parts, part); + return i; + } + acc += c; + } + // unfinished extglob + // if we got here, it was a malformed extglob! not an extglob, but + // maybe something else in there. + ast.type = null; + ast.#hasMagic = undefined; + ast.#parts = [str.substring(pos - 1)]; + return i; + } + static fromGlob(pattern, options = {}) { + const ast = new AST(null, undefined, options); + AST.#parseAST(pattern, ast, 0, options); + return ast; + } + // returns the regular expression if there's magic, or the unescaped + // string if not. + toMMPattern() { + // should only be called on root + /* c8 ignore start */ + if (this !== this.#root) + return this.#root.toMMPattern(); + /* c8 ignore stop */ + const glob = this.toString(); + const [re, body, hasMagic, uflag] = this.toRegExpSource(); + // if we're in nocase mode, and not nocaseMagicOnly, then we do + // still need a regular expression if we have to case-insensitively + // match capital/lowercase characters. + const anyMagic = hasMagic || + this.#hasMagic || + (this.#options.nocase && + !this.#options.nocaseMagicOnly && + glob.toUpperCase() !== glob.toLowerCase()); + if (!anyMagic) { + return body; + } + const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : ''); + return Object.assign(new RegExp(`^${re}$`, flags), { + _src: re, + _glob: glob, + }); + } + get options() { + return this.#options; + } + // returns the string match, the regexp source, whether there's magic + // in the regexp (so a regular expression is required) and whether or + // not the uflag is needed for the regular expression (for posix classes) + // TODO: instead of injecting the start/end at this point, just return + // the BODY of the regexp, along with the start/end portions suitable + // for binding the start/end in either a joined full-path makeRe context + // (where we bind to (^|/), or a standalone matchPart context (where + // we bind to ^, and not /). Otherwise slashes get duped! + // + // In part-matching mode, the start is: + // - if not isStart: nothing + // - if traversal possible, but not allowed: ^(?!\.\.?$) + // - if dots allowed or not possible: ^ + // - if dots possible and not allowed: ^(?!\.) + // end is: + // - if not isEnd(): nothing + // - else: $ + // + // In full-path matching mode, we put the slash at the START of the + // pattern, so start is: + // - if first pattern: same as part-matching mode + // - if not isStart(): nothing + // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/)) + // - if dots allowed or not possible: / + // - if dots possible and not allowed: /(?!\.) + // end is: + // - if last pattern, same as part-matching mode + // - else nothing + // + // Always put the (?:$|/) on negated tails, though, because that has to be + // there to bind the end of the negated pattern portion, and it's easier to + // just stick it in now rather than try to inject it later in the middle of + // the pattern. + // + // We can just always return the same end, and leave it up to the caller + // to know whether it's going to be used joined or in parts. + // And, if the start is adjusted slightly, can do the same there: + // - if not isStart: nothing + // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$) + // - if dots allowed or not possible: (?:/|^) + // - if dots possible and not allowed: (?:/|^)(?!\.) + // + // But it's better to have a simpler binding without a conditional, for + // performance, so probably better to return both start options. + // + // Then the caller just ignores the end if it's not the first pattern, + // and the start always gets applied. + // + // But that's always going to be $ if it's the ending pattern, or nothing, + // so the caller can just attach $ at the end of the pattern when building. + // + // So the todo is: + // - better detect what kind of start is needed + // - return both flavors of starting pattern + // - attach $ at the end of the pattern when creating the actual RegExp + // + // Ah, but wait, no, that all only applies to the root when the first pattern + // is not an extglob. If the first pattern IS an extglob, then we need all + // that dot prevention biz to live in the extglob portions, because eg + // +(*|.x*) can match .xy but not .yx. + // + // So, return the two flavors if it's #root and the first child is not an + // AST, otherwise leave it to the child AST to handle it, and there, + // use the (?:^|/) style of start binding. + // + // Even simplified further: + // - Since the start for a join is eg /(?!\.) and the start for a part + // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root + // or start or whatever) and prepend ^ or / at the Regexp construction. + toRegExpSource(allowDot) { + const dot = allowDot ?? !!this.#options.dot; + if (this.#root === this) + this.#fillNegs(); + if (!this.type) { + const noEmpty = this.isStart() && this.isEnd(); + const src = this.#parts + .map(p => { + const [re, _, hasMagic, uflag] = typeof p === 'string' + ? AST.#parseGlob(p, this.#hasMagic, noEmpty) + : p.toRegExpSource(allowDot); + this.#hasMagic = this.#hasMagic || hasMagic; + this.#uflag = this.#uflag || uflag; + return re; + }) + .join(''); + let start = ''; + if (this.isStart()) { + if (typeof this.#parts[0] === 'string') { + // this is the string that will match the start of the pattern, + // so we need to protect against dots and such. + // '.' and '..' cannot match unless the pattern is that exactly, + // even if it starts with . or dot:true is set. + const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]); + if (!dotTravAllowed) { + const aps = addPatternStart; + // check if we have a possibility of matching . or .., + // and prevent that. + const needNoTrav = + // dots are allowed, and the pattern starts with [ or . + (dot && aps.has(src.charAt(0))) || + // the pattern starts with \., and then [ or . + (src.startsWith('\\.') && aps.has(src.charAt(2))) || + // the pattern starts with \.\., and then [ or . + (src.startsWith('\\.\\.') && aps.has(src.charAt(4))); + // no need to prevent dots if it can't match a dot, or if a + // sub-pattern will be preventing it anyway. + const needNoDot = !dot && !allowDot && aps.has(src.charAt(0)); + start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ''; + } + } + } + // append the "end of path portion" pattern to negation tails + let end = ''; + if (this.isEnd() && + this.#root.#filledNegs && + this.#parent?.type === '!') { + end = '(?:$|\\/)'; + } + const final = start + src + end; + return [ + final, + (0, unescape_js_1.unescape)(src), + (this.#hasMagic = !!this.#hasMagic), + this.#uflag, + ]; + } + // We need to calculate the body *twice* if it's a repeat pattern + // at the start, once in nodot mode, then again in dot mode, so a + // pattern like *(?) can match 'x.y' + const repeated = this.type === '*' || this.type === '+'; + // some kind of extglob + const start = this.type === '!' ? '(?:(?!(?:' : '(?:'; + let body = this.#partsToRegExp(dot); + if (this.isStart() && this.isEnd() && !body && this.type !== '!') { + // invalid extglob, has to at least be *something* present, if it's + // the entire path portion. + const s = this.toString(); + this.#parts = [s]; + this.type = null; + this.#hasMagic = undefined; + return [s, (0, unescape_js_1.unescape)(this.toString()), false, false]; + } + // XXX abstract out this map method + let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot + ? '' + : this.#partsToRegExp(true); + if (bodyDotAllowed === body) { + bodyDotAllowed = ''; + } + if (bodyDotAllowed) { + body = `(?:${body})(?:${bodyDotAllowed})*?`; + } + // an empty !() is exactly equivalent to a starNoEmpty + let final = ''; + if (this.type === '!' && this.#emptyExt) { + final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty; + } + else { + const close = this.type === '!' + ? // !() must match something,but !(x) can match '' + '))' + + (this.isStart() && !dot && !allowDot ? startNoDot : '') + + star + + ')' + : this.type === '@' + ? ')' + : this.type === '?' + ? ')?' + : this.type === '+' && bodyDotAllowed + ? ')' + : this.type === '*' && bodyDotAllowed + ? `)?` + : `)${this.type}`; + final = start + body + close; + } + return [ + final, + (0, unescape_js_1.unescape)(body), + (this.#hasMagic = !!this.#hasMagic), + this.#uflag, + ]; + } + #partsToRegExp(dot) { + return this.#parts + .map(p => { + // extglob ASTs should only contain parent ASTs + /* c8 ignore start */ + if (typeof p === 'string') { + throw new Error('string type in extglob ast??'); + } + /* c8 ignore stop */ + // can ignore hasMagic, because extglobs are already always magic + const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot); + this.#uflag = this.#uflag || uflag; + return re; + }) + .filter(p => !(this.isStart() && this.isEnd()) || !!p) + .join('|'); + } + static #parseGlob(glob, hasMagic, noEmpty = false) { + let escaping = false; + let re = ''; + let uflag = false; + for (let i = 0; i < glob.length; i++) { + const c = glob.charAt(i); + if (escaping) { + escaping = false; + re += (reSpecials.has(c) ? '\\' : '') + c; + continue; + } + if (c === '\\') { + if (i === glob.length - 1) { + re += '\\\\'; + } + else { + escaping = true; + } + continue; + } + if (c === '[') { + const [src, needUflag, consumed, magic] = (0, brace_expressions_js_1.parseClass)(glob, i); + if (consumed) { + re += src; + uflag = uflag || needUflag; + i += consumed - 1; + hasMagic = hasMagic || magic; + continue; + } + } + if (c === '*') { + if (noEmpty && glob === '*') + re += starNoEmpty; + else + re += star; + hasMagic = true; + continue; + } + if (c === '?') { + re += qmark; + hasMagic = true; + continue; + } + re += regExpEscape(c); + } + return [re, (0, unescape_js_1.unescape)(glob), !!hasMagic, uflag]; + } +} +exports.AST = AST; +//# sourceMappingURL=ast.js.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/ast.js.map b/node_modules/minimatch/dist/commonjs/ast.js.map new file mode 100644 index 0000000..8383e43 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/ast.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ast.js","sourceRoot":"","sources":["../../src/ast.ts"],"names":[],"mappings":";AAAA,8BAA8B;;;AAE9B,iEAAmD;AAEnD,+CAAwC;AAwCxC,MAAM,KAAK,GAAG,IAAI,GAAG,CAAc,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAA;AAC7D,MAAM,aAAa,GAAG,CAAC,CAAS,EAAoB,EAAE,CACpD,KAAK,CAAC,GAAG,CAAC,CAAgB,CAAC,CAAA;AAE7B,iEAAiE;AACjE,gEAAgE;AAChE,0CAA0C;AAC1C,uEAAuE;AACvE,MAAM,gBAAgB,GAAG,2BAA2B,CAAA;AACpD,MAAM,UAAU,GAAG,SAAS,CAAA;AAE5B,uEAAuE;AACvE,qEAAqE;AACrE,qEAAqE;AACrE,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAA;AAC3C,0DAA0D;AAC1D,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;AACrC,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC,iBAAiB,CAAC,CAAA;AAC7C,MAAM,YAAY,GAAG,CAAC,CAAS,EAAE,EAAE,CACjC,CAAC,CAAC,OAAO,CAAC,0BAA0B,EAAE,MAAM,CAAC,CAAA;AAE/C,gCAAgC;AAChC,MAAM,KAAK,GAAG,MAAM,CAAA;AAEpB,gCAAgC;AAChC,MAAM,IA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CAAC,CAAA;SACtB;QACD,OAAO,CAAC,EAAE,EAAE,IAAA,sBAAQ,EAAC,IAAI,CAAC,EAAE,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAA;IAChD,CAAC;CACF;AA/kBD,kBA+kBC","sourcesContent":["// 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 get options() {\n return this.#options\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"]} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts b/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts new file mode 100644 index 0000000..b1572de --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts @@ -0,0 +1,8 @@ +export type ParseClassResult = [ + src: string, + uFlag: boolean, + consumed: number, + hasMagic: boolean +]; +export declare const parseClass: (glob: string, position: number) => ParseClassResult; +//# sourceMappingURL=brace-expressions.d.ts.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts.map b/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts.map new file mode 100644 index 0000000..d394964 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/brace-expressions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"brace-expressions.d.ts","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":"AA+BA,MAAM,MAAM,gBAAgB,GAAG;IAC7B,GAAG,EAAE,MAAM;IACX,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,MAAM;IAChB,QAAQ,EAAE,OAAO;CAClB,CAAA;AAQD,eAAO,MAAM,UAAU,SACf,MAAM,YACF,MAAM,qBA8HjB,CAAA"} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/brace-expressions.js b/node_modules/minimatch/dist/commonjs/brace-expressions.js new file mode 100644 index 0000000..0e13eef --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/brace-expressions.js @@ -0,0 +1,152 @@ +"use strict"; +// translate the various posix character classes into unicode properties +// this works across all unicode locales +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseClass = void 0; +// { : [, /u flag required, negated] +const posixClasses = { + '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true], + '[:alpha:]': ['\\p{L}\\p{Nl}', true], + '[:ascii:]': ['\\x' + '00-\\x' + '7f', false], + '[:blank:]': ['\\p{Zs}\\t', true], + '[:cntrl:]': ['\\p{Cc}', true], + '[:digit:]': ['\\p{Nd}', true], + '[:graph:]': ['\\p{Z}\\p{C}', true, true], + '[:lower:]': ['\\p{Ll}', true], + '[:print:]': ['\\p{C}', true], + '[:punct:]': ['\\p{P}', true], + '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true], + '[:upper:]': ['\\p{Lu}', true], + '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true], + '[:xdigit:]': ['A-Fa-f0-9', false], +}; +// only need to escape a few things inside of brace expressions +// escapes: [ \ ] - +const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&'); +// escape all regexp magic characters +const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); +// everything has already been escaped, we just have to join +const rangesToString = (ranges) => ranges.join(''); +// takes a glob string at a posix brace expression, and returns +// an equivalent regular expression source, and boolean indicating +// whether the /u flag needs to be applied, and the number of chars +// consumed to parse the character class. +// This also removes out of order ranges, and returns ($.) if the +// entire class just no good. +const parseClass = (glob, position) => { + const pos = position; + /* c8 ignore start */ + if (glob.charAt(pos) !== '[') { + throw new Error('not in a brace expression'); + } + /* c8 ignore stop */ + const ranges = []; + const negs = []; + let i = pos + 1; + let sawStart = false; + let uflag = false; + let escaping = false; + let negate = false; + let endPos = pos; + let rangeStart = ''; + WHILE: while (i < glob.length) { + const c = glob.charAt(i); + if ((c === '!' || c === '^') && i === pos + 1) { + negate = true; + i++; + continue; + } + if (c === ']' && sawStart && !escaping) { + endPos = i + 1; + break; + } + sawStart = true; + if (c === '\\') { + if (!escaping) { + escaping = true; + i++; + continue; + } + // escaped \ char, fall through and treat like normal char + } + if (c === '[' && !escaping) { + // either a posix class, a collation equivalent, or just a [ + for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) { + if (glob.startsWith(cls, i)) { + // invalid, [a-[] is fine, but not [a-[:alpha]] + if (rangeStart) { + return ['$.', false, glob.length - pos, true]; + } + i += cls.length; + if (neg) + negs.push(unip); + else + ranges.push(unip); + uflag = uflag || u; + continue WHILE; + } + } + } + // now it's just a normal character, effectively + escaping = false; + if (rangeStart) { + // throw this range away if it's not valid, but others + // can still match. + if (c > rangeStart) { + ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c)); + } + else if (c === rangeStart) { + ranges.push(braceEscape(c)); + } + rangeStart = ''; + i++; + continue; + } + // now might be the start of a range. + // can be either c-d or c-] or c] or c] at this point + if (glob.startsWith('-]', i + 1)) { + ranges.push(braceEscape(c + '-')); + i += 2; + continue; + } + if (glob.startsWith('-', i + 1)) { + rangeStart = c; + i += 2; + continue; + } + // not the start of a range, just a single character + ranges.push(braceEscape(c)); + i++; + } + if (endPos < i) { + // didn't see the end of the class, not a valid class, + // but might still be valid as a literal match. + return ['', false, 0, false]; + } + // if we got no ranges and no negates, then we have a range that + // cannot possibly match anything, and that poisons the whole glob + if (!ranges.length && !negs.length) { + return ['$.', false, glob.length - pos, true]; + } + // if we got one positive range, and it's a single character, then that's + // not actually a magic pattern, it's just that one literal character. + // we should not treat that as "magic", we should just return the literal + // character. [_] is a perfectly valid way to escape glob magic chars. + if (negs.length === 0 && + ranges.length === 1 && + /^\\?.$/.test(ranges[0]) && + !negate) { + const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]; + return [regexpEscape(r), false, endPos - pos, false]; + } + const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'; + const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'; + const comb = ranges.length && negs.length + ? '(' + sranges + '|' + snegs + ')' + : ranges.length + ? sranges + : snegs; + return [comb, uflag, endPos - pos, true]; +}; +exports.parseClass = parseClass; +//# sourceMappingURL=brace-expressions.js.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/brace-expressions.js.map b/node_modules/minimatch/dist/commonjs/brace-expressions.js.map new file mode 100644 index 0000000..86b0475 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/brace-expressions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"brace-expressions.js","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":";AAAA,wEAAwE;AACxE,wCAAwC;;;AAExC,8DAA8D;AAC9D,MAAM,YAAY,GAA0D;IAC1E,WAAW,EAAE,CAAC,sBAAsB,EAAE,IAAI,CAAC;IAC3C,WAAW,EAAE,CAAC,eAAe,EAAE,IAAI,CAAC;IACpC,WAAW,EAAE,CAAC,KAAK,GAAG,QAAQ,GAAG,IAAI,EAAE,KAAK,CAAC;IAC7C,WAAW,EAAE,CAAC,YAAY,EAAE,IAAI,CAA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,IAAI,CAAC,GAAG,GAAG,CAAA;IACpE,MAAM,IAAI,GACR,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM;QAC1B,CAAC,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,GAAG,KAAK,GAAG,GAAG;QACnC,CAAC,CAAC,MAAM,CAAC,MAAM;YACf,CAAC,CAAC,OAAO;YACT,CAAC,CAAC,KAAK,CAAA;IAEX,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,CAAA;AAC1C,CAAC,CAAA;AAhIY,QAAA,UAAU,cAgItB","sourcesContent":["// 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"]} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/escape.d.ts b/node_modules/minimatch/dist/commonjs/escape.d.ts new file mode 100644 index 0000000..dc3e316 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/escape.d.ts @@ -0,0 +1,12 @@ +import { MinimatchOptions } from './index.js'; +/** + * Escape all magic characters in a glob pattern. + * + * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape} + * option is used, then characters are escaped by wrapping in `[]`, because + * a magic character wrapped in a character class can only be satisfied by + * that exact character. In this mode, `\` is _not_ escaped, because it is + * not interpreted as a magic character, but instead as a path separator. + */ +export declare const escape: (s: string, { windowsPathsNoEscape, }?: Pick) => string; +//# sourceMappingURL=escape.d.ts.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/escape.d.ts.map b/node_modules/minimatch/dist/commonjs/escape.d.ts.map new file mode 100644 index 0000000..0779dae --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/escape.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"escape.d.ts","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAC7C;;;;;;;;GAQG;AACH,eAAO,MAAM,MAAM,MACd,MAAM,8BAGN,KAAK,gBAAgB,EAAE,sBAAsB,CAAC,WAQlD,CAAA"} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/escape.js b/node_modules/minimatch/dist/commonjs/escape.js new file mode 100644 index 0000000..02a4f8a --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/escape.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.escape = void 0; +/** + * Escape all magic characters in a glob pattern. + * + * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape} + * option is used, then characters are escaped by wrapping in `[]`, because + * a magic character wrapped in a character class can only be satisfied by + * that exact character. In this mode, `\` is _not_ escaped, because it is + * not interpreted as a magic character, but instead as a path separator. + */ +const escape = (s, { windowsPathsNoEscape = false, } = {}) => { + // don't need to escape +@! because we escape the parens + // that make those magic, and escaping ! as [!] isn't valid, + // because [!]] is a valid glob class meaning not ']'. + return windowsPathsNoEscape + ? s.replace(/[?*()[\]]/g, '[$&]') + : s.replace(/[?*()[\]\\]/g, '\\$&'); +}; +exports.escape = escape; +//# sourceMappingURL=escape.js.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/escape.js.map b/node_modules/minimatch/dist/commonjs/escape.js.map new file mode 100644 index 0000000..264b2ea --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/escape.js.map @@ -0,0 +1 @@ +{"version":3,"file":"escape.js","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":";;;AACA;;;;;;;;GAQG;AACI,MAAM,MAAM,GAAG,CACpB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,MACsB,EAAE,EACtD,EAAE;IACF,wDAAwD;IACxD,4DAA4D;IAC5D,sDAAsD;IACtD,OAAO,oBAAoB;QACzB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC;QACjC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;AACvC,CAAC,CAAA;AAZY,QAAA,MAAM,UAYlB","sourcesContent":["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"]} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/index.d.ts b/node_modules/minimatch/dist/commonjs/index.d.ts new file mode 100644 index 0000000..41d16a9 --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/index.d.ts @@ -0,0 +1,94 @@ +import { AST } from './ast.js'; +type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd'; +export interface MinimatchOptions { + nobrace?: boolean; + nocomment?: boolean; + nonegate?: boolean; + debug?: boolean; + noglobstar?: boolean; + noext?: boolean; + nonull?: boolean; + windowsPathsNoEscape?: boolean; + allowWindowsEscape?: boolean; + partial?: boolean; + dot?: boolean; + nocase?: boolean; + nocaseMagicOnly?: boolean; + magicalBraces?: boolean; + matchBase?: boolean; + flipNegate?: boolean; + preserveMultipleSlashes?: boolean; + optimizationLevel?: number; + platform?: Platform; + windowsNoMagicRoot?: boolean; +} +export declare const minimatch: { + (p: string, pattern: string, options?: MinimatchOptions): boolean; + sep: Sep; + GLOBSTAR: typeof GLOBSTAR; + filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean; + defaults: (def: MinimatchOptions) => typeof minimatch; + braceExpand: (pattern: string, options?: MinimatchOptions) => string[]; + makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp; + match: (list: string[], pattern: string, options?: MinimatchOptions) => string[]; + AST: typeof AST; + Minimatch: typeof Minimatch; + escape: (s: string, { windowsPathsNoEscape, }?: Pick) => string; + unescape: (s: string, { windowsPathsNoEscape, }?: Pick) => string; +}; +type Sep = '\\' | '/'; +export declare const sep: Sep; +export declare const GLOBSTAR: unique symbol; +export declare const filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean; +export declare const defaults: (def: MinimatchOptions) => typeof minimatch; +export declare const braceExpand: (pattern: string, options?: MinimatchOptions) => string[]; +export declare const makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp; +export declare const match: (list: string[], pattern: string, options?: MinimatchOptions) => string[]; +export type MMRegExp = RegExp & { + _src?: string; + _glob?: string; +}; +export type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR; +export type ParseReturn = ParseReturnFiltered | false; +export declare class Minimatch { + options: MinimatchOptions; + set: ParseReturnFiltered[][]; + pattern: string; + windowsPathsNoEscape: boolean; + nonegate: boolean; + negate: boolean; + comment: boolean; + empty: boolean; + preserveMultipleSlashes: boolean; + partial: boolean; + globSet: string[]; + globParts: string[][]; + nocase: boolean; + isWindows: boolean; + platform: Platform; + windowsNoMagicRoot: boolean; + regexp: false | null | MMRegExp; + constructor(pattern: string, options?: MinimatchOptions); + hasMagic(): boolean; + debug(..._: any[]): void; + make(): void; + preprocess(globParts: string[][]): string[][]; + adjascentGlobstarOptimize(globParts: string[][]): string[][]; + levelOneOptimize(globParts: string[][]): string[][]; + levelTwoFileOptimize(parts: string | string[]): string[]; + firstPhasePreProcess(globParts: string[][]): string[][]; + secondPhasePreProcess(globParts: string[][]): string[][]; + partsMatch(a: string[], b: string[], emptyGSMatch?: boolean): false | string[]; + parseNegate(): void; + matchOne(file: string[], pattern: ParseReturn[], partial?: boolean): boolean; + braceExpand(): string[]; + parse(pattern: string): ParseReturn; + makeRe(): false | MMRegExp; + slashSplit(p: string): string[]; + match(f: string, partial?: boolean): boolean; + static defaults(def: MinimatchOptions): typeof Minimatch; +} +export { AST } from './ast.js'; +export { escape } from './escape.js'; +export { unescape } from './unescape.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/index.d.ts.map b/node_modules/minimatch/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000..195491d --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,GAAG,EAAe,MAAM,UAAU,CAAA;AAI3C,KAAK,QAAQ,GACT,KAAK,GACL,SAAS,GACT,QAAQ,GACR,SAAS,GACT,OAAO,GACP,OAAO,GACP,SAAS,GACT,OAAO,GACP,OAAO,GACP,QAAQ,GACR,QAAQ,CAAA;AAEZ,MAAM,WAAW,gBAAgB;IAC/B,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,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AE;IA6D7C,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE;IA0F1C,qBAAqB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,GAAG,MAAM,EAAE,EAAE;IAkBxD,UAAU,CACR,CAAC,EAAE,MAAM,EAAE,EACX,CAAC,EAAE,MAAM,EAAE,EACX,YAAY,GAAE,OAAe,GAC5B,KAAK,GAAG,MAAM,EAAE;IA+CnB,WAAW;IAqBX,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,WAAW,EAAE,EAAE,OAAO,GAAE,OAAe;IAiNzE,WAAW;IAIX,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW;IAiDnC,MAAM;IAsFN,UAAU,CAAC,CAAC,EAAE,MAAM;IAepB,KAAK,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,UAAe;IAiEvC,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,gBAAgB;CAGtC;AAED,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAC9B,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA"} \ No newline at end of file diff --git a/node_modules/minimatch/dist/commonjs/index.js b/node_modules/minimatch/dist/commonjs/index.js new file mode 100644 index 0000000..64a0f1f --- /dev/null +++ b/node_modules/minimatch/dist/commonjs/index.js @@ -0,0 +1,1017 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unescape = exports.escape = exports.AST = exports.Minimatch = exports.match = exports.makeRe = exports.braceExpand = exports.defaults = exports.filter = exports.GLOBSTAR = exports.sep = exports.minimatch = void 0; +const brace_expansion_1 = __importDefault(require("brace-expansion")); +const assert_valid_pattern_js_1 = require("./assert-valid-pattern.js"); +const ast_js_1 = require("./ast.js"); +const escape_js_1 = require("./escape.js"); +const unescape_js_1 = require("./unescape.js"); +const minimatch = (p, pattern, options = {}) => { + (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false; + } + return new Minimatch(pattern, options).match(p); +}; +exports.minimatch = minimatch; +// Optimized checking for the most common glob patterns. +const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/; +const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext); +const starDotExtTestDot = (ext) => (f) => f.endsWith(ext); +const starDotExtTestNocase = (ext) => { + ext = ext.toLowerCase(); + return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext); +}; +const starDotExtTestNocaseDot = (ext) => { + ext = ext.toLowerCase(); + return (f) => f.toLowerCase().endsWith(ext); +}; +const starDotStarRE = /^\*+\.\*+$/; +const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.'); +const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.'); +const dotStarRE = /^\.\*+$/; +const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.'); +const starRE = /^\*+$/; +const starTest = (f) => f.length !== 0 && !f.startsWith('.'); +const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..'; +const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/; +const qmarksTestNocase = ([$0, ext = '']) => { + const noext = qmarksTestNoExt([$0]); + if (!ext) + return noext; + ext = ext.toLowerCase(); + return (f) => noext(f) && f.toLowerCase().endsWith(ext); +}; +const qmarksTestNocaseDot = ([$0, ext = '']) => { + const noext = qmarksTestNoExtDot([$0]); + if (!ext) + return noext; + ext = ext.toLowerCase(); + return (f) => noext(f) && f.toLowerCase().endsWith(ext); +}; +const qmarksTestDot = ([$0, ext = '']) => { + const noext = qmarksTestNoExtDot([$0]); + return !ext ? noext : (f) => noext(f) && f.endsWith(ext); +}; +const qmarksTest = ([$0, ext = '']) => { + const noext = qmarksTestNoExt([$0]); + return !ext ? noext : (f) => noext(f) && f.endsWith(ext); +}; +const qmarksTestNoExt = ([$0]) => { + const len = $0.length; + return (f) => f.length === len && !f.startsWith('.'); +}; +const qmarksTestNoExtDot = ([$0]) => { + const len = $0.length; + return (f) => f.length === len && f !== '.' && f !== '..'; +}; +/* c8 ignore start */ +const defaultPlatform = (typeof process === 'object' && process + ? (typeof process.env === 'object' && + process.env && + process.env.__MINIMATCH_TESTING_PLATFORM__) || + process.platform + : 'posix'); +const path = { + win32: { sep: '\\' }, + posix: { sep: '/' }, +}; +/* c8 ignore stop */ +exports.sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep; +exports.minimatch.sep = exports.sep; +exports.GLOBSTAR = Symbol('globstar **'); +exports.minimatch.GLOBSTAR = exports.GLOBSTAR; +// any single thing other than / +// don't need to escape / when using new RegExp() +const qmark = '[^/]'; +// * => any number of characters +const star = qmark + '*?'; +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?'; +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?'; +const filter = (pattern, options = {}) => (p) => (0, exports.minimatch)(p, pattern, options); +exports.filter = filter; +exports.minimatch.filter = exports.filter; +const ext = (a, b = {}) => Object.assign({}, a, b); +const defaults = (def) => { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return exports.minimatch; + } + const orig = exports.minimatch; + const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options)); + return Object.assign(m, { + Minimatch: class Minimatch extends orig.Minimatch { + constructor(pattern, options = {}) { + super(pattern, ext(def, options)); + } + static defaults(options) { + return orig.defaults(ext(def, options)).Minimatch; + } + }, + AST: class AST extends orig.AST { + /* c8 ignore start */ + constructor(type, parent, options = {}) { + super(type, parent, ext(def, options)); + } + /* c8 ignore stop */ + static fromGlob(pattern, options = {}) { + return orig.AST.fromGlob(pattern, ext(def, options)); + } + }, + unescape: (s, options = {}) => orig.unescape(s, ext(def, options)), + escape: (s, options = {}) => orig.escape(s, ext(def, options)), + filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)), + defaults: (options) => orig.defaults(ext(def, options)), + makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)), + braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)), + match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)), + sep: orig.sep, + GLOBSTAR: exports.GLOBSTAR, + }); +}; +exports.defaults = defaults; +exports.minimatch.defaults = exports.defaults; +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +const braceExpand = (pattern, options = {}) => { + (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern]; + } + return (0, brace_expansion_1.default)(pattern); +}; +exports.braceExpand = braceExpand; +exports.minimatch.braceExpand = exports.braceExpand; +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe(); +exports.makeRe = makeRe; +exports.minimatch.makeRe = exports.makeRe; +const match = (list, pattern, options = {}) => { + const mm = new Minimatch(pattern, options); + list = list.filter(f => mm.match(f)); + if (mm.options.nonull && !list.length) { + list.push(pattern); + } + return list; +}; +exports.match = match; +exports.minimatch.match = exports.match; +// replace stuff like \* with * +const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/; +const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); +class Minimatch { + options; + set; + pattern; + windowsPathsNoEscape; + nonegate; + negate; + comment; + empty; + preserveMultipleSlashes; + partial; + globSet; + globParts; + nocase; + isWindows; + platform; + windowsNoMagicRoot; + regexp; + constructor(pattern, options = {}) { + (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); + options = options || {}; + this.options = options; + this.pattern = pattern; + this.platform = options.platform || defaultPlatform; + this.isWindows = this.platform === 'win32'; + this.windowsPathsNoEscape = + !!options.windowsPathsNoEscape || options.allowWindowsEscape === false; + if (this.windowsPathsNoEscape) { + this.pattern = this.pattern.replace(/\\/g, '/'); + } + this.preserveMultipleSlashes = !!options.preserveMultipleSlashes; + this.regexp = null; + this.negate = false; + this.nonegate = !!options.nonegate; + this.comment = false; + this.empty = false; + this.partial = !!options.partial; + this.nocase = !!this.options.nocase; + this.windowsNoMagicRoot = + options.windowsNoMagicRoot !== undefined + ? options.windowsNoMagicRoot + : !!(this.isWindows && this.nocase); + this.globSet = []; + this.globParts = []; + this.set = []; + // make the set of regexps etc. + this.make(); + } + hasMagic() { + if (this.options.magicalBraces && this.set.length > 1) { + return true; + } + for (const pattern of this.set) { + for (const part of pattern) { + if (typeof part !== 'string') + return true; + } + } + return false; + } + debug(..._) { } + make() { + const pattern = this.pattern; + const options = this.options; + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true; + return; + } + if (!pattern) { + this.empty = true; + return; + } + // step 1: figure out negation, etc. + this.parseNegate(); + // step 2: expand braces + this.globSet = [...new Set(this.braceExpand())]; + if (options.debug) { + this.debug = (...args) => console.error(...args); + } + this.debug(this.pattern, this.globSet); + // step 3: now we have a set, so turn each one into a series of + // path-portion matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + // + // First, we preprocess to make the glob pattern sets a bit simpler + // and deduped. There are some perf-killing patterns that can cause + // problems with a glob walk, but we can simplify them down a bit. + const rawGlobParts = this.globSet.map(s => this.slashSplit(s)); + this.globParts = this.preprocess(rawGlobParts); + this.debug(this.pattern, this.globParts); + // glob --> regexps + let set = this.globParts.map((s, _, __) => { + if (this.isWindows && this.windowsNoMagicRoot) { + // check if it's a drive or unc path. + const isUNC = s[0] === '' && + s[1] === '' && + (s[2] === '?' || !globMagic.test(s[2])) && + !globMagic.test(s[3]); + const isDrive = /^[a-z]:/i.test(s[0]); + if (isUNC) { + return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))]; + } + else if (isDrive) { + return [s[0], ...s.slice(1).map(ss => this.parse(ss))]; + } + } + return s.map(ss => this.parse(ss)); + }); + this.debug(this.pattern, set); + // filter out everything that didn't compile properly. + this.set = set.filter(s => s.indexOf(false) === -1); + // do not treat the ? in UNC paths as magic + if (this.isWindows) { + for (let i = 0; i < this.set.length; i++) { + const p = this.set[i]; + if (p[0] === '' && + p[1] === '' && + this.globParts[i][2] === '?' && + typeof p[3] === 'string' && + /^[a-z]:$/i.test(p[3])) { + p[2] = '?'; + } + } + } + this.debug(this.pattern, this.set); + } + // various transforms to equivalent pattern sets that are + // faster to process in a filesystem walk. The goal is to + // eliminate what we can, and push all ** patterns as far + // to the right as possible, even if it increases the number + // of patterns that we have to process. + preprocess(globParts) { + // if we're not in globstar mode, then turn all ** into * + if (this.options.noglobstar) { + for (let i = 0; i < globParts.length; i++) { + for (let j = 0; j < globParts[i].length; j++) { + if (globParts[i][j] === '**') { + globParts[i][j] = '*'; + } + } + } + } + const { optimizationLevel = 1 } = this.options; + if (optimizationLevel >= 2) { + // aggressive optimization for the purpose of fs walking + globParts = this.firstPhasePreProcess(globParts); + globParts = this.secondPhasePreProcess(globParts); + } + else if (optimizationLevel >= 1) { + // just basic optimizations to remove some .. parts + globParts = this.levelOneOptimize(globParts); + } + else { + // just collapse multiple ** portions into one + globParts = this.adjascentGlobstarOptimize(globParts); + } + return globParts; + } + // just get rid of adjascent ** portions + adjascentGlobstarOptimize(globParts) { + return globParts.map(parts => { + let gs = -1; + while (-1 !== (gs = parts.indexOf('**', gs + 1))) { + let i = gs; + while (parts[i + 1] === '**') { + i++; + } + if (i !== gs) { + parts.splice(gs, i - gs); + } + } + return parts; + }); + } + // get rid of adjascent ** and resolve .. portions + levelOneOptimize(globParts) { + return globParts.map(parts => { + parts = parts.reduce((set, part) => { + const prev = set[set.length - 1]; + if (part === '**' && prev === '**') { + return set; + } + if (part === '..') { + if (prev && prev !== '..' && prev !== '.' && prev !== '**') { + set.pop(); + return set; + } + } + set.push(part); + return set; + }, []); + return parts.length === 0 ? [''] : parts; + }); + } + levelTwoFileOptimize(parts) { + if (!Array.isArray(parts)) { + parts = this.slashSplit(parts); + } + let didSomething = false; + do { + didSomething = false; + //

// -> 
/
+            if (!this.preserveMultipleSlashes) {
+                for (let i = 1; i < parts.length - 1; i++) {
+                    const p = parts[i];
+                    // don't squeeze out UNC patterns
+                    if (i === 1 && p === '' && parts[0] === '')
+                        continue;
+                    if (p === '.' || p === '') {
+                        didSomething = true;
+                        parts.splice(i, 1);
+                        i--;
+                    }
+                }
+                if (parts[0] === '.' &&
+                    parts.length === 2 &&
+                    (parts[1] === '.' || parts[1] === '')) {
+                    didSomething = true;
+                    parts.pop();
+                }
+            }
+            // 
/

/../ ->

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

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

/**/../

/

/ -> {

/../

/

/,

/**/

/

/} + //

// -> 
/
+    // 
/

/../ ->

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

/

/ -> {

/../

/

/,

/**/

/

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

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

/../ ->

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

/} ->

/*/
+    // {
/,
/} -> 
/
+    // {
/**/,
/} -> 
/**/
+    //
+    // {
/**/,
/**/

/} ->

/**/
+    // ^-- not valid because ** doens't follow symlinks
+    secondPhasePreProcess(globParts) {
+        for (let i = 0; i < globParts.length - 1; i++) {
+            for (let j = i + 1; j < globParts.length; j++) {
+                const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
+                if (matched) {
+                    globParts[i] = [];
+                    globParts[j] = matched;
+                    break;
+                }
+            }
+        }
+        return globParts.filter(gs => gs.length);
+    }
+    partsMatch(a, b, emptyGSMatch = false) {
+        let ai = 0;
+        let bi = 0;
+        let result = [];
+        let which = '';
+        while (ai < a.length && bi < b.length) {
+            if (a[ai] === b[bi]) {
+                result.push(which === 'b' ? b[bi] : a[ai]);
+                ai++;
+                bi++;
+            }
+            else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
+                result.push(a[ai]);
+                ai++;
+            }
+            else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
+                result.push(b[bi]);
+                bi++;
+            }
+            else if (a[ai] === '*' &&
+                b[bi] &&
+                (this.options.dot || !b[bi].startsWith('.')) &&
+                b[bi] !== '**') {
+                if (which === 'b')
+                    return false;
+                which = 'a';
+                result.push(a[ai]);
+                ai++;
+                bi++;
+            }
+            else if (b[bi] === '*' &&
+                a[ai] &&
+                (this.options.dot || !a[ai].startsWith('.')) &&
+                a[ai] !== '**') {
+                if (which === 'a')
+                    return false;
+                which = 'b';
+                result.push(b[bi]);
+                ai++;
+                bi++;
+            }
+            else {
+                return false;
+            }
+        }
+        // if we fall out of the loop, it means they two are identical
+        // as long as their lengths match
+        return a.length === b.length && result;
+    }
+    parseNegate() {
+        if (this.nonegate)
+            return;
+        const pattern = this.pattern;
+        let negate = false;
+        let negateOffset = 0;
+        for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
+            negate = !negate;
+            negateOffset++;
+        }
+        if (negateOffset)
+            this.pattern = pattern.slice(negateOffset);
+        this.negate = negate;
+    }
+    // set partial to true to test if, for example,
+    // "/a/b" matches the start of "/*/b/*/d"
+    // Partial means, if you run out of file before you run
+    // out of pattern, then that's fine, as long as all
+    // the parts match.
+    matchOne(file, pattern, partial = false) {
+        const options = this.options;
+        // UNC paths like //?/X:/... can match X:/... and vice versa
+        // Drive letters in absolute drive or unc paths are always compared
+        // case-insensitively.
+        if (this.isWindows) {
+            const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
+            const fileUNC = !fileDrive &&
+                file[0] === '' &&
+                file[1] === '' &&
+                file[2] === '?' &&
+                /^[a-z]:$/i.test(file[3]);
+            const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
+            const patternUNC = !patternDrive &&
+                pattern[0] === '' &&
+                pattern[1] === '' &&
+                pattern[2] === '?' &&
+                typeof pattern[3] === 'string' &&
+                /^[a-z]:$/i.test(pattern[3]);
+            const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
+            const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
+            if (typeof fdi === 'number' && typeof pdi === 'number') {
+                const [fd, pd] = [file[fdi], pattern[pdi]];
+                if (fd.toLowerCase() === pd.toLowerCase()) {
+                    pattern[pdi] = fd;
+                    if (pdi > fdi) {
+                        pattern = pattern.slice(pdi);
+                    }
+                    else if (fdi > pdi) {
+                        file = file.slice(fdi);
+                    }
+                }
+            }
+        }
+        // resolve and reduce . and .. portions in the file as well.
+        // dont' need to do the second phase, because it's only one string[]
+        const { optimizationLevel = 1 } = this.options;
+        if (optimizationLevel >= 2) {
+            file = this.levelTwoFileOptimize(file);
+        }
+        this.debug('matchOne', this, { file, pattern });
+        this.debug('matchOne', file.length, pattern.length);
+        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
+            this.debug('matchOne loop');
+            var p = pattern[pi];
+            var f = file[fi];
+            this.debug(pattern, p, f);
+            // should be impossible.
+            // some invalid regexp stuff in the set.
+            /* c8 ignore start */
+            if (p === false) {
+                return false;
+            }
+            /* c8 ignore stop */
+            if (p === exports.GLOBSTAR) {
+                this.debug('GLOBSTAR', [pattern, p, f]);
+                // "**"
+                // a/**/b/**/c would match the following:
+                // a/b/x/y/z/c
+                // a/x/y/z/b/c
+                // a/b/x/b/x/c
+                // a/b/c
+                // To do this, take the rest of the pattern after
+                // the **, and see if it would match the file remainder.
+                // If so, return success.
+                // If not, the ** "swallows" a segment, and try again.
+                // This is recursively awful.
+                //
+                // a/**/b/**/c matching a/b/x/y/z/c
+                // - a matches a
+                // - doublestar
+                //   - matchOne(b/x/y/z/c, b/**/c)
+                //     - b matches b
+                //     - doublestar
+                //       - matchOne(x/y/z/c, c) -> no
+                //       - matchOne(y/z/c, c) -> no
+                //       - matchOne(z/c, c) -> no
+                //       - matchOne(c, c) yes, hit
+                var fr = fi;
+                var pr = pi + 1;
+                if (pr === pl) {
+                    this.debug('** at the end');
+                    // a ** at the end will just swallow the rest.
+                    // We have found a match.
+                    // however, it will not swallow /.x, unless
+                    // options.dot is set.
+                    // . and .. are *never* matched by **, for explosively
+                    // exponential reasons.
+                    for (; fi < fl; fi++) {
+                        if (file[fi] === '.' ||
+                            file[fi] === '..' ||
+                            (!options.dot && file[fi].charAt(0) === '.'))
+                            return false;
+                    }
+                    return true;
+                }
+                // ok, let's see if we can swallow whatever we can.
+                while (fr < fl) {
+                    var swallowee = file[fr];
+                    this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
+                    // XXX remove this slice.  Just pass the start index.
+                    if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
+                        this.debug('globstar found match!', fr, fl, swallowee);
+                        // found a match.
+                        return true;
+                    }
+                    else {
+                        // can't swallow "." or ".." ever.
+                        // can only swallow ".foo" when explicitly asked.
+                        if (swallowee === '.' ||
+                            swallowee === '..' ||
+                            (!options.dot && swallowee.charAt(0) === '.')) {
+                            this.debug('dot detected!', file, fr, pattern, pr);
+                            break;
+                        }
+                        // ** swallows a segment, and continue.
+                        this.debug('globstar swallow a segment, and continue');
+                        fr++;
+                    }
+                }
+                // no match was found.
+                // However, in partial mode, we can't say this is necessarily over.
+                /* c8 ignore start */
+                if (partial) {
+                    // ran out of file
+                    this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
+                    if (fr === fl) {
+                        return true;
+                    }
+                }
+                /* c8 ignore stop */
+                return false;
+            }
+            // something other than **
+            // non-magic patterns just have to match exactly
+            // patterns with magic have been turned into regexps.
+            let hit;
+            if (typeof p === 'string') {
+                hit = f === p;
+                this.debug('string match', p, f, hit);
+            }
+            else {
+                hit = p.test(f);
+                this.debug('pattern match', p, f, hit);
+            }
+            if (!hit)
+                return false;
+        }
+        // Note: ending in / means that we'll get a final ""
+        // at the end of the pattern.  This can only match a
+        // corresponding "" at the end of the file.
+        // If the file ends in /, then it can only match a
+        // a pattern that ends in /, unless the pattern just
+        // doesn't have any more for it. But, a/b/ should *not*
+        // match "a/b/*", even though "" matches against the
+        // [^/]*? pattern, except in partial mode, where it might
+        // simply not be reached yet.
+        // However, a/b/ should still satisfy a/*
+        // now either we fell off the end of the pattern, or we're done.
+        if (fi === fl && pi === pl) {
+            // ran out of pattern and filename at the same time.
+            // an exact hit!
+            return true;
+        }
+        else if (fi === fl) {
+            // ran out of file, but still had pattern left.
+            // this is ok if we're doing the match as part of
+            // a glob fs traversal.
+            return partial;
+        }
+        else if (pi === pl) {
+            // ran out of pattern, still have file left.
+            // this is only acceptable if we're on the very last
+            // empty segment of a file with a trailing slash.
+            // a/* should match a/b/
+            return fi === fl - 1 && file[fi] === '';
+            /* c8 ignore start */
+        }
+        else {
+            // should be unreachable.
+            throw new Error('wtf?');
+        }
+        /* c8 ignore stop */
+    }
+    braceExpand() {
+        return (0, exports.braceExpand)(this.pattern, this.options);
+    }
+    parse(pattern) {
+        (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
+        const options = this.options;
+        // shortcuts
+        if (pattern === '**')
+            return exports.GLOBSTAR;
+        if (pattern === '')
+            return '';
+        // far and away, the most common glob pattern parts are
+        // *, *.*, and *.  Add a fast check method for those.
+        let m;
+        let fastTest = null;
+        if ((m = pattern.match(starRE))) {
+            fastTest = options.dot ? starTestDot : starTest;
+        }
+        else if ((m = pattern.match(starDotExtRE))) {
+            fastTest = (options.nocase
+                ? options.dot
+                    ? starDotExtTestNocaseDot
+                    : starDotExtTestNocase
+                : options.dot
+                    ? starDotExtTestDot
+                    : starDotExtTest)(m[1]);
+        }
+        else if ((m = pattern.match(qmarksRE))) {
+            fastTest = (options.nocase
+                ? options.dot
+                    ? qmarksTestNocaseDot
+                    : qmarksTestNocase
+                : options.dot
+                    ? qmarksTestDot
+                    : qmarksTest)(m);
+        }
+        else if ((m = pattern.match(starDotStarRE))) {
+            fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
+        }
+        else if ((m = pattern.match(dotStarRE))) {
+            fastTest = dotStarTest;
+        }
+        const re = ast_js_1.AST.fromGlob(pattern, this.options).toMMPattern();
+        if (fastTest && typeof re === 'object') {
+            // Avoids overriding in frozen environments
+            Reflect.defineProperty(re, 'test', { value: fastTest });
+        }
+        return re;
+    }
+    makeRe() {
+        if (this.regexp || this.regexp === false)
+            return this.regexp;
+        // at this point, this.set is a 2d array of partial
+        // pattern strings, or "**".
+        //
+        // It's better to use .match().  This function shouldn't
+        // be used, really, but it's pretty convenient sometimes,
+        // when you just want to work with a regex.
+        const set = this.set;
+        if (!set.length) {
+            this.regexp = false;
+            return this.regexp;
+        }
+        const options = this.options;
+        const twoStar = options.noglobstar
+            ? star
+            : options.dot
+                ? twoStarDot
+                : twoStarNoDot;
+        const flags = new Set(options.nocase ? ['i'] : []);
+        // regexpify non-globstar patterns
+        // if ** is only item, then we just do one twoStar
+        // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
+        // if ** is last, append (\/twoStar|) to previous
+        // if ** is in the middle, append (\/|\/twoStar\/) to previous
+        // then filter out GLOBSTAR symbols
+        let re = set
+            .map(pattern => {
+            const pp = pattern.map(p => {
+                if (p instanceof RegExp) {
+                    for (const f of p.flags.split(''))
+                        flags.add(f);
+                }
+                return typeof p === 'string'
+                    ? regExpEscape(p)
+                    : p === exports.GLOBSTAR
+                        ? exports.GLOBSTAR
+                        : p._src;
+            });
+            pp.forEach((p, i) => {
+                const next = pp[i + 1];
+                const prev = pp[i - 1];
+                if (p !== exports.GLOBSTAR || prev === exports.GLOBSTAR) {
+                    return;
+                }
+                if (prev === undefined) {
+                    if (next !== undefined && next !== exports.GLOBSTAR) {
+                        pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
+                    }
+                    else {
+                        pp[i] = twoStar;
+                    }
+                }
+                else if (next === undefined) {
+                    pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
+                }
+                else if (next !== exports.GLOBSTAR) {
+                    pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
+                    pp[i + 1] = exports.GLOBSTAR;
+                }
+            });
+            return pp.filter(p => p !== exports.GLOBSTAR).join('/');
+        })
+            .join('|');
+        // need to wrap in parens if we had more than one thing with |,
+        // otherwise only the first will be anchored to ^ and the last to $
+        const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
+        // must match entire pattern
+        // ending in a * or ** will make it less strict.
+        re = '^' + open + re + close + '$';
+        // can match anything, as long as it's not this.
+        if (this.negate)
+            re = '^(?!' + re + ').+$';
+        try {
+            this.regexp = new RegExp(re, [...flags].join(''));
+            /* c8 ignore start */
+        }
+        catch (ex) {
+            // should be impossible
+            this.regexp = false;
+        }
+        /* c8 ignore stop */
+        return this.regexp;
+    }
+    slashSplit(p) {
+        // if p starts with // on windows, we preserve that
+        // so that UNC paths aren't broken.  Otherwise, any number of
+        // / characters are coalesced into one, unless
+        // preserveMultipleSlashes is set to true.
+        if (this.preserveMultipleSlashes) {
+            return p.split('/');
+        }
+        else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
+            // add an extra '' for the one we lose
+            return ['', ...p.split(/\/+/)];
+        }
+        else {
+            return p.split(/\/+/);
+        }
+    }
+    match(f, partial = this.partial) {
+        this.debug('match', f, this.pattern);
+        // short-circuit in the case of busted things.
+        // comments, etc.
+        if (this.comment) {
+            return false;
+        }
+        if (this.empty) {
+            return f === '';
+        }
+        if (f === '/' && partial) {
+            return true;
+        }
+        const options = this.options;
+        // windows: need to use /, not \
+        if (this.isWindows) {
+            f = f.split('\\').join('/');
+        }
+        // treat the test path as a set of pathparts.
+        const ff = this.slashSplit(f);
+        this.debug(this.pattern, 'split', ff);
+        // just ONE of the pattern sets in this.set needs to match
+        // in order for it to be valid.  If negating, then just one
+        // match means that we have failed.
+        // Either way, return on the first hit.
+        const set = this.set;
+        this.debug(this.pattern, 'set', set);
+        // Find the basename of the path by looking for the last non-empty segment
+        let filename = ff[ff.length - 1];
+        if (!filename) {
+            for (let i = ff.length - 2; !filename && i >= 0; i--) {
+                filename = ff[i];
+            }
+        }
+        for (let i = 0; i < set.length; i++) {
+            const pattern = set[i];
+            let file = ff;
+            if (options.matchBase && pattern.length === 1) {
+                file = [filename];
+            }
+            const hit = this.matchOne(file, pattern, partial);
+            if (hit) {
+                if (options.flipNegate) {
+                    return true;
+                }
+                return !this.negate;
+            }
+        }
+        // didn't get any hits.  this is success if it's a negative
+        // pattern, failure otherwise.
+        if (options.flipNegate) {
+            return false;
+        }
+        return this.negate;
+    }
+    static defaults(def) {
+        return exports.minimatch.defaults(def).Minimatch;
+    }
+}
+exports.Minimatch = Minimatch;
+/* c8 ignore start */
+var ast_js_2 = require("./ast.js");
+Object.defineProperty(exports, "AST", { enumerable: true, get: function () { return ast_js_2.AST; } });
+var escape_js_2 = require("./escape.js");
+Object.defineProperty(exports, "escape", { enumerable: true, get: function () { return escape_js_2.escape; } });
+var unescape_js_2 = require("./unescape.js");
+Object.defineProperty(exports, "unescape", { enumerable: true, get: function () { return unescape_js_2.unescape; } });
+/* c8 ignore stop */
+exports.minimatch.AST = ast_js_1.AST;
+exports.minimatch.Minimatch = Minimatch;
+exports.minimatch.escape = escape_js_1.escape;
+exports.minimatch.unescape = unescape_js_1.unescape;
+//# sourceMappingURL=index.js.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/commonjs/index.js.map b/node_modules/minimatch/dist/commonjs/index.js.map
new file mode 100644
index 0000000..d4f6a87
--- /dev/null
+++ b/node_modules/minimatch/dist/commonjs/index.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;AAAA,sEAAoC;AACpC,uEAA8D;AAC9D,qCAA2C;AAC3C,2CAAoC;AACpC,+CAAwC;AAsCjC,MAAM,SAAS,GAAG,CACvB,CAAS,EACT,OAAe,EACf,UAA4B,EAAE,EAC9B,EAAE;IACF,IAAA,4CAAkB,EAAC,OAAO,CAAC,CAAA;IAE3B,oCAAoC;IACpC,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;QACnD,OAAO,KAAK,CAAA;KACb;IAED,OAAO,IAAI,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;AACjD,CAAC,CAAA;AAbY,QAAA,SAAS,aAarB;AAED,wDAAwD;AACxD,MAAM,YAAY,GAAG,uBAAuB,CAAA;AAC5C,MAAM,cAAc,GAAG,CAAC,GAAW,E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CAAC,QAAQ,GAAG,sBAAQ,CAAA","sourcesContent":["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      // just collapse multiple ** portions into one\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) {\n          globParts[i] = []\n          globParts[j] = matched\n          break\n        }\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    if (fastTest && typeof re === 'object') {\n      // Avoids overriding in frozen environments\n      Reflect.defineProperty(re, 'test', { value: fastTest })\n    }\n    return 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"]}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/commonjs/package.json b/node_modules/minimatch/dist/commonjs/package.json
new file mode 100644
index 0000000..5bbefff
--- /dev/null
+++ b/node_modules/minimatch/dist/commonjs/package.json
@@ -0,0 +1,3 @@
+{
+  "type": "commonjs"
+}
diff --git a/node_modules/minimatch/dist/commonjs/unescape.d.ts b/node_modules/minimatch/dist/commonjs/unescape.d.ts
new file mode 100644
index 0000000..23a7b38
--- /dev/null
+++ b/node_modules/minimatch/dist/commonjs/unescape.d.ts
@@ -0,0 +1,17 @@
+import { MinimatchOptions } from './index.js';
+/**
+ * Un-escape a string that has been escaped with {@link escape}.
+ *
+ * If the {@link windowsPathsNoEscape} option is used, then square-brace
+ * escapes are removed, but not backslash escapes.  For example, it will turn
+ * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
+ * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
+ *
+ * When `windowsPathsNoEscape` is not set, then both brace escapes and
+ * backslash escapes are removed.
+ *
+ * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
+ * or unescaped.
+ */
+export declare const unescape: (s: string, { windowsPathsNoEscape, }?: Pick) => string;
+//# sourceMappingURL=unescape.d.ts.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/commonjs/unescape.d.ts.map b/node_modules/minimatch/dist/commonjs/unescape.d.ts.map
new file mode 100644
index 0000000..7ace070
--- /dev/null
+++ b/node_modules/minimatch/dist/commonjs/unescape.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"unescape.d.ts","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAC7C;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,QAAQ,MAChB,MAAM,8BAGN,KAAK,gBAAgB,EAAE,sBAAsB,CAAC,WAKlD,CAAA"}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/commonjs/unescape.js b/node_modules/minimatch/dist/commonjs/unescape.js
new file mode 100644
index 0000000..47c36bc
--- /dev/null
+++ b/node_modules/minimatch/dist/commonjs/unescape.js
@@ -0,0 +1,24 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.unescape = void 0;
+/**
+ * Un-escape a string that has been escaped with {@link escape}.
+ *
+ * If the {@link windowsPathsNoEscape} option is used, then square-brace
+ * escapes are removed, but not backslash escapes.  For example, it will turn
+ * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
+ * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
+ *
+ * When `windowsPathsNoEscape` is not set, then both brace escapes and
+ * backslash escapes are removed.
+ *
+ * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
+ * or unescaped.
+ */
+const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
+    return windowsPathsNoEscape
+        ? s.replace(/\[([^\/\\])\]/g, '$1')
+        : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
+};
+exports.unescape = unescape;
+//# sourceMappingURL=unescape.js.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/commonjs/unescape.js.map b/node_modules/minimatch/dist/commonjs/unescape.js.map
new file mode 100644
index 0000000..353d3aa
--- /dev/null
+++ b/node_modules/minimatch/dist/commonjs/unescape.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"unescape.js","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":";;;AACA;;;;;;;;;;;;;GAaG;AACI,MAAM,QAAQ,GAAG,CACtB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,MACsB,EAAE,EACtD,EAAE;IACF,OAAO,oBAAoB;QACzB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,gBAAgB,EAAE,IAAI,CAAC;QACnC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,2BAA2B,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,IAAI,CAAC,CAAA;AAChF,CAAC,CAAA;AATY,QAAA,QAAQ,YASpB","sourcesContent":["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"]}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/assert-valid-pattern.d.ts b/node_modules/minimatch/dist/esm/assert-valid-pattern.d.ts
new file mode 100644
index 0000000..8e318b2
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/assert-valid-pattern.d.ts
@@ -0,0 +1,2 @@
+export declare const assertValidPattern: (pattern: any) => void;
+//# sourceMappingURL=assert-valid-pattern.d.ts.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/assert-valid-pattern.d.ts.map b/node_modules/minimatch/dist/esm/assert-valid-pattern.d.ts.map
new file mode 100644
index 0000000..c61c031
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/assert-valid-pattern.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"assert-valid-pattern.d.ts","sourceRoot":"","sources":["../../src/assert-valid-pattern.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,kBAAkB,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,IAUlD,CAAA"}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/assert-valid-pattern.js b/node_modules/minimatch/dist/esm/assert-valid-pattern.js
new file mode 100644
index 0000000..7b534fc
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/assert-valid-pattern.js
@@ -0,0 +1,10 @@
+const MAX_PATTERN_LENGTH = 1024 * 64;
+export const assertValidPattern = (pattern) => {
+    if (typeof pattern !== 'string') {
+        throw new TypeError('invalid pattern');
+    }
+    if (pattern.length > MAX_PATTERN_LENGTH) {
+        throw new TypeError('pattern is too long');
+    }
+};
+//# sourceMappingURL=assert-valid-pattern.js.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/assert-valid-pattern.js.map b/node_modules/minimatch/dist/esm/assert-valid-pattern.js.map
new file mode 100644
index 0000000..b1a5a0b
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/assert-valid-pattern.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"assert-valid-pattern.js","sourceRoot":"","sources":["../../src/assert-valid-pattern.ts"],"names":[],"mappings":"AAAA,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAE,CAAA;AACpC,MAAM,CAAC,MAAM,kBAAkB,GAA2B,CACxD,OAAY,EACe,EAAE;IAC7B,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;QAC/B,MAAM,IAAI,SAAS,CAAC,iBAAiB,CAAC,CAAA;KACvC;IAED,IAAI,OAAO,CAAC,MAAM,GAAG,kBAAkB,EAAE;QACvC,MAAM,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAA;KAC3C;AACH,CAAC,CAAA","sourcesContent":["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"]}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/ast.d.ts b/node_modules/minimatch/dist/esm/ast.d.ts
new file mode 100644
index 0000000..b8c1e54
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/ast.d.ts
@@ -0,0 +1,20 @@
+import { MinimatchOptions, MMRegExp } from './index.js';
+export type ExtglobType = '!' | '?' | '+' | '*' | '@';
+export declare class AST {
+    #private;
+    type: ExtglobType | null;
+    constructor(type: ExtglobType | null, parent?: AST, options?: MinimatchOptions);
+    get hasMagic(): boolean | undefined;
+    toString(): string;
+    push(...parts: (string | AST)[]): void;
+    toJSON(): any[];
+    isStart(): boolean;
+    isEnd(): boolean;
+    copyIn(part: AST | string): void;
+    clone(parent: AST): AST;
+    static fromGlob(pattern: string, options?: MinimatchOptions): AST;
+    toMMPattern(): MMRegExp | string;
+    get options(): MinimatchOptions;
+    toRegExpSource(allowDot?: boolean): [re: string, body: string, hasMagic: boolean, uflag: boolean];
+}
+//# sourceMappingURL=ast.d.ts.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/ast.d.ts.map b/node_modules/minimatch/dist/esm/ast.d.ts.map
new file mode 100644
index 0000000..9e7bfb9
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/ast.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../src/ast.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAwCvD,MAAM,MAAM,WAAW,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAA;AAkCrD,qBAAa,GAAG;;IACd,IAAI,EAAE,WAAW,GAAG,IAAI,CAAA;gBAiBtB,IAAI,EAAE,WAAW,GAAG,IAAI,EACxB,MAAM,CAAC,EAAE,GAAG,EACZ,OAAO,GAAE,gBAAqB;IAahC,IAAI,QAAQ,IAAI,OAAO,GAAG,SAAS,CAUlC;IAGD,QAAQ,IAAI,MAAM;IA+ClB,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,MAAM,GAAG,GAAG,CAAC,EAAE;IAY/B,MAAM;IAgBN,OAAO,IAAI,OAAO;IAgBlB,KAAK,IAAI,OAAO;IAYhB,MAAM,CAAC,IAAI,EAAE,GAAG,GAAG,MAAM;IAKzB,KAAK,CAAC,MAAM,EAAE,GAAG;IAsIjB,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB;IAQ/D,WAAW,IAAI,QAAQ,GAAG,MAAM;IA2BhC,IAAI,OAAO,qBAEV;IAuED,cAAc,CACZ,QAAQ,CAAC,EAAE,OAAO,GACjB,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC;CAiMjE"}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/ast.js b/node_modules/minimatch/dist/esm/ast.js
new file mode 100644
index 0000000..2d2bced
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/ast.js
@@ -0,0 +1,588 @@
+// parse a single path portion
+import { parseClass } from './brace-expressions.js';
+import { unescape } from './unescape.js';
+const types = new Set(['!', '?', '+', '*', '@']);
+const isExtglobType = (c) => types.has(c);
+// Patterns that get prepended to bind to the start of either the
+// entire string, or just a single path portion, to prevent dots
+// and/or traversal patterns, when needed.
+// Exts don't need the ^ or / bit, because the root binds that already.
+const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
+const startNoDot = '(?!\\.)';
+// characters that indicate a start of pattern needs the "no dots" bit,
+// because a dot *might* be matched. ( is not in the list, because in
+// the case of a child extglob, it will handle the prevention itself.
+const addPatternStart = new Set(['[', '.']);
+// cases where traversal is A-OK, no dot prevention needed
+const justDots = new Set(['..', '.']);
+const reSpecials = new Set('().*{}+?[]^$\\!');
+const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
+// any single thing other than /
+const qmark = '[^/]';
+// * => any number of characters
+const star = qmark + '*?';
+// use + when we need to ensure that *something* matches, because the * is
+// the only thing in the path portion.
+const starNoEmpty = qmark + '+?';
+// remove the \ chars that we added if we end up doing a nonmagic compare
+// const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
+export class AST {
+    type;
+    #root;
+    #hasMagic;
+    #uflag = false;
+    #parts = [];
+    #parent;
+    #parentIndex;
+    #negs;
+    #filledNegs = false;
+    #options;
+    #toString;
+    // set to true if it's an extglob with no children
+    // (which really means one child of '')
+    #emptyExt = false;
+    constructor(type, parent, options = {}) {
+        this.type = type;
+        // extglobs are inherently magical
+        if (type)
+            this.#hasMagic = true;
+        this.#parent = parent;
+        this.#root = this.#parent ? this.#parent.#root : this;
+        this.#options = this.#root === this ? options : this.#root.#options;
+        this.#negs = this.#root === this ? [] : this.#root.#negs;
+        if (type === '!' && !this.#root.#filledNegs)
+            this.#negs.push(this);
+        this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
+    }
+    get hasMagic() {
+        /* c8 ignore start */
+        if (this.#hasMagic !== undefined)
+            return this.#hasMagic;
+        /* c8 ignore stop */
+        for (const p of this.#parts) {
+            if (typeof p === 'string')
+                continue;
+            if (p.type || p.hasMagic)
+                return (this.#hasMagic = true);
+        }
+        // note: will be undefined until we generate the regexp src and find out
+        return this.#hasMagic;
+    }
+    // reconstructs the pattern
+    toString() {
+        if (this.#toString !== undefined)
+            return this.#toString;
+        if (!this.type) {
+            return (this.#toString = this.#parts.map(p => String(p)).join(''));
+        }
+        else {
+            return (this.#toString =
+                this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
+        }
+    }
+    #fillNegs() {
+        /* c8 ignore start */
+        if (this !== this.#root)
+            throw new Error('should only call on root');
+        if (this.#filledNegs)
+            return this;
+        /* c8 ignore stop */
+        // call toString() once to fill this out
+        this.toString();
+        this.#filledNegs = true;
+        let n;
+        while ((n = this.#negs.pop())) {
+            if (n.type !== '!')
+                continue;
+            // walk up the tree, appending everthing that comes AFTER parentIndex
+            let p = n;
+            let pp = p.#parent;
+            while (pp) {
+                for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
+                    for (const part of n.#parts) {
+                        /* c8 ignore start */
+                        if (typeof part === 'string') {
+                            throw new Error('string part in extglob AST??');
+                        }
+                        /* c8 ignore stop */
+                        part.copyIn(pp.#parts[i]);
+                    }
+                }
+                p = pp;
+                pp = p.#parent;
+            }
+        }
+        return this;
+    }
+    push(...parts) {
+        for (const p of parts) {
+            if (p === '')
+                continue;
+            /* c8 ignore start */
+            if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
+                throw new Error('invalid part: ' + p);
+            }
+            /* c8 ignore stop */
+            this.#parts.push(p);
+        }
+    }
+    toJSON() {
+        const ret = this.type === null
+            ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
+            : [this.type, ...this.#parts.map(p => p.toJSON())];
+        if (this.isStart() && !this.type)
+            ret.unshift([]);
+        if (this.isEnd() &&
+            (this === this.#root ||
+                (this.#root.#filledNegs && this.#parent?.type === '!'))) {
+            ret.push({});
+        }
+        return ret;
+    }
+    isStart() {
+        if (this.#root === this)
+            return true;
+        // if (this.type) return !!this.#parent?.isStart()
+        if (!this.#parent?.isStart())
+            return false;
+        if (this.#parentIndex === 0)
+            return true;
+        // if everything AHEAD of this is a negation, then it's still the "start"
+        const p = this.#parent;
+        for (let i = 0; i < this.#parentIndex; i++) {
+            const pp = p.#parts[i];
+            if (!(pp instanceof AST && pp.type === '!')) {
+                return false;
+            }
+        }
+        return true;
+    }
+    isEnd() {
+        if (this.#root === this)
+            return true;
+        if (this.#parent?.type === '!')
+            return true;
+        if (!this.#parent?.isEnd())
+            return false;
+        if (!this.type)
+            return this.#parent?.isEnd();
+        // if not root, it'll always have a parent
+        /* c8 ignore start */
+        const pl = this.#parent ? this.#parent.#parts.length : 0;
+        /* c8 ignore stop */
+        return this.#parentIndex === pl - 1;
+    }
+    copyIn(part) {
+        if (typeof part === 'string')
+            this.push(part);
+        else
+            this.push(part.clone(this));
+    }
+    clone(parent) {
+        const c = new AST(this.type, parent);
+        for (const p of this.#parts) {
+            c.copyIn(p);
+        }
+        return c;
+    }
+    static #parseAST(str, ast, pos, opt) {
+        let escaping = false;
+        let inBrace = false;
+        let braceStart = -1;
+        let braceNeg = false;
+        if (ast.type === null) {
+            // outside of a extglob, append until we find a start
+            let i = pos;
+            let acc = '';
+            while (i < str.length) {
+                const c = str.charAt(i++);
+                // still accumulate escapes at this point, but we do ignore
+                // starts that are escaped
+                if (escaping || c === '\\') {
+                    escaping = !escaping;
+                    acc += c;
+                    continue;
+                }
+                if (inBrace) {
+                    if (i === braceStart + 1) {
+                        if (c === '^' || c === '!') {
+                            braceNeg = true;
+                        }
+                    }
+                    else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
+                        inBrace = false;
+                    }
+                    acc += c;
+                    continue;
+                }
+                else if (c === '[') {
+                    inBrace = true;
+                    braceStart = i;
+                    braceNeg = false;
+                    acc += c;
+                    continue;
+                }
+                if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
+                    ast.push(acc);
+                    acc = '';
+                    const ext = new AST(c, ast);
+                    i = AST.#parseAST(str, ext, i, opt);
+                    ast.push(ext);
+                    continue;
+                }
+                acc += c;
+            }
+            ast.push(acc);
+            return i;
+        }
+        // some kind of extglob, pos is at the (
+        // find the next | or )
+        let i = pos + 1;
+        let part = new AST(null, ast);
+        const parts = [];
+        let acc = '';
+        while (i < str.length) {
+            const c = str.charAt(i++);
+            // still accumulate escapes at this point, but we do ignore
+            // starts that are escaped
+            if (escaping || c === '\\') {
+                escaping = !escaping;
+                acc += c;
+                continue;
+            }
+            if (inBrace) {
+                if (i === braceStart + 1) {
+                    if (c === '^' || c === '!') {
+                        braceNeg = true;
+                    }
+                }
+                else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
+                    inBrace = false;
+                }
+                acc += c;
+                continue;
+            }
+            else if (c === '[') {
+                inBrace = true;
+                braceStart = i;
+                braceNeg = false;
+                acc += c;
+                continue;
+            }
+            if (isExtglobType(c) && str.charAt(i) === '(') {
+                part.push(acc);
+                acc = '';
+                const ext = new AST(c, part);
+                part.push(ext);
+                i = AST.#parseAST(str, ext, i, opt);
+                continue;
+            }
+            if (c === '|') {
+                part.push(acc);
+                acc = '';
+                parts.push(part);
+                part = new AST(null, ast);
+                continue;
+            }
+            if (c === ')') {
+                if (acc === '' && ast.#parts.length === 0) {
+                    ast.#emptyExt = true;
+                }
+                part.push(acc);
+                acc = '';
+                ast.push(...parts, part);
+                return i;
+            }
+            acc += c;
+        }
+        // unfinished extglob
+        // if we got here, it was a malformed extglob! not an extglob, but
+        // maybe something else in there.
+        ast.type = null;
+        ast.#hasMagic = undefined;
+        ast.#parts = [str.substring(pos - 1)];
+        return i;
+    }
+    static fromGlob(pattern, options = {}) {
+        const ast = new AST(null, undefined, options);
+        AST.#parseAST(pattern, ast, 0, options);
+        return ast;
+    }
+    // returns the regular expression if there's magic, or the unescaped
+    // string if not.
+    toMMPattern() {
+        // should only be called on root
+        /* c8 ignore start */
+        if (this !== this.#root)
+            return this.#root.toMMPattern();
+        /* c8 ignore stop */
+        const glob = this.toString();
+        const [re, body, hasMagic, uflag] = this.toRegExpSource();
+        // if we're in nocase mode, and not nocaseMagicOnly, then we do
+        // still need a regular expression if we have to case-insensitively
+        // match capital/lowercase characters.
+        const anyMagic = hasMagic ||
+            this.#hasMagic ||
+            (this.#options.nocase &&
+                !this.#options.nocaseMagicOnly &&
+                glob.toUpperCase() !== glob.toLowerCase());
+        if (!anyMagic) {
+            return body;
+        }
+        const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
+        return Object.assign(new RegExp(`^${re}$`, flags), {
+            _src: re,
+            _glob: glob,
+        });
+    }
+    get options() {
+        return this.#options;
+    }
+    // returns the string match, the regexp source, whether there's magic
+    // in the regexp (so a regular expression is required) and whether or
+    // not the uflag is needed for the regular expression (for posix classes)
+    // TODO: instead of injecting the start/end at this point, just return
+    // the BODY of the regexp, along with the start/end portions suitable
+    // for binding the start/end in either a joined full-path makeRe context
+    // (where we bind to (^|/), or a standalone matchPart context (where
+    // we bind to ^, and not /).  Otherwise slashes get duped!
+    //
+    // In part-matching mode, the start is:
+    // - if not isStart: nothing
+    // - if traversal possible, but not allowed: ^(?!\.\.?$)
+    // - if dots allowed or not possible: ^
+    // - if dots possible and not allowed: ^(?!\.)
+    // end is:
+    // - if not isEnd(): nothing
+    // - else: $
+    //
+    // In full-path matching mode, we put the slash at the START of the
+    // pattern, so start is:
+    // - if first pattern: same as part-matching mode
+    // - if not isStart(): nothing
+    // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
+    // - if dots allowed or not possible: /
+    // - if dots possible and not allowed: /(?!\.)
+    // end is:
+    // - if last pattern, same as part-matching mode
+    // - else nothing
+    //
+    // Always put the (?:$|/) on negated tails, though, because that has to be
+    // there to bind the end of the negated pattern portion, and it's easier to
+    // just stick it in now rather than try to inject it later in the middle of
+    // the pattern.
+    //
+    // We can just always return the same end, and leave it up to the caller
+    // to know whether it's going to be used joined or in parts.
+    // And, if the start is adjusted slightly, can do the same there:
+    // - if not isStart: nothing
+    // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
+    // - if dots allowed or not possible: (?:/|^)
+    // - if dots possible and not allowed: (?:/|^)(?!\.)
+    //
+    // But it's better to have a simpler binding without a conditional, for
+    // performance, so probably better to return both start options.
+    //
+    // Then the caller just ignores the end if it's not the first pattern,
+    // and the start always gets applied.
+    //
+    // But that's always going to be $ if it's the ending pattern, or nothing,
+    // so the caller can just attach $ at the end of the pattern when building.
+    //
+    // So the todo is:
+    // - better detect what kind of start is needed
+    // - return both flavors of starting pattern
+    // - attach $ at the end of the pattern when creating the actual RegExp
+    //
+    // Ah, but wait, no, that all only applies to the root when the first pattern
+    // is not an extglob. If the first pattern IS an extglob, then we need all
+    // that dot prevention biz to live in the extglob portions, because eg
+    // +(*|.x*) can match .xy but not .yx.
+    //
+    // So, return the two flavors if it's #root and the first child is not an
+    // AST, otherwise leave it to the child AST to handle it, and there,
+    // use the (?:^|/) style of start binding.
+    //
+    // Even simplified further:
+    // - Since the start for a join is eg /(?!\.) and the start for a part
+    // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
+    // or start or whatever) and prepend ^ or / at the Regexp construction.
+    toRegExpSource(allowDot) {
+        const dot = allowDot ?? !!this.#options.dot;
+        if (this.#root === this)
+            this.#fillNegs();
+        if (!this.type) {
+            const noEmpty = this.isStart() && this.isEnd();
+            const src = this.#parts
+                .map(p => {
+                const [re, _, hasMagic, uflag] = typeof p === 'string'
+                    ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
+                    : p.toRegExpSource(allowDot);
+                this.#hasMagic = this.#hasMagic || hasMagic;
+                this.#uflag = this.#uflag || uflag;
+                return re;
+            })
+                .join('');
+            let start = '';
+            if (this.isStart()) {
+                if (typeof this.#parts[0] === 'string') {
+                    // this is the string that will match the start of the pattern,
+                    // so we need to protect against dots and such.
+                    // '.' and '..' cannot match unless the pattern is that exactly,
+                    // even if it starts with . or dot:true is set.
+                    const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
+                    if (!dotTravAllowed) {
+                        const aps = addPatternStart;
+                        // check if we have a possibility of matching . or ..,
+                        // and prevent that.
+                        const needNoTrav = 
+                        // dots are allowed, and the pattern starts with [ or .
+                        (dot && aps.has(src.charAt(0))) ||
+                            // the pattern starts with \., and then [ or .
+                            (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
+                            // the pattern starts with \.\., and then [ or .
+                            (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
+                        // no need to prevent dots if it can't match a dot, or if a
+                        // sub-pattern will be preventing it anyway.
+                        const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
+                        start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
+                    }
+                }
+            }
+            // append the "end of path portion" pattern to negation tails
+            let end = '';
+            if (this.isEnd() &&
+                this.#root.#filledNegs &&
+                this.#parent?.type === '!') {
+                end = '(?:$|\\/)';
+            }
+            const final = start + src + end;
+            return [
+                final,
+                unescape(src),
+                (this.#hasMagic = !!this.#hasMagic),
+                this.#uflag,
+            ];
+        }
+        // We need to calculate the body *twice* if it's a repeat pattern
+        // at the start, once in nodot mode, then again in dot mode, so a
+        // pattern like *(?) can match 'x.y'
+        const repeated = this.type === '*' || this.type === '+';
+        // some kind of extglob
+        const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
+        let body = this.#partsToRegExp(dot);
+        if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
+            // invalid extglob, has to at least be *something* present, if it's
+            // the entire path portion.
+            const s = this.toString();
+            this.#parts = [s];
+            this.type = null;
+            this.#hasMagic = undefined;
+            return [s, unescape(this.toString()), false, false];
+        }
+        // XXX abstract out this map method
+        let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
+            ? ''
+            : this.#partsToRegExp(true);
+        if (bodyDotAllowed === body) {
+            bodyDotAllowed = '';
+        }
+        if (bodyDotAllowed) {
+            body = `(?:${body})(?:${bodyDotAllowed})*?`;
+        }
+        // an empty !() is exactly equivalent to a starNoEmpty
+        let final = '';
+        if (this.type === '!' && this.#emptyExt) {
+            final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
+        }
+        else {
+            const close = this.type === '!'
+                ? // !() must match something,but !(x) can match ''
+                    '))' +
+                        (this.isStart() && !dot && !allowDot ? startNoDot : '') +
+                        star +
+                        ')'
+                : this.type === '@'
+                    ? ')'
+                    : this.type === '?'
+                        ? ')?'
+                        : this.type === '+' && bodyDotAllowed
+                            ? ')'
+                            : this.type === '*' && bodyDotAllowed
+                                ? `)?`
+                                : `)${this.type}`;
+            final = start + body + close;
+        }
+        return [
+            final,
+            unescape(body),
+            (this.#hasMagic = !!this.#hasMagic),
+            this.#uflag,
+        ];
+    }
+    #partsToRegExp(dot) {
+        return this.#parts
+            .map(p => {
+            // extglob ASTs should only contain parent ASTs
+            /* c8 ignore start */
+            if (typeof p === 'string') {
+                throw new Error('string type in extglob ast??');
+            }
+            /* c8 ignore stop */
+            // can ignore hasMagic, because extglobs are already always magic
+            const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
+            this.#uflag = this.#uflag || uflag;
+            return re;
+        })
+            .filter(p => !(this.isStart() && this.isEnd()) || !!p)
+            .join('|');
+    }
+    static #parseGlob(glob, hasMagic, noEmpty = false) {
+        let escaping = false;
+        let re = '';
+        let uflag = false;
+        for (let i = 0; i < glob.length; i++) {
+            const c = glob.charAt(i);
+            if (escaping) {
+                escaping = false;
+                re += (reSpecials.has(c) ? '\\' : '') + c;
+                continue;
+            }
+            if (c === '\\') {
+                if (i === glob.length - 1) {
+                    re += '\\\\';
+                }
+                else {
+                    escaping = true;
+                }
+                continue;
+            }
+            if (c === '[') {
+                const [src, needUflag, consumed, magic] = parseClass(glob, i);
+                if (consumed) {
+                    re += src;
+                    uflag = uflag || needUflag;
+                    i += consumed - 1;
+                    hasMagic = hasMagic || magic;
+                    continue;
+                }
+            }
+            if (c === '*') {
+                if (noEmpty && glob === '*')
+                    re += starNoEmpty;
+                else
+                    re += star;
+                hasMagic = true;
+                continue;
+            }
+            if (c === '?') {
+                re += qmark;
+                hasMagic = true;
+                continue;
+            }
+            re += regExpEscape(c);
+        }
+        return [re, unescape(glob), !!hasMagic, uflag];
+    }
+}
+//# sourceMappingURL=ast.js.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/ast.js.map b/node_modules/minimatch/dist/esm/ast.js.map
new file mode 100644
index 0000000..f1f8b34
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/ast.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"ast.js","sourceRoot":"","sources":["../../src/ast.ts"],"names":[],"mappings":"AAAA,8BAA8B;AAE9B,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AAEnD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAwCxC,MAAM,KAAK,GAAG,IAAI,GAAG,CAAc,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAA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;YACD,IAAI,CAAC,KAAK,GAAG,EAAE;gBACb,MAAM,CAAC,GAAG,EAAE,SAAS,EAAE,QAAQ,EAAE,KAAK,CAAC,GAAG,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;gBAC7D,IAAI,QAAQ,EAAE;oBACZ,EAAE,IAAI,GAAG,CAAA;oBACT,KAAK,GAAG,KAAK,IAAI,SAAS,CAAA;oBAC1B,CAAC,IAAI,QAAQ,GAAG,CAAC,CAAA;oBACjB,QAAQ,GAAG,QAAQ,IAAI,KAAK,CAAA;oBAC5B,SAAQ;iBACT;aACF;YACD,IAAI,CAAC,KAAK,GAAG,EAAE;gBACb,IAAI,OAAO,IAAI,IAAI,KAAK,GAAG;oBAAE,EAAE,IAAI,WAAW,CAAA;;oBACzC,EAAE,IAAI,IAAI,CAAA;gBACf,QAAQ,GAAG,IAAI,CAAA;gBACf,SAAQ;aACT;YACD,IAAI,CAAC,KAAK,GAAG,EAAE;gBACb,EAAE,IAAI,KAAK,CAAA;gBACX,QAAQ,GAAG,IAAI,CAAA;gBACf,SAAQ;aACT;YACD,EAAE,IAAI,YAAY,CAAC,CAAC,CAAC,CAAA;SACtB;QACD,OAAO,CAAC,EAAE,EAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAA;IAChD,CAAC;CACF","sourcesContent":["// 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  get options() {\n    return this.#options\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"]}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/brace-expressions.d.ts b/node_modules/minimatch/dist/esm/brace-expressions.d.ts
new file mode 100644
index 0000000..b1572de
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/brace-expressions.d.ts
@@ -0,0 +1,8 @@
+export type ParseClassResult = [
+    src: string,
+    uFlag: boolean,
+    consumed: number,
+    hasMagic: boolean
+];
+export declare const parseClass: (glob: string, position: number) => ParseClassResult;
+//# sourceMappingURL=brace-expressions.d.ts.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/brace-expressions.d.ts.map b/node_modules/minimatch/dist/esm/brace-expressions.d.ts.map
new file mode 100644
index 0000000..d394964
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/brace-expressions.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"brace-expressions.d.ts","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":"AA+BA,MAAM,MAAM,gBAAgB,GAAG;IAC7B,GAAG,EAAE,MAAM;IACX,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,MAAM;IAChB,QAAQ,EAAE,OAAO;CAClB,CAAA;AAQD,eAAO,MAAM,UAAU,SACf,MAAM,YACF,MAAM,qBA8HjB,CAAA"}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/brace-expressions.js b/node_modules/minimatch/dist/esm/brace-expressions.js
new file mode 100644
index 0000000..c629d6a
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/brace-expressions.js
@@ -0,0 +1,148 @@
+// translate the various posix character classes into unicode properties
+// this works across all unicode locales
+// { : [, /u flag required, negated]
+const posixClasses = {
+    '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
+    '[:alpha:]': ['\\p{L}\\p{Nl}', true],
+    '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
+    '[:blank:]': ['\\p{Zs}\\t', true],
+    '[:cntrl:]': ['\\p{Cc}', true],
+    '[:digit:]': ['\\p{Nd}', true],
+    '[:graph:]': ['\\p{Z}\\p{C}', true, true],
+    '[:lower:]': ['\\p{Ll}', true],
+    '[:print:]': ['\\p{C}', true],
+    '[:punct:]': ['\\p{P}', true],
+    '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
+    '[:upper:]': ['\\p{Lu}', true],
+    '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
+    '[:xdigit:]': ['A-Fa-f0-9', false],
+};
+// only need to escape a few things inside of brace expressions
+// escapes: [ \ ] -
+const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
+// escape all regexp magic characters
+const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
+// everything has already been escaped, we just have to join
+const rangesToString = (ranges) => ranges.join('');
+// takes a glob string at a posix brace expression, and returns
+// an equivalent regular expression source, and boolean indicating
+// whether the /u flag needs to be applied, and the number of chars
+// consumed to parse the character class.
+// This also removes out of order ranges, and returns ($.) if the
+// entire class just no good.
+export const parseClass = (glob, position) => {
+    const pos = position;
+    /* c8 ignore start */
+    if (glob.charAt(pos) !== '[') {
+        throw new Error('not in a brace expression');
+    }
+    /* c8 ignore stop */
+    const ranges = [];
+    const negs = [];
+    let i = pos + 1;
+    let sawStart = false;
+    let uflag = false;
+    let escaping = false;
+    let negate = false;
+    let endPos = pos;
+    let rangeStart = '';
+    WHILE: while (i < glob.length) {
+        const c = glob.charAt(i);
+        if ((c === '!' || c === '^') && i === pos + 1) {
+            negate = true;
+            i++;
+            continue;
+        }
+        if (c === ']' && sawStart && !escaping) {
+            endPos = i + 1;
+            break;
+        }
+        sawStart = true;
+        if (c === '\\') {
+            if (!escaping) {
+                escaping = true;
+                i++;
+                continue;
+            }
+            // escaped \ char, fall through and treat like normal char
+        }
+        if (c === '[' && !escaping) {
+            // either a posix class, a collation equivalent, or just a [
+            for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
+                if (glob.startsWith(cls, i)) {
+                    // invalid, [a-[] is fine, but not [a-[:alpha]]
+                    if (rangeStart) {
+                        return ['$.', false, glob.length - pos, true];
+                    }
+                    i += cls.length;
+                    if (neg)
+                        negs.push(unip);
+                    else
+                        ranges.push(unip);
+                    uflag = uflag || u;
+                    continue WHILE;
+                }
+            }
+        }
+        // now it's just a normal character, effectively
+        escaping = false;
+        if (rangeStart) {
+            // throw this range away if it's not valid, but others
+            // can still match.
+            if (c > rangeStart) {
+                ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
+            }
+            else if (c === rangeStart) {
+                ranges.push(braceEscape(c));
+            }
+            rangeStart = '';
+            i++;
+            continue;
+        }
+        // now might be the start of a range.
+        // can be either c-d or c-] or c] or c] at this point
+        if (glob.startsWith('-]', i + 1)) {
+            ranges.push(braceEscape(c + '-'));
+            i += 2;
+            continue;
+        }
+        if (glob.startsWith('-', i + 1)) {
+            rangeStart = c;
+            i += 2;
+            continue;
+        }
+        // not the start of a range, just a single character
+        ranges.push(braceEscape(c));
+        i++;
+    }
+    if (endPos < i) {
+        // didn't see the end of the class, not a valid class,
+        // but might still be valid as a literal match.
+        return ['', false, 0, false];
+    }
+    // if we got no ranges and no negates, then we have a range that
+    // cannot possibly match anything, and that poisons the whole glob
+    if (!ranges.length && !negs.length) {
+        return ['$.', false, glob.length - pos, true];
+    }
+    // if we got one positive range, and it's a single character, then that's
+    // not actually a magic pattern, it's just that one literal character.
+    // we should not treat that as "magic", we should just return the literal
+    // character. [_] is a perfectly valid way to escape glob magic chars.
+    if (negs.length === 0 &&
+        ranges.length === 1 &&
+        /^\\?.$/.test(ranges[0]) &&
+        !negate) {
+        const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
+        return [regexpEscape(r), false, endPos - pos, false];
+    }
+    const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
+    const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
+    const comb = ranges.length && negs.length
+        ? '(' + sranges + '|' + snegs + ')'
+        : ranges.length
+            ? sranges
+            : snegs;
+    return [comb, uflag, endPos - pos, true];
+};
+//# sourceMappingURL=brace-expressions.js.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/brace-expressions.js.map b/node_modules/minimatch/dist/esm/brace-expressions.js.map
new file mode 100644
index 0000000..cdba30d
--- /dev/null
+++ b/node_modules/minimatch/d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AAC,MAAM,CAAC,CAAC,CAAC,CAAA;QAClE,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,GAAG,GAAG,EAAE,KAAK,CAAC,CAAA;KACrD;IAED,MAAM,OAAO,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,cAAc,CAAC,MAAM,CAAC,GAAG,GAAG,CAAA;IACxE,MAAM,KAAK,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,cAAc,CAAC,IAAI,CAAC,GAAG,GAAG,CAAA;IACpE,MAAM,IAAI,GACR,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM;QAC1B,CAAC,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,GAAG,KAAK,GAAG,GAAG;QACnC,CAAC,CAAC,MAAM,CAAC,MAAM;YACf,CAAC,CAAC,OAAO;YACT,CAAC,CAAC,KAAK,CAAA;IAEX,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,CAAA;AAC1C,CAAC,CAAA","sourcesContent":["// 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"]}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/escape.d.ts b/node_modules/minimatch/dist/esm/escape.d.ts
new file mode 100644
index 0000000..dc3e316
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/escape.d.ts
@@ -0,0 +1,12 @@
+import { MinimatchOptions } from './index.js';
+/**
+ * Escape all magic characters in a glob pattern.
+ *
+ * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
+ * option is used, then characters are escaped by wrapping in `[]`, because
+ * a magic character wrapped in a character class can only be satisfied by
+ * that exact character.  In this mode, `\` is _not_ escaped, because it is
+ * not interpreted as a magic character, but instead as a path separator.
+ */
+export declare const escape: (s: string, { windowsPathsNoEscape, }?: Pick) => string;
+//# sourceMappingURL=escape.d.ts.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/escape.d.ts.map b/node_modules/minimatch/dist/esm/escape.d.ts.map
new file mode 100644
index 0000000..0779dae
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/escape.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"escape.d.ts","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAC7C;;;;;;;;GAQG;AACH,eAAO,MAAM,MAAM,MACd,MAAM,8BAGN,KAAK,gBAAgB,EAAE,sBAAsB,CAAC,WAQlD,CAAA"}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/escape.js b/node_modules/minimatch/dist/esm/escape.js
new file mode 100644
index 0000000..16f7c8c
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/escape.js
@@ -0,0 +1,18 @@
+/**
+ * Escape all magic characters in a glob pattern.
+ *
+ * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
+ * option is used, then characters are escaped by wrapping in `[]`, because
+ * a magic character wrapped in a character class can only be satisfied by
+ * that exact character.  In this mode, `\` is _not_ escaped, because it is
+ * not interpreted as a magic character, but instead as a path separator.
+ */
+export const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
+    // don't need to escape +@! because we escape the parens
+    // that make those magic, and escaping ! as [!] isn't valid,
+    // because [!]] is a valid glob class meaning not ']'.
+    return windowsPathsNoEscape
+        ? s.replace(/[?*()[\]]/g, '[$&]')
+        : s.replace(/[?*()[\]\\]/g, '\\$&');
+};
+//# sourceMappingURL=escape.js.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/escape.js.map b/node_modules/minimatch/dist/esm/escape.js.map
new file mode 100644
index 0000000..170fd1a
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/escape.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"escape.js","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AACA;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,CACpB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,MACsB,EAAE,EACtD,EAAE;IACF,wDAAwD;IACxD,4DAA4D;IAC5D,sDAAsD;IACtD,OAAO,oBAAoB;QACzB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC;QACjC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;AACvC,CAAC,CAAA","sourcesContent":["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"]}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/index.d.ts b/node_modules/minimatch/dist/esm/index.d.ts
new file mode 100644
index 0000000..41d16a9
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/index.d.ts
@@ -0,0 +1,94 @@
+import { AST } from './ast.js';
+type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd';
+export interface MinimatchOptions {
+    nobrace?: boolean;
+    nocomment?: boolean;
+    nonegate?: boolean;
+    debug?: boolean;
+    noglobstar?: boolean;
+    noext?: boolean;
+    nonull?: boolean;
+    windowsPathsNoEscape?: boolean;
+    allowWindowsEscape?: boolean;
+    partial?: boolean;
+    dot?: boolean;
+    nocase?: boolean;
+    nocaseMagicOnly?: boolean;
+    magicalBraces?: boolean;
+    matchBase?: boolean;
+    flipNegate?: boolean;
+    preserveMultipleSlashes?: boolean;
+    optimizationLevel?: number;
+    platform?: Platform;
+    windowsNoMagicRoot?: boolean;
+}
+export declare const minimatch: {
+    (p: string, pattern: string, options?: MinimatchOptions): boolean;
+    sep: Sep;
+    GLOBSTAR: typeof GLOBSTAR;
+    filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean;
+    defaults: (def: MinimatchOptions) => typeof minimatch;
+    braceExpand: (pattern: string, options?: MinimatchOptions) => string[];
+    makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp;
+    match: (list: string[], pattern: string, options?: MinimatchOptions) => string[];
+    AST: typeof AST;
+    Minimatch: typeof Minimatch;
+    escape: (s: string, { windowsPathsNoEscape, }?: Pick) => string;
+    unescape: (s: string, { windowsPathsNoEscape, }?: Pick) => string;
+};
+type Sep = '\\' | '/';
+export declare const sep: Sep;
+export declare const GLOBSTAR: unique symbol;
+export declare const filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean;
+export declare const defaults: (def: MinimatchOptions) => typeof minimatch;
+export declare const braceExpand: (pattern: string, options?: MinimatchOptions) => string[];
+export declare const makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp;
+export declare const match: (list: string[], pattern: string, options?: MinimatchOptions) => string[];
+export type MMRegExp = RegExp & {
+    _src?: string;
+    _glob?: string;
+};
+export type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR;
+export type ParseReturn = ParseReturnFiltered | false;
+export declare class Minimatch {
+    options: MinimatchOptions;
+    set: ParseReturnFiltered[][];
+    pattern: string;
+    windowsPathsNoEscape: boolean;
+    nonegate: boolean;
+    negate: boolean;
+    comment: boolean;
+    empty: boolean;
+    preserveMultipleSlashes: boolean;
+    partial: boolean;
+    globSet: string[];
+    globParts: string[][];
+    nocase: boolean;
+    isWindows: boolean;
+    platform: Platform;
+    windowsNoMagicRoot: boolean;
+    regexp: false | null | MMRegExp;
+    constructor(pattern: string, options?: MinimatchOptions);
+    hasMagic(): boolean;
+    debug(..._: any[]): void;
+    make(): void;
+    preprocess(globParts: string[][]): string[][];
+    adjascentGlobstarOptimize(globParts: string[][]): string[][];
+    levelOneOptimize(globParts: string[][]): string[][];
+    levelTwoFileOptimize(parts: string | string[]): string[];
+    firstPhasePreProcess(globParts: string[][]): string[][];
+    secondPhasePreProcess(globParts: string[][]): string[][];
+    partsMatch(a: string[], b: string[], emptyGSMatch?: boolean): false | string[];
+    parseNegate(): void;
+    matchOne(file: string[], pattern: ParseReturn[], partial?: boolean): boolean;
+    braceExpand(): string[];
+    parse(pattern: string): ParseReturn;
+    makeRe(): false | MMRegExp;
+    slashSplit(p: string): string[];
+    match(f: string, partial?: boolean): boolean;
+    static defaults(def: MinimatchOptions): typeof Minimatch;
+}
+export { AST } from './ast.js';
+export { escape } from './escape.js';
+export { unescape } from './unescape.js';
+//# sourceMappingURL=index.d.ts.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/index.d.ts.map b/node_modules/minimatch/dist/esm/index.d.ts.map
new file mode 100644
index 0000000..195491d
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/index.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,GAAG,EAAe,MAAM,UAAU,CAAA;AAI3C,KAAK,QAAQ,GACT,KAAK,GACL,SAAS,GACT,QAAQ,GACR,SAAS,GACT,OAAO,GACP,OAAO,GACP,SAAS,GACT,OAAO,GACP,OAAO,GACP,QAAQ,GACR,QAAQ,CAAA;AAEZ,MAAM,WAAW,gBAAgB;IAC/B,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,oBAAoB,CAAC,EAAE,OAAO,CAAA;IAC9B,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAC5B,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,GAAG,CAAC,EAAE,OAAO,CAAA;IACb,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,uBAAuB,CAAC,EAAE,OAAO,CAAA;IACjC,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,EAAE,QAAQ,CAAA;IACnB,kBAAkB,CAAC,EAAE,OAAO,CAAA;CAC7B;AAED,e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OAAO,UAAe;IAiEvC,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,gBAAgB;CAGtC;AAED,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAC9B,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA"}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/index.js b/node_modules/minimatch/dist/esm/index.js
new file mode 100644
index 0000000..84b577b
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/index.js
@@ -0,0 +1,1001 @@
+import expand from 'brace-expansion';
+import { assertValidPattern } from './assert-valid-pattern.js';
+import { AST } from './ast.js';
+import { escape } from './escape.js';
+import { unescape } from './unescape.js';
+export const minimatch = (p, pattern, options = {}) => {
+    assertValidPattern(pattern);
+    // shortcut: comments match nothing.
+    if (!options.nocomment && pattern.charAt(0) === '#') {
+        return false;
+    }
+    return new Minimatch(pattern, options).match(p);
+};
+// Optimized checking for the most common glob patterns.
+const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
+const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
+const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
+const starDotExtTestNocase = (ext) => {
+    ext = ext.toLowerCase();
+    return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
+};
+const starDotExtTestNocaseDot = (ext) => {
+    ext = ext.toLowerCase();
+    return (f) => f.toLowerCase().endsWith(ext);
+};
+const starDotStarRE = /^\*+\.\*+$/;
+const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
+const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
+const dotStarRE = /^\.\*+$/;
+const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
+const starRE = /^\*+$/;
+const starTest = (f) => f.length !== 0 && !f.startsWith('.');
+const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
+const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
+const qmarksTestNocase = ([$0, ext = '']) => {
+    const noext = qmarksTestNoExt([$0]);
+    if (!ext)
+        return noext;
+    ext = ext.toLowerCase();
+    return (f) => noext(f) && f.toLowerCase().endsWith(ext);
+};
+const qmarksTestNocaseDot = ([$0, ext = '']) => {
+    const noext = qmarksTestNoExtDot([$0]);
+    if (!ext)
+        return noext;
+    ext = ext.toLowerCase();
+    return (f) => noext(f) && f.toLowerCase().endsWith(ext);
+};
+const qmarksTestDot = ([$0, ext = '']) => {
+    const noext = qmarksTestNoExtDot([$0]);
+    return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
+};
+const qmarksTest = ([$0, ext = '']) => {
+    const noext = qmarksTestNoExt([$0]);
+    return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
+};
+const qmarksTestNoExt = ([$0]) => {
+    const len = $0.length;
+    return (f) => f.length === len && !f.startsWith('.');
+};
+const qmarksTestNoExtDot = ([$0]) => {
+    const len = $0.length;
+    return (f) => f.length === len && f !== '.' && f !== '..';
+};
+/* c8 ignore start */
+const defaultPlatform = (typeof process === 'object' && process
+    ? (typeof process.env === 'object' &&
+        process.env &&
+        process.env.__MINIMATCH_TESTING_PLATFORM__) ||
+        process.platform
+    : 'posix');
+const path = {
+    win32: { sep: '\\' },
+    posix: { sep: '/' },
+};
+/* c8 ignore stop */
+export const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
+minimatch.sep = sep;
+export const GLOBSTAR = Symbol('globstar **');
+minimatch.GLOBSTAR = GLOBSTAR;
+// any single thing other than /
+// don't need to escape / when using new RegExp()
+const qmark = '[^/]';
+// * => any number of characters
+const star = qmark + '*?';
+// ** when dots are allowed.  Anything goes, except .. and .
+// not (^ or / followed by one or two dots followed by $ or /),
+// followed by anything, any number of times.
+const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
+// not a ^ or / followed by a dot,
+// followed by anything, any number of times.
+const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
+export const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
+minimatch.filter = filter;
+const ext = (a, b = {}) => Object.assign({}, a, b);
+export const defaults = (def) => {
+    if (!def || typeof def !== 'object' || !Object.keys(def).length) {
+        return minimatch;
+    }
+    const orig = minimatch;
+    const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
+    return Object.assign(m, {
+        Minimatch: class Minimatch extends orig.Minimatch {
+            constructor(pattern, options = {}) {
+                super(pattern, ext(def, options));
+            }
+            static defaults(options) {
+                return orig.defaults(ext(def, options)).Minimatch;
+            }
+        },
+        AST: class AST extends orig.AST {
+            /* c8 ignore start */
+            constructor(type, parent, options = {}) {
+                super(type, parent, ext(def, options));
+            }
+            /* c8 ignore stop */
+            static fromGlob(pattern, options = {}) {
+                return orig.AST.fromGlob(pattern, ext(def, options));
+            }
+        },
+        unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
+        escape: (s, options = {}) => orig.escape(s, ext(def, options)),
+        filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
+        defaults: (options) => orig.defaults(ext(def, options)),
+        makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
+        braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
+        match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
+        sep: orig.sep,
+        GLOBSTAR: GLOBSTAR,
+    });
+};
+minimatch.defaults = defaults;
+// Brace expansion:
+// a{b,c}d -> abd acd
+// a{b,}c -> abc ac
+// a{0..3}d -> a0d a1d a2d a3d
+// a{b,c{d,e}f}g -> abg acdfg acefg
+// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
+//
+// Invalid sets are not expanded.
+// a{2..}b -> a{2..}b
+// a{b}c -> a{b}c
+export const braceExpand = (pattern, options = {}) => {
+    assertValidPattern(pattern);
+    // Thanks to Yeting Li  for
+    // improving this regexp to avoid a ReDOS vulnerability.
+    if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
+        // shortcut. no need to expand.
+        return [pattern];
+    }
+    return expand(pattern);
+};
+minimatch.braceExpand = braceExpand;
+// parse a component of the expanded set.
+// At this point, no pattern may contain "/" in it
+// so we're going to return a 2d array, where each entry is the full
+// pattern, split on '/', and then turned into a regular expression.
+// A regexp is made at the end which joins each array with an
+// escaped /, and another full one which joins each regexp with |.
+//
+// Following the lead of Bash 4.1, note that "**" only has special meaning
+// when it is the *only* thing in a path portion.  Otherwise, any series
+// of * is equivalent to a single *.  Globstar behavior is enabled by
+// default, and can be disabled by setting options.noglobstar.
+export const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
+minimatch.makeRe = makeRe;
+export const match = (list, pattern, options = {}) => {
+    const mm = new Minimatch(pattern, options);
+    list = list.filter(f => mm.match(f));
+    if (mm.options.nonull && !list.length) {
+        list.push(pattern);
+    }
+    return list;
+};
+minimatch.match = match;
+// replace stuff like \* with *
+const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
+const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
+export class Minimatch {
+    options;
+    set;
+    pattern;
+    windowsPathsNoEscape;
+    nonegate;
+    negate;
+    comment;
+    empty;
+    preserveMultipleSlashes;
+    partial;
+    globSet;
+    globParts;
+    nocase;
+    isWindows;
+    platform;
+    windowsNoMagicRoot;
+    regexp;
+    constructor(pattern, options = {}) {
+        assertValidPattern(pattern);
+        options = options || {};
+        this.options = options;
+        this.pattern = pattern;
+        this.platform = options.platform || defaultPlatform;
+        this.isWindows = this.platform === 'win32';
+        this.windowsPathsNoEscape =
+            !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
+        if (this.windowsPathsNoEscape) {
+            this.pattern = this.pattern.replace(/\\/g, '/');
+        }
+        this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
+        this.regexp = null;
+        this.negate = false;
+        this.nonegate = !!options.nonegate;
+        this.comment = false;
+        this.empty = false;
+        this.partial = !!options.partial;
+        this.nocase = !!this.options.nocase;
+        this.windowsNoMagicRoot =
+            options.windowsNoMagicRoot !== undefined
+                ? options.windowsNoMagicRoot
+                : !!(this.isWindows && this.nocase);
+        this.globSet = [];
+        this.globParts = [];
+        this.set = [];
+        // make the set of regexps etc.
+        this.make();
+    }
+    hasMagic() {
+        if (this.options.magicalBraces && this.set.length > 1) {
+            return true;
+        }
+        for (const pattern of this.set) {
+            for (const part of pattern) {
+                if (typeof part !== 'string')
+                    return true;
+            }
+        }
+        return false;
+    }
+    debug(..._) { }
+    make() {
+        const pattern = this.pattern;
+        const options = this.options;
+        // empty patterns and comments match nothing.
+        if (!options.nocomment && pattern.charAt(0) === '#') {
+            this.comment = true;
+            return;
+        }
+        if (!pattern) {
+            this.empty = true;
+            return;
+        }
+        // step 1: figure out negation, etc.
+        this.parseNegate();
+        // step 2: expand braces
+        this.globSet = [...new Set(this.braceExpand())];
+        if (options.debug) {
+            this.debug = (...args) => console.error(...args);
+        }
+        this.debug(this.pattern, this.globSet);
+        // step 3: now we have a set, so turn each one into a series of
+        // path-portion matching patterns.
+        // These will be regexps, except in the case of "**", which is
+        // set to the GLOBSTAR object for globstar behavior,
+        // and will not contain any / characters
+        //
+        // First, we preprocess to make the glob pattern sets a bit simpler
+        // and deduped.  There are some perf-killing patterns that can cause
+        // problems with a glob walk, but we can simplify them down a bit.
+        const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
+        this.globParts = this.preprocess(rawGlobParts);
+        this.debug(this.pattern, this.globParts);
+        // glob --> regexps
+        let set = this.globParts.map((s, _, __) => {
+            if (this.isWindows && this.windowsNoMagicRoot) {
+                // check if it's a drive or unc path.
+                const isUNC = s[0] === '' &&
+                    s[1] === '' &&
+                    (s[2] === '?' || !globMagic.test(s[2])) &&
+                    !globMagic.test(s[3]);
+                const isDrive = /^[a-z]:/i.test(s[0]);
+                if (isUNC) {
+                    return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
+                }
+                else if (isDrive) {
+                    return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
+                }
+            }
+            return s.map(ss => this.parse(ss));
+        });
+        this.debug(this.pattern, set);
+        // filter out everything that didn't compile properly.
+        this.set = set.filter(s => s.indexOf(false) === -1);
+        // do not treat the ? in UNC paths as magic
+        if (this.isWindows) {
+            for (let i = 0; i < this.set.length; i++) {
+                const p = this.set[i];
+                if (p[0] === '' &&
+                    p[1] === '' &&
+                    this.globParts[i][2] === '?' &&
+                    typeof p[3] === 'string' &&
+                    /^[a-z]:$/i.test(p[3])) {
+                    p[2] = '?';
+                }
+            }
+        }
+        this.debug(this.pattern, this.set);
+    }
+    // various transforms to equivalent pattern sets that are
+    // faster to process in a filesystem walk.  The goal is to
+    // eliminate what we can, and push all ** patterns as far
+    // to the right as possible, even if it increases the number
+    // of patterns that we have to process.
+    preprocess(globParts) {
+        // if we're not in globstar mode, then turn all ** into *
+        if (this.options.noglobstar) {
+            for (let i = 0; i < globParts.length; i++) {
+                for (let j = 0; j < globParts[i].length; j++) {
+                    if (globParts[i][j] === '**') {
+                        globParts[i][j] = '*';
+                    }
+                }
+            }
+        }
+        const { optimizationLevel = 1 } = this.options;
+        if (optimizationLevel >= 2) {
+            // aggressive optimization for the purpose of fs walking
+            globParts = this.firstPhasePreProcess(globParts);
+            globParts = this.secondPhasePreProcess(globParts);
+        }
+        else if (optimizationLevel >= 1) {
+            // just basic optimizations to remove some .. parts
+            globParts = this.levelOneOptimize(globParts);
+        }
+        else {
+            // just collapse multiple ** portions into one
+            globParts = this.adjascentGlobstarOptimize(globParts);
+        }
+        return globParts;
+    }
+    // just get rid of adjascent ** portions
+    adjascentGlobstarOptimize(globParts) {
+        return globParts.map(parts => {
+            let gs = -1;
+            while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
+                let i = gs;
+                while (parts[i + 1] === '**') {
+                    i++;
+                }
+                if (i !== gs) {
+                    parts.splice(gs, i - gs);
+                }
+            }
+            return parts;
+        });
+    }
+    // get rid of adjascent ** and resolve .. portions
+    levelOneOptimize(globParts) {
+        return globParts.map(parts => {
+            parts = parts.reduce((set, part) => {
+                const prev = set[set.length - 1];
+                if (part === '**' && prev === '**') {
+                    return set;
+                }
+                if (part === '..') {
+                    if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
+                        set.pop();
+                        return set;
+                    }
+                }
+                set.push(part);
+                return set;
+            }, []);
+            return parts.length === 0 ? [''] : parts;
+        });
+    }
+    levelTwoFileOptimize(parts) {
+        if (!Array.isArray(parts)) {
+            parts = this.slashSplit(parts);
+        }
+        let didSomething = false;
+        do {
+            didSomething = false;
+            // 
// -> 
/
+            if (!this.preserveMultipleSlashes) {
+                for (let i = 1; i < parts.length - 1; i++) {
+                    const p = parts[i];
+                    // don't squeeze out UNC patterns
+                    if (i === 1 && p === '' && parts[0] === '')
+                        continue;
+                    if (p === '.' || p === '') {
+                        didSomething = true;
+                        parts.splice(i, 1);
+                        i--;
+                    }
+                }
+                if (parts[0] === '.' &&
+                    parts.length === 2 &&
+                    (parts[1] === '.' || parts[1] === '')) {
+                    didSomething = true;
+                    parts.pop();
+                }
+            }
+            // 
/

/../ ->

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

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

/**/../

/

/ -> {

/../

/

/,

/**/

/

/} + //

// -> 
/
+    // 
/

/../ ->

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

/

/ -> {

/../

/

/,

/**/

/

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

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

/../ ->

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

/} ->

/*/
+    // {
/,
/} -> 
/
+    // {
/**/,
/} -> 
/**/
+    //
+    // {
/**/,
/**/

/} ->

/**/
+    // ^-- not valid because ** doens't follow symlinks
+    secondPhasePreProcess(globParts) {
+        for (let i = 0; i < globParts.length - 1; i++) {
+            for (let j = i + 1; j < globParts.length; j++) {
+                const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
+                if (matched) {
+                    globParts[i] = [];
+                    globParts[j] = matched;
+                    break;
+                }
+            }
+        }
+        return globParts.filter(gs => gs.length);
+    }
+    partsMatch(a, b, emptyGSMatch = false) {
+        let ai = 0;
+        let bi = 0;
+        let result = [];
+        let which = '';
+        while (ai < a.length && bi < b.length) {
+            if (a[ai] === b[bi]) {
+                result.push(which === 'b' ? b[bi] : a[ai]);
+                ai++;
+                bi++;
+            }
+            else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
+                result.push(a[ai]);
+                ai++;
+            }
+            else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
+                result.push(b[bi]);
+                bi++;
+            }
+            else if (a[ai] === '*' &&
+                b[bi] &&
+                (this.options.dot || !b[bi].startsWith('.')) &&
+                b[bi] !== '**') {
+                if (which === 'b')
+                    return false;
+                which = 'a';
+                result.push(a[ai]);
+                ai++;
+                bi++;
+            }
+            else if (b[bi] === '*' &&
+                a[ai] &&
+                (this.options.dot || !a[ai].startsWith('.')) &&
+                a[ai] !== '**') {
+                if (which === 'a')
+                    return false;
+                which = 'b';
+                result.push(b[bi]);
+                ai++;
+                bi++;
+            }
+            else {
+                return false;
+            }
+        }
+        // if we fall out of the loop, it means they two are identical
+        // as long as their lengths match
+        return a.length === b.length && result;
+    }
+    parseNegate() {
+        if (this.nonegate)
+            return;
+        const pattern = this.pattern;
+        let negate = false;
+        let negateOffset = 0;
+        for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
+            negate = !negate;
+            negateOffset++;
+        }
+        if (negateOffset)
+            this.pattern = pattern.slice(negateOffset);
+        this.negate = negate;
+    }
+    // set partial to true to test if, for example,
+    // "/a/b" matches the start of "/*/b/*/d"
+    // Partial means, if you run out of file before you run
+    // out of pattern, then that's fine, as long as all
+    // the parts match.
+    matchOne(file, pattern, partial = false) {
+        const options = this.options;
+        // UNC paths like //?/X:/... can match X:/... and vice versa
+        // Drive letters in absolute drive or unc paths are always compared
+        // case-insensitively.
+        if (this.isWindows) {
+            const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
+            const fileUNC = !fileDrive &&
+                file[0] === '' &&
+                file[1] === '' &&
+                file[2] === '?' &&
+                /^[a-z]:$/i.test(file[3]);
+            const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
+            const patternUNC = !patternDrive &&
+                pattern[0] === '' &&
+                pattern[1] === '' &&
+                pattern[2] === '?' &&
+                typeof pattern[3] === 'string' &&
+                /^[a-z]:$/i.test(pattern[3]);
+            const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
+            const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
+            if (typeof fdi === 'number' && typeof pdi === 'number') {
+                const [fd, pd] = [file[fdi], pattern[pdi]];
+                if (fd.toLowerCase() === pd.toLowerCase()) {
+                    pattern[pdi] = fd;
+                    if (pdi > fdi) {
+                        pattern = pattern.slice(pdi);
+                    }
+                    else if (fdi > pdi) {
+                        file = file.slice(fdi);
+                    }
+                }
+            }
+        }
+        // resolve and reduce . and .. portions in the file as well.
+        // dont' need to do the second phase, because it's only one string[]
+        const { optimizationLevel = 1 } = this.options;
+        if (optimizationLevel >= 2) {
+            file = this.levelTwoFileOptimize(file);
+        }
+        this.debug('matchOne', this, { file, pattern });
+        this.debug('matchOne', file.length, pattern.length);
+        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
+            this.debug('matchOne loop');
+            var p = pattern[pi];
+            var f = file[fi];
+            this.debug(pattern, p, f);
+            // should be impossible.
+            // some invalid regexp stuff in the set.
+            /* c8 ignore start */
+            if (p === false) {
+                return false;
+            }
+            /* c8 ignore stop */
+            if (p === GLOBSTAR) {
+                this.debug('GLOBSTAR', [pattern, p, f]);
+                // "**"
+                // a/**/b/**/c would match the following:
+                // a/b/x/y/z/c
+                // a/x/y/z/b/c
+                // a/b/x/b/x/c
+                // a/b/c
+                // To do this, take the rest of the pattern after
+                // the **, and see if it would match the file remainder.
+                // If so, return success.
+                // If not, the ** "swallows" a segment, and try again.
+                // This is recursively awful.
+                //
+                // a/**/b/**/c matching a/b/x/y/z/c
+                // - a matches a
+                // - doublestar
+                //   - matchOne(b/x/y/z/c, b/**/c)
+                //     - b matches b
+                //     - doublestar
+                //       - matchOne(x/y/z/c, c) -> no
+                //       - matchOne(y/z/c, c) -> no
+                //       - matchOne(z/c, c) -> no
+                //       - matchOne(c, c) yes, hit
+                var fr = fi;
+                var pr = pi + 1;
+                if (pr === pl) {
+                    this.debug('** at the end');
+                    // a ** at the end will just swallow the rest.
+                    // We have found a match.
+                    // however, it will not swallow /.x, unless
+                    // options.dot is set.
+                    // . and .. are *never* matched by **, for explosively
+                    // exponential reasons.
+                    for (; fi < fl; fi++) {
+                        if (file[fi] === '.' ||
+                            file[fi] === '..' ||
+                            (!options.dot && file[fi].charAt(0) === '.'))
+                            return false;
+                    }
+                    return true;
+                }
+                // ok, let's see if we can swallow whatever we can.
+                while (fr < fl) {
+                    var swallowee = file[fr];
+                    this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
+                    // XXX remove this slice.  Just pass the start index.
+                    if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
+                        this.debug('globstar found match!', fr, fl, swallowee);
+                        // found a match.
+                        return true;
+                    }
+                    else {
+                        // can't swallow "." or ".." ever.
+                        // can only swallow ".foo" when explicitly asked.
+                        if (swallowee === '.' ||
+                            swallowee === '..' ||
+                            (!options.dot && swallowee.charAt(0) === '.')) {
+                            this.debug('dot detected!', file, fr, pattern, pr);
+                            break;
+                        }
+                        // ** swallows a segment, and continue.
+                        this.debug('globstar swallow a segment, and continue');
+                        fr++;
+                    }
+                }
+                // no match was found.
+                // However, in partial mode, we can't say this is necessarily over.
+                /* c8 ignore start */
+                if (partial) {
+                    // ran out of file
+                    this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
+                    if (fr === fl) {
+                        return true;
+                    }
+                }
+                /* c8 ignore stop */
+                return false;
+            }
+            // something other than **
+            // non-magic patterns just have to match exactly
+            // patterns with magic have been turned into regexps.
+            let hit;
+            if (typeof p === 'string') {
+                hit = f === p;
+                this.debug('string match', p, f, hit);
+            }
+            else {
+                hit = p.test(f);
+                this.debug('pattern match', p, f, hit);
+            }
+            if (!hit)
+                return false;
+        }
+        // Note: ending in / means that we'll get a final ""
+        // at the end of the pattern.  This can only match a
+        // corresponding "" at the end of the file.
+        // If the file ends in /, then it can only match a
+        // a pattern that ends in /, unless the pattern just
+        // doesn't have any more for it. But, a/b/ should *not*
+        // match "a/b/*", even though "" matches against the
+        // [^/]*? pattern, except in partial mode, where it might
+        // simply not be reached yet.
+        // However, a/b/ should still satisfy a/*
+        // now either we fell off the end of the pattern, or we're done.
+        if (fi === fl && pi === pl) {
+            // ran out of pattern and filename at the same time.
+            // an exact hit!
+            return true;
+        }
+        else if (fi === fl) {
+            // ran out of file, but still had pattern left.
+            // this is ok if we're doing the match as part of
+            // a glob fs traversal.
+            return partial;
+        }
+        else if (pi === pl) {
+            // ran out of pattern, still have file left.
+            // this is only acceptable if we're on the very last
+            // empty segment of a file with a trailing slash.
+            // a/* should match a/b/
+            return fi === fl - 1 && file[fi] === '';
+            /* c8 ignore start */
+        }
+        else {
+            // should be unreachable.
+            throw new Error('wtf?');
+        }
+        /* c8 ignore stop */
+    }
+    braceExpand() {
+        return braceExpand(this.pattern, this.options);
+    }
+    parse(pattern) {
+        assertValidPattern(pattern);
+        const options = this.options;
+        // shortcuts
+        if (pattern === '**')
+            return GLOBSTAR;
+        if (pattern === '')
+            return '';
+        // far and away, the most common glob pattern parts are
+        // *, *.*, and *.  Add a fast check method for those.
+        let m;
+        let fastTest = null;
+        if ((m = pattern.match(starRE))) {
+            fastTest = options.dot ? starTestDot : starTest;
+        }
+        else if ((m = pattern.match(starDotExtRE))) {
+            fastTest = (options.nocase
+                ? options.dot
+                    ? starDotExtTestNocaseDot
+                    : starDotExtTestNocase
+                : options.dot
+                    ? starDotExtTestDot
+                    : starDotExtTest)(m[1]);
+        }
+        else if ((m = pattern.match(qmarksRE))) {
+            fastTest = (options.nocase
+                ? options.dot
+                    ? qmarksTestNocaseDot
+                    : qmarksTestNocase
+                : options.dot
+                    ? qmarksTestDot
+                    : qmarksTest)(m);
+        }
+        else if ((m = pattern.match(starDotStarRE))) {
+            fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
+        }
+        else if ((m = pattern.match(dotStarRE))) {
+            fastTest = dotStarTest;
+        }
+        const re = AST.fromGlob(pattern, this.options).toMMPattern();
+        if (fastTest && typeof re === 'object') {
+            // Avoids overriding in frozen environments
+            Reflect.defineProperty(re, 'test', { value: fastTest });
+        }
+        return re;
+    }
+    makeRe() {
+        if (this.regexp || this.regexp === false)
+            return this.regexp;
+        // at this point, this.set is a 2d array of partial
+        // pattern strings, or "**".
+        //
+        // It's better to use .match().  This function shouldn't
+        // be used, really, but it's pretty convenient sometimes,
+        // when you just want to work with a regex.
+        const set = this.set;
+        if (!set.length) {
+            this.regexp = false;
+            return this.regexp;
+        }
+        const options = this.options;
+        const twoStar = options.noglobstar
+            ? star
+            : options.dot
+                ? twoStarDot
+                : twoStarNoDot;
+        const flags = new Set(options.nocase ? ['i'] : []);
+        // regexpify non-globstar patterns
+        // if ** is only item, then we just do one twoStar
+        // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
+        // if ** is last, append (\/twoStar|) to previous
+        // if ** is in the middle, append (\/|\/twoStar\/) to previous
+        // then filter out GLOBSTAR symbols
+        let re = set
+            .map(pattern => {
+            const pp = pattern.map(p => {
+                if (p instanceof RegExp) {
+                    for (const f of p.flags.split(''))
+                        flags.add(f);
+                }
+                return typeof p === 'string'
+                    ? regExpEscape(p)
+                    : p === GLOBSTAR
+                        ? GLOBSTAR
+                        : p._src;
+            });
+            pp.forEach((p, i) => {
+                const next = pp[i + 1];
+                const prev = pp[i - 1];
+                if (p !== GLOBSTAR || prev === GLOBSTAR) {
+                    return;
+                }
+                if (prev === undefined) {
+                    if (next !== undefined && next !== GLOBSTAR) {
+                        pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
+                    }
+                    else {
+                        pp[i] = twoStar;
+                    }
+                }
+                else if (next === undefined) {
+                    pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
+                }
+                else if (next !== GLOBSTAR) {
+                    pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
+                    pp[i + 1] = GLOBSTAR;
+                }
+            });
+            return pp.filter(p => p !== GLOBSTAR).join('/');
+        })
+            .join('|');
+        // need to wrap in parens if we had more than one thing with |,
+        // otherwise only the first will be anchored to ^ and the last to $
+        const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
+        // must match entire pattern
+        // ending in a * or ** will make it less strict.
+        re = '^' + open + re + close + '$';
+        // can match anything, as long as it's not this.
+        if (this.negate)
+            re = '^(?!' + re + ').+$';
+        try {
+            this.regexp = new RegExp(re, [...flags].join(''));
+            /* c8 ignore start */
+        }
+        catch (ex) {
+            // should be impossible
+            this.regexp = false;
+        }
+        /* c8 ignore stop */
+        return this.regexp;
+    }
+    slashSplit(p) {
+        // if p starts with // on windows, we preserve that
+        // so that UNC paths aren't broken.  Otherwise, any number of
+        // / characters are coalesced into one, unless
+        // preserveMultipleSlashes is set to true.
+        if (this.preserveMultipleSlashes) {
+            return p.split('/');
+        }
+        else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
+            // add an extra '' for the one we lose
+            return ['', ...p.split(/\/+/)];
+        }
+        else {
+            return p.split(/\/+/);
+        }
+    }
+    match(f, partial = this.partial) {
+        this.debug('match', f, this.pattern);
+        // short-circuit in the case of busted things.
+        // comments, etc.
+        if (this.comment) {
+            return false;
+        }
+        if (this.empty) {
+            return f === '';
+        }
+        if (f === '/' && partial) {
+            return true;
+        }
+        const options = this.options;
+        // windows: need to use /, not \
+        if (this.isWindows) {
+            f = f.split('\\').join('/');
+        }
+        // treat the test path as a set of pathparts.
+        const ff = this.slashSplit(f);
+        this.debug(this.pattern, 'split', ff);
+        // just ONE of the pattern sets in this.set needs to match
+        // in order for it to be valid.  If negating, then just one
+        // match means that we have failed.
+        // Either way, return on the first hit.
+        const set = this.set;
+        this.debug(this.pattern, 'set', set);
+        // Find the basename of the path by looking for the last non-empty segment
+        let filename = ff[ff.length - 1];
+        if (!filename) {
+            for (let i = ff.length - 2; !filename && i >= 0; i--) {
+                filename = ff[i];
+            }
+        }
+        for (let i = 0; i < set.length; i++) {
+            const pattern = set[i];
+            let file = ff;
+            if (options.matchBase && pattern.length === 1) {
+                file = [filename];
+            }
+            const hit = this.matchOne(file, pattern, partial);
+            if (hit) {
+                if (options.flipNegate) {
+                    return true;
+                }
+                return !this.negate;
+            }
+        }
+        // didn't get any hits.  this is success if it's a negative
+        // pattern, failure otherwise.
+        if (options.flipNegate) {
+            return false;
+        }
+        return this.negate;
+    }
+    static defaults(def) {
+        return minimatch.defaults(def).Minimatch;
+    }
+}
+/* c8 ignore start */
+export { AST } from './ast.js';
+export { escape } from './escape.js';
+export { unescape } from './unescape.js';
+/* c8 ignore stop */
+minimatch.AST = AST;
+minimatch.Minimatch = Minimatch;
+minimatch.escape = escape;
+minimatch.unescape = unescape;
+//# sourceMappingURL=index.js.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/index.js.map b/node_modules/minimatch/dist/esm/index.js.map
new file mode 100644
index 0000000..ff82a0d
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/index.js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AO,CAAC,UAAU,EAAE;oBACtB,OAAO,IAAI,CAAA;iBACZ;gBACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAA;aACpB;SACF;QAED,2DAA2D;QAC3D,8BAA8B;QAC9B,IAAI,OAAO,CAAC,UAAU,EAAE;YACtB,OAAO,KAAK,CAAA;SACb;QACD,OAAO,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;IAED,MAAM,CAAC,QAAQ,CAAC,GAAqB;QACnC,OAAO,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,SAAS,CAAA;IAC1C,CAAC;CACF;AACD,qBAAqB;AACrB,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAC9B,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AACxC,oBAAoB;AACpB,SAAS,CAAC,GAAG,GAAG,GAAG,CAAA;AACnB,SAAS,CAAC,SAAS,GAAG,SAAS,CAAA;AAC/B,SAAS,CAAC,MAAM,GAAG,MAAM,CAAA;AACzB,SAAS,CAAC,QAAQ,GAAG,QAAQ,CAAA","sourcesContent":["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      // just collapse multiple ** portions into one\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) {\n          globParts[i] = []\n          globParts[j] = matched\n          break\n        }\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    if (fastTest && typeof re === 'object') {\n      // Avoids overriding in frozen environments\n      Reflect.defineProperty(re, 'test', { value: fastTest })\n    }\n    return 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"]}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/package.json b/node_modules/minimatch/dist/esm/package.json
new file mode 100644
index 0000000..3dbc1ca
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/package.json
@@ -0,0 +1,3 @@
+{
+  "type": "module"
+}
diff --git a/node_modules/minimatch/dist/esm/unescape.d.ts b/node_modules/minimatch/dist/esm/unescape.d.ts
new file mode 100644
index 0000000..23a7b38
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/unescape.d.ts
@@ -0,0 +1,17 @@
+import { MinimatchOptions } from './index.js';
+/**
+ * Un-escape a string that has been escaped with {@link escape}.
+ *
+ * If the {@link windowsPathsNoEscape} option is used, then square-brace
+ * escapes are removed, but not backslash escapes.  For example, it will turn
+ * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
+ * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
+ *
+ * When `windowsPathsNoEscape` is not set, then both brace escapes and
+ * backslash escapes are removed.
+ *
+ * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
+ * or unescaped.
+ */
+export declare const unescape: (s: string, { windowsPathsNoEscape, }?: Pick) => string;
+//# sourceMappingURL=unescape.d.ts.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/unescape.d.ts.map b/node_modules/minimatch/dist/esm/unescape.d.ts.map
new file mode 100644
index 0000000..7ace070
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/unescape.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"unescape.d.ts","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAC7C;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,QAAQ,MAChB,MAAM,8BAGN,KAAK,gBAAgB,EAAE,sBAAsB,CAAC,WAKlD,CAAA"}
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/unescape.js b/node_modules/minimatch/dist/esm/unescape.js
new file mode 100644
index 0000000..0faf9a2
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/unescape.js
@@ -0,0 +1,20 @@
+/**
+ * Un-escape a string that has been escaped with {@link escape}.
+ *
+ * If the {@link windowsPathsNoEscape} option is used, then square-brace
+ * escapes are removed, but not backslash escapes.  For example, it will turn
+ * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
+ * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
+ *
+ * When `windowsPathsNoEscape` is not set, then both brace escapes and
+ * backslash escapes are removed.
+ *
+ * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
+ * or unescaped.
+ */
+export const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
+    return windowsPathsNoEscape
+        ? s.replace(/\[([^\/\\])\]/g, '$1')
+        : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
+};
+//# sourceMappingURL=unescape.js.map
\ No newline at end of file
diff --git a/node_modules/minimatch/dist/esm/unescape.js.map b/node_modules/minimatch/dist/esm/unescape.js.map
new file mode 100644
index 0000000..eb146c2
--- /dev/null
+++ b/node_modules/minimatch/dist/esm/unescape.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"unescape.js","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AACA;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,MACsB,EAAE,EACtD,EAAE;IACF,OAAO,oBAAoB;QACzB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,gBAAgB,EAAE,IAAI,CAAC;QACnC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,2BAA2B,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,IAAI,CAAC,CAAA;AAChF,CAAC,CAAA","sourcesContent":["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"]}
\ No newline at end of file
diff --git a/node_modules/minimatch/package.json b/node_modules/minimatch/package.json
new file mode 100644
index 0000000..01fc48e
--- /dev/null
+++ b/node_modules/minimatch/package.json
@@ -0,0 +1,82 @@
+{
+  "author": "Isaac Z. Schlueter  (http://blog.izs.me)",
+  "name": "minimatch",
+  "description": "a glob matcher in javascript",
+  "version": "9.0.5",
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/isaacs/minimatch.git"
+  },
+  "main": "./dist/commonjs/index.js",
+  "types": "./dist/commonjs/index.d.ts",
+  "exports": {
+    "./package.json": "./package.json",
+    ".": {
+      "import": {
+        "types": "./dist/esm/index.d.ts",
+        "default": "./dist/esm/index.js"
+      },
+      "require": {
+        "types": "./dist/commonjs/index.d.ts",
+        "default": "./dist/commonjs/index.js"
+      }
+    }
+  },
+  "files": [
+    "dist"
+  ],
+  "scripts": {
+    "preversion": "npm test",
+    "postversion": "npm publish",
+    "prepublishOnly": "git push origin --follow-tags",
+    "prepare": "tshy",
+    "pretest": "npm run prepare",
+    "presnap": "npm run prepare",
+    "test": "tap",
+    "snap": "tap",
+    "format": "prettier --write . --loglevel warn",
+    "benchmark": "node benchmark/index.js",
+    "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts"
+  },
+  "prettier": {
+    "semi": false,
+    "printWidth": 80,
+    "tabWidth": 2,
+    "useTabs": false,
+    "singleQuote": true,
+    "jsxSingleQuote": false,
+    "bracketSameLine": true,
+    "arrowParens": "avoid",
+    "endOfLine": "lf"
+  },
+  "engines": {
+    "node": ">=16 || 14 >=14.17"
+  },
+  "dependencies": {
+    "brace-expansion": "^2.0.1"
+  },
+  "devDependencies": {
+    "@types/brace-expansion": "^1.1.0",
+    "@types/node": "^18.15.11",
+    "@types/tap": "^15.0.8",
+    "eslint-config-prettier": "^8.6.0",
+    "mkdirp": "1",
+    "prettier": "^2.8.2",
+    "tap": "^18.7.2",
+    "ts-node": "^10.9.1",
+    "tshy": "^1.12.0",
+    "typedoc": "^0.23.21",
+    "typescript": "^4.9.3"
+  },
+  "funding": {
+    "url": "https://github.com/sponsors/isaacs"
+  },
+  "license": "ISC",
+  "tshy": {
+    "exports": {
+      "./package.json": "./package.json",
+      ".": "./src/index.ts"
+    }
+  },
+  "type": "module"
+}
diff --git a/node_modules/minipass/LICENSE b/node_modules/minipass/LICENSE
new file mode 100644
index 0000000..97f8e32
--- /dev/null
+++ b/node_modules/minipass/LICENSE
@@ -0,0 +1,15 @@
+The ISC License
+
+Copyright (c) 2017-2023 npm, Inc., Isaac Z. Schlueter, and Contributors
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/node_modules/minipass/README.md b/node_modules/minipass/README.md
new file mode 100644
index 0000000..1126330
--- /dev/null
+++ b/node_modules/minipass/README.md
@@ -0,0 +1,825 @@
+# minipass
+
+A _very_ minimal implementation of a [PassThrough
+stream](https://nodejs.org/api/stream.html#stream_class_stream_passthrough)
+
+[It's very
+fast](https://docs.google.com/spreadsheets/d/1K_HR5oh3r80b8WVMWCPPjfuWXUgfkmhlX7FGI6JJ8tY/edit?usp=sharing)
+for objects, strings, and buffers.
+
+Supports `pipe()`ing (including multi-`pipe()` and backpressure
+transmission), buffering data until either a `data` event handler
+or `pipe()` is added (so you don't lose the first chunk), and
+most other cases where PassThrough is a good idea.
+
+There is a `read()` method, but it's much more efficient to
+consume data from this stream via `'data'` events or by calling
+`pipe()` into some other stream. Calling `read()` requires the
+buffer to be flattened in some cases, which requires copying
+memory.
+
+If you set `objectMode: true` in the options, then whatever is
+written will be emitted. Otherwise, it'll do a minimal amount of
+Buffer copying to ensure proper Streams semantics when `read(n)`
+is called.
+
+`objectMode` can only be set at instantiation. Attempting to
+write something other than a String or Buffer without having set
+`objectMode` in the options will throw an error.
+
+This is not a `through` or `through2` stream. It doesn't
+transform the data, it just passes it right through. If you want
+to transform the data, extend the class, and override the
+`write()` method. Once you're done transforming the data however
+you want, call `super.write()` with the transform output.
+
+For some examples of streams that extend Minipass in various
+ways, check out:
+
+- [minizlib](http://npm.im/minizlib)
+- [fs-minipass](http://npm.im/fs-minipass)
+- [tar](http://npm.im/tar)
+- [minipass-collect](http://npm.im/minipass-collect)
+- [minipass-flush](http://npm.im/minipass-flush)
+- [minipass-pipeline](http://npm.im/minipass-pipeline)
+- [tap](http://npm.im/tap)
+- [tap-parser](http://npm.im/tap-parser)
+- [treport](http://npm.im/treport)
+- [minipass-fetch](http://npm.im/minipass-fetch)
+- [pacote](http://npm.im/pacote)
+- [make-fetch-happen](http://npm.im/make-fetch-happen)
+- [cacache](http://npm.im/cacache)
+- [ssri](http://npm.im/ssri)
+- [npm-registry-fetch](http://npm.im/npm-registry-fetch)
+- [minipass-json-stream](http://npm.im/minipass-json-stream)
+- [minipass-sized](http://npm.im/minipass-sized)
+
+## Usage in TypeScript
+
+The `Minipass` class takes three type template definitions:
+
+- `RType` the type being read, which defaults to `Buffer`. If
+  `RType` is `string`, then the constructor _must_ get an options
+  object specifying either an `encoding` or `objectMode: true`.
+  If it's anything other than `string` or `Buffer`, then it
+  _must_ get an options object specifying `objectMode: true`.
+- `WType` the type being written. If `RType` is `Buffer` or
+  `string`, then this defaults to `ContiguousData` (Buffer,
+  string, ArrayBuffer, or ArrayBufferView). Otherwise, it
+  defaults to `RType`.
+- `Events` type mapping event names to the arguments emitted
+  with that event, which extends `Minipass.Events`.
+
+To declare types for custom events in subclasses, extend the
+third parameter with your own event signatures. For example:
+
+```js
+import { Minipass } from 'minipass'
+
+// a NDJSON stream that emits 'jsonError' when it can't stringify
+export interface Events extends Minipass.Events {
+  jsonError: [e: Error]
+}
+
+export class NDJSONStream extends Minipass {
+  constructor() {
+    super({ objectMode: true })
+  }
+
+  // data is type `any` because that's WType
+  write(data, encoding, cb) {
+    try {
+      const json = JSON.stringify(data)
+      return super.write(json + '\n', encoding, cb)
+    } catch (er) {
+      if (!er instanceof Error) {
+        er = Object.assign(new Error('json stringify failed'), {
+          cause: er,
+        })
+      }
+      // trying to emit with something OTHER than an error will
+      // fail, because we declared the event arguments type.
+      this.emit('jsonError', er)
+    }
+  }
+}
+
+const s = new NDJSONStream()
+s.on('jsonError', e => {
+  // here, TS knows that e is an Error
+})
+```
+
+Emitting/handling events that aren't declared in this way is
+fine, but the arguments will be typed as `unknown`.
+
+## Differences from Node.js Streams
+
+There are several things that make Minipass streams different
+from (and in some ways superior to) Node.js core streams.
+
+Please read these caveats if you are familiar with node-core
+streams and intend to use Minipass streams in your programs.
+
+You can avoid most of these differences entirely (for a very
+small performance penalty) by setting `{async: true}` in the
+constructor options.
+
+### Timing
+
+Minipass streams are designed to support synchronous use-cases.
+Thus, data is emitted as soon as it is available, always. It is
+buffered until read, but no longer. Another way to look at it is
+that Minipass streams are exactly as synchronous as the logic
+that writes into them.
+
+This can be surprising if your code relies on
+`PassThrough.write()` always providing data on the next tick
+rather than the current one, or being able to call `resume()` and
+not have the entire buffer disappear immediately.
+
+However, without this synchronicity guarantee, there would be no
+way for Minipass to achieve the speeds it does, or support the
+synchronous use cases that it does. Simply put, waiting takes
+time.
+
+This non-deferring approach makes Minipass streams much easier to
+reason about, especially in the context of Promises and other
+flow-control mechanisms.
+
+Example:
+
+```js
+// hybrid module, either works
+import { Minipass } from 'minipass'
+// or:
+const { Minipass } = require('minipass')
+
+const stream = new Minipass()
+stream.on('data', () => console.log('data event'))
+console.log('before write')
+stream.write('hello')
+console.log('after write')
+// output:
+// before write
+// data event
+// after write
+```
+
+### Exception: Async Opt-In
+
+If you wish to have a Minipass stream with behavior that more
+closely mimics Node.js core streams, you can set the stream in
+async mode either by setting `async: true` in the constructor
+options, or by setting `stream.async = true` later on.
+
+```js
+// hybrid module, either works
+import { Minipass } from 'minipass'
+// or:
+const { Minipass } = require('minipass')
+
+const asyncStream = new Minipass({ async: true })
+asyncStream.on('data', () => console.log('data event'))
+console.log('before write')
+asyncStream.write('hello')
+console.log('after write')
+// output:
+// before write
+// after write
+// data event <-- this is deferred until the next tick
+```
+
+Switching _out_ of async mode is unsafe, as it could cause data
+corruption, and so is not enabled. Example:
+
+```js
+import { Minipass } from 'minipass'
+const stream = new Minipass({ encoding: 'utf8' })
+stream.on('data', chunk => console.log(chunk))
+stream.async = true
+console.log('before writes')
+stream.write('hello')
+setStreamSyncAgainSomehow(stream) // <-- this doesn't actually exist!
+stream.write('world')
+console.log('after writes')
+// hypothetical output would be:
+// before writes
+// world
+// after writes
+// hello
+// NOT GOOD!
+```
+
+To avoid this problem, once set into async mode, any attempt to
+make the stream sync again will be ignored.
+
+```js
+const { Minipass } = require('minipass')
+const stream = new Minipass({ encoding: 'utf8' })
+stream.on('data', chunk => console.log(chunk))
+stream.async = true
+console.log('before writes')
+stream.write('hello')
+stream.async = false // <-- no-op, stream already async
+stream.write('world')
+console.log('after writes')
+// actual output:
+// before writes
+// after writes
+// hello
+// world
+```
+
+### No High/Low Water Marks
+
+Node.js core streams will optimistically fill up a buffer,
+returning `true` on all writes until the limit is hit, even if
+the data has nowhere to go. Then, they will not attempt to draw
+more data in until the buffer size dips below a minimum value.
+
+Minipass streams are much simpler. The `write()` method will
+return `true` if the data has somewhere to go (which is to say,
+given the timing guarantees, that the data is already there by
+the time `write()` returns).
+
+If the data has nowhere to go, then `write()` returns false, and
+the data sits in a buffer, to be drained out immediately as soon
+as anyone consumes it.
+
+Since nothing is ever buffered unnecessarily, there is much less
+copying data, and less bookkeeping about buffer capacity levels.
+
+### Hazards of Buffering (or: Why Minipass Is So Fast)
+
+Since data written to a Minipass stream is immediately written
+all the way through the pipeline, and `write()` always returns
+true/false based on whether the data was fully flushed,
+backpressure is communicated immediately to the upstream caller.
+This minimizes buffering.
+
+Consider this case:
+
+```js
+const { PassThrough } = require('stream')
+const p1 = new PassThrough({ highWaterMark: 1024 })
+const p2 = new PassThrough({ highWaterMark: 1024 })
+const p3 = new PassThrough({ highWaterMark: 1024 })
+const p4 = new PassThrough({ highWaterMark: 1024 })
+
+p1.pipe(p2).pipe(p3).pipe(p4)
+p4.on('data', () => console.log('made it through'))
+
+// this returns false and buffers, then writes to p2 on next tick (1)
+// p2 returns false and buffers, pausing p1, then writes to p3 on next tick (2)
+// p3 returns false and buffers, pausing p2, then writes to p4 on next tick (3)
+// p4 returns false and buffers, pausing p3, then emits 'data' and 'drain'
+// on next tick (4)
+// p3 sees p4's 'drain' event, and calls resume(), emitting 'resume' and
+// 'drain' on next tick (5)
+// p2 sees p3's 'drain', calls resume(), emits 'resume' and 'drain' on next tick (6)
+// p1 sees p2's 'drain', calls resume(), emits 'resume' and 'drain' on next
+// tick (7)
+
+p1.write(Buffer.alloc(2048)) // returns false
+```
+
+Along the way, the data was buffered and deferred at each stage,
+and multiple event deferrals happened, for an unblocked pipeline
+where it was perfectly safe to write all the way through!
+
+Furthermore, setting a `highWaterMark` of `1024` might lead
+someone reading the code to think an advisory maximum of 1KiB is
+being set for the pipeline. However, the actual advisory
+buffering level is the _sum_ of `highWaterMark` values, since
+each one has its own bucket.
+
+Consider the Minipass case:
+
+```js
+const m1 = new Minipass()
+const m2 = new Minipass()
+const m3 = new Minipass()
+const m4 = new Minipass()
+
+m1.pipe(m2).pipe(m3).pipe(m4)
+m4.on('data', () => console.log('made it through'))
+
+// m1 is flowing, so it writes the data to m2 immediately
+// m2 is flowing, so it writes the data to m3 immediately
+// m3 is flowing, so it writes the data to m4 immediately
+// m4 is flowing, so it fires the 'data' event immediately, returns true
+// m4's write returned true, so m3 is still flowing, returns true
+// m3's write returned true, so m2 is still flowing, returns true
+// m2's write returned true, so m1 is still flowing, returns true
+// No event deferrals or buffering along the way!
+
+m1.write(Buffer.alloc(2048)) // returns true
+```
+
+It is extremely unlikely that you _don't_ want to buffer any data
+written, or _ever_ buffer data that can be flushed all the way
+through. Neither node-core streams nor Minipass ever fail to
+buffer written data, but node-core streams do a lot of
+unnecessary buffering and pausing.
+
+As always, the faster implementation is the one that does less
+stuff and waits less time to do it.
+
+### Immediately emit `end` for empty streams (when not paused)
+
+If a stream is not paused, and `end()` is called before writing
+any data into it, then it will emit `end` immediately.
+
+If you have logic that occurs on the `end` event which you don't
+want to potentially happen immediately (for example, closing file
+descriptors, moving on to the next entry in an archive parse
+stream, etc.) then be sure to call `stream.pause()` on creation,
+and then `stream.resume()` once you are ready to respond to the
+`end` event.
+
+However, this is _usually_ not a problem because:
+
+### Emit `end` When Asked
+
+One hazard of immediately emitting `'end'` is that you may not
+yet have had a chance to add a listener. In order to avoid this
+hazard, Minipass streams safely re-emit the `'end'` event if a
+new listener is added after `'end'` has been emitted.
+
+Ie, if you do `stream.on('end', someFunction)`, and the stream
+has already emitted `end`, then it will call the handler right
+away. (You can think of this somewhat like attaching a new
+`.then(fn)` to a previously-resolved Promise.)
+
+To prevent calling handlers multiple times who would not expect
+multiple ends to occur, all listeners are removed from the
+`'end'` event whenever it is emitted.
+
+### Emit `error` When Asked
+
+The most recent error object passed to the `'error'` event is
+stored on the stream. If a new `'error'` event handler is added,
+and an error was previously emitted, then the event handler will
+be called immediately (or on `process.nextTick` in the case of
+async streams).
+
+This makes it much more difficult to end up trying to interact
+with a broken stream, if the error handler is added after an
+error was previously emitted.
+
+### Impact of "immediate flow" on Tee-streams
+
+A "tee stream" is a stream piping to multiple destinations:
+
+```js
+const tee = new Minipass()
+t.pipe(dest1)
+t.pipe(dest2)
+t.write('foo') // goes to both destinations
+```
+
+Since Minipass streams _immediately_ process any pending data
+through the pipeline when a new pipe destination is added, this
+can have surprising effects, especially when a stream comes in
+from some other function and may or may not have data in its
+buffer.
+
+```js
+// WARNING! WILL LOSE DATA!
+const src = new Minipass()
+src.write('foo')
+src.pipe(dest1) // 'foo' chunk flows to dest1 immediately, and is gone
+src.pipe(dest2) // gets nothing!
+```
+
+One solution is to create a dedicated tee-stream junction that
+pipes to both locations, and then pipe to _that_ instead.
+
+```js
+// Safe example: tee to both places
+const src = new Minipass()
+src.write('foo')
+const tee = new Minipass()
+tee.pipe(dest1)
+tee.pipe(dest2)
+src.pipe(tee) // tee gets 'foo', pipes to both locations
+```
+
+The same caveat applies to `on('data')` event listeners. The
+first one added will _immediately_ receive all of the data,
+leaving nothing for the second:
+
+```js
+// WARNING! WILL LOSE DATA!
+const src = new Minipass()
+src.write('foo')
+src.on('data', handler1) // receives 'foo' right away
+src.on('data', handler2) // nothing to see here!
+```
+
+Using a dedicated tee-stream can be used in this case as well:
+
+```js
+// Safe example: tee to both data handlers
+const src = new Minipass()
+src.write('foo')
+const tee = new Minipass()
+tee.on('data', handler1)
+tee.on('data', handler2)
+src.pipe(tee)
+```
+
+All of the hazards in this section are avoided by setting `{
+async: true }` in the Minipass constructor, or by setting
+`stream.async = true` afterwards. Note that this does add some
+overhead, so should only be done in cases where you are willing
+to lose a bit of performance in order to avoid having to refactor
+program logic.
+
+## USAGE
+
+It's a stream! Use it like a stream and it'll most likely do what
+you want.
+
+```js
+import { Minipass } from 'minipass'
+const mp = new Minipass(options) // options is optional
+mp.write('foo')
+mp.pipe(someOtherStream)
+mp.end('bar')
+```
+
+### OPTIONS
+
+- `encoding` How would you like the data coming _out_ of the
+  stream to be encoded? Accepts any values that can be passed to
+  `Buffer.toString()`.
+- `objectMode` Emit data exactly as it comes in. This will be
+  flipped on by default if you write() something other than a
+  string or Buffer at any point. Setting `objectMode: true` will
+  prevent setting any encoding value.
+- `async` Defaults to `false`. Set to `true` to defer data
+  emission until next tick. This reduces performance slightly,
+  but makes Minipass streams use timing behavior closer to Node
+  core streams. See [Timing](#timing) for more details.
+- `signal` An `AbortSignal` that will cause the stream to unhook
+  itself from everything and become as inert as possible. Note
+  that providing a `signal` parameter will make `'error'` events
+  no longer throw if they are unhandled, but they will still be
+  emitted to handlers if any are attached.
+
+### API
+
+Implements the user-facing portions of Node.js's `Readable` and
+`Writable` streams.
+
+### Methods
+
+- `write(chunk, [encoding], [callback])` - Put data in. (Note
+  that, in the base Minipass class, the same data will come out.)
+  Returns `false` if the stream will buffer the next write, or
+  true if it's still in "flowing" mode.
+- `end([chunk, [encoding]], [callback])` - Signal that you have
+  no more data to write. This will queue an `end` event to be
+  fired when all the data has been consumed.
+- `pause()` - No more data for a while, please. This also
+  prevents `end` from being emitted for empty streams until the
+  stream is resumed.
+- `resume()` - Resume the stream. If there's data in the buffer,
+  it is all discarded. Any buffered events are immediately
+  emitted.
+- `pipe(dest)` - Send all output to the stream provided. When
+  data is emitted, it is immediately written to any and all pipe
+  destinations. (Or written on next tick in `async` mode.)
+- `unpipe(dest)` - Stop piping to the destination stream. This is
+  immediate, meaning that any asynchronously queued data will
+  _not_ make it to the destination when running in `async` mode.
+  - `options.end` - Boolean, end the destination stream when the
+    source stream ends. Default `true`.
+  - `options.proxyErrors` - Boolean, proxy `error` events from
+    the source stream to the destination stream. Note that errors
+    are _not_ proxied after the pipeline terminates, either due
+    to the source emitting `'end'` or manually unpiping with
+    `src.unpipe(dest)`. Default `false`.
+- `on(ev, fn)`, `emit(ev, fn)` - Minipass streams are
+  EventEmitters. Some events are given special treatment,
+  however. (See below under "events".)
+- `promise()` - Returns a Promise that resolves when the stream
+  emits `end`, or rejects if the stream emits `error`.
+- `collect()` - Return a Promise that resolves on `end` with an
+  array containing each chunk of data that was emitted, or
+  rejects if the stream emits `error`. Note that this consumes
+  the stream data.
+- `concat()` - Same as `collect()`, but concatenates the data
+  into a single Buffer object. Will reject the returned promise
+  if the stream is in objectMode, or if it goes into objectMode
+  by the end of the data.
+- `read(n)` - Consume `n` bytes of data out of the buffer. If `n`
+  is not provided, then consume all of it. If `n` bytes are not
+  available, then it returns null. **Note** consuming streams in
+  this way is less efficient, and can lead to unnecessary Buffer
+  copying.
+- `destroy([er])` - Destroy the stream. If an error is provided,
+  then an `'error'` event is emitted. If the stream has a
+  `close()` method, and has not emitted a `'close'` event yet,
+  then `stream.close()` will be called. Any Promises returned by
+  `.promise()`, `.collect()` or `.concat()` will be rejected.
+  After being destroyed, writing to the stream will emit an
+  error. No more data will be emitted if the stream is destroyed,
+  even if it was previously buffered.
+
+### Properties
+
+- `bufferLength` Read-only. Total number of bytes buffered, or in
+  the case of objectMode, the total number of objects.
+- `encoding` Read-only. The encoding that has been set.
+- `flowing` Read-only. Boolean indicating whether a chunk written
+  to the stream will be immediately emitted.
+- `emittedEnd` Read-only. Boolean indicating whether the end-ish
+  events (ie, `end`, `prefinish`, `finish`) have been emitted.
+  Note that listening on any end-ish event will immediateyl
+  re-emit it if it has already been emitted.
+- `writable` Whether the stream is writable. Default `true`. Set
+  to `false` when `end()`
+- `readable` Whether the stream is readable. Default `true`.
+- `pipes` An array of Pipe objects referencing streams that this
+  stream is piping into.
+- `destroyed` A getter that indicates whether the stream was
+  destroyed.
+- `paused` True if the stream has been explicitly paused,
+  otherwise false.
+- `objectMode` Indicates whether the stream is in `objectMode`.
+- `aborted` Readonly property set when the `AbortSignal`
+  dispatches an `abort` event.
+
+### Events
+
+- `data` Emitted when there's data to read. Argument is the data
+  to read. This is never emitted while not flowing. If a listener
+  is attached, that will resume the stream.
+- `end` Emitted when there's no more data to read. This will be
+  emitted immediately for empty streams when `end()` is called.
+  If a listener is attached, and `end` was already emitted, then
+  it will be emitted again. All listeners are removed when `end`
+  is emitted.
+- `prefinish` An end-ish event that follows the same logic as
+  `end` and is emitted in the same conditions where `end` is
+  emitted. Emitted after `'end'`.
+- `finish` An end-ish event that follows the same logic as `end`
+  and is emitted in the same conditions where `end` is emitted.
+  Emitted after `'prefinish'`.
+- `close` An indication that an underlying resource has been
+  released. Minipass does not emit this event, but will defer it
+  until after `end` has been emitted, since it throws off some
+  stream libraries otherwise.
+- `drain` Emitted when the internal buffer empties, and it is
+  again suitable to `write()` into the stream.
+- `readable` Emitted when data is buffered and ready to be read
+  by a consumer.
+- `resume` Emitted when stream changes state from buffering to
+  flowing mode. (Ie, when `resume` is called, `pipe` is called,
+  or a `data` event listener is added.)
+
+### Static Methods
+
+- `Minipass.isStream(stream)` Returns `true` if the argument is a
+  stream, and false otherwise. To be considered a stream, the
+  object must be either an instance of Minipass, or an
+  EventEmitter that has either a `pipe()` method, or both
+  `write()` and `end()` methods. (Pretty much any stream in
+  node-land will return `true` for this.)
+
+## EXAMPLES
+
+Here are some examples of things you can do with Minipass
+streams.
+
+### simple "are you done yet" promise
+
+```js
+mp.promise().then(
+  () => {
+    // stream is finished
+  },
+  er => {
+    // stream emitted an error
+  }
+)
+```
+
+### collecting
+
+```js
+mp.collect().then(all => {
+  // all is an array of all the data emitted
+  // encoding is supported in this case, so
+  // so the result will be a collection of strings if
+  // an encoding is specified, or buffers/objects if not.
+  //
+  // In an async function, you may do
+  // const data = await stream.collect()
+})
+```
+
+### collecting into a single blob
+
+This is a bit slower because it concatenates the data into one
+chunk for you, but if you're going to do it yourself anyway, it's
+convenient this way:
+
+```js
+mp.concat().then(onebigchunk => {
+  // onebigchunk is a string if the stream
+  // had an encoding set, or a buffer otherwise.
+})
+```
+
+### iteration
+
+You can iterate over streams synchronously or asynchronously in
+platforms that support it.
+
+Synchronous iteration will end when the currently available data
+is consumed, even if the `end` event has not been reached. In
+string and buffer mode, the data is concatenated, so unless
+multiple writes are occurring in the same tick as the `read()`,
+sync iteration loops will generally only have a single iteration.
+
+To consume chunks in this way exactly as they have been written,
+with no flattening, create the stream with the `{ objectMode:
+true }` option.
+
+```js
+const mp = new Minipass({ objectMode: true })
+mp.write('a')
+mp.write('b')
+for (let letter of mp) {
+  console.log(letter) // a, b
+}
+mp.write('c')
+mp.write('d')
+for (let letter of mp) {
+  console.log(letter) // c, d
+}
+mp.write('e')
+mp.end()
+for (let letter of mp) {
+  console.log(letter) // e
+}
+for (let letter of mp) {
+  console.log(letter) // nothing
+}
+```
+
+Asynchronous iteration will continue until the end event is reached,
+consuming all of the data.
+
+```js
+const mp = new Minipass({ encoding: 'utf8' })
+
+// some source of some data
+let i = 5
+const inter = setInterval(() => {
+  if (i-- > 0) mp.write(Buffer.from('foo\n', 'utf8'))
+  else {
+    mp.end()
+    clearInterval(inter)
+  }
+}, 100)
+
+// consume the data with asynchronous iteration
+async function consume() {
+  for await (let chunk of mp) {
+    console.log(chunk)
+  }
+  return 'ok'
+}
+
+consume().then(res => console.log(res))
+// logs `foo\n` 5 times, and then `ok`
+```
+
+### subclass that `console.log()`s everything written into it
+
+```js
+class Logger extends Minipass {
+  write(chunk, encoding, callback) {
+    console.log('WRITE', chunk, encoding)
+    return super.write(chunk, encoding, callback)
+  }
+  end(chunk, encoding, callback) {
+    console.log('END', chunk, encoding)
+    return super.end(chunk, encoding, callback)
+  }
+}
+
+someSource.pipe(new Logger()).pipe(someDest)
+```
+
+### same thing, but using an inline anonymous class
+
+```js
+// js classes are fun
+someSource
+  .pipe(
+    new (class extends Minipass {
+      emit(ev, ...data) {
+        // let's also log events, because debugging some weird thing
+        console.log('EMIT', ev)
+        return super.emit(ev, ...data)
+      }
+      write(chunk, encoding, callback) {
+        console.log('WRITE', chunk, encoding)
+        return super.write(chunk, encoding, callback)
+      }
+      end(chunk, encoding, callback) {
+        console.log('END', chunk, encoding)
+        return super.end(chunk, encoding, callback)
+      }
+    })()
+  )
+  .pipe(someDest)
+```
+
+### subclass that defers 'end' for some reason
+
+```js
+class SlowEnd extends Minipass {
+  emit(ev, ...args) {
+    if (ev === 'end') {
+      console.log('going to end, hold on a sec')
+      setTimeout(() => {
+        console.log('ok, ready to end now')
+        super.emit('end', ...args)
+      }, 100)
+      return true
+    } else {
+      return super.emit(ev, ...args)
+    }
+  }
+}
+```
+
+### transform that creates newline-delimited JSON
+
+```js
+class NDJSONEncode extends Minipass {
+  write(obj, cb) {
+    try {
+      // JSON.stringify can throw, emit an error on that
+      return super.write(JSON.stringify(obj) + '\n', 'utf8', cb)
+    } catch (er) {
+      this.emit('error', er)
+    }
+  }
+  end(obj, cb) {
+    if (typeof obj === 'function') {
+      cb = obj
+      obj = undefined
+    }
+    if (obj !== undefined) {
+      this.write(obj)
+    }
+    return super.end(cb)
+  }
+}
+```
+
+### transform that parses newline-delimited JSON
+
+```js
+class NDJSONDecode extends Minipass {
+  constructor(options) {
+    // always be in object mode, as far as Minipass is concerned
+    super({ objectMode: true })
+    this._jsonBuffer = ''
+  }
+  write(chunk, encoding, cb) {
+    if (
+      typeof chunk === 'string' &&
+      typeof encoding === 'string' &&
+      encoding !== 'utf8'
+    ) {
+      chunk = Buffer.from(chunk, encoding).toString()
+    } else if (Buffer.isBuffer(chunk)) {
+      chunk = chunk.toString()
+    }
+    if (typeof encoding === 'function') {
+      cb = encoding
+    }
+    const jsonData = (this._jsonBuffer + chunk).split('\n')
+    this._jsonBuffer = jsonData.pop()
+    for (let i = 0; i < jsonData.length; i++) {
+      try {
+        // JSON.parse can throw, emit an error on that
+        super.write(JSON.parse(jsonData[i]))
+      } catch (er) {
+        this.emit('error', er)
+        continue
+      }
+    }
+    if (cb) cb()
+  }
+}
+```
diff --git a/node_modules/minipass/dist/commonjs/index.d.ts b/node_modules/minipass/dist/commonjs/index.d.ts
new file mode 100644
index 0000000..031e61a
--- /dev/null
+++ b/node_modules/minipass/dist/commonjs/index.d.ts
@@ -0,0 +1,549 @@
+/// 
+/// 
+/// 
+/// 
+import { EventEmitter } from 'node:events';
+import { StringDecoder } from 'node:string_decoder';
+/**
+ * Same as StringDecoder, but exposing the `lastNeed` flag on the type
+ */
+type SD = StringDecoder & {
+    lastNeed: boolean;
+};
+export type { SD, Pipe, PipeProxyErrors };
+/**
+ * Return true if the argument is a Minipass stream, Node stream, or something
+ * else that Minipass can interact with.
+ */
+export declare const isStream: (s: any) => s is NodeJS.WriteStream | NodeJS.ReadStream | Minipass | (NodeJS.ReadStream & {
+    fd: number;
+}) | (EventEmitter & {
+    pause(): any;
+    resume(): any;
+    pipe(...destArgs: any[]): any;
+}) | (NodeJS.WriteStream & {
+    fd: number;
+}) | (EventEmitter & {
+    end(): any;
+    write(chunk: any, ...args: any[]): any;
+});
+/**
+ * Return true if the argument is a valid {@link Minipass.Readable}
+ */
+export declare const isReadable: (s: any) => s is Minipass.Readable;
+/**
+ * Return true if the argument is a valid {@link Minipass.Writable}
+ */
+export declare const isWritable: (s: any) => s is Minipass.Readable;
+declare const EOF: unique symbol;
+declare const MAYBE_EMIT_END: unique symbol;
+declare const EMITTED_END: unique symbol;
+declare const EMITTING_END: unique symbol;
+declare const EMITTED_ERROR: unique symbol;
+declare const CLOSED: unique symbol;
+declare const READ: unique symbol;
+declare const FLUSH: unique symbol;
+declare const FLUSHCHUNK: unique symbol;
+declare const ENCODING: unique symbol;
+declare const DECODER: unique symbol;
+declare const FLOWING: unique symbol;
+declare const PAUSED: unique symbol;
+declare const RESUME: unique symbol;
+declare const BUFFER: unique symbol;
+declare const PIPES: unique symbol;
+declare const BUFFERLENGTH: unique symbol;
+declare const BUFFERPUSH: unique symbol;
+declare const BUFFERSHIFT: unique symbol;
+declare const OBJECTMODE: unique symbol;
+declare const DESTROYED: unique symbol;
+declare const ERROR: unique symbol;
+declare const EMITDATA: unique symbol;
+declare const EMITEND: unique symbol;
+declare const EMITEND2: unique symbol;
+declare const ASYNC: unique symbol;
+declare const ABORT: unique symbol;
+declare const ABORTED: unique symbol;
+declare const SIGNAL: unique symbol;
+declare const DATALISTENERS: unique symbol;
+declare const DISCARDED: unique symbol;
+/**
+ * Options that may be passed to stream.pipe()
+ */
+export interface PipeOptions {
+    /**
+     * end the destination stream when the source stream ends
+     */
+    end?: boolean;
+    /**
+     * proxy errors from the source stream to the destination stream
+     */
+    proxyErrors?: boolean;
+}
+/**
+ * Internal class representing a pipe to a destination stream.
+ *
+ * @internal
+ */
+declare class Pipe {
+    src: Minipass;
+    dest: Minipass;
+    opts: PipeOptions;
+    ondrain: () => any;
+    constructor(src: Minipass, dest: Minipass.Writable, opts: PipeOptions);
+    unpipe(): void;
+    proxyErrors(_er: any): void;
+    end(): void;
+}
+/**
+ * Internal class representing a pipe to a destination stream where
+ * errors are proxied.
+ *
+ * @internal
+ */
+declare class PipeProxyErrors extends Pipe {
+    unpipe(): void;
+    constructor(src: Minipass, dest: Minipass.Writable, opts: PipeOptions);
+}
+export declare namespace Minipass {
+    /**
+     * Encoding used to create a stream that outputs strings rather than
+     * Buffer objects.
+     */
+    export type Encoding = BufferEncoding | 'buffer' | null;
+    /**
+     * Any stream that Minipass can pipe into
+     */
+    export type Writable = Minipass | NodeJS.WriteStream | (NodeJS.WriteStream & {
+        fd: number;
+    }) | (EventEmitter & {
+        end(): any;
+        write(chunk: any, ...args: any[]): any;
+    });
+    /**
+     * Any stream that can be read from
+     */
+    export type Readable = Minipass | NodeJS.ReadStream | (NodeJS.ReadStream & {
+        fd: number;
+    }) | (EventEmitter & {
+        pause(): any;
+        resume(): any;
+        pipe(...destArgs: any[]): any;
+    });
+    /**
+     * Utility type that can be iterated sync or async
+     */
+    export type DualIterable = Iterable & AsyncIterable;
+    type EventArguments = Record;
+    /**
+     * The listing of events that a Minipass class can emit.
+     * Extend this when extending the Minipass class, and pass as
+     * the third template argument.  The key is the name of the event,
+     * and the value is the argument list.
+     *
+     * Any undeclared events will still be allowed, but the handler will get
+     * arguments as `unknown[]`.
+     */
+    export interface Events extends EventArguments {
+        readable: [];
+        data: [chunk: RType];
+        error: [er: unknown];
+        abort: [reason: unknown];
+        drain: [];
+        resume: [];
+        end: [];
+        finish: [];
+        prefinish: [];
+        close: [];
+        [DESTROYED]: [er?: unknown];
+        [ERROR]: [er: unknown];
+    }
+    /**
+     * String or buffer-like data that can be joined and sliced
+     */
+    export type ContiguousData = Buffer | ArrayBufferLike | ArrayBufferView | string;
+    export type BufferOrString = Buffer | string;
+    /**
+     * Options passed to the Minipass constructor.
+     */
+    export type SharedOptions = {
+        /**
+         * Defer all data emission and other events until the end of the
+         * current tick, similar to Node core streams
+         */
+        async?: boolean;
+        /**
+         * A signal which will abort the stream
+         */
+        signal?: AbortSignal;
+        /**
+         * Output string encoding. Set to `null` or `'buffer'` (or omit) to
+         * emit Buffer objects rather than strings.
+         *
+         * Conflicts with `objectMode`
+         */
+        encoding?: BufferEncoding | null | 'buffer';
+        /**
+         * Output data exactly as it was written, supporting non-buffer/string
+         * data (such as arbitrary objects, falsey values, etc.)
+         *
+         * Conflicts with `encoding`
+         */
+        objectMode?: boolean;
+    };
+    /**
+     * Options for a string encoded output
+     */
+    export type EncodingOptions = SharedOptions & {
+        encoding: BufferEncoding;
+        objectMode?: false;
+    };
+    /**
+     * Options for contiguous data buffer output
+     */
+    export type BufferOptions = SharedOptions & {
+        encoding?: null | 'buffer';
+        objectMode?: false;
+    };
+    /**
+     * Options for objectMode arbitrary output
+     */
+    export type ObjectModeOptions = SharedOptions & {
+        objectMode: true;
+        encoding?: null;
+    };
+    /**
+     * Utility type to determine allowed options based on read type
+     */
+    export type Options = ObjectModeOptions | (T extends string ? EncodingOptions : T extends Buffer ? BufferOptions : SharedOptions);
+    export {};
+}
+/**
+ * Main export, the Minipass class
+ *
+ * `RType` is the type of data emitted, defaults to Buffer
+ *
+ * `WType` is the type of data to be written, if RType is buffer or string,
+ * then any {@link Minipass.ContiguousData} is allowed.
+ *
+ * `Events` is the set of event handler signatures that this object
+ * will emit, see {@link Minipass.Events}
+ */
+export declare class Minipass = Minipass.Events> extends EventEmitter implements Minipass.DualIterable {
+    [FLOWING]: boolean;
+    [PAUSED]: boolean;
+    [PIPES]: Pipe[];
+    [BUFFER]: RType[];
+    [OBJECTMODE]: boolean;
+    [ENCODING]: BufferEncoding | null;
+    [ASYNC]: boolean;
+    [DECODER]: SD | null;
+    [EOF]: boolean;
+    [EMITTED_END]: boolean;
+    [EMITTING_END]: boolean;
+    [CLOSED]: boolean;
+    [EMITTED_ERROR]: unknown;
+    [BUFFERLENGTH]: number;
+    [DESTROYED]: boolean;
+    [SIGNAL]?: AbortSignal;
+    [ABORTED]: boolean;
+    [DATALISTENERS]: number;
+    [DISCARDED]: boolean;
+    /**
+     * true if the stream can be written
+     */
+    writable: boolean;
+    /**
+     * true if the stream can be read
+     */
+    readable: boolean;
+    /**
+     * If `RType` is Buffer, then options do not need to be provided.
+     * Otherwise, an options object must be provided to specify either
+     * {@link Minipass.SharedOptions.objectMode} or
+     * {@link Minipass.SharedOptions.encoding}, as appropriate.
+     */
+    constructor(...args: [Minipass.ObjectModeOptions] | (RType extends Buffer ? [] | [Minipass.Options] : [Minipass.Options]));
+    /**
+     * The amount of data stored in the buffer waiting to be read.
+     *
+     * For Buffer strings, this will be the total byte length.
+     * For string encoding streams, this will be the string character length,
+     * according to JavaScript's `string.length` logic.
+     * For objectMode streams, this is a count of the items waiting to be
+     * emitted.
+     */
+    get bufferLength(): number;
+    /**
+     * The `BufferEncoding` currently in use, or `null`
+     */
+    get encoding(): BufferEncoding | null;
+    /**
+     * @deprecated - This is a read only property
+     */
+    set encoding(_enc: BufferEncoding | null);
+    /**
+     * @deprecated - Encoding may only be set at instantiation time
+     */
+    setEncoding(_enc: Minipass.Encoding): void;
+    /**
+     * True if this is an objectMode stream
+     */
+    get objectMode(): boolean;
+    /**
+     * @deprecated - This is a read-only property
+     */
+    set objectMode(_om: boolean);
+    /**
+     * true if this is an async stream
+     */
+    get ['async'](): boolean;
+    /**
+     * Set to true to make this stream async.
+     *
+     * Once set, it cannot be unset, as this would potentially cause incorrect
+     * behavior.  Ie, a sync stream can be made async, but an async stream
+     * cannot be safely made sync.
+     */
+    set ['async'](a: boolean);
+    [ABORT](): void;
+    /**
+     * True if the stream has been aborted.
+     */
+    get aborted(): boolean;
+    /**
+     * No-op setter. Stream aborted status is set via the AbortSignal provided
+     * in the constructor options.
+     */
+    set aborted(_: boolean);
+    /**
+     * Write data into the stream
+     *
+     * If the chunk written is a string, and encoding is not specified, then
+     * `utf8` will be assumed. If the stream encoding matches the encoding of
+     * a written string, and the state of the string decoder allows it, then
+     * the string will be passed through to either the output or the internal
+     * buffer without any processing. Otherwise, it will be turned into a
+     * Buffer object for processing into the desired encoding.
+     *
+     * If provided, `cb` function is called immediately before return for
+     * sync streams, or on next tick for async streams, because for this
+     * base class, a chunk is considered "processed" once it is accepted
+     * and either emitted or buffered. That is, the callback does not indicate
+     * that the chunk has been eventually emitted, though of course child
+     * classes can override this function to do whatever processing is required
+     * and call `super.write(...)` only once processing is completed.
+     */
+    write(chunk: WType, cb?: () => void): boolean;
+    write(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): boolean;
+    /**
+     * Low-level explicit read method.
+     *
+     * In objectMode, the argument is ignored, and one item is returned if
+     * available.
+     *
+     * `n` is the number of bytes (or in the case of encoding streams,
+     * characters) to consume. If `n` is not provided, then the entire buffer
+     * is returned, or `null` is returned if no data is available.
+     *
+     * If `n` is greater that the amount of data in the internal buffer,
+     * then `null` is returned.
+     */
+    read(n?: number | null): RType | null;
+    [READ](n: number | null, chunk: RType): RType;
+    /**
+     * End the stream, optionally providing a final write.
+     *
+     * See {@link Minipass#write} for argument descriptions
+     */
+    end(cb?: () => void): this;
+    end(chunk: WType, cb?: () => void): this;
+    end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this;
+    [RESUME](): void;
+    /**
+     * Resume the stream if it is currently in a paused state
+     *
+     * If called when there are no pipe destinations or `data` event listeners,
+     * this will place the stream in a "discarded" state, where all data will
+     * be thrown away. The discarded state is removed if a pipe destination or
+     * data handler is added, if pause() is called, or if any synchronous or
+     * asynchronous iteration is started.
+     */
+    resume(): void;
+    /**
+     * Pause the stream
+     */
+    pause(): void;
+    /**
+     * true if the stream has been forcibly destroyed
+     */
+    get destroyed(): boolean;
+    /**
+     * true if the stream is currently in a flowing state, meaning that
+     * any writes will be immediately emitted.
+     */
+    get flowing(): boolean;
+    /**
+     * true if the stream is currently in a paused state
+     */
+    get paused(): boolean;
+    [BUFFERPUSH](chunk: RType): void;
+    [BUFFERSHIFT](): RType;
+    [FLUSH](noDrain?: boolean): void;
+    [FLUSHCHUNK](chunk: RType): boolean;
+    /**
+     * Pipe all data emitted by this stream into the destination provided.
+     *
+     * Triggers the flow of data.
+     */
+    pipe(dest: W, opts?: PipeOptions): W;
+    /**
+     * Fully unhook a piped destination stream.
+     *
+     * If the destination stream was the only consumer of this stream (ie,
+     * there are no other piped destinations or `'data'` event listeners)
+     * then the flow of data will stop until there is another consumer or
+     * {@link Minipass#resume} is explicitly called.
+     */
+    unpipe(dest: W): void;
+    /**
+     * Alias for {@link Minipass#on}
+     */
+    addListener(ev: Event, handler: (...args: Events[Event]) => any): this;
+    /**
+     * Mostly identical to `EventEmitter.on`, with the following
+     * behavior differences to prevent data loss and unnecessary hangs:
+     *
+     * - Adding a 'data' event handler will trigger the flow of data
+     *
+     * - Adding a 'readable' event handler when there is data waiting to be read
+     *   will cause 'readable' to be emitted immediately.
+     *
+     * - Adding an 'endish' event handler ('end', 'finish', etc.) which has
+     *   already passed will cause the event to be emitted immediately and all
+     *   handlers removed.
+     *
+     * - Adding an 'error' event handler after an error has been emitted will
+     *   cause the event to be re-emitted immediately with the error previously
+     *   raised.
+     */
+    on(ev: Event, handler: (...args: Events[Event]) => any): this;
+    /**
+     * Alias for {@link Minipass#off}
+     */
+    removeListener(ev: Event, handler: (...args: Events[Event]) => any): this;
+    /**
+     * Mostly identical to `EventEmitter.off`
+     *
+     * If a 'data' event handler is removed, and it was the last consumer
+     * (ie, there are no pipe destinations or other 'data' event listeners),
+     * then the flow of data will stop until there is another consumer or
+     * {@link Minipass#resume} is explicitly called.
+     */
+    off(ev: Event, handler: (...args: Events[Event]) => any): this;
+    /**
+     * Mostly identical to `EventEmitter.removeAllListeners`
+     *
+     * If all 'data' event handlers are removed, and they were the last consumer
+     * (ie, there are no pipe destinations), then the flow of data will stop
+     * until there is another consumer or {@link Minipass#resume} is explicitly
+     * called.
+     */
+    removeAllListeners(ev?: Event): this;
+    /**
+     * true if the 'end' event has been emitted
+     */
+    get emittedEnd(): boolean;
+    [MAYBE_EMIT_END](): void;
+    /**
+     * Mostly identical to `EventEmitter.emit`, with the following
+     * behavior differences to prevent data loss and unnecessary hangs:
+     *
+     * If the stream has been destroyed, and the event is something other
+     * than 'close' or 'error', then `false` is returned and no handlers
+     * are called.
+     *
+     * If the event is 'end', and has already been emitted, then the event
+     * is ignored. If the stream is in a paused or non-flowing state, then
+     * the event will be deferred until data flow resumes. If the stream is
+     * async, then handlers will be called on the next tick rather than
+     * immediately.
+     *
+     * If the event is 'close', and 'end' has not yet been emitted, then
+     * the event will be deferred until after 'end' is emitted.
+     *
+     * If the event is 'error', and an AbortSignal was provided for the stream,
+     * and there are no listeners, then the event is ignored, matching the
+     * behavior of node core streams in the presense of an AbortSignal.
+     *
+     * If the event is 'finish' or 'prefinish', then all listeners will be
+     * removed after emitting the event, to prevent double-firing.
+     */
+    emit(ev: Event, ...args: Events[Event]): boolean;
+    [EMITDATA](data: RType): boolean;
+    [EMITEND](): boolean;
+    [EMITEND2](): boolean;
+    /**
+     * Return a Promise that resolves to an array of all emitted data once
+     * the stream ends.
+     */
+    collect(): Promise;
+    /**
+     * Return a Promise that resolves to the concatenation of all emitted data
+     * once the stream ends.
+     *
+     * Not allowed on objectMode streams.
+     */
+    concat(): Promise;
+    /**
+     * Return a void Promise that resolves once the stream ends.
+     */
+    promise(): Promise;
+    /**
+     * Asynchronous `for await of` iteration.
+     *
+     * This will continue emitting all chunks until the stream terminates.
+     */
+    [Symbol.asyncIterator](): AsyncGenerator;
+    /**
+     * Synchronous `for of` iteration.
+     *
+     * The iteration will terminate when the internal buffer runs out, even
+     * if the stream has not yet terminated.
+     */
+    [Symbol.iterator](): Generator;
+    /**
+     * Destroy a stream, preventing it from being used for any further purpose.
+     *
+     * If the stream has a `close()` method, then it will be called on
+     * destruction.
+     *
+     * After destruction, any attempt to write data, read data, or emit most
+     * events will be ignored.
+     *
+     * If an error argument is provided, then it will be emitted in an
+     * 'error' event.
+     */
+    destroy(er?: unknown): this;
+    /**
+     * Alias for {@link isStream}
+     *
+     * Former export location, maintained for backwards compatibility.
+     *
+     * @deprecated
+     */
+    static get isStream(): (s: any) => s is NodeJS.WriteStream | NodeJS.ReadStream | Minipass | (NodeJS.ReadStream & {
+        fd: number;
+    }) | (EventEmitter & {
+        pause(): any;
+        resume(): any;
+        pipe(...destArgs: any[]): any;
+    }) | (NodeJS.WriteStream & {
+        fd: number;
+    }) | (EventEmitter & {
+        end(): any;
+        write(chunk: any, ...args: any[]): any;
+    });
+}
+//# sourceMappingURL=index.d.ts.map
\ No newline at end of file
diff --git a/node_modules/minipass/dist/commonjs/index.d.ts.map b/node_modules/minipass/dist/commonjs/index.d.ts.map
new file mode 100644
index 0000000..cac7e00
--- /dev/null
+++ b/node_modules/minipass/dist/commonjs/index.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAOA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAE1C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAEnD;;GAEG;AACH,KAAK,EAAE,GAAG,aAAa,GAAG;IAAE,QAAQ,EAAE,OAAO,CAAA;CAAE,CAAA;AAE/C,YAAY,EAAE,EAAE,EAAE,IAAI,EAAE,eAAe,EAAE,CAAA;AAEzC;;;GAGG;AACH,eAAO,MAAM,QAAQ,MAChB,GAAG;QAoLyB,MAAM;;aAEtB,GAAG;cACF,GAAG;sBACK,GAAG,EAAE,GAAG,GAAG;;QAhBH,MAAM;;WAEzB,GAAG;iBACG,GAAG,WAAW,GAAG,EAAE,GAAG,GAAG;EApK5B,CAAA;AAElB;;GAEG;AACH,eAAO,MAAM,UAAU,MAAO,GAAG,2BAMiC,CAAA;AAElE;;GAEG;AACH,eAAO,MAAM,UAAU,MAAO,GAAG,2BAKmB,CAAA;AAEpD,QAAA,MAAM,GAAG,eAAgB,CAAA;AACzB,QAAA,MAAM,cAAc,eAAyB,CAAA;AAC7C,QAAA,MAAM,WAAW,eAAuB,CAAA;AACxC,QAAA,MA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AAC,EAAE,KAAK;IAWzD;;OAEG;IACH,IAAI,UAAU,YAEb;IAED,CAAC,cAAc,CAAC;IAiBhB;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,IAAI,CAAC,KAAK,SAAS,MAAM,MAAM,EAC7B,EAAE,EAAE,KAAK,EACT,GAAG,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,GACrB,OAAO;IAkDV,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE,KAAK;IAStB,CAAC,OAAO,CAAC;IAUT,CAAC,QAAQ,CAAC;IAmBV;;;OAGG;IACG,OAAO,IAAI,OAAO,CAAC,KAAK,EAAE,GAAG;QAAE,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC;IAiB1D;;;;;OAKG;IACG,MAAM,IAAI,OAAO,CAAC,KAAK,CAAC;IAY9B;;OAEG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAQ9B;;;;OAIG;IACH,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,cAAc,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC;IA6D3D;;;;;OAKG;IACH,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC;IAkCjD;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,EAAE,CAAC,EAAE,OAAO;IA0BpB;;;;;;OAMG;IACH,MAAM,KAAK,QAAQ;;;;;;;;;;;OAElB;CACF"}
\ No newline at end of file
diff --git a/node_modules/minipass/dist/commonjs/index.js b/node_modules/minipass/dist/commonjs/index.js
new file mode 100644
index 0000000..068c095
--- /dev/null
+++ b/node_modules/minipass/dist/commonjs/index.js
@@ -0,0 +1,1028 @@
+"use strict";
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.Minipass = exports.isWritable = exports.isReadable = exports.isStream = void 0;
+const proc = typeof process === 'object' && process
+    ? process
+    : {
+        stdout: null,
+        stderr: null,
+    };
+const node_events_1 = require("node:events");
+const node_stream_1 = __importDefault(require("node:stream"));
+const node_string_decoder_1 = require("node:string_decoder");
+/**
+ * Return true if the argument is a Minipass stream, Node stream, or something
+ * else that Minipass can interact with.
+ */
+const isStream = (s) => !!s &&
+    typeof s === 'object' &&
+    (s instanceof Minipass ||
+        s instanceof node_stream_1.default ||
+        (0, exports.isReadable)(s) ||
+        (0, exports.isWritable)(s));
+exports.isStream = isStream;
+/**
+ * Return true if the argument is a valid {@link Minipass.Readable}
+ */
+const isReadable = (s) => !!s &&
+    typeof s === 'object' &&
+    s instanceof node_events_1.EventEmitter &&
+    typeof s.pipe === 'function' &&
+    // node core Writable streams have a pipe() method, but it throws
+    s.pipe !== node_stream_1.default.Writable.prototype.pipe;
+exports.isReadable = isReadable;
+/**
+ * Return true if the argument is a valid {@link Minipass.Writable}
+ */
+const isWritable = (s) => !!s &&
+    typeof s === 'object' &&
+    s instanceof node_events_1.EventEmitter &&
+    typeof s.write === 'function' &&
+    typeof s.end === 'function';
+exports.isWritable = isWritable;
+const EOF = Symbol('EOF');
+const MAYBE_EMIT_END = Symbol('maybeEmitEnd');
+const EMITTED_END = Symbol('emittedEnd');
+const EMITTING_END = Symbol('emittingEnd');
+const EMITTED_ERROR = Symbol('emittedError');
+const CLOSED = Symbol('closed');
+const READ = Symbol('read');
+const FLUSH = Symbol('flush');
+const FLUSHCHUNK = Symbol('flushChunk');
+const ENCODING = Symbol('encoding');
+const DECODER = Symbol('decoder');
+const FLOWING = Symbol('flowing');
+const PAUSED = Symbol('paused');
+const RESUME = Symbol('resume');
+const BUFFER = Symbol('buffer');
+const PIPES = Symbol('pipes');
+const BUFFERLENGTH = Symbol('bufferLength');
+const BUFFERPUSH = Symbol('bufferPush');
+const BUFFERSHIFT = Symbol('bufferShift');
+const OBJECTMODE = Symbol('objectMode');
+// internal event when stream is destroyed
+const DESTROYED = Symbol('destroyed');
+// internal event when stream has an error
+const ERROR = Symbol('error');
+const EMITDATA = Symbol('emitData');
+const EMITEND = Symbol('emitEnd');
+const EMITEND2 = Symbol('emitEnd2');
+const ASYNC = Symbol('async');
+const ABORT = Symbol('abort');
+const ABORTED = Symbol('aborted');
+const SIGNAL = Symbol('signal');
+const DATALISTENERS = Symbol('dataListeners');
+const DISCARDED = Symbol('discarded');
+const defer = (fn) => Promise.resolve().then(fn);
+const nodefer = (fn) => fn();
+const isEndish = (ev) => ev === 'end' || ev === 'finish' || ev === 'prefinish';
+const isArrayBufferLike = (b) => b instanceof ArrayBuffer ||
+    (!!b &&
+        typeof b === 'object' &&
+        b.constructor &&
+        b.constructor.name === 'ArrayBuffer' &&
+        b.byteLength >= 0);
+const isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b);
+/**
+ * Internal class representing a pipe to a destination stream.
+ *
+ * @internal
+ */
+class Pipe {
+    src;
+    dest;
+    opts;
+    ondrain;
+    constructor(src, dest, opts) {
+        this.src = src;
+        this.dest = dest;
+        this.opts = opts;
+        this.ondrain = () => src[RESUME]();
+        this.dest.on('drain', this.ondrain);
+    }
+    unpipe() {
+        this.dest.removeListener('drain', this.ondrain);
+    }
+    // only here for the prototype
+    /* c8 ignore start */
+    proxyErrors(_er) { }
+    /* c8 ignore stop */
+    end() {
+        this.unpipe();
+        if (this.opts.end)
+            this.dest.end();
+    }
+}
+/**
+ * Internal class representing a pipe to a destination stream where
+ * errors are proxied.
+ *
+ * @internal
+ */
+class PipeProxyErrors extends Pipe {
+    unpipe() {
+        this.src.removeListener('error', this.proxyErrors);
+        super.unpipe();
+    }
+    constructor(src, dest, opts) {
+        super(src, dest, opts);
+        this.proxyErrors = er => dest.emit('error', er);
+        src.on('error', this.proxyErrors);
+    }
+}
+const isObjectModeOptions = (o) => !!o.objectMode;
+const isEncodingOptions = (o) => !o.objectMode && !!o.encoding && o.encoding !== 'buffer';
+/**
+ * Main export, the Minipass class
+ *
+ * `RType` is the type of data emitted, defaults to Buffer
+ *
+ * `WType` is the type of data to be written, if RType is buffer or string,
+ * then any {@link Minipass.ContiguousData} is allowed.
+ *
+ * `Events` is the set of event handler signatures that this object
+ * will emit, see {@link Minipass.Events}
+ */
+class Minipass extends node_events_1.EventEmitter {
+    [FLOWING] = false;
+    [PAUSED] = false;
+    [PIPES] = [];
+    [BUFFER] = [];
+    [OBJECTMODE];
+    [ENCODING];
+    [ASYNC];
+    [DECODER];
+    [EOF] = false;
+    [EMITTED_END] = false;
+    [EMITTING_END] = false;
+    [CLOSED] = false;
+    [EMITTED_ERROR] = null;
+    [BUFFERLENGTH] = 0;
+    [DESTROYED] = false;
+    [SIGNAL];
+    [ABORTED] = false;
+    [DATALISTENERS] = 0;
+    [DISCARDED] = false;
+    /**
+     * true if the stream can be written
+     */
+    writable = true;
+    /**
+     * true if the stream can be read
+     */
+    readable = true;
+    /**
+     * If `RType` is Buffer, then options do not need to be provided.
+     * Otherwise, an options object must be provided to specify either
+     * {@link Minipass.SharedOptions.objectMode} or
+     * {@link Minipass.SharedOptions.encoding}, as appropriate.
+     */
+    constructor(...args) {
+        const options = (args[0] ||
+            {});
+        super();
+        if (options.objectMode && typeof options.encoding === 'string') {
+            throw new TypeError('Encoding and objectMode may not be used together');
+        }
+        if (isObjectModeOptions(options)) {
+            this[OBJECTMODE] = true;
+            this[ENCODING] = null;
+        }
+        else if (isEncodingOptions(options)) {
+            this[ENCODING] = options.encoding;
+            this[OBJECTMODE] = false;
+        }
+        else {
+            this[OBJECTMODE] = false;
+            this[ENCODING] = null;
+        }
+        this[ASYNC] = !!options.async;
+        this[DECODER] = this[ENCODING]
+            ? new node_string_decoder_1.StringDecoder(this[ENCODING])
+            : null;
+        //@ts-ignore - private option for debugging and testing
+        if (options && options.debugExposeBuffer === true) {
+            Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] });
+        }
+        //@ts-ignore - private option for debugging and testing
+        if (options && options.debugExposePipes === true) {
+            Object.defineProperty(this, 'pipes', { get: () => this[PIPES] });
+        }
+        const { signal } = options;
+        if (signal) {
+            this[SIGNAL] = signal;
+            if (signal.aborted) {
+                this[ABORT]();
+            }
+            else {
+                signal.addEventListener('abort', () => this[ABORT]());
+            }
+        }
+    }
+    /**
+     * The amount of data stored in the buffer waiting to be read.
+     *
+     * For Buffer strings, this will be the total byte length.
+     * For string encoding streams, this will be the string character length,
+     * according to JavaScript's `string.length` logic.
+     * For objectMode streams, this is a count of the items waiting to be
+     * emitted.
+     */
+    get bufferLength() {
+        return this[BUFFERLENGTH];
+    }
+    /**
+     * The `BufferEncoding` currently in use, or `null`
+     */
+    get encoding() {
+        return this[ENCODING];
+    }
+    /**
+     * @deprecated - This is a read only property
+     */
+    set encoding(_enc) {
+        throw new Error('Encoding must be set at instantiation time');
+    }
+    /**
+     * @deprecated - Encoding may only be set at instantiation time
+     */
+    setEncoding(_enc) {
+        throw new Error('Encoding must be set at instantiation time');
+    }
+    /**
+     * True if this is an objectMode stream
+     */
+    get objectMode() {
+        return this[OBJECTMODE];
+    }
+    /**
+     * @deprecated - This is a read-only property
+     */
+    set objectMode(_om) {
+        throw new Error('objectMode must be set at instantiation time');
+    }
+    /**
+     * true if this is an async stream
+     */
+    get ['async']() {
+        return this[ASYNC];
+    }
+    /**
+     * Set to true to make this stream async.
+     *
+     * Once set, it cannot be unset, as this would potentially cause incorrect
+     * behavior.  Ie, a sync stream can be made async, but an async stream
+     * cannot be safely made sync.
+     */
+    set ['async'](a) {
+        this[ASYNC] = this[ASYNC] || !!a;
+    }
+    // drop everything and get out of the flow completely
+    [ABORT]() {
+        this[ABORTED] = true;
+        this.emit('abort', this[SIGNAL]?.reason);
+        this.destroy(this[SIGNAL]?.reason);
+    }
+    /**
+     * True if the stream has been aborted.
+     */
+    get aborted() {
+        return this[ABORTED];
+    }
+    /**
+     * No-op setter. Stream aborted status is set via the AbortSignal provided
+     * in the constructor options.
+     */
+    set aborted(_) { }
+    write(chunk, encoding, cb) {
+        if (this[ABORTED])
+            return false;
+        if (this[EOF])
+            throw new Error('write after end');
+        if (this[DESTROYED]) {
+            this.emit('error', Object.assign(new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' }));
+            return true;
+        }
+        if (typeof encoding === 'function') {
+            cb = encoding;
+            encoding = 'utf8';
+        }
+        if (!encoding)
+            encoding = 'utf8';
+        const fn = this[ASYNC] ? defer : nodefer;
+        // convert array buffers and typed array views into buffers
+        // at some point in the future, we may want to do the opposite!
+        // leave strings and buffers as-is
+        // anything is only allowed if in object mode, so throw
+        if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
+            if (isArrayBufferView(chunk)) {
+                //@ts-ignore - sinful unsafe type changing
+                chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
+            }
+            else if (isArrayBufferLike(chunk)) {
+                //@ts-ignore - sinful unsafe type changing
+                chunk = Buffer.from(chunk);
+            }
+            else if (typeof chunk !== 'string') {
+                throw new Error('Non-contiguous data written to non-objectMode stream');
+            }
+        }
+        // handle object mode up front, since it's simpler
+        // this yields better performance, fewer checks later.
+        if (this[OBJECTMODE]) {
+            // maybe impossible?
+            /* c8 ignore start */
+            if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
+                this[FLUSH](true);
+            /* c8 ignore stop */
+            if (this[FLOWING])
+                this.emit('data', chunk);
+            else
+                this[BUFFERPUSH](chunk);
+            if (this[BUFFERLENGTH] !== 0)
+                this.emit('readable');
+            if (cb)
+                fn(cb);
+            return this[FLOWING];
+        }
+        // at this point the chunk is a buffer or string
+        // don't buffer it up or send it to the decoder
+        if (!chunk.length) {
+            if (this[BUFFERLENGTH] !== 0)
+                this.emit('readable');
+            if (cb)
+                fn(cb);
+            return this[FLOWING];
+        }
+        // fast-path writing strings of same encoding to a stream with
+        // an empty buffer, skipping the buffer/decoder dance
+        if (typeof chunk === 'string' &&
+            // unless it is a string already ready for us to use
+            !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)) {
+            //@ts-ignore - sinful unsafe type change
+            chunk = Buffer.from(chunk, encoding);
+        }
+        if (Buffer.isBuffer(chunk) && this[ENCODING]) {
+            //@ts-ignore - sinful unsafe type change
+            chunk = this[DECODER].write(chunk);
+        }
+        // Note: flushing CAN potentially switch us into not-flowing mode
+        if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
+            this[FLUSH](true);
+        if (this[FLOWING])
+            this.emit('data', chunk);
+        else
+            this[BUFFERPUSH](chunk);
+        if (this[BUFFERLENGTH] !== 0)
+            this.emit('readable');
+        if (cb)
+            fn(cb);
+        return this[FLOWING];
+    }
+    /**
+     * Low-level explicit read method.
+     *
+     * In objectMode, the argument is ignored, and one item is returned if
+     * available.
+     *
+     * `n` is the number of bytes (or in the case of encoding streams,
+     * characters) to consume. If `n` is not provided, then the entire buffer
+     * is returned, or `null` is returned if no data is available.
+     *
+     * If `n` is greater that the amount of data in the internal buffer,
+     * then `null` is returned.
+     */
+    read(n) {
+        if (this[DESTROYED])
+            return null;
+        this[DISCARDED] = false;
+        if (this[BUFFERLENGTH] === 0 ||
+            n === 0 ||
+            (n && n > this[BUFFERLENGTH])) {
+            this[MAYBE_EMIT_END]();
+            return null;
+        }
+        if (this[OBJECTMODE])
+            n = null;
+        if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {
+            // not object mode, so if we have an encoding, then RType is string
+            // otherwise, must be Buffer
+            this[BUFFER] = [
+                (this[ENCODING]
+                    ? this[BUFFER].join('')
+                    : Buffer.concat(this[BUFFER], this[BUFFERLENGTH])),
+            ];
+        }
+        const ret = this[READ](n || null, this[BUFFER][0]);
+        this[MAYBE_EMIT_END]();
+        return ret;
+    }
+    [READ](n, chunk) {
+        if (this[OBJECTMODE])
+            this[BUFFERSHIFT]();
+        else {
+            const c = chunk;
+            if (n === c.length || n === null)
+                this[BUFFERSHIFT]();
+            else if (typeof c === 'string') {
+                this[BUFFER][0] = c.slice(n);
+                chunk = c.slice(0, n);
+                this[BUFFERLENGTH] -= n;
+            }
+            else {
+                this[BUFFER][0] = c.subarray(n);
+                chunk = c.subarray(0, n);
+                this[BUFFERLENGTH] -= n;
+            }
+        }
+        this.emit('data', chunk);
+        if (!this[BUFFER].length && !this[EOF])
+            this.emit('drain');
+        return chunk;
+    }
+    end(chunk, encoding, cb) {
+        if (typeof chunk === 'function') {
+            cb = chunk;
+            chunk = undefined;
+        }
+        if (typeof encoding === 'function') {
+            cb = encoding;
+            encoding = 'utf8';
+        }
+        if (chunk !== undefined)
+            this.write(chunk, encoding);
+        if (cb)
+            this.once('end', cb);
+        this[EOF] = true;
+        this.writable = false;
+        // if we haven't written anything, then go ahead and emit,
+        // even if we're not reading.
+        // we'll re-emit if a new 'end' listener is added anyway.
+        // This makes MP more suitable to write-only use cases.
+        if (this[FLOWING] || !this[PAUSED])
+            this[MAYBE_EMIT_END]();
+        return this;
+    }
+    // don't let the internal resume be overwritten
+    [RESUME]() {
+        if (this[DESTROYED])
+            return;
+        if (!this[DATALISTENERS] && !this[PIPES].length) {
+            this[DISCARDED] = true;
+        }
+        this[PAUSED] = false;
+        this[FLOWING] = true;
+        this.emit('resume');
+        if (this[BUFFER].length)
+            this[FLUSH]();
+        else if (this[EOF])
+            this[MAYBE_EMIT_END]();
+        else
+            this.emit('drain');
+    }
+    /**
+     * Resume the stream if it is currently in a paused state
+     *
+     * If called when there are no pipe destinations or `data` event listeners,
+     * this will place the stream in a "discarded" state, where all data will
+     * be thrown away. The discarded state is removed if a pipe destination or
+     * data handler is added, if pause() is called, or if any synchronous or
+     * asynchronous iteration is started.
+     */
+    resume() {
+        return this[RESUME]();
+    }
+    /**
+     * Pause the stream
+     */
+    pause() {
+        this[FLOWING] = false;
+        this[PAUSED] = true;
+        this[DISCARDED] = false;
+    }
+    /**
+     * true if the stream has been forcibly destroyed
+     */
+    get destroyed() {
+        return this[DESTROYED];
+    }
+    /**
+     * true if the stream is currently in a flowing state, meaning that
+     * any writes will be immediately emitted.
+     */
+    get flowing() {
+        return this[FLOWING];
+    }
+    /**
+     * true if the stream is currently in a paused state
+     */
+    get paused() {
+        return this[PAUSED];
+    }
+    [BUFFERPUSH](chunk) {
+        if (this[OBJECTMODE])
+            this[BUFFERLENGTH] += 1;
+        else
+            this[BUFFERLENGTH] += chunk.length;
+        this[BUFFER].push(chunk);
+    }
+    [BUFFERSHIFT]() {
+        if (this[OBJECTMODE])
+            this[BUFFERLENGTH] -= 1;
+        else
+            this[BUFFERLENGTH] -= this[BUFFER][0].length;
+        return this[BUFFER].shift();
+    }
+    [FLUSH](noDrain = false) {
+        do { } while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&
+            this[BUFFER].length);
+        if (!noDrain && !this[BUFFER].length && !this[EOF])
+            this.emit('drain');
+    }
+    [FLUSHCHUNK](chunk) {
+        this.emit('data', chunk);
+        return this[FLOWING];
+    }
+    /**
+     * Pipe all data emitted by this stream into the destination provided.
+     *
+     * Triggers the flow of data.
+     */
+    pipe(dest, opts) {
+        if (this[DESTROYED])
+            return dest;
+        this[DISCARDED] = false;
+        const ended = this[EMITTED_END];
+        opts = opts || {};
+        if (dest === proc.stdout || dest === proc.stderr)
+            opts.end = false;
+        else
+            opts.end = opts.end !== false;
+        opts.proxyErrors = !!opts.proxyErrors;
+        // piping an ended stream ends immediately
+        if (ended) {
+            if (opts.end)
+                dest.end();
+        }
+        else {
+            // "as" here just ignores the WType, which pipes don't care about,
+            // since they're only consuming from us, and writing to the dest
+            this[PIPES].push(!opts.proxyErrors
+                ? new Pipe(this, dest, opts)
+                : new PipeProxyErrors(this, dest, opts));
+            if (this[ASYNC])
+                defer(() => this[RESUME]());
+            else
+                this[RESUME]();
+        }
+        return dest;
+    }
+    /**
+     * Fully unhook a piped destination stream.
+     *
+     * If the destination stream was the only consumer of this stream (ie,
+     * there are no other piped destinations or `'data'` event listeners)
+     * then the flow of data will stop until there is another consumer or
+     * {@link Minipass#resume} is explicitly called.
+     */
+    unpipe(dest) {
+        const p = this[PIPES].find(p => p.dest === dest);
+        if (p) {
+            if (this[PIPES].length === 1) {
+                if (this[FLOWING] && this[DATALISTENERS] === 0) {
+                    this[FLOWING] = false;
+                }
+                this[PIPES] = [];
+            }
+            else
+                this[PIPES].splice(this[PIPES].indexOf(p), 1);
+            p.unpipe();
+        }
+    }
+    /**
+     * Alias for {@link Minipass#on}
+     */
+    addListener(ev, handler) {
+        return this.on(ev, handler);
+    }
+    /**
+     * Mostly identical to `EventEmitter.on`, with the following
+     * behavior differences to prevent data loss and unnecessary hangs:
+     *
+     * - Adding a 'data' event handler will trigger the flow of data
+     *
+     * - Adding a 'readable' event handler when there is data waiting to be read
+     *   will cause 'readable' to be emitted immediately.
+     *
+     * - Adding an 'endish' event handler ('end', 'finish', etc.) which has
+     *   already passed will cause the event to be emitted immediately and all
+     *   handlers removed.
+     *
+     * - Adding an 'error' event handler after an error has been emitted will
+     *   cause the event to be re-emitted immediately with the error previously
+     *   raised.
+     */
+    on(ev, handler) {
+        const ret = super.on(ev, handler);
+        if (ev === 'data') {
+            this[DISCARDED] = false;
+            this[DATALISTENERS]++;
+            if (!this[PIPES].length && !this[FLOWING]) {
+                this[RESUME]();
+            }
+        }
+        else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {
+            super.emit('readable');
+        }
+        else if (isEndish(ev) && this[EMITTED_END]) {
+            super.emit(ev);
+            this.removeAllListeners(ev);
+        }
+        else if (ev === 'error' && this[EMITTED_ERROR]) {
+            const h = handler;
+            if (this[ASYNC])
+                defer(() => h.call(this, this[EMITTED_ERROR]));
+            else
+                h.call(this, this[EMITTED_ERROR]);
+        }
+        return ret;
+    }
+    /**
+     * Alias for {@link Minipass#off}
+     */
+    removeListener(ev, handler) {
+        return this.off(ev, handler);
+    }
+    /**
+     * Mostly identical to `EventEmitter.off`
+     *
+     * If a 'data' event handler is removed, and it was the last consumer
+     * (ie, there are no pipe destinations or other 'data' event listeners),
+     * then the flow of data will stop until there is another consumer or
+     * {@link Minipass#resume} is explicitly called.
+     */
+    off(ev, handler) {
+        const ret = super.off(ev, handler);
+        // if we previously had listeners, and now we don't, and we don't
+        // have any pipes, then stop the flow, unless it's been explicitly
+        // put in a discarded flowing state via stream.resume().
+        if (ev === 'data') {
+            this[DATALISTENERS] = this.listeners('data').length;
+            if (this[DATALISTENERS] === 0 &&
+                !this[DISCARDED] &&
+                !this[PIPES].length) {
+                this[FLOWING] = false;
+            }
+        }
+        return ret;
+    }
+    /**
+     * Mostly identical to `EventEmitter.removeAllListeners`
+     *
+     * If all 'data' event handlers are removed, and they were the last consumer
+     * (ie, there are no pipe destinations), then the flow of data will stop
+     * until there is another consumer or {@link Minipass#resume} is explicitly
+     * called.
+     */
+    removeAllListeners(ev) {
+        const ret = super.removeAllListeners(ev);
+        if (ev === 'data' || ev === undefined) {
+            this[DATALISTENERS] = 0;
+            if (!this[DISCARDED] && !this[PIPES].length) {
+                this[FLOWING] = false;
+            }
+        }
+        return ret;
+    }
+    /**
+     * true if the 'end' event has been emitted
+     */
+    get emittedEnd() {
+        return this[EMITTED_END];
+    }
+    [MAYBE_EMIT_END]() {
+        if (!this[EMITTING_END] &&
+            !this[EMITTED_END] &&
+            !this[DESTROYED] &&
+            this[BUFFER].length === 0 &&
+            this[EOF]) {
+            this[EMITTING_END] = true;
+            this.emit('end');
+            this.emit('prefinish');
+            this.emit('finish');
+            if (this[CLOSED])
+                this.emit('close');
+            this[EMITTING_END] = false;
+        }
+    }
+    /**
+     * Mostly identical to `EventEmitter.emit`, with the following
+     * behavior differences to prevent data loss and unnecessary hangs:
+     *
+     * If the stream has been destroyed, and the event is something other
+     * than 'close' or 'error', then `false` is returned and no handlers
+     * are called.
+     *
+     * If the event is 'end', and has already been emitted, then the event
+     * is ignored. If the stream is in a paused or non-flowing state, then
+     * the event will be deferred until data flow resumes. If the stream is
+     * async, then handlers will be called on the next tick rather than
+     * immediately.
+     *
+     * If the event is 'close', and 'end' has not yet been emitted, then
+     * the event will be deferred until after 'end' is emitted.
+     *
+     * If the event is 'error', and an AbortSignal was provided for the stream,
+     * and there are no listeners, then the event is ignored, matching the
+     * behavior of node core streams in the presense of an AbortSignal.
+     *
+     * If the event is 'finish' or 'prefinish', then all listeners will be
+     * removed after emitting the event, to prevent double-firing.
+     */
+    emit(ev, ...args) {
+        const data = args[0];
+        // error and close are only events allowed after calling destroy()
+        if (ev !== 'error' &&
+            ev !== 'close' &&
+            ev !== DESTROYED &&
+            this[DESTROYED]) {
+            return false;
+        }
+        else if (ev === 'data') {
+            return !this[OBJECTMODE] && !data
+                ? false
+                : this[ASYNC]
+                    ? (defer(() => this[EMITDATA](data)), true)
+                    : this[EMITDATA](data);
+        }
+        else if (ev === 'end') {
+            return this[EMITEND]();
+        }
+        else if (ev === 'close') {
+            this[CLOSED] = true;
+            // don't emit close before 'end' and 'finish'
+            if (!this[EMITTED_END] && !this[DESTROYED])
+                return false;
+            const ret = super.emit('close');
+            this.removeAllListeners('close');
+            return ret;
+        }
+        else if (ev === 'error') {
+            this[EMITTED_ERROR] = data;
+            super.emit(ERROR, data);
+            const ret = !this[SIGNAL] || this.listeners('error').length
+                ? super.emit('error', data)
+                : false;
+            this[MAYBE_EMIT_END]();
+            return ret;
+        }
+        else if (ev === 'resume') {
+            const ret = super.emit('resume');
+            this[MAYBE_EMIT_END]();
+            return ret;
+        }
+        else if (ev === 'finish' || ev === 'prefinish') {
+            const ret = super.emit(ev);
+            this.removeAllListeners(ev);
+            return ret;
+        }
+        // Some other unknown event
+        const ret = super.emit(ev, ...args);
+        this[MAYBE_EMIT_END]();
+        return ret;
+    }
+    [EMITDATA](data) {
+        for (const p of this[PIPES]) {
+            if (p.dest.write(data) === false)
+                this.pause();
+        }
+        const ret = this[DISCARDED] ? false : super.emit('data', data);
+        this[MAYBE_EMIT_END]();
+        return ret;
+    }
+    [EMITEND]() {
+        if (this[EMITTED_END])
+            return false;
+        this[EMITTED_END] = true;
+        this.readable = false;
+        return this[ASYNC]
+            ? (defer(() => this[EMITEND2]()), true)
+            : this[EMITEND2]();
+    }
+    [EMITEND2]() {
+        if (this[DECODER]) {
+            const data = this[DECODER].end();
+            if (data) {
+                for (const p of this[PIPES]) {
+                    p.dest.write(data);
+                }
+                if (!this[DISCARDED])
+                    super.emit('data', data);
+            }
+        }
+        for (const p of this[PIPES]) {
+            p.end();
+        }
+        const ret = super.emit('end');
+        this.removeAllListeners('end');
+        return ret;
+    }
+    /**
+     * Return a Promise that resolves to an array of all emitted data once
+     * the stream ends.
+     */
+    async collect() {
+        const buf = Object.assign([], {
+            dataLength: 0,
+        });
+        if (!this[OBJECTMODE])
+            buf.dataLength = 0;
+        // set the promise first, in case an error is raised
+        // by triggering the flow here.
+        const p = this.promise();
+        this.on('data', c => {
+            buf.push(c);
+            if (!this[OBJECTMODE])
+                buf.dataLength += c.length;
+        });
+        await p;
+        return buf;
+    }
+    /**
+     * Return a Promise that resolves to the concatenation of all emitted data
+     * once the stream ends.
+     *
+     * Not allowed on objectMode streams.
+     */
+    async concat() {
+        if (this[OBJECTMODE]) {
+            throw new Error('cannot concat in objectMode');
+        }
+        const buf = await this.collect();
+        return (this[ENCODING]
+            ? buf.join('')
+            : Buffer.concat(buf, buf.dataLength));
+    }
+    /**
+     * Return a void Promise that resolves once the stream ends.
+     */
+    async promise() {
+        return new Promise((resolve, reject) => {
+            this.on(DESTROYED, () => reject(new Error('stream destroyed')));
+            this.on('error', er => reject(er));
+            this.on('end', () => resolve());
+        });
+    }
+    /**
+     * Asynchronous `for await of` iteration.
+     *
+     * This will continue emitting all chunks until the stream terminates.
+     */
+    [Symbol.asyncIterator]() {
+        // set this up front, in case the consumer doesn't call next()
+        // right away.
+        this[DISCARDED] = false;
+        let stopped = false;
+        const stop = async () => {
+            this.pause();
+            stopped = true;
+            return { value: undefined, done: true };
+        };
+        const next = () => {
+            if (stopped)
+                return stop();
+            const res = this.read();
+            if (res !== null)
+                return Promise.resolve({ done: false, value: res });
+            if (this[EOF])
+                return stop();
+            let resolve;
+            let reject;
+            const onerr = (er) => {
+                this.off('data', ondata);
+                this.off('end', onend);
+                this.off(DESTROYED, ondestroy);
+                stop();
+                reject(er);
+            };
+            const ondata = (value) => {
+                this.off('error', onerr);
+                this.off('end', onend);
+                this.off(DESTROYED, ondestroy);
+                this.pause();
+                resolve({ value, done: !!this[EOF] });
+            };
+            const onend = () => {
+                this.off('error', onerr);
+                this.off('data', ondata);
+                this.off(DESTROYED, ondestroy);
+                stop();
+                resolve({ done: true, value: undefined });
+            };
+            const ondestroy = () => onerr(new Error('stream destroyed'));
+            return new Promise((res, rej) => {
+                reject = rej;
+                resolve = res;
+                this.once(DESTROYED, ondestroy);
+                this.once('error', onerr);
+                this.once('end', onend);
+                this.once('data', ondata);
+            });
+        };
+        return {
+            next,
+            throw: stop,
+            return: stop,
+            [Symbol.asyncIterator]() {
+                return this;
+            },
+        };
+    }
+    /**
+     * Synchronous `for of` iteration.
+     *
+     * The iteration will terminate when the internal buffer runs out, even
+     * if the stream has not yet terminated.
+     */
+    [Symbol.iterator]() {
+        // set this up front, in case the consumer doesn't call next()
+        // right away.
+        this[DISCARDED] = false;
+        let stopped = false;
+        const stop = () => {
+            this.pause();
+            this.off(ERROR, stop);
+            this.off(DESTROYED, stop);
+            this.off('end', stop);
+            stopped = true;
+            return { done: true, value: undefined };
+        };
+        const next = () => {
+            if (stopped)
+                return stop();
+            const value = this.read();
+            return value === null ? stop() : { done: false, value };
+        };
+        this.once('end', stop);
+        this.once(ERROR, stop);
+        this.once(DESTROYED, stop);
+        return {
+            next,
+            throw: stop,
+            return: stop,
+            [Symbol.iterator]() {
+                return this;
+            },
+        };
+    }
+    /**
+     * Destroy a stream, preventing it from being used for any further purpose.
+     *
+     * If the stream has a `close()` method, then it will be called on
+     * destruction.
+     *
+     * After destruction, any attempt to write data, read data, or emit most
+     * events will be ignored.
+     *
+     * If an error argument is provided, then it will be emitted in an
+     * 'error' event.
+     */
+    destroy(er) {
+        if (this[DESTROYED]) {
+            if (er)
+                this.emit('error', er);
+            else
+                this.emit(DESTROYED);
+            return this;
+        }
+        this[DESTROYED] = true;
+        this[DISCARDED] = true;
+        // throw away all buffered data, it's never coming out
+        this[BUFFER].length = 0;
+        this[BUFFERLENGTH] = 0;
+        const wc = this;
+        if (typeof wc.close === 'function' && !this[CLOSED])
+            wc.close();
+        if (er)
+            this.emit('error', er);
+        // if no error to emit, still reject pending promises
+        else
+            this.emit(DESTROYED);
+        return this;
+    }
+    /**
+     * Alias for {@link isStream}
+     *
+     * Former export location, maintained for backwards compatibility.
+     *
+     * @deprecated
+     */
+    static get isStream() {
+        return exports.isStream;
+    }
+}
+exports.Minipass = Minipass;
+//# sourceMappingURL=index.js.map
\ No newline at end of file
diff --git a/node_modules/minipass/dist/commonjs/index.js.map b/node_modules/minipass/dist/commonjs/index.js.map
new file mode 100644
index 0000000..9f3ef4b
--- /dev/null
+++ b/node_modules/minipass/dist/commonjs/index.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;AAAA,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO;IACpC,CAAC,CAAC,OAAO;IACT,CAAC,CAAC;QACE,MAAM,EAAE,IAAI;QACZ,MAAM,EAAE,IAAI;KACb,CAAA;AACP,6CAA0C;AAC1C,8DAAgC;AAChC,6DAAmD;AASnD;;;GAGG;AACI,MAAM,QAAQ,GAAG,CACtB,CAAM,EACsC,EAAE,CAC9C,CAAC,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,QAAQ;IACrB,CAAC,CAAC,YAAY,QAAQ;QACpB,CAAC,YAAY,qBAAM;QACnB,IAAA,kBAAU,EAAC,CAAC,CAAC;QACb,IAAA,kBAAU,EAAC,CAAC,CAAC,CAAC,CAAA;AARL,QAAA,QAAQ,YAQH;AAElB;;GAEG;AACI,MAAM,UAAU,GAAG,CAAC,CAAM,EAA0B,EAAE,CAC3D,CAAC,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,QAAQ;IACrB,CAAC,YAAY,0BAAY;IACzB,OAAQ,CAAuB,CAAC,IAAI,KAAK,UAAU;IACn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ACvB,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,CAAA;QAEtB,MAAM,EAAE,GAAG,IAEV,CAAA;QACD,IAAI,OAAO,EAAE,CAAC,KAAK,KAAK,UAAU,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC;YAAE,EAAE,CAAC,KAAK,EAAE,CAAA;QAE/D,IAAI,EAAE;YAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC,CAAA;QAC9B,qDAAqD;;YAChD,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;QAEzB,OAAO,IAAI,CAAA;IACb,CAAC;IAED;;;;;;OAMG;IACH,MAAM,KAAK,QAAQ;QACjB,OAAO,gBAAQ,CAAA;IACjB,CAAC;CACF;AAn/BD,4BAm/BC","sourcesContent":["const proc =\n  typeof process === 'object' && process\n    ? process\n    : {\n        stdout: null,\n        stderr: null,\n      }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node: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 =\n    | ObjectModeOptions\n    | (T extends string\n        ? EncodingOptions\n        : T extends Buffer\n        ? BufferOptions\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:\n      | [Minipass.ObjectModeOptions]\n      | (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  ): this {\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 as RType) === 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"]}
\ No newline at end of file
diff --git a/node_modules/minipass/dist/commonjs/package.json b/node_modules/minipass/dist/commonjs/package.json
new file mode 100644
index 0000000..5bbefff
--- /dev/null
+++ b/node_modules/minipass/dist/commonjs/package.json
@@ -0,0 +1,3 @@
+{
+  "type": "commonjs"
+}
diff --git a/node_modules/minipass/dist/esm/index.d.ts b/node_modules/minipass/dist/esm/index.d.ts
new file mode 100644
index 0000000..6dbfbcf
--- /dev/null
+++ b/node_modules/minipass/dist/esm/index.d.ts
@@ -0,0 +1,549 @@
+/// 
+/// 
+/// 
+/// 
+import { EventEmitter } from 'node:events';
+import { StringDecoder } from 'node:string_decoder';
+/**
+ * Same as StringDecoder, but exposing the `lastNeed` flag on the type
+ */
+type SD = StringDecoder & {
+    lastNeed: boolean;
+};
+export type { SD, Pipe, PipeProxyErrors };
+/**
+ * Return true if the argument is a Minipass stream, Node stream, or something
+ * else that Minipass can interact with.
+ */
+export declare const isStream: (s: any) => s is NodeJS.WriteStream | NodeJS.ReadStream | Minipass | (NodeJS.ReadStream & {
+    fd: number;
+}) | (EventEmitter & {
+    pause(): any;
+    resume(): any;
+    pipe(...destArgs: any[]): any;
+}) | (NodeJS.WriteStream & {
+    fd: number;
+}) | (EventEmitter & {
+    end(): any;
+    write(chunk: any, ...args: any[]): any;
+});
+/**
+ * Return true if the argument is a valid {@link Minipass.Readable}
+ */
+export declare const isReadable: (s: any) => s is Minipass.Readable;
+/**
+ * Return true if the argument is a valid {@link Minipass.Writable}
+ */
+export declare const isWritable: (s: any) => s is Minipass.Readable;
+declare const EOF: unique symbol;
+declare const MAYBE_EMIT_END: unique symbol;
+declare const EMITTED_END: unique symbol;
+declare const EMITTING_END: unique symbol;
+declare const EMITTED_ERROR: unique symbol;
+declare const CLOSED: unique symbol;
+declare const READ: unique symbol;
+declare const FLUSH: unique symbol;
+declare const FLUSHCHUNK: unique symbol;
+declare const ENCODING: unique symbol;
+declare const DECODER: unique symbol;
+declare const FLOWING: unique symbol;
+declare const PAUSED: unique symbol;
+declare const RESUME: unique symbol;
+declare const BUFFER: unique symbol;
+declare const PIPES: unique symbol;
+declare const BUFFERLENGTH: unique symbol;
+declare const BUFFERPUSH: unique symbol;
+declare const BUFFERSHIFT: unique symbol;
+declare const OBJECTMODE: unique symbol;
+declare const DESTROYED: unique symbol;
+declare const ERROR: unique symbol;
+declare const EMITDATA: unique symbol;
+declare const EMITEND: unique symbol;
+declare const EMITEND2: unique symbol;
+declare const ASYNC: unique symbol;
+declare const ABORT: unique symbol;
+declare const ABORTED: unique symbol;
+declare const SIGNAL: unique symbol;
+declare const DATALISTENERS: unique symbol;
+declare const DISCARDED: unique symbol;
+/**
+ * Options that may be passed to stream.pipe()
+ */
+export interface PipeOptions {
+    /**
+     * end the destination stream when the source stream ends
+     */
+    end?: boolean;
+    /**
+     * proxy errors from the source stream to the destination stream
+     */
+    proxyErrors?: boolean;
+}
+/**
+ * Internal class representing a pipe to a destination stream.
+ *
+ * @internal
+ */
+declare class Pipe {
+    src: Minipass;
+    dest: Minipass;
+    opts: PipeOptions;
+    ondrain: () => any;
+    constructor(src: Minipass, dest: Minipass.Writable, opts: PipeOptions);
+    unpipe(): void;
+    proxyErrors(_er: any): void;
+    end(): void;
+}
+/**
+ * Internal class representing a pipe to a destination stream where
+ * errors are proxied.
+ *
+ * @internal
+ */
+declare class PipeProxyErrors extends Pipe {
+    unpipe(): void;
+    constructor(src: Minipass, dest: Minipass.Writable, opts: PipeOptions);
+}
+export declare namespace Minipass {
+    /**
+     * Encoding used to create a stream that outputs strings rather than
+     * Buffer objects.
+     */
+    export type Encoding = BufferEncoding | 'buffer' | null;
+    /**
+     * Any stream that Minipass can pipe into
+     */
+    export type Writable = Minipass | NodeJS.WriteStream | (NodeJS.WriteStream & {
+        fd: number;
+    }) | (EventEmitter & {
+        end(): any;
+        write(chunk: any, ...args: any[]): any;
+    });
+    /**
+     * Any stream that can be read from
+     */
+    export type Readable = Minipass | NodeJS.ReadStream | (NodeJS.ReadStream & {
+        fd: number;
+    }) | (EventEmitter & {
+        pause(): any;
+        resume(): any;
+        pipe(...destArgs: any[]): any;
+    });
+    /**
+     * Utility type that can be iterated sync or async
+     */
+    export type DualIterable = Iterable & AsyncIterable;
+    type EventArguments = Record;
+    /**
+     * The listing of events that a Minipass class can emit.
+     * Extend this when extending the Minipass class, and pass as
+     * the third template argument.  The key is the name of the event,
+     * and the value is the argument list.
+     *
+     * Any undeclared events will still be allowed, but the handler will get
+     * arguments as `unknown[]`.
+     */
+    export interface Events extends EventArguments {
+        readable: [];
+        data: [chunk: RType];
+        error: [er: unknown];
+        abort: [reason: unknown];
+        drain: [];
+        resume: [];
+        end: [];
+        finish: [];
+        prefinish: [];
+        close: [];
+        [DESTROYED]: [er?: unknown];
+        [ERROR]: [er: unknown];
+    }
+    /**
+     * String or buffer-like data that can be joined and sliced
+     */
+    export type ContiguousData = Buffer | ArrayBufferLike | ArrayBufferView | string;
+    export type BufferOrString = Buffer | string;
+    /**
+     * Options passed to the Minipass constructor.
+     */
+    export type SharedOptions = {
+        /**
+         * Defer all data emission and other events until the end of the
+         * current tick, similar to Node core streams
+         */
+        async?: boolean;
+        /**
+         * A signal which will abort the stream
+         */
+        signal?: AbortSignal;
+        /**
+         * Output string encoding. Set to `null` or `'buffer'` (or omit) to
+         * emit Buffer objects rather than strings.
+         *
+         * Conflicts with `objectMode`
+         */
+        encoding?: BufferEncoding | null | 'buffer';
+        /**
+         * Output data exactly as it was written, supporting non-buffer/string
+         * data (such as arbitrary objects, falsey values, etc.)
+         *
+         * Conflicts with `encoding`
+         */
+        objectMode?: boolean;
+    };
+    /**
+     * Options for a string encoded output
+     */
+    export type EncodingOptions = SharedOptions & {
+        encoding: BufferEncoding;
+        objectMode?: false;
+    };
+    /**
+     * Options for contiguous data buffer output
+     */
+    export type BufferOptions = SharedOptions & {
+        encoding?: null | 'buffer';
+        objectMode?: false;
+    };
+    /**
+     * Options for objectMode arbitrary output
+     */
+    export type ObjectModeOptions = SharedOptions & {
+        objectMode: true;
+        encoding?: null;
+    };
+    /**
+     * Utility type to determine allowed options based on read type
+     */
+    export type Options = ObjectModeOptions | (T extends string ? EncodingOptions : T extends Buffer ? BufferOptions : SharedOptions);
+    export {};
+}
+/**
+ * Main export, the Minipass class
+ *
+ * `RType` is the type of data emitted, defaults to Buffer
+ *
+ * `WType` is the type of data to be written, if RType is buffer or string,
+ * then any {@link Minipass.ContiguousData} is allowed.
+ *
+ * `Events` is the set of event handler signatures that this object
+ * will emit, see {@link Minipass.Events}
+ */
+export declare class Minipass = Minipass.Events> extends EventEmitter implements Minipass.DualIterable {
+    [FLOWING]: boolean;
+    [PAUSED]: boolean;
+    [PIPES]: Pipe[];
+    [BUFFER]: RType[];
+    [OBJECTMODE]: boolean;
+    [ENCODING]: BufferEncoding | null;
+    [ASYNC]: boolean;
+    [DECODER]: SD | null;
+    [EOF]: boolean;
+    [EMITTED_END]: boolean;
+    [EMITTING_END]: boolean;
+    [CLOSED]: boolean;
+    [EMITTED_ERROR]: unknown;
+    [BUFFERLENGTH]: number;
+    [DESTROYED]: boolean;
+    [SIGNAL]?: AbortSignal;
+    [ABORTED]: boolean;
+    [DATALISTENERS]: number;
+    [DISCARDED]: boolean;
+    /**
+     * true if the stream can be written
+     */
+    writable: boolean;
+    /**
+     * true if the stream can be read
+     */
+    readable: boolean;
+    /**
+     * If `RType` is Buffer, then options do not need to be provided.
+     * Otherwise, an options object must be provided to specify either
+     * {@link Minipass.SharedOptions.objectMode} or
+     * {@link Minipass.SharedOptions.encoding}, as appropriate.
+     */
+    constructor(...args: [Minipass.ObjectModeOptions] | (RType extends Buffer ? [] | [Minipass.Options] : [Minipass.Options]));
+    /**
+     * The amount of data stored in the buffer waiting to be read.
+     *
+     * For Buffer strings, this will be the total byte length.
+     * For string encoding streams, this will be the string character length,
+     * according to JavaScript's `string.length` logic.
+     * For objectMode streams, this is a count of the items waiting to be
+     * emitted.
+     */
+    get bufferLength(): number;
+    /**
+     * The `BufferEncoding` currently in use, or `null`
+     */
+    get encoding(): BufferEncoding | null;
+    /**
+     * @deprecated - This is a read only property
+     */
+    set encoding(_enc: BufferEncoding | null);
+    /**
+     * @deprecated - Encoding may only be set at instantiation time
+     */
+    setEncoding(_enc: Minipass.Encoding): void;
+    /**
+     * True if this is an objectMode stream
+     */
+    get objectMode(): boolean;
+    /**
+     * @deprecated - This is a read-only property
+     */
+    set objectMode(_om: boolean);
+    /**
+     * true if this is an async stream
+     */
+    get ['async'](): boolean;
+    /**
+     * Set to true to make this stream async.
+     *
+     * Once set, it cannot be unset, as this would potentially cause incorrect
+     * behavior.  Ie, a sync stream can be made async, but an async stream
+     * cannot be safely made sync.
+     */
+    set ['async'](a: boolean);
+    [ABORT](): void;
+    /**
+     * True if the stream has been aborted.
+     */
+    get aborted(): boolean;
+    /**
+     * No-op setter. Stream aborted status is set via the AbortSignal provided
+     * in the constructor options.
+     */
+    set aborted(_: boolean);
+    /**
+     * Write data into the stream
+     *
+     * If the chunk written is a string, and encoding is not specified, then
+     * `utf8` will be assumed. If the stream encoding matches the encoding of
+     * a written string, and the state of the string decoder allows it, then
+     * the string will be passed through to either the output or the internal
+     * buffer without any processing. Otherwise, it will be turned into a
+     * Buffer object for processing into the desired encoding.
+     *
+     * If provided, `cb` function is called immediately before return for
+     * sync streams, or on next tick for async streams, because for this
+     * base class, a chunk is considered "processed" once it is accepted
+     * and either emitted or buffered. That is, the callback does not indicate
+     * that the chunk has been eventually emitted, though of course child
+     * classes can override this function to do whatever processing is required
+     * and call `super.write(...)` only once processing is completed.
+     */
+    write(chunk: WType, cb?: () => void): boolean;
+    write(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): boolean;
+    /**
+     * Low-level explicit read method.
+     *
+     * In objectMode, the argument is ignored, and one item is returned if
+     * available.
+     *
+     * `n` is the number of bytes (or in the case of encoding streams,
+     * characters) to consume. If `n` is not provided, then the entire buffer
+     * is returned, or `null` is returned if no data is available.
+     *
+     * If `n` is greater that the amount of data in the internal buffer,
+     * then `null` is returned.
+     */
+    read(n?: number | null): RType | null;
+    [READ](n: number | null, chunk: RType): RType;
+    /**
+     * End the stream, optionally providing a final write.
+     *
+     * See {@link Minipass#write} for argument descriptions
+     */
+    end(cb?: () => void): this;
+    end(chunk: WType, cb?: () => void): this;
+    end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this;
+    [RESUME](): void;
+    /**
+     * Resume the stream if it is currently in a paused state
+     *
+     * If called when there are no pipe destinations or `data` event listeners,
+     * this will place the stream in a "discarded" state, where all data will
+     * be thrown away. The discarded state is removed if a pipe destination or
+     * data handler is added, if pause() is called, or if any synchronous or
+     * asynchronous iteration is started.
+     */
+    resume(): void;
+    /**
+     * Pause the stream
+     */
+    pause(): void;
+    /**
+     * true if the stream has been forcibly destroyed
+     */
+    get destroyed(): boolean;
+    /**
+     * true if the stream is currently in a flowing state, meaning that
+     * any writes will be immediately emitted.
+     */
+    get flowing(): boolean;
+    /**
+     * true if the stream is currently in a paused state
+     */
+    get paused(): boolean;
+    [BUFFERPUSH](chunk: RType): void;
+    [BUFFERSHIFT](): RType;
+    [FLUSH](noDrain?: boolean): void;
+    [FLUSHCHUNK](chunk: RType): boolean;
+    /**
+     * Pipe all data emitted by this stream into the destination provided.
+     *
+     * Triggers the flow of data.
+     */
+    pipe(dest: W, opts?: PipeOptions): W;
+    /**
+     * Fully unhook a piped destination stream.
+     *
+     * If the destination stream was the only consumer of this stream (ie,
+     * there are no other piped destinations or `'data'` event listeners)
+     * then the flow of data will stop until there is another consumer or
+     * {@link Minipass#resume} is explicitly called.
+     */
+    unpipe(dest: W): void;
+    /**
+     * Alias for {@link Minipass#on}
+     */
+    addListener(ev: Event, handler: (...args: Events[Event]) => any): this;
+    /**
+     * Mostly identical to `EventEmitter.on`, with the following
+     * behavior differences to prevent data loss and unnecessary hangs:
+     *
+     * - Adding a 'data' event handler will trigger the flow of data
+     *
+     * - Adding a 'readable' event handler when there is data waiting to be read
+     *   will cause 'readable' to be emitted immediately.
+     *
+     * - Adding an 'endish' event handler ('end', 'finish', etc.) which has
+     *   already passed will cause the event to be emitted immediately and all
+     *   handlers removed.
+     *
+     * - Adding an 'error' event handler after an error has been emitted will
+     *   cause the event to be re-emitted immediately with the error previously
+     *   raised.
+     */
+    on(ev: Event, handler: (...args: Events[Event]) => any): this;
+    /**
+     * Alias for {@link Minipass#off}
+     */
+    removeListener(ev: Event, handler: (...args: Events[Event]) => any): this;
+    /**
+     * Mostly identical to `EventEmitter.off`
+     *
+     * If a 'data' event handler is removed, and it was the last consumer
+     * (ie, there are no pipe destinations or other 'data' event listeners),
+     * then the flow of data will stop until there is another consumer or
+     * {@link Minipass#resume} is explicitly called.
+     */
+    off(ev: Event, handler: (...args: Events[Event]) => any): this;
+    /**
+     * Mostly identical to `EventEmitter.removeAllListeners`
+     *
+     * If all 'data' event handlers are removed, and they were the last consumer
+     * (ie, there are no pipe destinations), then the flow of data will stop
+     * until there is another consumer or {@link Minipass#resume} is explicitly
+     * called.
+     */
+    removeAllListeners(ev?: Event): this;
+    /**
+     * true if the 'end' event has been emitted
+     */
+    get emittedEnd(): boolean;
+    [MAYBE_EMIT_END](): void;
+    /**
+     * Mostly identical to `EventEmitter.emit`, with the following
+     * behavior differences to prevent data loss and unnecessary hangs:
+     *
+     * If the stream has been destroyed, and the event is something other
+     * than 'close' or 'error', then `false` is returned and no handlers
+     * are called.
+     *
+     * If the event is 'end', and has already been emitted, then the event
+     * is ignored. If the stream is in a paused or non-flowing state, then
+     * the event will be deferred until data flow resumes. If the stream is
+     * async, then handlers will be called on the next tick rather than
+     * immediately.
+     *
+     * If the event is 'close', and 'end' has not yet been emitted, then
+     * the event will be deferred until after 'end' is emitted.
+     *
+     * If the event is 'error', and an AbortSignal was provided for the stream,
+     * and there are no listeners, then the event is ignored, matching the
+     * behavior of node core streams in the presense of an AbortSignal.
+     *
+     * If the event is 'finish' or 'prefinish', then all listeners will be
+     * removed after emitting the event, to prevent double-firing.
+     */
+    emit(ev: Event, ...args: Events[Event]): boolean;
+    [EMITDATA](data: RType): boolean;
+    [EMITEND](): boolean;
+    [EMITEND2](): boolean;
+    /**
+     * Return a Promise that resolves to an array of all emitted data once
+     * the stream ends.
+     */
+    collect(): Promise;
+    /**
+     * Return a Promise that resolves to the concatenation of all emitted data
+     * once the stream ends.
+     *
+     * Not allowed on objectMode streams.
+     */
+    concat(): Promise;
+    /**
+     * Return a void Promise that resolves once the stream ends.
+     */
+    promise(): Promise;
+    /**
+     * Asynchronous `for await of` iteration.
+     *
+     * This will continue emitting all chunks until the stream terminates.
+     */
+    [Symbol.asyncIterator](): AsyncGenerator;
+    /**
+     * Synchronous `for of` iteration.
+     *
+     * The iteration will terminate when the internal buffer runs out, even
+     * if the stream has not yet terminated.
+     */
+    [Symbol.iterator](): Generator;
+    /**
+     * Destroy a stream, preventing it from being used for any further purpose.
+     *
+     * If the stream has a `close()` method, then it will be called on
+     * destruction.
+     *
+     * After destruction, any attempt to write data, read data, or emit most
+     * events will be ignored.
+     *
+     * If an error argument is provided, then it will be emitted in an
+     * 'error' event.
+     */
+    destroy(er?: unknown): this;
+    /**
+     * Alias for {@link isStream}
+     *
+     * Former export location, maintained for backwards compatibility.
+     *
+     * @deprecated
+     */
+    static get isStream(): (s: any) => s is NodeJS.WriteStream | NodeJS.ReadStream | Minipass | (NodeJS.ReadStream & {
+        fd: number;
+    }) | (EventEmitter & {
+        pause(): any;
+        resume(): any;
+        pipe(...destArgs: any[]): any;
+    }) | (NodeJS.WriteStream & {
+        fd: number;
+    }) | (EventEmitter & {
+        end(): any;
+        write(chunk: any, ...args: any[]): any;
+    });
+}
+//# sourceMappingURL=index.d.ts.map
\ No newline at end of file
diff --git a/node_modules/minipass/dist/esm/index.d.ts.map b/node_modules/minipass/dist/esm/index.d.ts.map
new file mode 100644
index 0000000..cac7e00
--- /dev/null
+++ b/node_modules/minipass/dist/esm/index.d.ts.map
@@ -0,0 +1 @@
+{"version":3,"file":"index.d.ts","sourceRoot":"","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OAAO,CAAC,KAAK,CAAC;IAY9B;;OAEG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAQ9B;;;;OAIG;IACH,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,cAAc,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC;IA6D3D;;;;;OAKG;IACH,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC;IAkCjD;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,EAAE,CAAC,EAAE,OAAO;IA0BpB;;;;;;OAMG;IACH,MAAM,KAAK,QAAQ;;;;;;;;;;;OAElB;CACF"}
\ No newline at end of file
diff --git a/node_modules/minipass/dist/esm/index.js b/node_modules/minipass/dist/esm/index.js
new file mode 100644
index 0000000..b5fa451
--- /dev/null
+++ b/node_modules/minipass/dist/esm/index.js
@@ -0,0 +1,1018 @@
+const proc = typeof process === 'object' && process
+    ? process
+    : {
+        stdout: null,
+        stderr: null,
+    };
+import { EventEmitter } from 'node:events';
+import Stream from 'node:stream';
+import { StringDecoder } from 'node:string_decoder';
+/**
+ * Return true if the argument is a Minipass stream, Node stream, or something
+ * else that Minipass can interact with.
+ */
+export const isStream = (s) => !!s &&
+    typeof s === 'object' &&
+    (s instanceof Minipass ||
+        s instanceof Stream ||
+        isReadable(s) ||
+        isWritable(s));
+/**
+ * Return true if the argument is a valid {@link Minipass.Readable}
+ */
+export const isReadable = (s) => !!s &&
+    typeof s === 'object' &&
+    s instanceof EventEmitter &&
+    typeof s.pipe === 'function' &&
+    // node core Writable streams have a pipe() method, but it throws
+    s.pipe !== Stream.Writable.prototype.pipe;
+/**
+ * Return true if the argument is a valid {@link Minipass.Writable}
+ */
+export const isWritable = (s) => !!s &&
+    typeof s === 'object' &&
+    s instanceof EventEmitter &&
+    typeof s.write === 'function' &&
+    typeof s.end === 'function';
+const EOF = Symbol('EOF');
+const MAYBE_EMIT_END = Symbol('maybeEmitEnd');
+const EMITTED_END = Symbol('emittedEnd');
+const EMITTING_END = Symbol('emittingEnd');
+const EMITTED_ERROR = Symbol('emittedError');
+const CLOSED = Symbol('closed');
+const READ = Symbol('read');
+const FLUSH = Symbol('flush');
+const FLUSHCHUNK = Symbol('flushChunk');
+const ENCODING = Symbol('encoding');
+const DECODER = Symbol('decoder');
+const FLOWING = Symbol('flowing');
+const PAUSED = Symbol('paused');
+const RESUME = Symbol('resume');
+const BUFFER = Symbol('buffer');
+const PIPES = Symbol('pipes');
+const BUFFERLENGTH = Symbol('bufferLength');
+const BUFFERPUSH = Symbol('bufferPush');
+const BUFFERSHIFT = Symbol('bufferShift');
+const OBJECTMODE = Symbol('objectMode');
+// internal event when stream is destroyed
+const DESTROYED = Symbol('destroyed');
+// internal event when stream has an error
+const ERROR = Symbol('error');
+const EMITDATA = Symbol('emitData');
+const EMITEND = Symbol('emitEnd');
+const EMITEND2 = Symbol('emitEnd2');
+const ASYNC = Symbol('async');
+const ABORT = Symbol('abort');
+const ABORTED = Symbol('aborted');
+const SIGNAL = Symbol('signal');
+const DATALISTENERS = Symbol('dataListeners');
+const DISCARDED = Symbol('discarded');
+const defer = (fn) => Promise.resolve().then(fn);
+const nodefer = (fn) => fn();
+const isEndish = (ev) => ev === 'end' || ev === 'finish' || ev === 'prefinish';
+const isArrayBufferLike = (b) => b instanceof ArrayBuffer ||
+    (!!b &&
+        typeof b === 'object' &&
+        b.constructor &&
+        b.constructor.name === 'ArrayBuffer' &&
+        b.byteLength >= 0);
+const isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b);
+/**
+ * Internal class representing a pipe to a destination stream.
+ *
+ * @internal
+ */
+class Pipe {
+    src;
+    dest;
+    opts;
+    ondrain;
+    constructor(src, dest, opts) {
+        this.src = src;
+        this.dest = dest;
+        this.opts = opts;
+        this.ondrain = () => src[RESUME]();
+        this.dest.on('drain', this.ondrain);
+    }
+    unpipe() {
+        this.dest.removeListener('drain', this.ondrain);
+    }
+    // only here for the prototype
+    /* c8 ignore start */
+    proxyErrors(_er) { }
+    /* c8 ignore stop */
+    end() {
+        this.unpipe();
+        if (this.opts.end)
+            this.dest.end();
+    }
+}
+/**
+ * Internal class representing a pipe to a destination stream where
+ * errors are proxied.
+ *
+ * @internal
+ */
+class PipeProxyErrors extends Pipe {
+    unpipe() {
+        this.src.removeListener('error', this.proxyErrors);
+        super.unpipe();
+    }
+    constructor(src, dest, opts) {
+        super(src, dest, opts);
+        this.proxyErrors = er => dest.emit('error', er);
+        src.on('error', this.proxyErrors);
+    }
+}
+const isObjectModeOptions = (o) => !!o.objectMode;
+const isEncodingOptions = (o) => !o.objectMode && !!o.encoding && o.encoding !== 'buffer';
+/**
+ * Main export, the Minipass class
+ *
+ * `RType` is the type of data emitted, defaults to Buffer
+ *
+ * `WType` is the type of data to be written, if RType is buffer or string,
+ * then any {@link Minipass.ContiguousData} is allowed.
+ *
+ * `Events` is the set of event handler signatures that this object
+ * will emit, see {@link Minipass.Events}
+ */
+export class Minipass extends EventEmitter {
+    [FLOWING] = false;
+    [PAUSED] = false;
+    [PIPES] = [];
+    [BUFFER] = [];
+    [OBJECTMODE];
+    [ENCODING];
+    [ASYNC];
+    [DECODER];
+    [EOF] = false;
+    [EMITTED_END] = false;
+    [EMITTING_END] = false;
+    [CLOSED] = false;
+    [EMITTED_ERROR] = null;
+    [BUFFERLENGTH] = 0;
+    [DESTROYED] = false;
+    [SIGNAL];
+    [ABORTED] = false;
+    [DATALISTENERS] = 0;
+    [DISCARDED] = false;
+    /**
+     * true if the stream can be written
+     */
+    writable = true;
+    /**
+     * true if the stream can be read
+     */
+    readable = true;
+    /**
+     * If `RType` is Buffer, then options do not need to be provided.
+     * Otherwise, an options object must be provided to specify either
+     * {@link Minipass.SharedOptions.objectMode} or
+     * {@link Minipass.SharedOptions.encoding}, as appropriate.
+     */
+    constructor(...args) {
+        const options = (args[0] ||
+            {});
+        super();
+        if (options.objectMode && typeof options.encoding === 'string') {
+            throw new TypeError('Encoding and objectMode may not be used together');
+        }
+        if (isObjectModeOptions(options)) {
+            this[OBJECTMODE] = true;
+            this[ENCODING] = null;
+        }
+        else if (isEncodingOptions(options)) {
+            this[ENCODING] = options.encoding;
+            this[OBJECTMODE] = false;
+        }
+        else {
+            this[OBJECTMODE] = false;
+            this[ENCODING] = null;
+        }
+        this[ASYNC] = !!options.async;
+        this[DECODER] = this[ENCODING]
+            ? new StringDecoder(this[ENCODING])
+            : null;
+        //@ts-ignore - private option for debugging and testing
+        if (options && options.debugExposeBuffer === true) {
+            Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] });
+        }
+        //@ts-ignore - private option for debugging and testing
+        if (options && options.debugExposePipes === true) {
+            Object.defineProperty(this, 'pipes', { get: () => this[PIPES] });
+        }
+        const { signal } = options;
+        if (signal) {
+            this[SIGNAL] = signal;
+            if (signal.aborted) {
+                this[ABORT]();
+            }
+            else {
+                signal.addEventListener('abort', () => this[ABORT]());
+            }
+        }
+    }
+    /**
+     * The amount of data stored in the buffer waiting to be read.
+     *
+     * For Buffer strings, this will be the total byte length.
+     * For string encoding streams, this will be the string character length,
+     * according to JavaScript's `string.length` logic.
+     * For objectMode streams, this is a count of the items waiting to be
+     * emitted.
+     */
+    get bufferLength() {
+        return this[BUFFERLENGTH];
+    }
+    /**
+     * The `BufferEncoding` currently in use, or `null`
+     */
+    get encoding() {
+        return this[ENCODING];
+    }
+    /**
+     * @deprecated - This is a read only property
+     */
+    set encoding(_enc) {
+        throw new Error('Encoding must be set at instantiation time');
+    }
+    /**
+     * @deprecated - Encoding may only be set at instantiation time
+     */
+    setEncoding(_enc) {
+        throw new Error('Encoding must be set at instantiation time');
+    }
+    /**
+     * True if this is an objectMode stream
+     */
+    get objectMode() {
+        return this[OBJECTMODE];
+    }
+    /**
+     * @deprecated - This is a read-only property
+     */
+    set objectMode(_om) {
+        throw new Error('objectMode must be set at instantiation time');
+    }
+    /**
+     * true if this is an async stream
+     */
+    get ['async']() {
+        return this[ASYNC];
+    }
+    /**
+     * Set to true to make this stream async.
+     *
+     * Once set, it cannot be unset, as this would potentially cause incorrect
+     * behavior.  Ie, a sync stream can be made async, but an async stream
+     * cannot be safely made sync.
+     */
+    set ['async'](a) {
+        this[ASYNC] = this[ASYNC] || !!a;
+    }
+    // drop everything and get out of the flow completely
+    [ABORT]() {
+        this[ABORTED] = true;
+        this.emit('abort', this[SIGNAL]?.reason);
+        this.destroy(this[SIGNAL]?.reason);
+    }
+    /**
+     * True if the stream has been aborted.
+     */
+    get aborted() {
+        return this[ABORTED];
+    }
+    /**
+     * No-op setter. Stream aborted status is set via the AbortSignal provided
+     * in the constructor options.
+     */
+    set aborted(_) { }
+    write(chunk, encoding, cb) {
+        if (this[ABORTED])
+            return false;
+        if (this[EOF])
+            throw new Error('write after end');
+        if (this[DESTROYED]) {
+            this.emit('error', Object.assign(new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' }));
+            return true;
+        }
+        if (typeof encoding === 'function') {
+            cb = encoding;
+            encoding = 'utf8';
+        }
+        if (!encoding)
+            encoding = 'utf8';
+        const fn = this[ASYNC] ? defer : nodefer;
+        // convert array buffers and typed array views into buffers
+        // at some point in the future, we may want to do the opposite!
+        // leave strings and buffers as-is
+        // anything is only allowed if in object mode, so throw
+        if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
+            if (isArrayBufferView(chunk)) {
+                //@ts-ignore - sinful unsafe type changing
+                chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
+            }
+            else if (isArrayBufferLike(chunk)) {
+                //@ts-ignore - sinful unsafe type changing
+                chunk = Buffer.from(chunk);
+            }
+            else if (typeof chunk !== 'string') {
+                throw new Error('Non-contiguous data written to non-objectMode stream');
+            }
+        }
+        // handle object mode up front, since it's simpler
+        // this yields better performance, fewer checks later.
+        if (this[OBJECTMODE]) {
+            // maybe impossible?
+            /* c8 ignore start */
+            if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
+                this[FLUSH](true);
+            /* c8 ignore stop */
+            if (this[FLOWING])
+                this.emit('data', chunk);
+            else
+                this[BUFFERPUSH](chunk);
+            if (this[BUFFERLENGTH] !== 0)
+                this.emit('readable');
+            if (cb)
+                fn(cb);
+            return this[FLOWING];
+        }
+        // at this point the chunk is a buffer or string
+        // don't buffer it up or send it to the decoder
+        if (!chunk.length) {
+            if (this[BUFFERLENGTH] !== 0)
+                this.emit('readable');
+            if (cb)
+                fn(cb);
+            return this[FLOWING];
+        }
+        // fast-path writing strings of same encoding to a stream with
+        // an empty buffer, skipping the buffer/decoder dance
+        if (typeof chunk === 'string' &&
+            // unless it is a string already ready for us to use
+            !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)) {
+            //@ts-ignore - sinful unsafe type change
+            chunk = Buffer.from(chunk, encoding);
+        }
+        if (Buffer.isBuffer(chunk) && this[ENCODING]) {
+            //@ts-ignore - sinful unsafe type change
+            chunk = this[DECODER].write(chunk);
+        }
+        // Note: flushing CAN potentially switch us into not-flowing mode
+        if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
+            this[FLUSH](true);
+        if (this[FLOWING])
+            this.emit('data', chunk);
+        else
+            this[BUFFERPUSH](chunk);
+        if (this[BUFFERLENGTH] !== 0)
+            this.emit('readable');
+        if (cb)
+            fn(cb);
+        return this[FLOWING];
+    }
+    /**
+     * Low-level explicit read method.
+     *
+     * In objectMode, the argument is ignored, and one item is returned if
+     * available.
+     *
+     * `n` is the number of bytes (or in the case of encoding streams,
+     * characters) to consume. If `n` is not provided, then the entire buffer
+     * is returned, or `null` is returned if no data is available.
+     *
+     * If `n` is greater that the amount of data in the internal buffer,
+     * then `null` is returned.
+     */
+    read(n) {
+        if (this[DESTROYED])
+            return null;
+        this[DISCARDED] = false;
+        if (this[BUFFERLENGTH] === 0 ||
+            n === 0 ||
+            (n && n > this[BUFFERLENGTH])) {
+            this[MAYBE_EMIT_END]();
+            return null;
+        }
+        if (this[OBJECTMODE])
+            n = null;
+        if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {
+            // not object mode, so if we have an encoding, then RType is string
+            // otherwise, must be Buffer
+            this[BUFFER] = [
+                (this[ENCODING]
+                    ? this[BUFFER].join('')
+                    : Buffer.concat(this[BUFFER], this[BUFFERLENGTH])),
+            ];
+        }
+        const ret = this[READ](n || null, this[BUFFER][0]);
+        this[MAYBE_EMIT_END]();
+        return ret;
+    }
+    [READ](n, chunk) {
+        if (this[OBJECTMODE])
+            this[BUFFERSHIFT]();
+        else {
+            const c = chunk;
+            if (n === c.length || n === null)
+                this[BUFFERSHIFT]();
+            else if (typeof c === 'string') {
+                this[BUFFER][0] = c.slice(n);
+                chunk = c.slice(0, n);
+                this[BUFFERLENGTH] -= n;
+            }
+            else {
+                this[BUFFER][0] = c.subarray(n);
+                chunk = c.subarray(0, n);
+                this[BUFFERLENGTH] -= n;
+            }
+        }
+        this.emit('data', chunk);
+        if (!this[BUFFER].length && !this[EOF])
+            this.emit('drain');
+        return chunk;
+    }
+    end(chunk, encoding, cb) {
+        if (typeof chunk === 'function') {
+            cb = chunk;
+            chunk = undefined;
+        }
+        if (typeof encoding === 'function') {
+            cb = encoding;
+            encoding = 'utf8';
+        }
+        if (chunk !== undefined)
+            this.write(chunk, encoding);
+        if (cb)
+            this.once('end', cb);
+        this[EOF] = true;
+        this.writable = false;
+        // if we haven't written anything, then go ahead and emit,
+        // even if we're not reading.
+        // we'll re-emit if a new 'end' listener is added anyway.
+        // This makes MP more suitable to write-only use cases.
+        if (this[FLOWING] || !this[PAUSED])
+            this[MAYBE_EMIT_END]();
+        return this;
+    }
+    // don't let the internal resume be overwritten
+    [RESUME]() {
+        if (this[DESTROYED])
+            return;
+        if (!this[DATALISTENERS] && !this[PIPES].length) {
+            this[DISCARDED] = true;
+        }
+        this[PAUSED] = false;
+        this[FLOWING] = true;
+        this.emit('resume');
+        if (this[BUFFER].length)
+            this[FLUSH]();
+        else if (this[EOF])
+            this[MAYBE_EMIT_END]();
+        else
+            this.emit('drain');
+    }
+    /**
+     * Resume the stream if it is currently in a paused state
+     *
+     * If called when there are no pipe destinations or `data` event listeners,
+     * this will place the stream in a "discarded" state, where all data will
+     * be thrown away. The discarded state is removed if a pipe destination or
+     * data handler is added, if pause() is called, or if any synchronous or
+     * asynchronous iteration is started.
+     */
+    resume() {
+        return this[RESUME]();
+    }
+    /**
+     * Pause the stream
+     */
+    pause() {
+        this[FLOWING] = false;
+        this[PAUSED] = true;
+        this[DISCARDED] = false;
+    }
+    /**
+     * true if the stream has been forcibly destroyed
+     */
+    get destroyed() {
+        return this[DESTROYED];
+    }
+    /**
+     * true if the stream is currently in a flowing state, meaning that
+     * any writes will be immediately emitted.
+     */
+    get flowing() {
+        return this[FLOWING];
+    }
+    /**
+     * true if the stream is currently in a paused state
+     */
+    get paused() {
+        return this[PAUSED];
+    }
+    [BUFFERPUSH](chunk) {
+        if (this[OBJECTMODE])
+            this[BUFFERLENGTH] += 1;
+        else
+            this[BUFFERLENGTH] += chunk.length;
+        this[BUFFER].push(chunk);
+    }
+    [BUFFERSHIFT]() {
+        if (this[OBJECTMODE])
+            this[BUFFERLENGTH] -= 1;
+        else
+            this[BUFFERLENGTH] -= this[BUFFER][0].length;
+        return this[BUFFER].shift();
+    }
+    [FLUSH](noDrain = false) {
+        do { } while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&
+            this[BUFFER].length);
+        if (!noDrain && !this[BUFFER].length && !this[EOF])
+            this.emit('drain');
+    }
+    [FLUSHCHUNK](chunk) {
+        this.emit('data', chunk);
+        return this[FLOWING];
+    }
+    /**
+     * Pipe all data emitted by this stream into the destination provided.
+     *
+     * Triggers the flow of data.
+     */
+    pipe(dest, opts) {
+        if (this[DESTROYED])
+            return dest;
+        this[DISCARDED] = false;
+        const ended = this[EMITTED_END];
+        opts = opts || {};
+        if (dest === proc.stdout || dest === proc.stderr)
+            opts.end = false;
+        else
+            opts.end = opts.end !== false;
+        opts.proxyErrors = !!opts.proxyErrors;
+        // piping an ended stream ends immediately
+        if (ended) {
+            if (opts.end)
+                dest.end();
+        }
+        else {
+            // "as" here just ignores the WType, which pipes don't care about,
+            // since they're only consuming from us, and writing to the dest
+            this[PIPES].push(!opts.proxyErrors
+                ? new Pipe(this, dest, opts)
+                : new PipeProxyErrors(this, dest, opts));
+            if (this[ASYNC])
+                defer(() => this[RESUME]());
+            else
+                this[RESUME]();
+        }
+        return dest;
+    }
+    /**
+     * Fully unhook a piped destination stream.
+     *
+     * If the destination stream was the only consumer of this stream (ie,
+     * there are no other piped destinations or `'data'` event listeners)
+     * then the flow of data will stop until there is another consumer or
+     * {@link Minipass#resume} is explicitly called.
+     */
+    unpipe(dest) {
+        const p = this[PIPES].find(p => p.dest === dest);
+        if (p) {
+            if (this[PIPES].length === 1) {
+                if (this[FLOWING] && this[DATALISTENERS] === 0) {
+                    this[FLOWING] = false;
+                }
+                this[PIPES] = [];
+            }
+            else
+                this[PIPES].splice(this[PIPES].indexOf(p), 1);
+            p.unpipe();
+        }
+    }
+    /**
+     * Alias for {@link Minipass#on}
+     */
+    addListener(ev, handler) {
+        return this.on(ev, handler);
+    }
+    /**
+     * Mostly identical to `EventEmitter.on`, with the following
+     * behavior differences to prevent data loss and unnecessary hangs:
+     *
+     * - Adding a 'data' event handler will trigger the flow of data
+     *
+     * - Adding a 'readable' event handler when there is data waiting to be read
+     *   will cause 'readable' to be emitted immediately.
+     *
+     * - Adding an 'endish' event handler ('end', 'finish', etc.) which has
+     *   already passed will cause the event to be emitted immediately and all
+     *   handlers removed.
+     *
+     * - Adding an 'error' event handler after an error has been emitted will
+     *   cause the event to be re-emitted immediately with the error previously
+     *   raised.
+     */
+    on(ev, handler) {
+        const ret = super.on(ev, handler);
+        if (ev === 'data') {
+            this[DISCARDED] = false;
+            this[DATALISTENERS]++;
+            if (!this[PIPES].length && !this[FLOWING]) {
+                this[RESUME]();
+            }
+        }
+        else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {
+            super.emit('readable');
+        }
+        else if (isEndish(ev) && this[EMITTED_END]) {
+            super.emit(ev);
+            this.removeAllListeners(ev);
+        }
+        else if (ev === 'error' && this[EMITTED_ERROR]) {
+            const h = handler;
+            if (this[ASYNC])
+                defer(() => h.call(this, this[EMITTED_ERROR]));
+            else
+                h.call(this, this[EMITTED_ERROR]);
+        }
+        return ret;
+    }
+    /**
+     * Alias for {@link Minipass#off}
+     */
+    removeListener(ev, handler) {
+        return this.off(ev, handler);
+    }
+    /**
+     * Mostly identical to `EventEmitter.off`
+     *
+     * If a 'data' event handler is removed, and it was the last consumer
+     * (ie, there are no pipe destinations or other 'data' event listeners),
+     * then the flow of data will stop until there is another consumer or
+     * {@link Minipass#resume} is explicitly called.
+     */
+    off(ev, handler) {
+        const ret = super.off(ev, handler);
+        // if we previously had listeners, and now we don't, and we don't
+        // have any pipes, then stop the flow, unless it's been explicitly
+        // put in a discarded flowing state via stream.resume().
+        if (ev === 'data') {
+            this[DATALISTENERS] = this.listeners('data').length;
+            if (this[DATALISTENERS] === 0 &&
+                !this[DISCARDED] &&
+                !this[PIPES].length) {
+                this[FLOWING] = false;
+            }
+        }
+        return ret;
+    }
+    /**
+     * Mostly identical to `EventEmitter.removeAllListeners`
+     *
+     * If all 'data' event handlers are removed, and they were the last consumer
+     * (ie, there are no pipe destinations), then the flow of data will stop
+     * until there is another consumer or {@link Minipass#resume} is explicitly
+     * called.
+     */
+    removeAllListeners(ev) {
+        const ret = super.removeAllListeners(ev);
+        if (ev === 'data' || ev === undefined) {
+            this[DATALISTENERS] = 0;
+            if (!this[DISCARDED] && !this[PIPES].length) {
+                this[FLOWING] = false;
+            }
+        }
+        return ret;
+    }
+    /**
+     * true if the 'end' event has been emitted
+     */
+    get emittedEnd() {
+        return this[EMITTED_END];
+    }
+    [MAYBE_EMIT_END]() {
+        if (!this[EMITTING_END] &&
+            !this[EMITTED_END] &&
+            !this[DESTROYED] &&
+            this[BUFFER].length === 0 &&
+            this[EOF]) {
+            this[EMITTING_END] = true;
+            this.emit('end');
+            this.emit('prefinish');
+            this.emit('finish');
+            if (this[CLOSED])
+                this.emit('close');
+            this[EMITTING_END] = false;
+        }
+    }
+    /**
+     * Mostly identical to `EventEmitter.emit`, with the following
+     * behavior differences to prevent data loss and unnecessary hangs:
+     *
+     * If the stream has been destroyed, and the event is something other
+     * than 'close' or 'error', then `false` is returned and no handlers
+     * are called.
+     *
+     * If the event is 'end', and has already been emitted, then the event
+     * is ignored. If the stream is in a paused or non-flowing state, then
+     * the event will be deferred until data flow resumes. If the stream is
+     * async, then handlers will be called on the next tick rather than
+     * immediately.
+     *
+     * If the event is 'close', and 'end' has not yet been emitted, then
+     * the event will be deferred until after 'end' is emitted.
+     *
+     * If the event is 'error', and an AbortSignal was provided for the stream,
+     * and there are no listeners, then the event is ignored, matching the
+     * behavior of node core streams in the presense of an AbortSignal.
+     *
+     * If the event is 'finish' or 'prefinish', then all listeners will be
+     * removed after emitting the event, to prevent double-firing.
+     */
+    emit(ev, ...args) {
+        const data = args[0];
+        // error and close are only events allowed after calling destroy()
+        if (ev !== 'error' &&
+            ev !== 'close' &&
+            ev !== DESTROYED &&
+            this[DESTROYED]) {
+            return false;
+        }
+        else if (ev === 'data') {
+            return !this[OBJECTMODE] && !data
+                ? false
+                : this[ASYNC]
+                    ? (defer(() => this[EMITDATA](data)), true)
+                    : this[EMITDATA](data);
+        }
+        else if (ev === 'end') {
+            return this[EMITEND]();
+        }
+        else if (ev === 'close') {
+            this[CLOSED] = true;
+            // don't emit close before 'end' and 'finish'
+            if (!this[EMITTED_END] && !this[DESTROYED])
+                return false;
+            const ret = super.emit('close');
+            this.removeAllListeners('close');
+            return ret;
+        }
+        else if (ev === 'error') {
+            this[EMITTED_ERROR] = data;
+            super.emit(ERROR, data);
+            const ret = !this[SIGNAL] || this.listeners('error').length
+                ? super.emit('error', data)
+                : false;
+            this[MAYBE_EMIT_END]();
+            return ret;
+        }
+        else if (ev === 'resume') {
+            const ret = super.emit('resume');
+            this[MAYBE_EMIT_END]();
+            return ret;
+        }
+        else if (ev === 'finish' || ev === 'prefinish') {
+            const ret = super.emit(ev);
+            this.removeAllListeners(ev);
+            return ret;
+        }
+        // Some other unknown event
+        const ret = super.emit(ev, ...args);
+        this[MAYBE_EMIT_END]();
+        return ret;
+    }
+    [EMITDATA](data) {
+        for (const p of this[PIPES]) {
+            if (p.dest.write(data) === false)
+                this.pause();
+        }
+        const ret = this[DISCARDED] ? false : super.emit('data', data);
+        this[MAYBE_EMIT_END]();
+        return ret;
+    }
+    [EMITEND]() {
+        if (this[EMITTED_END])
+            return false;
+        this[EMITTED_END] = true;
+        this.readable = false;
+        return this[ASYNC]
+            ? (defer(() => this[EMITEND2]()), true)
+            : this[EMITEND2]();
+    }
+    [EMITEND2]() {
+        if (this[DECODER]) {
+            const data = this[DECODER].end();
+            if (data) {
+                for (const p of this[PIPES]) {
+                    p.dest.write(data);
+                }
+                if (!this[DISCARDED])
+                    super.emit('data', data);
+            }
+        }
+        for (const p of this[PIPES]) {
+            p.end();
+        }
+        const ret = super.emit('end');
+        this.removeAllListeners('end');
+        return ret;
+    }
+    /**
+     * Return a Promise that resolves to an array of all emitted data once
+     * the stream ends.
+     */
+    async collect() {
+        const buf = Object.assign([], {
+            dataLength: 0,
+        });
+        if (!this[OBJECTMODE])
+            buf.dataLength = 0;
+        // set the promise first, in case an error is raised
+        // by triggering the flow here.
+        const p = this.promise();
+        this.on('data', c => {
+            buf.push(c);
+            if (!this[OBJECTMODE])
+                buf.dataLength += c.length;
+        });
+        await p;
+        return buf;
+    }
+    /**
+     * Return a Promise that resolves to the concatenation of all emitted data
+     * once the stream ends.
+     *
+     * Not allowed on objectMode streams.
+     */
+    async concat() {
+        if (this[OBJECTMODE]) {
+            throw new Error('cannot concat in objectMode');
+        }
+        const buf = await this.collect();
+        return (this[ENCODING]
+            ? buf.join('')
+            : Buffer.concat(buf, buf.dataLength));
+    }
+    /**
+     * Return a void Promise that resolves once the stream ends.
+     */
+    async promise() {
+        return new Promise((resolve, reject) => {
+            this.on(DESTROYED, () => reject(new Error('stream destroyed')));
+            this.on('error', er => reject(er));
+            this.on('end', () => resolve());
+        });
+    }
+    /**
+     * Asynchronous `for await of` iteration.
+     *
+     * This will continue emitting all chunks until the stream terminates.
+     */
+    [Symbol.asyncIterator]() {
+        // set this up front, in case the consumer doesn't call next()
+        // right away.
+        this[DISCARDED] = false;
+        let stopped = false;
+        const stop = async () => {
+            this.pause();
+            stopped = true;
+            return { value: undefined, done: true };
+        };
+        const next = () => {
+            if (stopped)
+                return stop();
+            const res = this.read();
+            if (res !== null)
+                return Promise.resolve({ done: false, value: res });
+            if (this[EOF])
+                return stop();
+            let resolve;
+            let reject;
+            const onerr = (er) => {
+                this.off('data', ondata);
+                this.off('end', onend);
+                this.off(DESTROYED, ondestroy);
+                stop();
+                reject(er);
+            };
+            const ondata = (value) => {
+                this.off('error', onerr);
+                this.off('end', onend);
+                this.off(DESTROYED, ondestroy);
+                this.pause();
+                resolve({ value, done: !!this[EOF] });
+            };
+            const onend = () => {
+                this.off('error', onerr);
+                this.off('data', ondata);
+                this.off(DESTROYED, ondestroy);
+                stop();
+                resolve({ done: true, value: undefined });
+            };
+            const ondestroy = () => onerr(new Error('stream destroyed'));
+            return new Promise((res, rej) => {
+                reject = rej;
+                resolve = res;
+                this.once(DESTROYED, ondestroy);
+                this.once('error', onerr);
+                this.once('end', onend);
+                this.once('data', ondata);
+            });
+        };
+        return {
+            next,
+            throw: stop,
+            return: stop,
+            [Symbol.asyncIterator]() {
+                return this;
+            },
+        };
+    }
+    /**
+     * Synchronous `for of` iteration.
+     *
+     * The iteration will terminate when the internal buffer runs out, even
+     * if the stream has not yet terminated.
+     */
+    [Symbol.iterator]() {
+        // set this up front, in case the consumer doesn't call next()
+        // right away.
+        this[DISCARDED] = false;
+        let stopped = false;
+        const stop = () => {
+            this.pause();
+            this.off(ERROR, stop);
+            this.off(DESTROYED, stop);
+            this.off('end', stop);
+            stopped = true;
+            return { done: true, value: undefined };
+        };
+        const next = () => {
+            if (stopped)
+                return stop();
+            const value = this.read();
+            return value === null ? stop() : { done: false, value };
+        };
+        this.once('end', stop);
+        this.once(ERROR, stop);
+        this.once(DESTROYED, stop);
+        return {
+            next,
+            throw: stop,
+            return: stop,
+            [Symbol.iterator]() {
+                return this;
+            },
+        };
+    }
+    /**
+     * Destroy a stream, preventing it from being used for any further purpose.
+     *
+     * If the stream has a `close()` method, then it will be called on
+     * destruction.
+     *
+     * After destruction, any attempt to write data, read data, or emit most
+     * events will be ignored.
+     *
+     * If an error argument is provided, then it will be emitted in an
+     * 'error' event.
+     */
+    destroy(er) {
+        if (this[DESTROYED]) {
+            if (er)
+                this.emit('error', er);
+            else
+                this.emit(DESTROYED);
+            return this;
+        }
+        this[DESTROYED] = true;
+        this[DISCARDED] = true;
+        // throw away all buffered data, it's never coming out
+        this[BUFFER].length = 0;
+        this[BUFFERLENGTH] = 0;
+        const wc = this;
+        if (typeof wc.close === 'function' && !this[CLOSED])
+            wc.close();
+        if (er)
+            this.emit('error', er);
+        // if no error to emit, still reject pending promises
+        else
+            this.emit(DESTROYED);
+        return this;
+    }
+    /**
+     * Alias for {@link isStream}
+     *
+     * Former export location, maintained for backwards compatibility.
+     *
+     * @deprecated
+     */
+    static get isStream() {
+        return isStream;
+    }
+}
+//# sourceMappingURL=index.js.map
\ No newline at end of file
diff --git a/node_modules/minipass/dist/esm/index.js.map b/node_modules/minipass/dist/esm/index.js.map
new file mode 100644
index 0000000..741425a
--- /dev/null
+++ b/node_modules/minipass/dist/esm/index.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO;IACpC,CAAC,CAAC,OAAO;IACT,CAAC,CAAC;QACE,MAAM,EAAE,IAAI;QACZ,MAAM,EAAE,IAAI;KACb,CAAA;AACP,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC1C,OAAO,MAAM,MAAM,aAAa,CAAA;AAChC,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;YACb,CAAC;SACF,CAAA;IACH,CAAC;IAED;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,EAAY;QAClB,IAAI,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;YACpB,IAAI,EAAE;gBAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC,CAAA;;gBACzB,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;YACzB,OAAO,IAAI,CAAA;QACb,CAAC;QAED,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,CAAA;QACtB,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,CAAA;QAEtB,sDAAsD;QACtD,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,CAAA;QACvB,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,CAAA;QAEtB,MAAM,EAAE,GAAG,IAEV,CAAA;QACD,IAAI,OAAO,EAAE,CAAC,KAAK,KAAK,UAAU,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC;YAAE,EAAE,CAAC,KAAK,EAAE,CAAA;QAE/D,IAAI,EAAE;YAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC,CAAA;QAC9B,qDAAqD;;YAChD,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;QAEzB,OAAO,IAAI,CAAA;IACb,CAAC;IAED;;;;;;OAMG;IACH,MAAM,KAAK,QAAQ;QACjB,OAAO,QAAQ,CAAA;IACjB,CAAC;CACF","sourcesContent":["const proc =\n  typeof process === 'object' && process\n    ? process\n    : {\n        stdout: null,\n        stderr: null,\n      }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node: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 =\n    | ObjectModeOptions\n    | (T extends string\n        ? EncodingOptions\n        : T extends Buffer\n        ? BufferOptions\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:\n      | [Minipass.ObjectModeOptions]\n      | (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  ): this {\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 as RType) === 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"]}
\ No newline at end of file
diff --git a/node_modules/minipass/dist/esm/package.json b/node_modules/minipass/dist/esm/package.json
new file mode 100644
index 0000000..3dbc1ca
--- /dev/null
+++ b/node_modules/minipass/dist/esm/package.json
@@ -0,0 +1,3 @@
+{
+  "type": "module"
+}
diff --git a/node_modules/minipass/package.json b/node_modules/minipass/package.json
new file mode 100644
index 0000000..771969b
--- /dev/null
+++ b/node_modules/minipass/package.json
@@ -0,0 +1,82 @@
+{
+  "name": "minipass",
+  "version": "7.1.2",
+  "description": "minimal implementation of a PassThrough stream",
+  "main": "./dist/commonjs/index.js",
+  "types": "./dist/commonjs/index.d.ts",
+  "type": "module",
+  "tshy": {
+    "selfLink": false,
+    "main": true,
+    "exports": {
+      "./package.json": "./package.json",
+      ".": "./src/index.ts"
+    }
+  },
+  "exports": {
+    "./package.json": "./package.json",
+    ".": {
+      "import": {
+        "types": "./dist/esm/index.d.ts",
+        "default": "./dist/esm/index.js"
+      },
+      "require": {
+        "types": "./dist/commonjs/index.d.ts",
+        "default": "./dist/commonjs/index.js"
+      }
+    }
+  },
+  "files": [
+    "dist"
+  ],
+  "scripts": {
+    "preversion": "npm test",
+    "postversion": "npm publish",
+    "prepublishOnly": "git push origin --follow-tags",
+    "prepare": "tshy",
+    "pretest": "npm run prepare",
+    "presnap": "npm run prepare",
+    "test": "tap",
+    "snap": "tap",
+    "format": "prettier --write . --loglevel warn",
+    "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts"
+  },
+  "prettier": {
+    "semi": false,
+    "printWidth": 75,
+    "tabWidth": 2,
+    "useTabs": false,
+    "singleQuote": true,
+    "jsxSingleQuote": false,
+    "bracketSameLine": true,
+    "arrowParens": "avoid",
+    "endOfLine": "lf"
+  },
+  "devDependencies": {
+    "@types/end-of-stream": "^1.4.2",
+    "@types/node": "^20.1.2",
+    "end-of-stream": "^1.4.0",
+    "node-abort-controller": "^3.1.1",
+    "prettier": "^2.6.2",
+    "tap": "^19.0.0",
+    "through2": "^2.0.3",
+    "tshy": "^1.14.0",
+    "typedoc": "^0.25.1"
+  },
+  "repository": "https://github.com/isaacs/minipass",
+  "keywords": [
+    "passthrough",
+    "stream"
+  ],
+  "author": "Isaac Z. Schlueter  (http://blog.izs.me/)",
+  "license": "ISC",
+  "engines": {
+    "node": ">=16 || 14 >=14.17"
+  },
+  "tap": {
+    "typecheck": true,
+    "include": [
+      "test/*.ts"
+    ]
+  }
+}
diff --git a/node_modules/mz/HISTORY.md b/node_modules/mz/HISTORY.md
new file mode 100644
index 0000000..6ebee21
--- /dev/null
+++ b/node_modules/mz/HISTORY.md
@@ -0,0 +1,66 @@
+
+2.7.0 / 2017-09-13
+==================
+
+  * feat: support fs.copyFile (#58)
+
+2.6.0 / 2016-11-22
+==================
+
+  * Added fdatasync to fs api (#46)
+
+2.5.0 / 2016-11-04
+==================
+
+  * feat: support fs.mkdtemp
+
+2.4.0 / 2016-03-23
+==================
+
+  * add `fs.truncate()` [#34](https://github.com/normalize/mz/pull/34)
+
+2.3.1 / 2016-02-01
+==================
+
+  * update `any-promise@v1`
+
+2.3.0 / 2016-01-30
+==================
+
+  * feat(package): switch to `any-promise` to support more promise engines
+
+2.2.0 / 2016-01-24
+==================
+
+  * feat(package): add index.js to files
+
+2.1.0 / 2015-10-15
+==================
+
+ * support for readline library
+
+2.0.0 / 2015-05-24
+==================
+
+ * support callbacks as well
+
+1.2.0 / 2014-12-16
+==================
+
+ * refactor promisification to `thenify` and `thenify-all`
+
+1.1.0 / 2014-11-14
+==================
+
+ * use `graceful-fs` if available
+
+1.0.1 / 2014-08-18
+==================
+
+ * don't use `bluebird.promisify()` - unnecessarily wraps runtime errors, causing issues
+
+1.0.0 / 2014-06-18
+==================
+
+ * use `bluebird` by default if found
+ * support node 0.8
diff --git a/node_modules/mz/LICENSE b/node_modules/mz/LICENSE
new file mode 100644
index 0000000..1835f3d
--- /dev/null
+++ b/node_modules/mz/LICENSE
@@ -0,0 +1,22 @@
+
+The MIT License (MIT)
+
+Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/node_modules/mz/README.md b/node_modules/mz/README.md
new file mode 100644
index 0000000..50d6557
--- /dev/null
+++ b/node_modules/mz/README.md
@@ -0,0 +1,106 @@
+
+# MZ - Modernize node.js
+
+[![NPM version][npm-image]][npm-url]
+[![Build status][travis-image]][travis-url]
+[![Test coverage][coveralls-image]][coveralls-url]
+[![Dependency Status][david-image]][david-url]
+[![License][license-image]][license-url]
+[![Downloads][downloads-image]][downloads-url]
+
+Modernize node.js to current ECMAScript specifications!
+node.js will not update their API to ES6+ [for a while](https://github.com/joyent/node/issues/7549).
+This library is a wrapper for various aspects of node.js' API.
+
+## Installation and Usage
+
+Set `mz` as a dependency and install it.
+
+```bash
+npm i mz
+```
+
+Then prefix the relevant `require()`s with `mz/`:
+
+```js
+var fs = require('mz/fs')
+
+fs.exists(__filename).then(function (exists) {
+  if (exists) // do something
+})
+```
+
+With ES2017, this will allow you to use async functions cleanly with node's core API:
+
+```js
+const fs = require('mz/fs')
+
+
+async function doSomething () {
+  if (await fs.exists(__filename)) // do something
+}
+```
+
+## Promisification
+
+Many node methods are converted into promises.
+Any properties that are deprecated or aren't asynchronous will simply be proxied.
+The modules wrapped are:
+
+- `child_process`
+- `crypto`
+- `dns`
+- `fs` (uses `graceful-fs` if available)
+- `readline`
+- `zlib`
+
+```js
+var exec = require('mz/child_process').exec
+
+exec('node --version').then(function (stdout) {
+  console.log(stdout)
+})
+```
+
+## Promise Engine
+
+`mz` uses [`any-promise`](https://github.com/kevinbeaty/any-promise).
+
+## FAQ
+
+### Can I use this in production?
+
+Yes, Node 4.x ships with stable promises support. For older engines,
+you should probably install your own promise implementation and register it with
+`require('any-promise/register')('bluebird')`.
+
+### Will this make my app faster?
+
+Nope, probably slower actually.
+
+### Can I add more features?
+
+Sure.
+Open an issue.
+
+Currently, the plans are to eventually support:
+
+- New APIs in node.js that are not available in older versions of node
+- ECMAScript7 Streams
+
+[bluebird]: https://github.com/petkaantonov/bluebird
+
+[npm-image]: https://img.shields.io/npm/v/mz.svg?style=flat-square
+[npm-url]: https://npmjs.org/package/mz
+[github-tag]: http://img.shields.io/github/tag/normalize/mz.svg?style=flat-square
+[github-url]: https://github.com/normalize/mz/tags
+[travis-image]: https://img.shields.io/travis/normalize/mz.svg?style=flat-square
+[travis-url]: https://travis-ci.org/normalize/mz
+[coveralls-image]: https://img.shields.io/coveralls/normalize/mz.svg?style=flat-square
+[coveralls-url]: https://coveralls.io/r/normalize/mz?branch=master
+[david-image]: http://img.shields.io/david/normalize/mz.svg?style=flat-square
+[david-url]: https://david-dm.org/normalize/mz
+[license-image]: http://img.shields.io/npm/l/mz.svg?style=flat-square
+[license-url]: LICENSE
+[downloads-image]: http://img.shields.io/npm/dm/mz.svg?style=flat-square
+[downloads-url]: https://npmjs.org/package/mz
diff --git a/node_modules/mz/child_process.js b/node_modules/mz/child_process.js
new file mode 100644
index 0000000..06d5d9e
--- /dev/null
+++ b/node_modules/mz/child_process.js
@@ -0,0 +1,8 @@
+
+require('thenify-all').withCallback(
+  require('child_process'),
+  exports, [
+    'exec',
+    'execFile',
+  ]
+)
diff --git a/node_modules/mz/crypto.js b/node_modules/mz/crypto.js
new file mode 100644
index 0000000..d8cff57
--- /dev/null
+++ b/node_modules/mz/crypto.js
@@ -0,0 +1,9 @@
+
+require('thenify-all').withCallback(
+  require('crypto'),
+  exports, [
+    'pbkdf2',
+    'pseudoRandomBytes',
+    'randomBytes'
+  ]
+)
diff --git a/node_modules/mz/dns.js b/node_modules/mz/dns.js
new file mode 100644
index 0000000..c103582
--- /dev/null
+++ b/node_modules/mz/dns.js
@@ -0,0 +1,16 @@
+
+require('thenify-all').withCallback(
+  require('dns'),
+  exports, [
+    'lookup',
+    'resolve',
+    'resolve4',
+    'resolve6',
+    'resolveCname',
+    'resolveMx',
+    'resolveNs',
+    'resolveSrv',
+    'resolveTxt',
+    'reverse'
+  ]
+)
diff --git a/node_modules/mz/fs.js b/node_modules/mz/fs.js
new file mode 100644
index 0000000..1cfd2d7
--- /dev/null
+++ b/node_modules/mz/fs.js
@@ -0,0 +1,62 @@
+
+var Promise = require('any-promise')
+var fs
+try {
+  fs = require('graceful-fs')
+} catch(err) {
+  fs = require('fs')
+}
+
+var api = [
+  'appendFile',
+  'chmod',
+  'chown',
+  'close',
+  'fchmod',
+  'fchown',
+  'fdatasync',
+  'fstat',
+  'fsync',
+  'ftruncate',
+  'futimes',
+  'lchown',
+  'link',
+  'lstat',
+  'mkdir',
+  'open',
+  'read',
+  'readFile',
+  'readdir',
+  'readlink',
+  'realpath',
+  'rename',
+  'rmdir',
+  'stat',
+  'symlink',
+  'truncate',
+  'unlink',
+  'utimes',
+  'write',
+  'writeFile'
+]
+
+typeof fs.access === 'function' && api.push('access')
+typeof fs.copyFile === 'function' && api.push('copyFile')
+typeof fs.mkdtemp === 'function' && api.push('mkdtemp')
+
+require('thenify-all').withCallback(fs, exports, api)
+
+exports.exists = function (filename, callback) {
+  // callback
+  if (typeof callback === 'function') {
+    return fs.stat(filename, function (err) {
+      callback(null, !err);
+    })
+  }
+  // or promise
+  return new Promise(function (resolve) {
+    fs.stat(filename, function (err) {
+      resolve(!err)
+    })
+  })
+}
diff --git a/node_modules/mz/index.js b/node_modules/mz/index.js
new file mode 100644
index 0000000..cef508d
--- /dev/null
+++ b/node_modules/mz/index.js
@@ -0,0 +1,8 @@
+module.exports = {
+  fs: require('./fs'),
+  dns: require('./dns'),
+  zlib: require('./zlib'),
+  crypto: require('./crypto'),
+  readline: require('./readline'),
+  child_process: require('./child_process')
+}
diff --git a/node_modules/mz/package.json b/node_modules/mz/package.json
new file mode 100644
index 0000000..de8d542
--- /dev/null
+++ b/node_modules/mz/package.json
@@ -0,0 +1,44 @@
+{
+  "name": "mz",
+  "description": "modernize node.js to current ECMAScript standards",
+  "version": "2.7.0",
+  "author": {
+    "name": "Jonathan Ong",
+    "email": "me@jongleberry.com",
+    "url": "http://jongleberry.com",
+    "twitter": "https://twitter.com/jongleberry"
+  },
+  "license": "MIT",
+  "repository": "normalize/mz",
+  "dependencies": {
+    "any-promise": "^1.0.0",
+    "object-assign": "^4.0.1",
+    "thenify-all": "^1.0.0"
+  },
+  "devDependencies": {
+    "istanbul": "^0.4.0",
+    "bluebird": "^3.0.0",
+    "mocha": "^3.0.0"
+  },
+  "scripts": {
+    "test": "mocha --reporter spec",
+    "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot",
+    "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot"
+  },
+  "keywords": [
+    "promisify",
+    "promise",
+    "thenify",
+    "then",
+    "es6"
+  ],
+  "files": [
+    "index.js",
+    "child_process.js",
+    "crypto.js",
+    "dns.js",
+    "fs.js",
+    "readline.js",
+    "zlib.js"
+  ]
+}
diff --git a/node_modules/mz/readline.js b/node_modules/mz/readline.js
new file mode 100644
index 0000000..eb70c46
--- /dev/null
+++ b/node_modules/mz/readline.js
@@ -0,0 +1,64 @@
+var readline = require('readline')
+var Promise = require('any-promise')
+var objectAssign = require('object-assign')
+var Interface = readline.Interface
+
+function wrapCompleter (completer) {
+  if (completer.length === 2) return completer
+
+  return function (line, cb) {
+    var result = completer(line)
+
+    if (typeof result.then !== 'function') {
+      return cb(null, result)
+    }
+
+    result.catch(cb).then(function (result) {
+      process.nextTick(function () { cb(null, result) })
+    })
+  }
+}
+
+function InterfaceAsPromised (input, output, completer, terminal) {
+  if (arguments.length === 1) {
+    var options = input
+
+    if (typeof options.completer === 'function') {
+      options = objectAssign({}, options, {
+        completer: wrapCompleter(options.completer)
+      })
+    }
+
+    Interface.call(this, options)
+  } else {
+    if (typeof completer === 'function') {
+      completer = wrapCompleter(completer)
+    }
+
+    Interface.call(this, input, output, completer, terminal)
+  }
+}
+
+InterfaceAsPromised.prototype = Object.create(Interface.prototype)
+
+InterfaceAsPromised.prototype.question = function (question, callback) {
+  if (typeof callback === 'function') {
+    return Interface.prototype.question.call(this, question, callback)
+  }
+
+  var self = this
+  return new Promise(function (resolve) {
+    Interface.prototype.question.call(self, question, resolve)
+  })
+}
+
+objectAssign(exports, readline, {
+  Interface: InterfaceAsPromised,
+  createInterface: function (input, output, completer, terminal) {
+    if (arguments.length === 1) {
+      return new InterfaceAsPromised(input)
+    }
+
+    return new InterfaceAsPromised(input, output, completer, terminal)
+  }
+})
diff --git a/node_modules/mz/zlib.js b/node_modules/mz/zlib.js
new file mode 100644
index 0000000..a05c26a
--- /dev/null
+++ b/node_modules/mz/zlib.js
@@ -0,0 +1,13 @@
+
+require('thenify-all').withCallback(
+  require('zlib'),
+  exports, [
+    'deflate',
+    'deflateRaw',
+    'gzip',
+    'gunzip',
+    'inflate',
+    'inflateRaw',
+    'unzip',
+  ]
+)
diff --git a/node_modules/nanoid/LICENSE b/node_modules/nanoid/LICENSE
new file mode 100644
index 0000000..37f56aa
--- /dev/null
+++ b/node_modules/nanoid/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright 2017 Andrey Sitnik 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/node_modules/nanoid/README.md b/node_modules/nanoid/README.md
new file mode 100644
index 0000000..35abb57
--- /dev/null
+++ b/node_modules/nanoid/README.md
@@ -0,0 +1,39 @@
+# Nano ID
+
+Nano ID logo by Anton Lovchikov
+
+**English** | [Русский](./README.ru.md) | [简体中文](./README.zh-CN.md) | [Bahasa Indonesia](./README.id-ID.md)
+
+A tiny, secure, URL-friendly, unique string ID generator for JavaScript.
+
+> “An amazing level of senseless perfectionism,
+> which is simply impossible not to respect.”
+
+* **Small.** 130 bytes (minified and gzipped). No dependencies.
+  [Size Limit] controls the size.
+* **Fast.** It is 2 times faster than UUID.
+* **Safe.** It uses hardware random generator. Can be used in clusters.
+* **Short IDs.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`).
+  So ID size was reduced from 36 to 21 symbols.
+* **Portable.** Nano ID was ported
+  to [20 programming languages](#other-programming-languages).
+
+```js
+import { nanoid } from 'nanoid'
+model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
+```
+
+Supports modern browsers, IE [with Babel], Node.js and React Native.
+
+[online tool]: https://gitpod.io/#https://github.com/ai/nanoid/
+[with Babel]:  https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/
+[Size Limit]:  https://github.com/ai/size-limit
+
+
+  Sponsored by Evil Martians
+
+
+## Docs
+Read full docs **[here](https://github.com/ai/nanoid#readme)**.
diff --git a/node_modules/nanoid/async/index.browser.cjs b/node_modules/nanoid/async/index.browser.cjs
new file mode 100644
index 0000000..80d1871
--- /dev/null
+++ b/node_modules/nanoid/async/index.browser.cjs
@@ -0,0 +1,69 @@
+let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes))
+
+let customAlphabet = (alphabet, defaultSize = 21) => {
+  // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
+  // values closer to the alphabet size. The bitmask calculates the closest
+  // `2^31 - 1` number, which exceeds the alphabet size.
+  // For example, the bitmask for the alphabet size 30 is 31 (00011111).
+  // `Math.clz32` is not used, because it is not available in browsers.
+  let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
+  // Though, the bitmask solution is not perfect since the bytes exceeding
+  // the alphabet size are refused. Therefore, to reliably generate the ID,
+  // the random bytes redundancy has to be satisfied.
+
+  // Note: every hardware random generator call is performance expensive,
+  // because the system call for entropy collection takes a lot of time.
+  // So, to avoid additional system calls, extra bytes are requested in advance.
+
+  // Next, a step determines how many random bytes to generate.
+  // The number of random bytes gets decided upon the ID size, mask,
+  // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
+  // according to benchmarks).
+
+  // `-~f => Math.ceil(f)` if f is a float
+  // `-~i => i + 1` if i is an integer
+  let step = -~((1.6 * mask * defaultSize) / alphabet.length)
+
+  return async (size = defaultSize) => {
+    let id = ''
+    while (true) {
+      let bytes = crypto.getRandomValues(new Uint8Array(step))
+      // A compact alternative for `for (var i = 0; i < step; i++)`.
+      let i = step | 0
+      while (i--) {
+        // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
+        id += alphabet[bytes[i] & mask] || ''
+        if (id.length === size) return id
+      }
+    }
+  }
+}
+
+let nanoid = async (size = 21) => {
+  let id = ''
+  let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))
+
+  // A compact alternative for `for (var i = 0; i < step; i++)`.
+  while (size--) {
+    // It is incorrect to use bytes exceeding the alphabet size.
+    // The following mask reduces the random byte in the 0-255 value
+    // range to the 0-63 value range. Therefore, adding hacks, such
+    // as empty string fallback or magic numbers, is unneccessary because
+    // the bitmask trims bytes down to the alphabet size.
+    let byte = bytes[size] & 63
+    if (byte < 36) {
+      // `0-9a-z`
+      id += byte.toString(36)
+    } else if (byte < 62) {
+      // `A-Z`
+      id += (byte - 26).toString(36).toUpperCase()
+    } else if (byte < 63) {
+      id += '_'
+    } else {
+      id += '-'
+    }
+  }
+  return id
+}
+
+module.exports = { nanoid, customAlphabet, random }
diff --git a/node_modules/nanoid/async/index.browser.js b/node_modules/nanoid/async/index.browser.js
new file mode 100644
index 0000000..fbaa230
--- /dev/null
+++ b/node_modules/nanoid/async/index.browser.js
@@ -0,0 +1,34 @@
+let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes))
+let customAlphabet = (alphabet, defaultSize = 21) => {
+  let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
+  let step = -~((1.6 * mask * defaultSize) / alphabet.length)
+  return async (size = defaultSize) => {
+    let id = ''
+    while (true) {
+      let bytes = crypto.getRandomValues(new Uint8Array(step))
+      let i = step | 0
+      while (i--) {
+        id += alphabet[bytes[i] & mask] || ''
+        if (id.length === size) return id
+      }
+    }
+  }
+}
+let nanoid = async (size = 21) => {
+  let id = ''
+  let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))
+  while (size--) {
+    let byte = bytes[size] & 63
+    if (byte < 36) {
+      id += byte.toString(36)
+    } else if (byte < 62) {
+      id += (byte - 26).toString(36).toUpperCase()
+    } else if (byte < 63) {
+      id += '_'
+    } else {
+      id += '-'
+    }
+  }
+  return id
+}
+export { nanoid, customAlphabet, random }
diff --git a/node_modules/nanoid/async/index.cjs b/node_modules/nanoid/async/index.cjs
new file mode 100644
index 0000000..f1b0ad0
--- /dev/null
+++ b/node_modules/nanoid/async/index.cjs
@@ -0,0 +1,71 @@
+let crypto = require('crypto')
+
+let { urlAlphabet } = require('../url-alphabet/index.cjs')
+
+// `crypto.randomFill()` is a little faster than `crypto.randomBytes()`,
+// because it is possible to use in combination with `Buffer.allocUnsafe()`.
+let random = bytes =>
+  new Promise((resolve, reject) => {
+    // `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory.
+    // Memory flushing is unnecessary since the buffer allocation itself resets
+    // the memory with the new bytes.
+    crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
+      if (err) {
+        reject(err)
+      } else {
+        resolve(buf)
+      }
+    })
+  })
+
+let customAlphabet = (alphabet, defaultSize = 21) => {
+  // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
+  // values closer to the alphabet size. The bitmask calculates the closest
+  // `2^31 - 1` number, which exceeds the alphabet size.
+  // For example, the bitmask for the alphabet size 30 is 31 (00011111).
+  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
+  // Though, the bitmask solution is not perfect since the bytes exceeding
+  // the alphabet size are refused. Therefore, to reliably generate the ID,
+  // the random bytes redundancy has to be satisfied.
+
+  // Note: every hardware random generator call is performance expensive,
+  // because the system call for entropy collection takes a lot of time.
+  // So, to avoid additional system calls, extra bytes are requested in advance.
+
+  // Next, a step determines how many random bytes to generate.
+  // The number of random bytes gets decided upon the ID size, mask,
+  // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
+  // according to benchmarks).
+  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
+
+  let tick = (id, size = defaultSize) =>
+    random(step).then(bytes => {
+      // A compact alternative for `for (var i = 0; i < step; i++)`.
+      let i = step
+      while (i--) {
+        // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
+        id += alphabet[bytes[i] & mask] || ''
+        if (id.length >= size) return id
+      }
+      return tick(id, size)
+    })
+
+  return size => tick('', size)
+}
+
+let nanoid = (size = 21) =>
+  random((size |= 0)).then(bytes => {
+    let id = ''
+    // A compact alternative for `for (var i = 0; i < step; i++)`.
+    while (size--) {
+      // It is incorrect to use bytes exceeding the alphabet size.
+      // The following mask reduces the random byte in the 0-255 value
+      // range to the 0-63 value range. Therefore, adding hacks, such
+      // as empty string fallback or magic numbers, is unneccessary because
+      // the bitmask trims bytes down to the alphabet size.
+      id += urlAlphabet[bytes[size] & 63]
+    }
+    return id
+  })
+
+module.exports = { nanoid, customAlphabet, random }
diff --git a/node_modules/nanoid/async/index.d.ts b/node_modules/nanoid/async/index.d.ts
new file mode 100644
index 0000000..9e91965
--- /dev/null
+++ b/node_modules/nanoid/async/index.d.ts
@@ -0,0 +1,56 @@
+/**
+ * Generate secure URL-friendly unique ID. The non-blocking version.
+ *
+ * By default, the ID will have 21 symbols to have a collision probability
+ * similar to UUID v4.
+ *
+ * ```js
+ * import { nanoid } from 'nanoid/async'
+ * nanoid().then(id => {
+ *   model.id = id
+ * })
+ * ```
+ *
+ * @param size Size of the ID. The default size is 21.
+ * @returns A promise with a random string.
+ */
+export function nanoid(size?: number): Promise
+
+/**
+ * A low-level function.
+ * Generate secure unique ID with custom alphabet. The non-blocking version.
+ *
+ * Alphabet must contain 256 symbols or less. Otherwise, the generator
+ * will not be secure.
+ *
+ * @param alphabet Alphabet used to generate the ID.
+ * @param defaultSize Size of the ID. The default size is 21.
+ * @returns A function that returns a promise with a random string.
+ *
+ * ```js
+ * import { customAlphabet } from 'nanoid/async'
+ * const nanoid = customAlphabet('0123456789абвгдеё', 5)
+ * nanoid().then(id => {
+ *   model.id = id //=> "8ё56а"
+ * })
+ * ```
+ */
+export function customAlphabet(
+  alphabet: string,
+  defaultSize?: number
+): (size?: number) => Promise
+
+/**
+ * Generate an array of random bytes collected from hardware noise.
+ *
+ * ```js
+ * import { random } from 'nanoid/async'
+ * random(5).then(bytes => {
+ *   bytes //=> [10, 67, 212, 67, 89]
+ * })
+ * ```
+ *
+ * @param bytes Size of the array.
+ * @returns A promise with a random bytes array.
+ */
+export function random(bytes: number): Promise
diff --git a/node_modules/nanoid/async/index.js b/node_modules/nanoid/async/index.js
new file mode 100644
index 0000000..cec454a
--- /dev/null
+++ b/node_modules/nanoid/async/index.js
@@ -0,0 +1,35 @@
+import crypto from 'crypto'
+import { urlAlphabet } from '../url-alphabet/index.js'
+let random = bytes =>
+  new Promise((resolve, reject) => {
+    crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
+      if (err) {
+        reject(err)
+      } else {
+        resolve(buf)
+      }
+    })
+  })
+let customAlphabet = (alphabet, defaultSize = 21) => {
+  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
+  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
+  let tick = (id, size = defaultSize) =>
+    random(step).then(bytes => {
+      let i = step
+      while (i--) {
+        id += alphabet[bytes[i] & mask] || ''
+        if (id.length >= size) return id
+      }
+      return tick(id, size)
+    })
+  return size => tick('', size)
+}
+let nanoid = (size = 21) =>
+  random((size |= 0)).then(bytes => {
+    let id = ''
+    while (size--) {
+      id += urlAlphabet[bytes[size] & 63]
+    }
+    return id
+  })
+export { nanoid, customAlphabet, random }
diff --git a/node_modules/nanoid/async/index.native.js b/node_modules/nanoid/async/index.native.js
new file mode 100644
index 0000000..7c1d6f3
--- /dev/null
+++ b/node_modules/nanoid/async/index.native.js
@@ -0,0 +1,26 @@
+import { getRandomBytesAsync } from 'expo-random'
+import { urlAlphabet } from '../url-alphabet/index.js'
+let random = getRandomBytesAsync
+let customAlphabet = (alphabet, defaultSize = 21) => {
+  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
+  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
+  let tick = (id, size = defaultSize) =>
+    random(step).then(bytes => {
+      let i = step
+      while (i--) {
+        id += alphabet[bytes[i] & mask] || ''
+        if (id.length >= size) return id
+      }
+      return tick(id, size)
+    })
+  return size => tick('', size)
+}
+let nanoid = (size = 21) =>
+  random((size |= 0)).then(bytes => {
+    let id = ''
+    while (size--) {
+      id += urlAlphabet[bytes[size] & 63]
+    }
+    return id
+  })
+export { nanoid, customAlphabet, random }
diff --git a/node_modules/nanoid/async/package.json b/node_modules/nanoid/async/package.json
new file mode 100644
index 0000000..578cdb4
--- /dev/null
+++ b/node_modules/nanoid/async/package.json
@@ -0,0 +1,12 @@
+{
+  "type": "module",
+  "main": "index.cjs",
+  "module": "index.js",
+  "react-native": {
+    "./index.js": "./index.native.js"
+  },
+  "browser": {
+    "./index.js": "./index.browser.js",
+    "./index.cjs": "./index.browser.cjs"
+  }
+}
\ No newline at end of file
diff --git a/node_modules/nanoid/bin/nanoid.cjs b/node_modules/nanoid/bin/nanoid.cjs
new file mode 100644
index 0000000..c76db0f
--- /dev/null
+++ b/node_modules/nanoid/bin/nanoid.cjs
@@ -0,0 +1,55 @@
+#!/usr/bin/env node
+
+let { nanoid, customAlphabet } = require('..')
+
+function print(msg) {
+  process.stdout.write(msg + '\n')
+}
+
+function error(msg) {
+  process.stderr.write(msg + '\n')
+  process.exit(1)
+}
+
+if (process.argv.includes('--help') || process.argv.includes('-h')) {
+  print(`
+  Usage
+    $ nanoid [options]
+
+  Options
+    -s, --size       Generated ID size
+    -a, --alphabet   Alphabet to use
+    -h, --help       Show this help
+
+  Examples
+    $ nanoid --s 15
+    S9sBF77U6sDB8Yg
+
+    $ nanoid --size 10 --alphabet abc
+    bcabababca`)
+  process.exit()
+}
+
+let alphabet, size
+for (let i = 2; i < process.argv.length; i++) {
+  let arg = process.argv[i]
+  if (arg === '--size' || arg === '-s') {
+    size = Number(process.argv[i + 1])
+    i += 1
+    if (Number.isNaN(size) || size <= 0) {
+      error('Size must be positive integer')
+    }
+  } else if (arg === '--alphabet' || arg === '-a') {
+    alphabet = process.argv[i + 1]
+    i += 1
+  } else {
+    error('Unknown argument ' + arg)
+  }
+}
+
+if (alphabet) {
+  let customNanoid = customAlphabet(alphabet, size)
+  print(customNanoid())
+} else {
+  print(nanoid(size))
+}
diff --git a/node_modules/nanoid/index.browser.cjs b/node_modules/nanoid/index.browser.cjs
new file mode 100644
index 0000000..d21a91f
--- /dev/null
+++ b/node_modules/nanoid/index.browser.cjs
@@ -0,0 +1,72 @@
+// This file replaces `index.js` in bundlers like webpack or Rollup,
+// according to `browser` config in `package.json`.
+
+let { urlAlphabet } = require('./url-alphabet/index.cjs')
+
+let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
+
+let customRandom = (alphabet, defaultSize, getRandom) => {
+  // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
+  // values closer to the alphabet size. The bitmask calculates the closest
+  // `2^31 - 1` number, which exceeds the alphabet size.
+  // For example, the bitmask for the alphabet size 30 is 31 (00011111).
+  // `Math.clz32` is not used, because it is not available in browsers.
+  let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
+  // Though, the bitmask solution is not perfect since the bytes exceeding
+  // the alphabet size are refused. Therefore, to reliably generate the ID,
+  // the random bytes redundancy has to be satisfied.
+
+  // Note: every hardware random generator call is performance expensive,
+  // because the system call for entropy collection takes a lot of time.
+  // So, to avoid additional system calls, extra bytes are requested in advance.
+
+  // Next, a step determines how many random bytes to generate.
+  // The number of random bytes gets decided upon the ID size, mask,
+  // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
+  // according to benchmarks).
+
+  // `-~f => Math.ceil(f)` if f is a float
+  // `-~i => i + 1` if i is an integer
+  let step = -~((1.6 * mask * defaultSize) / alphabet.length)
+
+  return (size = defaultSize) => {
+    let id = ''
+    while (true) {
+      let bytes = getRandom(step)
+      // A compact alternative for `for (var i = 0; i < step; i++)`.
+      let j = step | 0
+      while (j--) {
+        // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
+        id += alphabet[bytes[j] & mask] || ''
+        if (id.length === size) return id
+      }
+    }
+  }
+}
+
+let customAlphabet = (alphabet, size = 21) =>
+  customRandom(alphabet, size, random)
+
+let nanoid = (size = 21) =>
+  crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
+    // It is incorrect to use bytes exceeding the alphabet size.
+    // The following mask reduces the random byte in the 0-255 value
+    // range to the 0-63 value range. Therefore, adding hacks, such
+    // as empty string fallback or magic numbers, is unneccessary because
+    // the bitmask trims bytes down to the alphabet size.
+    byte &= 63
+    if (byte < 36) {
+      // `0-9a-z`
+      id += byte.toString(36)
+    } else if (byte < 62) {
+      // `A-Z`
+      id += (byte - 26).toString(36).toUpperCase()
+    } else if (byte > 62) {
+      id += '-'
+    } else {
+      id += '_'
+    }
+    return id
+  }, '')
+
+module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
diff --git a/node_modules/nanoid/index.browser.js b/node_modules/nanoid/index.browser.js
new file mode 100644
index 0000000..7d3b876
--- /dev/null
+++ b/node_modules/nanoid/index.browser.js
@@ -0,0 +1,34 @@
+import { urlAlphabet } from './url-alphabet/index.js'
+let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
+let customRandom = (alphabet, defaultSize, getRandom) => {
+  let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
+  let step = -~((1.6 * mask * defaultSize) / alphabet.length)
+  return (size = defaultSize) => {
+    let id = ''
+    while (true) {
+      let bytes = getRandom(step)
+      let j = step | 0
+      while (j--) {
+        id += alphabet[bytes[j] & mask] || ''
+        if (id.length === size) return id
+      }
+    }
+  }
+}
+let customAlphabet = (alphabet, size = 21) =>
+  customRandom(alphabet, size, random)
+let nanoid = (size = 21) =>
+  crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
+    byte &= 63
+    if (byte < 36) {
+      id += byte.toString(36)
+    } else if (byte < 62) {
+      id += (byte - 26).toString(36).toUpperCase()
+    } else if (byte > 62) {
+      id += '-'
+    } else {
+      id += '_'
+    }
+    return id
+  }, '')
+export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
diff --git a/node_modules/nanoid/index.cjs b/node_modules/nanoid/index.cjs
new file mode 100644
index 0000000..c20e374
--- /dev/null
+++ b/node_modules/nanoid/index.cjs
@@ -0,0 +1,85 @@
+let crypto = require('crypto')
+
+let { urlAlphabet } = require('./url-alphabet/index.cjs')
+
+// It is best to make fewer, larger requests to the crypto module to
+// avoid system call overhead. So, random numbers are generated in a
+// pool. The pool is a Buffer that is larger than the initial random
+// request size by this multiplier. The pool is enlarged if subsequent
+// requests exceed the maximum buffer size.
+const POOL_SIZE_MULTIPLIER = 128
+let pool, poolOffset
+
+let fillPool = bytes => {
+  if (!pool || pool.length < bytes) {
+    pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
+    crypto.randomFillSync(pool)
+    poolOffset = 0
+  } else if (poolOffset + bytes > pool.length) {
+    crypto.randomFillSync(pool)
+    poolOffset = 0
+  }
+  poolOffset += bytes
+}
+
+let random = bytes => {
+  // `|=` convert `bytes` to number to prevent `valueOf` abusing and pool pollution
+  fillPool((bytes |= 0))
+  return pool.subarray(poolOffset - bytes, poolOffset)
+}
+
+let customRandom = (alphabet, defaultSize, getRandom) => {
+  // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
+  // values closer to the alphabet size. The bitmask calculates the closest
+  // `2^31 - 1` number, which exceeds the alphabet size.
+  // For example, the bitmask for the alphabet size 30 is 31 (00011111).
+  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
+  // Though, the bitmask solution is not perfect since the bytes exceeding
+  // the alphabet size are refused. Therefore, to reliably generate the ID,
+  // the random bytes redundancy has to be satisfied.
+
+  // Note: every hardware random generator call is performance expensive,
+  // because the system call for entropy collection takes a lot of time.
+  // So, to avoid additional system calls, extra bytes are requested in advance.
+
+  // Next, a step determines how many random bytes to generate.
+  // The number of random bytes gets decided upon the ID size, mask,
+  // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
+  // according to benchmarks).
+  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
+
+  return (size = defaultSize) => {
+    let id = ''
+    while (true) {
+      let bytes = getRandom(step)
+      // A compact alternative for `for (let i = 0; i < step; i++)`.
+      let i = step
+      while (i--) {
+        // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
+        id += alphabet[bytes[i] & mask] || ''
+        if (id.length === size) return id
+      }
+    }
+  }
+}
+
+let customAlphabet = (alphabet, size = 21) =>
+  customRandom(alphabet, size, random)
+
+let nanoid = (size = 21) => {
+  // `|=` convert `size` to number to prevent `valueOf` abusing and pool pollution
+  fillPool((size |= 0))
+  let id = ''
+  // We are reading directly from the random pool to avoid creating new array
+  for (let i = poolOffset - size; i < poolOffset; i++) {
+    // It is incorrect to use bytes exceeding the alphabet size.
+    // The following mask reduces the random byte in the 0-255 value
+    // range to the 0-63 value range. Therefore, adding hacks, such
+    // as empty string fallback or magic numbers, is unneccessary because
+    // the bitmask trims bytes down to the alphabet size.
+    id += urlAlphabet[pool[i] & 63]
+  }
+  return id
+}
+
+module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
diff --git a/node_modules/nanoid/index.d.cts b/node_modules/nanoid/index.d.cts
new file mode 100644
index 0000000..3e111a3
--- /dev/null
+++ b/node_modules/nanoid/index.d.cts
@@ -0,0 +1,91 @@
+/**
+ * Generate secure URL-friendly unique ID.
+ *
+ * By default, the ID will have 21 symbols to have a collision probability
+ * similar to UUID v4.
+ *
+ * ```js
+ * import { nanoid } from 'nanoid'
+ * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"
+ * ```
+ *
+ * @param size Size of the ID. The default size is 21.
+ * @returns A random string.
+ */
+export function nanoid(size?: number): string
+
+/**
+ * Generate secure unique ID with custom alphabet.
+ *
+ * Alphabet must contain 256 symbols or less. Otherwise, the generator
+ * will not be secure.
+ *
+ * @param alphabet Alphabet used to generate the ID.
+ * @param defaultSize Size of the ID. The default size is 21.
+ * @returns A random string generator.
+ *
+ * ```js
+ * const { customAlphabet } = require('nanoid')
+ * const nanoid = customAlphabet('0123456789абвгдеё', 5)
+ * nanoid() //=> "8ё56а"
+ * ```
+ */
+export function customAlphabet(
+  alphabet: string,
+  defaultSize?: number
+): (size?: number) => string
+
+/**
+ * Generate unique ID with custom random generator and alphabet.
+ *
+ * Alphabet must contain 256 symbols or less. Otherwise, the generator
+ * will not be secure.
+ *
+ * ```js
+ * import { customRandom } from 'nanoid/format'
+ *
+ * const nanoid = customRandom('abcdef', 5, size => {
+ *   const random = []
+ *   for (let i = 0; i < size; i++) {
+ *     random.push(randomByte())
+ *   }
+ *   return random
+ * })
+ *
+ * nanoid() //=> "fbaef"
+ * ```
+ *
+ * @param alphabet Alphabet used to generate a random string.
+ * @param size Size of the random string.
+ * @param random A random bytes generator.
+ * @returns A random string generator.
+ */
+export function customRandom(
+  alphabet: string,
+  size: number,
+  random: (bytes: number) => Uint8Array
+): () => string
+
+/**
+ * URL safe symbols.
+ *
+ * ```js
+ * import { urlAlphabet } from 'nanoid'
+ * const nanoid = customAlphabet(urlAlphabet, 10)
+ * nanoid() //=> "Uakgb_J5m9"
+ * ```
+ */
+export const urlAlphabet: string
+
+/**
+ * Generate an array of random bytes collected from hardware noise.
+ *
+ * ```js
+ * import { customRandom, random } from 'nanoid'
+ * const nanoid = customRandom("abcdef", 5, random)
+ * ```
+ *
+ * @param bytes Size of the array.
+ * @returns An array of random bytes.
+ */
+export function random(bytes: number): Uint8Array
diff --git a/node_modules/nanoid/index.d.ts b/node_modules/nanoid/index.d.ts
new file mode 100644
index 0000000..3e111a3
--- /dev/null
+++ b/node_modules/nanoid/index.d.ts
@@ -0,0 +1,91 @@
+/**
+ * Generate secure URL-friendly unique ID.
+ *
+ * By default, the ID will have 21 symbols to have a collision probability
+ * similar to UUID v4.
+ *
+ * ```js
+ * import { nanoid } from 'nanoid'
+ * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"
+ * ```
+ *
+ * @param size Size of the ID. The default size is 21.
+ * @returns A random string.
+ */
+export function nanoid(size?: number): string
+
+/**
+ * Generate secure unique ID with custom alphabet.
+ *
+ * Alphabet must contain 256 symbols or less. Otherwise, the generator
+ * will not be secure.
+ *
+ * @param alphabet Alphabet used to generate the ID.
+ * @param defaultSize Size of the ID. The default size is 21.
+ * @returns A random string generator.
+ *
+ * ```js
+ * const { customAlphabet } = require('nanoid')
+ * const nanoid = customAlphabet('0123456789абвгдеё', 5)
+ * nanoid() //=> "8ё56а"
+ * ```
+ */
+export function customAlphabet(
+  alphabet: string,
+  defaultSize?: number
+): (size?: number) => string
+
+/**
+ * Generate unique ID with custom random generator and alphabet.
+ *
+ * Alphabet must contain 256 symbols or less. Otherwise, the generator
+ * will not be secure.
+ *
+ * ```js
+ * import { customRandom } from 'nanoid/format'
+ *
+ * const nanoid = customRandom('abcdef', 5, size => {
+ *   const random = []
+ *   for (let i = 0; i < size; i++) {
+ *     random.push(randomByte())
+ *   }
+ *   return random
+ * })
+ *
+ * nanoid() //=> "fbaef"
+ * ```
+ *
+ * @param alphabet Alphabet used to generate a random string.
+ * @param size Size of the random string.
+ * @param random A random bytes generator.
+ * @returns A random string generator.
+ */
+export function customRandom(
+  alphabet: string,
+  size: number,
+  random: (bytes: number) => Uint8Array
+): () => string
+
+/**
+ * URL safe symbols.
+ *
+ * ```js
+ * import { urlAlphabet } from 'nanoid'
+ * const nanoid = customAlphabet(urlAlphabet, 10)
+ * nanoid() //=> "Uakgb_J5m9"
+ * ```
+ */
+export const urlAlphabet: string
+
+/**
+ * Generate an array of random bytes collected from hardware noise.
+ *
+ * ```js
+ * import { customRandom, random } from 'nanoid'
+ * const nanoid = customRandom("abcdef", 5, random)
+ * ```
+ *
+ * @param bytes Size of the array.
+ * @returns An array of random bytes.
+ */
+export function random(bytes: number): Uint8Array
diff --git a/node_modules/nanoid/index.js b/node_modules/nanoid/index.js
new file mode 100644
index 0000000..9bc909d
--- /dev/null
+++ b/node_modules/nanoid/index.js
@@ -0,0 +1,45 @@
+import crypto from 'crypto'
+import { urlAlphabet } from './url-alphabet/index.js'
+const POOL_SIZE_MULTIPLIER = 128
+let pool, poolOffset
+let fillPool = bytes => {
+  if (!pool || pool.length < bytes) {
+    pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
+    crypto.randomFillSync(pool)
+    poolOffset = 0
+  } else if (poolOffset + bytes > pool.length) {
+    crypto.randomFillSync(pool)
+    poolOffset = 0
+  }
+  poolOffset += bytes
+}
+let random = bytes => {
+  fillPool((bytes |= 0))
+  return pool.subarray(poolOffset - bytes, poolOffset)
+}
+let customRandom = (alphabet, defaultSize, getRandom) => {
+  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
+  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
+  return (size = defaultSize) => {
+    let id = ''
+    while (true) {
+      let bytes = getRandom(step)
+      let i = step
+      while (i--) {
+        id += alphabet[bytes[i] & mask] || ''
+        if (id.length === size) return id
+      }
+    }
+  }
+}
+let customAlphabet = (alphabet, size = 21) =>
+  customRandom(alphabet, size, random)
+let nanoid = (size = 21) => {
+  fillPool((size |= 0))
+  let id = ''
+  for (let i = poolOffset - size; i < poolOffset; i++) {
+    id += urlAlphabet[pool[i] & 63]
+  }
+  return id
+}
+export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
diff --git a/node_modules/nanoid/nanoid.js b/node_modules/nanoid/nanoid.js
new file mode 100644
index 0000000..ec242ea
--- /dev/null
+++ b/node_modules/nanoid/nanoid.js
@@ -0,0 +1 @@
+export let nanoid=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce(((t,e)=>t+=(e&=63)<36?e.toString(36):e<62?(e-26).toString(36).toUpperCase():e<63?"_":"-"),"");
\ No newline at end of file
diff --git a/node_modules/nanoid/non-secure/index.cjs b/node_modules/nanoid/non-secure/index.cjs
new file mode 100644
index 0000000..d51fcb6
--- /dev/null
+++ b/node_modules/nanoid/non-secure/index.cjs
@@ -0,0 +1,34 @@
+// This alphabet uses `A-Za-z0-9_-` symbols.
+// The order of characters is optimized for better gzip and brotli compression.
+// References to the same file (works both for gzip and brotli):
+// `'use`, `andom`, and `rict'`
+// References to the brotli default dictionary:
+// `-26T`, `1983`, `40px`, `75px`, `bush`, `jack`, `mind`, `very`, and `wolf`
+let urlAlphabet =
+  'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
+
+let customAlphabet = (alphabet, defaultSize = 21) => {
+  return (size = defaultSize) => {
+    let id = ''
+    // A compact alternative for `for (var i = 0; i < step; i++)`.
+    let i = size | 0
+    while (i--) {
+      // `| 0` is more compact and faster than `Math.floor()`.
+      id += alphabet[(Math.random() * alphabet.length) | 0]
+    }
+    return id
+  }
+}
+
+let nanoid = (size = 21) => {
+  let id = ''
+  // A compact alternative for `for (var i = 0; i < step; i++)`.
+  let i = size | 0
+  while (i--) {
+    // `| 0` is more compact and faster than `Math.floor()`.
+    id += urlAlphabet[(Math.random() * 64) | 0]
+  }
+  return id
+}
+
+module.exports = { nanoid, customAlphabet }
diff --git a/node_modules/nanoid/non-secure/index.d.ts b/node_modules/nanoid/non-secure/index.d.ts
new file mode 100644
index 0000000..4965322
--- /dev/null
+++ b/node_modules/nanoid/non-secure/index.d.ts
@@ -0,0 +1,33 @@
+/**
+ * Generate URL-friendly unique ID. This method uses the non-secure
+ * predictable random generator with bigger collision probability.
+ *
+ * ```js
+ * import { nanoid } from 'nanoid/non-secure'
+ * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"
+ * ```
+ *
+ * @param size Size of the ID. The default size is 21.
+ * @returns A random string.
+ */
+export function nanoid(size?: number): string
+
+/**
+ * Generate a unique ID based on a custom alphabet.
+ * This method uses the non-secure predictable random generator
+ * with bigger collision probability.
+ *
+ * @param alphabet Alphabet used to generate the ID.
+ * @param defaultSize Size of the ID. The default size is 21.
+ * @returns A random string generator.
+ *
+ * ```js
+ * import { customAlphabet } from 'nanoid/non-secure'
+ * const nanoid = customAlphabet('0123456789абвгдеё', 5)
+ * model.id = //=> "8ё56а"
+ * ```
+ */
+export function customAlphabet(
+  alphabet: string,
+  defaultSize?: number
+): (size?: number) => string
diff --git a/node_modules/nanoid/non-secure/index.js b/node_modules/nanoid/non-secure/index.js
new file mode 100644
index 0000000..2ea5827
--- /dev/null
+++ b/node_modules/nanoid/non-secure/index.js
@@ -0,0 +1,21 @@
+let urlAlphabet =
+  'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
+let customAlphabet = (alphabet, defaultSize = 21) => {
+  return (size = defaultSize) => {
+    let id = ''
+    let i = size | 0
+    while (i--) {
+      id += alphabet[(Math.random() * alphabet.length) | 0]
+    }
+    return id
+  }
+}
+let nanoid = (size = 21) => {
+  let id = ''
+  let i = size | 0
+  while (i--) {
+    id += urlAlphabet[(Math.random() * 64) | 0]
+  }
+  return id
+}
+export { nanoid, customAlphabet }
diff --git a/node_modules/nanoid/non-secure/package.json b/node_modules/nanoid/non-secure/package.json
new file mode 100644
index 0000000..9930d6a
--- /dev/null
+++ b/node_modules/nanoid/non-secure/package.json
@@ -0,0 +1,6 @@
+{
+  "type": "module",
+  "main": "index.cjs",
+  "module": "index.js",
+  "react-native": "index.js"
+}
\ No newline at end of file
diff --git a/node_modules/nanoid/package.json b/node_modules/nanoid/package.json
new file mode 100644
index 0000000..a3d3f44
--- /dev/null
+++ b/node_modules/nanoid/package.json
@@ -0,0 +1,89 @@
+{
+  "name": "nanoid",
+  "version": "3.3.11",
+  "description": "A tiny (116 bytes), secure URL-friendly unique string ID generator",
+  "keywords": [
+    "uuid",
+    "random",
+    "id",
+    "url"
+  ],
+  "engines": {
+    "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+  },
+  "funding": [
+    {
+      "type": "github",
+      "url": "https://github.com/sponsors/ai"
+    }
+  ],
+  "author": "Andrey Sitnik ",
+  "license": "MIT",
+  "repository": "ai/nanoid",
+  "browser": {
+    "./index.js": "./index.browser.js",
+    "./async/index.js": "./async/index.browser.js",
+    "./async/index.cjs": "./async/index.browser.cjs",
+    "./index.cjs": "./index.browser.cjs"
+  },
+  "react-native": "index.js",
+  "bin": "./bin/nanoid.cjs",
+  "sideEffects": false,
+  "types": "./index.d.ts",
+  "type": "module",
+  "main": "index.cjs",
+  "module": "index.js",
+  "exports": {
+    ".": {
+      "react-native": "./index.browser.js",
+      "browser": "./index.browser.js",
+      "require": {
+        "types": "./index.d.cts",
+        "default": "./index.cjs"
+      },
+      "import": {
+        "types": "./index.d.ts",
+        "default": "./index.js"
+      },
+      "default": "./index.js"
+    },
+    "./package.json": "./package.json",
+    "./async/package.json": "./async/package.json",
+    "./async": {
+      "browser": "./async/index.browser.js",
+      "require": {
+        "types": "./index.d.cts",
+        "default": "./async/index.cjs"
+      },
+      "import": {
+        "types": "./index.d.ts",
+        "default": "./async/index.js"
+      },
+      "default": "./async/index.js"
+    },
+    "./non-secure/package.json": "./non-secure/package.json",
+    "./non-secure": {
+      "require": {
+        "types": "./index.d.cts",
+        "default": "./non-secure/index.cjs"
+      },
+      "import": {
+        "types": "./index.d.ts",
+        "default": "./non-secure/index.js"
+      },
+      "default": "./non-secure/index.js"
+    },
+    "./url-alphabet/package.json": "./url-alphabet/package.json",
+    "./url-alphabet": {
+      "require": {
+        "types": "./index.d.cts",
+        "default": "./url-alphabet/index.cjs"
+      },
+      "import": {
+        "types": "./index.d.ts",
+        "default": "./url-alphabet/index.js"
+      },
+      "default": "./url-alphabet/index.js"
+    }
+  }
+}
diff --git a/node_modules/nanoid/url-alphabet/index.cjs b/node_modules/nanoid/url-alphabet/index.cjs
new file mode 100644
index 0000000..a332f0b
--- /dev/null
+++ b/node_modules/nanoid/url-alphabet/index.cjs
@@ -0,0 +1,7 @@
+// This alphabet uses `A-Za-z0-9_-` symbols.
+// The order of characters is optimized for better gzip and brotli compression.
+// Same as in non-secure/index.js
+let urlAlphabet =
+  'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
+
+module.exports = { urlAlphabet }
diff --git a/node_modules/nanoid/url-alphabet/index.js b/node_modules/nanoid/url-alphabet/index.js
new file mode 100644
index 0000000..c2782e5
--- /dev/null
+++ b/node_modules/nanoid/url-alphabet/index.js
@@ -0,0 +1,3 @@
+let urlAlphabet =
+  'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
+export { urlAlphabet }
diff --git a/node_modules/nanoid/url-alphabet/package.json b/node_modules/nanoid/url-alphabet/package.json
new file mode 100644
index 0000000..9930d6a
--- /dev/null
+++ b/node_modules/nanoid/url-alphabet/package.json
@@ -0,0 +1,6 @@
+{
+  "type": "module",
+  "main": "index.cjs",
+  "module": "index.js",
+  "react-native": "index.js"
+}
\ No newline at end of file
diff --git a/node_modules/normalize-path/LICENSE b/node_modules/normalize-path/LICENSE
new file mode 100644
index 0000000..d32ab44
--- /dev/null
+++ b/node_modules/normalize-path/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014-2018, Jon Schlinkert.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/node_modules/normalize-path/README.md b/node_modules/normalize-path/README.md
new file mode 100644
index 0000000..726d4d6
--- /dev/null
+++ b/node_modules/normalize-path/README.md
@@ -0,0 +1,127 @@
+# normalize-path [![NPM version](https://img.shields.io/npm/v/normalize-path.svg?style=flat)](https://www.npmjs.com/package/normalize-path) [![NPM monthly downloads](https://img.shields.io/npm/dm/normalize-path.svg?style=flat)](https://npmjs.org/package/normalize-path) [![NPM total downloads](https://img.shields.io/npm/dt/normalize-path.svg?style=flat)](https://npmjs.org/package/normalize-path) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/normalize-path.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/normalize-path)
+
+> Normalize slashes in a file path to be posix/unix-like forward slashes. Also condenses repeat slashes to a single slash and removes and trailing slashes, unless disabled.
+
+Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
+
+## Install
+
+Install with [npm](https://www.npmjs.com/):
+
+```sh
+$ npm install --save normalize-path
+```
+
+## Usage
+
+```js
+const normalize = require('normalize-path');
+
+console.log(normalize('\\foo\\bar\\baz\\')); 
+//=> '/foo/bar/baz'
+```
+
+**win32 namespaces**
+
+```js
+console.log(normalize('\\\\?\\UNC\\Server01\\user\\docs\\Letter.txt')); 
+//=> '//?/UNC/Server01/user/docs/Letter.txt'
+
+console.log(normalize('\\\\.\\CdRomX')); 
+//=> '//./CdRomX'
+```
+
+**Consecutive slashes**
+
+Condenses multiple consecutive forward slashes (except for leading slashes in win32 namespaces) to a single slash.
+
+```js
+console.log(normalize('.//foo//bar///////baz/')); 
+//=> './foo/bar/baz'
+```
+
+### Trailing slashes
+
+By default trailing slashes are removed. Pass `false` as the last argument to disable this behavior and _**keep** trailing slashes_:
+
+```js
+console.log(normalize('foo\\bar\\baz\\', false)); //=> 'foo/bar/baz/'
+console.log(normalize('./foo/bar/baz/', false)); //=> './foo/bar/baz/'
+```
+
+## Release history
+
+### v3.0
+
+No breaking changes in this release.
+
+* a check was added to ensure that [win32 namespaces](https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces) are handled properly by win32 `path.parse()` after a path has been normalized by this library.
+* a minor optimization was made to simplify how the trailing separator was handled
+
+## About
+
+
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +Other useful path-related libraries: + +* [contains-path](https://www.npmjs.com/package/contains-path): Return true if a file path contains the given path. | [homepage](https://github.com/jonschlinkert/contains-path "Return true if a file path contains the given path.") +* [is-absolute](https://www.npmjs.com/package/is-absolute): Returns true if a file path is absolute. Does not rely on the path module… [more](https://github.com/jonschlinkert/is-absolute) | [homepage](https://github.com/jonschlinkert/is-absolute "Returns true if a file path is absolute. Does not rely on the path module and can be used as a polyfill for node.js native `path.isAbolute`.") +* [is-relative](https://www.npmjs.com/package/is-relative): Returns `true` if the path appears to be relative. | [homepage](https://github.com/jonschlinkert/is-relative "Returns `true` if the path appears to be relative.") +* [parse-filepath](https://www.npmjs.com/package/parse-filepath): Pollyfill for node.js `path.parse`, parses a filepath into an object. | [homepage](https://github.com/jonschlinkert/parse-filepath "Pollyfill for node.js `path.parse`, parses a filepath into an object.") +* [path-ends-with](https://www.npmjs.com/package/path-ends-with): Return `true` if a file path ends with the given string/suffix. | [homepage](https://github.com/jonschlinkert/path-ends-with "Return `true` if a file path ends with the given string/suffix.") +* [unixify](https://www.npmjs.com/package/unixify): Convert Windows file paths to unix paths. | [homepage](https://github.com/jonschlinkert/unixify "Convert Windows file paths to unix paths.") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 35 | [jonschlinkert](https://github.com/jonschlinkert) | +| 1 | [phated](https://github.com/phated) | + +### Author + +**Jon Schlinkert** + +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) + +### License + +Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on April 19, 2018._ \ No newline at end of file diff --git a/node_modules/normalize-path/index.js b/node_modules/normalize-path/index.js new file mode 100644 index 0000000..6fac553 --- /dev/null +++ b/node_modules/normalize-path/index.js @@ -0,0 +1,35 @@ +/*! + * normalize-path + * + * Copyright (c) 2014-2018, Jon Schlinkert. + * Released under the MIT License. + */ + +module.exports = function(path, stripTrailing) { + if (typeof path !== 'string') { + throw new TypeError('expected path to be a string'); + } + + if (path === '\\' || path === '/') return '/'; + + var len = path.length; + if (len <= 1) return path; + + // ensure that win32 namespaces has two leading slashes, so that the path is + // handled properly by the win32 version of path.parse() after being normalized + // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces + var prefix = ''; + if (len > 4 && path[3] === '\\') { + var ch = path[2]; + if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') { + path = path.slice(2); + prefix = '//'; + } + } + + var segs = path.split(/[/\\]+/); + if (stripTrailing !== false && segs[segs.length - 1] === '') { + segs.pop(); + } + return prefix + segs.join('/'); +}; diff --git a/node_modules/normalize-path/package.json b/node_modules/normalize-path/package.json new file mode 100644 index 0000000..ad61098 --- /dev/null +++ b/node_modules/normalize-path/package.json @@ -0,0 +1,77 @@ +{ + "name": "normalize-path", + "description": "Normalize slashes in a file path to be posix/unix-like forward slashes. Also condenses repeat slashes to a single slash and removes and trailing slashes, unless disabled.", + "version": "3.0.0", + "homepage": "https://github.com/jonschlinkert/normalize-path", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Blaine Bublitz (https://twitter.com/BlaineBublitz)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)" + ], + "repository": "jonschlinkert/normalize-path", + "bugs": { + "url": "https://github.com/jonschlinkert/normalize-path/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "gulp-format-md": "^1.0.0", + "minimist": "^1.2.0", + "mocha": "^3.5.3" + }, + "keywords": [ + "absolute", + "backslash", + "delimiter", + "file", + "file-path", + "filepath", + "fix", + "forward", + "fp", + "fs", + "normalize", + "path", + "relative", + "separator", + "slash", + "slashes", + "trailing", + "unix", + "urix" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "related": { + "description": "Other useful path-related libraries:", + "list": [ + "contains-path", + "is-absolute", + "is-relative", + "parse-filepath", + "path-ends-with", + "path-ends-with", + "unixify" + ] + }, + "lint": { + "reflinks": true + } + } +} diff --git a/node_modules/object-assign/index.js b/node_modules/object-assign/index.js new file mode 100644 index 0000000..0930cf8 --- /dev/null +++ b/node_modules/object-assign/index.js @@ -0,0 +1,90 @@ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; diff --git a/node_modules/object-assign/license b/node_modules/object-assign/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/node_modules/object-assign/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/object-assign/package.json b/node_modules/object-assign/package.json new file mode 100644 index 0000000..503eb1e --- /dev/null +++ b/node_modules/object-assign/package.json @@ -0,0 +1,42 @@ +{ + "name": "object-assign", + "version": "4.1.1", + "description": "ES2015 `Object.assign()` ponyfill", + "license": "MIT", + "repository": "sindresorhus/object-assign", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava", + "bench": "matcha bench.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "object", + "assign", + "extend", + "properties", + "es2015", + "ecmascript", + "harmony", + "ponyfill", + "prollyfill", + "polyfill", + "shim", + "browser" + ], + "devDependencies": { + "ava": "^0.16.0", + "lodash": "^4.16.4", + "matcha": "^0.7.0", + "xo": "^0.16.0" + } +} diff --git a/node_modules/object-assign/readme.md b/node_modules/object-assign/readme.md new file mode 100644 index 0000000..1be09d3 --- /dev/null +++ b/node_modules/object-assign/readme.md @@ -0,0 +1,61 @@ +# object-assign [![Build Status](https://travis-ci.org/sindresorhus/object-assign.svg?branch=master)](https://travis-ci.org/sindresorhus/object-assign) + +> ES2015 [`Object.assign()`](http://www.2ality.com/2014/01/object-assign.html) [ponyfill](https://ponyfill.com) + + +## Use the built-in + +Node.js 4 and up, as well as every evergreen browser (Chrome, Edge, Firefox, Opera, Safari), +support `Object.assign()` :tada:. If you target only those environments, then by all +means, use `Object.assign()` instead of this package. + + +## Install + +``` +$ npm install --save object-assign +``` + + +## Usage + +```js +const objectAssign = require('object-assign'); + +objectAssign({foo: 0}, {bar: 1}); +//=> {foo: 0, bar: 1} + +// multiple sources +objectAssign({foo: 0}, {bar: 1}, {baz: 2}); +//=> {foo: 0, bar: 1, baz: 2} + +// overwrites equal keys +objectAssign({foo: 0}, {foo: 1}, {foo: 2}); +//=> {foo: 2} + +// ignores null and undefined sources +objectAssign({foo: 0}, null, {bar: 1}, undefined); +//=> {foo: 0, bar: 1} +``` + + +## API + +### objectAssign(target, [source, ...]) + +Assigns enumerable own properties of `source` objects to the `target` object and returns the `target` object. Additional `source` objects will overwrite previous ones. + + +## Resources + +- [ES2015 spec - Object.assign](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign) + + +## Related + +- [deep-assign](https://github.com/sindresorhus/deep-assign) - Recursive `Object.assign()` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/object-hash/LICENSE b/node_modules/object-hash/LICENSE new file mode 100644 index 0000000..6ea185f --- /dev/null +++ b/node_modules/object-hash/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2014 object-hash contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/object-hash/dist/object_hash.js b/node_modules/object-hash/dist/object_hash.js new file mode 100644 index 0000000..2e584c5 --- /dev/null +++ b/node_modules/object-hash/dist/object_hash.js @@ -0,0 +1 @@ +!function(e){var t;"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):("undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.objectHash=e())}(function(){return function r(o,i,u){function s(n,e){if(!i[n]){if(!o[n]){var t="function"==typeof require&&require;if(!e&&t)return t(n,!0);if(a)return a(n,!0);throw new Error("Cannot find module '"+n+"'")}e=i[n]={exports:{}};o[n][0].call(e.exports,function(e){var t=o[n][1][e];return s(t||e)},e,e.exports,r,o,i,u)}return i[n].exports}for(var a="function"==typeof require&&require,e=0;e>16),s((65280&n)>>8),s(255&n);return 2==r?s(255&(n=f(e.charAt(t))<<2|f(e.charAt(t+1))>>4)):1==r&&(s((n=f(e.charAt(t))<<10|f(e.charAt(t+1))<<4|f(e.charAt(t+2))>>2)>>8&255),s(255&n)),o},e.fromByteArray=function(e){var t,n,r,o,i=e.length%3,u="";function s(e){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(e)}for(t=0,r=e.length-i;t>18&63)+s(o>>12&63)+s(o>>6&63)+s(63&o);switch(i){case 1:u=(u+=s((n=e[e.length-1])>>2))+s(n<<4&63)+"==";break;case 2:u=(u=(u+=s((n=(e[e.length-2]<<8)+e[e.length-1])>>10))+s(n>>4&63))+s(n<<2&63)+"="}return u}}(void 0===f?this.base64js={}:f)}.call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:11}],3:[function(O,e,H){!function(e,n,f,r,h,p,g,y,w){var a=O("base64-js"),i=O("ieee754");function f(e,t,n){if(!(this instanceof f))return new f(e,t,n);var r,o,i,u,s=typeof e;if("base64"===t&&"string"==s)for(e=(u=e).trim?u.trim():u.replace(/^\s+|\s+$/g,"");e.length%4!=0;)e+="=";if("number"==s)r=j(e);else if("string"==s)r=f.byteLength(e,t);else{if("object"!=s)throw new Error("First argument needs to be a number, array or string.");r=j(e.length)}if(f._useTypedArrays?o=f._augment(new Uint8Array(r)):((o=this).length=r,o._isBuffer=!0),f._useTypedArrays&&"number"==typeof e.byteLength)o._set(e);else if(C(u=e)||f.isBuffer(u)||u&&"object"==typeof u&&"number"==typeof u.length)for(i=0;i>8,n=n%256,r.push(n),r.push(t);return r}(t),e,n,r)}function v(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;o>>0)):(t+1>>0),o}function _(e,t,n,r){if(r||(d("boolean"==typeof n,"missing or invalid endian"),d(null!=t,"missing offset"),d(t+1>>8*(r?i:1-i)}function l(e,t,n,r,o){o||(d(null!=t,"missing value"),d("boolean"==typeof r,"missing or invalid endian"),d(null!=n,"missing offset"),d(n+3>>8*(r?i:3-i)&255}function B(e,t,n,r,o){o||(d(null!=t,"missing value"),d("boolean"==typeof r,"missing or invalid endian"),d(null!=n,"missing offset"),d(n+1this.length&&(r=this.length);var o=(r=e.length-t=this.length))return this[e]},f.prototype.readUInt16LE=function(e,t){return o(this,e,!0,t)},f.prototype.readUInt16BE=function(e,t){return o(this,e,!1,t)},f.prototype.readUInt32LE=function(e,t){return u(this,e,!0,t)},f.prototype.readUInt32BE=function(e,t){return u(this,e,!1,t)},f.prototype.readInt8=function(e,t){if(t||(d(null!=e,"missing offset"),d(e=this.length))return 128&this[e]?-1*(255-this[e]+1):this[e]},f.prototype.readInt16LE=function(e,t){return _(this,e,!0,t)},f.prototype.readInt16BE=function(e,t){return _(this,e,!1,t)},f.prototype.readInt32LE=function(e,t){return E(this,e,!0,t)},f.prototype.readInt32BE=function(e,t){return E(this,e,!1,t)},f.prototype.readFloatLE=function(e,t){return I(this,e,!0,t)},f.prototype.readFloatBE=function(e,t){return I(this,e,!1,t)},f.prototype.readDoubleLE=function(e,t){return A(this,e,!0,t)},f.prototype.readDoubleBE=function(e,t){return A(this,e,!1,t)},f.prototype.writeUInt8=function(e,t,n){n||(d(null!=e,"missing value"),d(null!=t,"missing offset"),d(t=this.length||(this[t]=e)},f.prototype.writeUInt16LE=function(e,t,n){s(this,e,t,!0,n)},f.prototype.writeUInt16BE=function(e,t,n){s(this,e,t,!1,n)},f.prototype.writeUInt32LE=function(e,t,n){l(this,e,t,!0,n)},f.prototype.writeUInt32BE=function(e,t,n){l(this,e,t,!1,n)},f.prototype.writeInt8=function(e,t,n){n||(d(null!=e,"missing value"),d(null!=t,"missing offset"),d(t=this.length||(0<=e?this.writeUInt8(e,t,n):this.writeUInt8(255+e+1,t,n))},f.prototype.writeInt16LE=function(e,t,n){B(this,e,t,!0,n)},f.prototype.writeInt16BE=function(e,t,n){B(this,e,t,!1,n)},f.prototype.writeInt32LE=function(e,t,n){L(this,e,t,!0,n)},f.prototype.writeInt32BE=function(e,t,n){L(this,e,t,!1,n)},f.prototype.writeFloatLE=function(e,t,n){U(this,e,t,!0,n)},f.prototype.writeFloatBE=function(e,t,n){U(this,e,t,!1,n)},f.prototype.writeDoubleLE=function(e,t,n){x(this,e,t,!0,n)},f.prototype.writeDoubleBE=function(e,t,n){x(this,e,t,!1,n)},f.prototype.fill=function(e,t,n){if(t=t||0,n=n||this.length,d("number"==typeof(e="string"==typeof(e=e||0)?e.charCodeAt(0):e)&&!isNaN(e),"value is not a number"),d(t<=n,"end < start"),n!==t&&0!==this.length){d(0<=t&&t"},f.prototype.toArrayBuffer=function(){if("undefined"==typeof Uint8Array)throw new Error("Buffer.toArrayBuffer not supported in this browser");if(f._useTypedArrays)return new f(this).buffer;for(var e=new Uint8Array(this.length),t=0,n=e.length;t=t.length||o>=e.length);o++)t[o+n]=e[o];return o}function N(e){try{return decodeURIComponent(e)}catch(e){return String.fromCharCode(65533)}}function Y(e,t){d("number"==typeof e,"cannot write a non-number as a number"),d(0<=e,"specified a negative value for writing an unsigned value"),d(e<=t,"value is larger than maximum value for type"),d(Math.floor(e)===e,"value has a fractional component")}function F(e,t,n){d("number"==typeof e,"cannot write a non-number as a number"),d(e<=t,"value larger than maximum allowed value"),d(n<=e,"value smaller than minimum allowed value"),d(Math.floor(e)===e,"value has a fractional component")}function D(e,t,n){d("number"==typeof e,"cannot write a non-number as a number"),d(e<=t,"value larger than maximum allowed value"),d(n<=e,"value smaller than minimum allowed value")}function d(e,t){if(!e)throw new Error(t||"Failed assertion")}f._augment=function(e){return e._isBuffer=!0,e._get=e.get,e._set=e.set,e.get=t.get,e.set=t.set,e.write=t.write,e.toString=t.toString,e.toLocaleString=t.toString,e.toJSON=t.toJSON,e.copy=t.copy,e.slice=t.slice,e.readUInt8=t.readUInt8,e.readUInt16LE=t.readUInt16LE,e.readUInt16BE=t.readUInt16BE,e.readUInt32LE=t.readUInt32LE,e.readUInt32BE=t.readUInt32BE,e.readInt8=t.readInt8,e.readInt16LE=t.readInt16LE,e.readInt16BE=t.readInt16BE,e.readInt32LE=t.readInt32LE,e.readInt32BE=t.readInt32BE,e.readFloatLE=t.readFloatLE,e.readFloatBE=t.readFloatBE,e.readDoubleLE=t.readDoubleLE,e.readDoubleBE=t.readDoubleBE,e.writeUInt8=t.writeUInt8,e.writeUInt16LE=t.writeUInt16LE,e.writeUInt16BE=t.writeUInt16BE,e.writeUInt32LE=t.writeUInt32LE,e.writeUInt32BE=t.writeUInt32BE,e.writeInt8=t.writeInt8,e.writeInt16LE=t.writeInt16LE,e.writeInt16BE=t.writeInt16BE,e.writeInt32LE=t.writeInt32LE,e.writeInt32BE=t.writeInt32BE,e.writeFloatLE=t.writeFloatLE,e.writeFloatBE=t.writeFloatBE,e.writeDoubleLE=t.writeDoubleLE,e.writeDoubleBE=t.writeDoubleBE,e.fill=t.fill,e.inspect=t.inspect,e.toArrayBuffer=t.toArrayBuffer,e}}.call(this,O("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},O("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(c,d,e){!function(e,t,a,n,r,o,i,u,s){var a=c("buffer").Buffer,f=4,l=new a(f);l.fill(0);d.exports={hash:function(e,t,n,r){for(var o=t(function(e,t){e.length%f!=0&&(n=e.length+(f-e.length%f),e=a.concat([e,l],n));for(var n,r=[],o=t?e.readInt32BE:e.readInt32LE,i=0;is?t=e(t):t.length>5]|=128<>>9<<4)]=t;for(var n=1732584193,r=-271733879,o=-1732584194,i=271733878,u=0;u>>32-o,n)}function c(e,t,n,r,o,i,u){return s(t&n|~t&r,e,t,o,i,u)}function d(e,t,n,r,o,i,u){return s(t&r|n&~r,e,t,o,i,u)}function h(e,t,n,r,o,i,u){return s(t^n^r,e,t,o,i,u)}function p(e,t,n,r,o,i,u){return s(n^(t|~r),e,t,o,i,u)}function g(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}b.exports=function(e){return t.hash(e,n,16)}}.call(this,w("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},w("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(e,l,t){!function(e,t,n,r,o,i,u,s,f){var a;l.exports=a||function(e){for(var t,n=new Array(e),r=0;r>>((3&r)<<3)&255;return n}}.call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(c,d,e){!function(e,t,n,r,o,s,a,f,l){var i=c("./helpers");function u(l,c){l[c>>5]|=128<<24-c%32,l[15+(c+64>>9<<4)]=c;for(var e,t,n,r=Array(80),o=1732584193,i=-271733879,u=-1732584194,s=271733878,d=-1009589776,h=0;h>16)+(t>>16)+(n>>16)<<16|65535&n}function v(e,t){return e<>>32-t}d.exports=function(e){return i.hash(e,u,20,!0)}}.call(this,c("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},c("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(c,d,e){!function(e,t,n,r,u,s,a,f,l){function b(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function o(e,l){var c,d=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),t=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),n=new Array(64);e[l>>5]|=128<<24-l%32,e[15+(l+64>>9<<4)]=l;for(var r,o,h=0;h>>t|e<<32-t},v=function(e,t){return e>>>t};d.exports=function(e){return i.hash(e,o,32,!0)}}.call(this,c("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},c("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(e,t,f){!function(e,t,n,r,o,i,u,s,a){f.read=function(e,t,n,r,o){var i,u,l=8*o-r-1,c=(1<>1,s=-7,a=n?o-1:0,f=n?-1:1,o=e[t+a];for(a+=f,i=o&(1<<-s)-1,o>>=-s,s+=l;0>=-s,s+=r;0>1,d=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:c-1,h=n?1:-1,c=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,o=s):(o=Math.floor(Math.log(t)/Math.LN2),t*(n=Math.pow(2,-o))<1&&(o--,n*=2),2<=(t+=1<=o+a?d/n:d*Math.pow(2,1-a))*n&&(o++,n/=2),s<=o+a?(i=0,o=s):1<=o+a?(i=(t*n-1)*Math.pow(2,r),o+=a):(i=t*Math.pow(2,a-1)*Math.pow(2,r),o=0));8<=r;e[l+f]=255&i,f+=h,i/=256,r-=8);for(o=o<", type, " -> ", "_" + type); + + return this['_' + type](value); + }, + _object: function(object) { + var pattern = (/\[object (.*)\]/i); + var objString = Object.prototype.toString.call(object); + var objType = pattern.exec(objString); + if (!objType) { // object type did not match [object ...] + objType = 'unknown:[' + objString + ']'; + } else { + objType = objType[1]; // take only the class name + } + + objType = objType.toLowerCase(); + + var objectNumber = null; + + if ((objectNumber = context.indexOf(object)) >= 0) { + return this.dispatch('[CIRCULAR:' + objectNumber + ']'); + } else { + context.push(object); + } + + if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) { + write('buffer:'); + return write(object); + } + + if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') { + if(this['_' + objType]) { + this['_' + objType](object); + } else if (options.ignoreUnknown) { + return write('[' + objType + ']'); + } else { + throw new Error('Unknown object type "' + objType + '"'); + } + }else{ + var keys = Object.keys(object); + if (options.unorderedObjects) { + keys = keys.sort(); + } + // Make sure to incorporate special properties, so + // Types with different prototypes will produce + // a different hash and objects derived from + // different functions (`new Foo`, `new Bar`) will + // produce different hashes. + // We never do this for native functions since some + // seem to break because of that. + if (options.respectType !== false && !isNativeFunction(object)) { + keys.splice(0, 0, 'prototype', '__proto__', 'constructor'); + } + + if (options.excludeKeys) { + keys = keys.filter(function(key) { return !options.excludeKeys(key); }); + } + + write('object:' + keys.length + ':'); + var self = this; + return keys.forEach(function(key){ + self.dispatch(key); + write(':'); + if(!options.excludeValues) { + self.dispatch(object[key]); + } + write(','); + }); + } + }, + _array: function(arr, unordered){ + unordered = typeof unordered !== 'undefined' ? unordered : + options.unorderedArrays !== false; // default to options.unorderedArrays + + var self = this; + write('array:' + arr.length + ':'); + if (!unordered || arr.length <= 1) { + return arr.forEach(function(entry) { + return self.dispatch(entry); + }); + } + + // the unordered case is a little more complicated: + // since there is no canonical ordering on objects, + // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false, + // we first serialize each entry using a PassThrough stream + // before sorting. + // also: we can’t use the same context array for all entries + // since the order of hashing should *not* matter. instead, + // we keep track of the additions to a copy of the context array + // and add all of them to the global context array when we’re done + var contextAdditions = []; + var entries = arr.map(function(entry) { + var strm = new PassThrough(); + var localContext = context.slice(); // make copy + var hasher = typeHasher(options, strm, localContext); + hasher.dispatch(entry); + // take only what was added to localContext and append it to contextAdditions + contextAdditions = contextAdditions.concat(localContext.slice(context.length)); + return strm.read().toString(); + }); + context = context.concat(contextAdditions); + entries.sort(); + return this._array(entries, false); + }, + _date: function(date){ + return write('date:' + date.toJSON()); + }, + _symbol: function(sym){ + return write('symbol:' + sym.toString()); + }, + _error: function(err){ + return write('error:' + err.toString()); + }, + _boolean: function(bool){ + return write('bool:' + bool.toString()); + }, + _string: function(string){ + write('string:' + string.length + ':'); + write(string.toString()); + }, + _function: function(fn){ + write('fn:'); + if (isNativeFunction(fn)) { + this.dispatch('[native]'); + } else { + this.dispatch(fn.toString()); + } + + if (options.respectFunctionNames !== false) { + // Make sure we can still distinguish native functions + // by their name, otherwise String and Function will + // have the same hash + this.dispatch("function-name:" + String(fn.name)); + } + + if (options.respectFunctionProperties) { + this._object(fn); + } + }, + _number: function(number){ + return write('number:' + number.toString()); + }, + _xml: function(xml){ + return write('xml:' + xml.toString()); + }, + _null: function() { + return write('Null'); + }, + _undefined: function() { + return write('Undefined'); + }, + _regexp: function(regex){ + return write('regex:' + regex.toString()); + }, + _uint8array: function(arr){ + write('uint8array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint8clampedarray: function(arr){ + write('uint8clampedarray:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int8array: function(arr){ + write('int8array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint16array: function(arr){ + write('uint16array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int16array: function(arr){ + write('int16array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint32array: function(arr){ + write('uint32array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int32array: function(arr){ + write('int32array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _float32array: function(arr){ + write('float32array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _float64array: function(arr){ + write('float64array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _arraybuffer: function(arr){ + write('arraybuffer:'); + return this.dispatch(new Uint8Array(arr)); + }, + _url: function(url) { + return write('url:' + url.toString(), 'utf8'); + }, + _map: function(map) { + write('map:'); + var arr = Array.from(map); + return this._array(arr, options.unorderedSets !== false); + }, + _set: function(set) { + write('set:'); + var arr = Array.from(set); + return this._array(arr, options.unorderedSets !== false); + }, + _file: function(file) { + write('file:'); + return this.dispatch([file.name, file.size, file.type, file.lastModfied]); + }, + _blob: function() { + if (options.ignoreUnknown) { + return write('[blob]'); + } + + throw Error('Hashing Blob objects is currently not supported\n' + + '(see https://github.com/puleos/object-hash/issues/26)\n' + + 'Use "options.replacer" or "options.ignoreUnknown"\n'); + }, + _domwindow: function() { return write('domwindow'); }, + _bigint: function(number){ + return write('bigint:' + number.toString()); + }, + /* Node.js standard native objects */ + _process: function() { return write('process'); }, + _timer: function() { return write('timer'); }, + _pipe: function() { return write('pipe'); }, + _tcp: function() { return write('tcp'); }, + _udp: function() { return write('udp'); }, + _tty: function() { return write('tty'); }, + _statwatcher: function() { return write('statwatcher'); }, + _securecontext: function() { return write('securecontext'); }, + _connection: function() { return write('connection'); }, + _zlib: function() { return write('zlib'); }, + _context: function() { return write('context'); }, + _nodescript: function() { return write('nodescript'); }, + _httpparser: function() { return write('httpparser'); }, + _dataview: function() { return write('dataview'); }, + _signal: function() { return write('signal'); }, + _fsevent: function() { return write('fsevent'); }, + _tlswrap: function() { return write('tlswrap'); }, + }; +} + +// Mini-implementation of stream.PassThrough +// We are far from having need for the full implementation, and we can +// make assumptions like "many writes, then only one final read" +// and we can ignore encoding specifics +function PassThrough() { + return { + buf: '', + + write: function(b) { + this.buf += b; + }, + + end: function(b) { + this.buf += b; + }, + + read: function() { + return this.buf; + } + }; +} diff --git a/node_modules/object-hash/package.json b/node_modules/object-hash/package.json new file mode 100644 index 0000000..a72557f --- /dev/null +++ b/node_modules/object-hash/package.json @@ -0,0 +1,53 @@ +{ + "name": "object-hash", + "version": "3.0.0", + "description": "Generate hashes from javascript objects in node and the browser.", + "homepage": "https://github.com/puleos/object-hash", + "repository": { + "type": "git", + "url": "https://github.com/puleos/object-hash" + }, + "keywords": [ + "object", + "hash", + "sha1", + "md5" + ], + "bugs": { + "url": "https://github.com/puleos/object-hash/issues" + }, + "scripts": { + "test": "node ./node_modules/.bin/mocha test", + "prepublish": "gulp dist" + }, + "author": "Scott Puleo ", + "files": [ + "index.js", + "dist/object_hash.js" + ], + "license": "MIT", + "devDependencies": { + "browserify": "^16.2.3", + "gulp": "^4.0.0", + "gulp-browserify": "^0.5.1", + "gulp-coveralls": "^0.1.4", + "gulp-exec": "^3.0.1", + "gulp-istanbul": "^1.1.3", + "gulp-jshint": "^2.0.0", + "gulp-mocha": "^5.0.0", + "gulp-rename": "^1.2.0", + "gulp-replace": "^1.0.0", + "gulp-uglify": "^3.0.0", + "jshint": "^2.8.0", + "jshint-stylish": "^2.1.0", + "karma": "^4.2.0", + "karma-chrome-launcher": "^2.2.0", + "karma-mocha": "^1.3.0", + "mocha": "^6.2.0" + }, + "engines": { + "node": ">= 6" + }, + "main": "./index.js", + "browser": "./dist/object_hash.js" +} diff --git a/node_modules/object-hash/readme.markdown b/node_modules/object-hash/readme.markdown new file mode 100644 index 0000000..c507cf8 --- /dev/null +++ b/node_modules/object-hash/readme.markdown @@ -0,0 +1,198 @@ +# object-hash + +Generate hashes from objects and values in node and the browser. Uses node.js +crypto module for hashing. Supports SHA1 and many others (depending on the platform) +as well as custom streams (e.g. CRC32). + +[![NPM](https://nodei.co/npm/object-hash.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/object-hash) + +[![Travis CI](https://secure.travis-ci.org/puleos/object-hash.png?branch=master)](https://secure.travis-ci.org/puleos/object-hash?branch=master) +[![Coverage Status](https://coveralls.io/repos/puleos/object-hash/badge.svg?branch=master&service=github)](https://coveralls.io/github/puleos/object-hash?branch=master) + +* Hash values of any type. +* Supports a keys only option for grouping similar objects with different values. + +```js +var hash = require('object-hash'); + +hash({foo: 'bar'}) // => '67b69634f9880a282c14a0f0cb7ba20cf5d677e9' +hash([1, 2, 2.718, 3.14159]) // => '136b9b88375971dff9f1af09d7356e3e04281951' +``` + +## Versioning Disclaimer + +Starting with version `1.1.8` (released April 2017), new versions will consider +the exact returned hash part of the API contract, i.e. changes that will affect +hash values will be considered `semver-major`. Previous versions may violate +that expectation. + +For more information, see [this discussion](https://github.com/puleos/object-hash/issues/30). + +## hash(value, options) + +Generate a hash from any object or type. Defaults to sha1 with hex encoding. + +* `algorithm` hash algo to be used: 'sha1', 'md5', 'passthrough'. default: sha1 + * This supports the algorithms returned by `crypto.getHashes()`. Note that the default of SHA-1 is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired. + * This also supports the `passthrough` algorith, which will return the information that would otherwise have been hashed. +* `excludeValues` {true|false} hash object keys, values ignored. default: false +* `encoding` hash encoding, supports 'buffer', 'hex', 'binary', 'base64'. default: hex +* `ignoreUnknown` {true|*false} ignore unknown object types. default: false +* `replacer` optional function that replaces values before hashing. default: accept all values +* `respectFunctionProperties` {true|false} Whether properties on functions are considered when hashing. default: true +* `respectFunctionNames` {true|false} consider `name` property of functions for hashing. default: true +* `respectType` {true|false} Whether special type attributes (`.prototype`, `.__proto__`, `.constructor`) + are hashed. default: true +* `unorderedArrays` {true|false} Sort all arrays before hashing. Note that this affects *all* collections, + i.e. including typed arrays, Sets, Maps, etc. default: false +* `unorderedSets` {true|false} Sort `Set` and `Map` instances before hashing, i.e. make + `hash(new Set([1, 2])) == hash(new Set([2, 1]))` return `true`. default: true +* `unorderedObjects` {true|false} Sort objects before hashing, i.e. make `hash({ x: 1, y: 2 }) === hash({ y: 2, x: 1 })`. default: true +* `excludeKeys` optional function for excluding specific key(s) from hashing, if true is returned then exclude from hash. default: include all keys + +## hash.sha1(value) + +Hash using the sha1 algorithm. + +Note that SHA-1 is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired. + +*Sugar method, equivalent to* `hash(value, {algorithm: 'sha1'})` + +## hash.keys(value) + +Hash object keys using the sha1 algorithm, values ignored. + +*Sugar method, equivalent to* `hash(value, {excludeValues: true})` + +## hash.MD5(value) + +Hash using the md5 algorithm. + +Note that the MD5 algorithm is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired. + +*Sugar method, equivalent to* `hash(value, {algorithm: 'md5'})` + +## hash.keysMD5(value) + +Hash object keys using the md5 algorithm, values ignored. + +Note that the MD5 algorithm is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired. + +*Sugar method, equivalent to* `hash(value, {algorithm: 'md5', excludeValues: true})` + +## hash.writeToStream(value, [options,] stream) + +Write the information that would otherwise have been hashed to a stream, e.g.: + +```js +hash.writeToStream({foo: 'bar', a: 42}, {respectType: false}, process.stdout) +// => e.g. 'object:a:number:42foo:string:bar' +``` + +## Installation + +node: + +```js +npm install object-hash +``` + +browser: */dist/object_hash.js* + +```html + + + +``` + +## Example usage + +```js +var hash = require('object-hash'); + +var peter = { name: 'Peter', stapler: false, friends: ['Joanna', 'Michael', 'Samir'] }; +var michael = { name: 'Michael', stapler: false, friends: ['Peter', 'Samir'] }; +var bob = { name: 'Bob', stapler: true, friends: [] }; + +/*** + * sha1 hex encoding (default) + */ +hash(peter); +// 14fa461bf4b98155e82adc86532938553b4d33a9 +hash(michael); +// 4b2b30e27699979ce46714253bc2213010db039c +hash(bob); +// 38d96106bc8ef3d8bd369b99bb6972702c9826d5 + +/*** + * hash object keys, values ignored + */ +hash(peter, { excludeValues: true }); +// 48f370a772c7496f6c9d2e6d92e920c87dd00a5c +hash(michael, { excludeValues: true }); +// 48f370a772c7496f6c9d2e6d92e920c87dd00a5c +hash.keys(bob); +// 48f370a772c7496f6c9d2e6d92e920c87dd00a5c + +/*** + * hash object, ignore specific key(s) + */ +hash(peter, { excludeKeys: function(key) { + if ( key === 'friends') { + return true; + } + return false; + } +}); +// 66b7d7e64871aa9fda1bdc8e88a28df797648d80 + +/*** + * md5 base64 encoding + */ +hash(peter, { algorithm: 'md5', encoding: 'base64' }); +// 6rkWaaDiG3NynWw4svGH7g== +hash(michael, { algorithm: 'md5', encoding: 'base64' }); +// djXaWpuWVJeOF8Sb6SFFNg== +hash(bob, { algorithm: 'md5', encoding: 'base64' }); +// lFzkw/IJ8/12jZI0rQeS3w== +``` + +## Legacy Browser Support + +IE <= 8 and Opera <= 11 support dropped in version 0.3.0. If you require +legacy browser support you must either use an ES5 shim or use version 0.2.5 +of this module. + +## Development + +```sh-session +git clone https://github.com/puleos/object-hash +``` + +## Node Docker Wrapper + +If you want to stand this up in a docker container, you should take at look +at the [![node-object-hash](https://github.com/bean5/node-object-hash)](https://github.com/bean5/node-object-hash) project. + +### gulp tasks + +* `gulp watch` (default) watch files, test and lint on change/add +* `gulp test` unit tests +* `gulp karma` browser unit tests +* `gulp lint` jshint +* `gulp dist` create browser version in /dist + +## License + +MIT + +## Changelog + +### v2.0.0 + +Only Node.js versions `>= 6.0.0` are being tested in CI now. +No other breaking changes were introduced. diff --git a/node_modules/package-json-from-dist/LICENSE.md b/node_modules/package-json-from-dist/LICENSE.md new file mode 100644 index 0000000..881248b --- /dev/null +++ b/node_modules/package-json-from-dist/LICENSE.md @@ -0,0 +1,63 @@ +All packages under `src/` are licensed according to the terms in +their respective `LICENSE` or `LICENSE.md` files. + +The remainder of this project is licensed under the Blue Oak +Model License, as follows: + +----- + +# Blue Oak Model License + +Version 1.0.0 + +## Purpose + +This license gives everyone as much permission to work with +this software as possible, while protecting contributors +from liability. + +## Acceptance + +In order to receive this license, you must agree to its +rules. The rules of this license are both obligations +under that agreement and conditions to your license. +You must not do anything with this software that triggers +a rule that you cannot or will not follow. + +## Copyright + +Each contributor licenses you to do everything with this +software that would otherwise infringe that contributor's +copyright in it. + +## Notices + +You must ensure that everyone who gets a copy of +any part of this software from you, with or without +changes, also gets the text of this license or a link to +. + +## Excuse + +If anyone notifies you in writing that you have not +complied with [Notices](#notices), you can keep your +license by taking all practical steps to comply within 30 +days after the notice. If you do not do so, your license +ends immediately. + +## Patent + +Each contributor licenses you to do everything with this +software that would otherwise infringe any patent claims +they can license or become able to license. + +## Reliability + +No contributor can revoke this license. + +## No Liability + +***As far as the law allows, this software comes as is, +without any warranty or condition, and no contributor +will be liable to anyone for any damages related to this +software or this license, under any kind of legal claim.*** diff --git a/node_modules/package-json-from-dist/README.md b/node_modules/package-json-from-dist/README.md new file mode 100644 index 0000000..a9e1344 --- /dev/null +++ b/node_modules/package-json-from-dist/README.md @@ -0,0 +1,110 @@ +# package-json-from-dist + +Sometimes you want to load the `package.json` into your +TypeScript program, and it's tempting to just `import +'../package.json'`, since that seems to work. + +However, this requires `tsc` to make an entire copy of your +`package.json` file into the `dist` folder, which is a problem if +you're using something like +[tshy](https://github.com/isaacs/tshy), which uses the +`package.json` file in dist for another purpose. Even when that +does work, it's asking the module system to do a bunch of extra +fs system calls, just to load a version number or something. (See +[this issue](https://github.com/isaacs/tshy/issues/61).) + +This module helps by just finding the package.json file +appropriately, and reading and parsing it in the most normal +fashion. + +## Caveats + +This _only_ works if your code builds into a target folder called +`dist`, which is in the root of the package. It also requires +that you do not have a folder named `node_modules` anywhere +within your dev environment, or else it'll get the wrong answers +there. (But, at least, that'll be in dev, so you're pretty likely +to notice.) + +If you build to some other location, then you'll need a different +approach. (Feel free to fork this module and make it your own, or +just put the code right inline, there's not much of it.) + +## USAGE + +```js +// src/index.ts +import { + findPackageJson, + loadPackageJson, +} from 'package-json-from-dist' + +const pj = findPackageJson(import.meta.url) +console.log(`package.json found at ${pj}`) + +const pkg = loadPackageJson(import.meta.url) +console.log(`Hello from ${pkg.name}@${pkg.version}`) +``` + +If your module is not directly in the `./src` folder, then you need +to specify the path that you would expect to find the +`package.json` when it's _not_ built to the `dist` folder. + +```js +// src/components/something.ts +import { + findPackageJson, + loadPackageJson, +} from 'package-json-from-dist' + +const pj = findPackageJson(import.meta.url, '../../package.json') +console.log(`package.json found at ${pj}`) + +const pkg = loadPackageJson(import.meta.url, '../../package.json') +console.log(`Hello from ${pkg.name}@${pkg.version}`) +``` + +When running from CommmonJS, use `__filename` instead of +`import.meta.url`. + +```js +// src/index.cts +import { + findPackageJson, + loadPackageJson, +} from 'package-json-from-dist' + +const pj = findPackageJson(__filename) +console.log(`package.json found at ${pj}`) + +const pkg = loadPackageJson(__filename) +console.log(`Hello from ${pkg.name}@${pkg.version}`) +``` + +Since [tshy](https://github.com/isaacs/tshy) builds _both_ +CommonJS and ESM by default, you may find that you need a +CommonJS override and some `//@ts-ignore` magic to make it work. + +`src/pkg.ts`: + +```js +import { + findPackageJson, + loadPackageJson, +} from 'package-json-from-dist' +//@ts-ignore +export const pkg = loadPackageJson(import.meta.url) +//@ts-ignore +export const pj = findPackageJson(import.meta.url) +``` + +`src/pkg-cjs.cts`: + +```js +import { + findPackageJson, + loadPackageJson, +} from 'package-json-from-dist' +export const pkg = loadPackageJson(__filename) +export const pj = findPackageJson(__filename) +``` diff --git a/node_modules/package-json-from-dist/dist/commonjs/index.d.ts b/node_modules/package-json-from-dist/dist/commonjs/index.d.ts new file mode 100644 index 0000000..d486ffd --- /dev/null +++ b/node_modules/package-json-from-dist/dist/commonjs/index.d.ts @@ -0,0 +1,89 @@ +/** + * Find the package.json file, either from a TypeScript file somewhere not + * in a 'dist' folder, or a built and/or installed 'dist' folder. + * + * Note: this *only* works if you build your code into `'./dist'`, and that the + * source path does not also contain `'dist'`! If you don't build into + * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will + * not work properly! + * + * The default `pathFromSrc` option assumes that the calling code lives one + * folder below the root of the package. Otherwise, it must be specified. + * + * Example: + * + * ```ts + * // src/index.ts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(import.meta.url) + * console.log(`package.json found at ${pj}`) + * ``` + * + * If the caller is deeper within the project source, then you must provide + * the appropriate fallback path: + * + * ```ts + * // src/components/something.ts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(import.meta.url, '../../package.json') + * console.log(`package.json found at ${pj}`) + * ``` + * + * When running from CommmonJS, use `__filename` instead of `import.meta.url` + * + * ```ts + * // src/index.cts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(__filename) + * console.log(`package.json found at ${pj}`) + * ``` + */ +export declare const findPackageJson: (from: string | URL, pathFromSrc?: string) => string; +/** + * Load the package.json file, either from a TypeScript file somewhere not + * in a 'dist' folder, or a built and/or installed 'dist' folder. + * + * Note: this *only* works if you build your code into `'./dist'`, and that the + * source path does not also contain `'dist'`! If you don't build into + * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will + * not work properly! + * + * The default `pathFromSrc` option assumes that the calling code lives one + * folder below the root of the package. Otherwise, it must be specified. + * + * Example: + * + * ```ts + * // src/index.ts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(import.meta.url) + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + * + * If the caller is deeper within the project source, then you must provide + * the appropriate fallback path: + * + * ```ts + * // src/components/something.ts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(import.meta.url, '../../package.json') + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + * + * When running from CommmonJS, use `__filename` instead of `import.meta.url` + * + * ```ts + * // src/index.cts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(__filename) + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + */ +export declare const loadPackageJson: (from: string | URL, pathFromSrc?: string) => any; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/package-json-from-dist/dist/commonjs/index.d.ts.map b/node_modules/package-json-from-dist/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000..ca3e21c --- /dev/null +++ b/node_modules/package-json-from-dist/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,eAAO,MAAM,eAAe,SACpB,MAAM,GAAG,GAAG,gBACL,MAAM,KAClB,MAsCF,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,eAAO,MAAM,eAAe,SACpB,MAAM,GAAG,GAAG,gBACL,MAAM,QAEiD,CAAA"} \ No newline at end of file diff --git a/node_modules/package-json-from-dist/dist/commonjs/index.js b/node_modules/package-json-from-dist/dist/commonjs/index.js new file mode 100644 index 0000000..b966ac9 --- /dev/null +++ b/node_modules/package-json-from-dist/dist/commonjs/index.js @@ -0,0 +1,134 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.loadPackageJson = exports.findPackageJson = void 0; +const node_fs_1 = require("node:fs"); +const node_path_1 = require("node:path"); +const node_url_1 = require("node:url"); +const NM = `${node_path_1.sep}node_modules${node_path_1.sep}`; +const STORE = `.store${node_path_1.sep}`; +const PKG = `${node_path_1.sep}package${node_path_1.sep}`; +const DIST = `${node_path_1.sep}dist${node_path_1.sep}`; +/** + * Find the package.json file, either from a TypeScript file somewhere not + * in a 'dist' folder, or a built and/or installed 'dist' folder. + * + * Note: this *only* works if you build your code into `'./dist'`, and that the + * source path does not also contain `'dist'`! If you don't build into + * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will + * not work properly! + * + * The default `pathFromSrc` option assumes that the calling code lives one + * folder below the root of the package. Otherwise, it must be specified. + * + * Example: + * + * ```ts + * // src/index.ts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(import.meta.url) + * console.log(`package.json found at ${pj}`) + * ``` + * + * If the caller is deeper within the project source, then you must provide + * the appropriate fallback path: + * + * ```ts + * // src/components/something.ts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(import.meta.url, '../../package.json') + * console.log(`package.json found at ${pj}`) + * ``` + * + * When running from CommmonJS, use `__filename` instead of `import.meta.url` + * + * ```ts + * // src/index.cts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(__filename) + * console.log(`package.json found at ${pj}`) + * ``` + */ +const findPackageJson = (from, pathFromSrc = '../package.json') => { + const f = typeof from === 'object' || from.startsWith('file://') ? + (0, node_url_1.fileURLToPath)(from) + : from; + const __dirname = (0, node_path_1.dirname)(f); + const nms = __dirname.lastIndexOf(NM); + if (nms !== -1) { + // inside of node_modules. find the dist directly under package name. + const nm = __dirname.substring(0, nms + NM.length); + const pkgDir = __dirname.substring(nms + NM.length); + // affordance for yarn berry, which puts package contents in + // '.../node_modules/.store/${id}-${hash}/package/...' + if (pkgDir.startsWith(STORE)) { + const pkg = pkgDir.indexOf(PKG, STORE.length); + if (pkg) { + return (0, node_path_1.resolve)(nm, pkgDir.substring(0, pkg + PKG.length), 'package.json'); + } + } + const pkgName = pkgDir.startsWith('@') ? + pkgDir.split(node_path_1.sep, 2).join(node_path_1.sep) + : String(pkgDir.split(node_path_1.sep)[0]); + return (0, node_path_1.resolve)(nm, pkgName, 'package.json'); + } + else { + // see if we are in a dist folder. + const d = __dirname.lastIndexOf(DIST); + if (d !== -1) { + return (0, node_path_1.resolve)(__dirname.substring(0, d), 'package.json'); + } + else { + return (0, node_path_1.resolve)(__dirname, pathFromSrc); + } + } +}; +exports.findPackageJson = findPackageJson; +/** + * Load the package.json file, either from a TypeScript file somewhere not + * in a 'dist' folder, or a built and/or installed 'dist' folder. + * + * Note: this *only* works if you build your code into `'./dist'`, and that the + * source path does not also contain `'dist'`! If you don't build into + * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will + * not work properly! + * + * The default `pathFromSrc` option assumes that the calling code lives one + * folder below the root of the package. Otherwise, it must be specified. + * + * Example: + * + * ```ts + * // src/index.ts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(import.meta.url) + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + * + * If the caller is deeper within the project source, then you must provide + * the appropriate fallback path: + * + * ```ts + * // src/components/something.ts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(import.meta.url, '../../package.json') + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + * + * When running from CommmonJS, use `__filename` instead of `import.meta.url` + * + * ```ts + * // src/index.cts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(__filename) + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + */ +const loadPackageJson = (from, pathFromSrc = '../package.json') => JSON.parse((0, node_fs_1.readFileSync)((0, exports.findPackageJson)(from, pathFromSrc), 'utf8')); +exports.loadPackageJson = loadPackageJson; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/package-json-from-dist/dist/commonjs/index.js.map b/node_modules/package-json-from-dist/dist/commonjs/index.js.map new file mode 100644 index 0000000..2fb5d23 --- /dev/null +++ b/node_modules/package-json-from-dist/dist/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,qCAAsC;AACtC,yCAAiD;AACjD,uCAAwC;AAExC,MAAM,EAAE,GAAG,GAAG,eAAG,eAAe,eAAG,EAAE,CAAA;AACrC,MAAM,KAAK,GAAG,SAAS,eAAG,EAAE,CAAA;AAC5B,MAAM,GAAG,GAAG,GAAG,eAAG,UAAU,eAAG,EAAE,CAAA;AACjC,MAAM,IAAI,GAAG,GAAG,eAAG,OAAO,eAAG,EAAE,CAAA;AAE/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACI,MAAM,eAAe,GAAG,CAC7B,IAAkB,EAClB,cAAsB,iBAAiB,EAC/B,EAAE;IACV,MAAM,CAAC,GACL,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC;QACtD,IAAA,wBAAa,EAAC,IAAI,CAAC;QACrB,CAAC,CAAC,IAAI,CAAA;IACR,MAAM,SA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,mBAAO,EAAC,SAAS,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,cAAc,CAAC,CAAA;QAC3D,CAAC;aAAM,CAAC;YACN,OAAO,IAAA,mBAAO,EAAC,SAAS,EAAE,WAAW,CAAC,CAAA;QACxC,CAAC;IACH,CAAC;AACH,CAAC,CAAA;AAzCY,QAAA,eAAe,mBAyC3B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACI,MAAM,eAAe,GAAG,CAC7B,IAAkB,EAClB,cAAsB,iBAAiB,EACvC,EAAE,CACF,IAAI,CAAC,KAAK,CAAC,IAAA,sBAAY,EAAC,IAAA,uBAAe,EAAC,IAAI,EAAE,WAAW,CAAC,EAAE,MAAM,CAAC,CAAC,CAAA;AAJzD,QAAA,eAAe,mBAI0C","sourcesContent":["import { readFileSync } from 'node:fs'\nimport { dirname, resolve, sep } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst NM = `${sep}node_modules${sep}`\nconst STORE = `.store${sep}`\nconst PKG = `${sep}package${sep}`\nconst DIST = `${sep}dist${sep}`\n\n/**\n * Find the package.json file, either from a TypeScript file somewhere not\n * in a 'dist' folder, or a built and/or installed 'dist' folder.\n *\n * Note: this *only* works if you build your code into `'./dist'`, and that the\n * source path does not also contain `'dist'`! If you don't build into\n * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will\n * not work properly!\n *\n * The default `pathFromSrc` option assumes that the calling code lives one\n * folder below the root of the package. Otherwise, it must be specified.\n *\n * Example:\n *\n * ```ts\n * // src/index.ts\n * import { findPackageJson } from 'package-json-from-dist'\n *\n * const pj = findPackageJson(import.meta.url)\n * console.log(`package.json found at ${pj}`)\n * ```\n *\n * If the caller is deeper within the project source, then you must provide\n * the appropriate fallback path:\n *\n * ```ts\n * // src/components/something.ts\n * import { findPackageJson } from 'package-json-from-dist'\n *\n * const pj = findPackageJson(import.meta.url, '../../package.json')\n * console.log(`package.json found at ${pj}`)\n * ```\n *\n * When running from CommmonJS, use `__filename` instead of `import.meta.url`\n *\n * ```ts\n * // src/index.cts\n * import { findPackageJson } from 'package-json-from-dist'\n *\n * const pj = findPackageJson(__filename)\n * console.log(`package.json found at ${pj}`)\n * ```\n */\nexport const findPackageJson = (\n from: string | URL,\n pathFromSrc: string = '../package.json',\n): string => {\n const f =\n typeof from === 'object' || from.startsWith('file://') ?\n fileURLToPath(from)\n : from\n const __dirname = dirname(f)\n\n const nms = __dirname.lastIndexOf(NM)\n if (nms !== -1) {\n // inside of node_modules. find the dist directly under package name.\n const nm = __dirname.substring(0, nms + NM.length)\n const pkgDir = __dirname.substring(nms + NM.length)\n // affordance for yarn berry, which puts package contents in\n // '.../node_modules/.store/${id}-${hash}/package/...'\n if (pkgDir.startsWith(STORE)) {\n const pkg = pkgDir.indexOf(PKG, STORE.length)\n if (pkg) {\n return resolve(\n nm,\n pkgDir.substring(0, pkg + PKG.length),\n 'package.json',\n )\n }\n }\n const pkgName =\n pkgDir.startsWith('@') ?\n pkgDir.split(sep, 2).join(sep)\n : String(pkgDir.split(sep)[0])\n return resolve(nm, pkgName, 'package.json')\n } else {\n // see if we are in a dist folder.\n const d = __dirname.lastIndexOf(DIST)\n if (d !== -1) {\n return resolve(__dirname.substring(0, d), 'package.json')\n } else {\n return resolve(__dirname, pathFromSrc)\n }\n }\n}\n\n/**\n * Load the package.json file, either from a TypeScript file somewhere not\n * in a 'dist' folder, or a built and/or installed 'dist' folder.\n *\n * Note: this *only* works if you build your code into `'./dist'`, and that the\n * source path does not also contain `'dist'`! If you don't build into\n * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will\n * not work properly!\n *\n * The default `pathFromSrc` option assumes that the calling code lives one\n * folder below the root of the package. Otherwise, it must be specified.\n *\n * Example:\n *\n * ```ts\n * // src/index.ts\n * import { loadPackageJson } from 'package-json-from-dist'\n *\n * const pj = loadPackageJson(import.meta.url)\n * console.log(`Hello from ${pj.name}@${pj.version}`)\n * ```\n *\n * If the caller is deeper within the project source, then you must provide\n * the appropriate fallback path:\n *\n * ```ts\n * // src/components/something.ts\n * import { loadPackageJson } from 'package-json-from-dist'\n *\n * const pj = loadPackageJson(import.meta.url, '../../package.json')\n * console.log(`Hello from ${pj.name}@${pj.version}`)\n * ```\n *\n * When running from CommmonJS, use `__filename` instead of `import.meta.url`\n *\n * ```ts\n * // src/index.cts\n * import { loadPackageJson } from 'package-json-from-dist'\n *\n * const pj = loadPackageJson(__filename)\n * console.log(`Hello from ${pj.name}@${pj.version}`)\n * ```\n */\nexport const loadPackageJson = (\n from: string | URL,\n pathFromSrc: string = '../package.json',\n) =>\n JSON.parse(readFileSync(findPackageJson(from, pathFromSrc), 'utf8'))\n"]} \ No newline at end of file diff --git a/node_modules/package-json-from-dist/dist/commonjs/package.json b/node_modules/package-json-from-dist/dist/commonjs/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/node_modules/package-json-from-dist/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/package-json-from-dist/dist/esm/index.d.ts b/node_modules/package-json-from-dist/dist/esm/index.d.ts new file mode 100644 index 0000000..d486ffd --- /dev/null +++ b/node_modules/package-json-from-dist/dist/esm/index.d.ts @@ -0,0 +1,89 @@ +/** + * Find the package.json file, either from a TypeScript file somewhere not + * in a 'dist' folder, or a built and/or installed 'dist' folder. + * + * Note: this *only* works if you build your code into `'./dist'`, and that the + * source path does not also contain `'dist'`! If you don't build into + * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will + * not work properly! + * + * The default `pathFromSrc` option assumes that the calling code lives one + * folder below the root of the package. Otherwise, it must be specified. + * + * Example: + * + * ```ts + * // src/index.ts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(import.meta.url) + * console.log(`package.json found at ${pj}`) + * ``` + * + * If the caller is deeper within the project source, then you must provide + * the appropriate fallback path: + * + * ```ts + * // src/components/something.ts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(import.meta.url, '../../package.json') + * console.log(`package.json found at ${pj}`) + * ``` + * + * When running from CommmonJS, use `__filename` instead of `import.meta.url` + * + * ```ts + * // src/index.cts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(__filename) + * console.log(`package.json found at ${pj}`) + * ``` + */ +export declare const findPackageJson: (from: string | URL, pathFromSrc?: string) => string; +/** + * Load the package.json file, either from a TypeScript file somewhere not + * in a 'dist' folder, or a built and/or installed 'dist' folder. + * + * Note: this *only* works if you build your code into `'./dist'`, and that the + * source path does not also contain `'dist'`! If you don't build into + * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will + * not work properly! + * + * The default `pathFromSrc` option assumes that the calling code lives one + * folder below the root of the package. Otherwise, it must be specified. + * + * Example: + * + * ```ts + * // src/index.ts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(import.meta.url) + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + * + * If the caller is deeper within the project source, then you must provide + * the appropriate fallback path: + * + * ```ts + * // src/components/something.ts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(import.meta.url, '../../package.json') + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + * + * When running from CommmonJS, use `__filename` instead of `import.meta.url` + * + * ```ts + * // src/index.cts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(__filename) + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + */ +export declare const loadPackageJson: (from: string | URL, pathFromSrc?: string) => any; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/package-json-from-dist/dist/esm/index.d.ts.map b/node_modules/package-json-from-dist/dist/esm/index.d.ts.map new file mode 100644 index 0000000..ca3e21c --- /dev/null +++ b/node_modules/package-json-from-dist/dist/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,eAAO,MAAM,eAAe,SACpB,MAAM,GAAG,GAAG,gBACL,MAAM,KAClB,MAsCF,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,eAAO,MAAM,eAAe,SACpB,MAAM,GAAG,GAAG,gBACL,MAAM,QAEiD,CAAA"} \ No newline at end of file diff --git a/node_modules/package-json-from-dist/dist/esm/index.js b/node_modules/package-json-from-dist/dist/esm/index.js new file mode 100644 index 0000000..426ad3c --- /dev/null +++ b/node_modules/package-json-from-dist/dist/esm/index.js @@ -0,0 +1,129 @@ +import { readFileSync } from 'node:fs'; +import { dirname, resolve, sep } from 'node:path'; +import { fileURLToPath } from 'node:url'; +const NM = `${sep}node_modules${sep}`; +const STORE = `.store${sep}`; +const PKG = `${sep}package${sep}`; +const DIST = `${sep}dist${sep}`; +/** + * Find the package.json file, either from a TypeScript file somewhere not + * in a 'dist' folder, or a built and/or installed 'dist' folder. + * + * Note: this *only* works if you build your code into `'./dist'`, and that the + * source path does not also contain `'dist'`! If you don't build into + * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will + * not work properly! + * + * The default `pathFromSrc` option assumes that the calling code lives one + * folder below the root of the package. Otherwise, it must be specified. + * + * Example: + * + * ```ts + * // src/index.ts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(import.meta.url) + * console.log(`package.json found at ${pj}`) + * ``` + * + * If the caller is deeper within the project source, then you must provide + * the appropriate fallback path: + * + * ```ts + * // src/components/something.ts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(import.meta.url, '../../package.json') + * console.log(`package.json found at ${pj}`) + * ``` + * + * When running from CommmonJS, use `__filename` instead of `import.meta.url` + * + * ```ts + * // src/index.cts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(__filename) + * console.log(`package.json found at ${pj}`) + * ``` + */ +export const findPackageJson = (from, pathFromSrc = '../package.json') => { + const f = typeof from === 'object' || from.startsWith('file://') ? + fileURLToPath(from) + : from; + const __dirname = dirname(f); + const nms = __dirname.lastIndexOf(NM); + if (nms !== -1) { + // inside of node_modules. find the dist directly under package name. + const nm = __dirname.substring(0, nms + NM.length); + const pkgDir = __dirname.substring(nms + NM.length); + // affordance for yarn berry, which puts package contents in + // '.../node_modules/.store/${id}-${hash}/package/...' + if (pkgDir.startsWith(STORE)) { + const pkg = pkgDir.indexOf(PKG, STORE.length); + if (pkg) { + return resolve(nm, pkgDir.substring(0, pkg + PKG.length), 'package.json'); + } + } + const pkgName = pkgDir.startsWith('@') ? + pkgDir.split(sep, 2).join(sep) + : String(pkgDir.split(sep)[0]); + return resolve(nm, pkgName, 'package.json'); + } + else { + // see if we are in a dist folder. + const d = __dirname.lastIndexOf(DIST); + if (d !== -1) { + return resolve(__dirname.substring(0, d), 'package.json'); + } + else { + return resolve(__dirname, pathFromSrc); + } + } +}; +/** + * Load the package.json file, either from a TypeScript file somewhere not + * in a 'dist' folder, or a built and/or installed 'dist' folder. + * + * Note: this *only* works if you build your code into `'./dist'`, and that the + * source path does not also contain `'dist'`! If you don't build into + * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will + * not work properly! + * + * The default `pathFromSrc` option assumes that the calling code lives one + * folder below the root of the package. Otherwise, it must be specified. + * + * Example: + * + * ```ts + * // src/index.ts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(import.meta.url) + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + * + * If the caller is deeper within the project source, then you must provide + * the appropriate fallback path: + * + * ```ts + * // src/components/something.ts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(import.meta.url, '../../package.json') + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + * + * When running from CommmonJS, use `__filename` instead of `import.meta.url` + * + * ```ts + * // src/index.cts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(__filename) + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + */ +export const loadPackageJson = (from, pathFromSrc = '../package.json') => JSON.parse(readFileSync(findPackageJson(from, pathFromSrc), 'utf8')); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/package-json-from-dist/dist/esm/index.js.map b/node_modules/package-json-from-dist/dist/esm/index.js.map new file mode 100644 index 0000000..53b6ce7 --- /dev/null +++ b/node_modules/package-json-from-dist/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AACtC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAA;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAExC,MAAM,EAAE,GAAG,GAAG,GAAG,eAAe,GAAG,EAAE,CAAA;AACrC,MAAM,KAAK,GAAG,SAAS,GAAG,EAAE,CAAA;AAC5B,MAAM,GAAG,GAAG,GAAG,GAAG,UAAU,GAAG,EAAE,CAAA;AACjC,MAAM,IAAI,GAAG,GAAG,GAAG,OAAO,GAAG,EAAE,CAAA;AAE/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAC7B,IAAkB,EAClB,cAAsB,iBAAiB,EAC/B,EAAE;IACV,MAAM,CAAC,GACL,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC;QACtD,aAAa,CAAC,IAAI,CAAC;QACrB,CAAC,CAAC,IAAI,CAAA;IACR,MAAM,SAAS,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;IAE5B,MAAM,GAAG,GAAG,SAAS,CAAC,WAAW,CAAC,EAAE,CAAC,CAAA;IACrC,IAAI,GAAG,K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AC,CAAA;QACxC,CAAC;IACH,CAAC;AACH,CAAC,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAC7B,IAAkB,EAClB,cAAsB,iBAAiB,EACvC,EAAE,CACF,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,EAAE,MAAM,CAAC,CAAC,CAAA","sourcesContent":["import { readFileSync } from 'node:fs'\nimport { dirname, resolve, sep } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst NM = `${sep}node_modules${sep}`\nconst STORE = `.store${sep}`\nconst PKG = `${sep}package${sep}`\nconst DIST = `${sep}dist${sep}`\n\n/**\n * Find the package.json file, either from a TypeScript file somewhere not\n * in a 'dist' folder, or a built and/or installed 'dist' folder.\n *\n * Note: this *only* works if you build your code into `'./dist'`, and that the\n * source path does not also contain `'dist'`! If you don't build into\n * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will\n * not work properly!\n *\n * The default `pathFromSrc` option assumes that the calling code lives one\n * folder below the root of the package. Otherwise, it must be specified.\n *\n * Example:\n *\n * ```ts\n * // src/index.ts\n * import { findPackageJson } from 'package-json-from-dist'\n *\n * const pj = findPackageJson(import.meta.url)\n * console.log(`package.json found at ${pj}`)\n * ```\n *\n * If the caller is deeper within the project source, then you must provide\n * the appropriate fallback path:\n *\n * ```ts\n * // src/components/something.ts\n * import { findPackageJson } from 'package-json-from-dist'\n *\n * const pj = findPackageJson(import.meta.url, '../../package.json')\n * console.log(`package.json found at ${pj}`)\n * ```\n *\n * When running from CommmonJS, use `__filename` instead of `import.meta.url`\n *\n * ```ts\n * // src/index.cts\n * import { findPackageJson } from 'package-json-from-dist'\n *\n * const pj = findPackageJson(__filename)\n * console.log(`package.json found at ${pj}`)\n * ```\n */\nexport const findPackageJson = (\n from: string | URL,\n pathFromSrc: string = '../package.json',\n): string => {\n const f =\n typeof from === 'object' || from.startsWith('file://') ?\n fileURLToPath(from)\n : from\n const __dirname = dirname(f)\n\n const nms = __dirname.lastIndexOf(NM)\n if (nms !== -1) {\n // inside of node_modules. find the dist directly under package name.\n const nm = __dirname.substring(0, nms + NM.length)\n const pkgDir = __dirname.substring(nms + NM.length)\n // affordance for yarn berry, which puts package contents in\n // '.../node_modules/.store/${id}-${hash}/package/...'\n if (pkgDir.startsWith(STORE)) {\n const pkg = pkgDir.indexOf(PKG, STORE.length)\n if (pkg) {\n return resolve(\n nm,\n pkgDir.substring(0, pkg + PKG.length),\n 'package.json',\n )\n }\n }\n const pkgName =\n pkgDir.startsWith('@') ?\n pkgDir.split(sep, 2).join(sep)\n : String(pkgDir.split(sep)[0])\n return resolve(nm, pkgName, 'package.json')\n } else {\n // see if we are in a dist folder.\n const d = __dirname.lastIndexOf(DIST)\n if (d !== -1) {\n return resolve(__dirname.substring(0, d), 'package.json')\n } else {\n return resolve(__dirname, pathFromSrc)\n }\n }\n}\n\n/**\n * Load the package.json file, either from a TypeScript file somewhere not\n * in a 'dist' folder, or a built and/or installed 'dist' folder.\n *\n * Note: this *only* works if you build your code into `'./dist'`, and that the\n * source path does not also contain `'dist'`! If you don't build into\n * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will\n * not work properly!\n *\n * The default `pathFromSrc` option assumes that the calling code lives one\n * folder below the root of the package. Otherwise, it must be specified.\n *\n * Example:\n *\n * ```ts\n * // src/index.ts\n * import { loadPackageJson } from 'package-json-from-dist'\n *\n * const pj = loadPackageJson(import.meta.url)\n * console.log(`Hello from ${pj.name}@${pj.version}`)\n * ```\n *\n * If the caller is deeper within the project source, then you must provide\n * the appropriate fallback path:\n *\n * ```ts\n * // src/components/something.ts\n * import { loadPackageJson } from 'package-json-from-dist'\n *\n * const pj = loadPackageJson(import.meta.url, '../../package.json')\n * console.log(`Hello from ${pj.name}@${pj.version}`)\n * ```\n *\n * When running from CommmonJS, use `__filename` instead of `import.meta.url`\n *\n * ```ts\n * // src/index.cts\n * import { loadPackageJson } from 'package-json-from-dist'\n *\n * const pj = loadPackageJson(__filename)\n * console.log(`Hello from ${pj.name}@${pj.version}`)\n * ```\n */\nexport const loadPackageJson = (\n from: string | URL,\n pathFromSrc: string = '../package.json',\n) =>\n JSON.parse(readFileSync(findPackageJson(from, pathFromSrc), 'utf8'))\n"]} \ No newline at end of file diff --git a/node_modules/package-json-from-dist/dist/esm/package.json b/node_modules/package-json-from-dist/dist/esm/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/node_modules/package-json-from-dist/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/package-json-from-dist/package.json b/node_modules/package-json-from-dist/package.json new file mode 100644 index 0000000..a2d03c3 --- /dev/null +++ b/node_modules/package-json-from-dist/package.json @@ -0,0 +1,68 @@ +{ + "name": "package-json-from-dist", + "version": "1.0.1", + "description": "Load the local package.json from either src or dist folder", + "main": "./dist/commonjs/index.js", + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "files": [ + "dist" + ], + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --log-level warn", + "typedoc": "typedoc" + }, + "author": "Isaac Z. Schlueter (https://izs.me)", + "license": "BlueOak-1.0.0", + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/package-json-from-dist.git" + }, + "devDependencies": { + "@types/node": "^20.12.12", + "prettier": "^3.2.5", + "tap": "^18.5.3", + "typedoc": "^0.24.8", + "typescript": "^5.1.6", + "tshy": "^1.14.0" + }, + "prettier": { + "semi": false, + "printWidth": 70, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf", + "experimentalTernaries": true + }, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "types": "./dist/commonjs/index.d.ts", + "type": "module" +} diff --git a/node_modules/path-key/index.d.ts b/node_modules/path-key/index.d.ts new file mode 100644 index 0000000..7c575d1 --- /dev/null +++ b/node_modules/path-key/index.d.ts @@ -0,0 +1,40 @@ +/// + +declare namespace pathKey { + interface Options { + /** + Use a custom environment variables object. Default: [`process.env`](https://nodejs.org/api/process.html#process_process_env). + */ + readonly env?: {[key: string]: string | undefined}; + + /** + Get the PATH key for a specific platform. Default: [`process.platform`](https://nodejs.org/api/process.html#process_process_platform). + */ + readonly platform?: NodeJS.Platform; + } +} + +declare const pathKey: { + /** + Get the [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable key cross-platform. + + @example + ``` + import pathKey = require('path-key'); + + const key = pathKey(); + //=> 'PATH' + + const PATH = process.env[key]; + //=> '/usr/local/bin:/usr/bin:/bin' + ``` + */ + (options?: pathKey.Options): string; + + // TODO: Remove this for the next major release, refactor the whole definition to: + // declare function pathKey(options?: pathKey.Options): string; + // export = pathKey; + default: typeof pathKey; +}; + +export = pathKey; diff --git a/node_modules/path-key/index.js b/node_modules/path-key/index.js new file mode 100644 index 0000000..0cf6415 --- /dev/null +++ b/node_modules/path-key/index.js @@ -0,0 +1,16 @@ +'use strict'; + +const pathKey = (options = {}) => { + const environment = options.env || process.env; + const platform = options.platform || process.platform; + + if (platform !== 'win32') { + return 'PATH'; + } + + return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; +}; + +module.exports = pathKey; +// TODO: Remove this for the next major release +module.exports.default = pathKey; diff --git a/node_modules/path-key/license b/node_modules/path-key/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/path-key/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/path-key/package.json b/node_modules/path-key/package.json new file mode 100644 index 0000000..c8cbd38 --- /dev/null +++ b/node_modules/path-key/package.json @@ -0,0 +1,39 @@ +{ + "name": "path-key", + "version": "3.1.1", + "description": "Get the PATH environment variable key cross-platform", + "license": "MIT", + "repository": "sindresorhus/path-key", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "path", + "key", + "environment", + "env", + "variable", + "var", + "get", + "cross-platform", + "windows" + ], + "devDependencies": { + "@types/node": "^11.13.0", + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/path-key/readme.md b/node_modules/path-key/readme.md new file mode 100644 index 0000000..a9052d7 --- /dev/null +++ b/node_modules/path-key/readme.md @@ -0,0 +1,61 @@ +# path-key [![Build Status](https://travis-ci.org/sindresorhus/path-key.svg?branch=master)](https://travis-ci.org/sindresorhus/path-key) + +> Get the [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable key cross-platform + +It's usually `PATH`, but on Windows it can be any casing like `Path`... + + +## Install + +``` +$ npm install path-key +``` + + +## Usage + +```js +const pathKey = require('path-key'); + +const key = pathKey(); +//=> 'PATH' + +const PATH = process.env[key]; +//=> '/usr/local/bin:/usr/bin:/bin' +``` + + +## API + +### pathKey(options?) + +#### options + +Type: `object` + +##### env + +Type: `object`
+Default: [`process.env`](https://nodejs.org/api/process.html#process_process_env) + +Use a custom environment variables object. + +#### platform + +Type: `string`
+Default: [`process.platform`](https://nodejs.org/api/process.html#process_process_platform) + +Get the PATH key for a specific platform. + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/path-parse/LICENSE b/node_modules/path-parse/LICENSE new file mode 100644 index 0000000..810f3db --- /dev/null +++ b/node_modules/path-parse/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Javier Blanco + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/path-parse/README.md b/node_modules/path-parse/README.md new file mode 100644 index 0000000..05097f8 --- /dev/null +++ b/node_modules/path-parse/README.md @@ -0,0 +1,42 @@ +# path-parse [![Build Status](https://travis-ci.org/jbgutierrez/path-parse.svg?branch=master)](https://travis-ci.org/jbgutierrez/path-parse) + +> Node.js [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) [ponyfill](https://ponyfill.com). + +## Install + +``` +$ npm install --save path-parse +``` + +## Usage + +```js +var pathParse = require('path-parse'); + +pathParse('/home/user/dir/file.txt'); +//=> { +// root : "/", +// dir : "/home/user/dir", +// base : "file.txt", +// ext : ".txt", +// name : "file" +// } +``` + +## API + +See [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) docs. + +### pathParse(path) + +### pathParse.posix(path) + +The Posix specific version. + +### pathParse.win32(path) + +The Windows specific version. + +## License + +MIT © [Javier Blanco](http://jbgutierrez.info) diff --git a/node_modules/path-parse/index.js b/node_modules/path-parse/index.js new file mode 100644 index 0000000..f062d0a --- /dev/null +++ b/node_modules/path-parse/index.js @@ -0,0 +1,75 @@ +'use strict'; + +var isWindows = process.platform === 'win32'; + +// Regex to split a windows path into into [dir, root, basename, name, ext] +var splitWindowsRe = + /^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/; + +var win32 = {}; + +function win32SplitPath(filename) { + return splitWindowsRe.exec(filename).slice(1); +} + +win32.parse = function(pathString) { + if (typeof pathString !== 'string') { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = win32SplitPath(pathString); + if (!allParts || allParts.length !== 5) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + return { + root: allParts[1], + dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1), + base: allParts[2], + ext: allParts[4], + name: allParts[3] + }; +}; + + + +// Split a filename into [dir, root, basename, name, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/; +var posix = {}; + + +function posixSplitPath(filename) { + return splitPathRe.exec(filename).slice(1); +} + + +posix.parse = function(pathString) { + if (typeof pathString !== 'string') { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = posixSplitPath(pathString); + if (!allParts || allParts.length !== 5) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + + return { + root: allParts[1], + dir: allParts[0].slice(0, -1), + base: allParts[2], + ext: allParts[4], + name: allParts[3], + }; +}; + + +if (isWindows) + module.exports = win32.parse; +else /* posix */ + module.exports = posix.parse; + +module.exports.posix = posix.parse; +module.exports.win32 = win32.parse; diff --git a/node_modules/path-parse/package.json b/node_modules/path-parse/package.json new file mode 100644 index 0000000..36c23f8 --- /dev/null +++ b/node_modules/path-parse/package.json @@ -0,0 +1,33 @@ +{ + "name": "path-parse", + "version": "1.0.7", + "description": "Node.js path.parse() ponyfill", + "main": "index.js", + "scripts": { + "test": "node test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/jbgutierrez/path-parse.git" + }, + "keywords": [ + "path", + "paths", + "file", + "dir", + "parse", + "built-in", + "util", + "utils", + "core", + "ponyfill", + "polyfill", + "shim" + ], + "author": "Javier Blanco ", + "license": "MIT", + "bugs": { + "url": "https://github.com/jbgutierrez/path-parse/issues" + }, + "homepage": "https://github.com/jbgutierrez/path-parse#readme" +} diff --git a/node_modules/path-scurry/LICENSE.md b/node_modules/path-scurry/LICENSE.md new file mode 100644 index 0000000..c5402b9 --- /dev/null +++ b/node_modules/path-scurry/LICENSE.md @@ -0,0 +1,55 @@ +# Blue Oak Model License + +Version 1.0.0 + +## Purpose + +This license gives everyone as much permission to work with +this software as possible, while protecting contributors +from liability. + +## Acceptance + +In order to receive this license, you must agree to its +rules. The rules of this license are both obligations +under that agreement and conditions to your license. +You must not do anything with this software that triggers +a rule that you cannot or will not follow. + +## Copyright + +Each contributor licenses you to do everything with this +software that would otherwise infringe that contributor's +copyright in it. + +## Notices + +You must ensure that everyone who gets a copy of +any part of this software from you, with or without +changes, also gets the text of this license or a link to +. + +## Excuse + +If anyone notifies you in writing that you have not +complied with [Notices](#notices), you can keep your +license by taking all practical steps to comply within 30 +days after the notice. If you do not do so, your license +ends immediately. + +## Patent + +Each contributor licenses you to do everything with this +software that would otherwise infringe any patent claims +they can license or become able to license. + +## Reliability + +No contributor can revoke this license. + +## No Liability + +***As far as the law allows, this software comes as is, +without any warranty or condition, and no contributor +will be liable to anyone for any damages related to this +software or this license, under any kind of legal claim.*** diff --git a/node_modules/path-scurry/README.md b/node_modules/path-scurry/README.md new file mode 100644 index 0000000..b5cb495 --- /dev/null +++ b/node_modules/path-scurry/README.md @@ -0,0 +1,636 @@ +# path-scurry + +Extremely high performant utility for building tools that read +the file system, minimizing filesystem and path string munging +operations to the greatest degree possible. + +## Ugh, yet another file traversal thing on npm? + +Yes. None of the existing ones gave me exactly what I wanted. + +## Well what is it you wanted? + +While working on [glob](http://npm.im/glob), I found that I +needed a module to very efficiently manage the traversal over a +folder tree, such that: + +1. No `readdir()` or `stat()` would ever be called on the same + file or directory more than one time. +2. No `readdir()` calls would be made if we can be reasonably + sure that the path is not a directory. (Ie, a previous + `readdir()` or `stat()` covered the path, and + `ent.isDirectory()` is false.) +3. `path.resolve()`, `dirname()`, `basename()`, and other + string-parsing/munging operations are be minimized. This means + it has to track "provisional" child nodes that may not exist + (and if we find that they _don't_ exist, store that + information as well, so we don't have to ever check again). +4. The API is not limited to use as a stream/iterator/etc. There + are many cases where an API like node's `fs` is preferrable. +5. It's more important to prevent excess syscalls than to be up + to date, but it should be smart enough to know what it + _doesn't_ know, and go get it seamlessly when requested. +6. Do not blow up the JS heap allocation if operating on a + directory with a huge number of entries. +7. Handle all the weird aspects of Windows paths, like UNC paths + and drive letters and wrongway slashes, so that the consumer + can return canonical platform-specific paths without having to + parse or join or do any error-prone string munging. + +## PERFORMANCE + +JavaScript people throw around the word "blazing" a lot. I hope +that this module doesn't blaze anyone. But it does go very fast, +in the cases it's optimized for, if used properly. + +PathScurry provides ample opportunities to get extremely good +performance, as well as several options to trade performance for +convenience. + +Benchmarks can be run by executing `npm run bench`. + +As is always the case, doing more means going slower, doing less +means going faster, and there are trade offs between speed and +memory usage. + +PathScurry makes heavy use of [LRUCache](http://npm.im/lru-cache) +to efficiently cache whatever it can, and `Path` objects remain +in the graph for the lifetime of the walker, so repeated calls +with a single PathScurry object will be extremely fast. However, +adding items to a cold cache means "doing more", so in those +cases, we pay a price. Nothing is free, but every effort has been +made to reduce costs wherever possible. + +Also, note that a "cache as long as possible" approach means that +changes to the filesystem may not be reflected in the results of +repeated PathScurry operations. + +For resolving string paths, `PathScurry` ranges from 5-50 times +faster than `path.resolve` on repeated resolutions, but around +100 to 1000 times _slower_ on the first resolution. If your +program is spending a lot of time resolving the _same_ paths +repeatedly (like, thousands or millions of times), then this can +be beneficial. But both implementations are pretty fast, and +speeding up an infrequent operation from 4µs to 400ns is not +going to move the needle on your app's performance. + +For walking file system directory trees, a lot depends on how +often a given PathScurry object will be used, and also on the +walk method used. + +With default settings on a folder tree of 100,000 items, +consisting of around a 10-to-1 ratio of normal files to +directories, PathScurry performs comparably to +[@nodelib/fs.walk](http://npm.im/@nodelib/fs.walk), which is the +fastest and most reliable file system walker I could find. As far +as I can tell, it's almost impossible to go much faster in a +Node.js program, just based on how fast you can push syscalls out +to the fs thread pool. + +On my machine, that is about 1000-1200 completed walks per second +for async or stream walks, and around 500-600 walks per second +synchronously. + +In the warm cache state, PathScurry's performance increases +around 4x for async `for await` iteration, 10-15x faster for +streams and synchronous `for of` iteration, and anywhere from 30x +to 80x faster for the rest. + +``` +# walk 100,000 fs entries, 10/1 file/dir ratio +# operations / ms + New PathScurry object | Reuse PathScurry object + stream: 1112.589 | 13974.917 +sync stream: 492.718 | 15028.343 + async walk: 1095.648 | 32706.395 + sync walk: 527.632 | 46129.772 + async iter: 1288.821 | 5045.510 + sync iter: 498.496 | 17920.746 +``` + +A hand-rolled walk calling `entry.readdir()` and recursing +through the entries can benefit even more from caching, with +greater flexibility and without the overhead of streams or +generators. + +The cold cache state is still limited by the costs of file system +operations, but with a warm cache, the only bottleneck is CPU +speed and VM optimizations. Of course, in that case, some care +must be taken to ensure that you don't lose performance as a +result of silly mistakes, like calling `readdir()` on entries +that you know are not directories. + +``` +# manual recursive iteration functions + cold cache | warm cache +async: 1164.901 | 17923.320 + cb: 1101.127 | 40999.344 +zalgo: 1082.240 | 66689.936 + sync: 526.935 | 87097.591 +``` + +In this case, the speed improves by around 10-20x in the async +case, 40x in the case of using `entry.readdirCB` with protections +against synchronous callbacks, and 50-100x with callback +deferrals disabled, and _several hundred times faster_ for +synchronous iteration. + +If you can think of a case that is not covered in these +benchmarks, or an implementation that performs significantly +better than PathScurry, please [let me +know](https://github.com/isaacs/path-scurry/issues). + +## USAGE + +```ts +// hybrid module, load with either method +import { PathScurry, Path } from 'path-scurry' +// or: +const { PathScurry, Path } = require('path-scurry') + +// very simple example, say we want to find and +// delete all the .DS_Store files in a given path +// note that the API is very similar to just a +// naive walk with fs.readdir() +import { unlink } from 'fs/promises' + +// easy way, iterate over the directory and do the thing +const pw = new PathScurry(process.cwd()) +for await (const entry of pw) { + if (entry.isFile() && entry.name === '.DS_Store') { + unlink(entry.fullpath()) + } +} + +// here it is as a manual recursive method +const walk = async (entry: Path) => { + const promises: Promise = [] + // readdir doesn't throw on non-directories, it just doesn't + // return any entries, to save stack trace costs. + // Items are returned in arbitrary unsorted order + for (const child of await pw.readdir(entry)) { + // each child is a Path object + if (child.name === '.DS_Store' && child.isFile()) { + // could also do pw.resolve(entry, child.name), + // just like fs.readdir walking, but .fullpath is + // a *slightly* more efficient shorthand. + promises.push(unlink(child.fullpath())) + } else if (child.isDirectory()) { + promises.push(walk(child)) + } + } + return Promise.all(promises) +} + +walk(pw.cwd).then(() => { + console.log('all .DS_Store files removed') +}) + +const pw2 = new PathScurry('/a/b/c') // pw2.cwd is the Path for /a/b/c +const relativeDir = pw2.cwd.resolve('../x') // Path entry for '/a/b/x' +const relative2 = pw2.cwd.resolve('/a/b/d/../x') // same path, same entry +assert.equal(relativeDir, relative2) +``` + +## API + +[Full TypeDoc API](https://isaacs.github.io/path-scurry) + +There are platform-specific classes exported, but for the most +part, the default `PathScurry` and `Path` exports are what you +most likely need, unless you are testing behavior for other +platforms. + +Intended public API is documented here, but the full +documentation does include internal types, which should not be +accessed directly. + +### Interface `PathScurryOpts` + +The type of the `options` argument passed to the `PathScurry` +constructor. + +- `nocase`: Boolean indicating that file names should be compared + case-insensitively. Defaults to `true` on darwin and win32 + implementations, `false` elsewhere. + + **Warning** Performing case-insensitive matching on a + case-sensitive filesystem will result in occasionally very + bizarre behavior. Performing case-sensitive matching on a + case-insensitive filesystem may negatively impact performance. + +- `childrenCacheSize`: Number of child entries to cache, in order + to speed up `resolve()` and `readdir()` calls. Defaults to + `16 * 1024` (ie, `16384`). + + Setting it to a higher value will run the risk of JS heap + allocation errors on large directory trees. Setting it to `256` + or smaller will significantly reduce the construction time and + data consumption overhead, but with the downside of operations + being slower on large directory trees. Setting it to `0` will + mean that effectively no operations are cached, and this module + will be roughly the same speed as `fs` for file system + operations, and _much_ slower than `path.resolve()` for + repeated path resolution. + +- `fs` An object that will be used to override the default `fs` + methods. Any methods that are not overridden will use Node's + built-in implementations. + + - lstatSync + - readdir (callback `withFileTypes` Dirent variant, used for + readdirCB and most walks) + - readdirSync + - readlinkSync + - realpathSync + - promises: Object containing the following async methods: + - lstat + - readdir (Dirent variant only) + - readlink + - realpath + +### Interface `WalkOptions` + +The options object that may be passed to all walk methods. + +- `withFileTypes`: Boolean, default true. Indicates that `Path` + objects should be returned. Set to `false` to get string paths + instead. +- `follow`: Boolean, default false. Attempt to read directory + entries from symbolic links. Otherwise, only actual directories + are traversed. Regardless of this setting, a given target path + will only ever be walked once, meaning that a symbolic link to + a previously traversed directory will never be followed. + + Setting this imposes a slight performance penalty, because + `readlink` must be called on all symbolic links encountered, in + order to avoid infinite cycles. + +- `filter`: Function `(entry: Path) => boolean`. If provided, + will prevent the inclusion of any entry for which it returns a + falsey value. This will not prevent directories from being + traversed if they do not pass the filter, though it will + prevent the directories themselves from being included in the + results. By default, if no filter is provided, then all entries + are included in the results. +- `walkFilter`: Function `(entry: Path) => boolean`. If provided, + will prevent the traversal of any directory (or in the case of + `follow:true` symbolic links to directories) for which the + function returns false. This will not prevent the directories + themselves from being included in the result set. Use `filter` + for that. + +Note that TypeScript return types will only be inferred properly +from static analysis if the `withFileTypes` option is omitted, or +a constant `true` or `false` value. + +### Class `PathScurry` + +The main interface. Defaults to an appropriate class based on the +current platform. + +Use `PathScurryWin32`, `PathScurryDarwin`, or `PathScurryPosix` +if implementation-specific behavior is desired. + +All walk methods may be called with a `WalkOptions` argument to +walk over the object's current working directory with the +supplied options. + +#### `async pw.walk(entry?: string | Path | WalkOptions, opts?: WalkOptions)` + +Walk the directory tree according to the options provided, +resolving to an array of all entries found. + +#### `pw.walkSync(entry?: string | Path | WalkOptions, opts?: WalkOptions)` + +Walk the directory tree according to the options provided, +returning an array of all entries found. + +#### `pw.iterate(entry?: string | Path | WalkOptions, opts?: WalkOptions)` + +Iterate over the directory asynchronously, for use with `for +await of`. This is also the default async iterator method. + +#### `pw.iterateSync(entry?: string | Path | WalkOptions, opts?: WalkOptions)` + +Iterate over the directory synchronously, for use with `for of`. +This is also the default sync iterator method. + +#### `pw.stream(entry?: string | Path | WalkOptions, opts?: WalkOptions)` + +Return a [Minipass](http://npm.im/minipass) stream that emits +each entry or path string in the walk. Results are made available +asynchronously. + +#### `pw.streamSync(entry?: string | Path | WalkOptions, opts?: WalkOptions)` + +Return a [Minipass](http://npm.im/minipass) stream that emits +each entry or path string in the walk. Results are made available +synchronously, meaning that the walk will complete in a single +tick if the stream is fully consumed. + +#### `pw.cwd` + +Path object representing the current working directory for the +PathScurry. + +#### `pw.chdir(path: string)` + +Set the new effective current working directory for the scurry +object, so that `path.relative()` and `path.relativePosix()` +return values relative to the new cwd path. + +#### `pw.depth(path?: Path | string): number` + +Return the depth of the specified path (or the PathScurry cwd) +within the directory tree. + +Root entries have a depth of `0`. + +#### `pw.resolve(...paths: string[])` + +Caching `path.resolve()`. + +Significantly faster than `path.resolve()` if called repeatedly +with the same paths. Significantly slower otherwise, as it builds +out the cached Path entries. + +To get a `Path` object resolved from the `PathScurry`, use +`pw.cwd.resolve(path)`. Note that `Path.resolve` only takes a +single string argument, not multiple. + +#### `pw.resolvePosix(...paths: string[])` + +Caching `path.resolve()`, but always using posix style paths. + +This is identical to `pw.resolve(...paths)` on posix systems (ie, +everywhere except Windows). + +On Windows, it returns the full absolute UNC path using `/` +separators. Ie, instead of `'C:\\foo\\bar`, it would return +`//?/C:/foo/bar`. + +#### `pw.relative(path: string | Path): string` + +Return the relative path from the PathWalker cwd to the supplied +path string or entry. + +If the nearest common ancestor is the root, then an absolute path +is returned. + +#### `pw.relativePosix(path: string | Path): string` + +Return the relative path from the PathWalker cwd to the supplied +path string or entry, using `/` path separators. + +If the nearest common ancestor is the root, then an absolute path +is returned. + +On posix platforms (ie, all platforms except Windows), this is +identical to `pw.relative(path)`. + +On Windows systems, it returns the resulting string as a +`/`-delimited path. If an absolute path is returned (because the +target does not share a common ancestor with `pw.cwd`), then a +full absolute UNC path will be returned. Ie, instead of +`'C:\\foo\\bar`, it would return `//?/C:/foo/bar`. + +#### `pw.basename(path: string | Path): string` + +Return the basename of the provided string or Path. + +#### `pw.dirname(path: string | Path): string` + +Return the parent directory of the supplied string or Path. + +#### `async pw.readdir(dir = pw.cwd, opts = { withFileTypes: true })` + +Read the directory and resolve to an array of strings if +`withFileTypes` is explicitly set to `false` or Path objects +otherwise. + +Can be called as `pw.readdir({ withFileTypes: boolean })` as +well. + +Returns `[]` if no entries are found, or if any error occurs. + +Note that TypeScript return types will only be inferred properly +from static analysis if the `withFileTypes` option is omitted, or +a constant `true` or `false` value. + +#### `pw.readdirSync(dir = pw.cwd, opts = { withFileTypes: true })` + +Synchronous `pw.readdir()` + +#### `async pw.readlink(link = pw.cwd, opts = { withFileTypes: false })` + +Call `fs.readlink` on the supplied string or Path object, and +return the result. + +Can be called as `pw.readlink({ withFileTypes: boolean })` as +well. + +Returns `undefined` if any error occurs (for example, if the +argument is not a symbolic link), or a `Path` object if +`withFileTypes` is explicitly set to `true`, or a string +otherwise. + +Note that TypeScript return types will only be inferred properly +from static analysis if the `withFileTypes` option is omitted, or +a constant `true` or `false` value. + +#### `pw.readlinkSync(link = pw.cwd, opts = { withFileTypes: false })` + +Synchronous `pw.readlink()` + +#### `async pw.lstat(entry = pw.cwd)` + +Call `fs.lstat` on the supplied string or Path object, and fill +in as much information as possible, returning the updated `Path` +object. + +Returns `undefined` if the entry does not exist, or if any error +is encountered. + +Note that some `Stats` data (such as `ino`, `dev`, and `mode`) +will not be supplied. For those things, you'll need to call +`fs.lstat` yourself. + +#### `pw.lstatSync(entry = pw.cwd)` + +Synchronous `pw.lstat()` + +#### `pw.realpath(entry = pw.cwd, opts = { withFileTypes: false })` + +Call `fs.realpath` on the supplied string or Path object, and +return the realpath if available. + +Returns `undefined` if any error occurs. + +May be called as `pw.realpath({ withFileTypes: boolean })` to run +on `pw.cwd`. + +#### `pw.realpathSync(entry = pw.cwd, opts = { withFileTypes: false })` + +Synchronous `pw.realpath()` + +### Class `Path` implements [fs.Dirent](https://nodejs.org/docs/latest/api/fs.html#class-fsdirent) + +Object representing a given path on the filesystem, which may or +may not exist. + +Note that the actual class in use will be either `PathWin32` or +`PathPosix`, depending on the implementation of `PathScurry` in +use. They differ in the separators used to split and join path +strings, and the handling of root paths. + +In `PathPosix` implementations, paths are split and joined using +the `'/'` character, and `'/'` is the only root path ever in use. + +In `PathWin32` implementations, paths are split using either +`'/'` or `'\\'` and joined using `'\\'`, and multiple roots may +be in use based on the drives and UNC paths encountered. UNC +paths such as `//?/C:/` that identify a drive letter, will be +treated as an alias for the same root entry as their associated +drive letter (in this case `'C:\\'`). + +#### `path.name` + +Name of this file system entry. + +**Important**: _always_ test the path name against any test +string using the `isNamed` method, and not by directly comparing +this string. Otherwise, unicode path strings that the system sees +as identical will not be properly treated as the same path, +leading to incorrect behavior and possible security issues. + +#### `path.isNamed(name: string): boolean` + +Return true if the path is a match for the given path name. This +handles case sensitivity and unicode normalization. + +Note: even on case-sensitive systems, it is **not** safe to test +the equality of the `.name` property to determine whether a given +pathname matches, due to unicode normalization mismatches. + +Always use this method instead of testing the `path.name` +property directly. + +#### `path.isCWD` + +Set to true if this `Path` object is the current working +directory of the `PathScurry` collection that contains it. + +#### `path.getType()` + +Returns the type of the Path object, `'File'`, `'Directory'`, +etc. + +#### `path.isType(t: type)` + +Returns true if `is{t}()` returns true. + +For example, `path.isType('Directory')` is equivalent to +`path.isDirectory()`. + +#### `path.depth()` + +Return the depth of the Path entry within the directory tree. +Root paths have a depth of `0`. + +#### `path.fullpath()` + +The fully resolved path to the entry. + +#### `path.fullpathPosix()` + +The fully resolved path to the entry, using `/` separators. + +On posix systems, this is identical to `path.fullpath()`. On +windows, this will return a fully resolved absolute UNC path +using `/` separators. Eg, instead of `'C:\\foo\\bar'`, it will +return `'//?/C:/foo/bar'`. + +#### `path.isFile()`, `path.isDirectory()`, etc. + +Same as the identical `fs.Dirent.isX()` methods. + +#### `path.isUnknown()` + +Returns true if the path's type is unknown. Always returns true +when the path is known to not exist. + +#### `path.resolve(p: string)` + +Return a `Path` object associated with the provided path string +as resolved from the current Path object. + +#### `path.relative(): string` + +Return the relative path from the PathWalker cwd to the supplied +path string or entry. + +If the nearest common ancestor is the root, then an absolute path +is returned. + +#### `path.relativePosix(): string` + +Return the relative path from the PathWalker cwd to the supplied +path string or entry, using `/` path separators. + +If the nearest common ancestor is the root, then an absolute path +is returned. + +On posix platforms (ie, all platforms except Windows), this is +identical to `pw.relative(path)`. + +On Windows systems, it returns the resulting string as a +`/`-delimited path. If an absolute path is returned (because the +target does not share a common ancestor with `pw.cwd`), then a +full absolute UNC path will be returned. Ie, instead of +`'C:\\foo\\bar`, it would return `//?/C:/foo/bar`. + +#### `async path.readdir()` + +Return an array of `Path` objects found by reading the associated +path entry. + +If path is not a directory, or if any error occurs, returns `[]`, +and marks all children as provisional and non-existent. + +#### `path.readdirSync()` + +Synchronous `path.readdir()` + +#### `async path.readlink()` + +Return the `Path` object referenced by the `path` as a symbolic +link. + +If the `path` is not a symbolic link, or any error occurs, +returns `undefined`. + +#### `path.readlinkSync()` + +Synchronous `path.readlink()` + +#### `async path.lstat()` + +Call `lstat` on the path object, and fill it in with details +determined. + +If path does not exist, or any other error occurs, returns +`undefined`, and marks the path as "unknown" type. + +#### `path.lstatSync()` + +Synchronous `path.lstat()` + +#### `async path.realpath()` + +Call `realpath` on the path, and return a Path object +corresponding to the result, or `undefined` if any error occurs. + +#### `path.realpathSync()` + +Synchornous `path.realpath()` diff --git a/node_modules/path-scurry/dist/commonjs/index.d.ts b/node_modules/path-scurry/dist/commonjs/index.d.ts new file mode 100644 index 0000000..3ad4aa5 --- /dev/null +++ b/node_modules/path-scurry/dist/commonjs/index.d.ts @@ -0,0 +1,1116 @@ +/// +/// +/// +import { LRUCache } from 'lru-cache'; +import { posix, win32 } from 'node:path'; +import { Minipass } from 'minipass'; +import type { Dirent, Stats } from 'node:fs'; +/** + * An object that will be used to override the default `fs` + * methods. Any methods that are not overridden will use Node's + * built-in implementations. + * + * - lstatSync + * - readdir (callback `withFileTypes` Dirent variant, used for + * readdirCB and most walks) + * - readdirSync + * - readlinkSync + * - realpathSync + * - promises: Object containing the following async methods: + * - lstat + * - readdir (Dirent variant only) + * - readlink + * - realpath + */ +export interface FSOption { + lstatSync?: (path: string) => Stats; + readdir?: (path: string, options: { + withFileTypes: true; + }, cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any) => void; + readdirSync?: (path: string, options: { + withFileTypes: true; + }) => Dirent[]; + readlinkSync?: (path: string) => string; + realpathSync?: (path: string) => string; + promises?: { + lstat?: (path: string) => Promise; + readdir?: (path: string, options: { + withFileTypes: true; + }) => Promise; + readlink?: (path: string) => Promise; + realpath?: (path: string) => Promise; + [k: string]: any; + }; + [k: string]: any; +} +interface FSValue { + lstatSync: (path: string) => Stats; + readdir: (path: string, options: { + withFileTypes: true; + }, cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any) => void; + readdirSync: (path: string, options: { + withFileTypes: true; + }) => Dirent[]; + readlinkSync: (path: string) => string; + realpathSync: (path: string) => string; + promises: { + lstat: (path: string) => Promise; + readdir: (path: string, options: { + withFileTypes: true; + }) => Promise; + readlink: (path: string) => Promise; + realpath: (path: string) => Promise; + [k: string]: any; + }; + [k: string]: any; +} +export type Type = 'Unknown' | 'FIFO' | 'CharacterDevice' | 'Directory' | 'BlockDevice' | 'File' | 'SymbolicLink' | 'Socket'; +/** + * Options that may be provided to the Path constructor + */ +export interface PathOpts { + fullpath?: string; + relative?: string; + relativePosix?: string; + parent?: PathBase; + /** + * See {@link FSOption} + */ + fs?: FSOption; +} +/** + * An LRUCache for storing resolved path strings or Path objects. + * @internal + */ +export declare class ResolveCache extends LRUCache { + constructor(); +} +/** + * an LRUCache for storing child entries. + * @internal + */ +export declare class ChildrenCache extends LRUCache { + constructor(maxSize?: number); +} +/** + * Array of Path objects, plus a marker indicating the first provisional entry + * + * @internal + */ +export type Children = PathBase[] & { + provisional: number; +}; +declare const setAsCwd: unique symbol; +/** + * Path objects are sort of like a super-powered + * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent} + * + * Each one represents a single filesystem entry on disk, which may or may not + * exist. It includes methods for reading various types of information via + * lstat, readlink, and readdir, and caches all information to the greatest + * degree possible. + * + * Note that fs operations that would normally throw will instead return an + * "empty" value. This is in order to prevent excessive overhead from error + * stack traces. + */ +export declare abstract class PathBase implements Dirent { + #private; + /** + * the basename of this path + * + * **Important**: *always* test the path name against any test string + * usingthe {@link isNamed} method, and not by directly comparing this + * string. Otherwise, unicode path strings that the system sees as identical + * will not be properly treated as the same path, leading to incorrect + * behavior and possible security issues. + */ + name: string; + /** + * the Path entry corresponding to the path root. + * + * @internal + */ + root: PathBase; + /** + * All roots found within the current PathScurry family + * + * @internal + */ + roots: { + [k: string]: PathBase; + }; + /** + * a reference to the parent path, or undefined in the case of root entries + * + * @internal + */ + parent?: PathBase; + /** + * boolean indicating whether paths are compared case-insensitively + * @internal + */ + nocase: boolean; + /** + * boolean indicating that this path is the current working directory + * of the PathScurry collection that contains it. + */ + isCWD: boolean; + /** + * the string or regexp used to split paths. On posix, it is `'/'`, and on + * windows it is a RegExp matching either `'/'` or `'\\'` + */ + abstract splitSep: string | RegExp; + /** + * The path separator string to use when joining paths + */ + abstract sep: string; + get dev(): number | undefined; + get mode(): number | undefined; + get nlink(): number | undefined; + get uid(): number | undefined; + get gid(): number | undefined; + get rdev(): number | undefined; + get blksize(): number | undefined; + get ino(): number | undefined; + get size(): number | undefined; + get blocks(): number | undefined; + get atimeMs(): number | undefined; + get mtimeMs(): number | undefined; + get ctimeMs(): number | undefined; + get birthtimeMs(): number | undefined; + get atime(): Date | undefined; + get mtime(): Date | undefined; + get ctime(): Date | undefined; + get birthtime(): Date | undefined; + /** + * This property is for compatibility with the Dirent class as of + * Node v20, where Dirent['parentPath'] refers to the path of the + * directory that was passed to readdir. For root entries, it's the path + * to the entry itself. + */ + get parentPath(): string; + /** + * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively, + * this property refers to the *parent* path, not the path object itself. + */ + get path(): string; + /** + * Do not create new Path objects directly. They should always be accessed + * via the PathScurry class or other methods on the Path class. + * + * @internal + */ + constructor(name: string, type: number | undefined, root: PathBase | undefined, roots: { + [k: string]: PathBase; + }, nocase: boolean, children: ChildrenCache, opts: PathOpts); + /** + * Returns the depth of the Path object from its root. + * + * For example, a path at `/foo/bar` would have a depth of 2. + */ + depth(): number; + /** + * @internal + */ + abstract getRootString(path: string): string; + /** + * @internal + */ + abstract getRoot(rootPath: string): PathBase; + /** + * @internal + */ + abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase; + /** + * @internal + */ + childrenCache(): ChildrenCache; + /** + * Get the Path object referenced by the string path, resolved from this Path + */ + resolve(path?: string): PathBase; + /** + * Returns the cached children Path objects, if still available. If they + * have fallen out of the cache, then returns an empty array, and resets the + * READDIR_CALLED bit, so that future calls to readdir() will require an fs + * lookup. + * + * @internal + */ + children(): Children; + /** + * Resolves a path portion and returns or creates the child Path. + * + * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is + * `'..'`. + * + * This should not be called directly. If `pathPart` contains any path + * separators, it will lead to unsafe undefined behavior. + * + * Use `Path.resolve()` instead. + * + * @internal + */ + child(pathPart: string, opts?: PathOpts): PathBase; + /** + * The relative path from the cwd. If it does not share an ancestor with + * the cwd, then this ends up being equivalent to the fullpath() + */ + relative(): string; + /** + * The relative path from the cwd, using / as the path separator. + * If it does not share an ancestor with + * the cwd, then this ends up being equivalent to the fullpathPosix() + * On posix systems, this is identical to relative(). + */ + relativePosix(): string; + /** + * The fully resolved path string for this Path entry + */ + fullpath(): string; + /** + * On platforms other than windows, this is identical to fullpath. + * + * On windows, this is overridden to return the forward-slash form of the + * full UNC path. + */ + fullpathPosix(): string; + /** + * Is the Path of an unknown type? + * + * Note that we might know *something* about it if there has been a previous + * filesystem operation, for example that it does not exist, or is not a + * link, or whether it has child entries. + */ + isUnknown(): boolean; + isType(type: Type): boolean; + getType(): Type; + /** + * Is the Path a regular file? + */ + isFile(): boolean; + /** + * Is the Path a directory? + */ + isDirectory(): boolean; + /** + * Is the path a character device? + */ + isCharacterDevice(): boolean; + /** + * Is the path a block device? + */ + isBlockDevice(): boolean; + /** + * Is the path a FIFO pipe? + */ + isFIFO(): boolean; + /** + * Is the path a socket? + */ + isSocket(): boolean; + /** + * Is the path a symbolic link? + */ + isSymbolicLink(): boolean; + /** + * Return the entry if it has been subject of a successful lstat, or + * undefined otherwise. + * + * Does not read the filesystem, so an undefined result *could* simply + * mean that we haven't called lstat on it. + */ + lstatCached(): PathBase | undefined; + /** + * Return the cached link target if the entry has been the subject of a + * successful readlink, or undefined otherwise. + * + * Does not read the filesystem, so an undefined result *could* just mean we + * don't have any cached data. Only use it if you are very sure that a + * readlink() has been called at some point. + */ + readlinkCached(): PathBase | undefined; + /** + * Returns the cached realpath target if the entry has been the subject + * of a successful realpath, or undefined otherwise. + * + * Does not read the filesystem, so an undefined result *could* just mean we + * don't have any cached data. Only use it if you are very sure that a + * realpath() has been called at some point. + */ + realpathCached(): PathBase | undefined; + /** + * Returns the cached child Path entries array if the entry has been the + * subject of a successful readdir(), or [] otherwise. + * + * Does not read the filesystem, so an empty array *could* just mean we + * don't have any cached data. Only use it if you are very sure that a + * readdir() has been called recently enough to still be valid. + */ + readdirCached(): PathBase[]; + /** + * Return true if it's worth trying to readlink. Ie, we don't (yet) have + * any indication that readlink will definitely fail. + * + * Returns false if the path is known to not be a symlink, if a previous + * readlink failed, or if the entry does not exist. + */ + canReadlink(): boolean; + /** + * Return true if readdir has previously been successfully called on this + * path, indicating that cachedReaddir() is likely valid. + */ + calledReaddir(): boolean; + /** + * Returns true if the path is known to not exist. That is, a previous lstat + * or readdir failed to verify its existence when that would have been + * expected, or a parent entry was marked either enoent or enotdir. + */ + isENOENT(): boolean; + /** + * Return true if the path is a match for the given path name. This handles + * case sensitivity and unicode normalization. + * + * Note: even on case-sensitive systems, it is **not** safe to test the + * equality of the `.name` property to determine whether a given pathname + * matches, due to unicode normalization mismatches. + * + * Always use this method instead of testing the `path.name` property + * directly. + */ + isNamed(n: string): boolean; + /** + * Return the Path object corresponding to the target of a symbolic link. + * + * If the Path is not a symbolic link, or if the readlink call fails for any + * reason, `undefined` is returned. + * + * Result is cached, and thus may be outdated if the filesystem is mutated. + */ + readlink(): Promise; + /** + * Synchronous {@link PathBase.readlink} + */ + readlinkSync(): PathBase | undefined; + /** + * Call lstat() on this Path, and update all known information that can be + * determined. + * + * Note that unlike `fs.lstat()`, the returned value does not contain some + * information, such as `mode`, `dev`, `nlink`, and `ino`. If that + * information is required, you will need to call `fs.lstat` yourself. + * + * If the Path refers to a nonexistent file, or if the lstat call fails for + * any reason, `undefined` is returned. Otherwise the updated Path object is + * returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + */ + lstat(): Promise; + /** + * synchronous {@link PathBase.lstat} + */ + lstatSync(): PathBase | undefined; + /** + * Standard node-style callback interface to get list of directory entries. + * + * If the Path cannot or does not contain any children, then an empty array + * is returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + * + * @param cb The callback called with (er, entries). Note that the `er` + * param is somewhat extraneous, as all readdir() errors are handled and + * simply result in an empty set of entries being returned. + * @param allowZalgo Boolean indicating that immediately known results should + * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release + * zalgo at your peril, the dark pony lord is devious and unforgiving. + */ + readdirCB(cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any, allowZalgo?: boolean): void; + /** + * Return an array of known child entries. + * + * If the Path cannot or does not contain any children, then an empty array + * is returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + */ + readdir(): Promise; + /** + * synchronous {@link PathBase.readdir} + */ + readdirSync(): PathBase[]; + canReaddir(): boolean; + shouldWalk(dirs: Set, walkFilter?: (e: PathBase) => boolean): boolean; + /** + * Return the Path object corresponding to path as resolved + * by realpath(3). + * + * If the realpath call fails for any reason, `undefined` is returned. + * + * Result is cached, and thus may be outdated if the filesystem is mutated. + * On success, returns a Path object. + */ + realpath(): Promise; + /** + * Synchronous {@link realpath} + */ + realpathSync(): PathBase | undefined; + /** + * Internal method to mark this Path object as the scurry cwd, + * called by {@link PathScurry#chdir} + * + * @internal + */ + [setAsCwd](oldCwd: PathBase): void; +} +/** + * Path class used on win32 systems + * + * Uses `'\\'` as the path separator for returned paths, either `'\\'` or `'/'` + * as the path separator for parsing paths. + */ +export declare class PathWin32 extends PathBase { + /** + * Separator for generating path strings. + */ + sep: '\\'; + /** + * Separator for parsing path strings. + */ + splitSep: RegExp; + /** + * Do not create new Path objects directly. They should always be accessed + * via the PathScurry class or other methods on the Path class. + * + * @internal + */ + constructor(name: string, type: number | undefined, root: PathBase | undefined, roots: { + [k: string]: PathBase; + }, nocase: boolean, children: ChildrenCache, opts: PathOpts); + /** + * @internal + */ + newChild(name: string, type?: number, opts?: PathOpts): PathWin32; + /** + * @internal + */ + getRootString(path: string): string; + /** + * @internal + */ + getRoot(rootPath: string): PathBase; + /** + * @internal + */ + sameRoot(rootPath: string, compare?: string): boolean; +} +/** + * Path class used on all posix systems. + * + * Uses `'/'` as the path separator. + */ +export declare class PathPosix extends PathBase { + /** + * separator for parsing path strings + */ + splitSep: '/'; + /** + * separator for generating path strings + */ + sep: '/'; + /** + * Do not create new Path objects directly. They should always be accessed + * via the PathScurry class or other methods on the Path class. + * + * @internal + */ + constructor(name: string, type: number | undefined, root: PathBase | undefined, roots: { + [k: string]: PathBase; + }, nocase: boolean, children: ChildrenCache, opts: PathOpts); + /** + * @internal + */ + getRootString(path: string): string; + /** + * @internal + */ + getRoot(_rootPath: string): PathBase; + /** + * @internal + */ + newChild(name: string, type?: number, opts?: PathOpts): PathPosix; +} +/** + * Options that may be provided to the PathScurry constructor + */ +export interface PathScurryOpts { + /** + * perform case-insensitive path matching. Default based on platform + * subclass. + */ + nocase?: boolean; + /** + * Number of Path entries to keep in the cache of Path child references. + * + * Setting this higher than 65536 will dramatically increase the data + * consumption and construction time overhead of each PathScurry. + * + * Setting this value to 256 or lower will significantly reduce the data + * consumption and construction time overhead, but may also reduce resolve() + * and readdir() performance on large filesystems. + * + * Default `16384`. + */ + childrenCacheSize?: number; + /** + * An object that overrides the built-in functions from the fs and + * fs/promises modules. + * + * See {@link FSOption} + */ + fs?: FSOption; +} +/** + * The base class for all PathScurry classes, providing the interface for path + * resolution and filesystem operations. + * + * Typically, you should *not* instantiate this class directly, but rather one + * of the platform-specific classes, or the exported {@link PathScurry} which + * defaults to the current platform. + */ +export declare abstract class PathScurryBase { + #private; + /** + * The root Path entry for the current working directory of this Scurry + */ + root: PathBase; + /** + * The string path for the root of this Scurry's current working directory + */ + rootPath: string; + /** + * A collection of all roots encountered, referenced by rootPath + */ + roots: { + [k: string]: PathBase; + }; + /** + * The Path entry corresponding to this PathScurry's current working directory. + */ + cwd: PathBase; + /** + * Perform path comparisons case-insensitively. + * + * Defaults true on Darwin and Windows systems, false elsewhere. + */ + nocase: boolean; + /** + * The path separator used for parsing paths + * + * `'/'` on Posix systems, either `'/'` or `'\\'` on Windows + */ + abstract sep: string | RegExp; + /** + * This class should not be instantiated directly. + * + * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry + * + * @internal + */ + constructor(cwd: string | URL | undefined, pathImpl: typeof win32 | typeof posix, sep: string | RegExp, { nocase, childrenCacheSize, fs, }?: PathScurryOpts); + /** + * Get the depth of a provided path, string, or the cwd + */ + depth(path?: Path | string): number; + /** + * Parse the root portion of a path string + * + * @internal + */ + abstract parseRootPath(dir: string): string; + /** + * create a new Path to use as root during construction. + * + * @internal + */ + abstract newRoot(fs: FSValue): PathBase; + /** + * Determine whether a given path string is absolute + */ + abstract isAbsolute(p: string): boolean; + /** + * Return the cache of child entries. Exposed so subclasses can create + * child Path objects in a platform-specific way. + * + * @internal + */ + childrenCache(): ChildrenCache; + /** + * Resolve one or more path strings to a resolved string + * + * Same interface as require('path').resolve. + * + * Much faster than path.resolve() when called multiple times for the same + * path, because the resolved Path objects are cached. Much slower + * otherwise. + */ + resolve(...paths: string[]): string; + /** + * Resolve one or more path strings to a resolved string, returning + * the posix path. Identical to .resolve() on posix systems, but on + * windows will return a forward-slash separated UNC path. + * + * Same interface as require('path').resolve. + * + * Much faster than path.resolve() when called multiple times for the same + * path, because the resolved Path objects are cached. Much slower + * otherwise. + */ + resolvePosix(...paths: string[]): string; + /** + * find the relative path from the cwd to the supplied path string or entry + */ + relative(entry?: PathBase | string): string; + /** + * find the relative path from the cwd to the supplied path string or + * entry, using / as the path delimiter, even on Windows. + */ + relativePosix(entry?: PathBase | string): string; + /** + * Return the basename for the provided string or Path object + */ + basename(entry?: PathBase | string): string; + /** + * Return the dirname for the provided string or Path object + */ + dirname(entry?: PathBase | string): string; + /** + * Return an array of known child entries. + * + * First argument may be either a string, or a Path object. + * + * If the Path cannot or does not contain any children, then an empty array + * is returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + * + * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set + * `{ withFileTypes: false }` to return strings. + */ + readdir(): Promise; + readdir(opts: { + withFileTypes: true; + }): Promise; + readdir(opts: { + withFileTypes: false; + }): Promise; + readdir(opts: { + withFileTypes: boolean; + }): Promise; + readdir(entry: PathBase | string): Promise; + readdir(entry: PathBase | string, opts: { + withFileTypes: true; + }): Promise; + readdir(entry: PathBase | string, opts: { + withFileTypes: false; + }): Promise; + readdir(entry: PathBase | string, opts: { + withFileTypes: boolean; + }): Promise; + /** + * synchronous {@link PathScurryBase.readdir} + */ + readdirSync(): PathBase[]; + readdirSync(opts: { + withFileTypes: true; + }): PathBase[]; + readdirSync(opts: { + withFileTypes: false; + }): string[]; + readdirSync(opts: { + withFileTypes: boolean; + }): PathBase[] | string[]; + readdirSync(entry: PathBase | string): PathBase[]; + readdirSync(entry: PathBase | string, opts: { + withFileTypes: true; + }): PathBase[]; + readdirSync(entry: PathBase | string, opts: { + withFileTypes: false; + }): string[]; + readdirSync(entry: PathBase | string, opts: { + withFileTypes: boolean; + }): PathBase[] | string[]; + /** + * Call lstat() on the string or Path object, and update all known + * information that can be determined. + * + * Note that unlike `fs.lstat()`, the returned value does not contain some + * information, such as `mode`, `dev`, `nlink`, and `ino`. If that + * information is required, you will need to call `fs.lstat` yourself. + * + * If the Path refers to a nonexistent file, or if the lstat call fails for + * any reason, `undefined` is returned. Otherwise the updated Path object is + * returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + */ + lstat(entry?: string | PathBase): Promise; + /** + * synchronous {@link PathScurryBase.lstat} + */ + lstatSync(entry?: string | PathBase): PathBase | undefined; + /** + * Return the Path object or string path corresponding to the target of a + * symbolic link. + * + * If the path is not a symbolic link, or if the readlink call fails for any + * reason, `undefined` is returned. + * + * Result is cached, and thus may be outdated if the filesystem is mutated. + * + * `{withFileTypes}` option defaults to `false`. + * + * On success, returns a Path object if `withFileTypes` option is true, + * otherwise a string. + */ + readlink(): Promise; + readlink(opt: { + withFileTypes: false; + }): Promise; + readlink(opt: { + withFileTypes: true; + }): Promise; + readlink(opt: { + withFileTypes: boolean; + }): Promise; + readlink(entry: string | PathBase, opt?: { + withFileTypes: false; + }): Promise; + readlink(entry: string | PathBase, opt: { + withFileTypes: true; + }): Promise; + readlink(entry: string | PathBase, opt: { + withFileTypes: boolean; + }): Promise; + /** + * synchronous {@link PathScurryBase.readlink} + */ + readlinkSync(): string | undefined; + readlinkSync(opt: { + withFileTypes: false; + }): string | undefined; + readlinkSync(opt: { + withFileTypes: true; + }): PathBase | undefined; + readlinkSync(opt: { + withFileTypes: boolean; + }): PathBase | string | undefined; + readlinkSync(entry: string | PathBase, opt?: { + withFileTypes: false; + }): string | undefined; + readlinkSync(entry: string | PathBase, opt: { + withFileTypes: true; + }): PathBase | undefined; + readlinkSync(entry: string | PathBase, opt: { + withFileTypes: boolean; + }): string | PathBase | undefined; + /** + * Return the Path object or string path corresponding to path as resolved + * by realpath(3). + * + * If the realpath call fails for any reason, `undefined` is returned. + * + * Result is cached, and thus may be outdated if the filesystem is mutated. + * + * `{withFileTypes}` option defaults to `false`. + * + * On success, returns a Path object if `withFileTypes` option is true, + * otherwise a string. + */ + realpath(): Promise; + realpath(opt: { + withFileTypes: false; + }): Promise; + realpath(opt: { + withFileTypes: true; + }): Promise; + realpath(opt: { + withFileTypes: boolean; + }): Promise; + realpath(entry: string | PathBase, opt?: { + withFileTypes: false; + }): Promise; + realpath(entry: string | PathBase, opt: { + withFileTypes: true; + }): Promise; + realpath(entry: string | PathBase, opt: { + withFileTypes: boolean; + }): Promise; + realpathSync(): string | undefined; + realpathSync(opt: { + withFileTypes: false; + }): string | undefined; + realpathSync(opt: { + withFileTypes: true; + }): PathBase | undefined; + realpathSync(opt: { + withFileTypes: boolean; + }): PathBase | string | undefined; + realpathSync(entry: string | PathBase, opt?: { + withFileTypes: false; + }): string | undefined; + realpathSync(entry: string | PathBase, opt: { + withFileTypes: true; + }): PathBase | undefined; + realpathSync(entry: string | PathBase, opt: { + withFileTypes: boolean; + }): string | PathBase | undefined; + /** + * Asynchronously walk the directory tree, returning an array of + * all path strings or Path objects found. + * + * Note that this will be extremely memory-hungry on large filesystems. + * In such cases, it may be better to use the stream or async iterator + * walk implementation. + */ + walk(): Promise; + walk(opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): Promise; + walk(opts: WalkOptionsWithFileTypesFalse): Promise; + walk(opts: WalkOptions): Promise; + walk(entry: string | PathBase): Promise; + walk(entry: string | PathBase, opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): Promise; + walk(entry: string | PathBase, opts: WalkOptionsWithFileTypesFalse): Promise; + walk(entry: string | PathBase, opts: WalkOptions): Promise; + /** + * Synchronously walk the directory tree, returning an array of + * all path strings or Path objects found. + * + * Note that this will be extremely memory-hungry on large filesystems. + * In such cases, it may be better to use the stream or async iterator + * walk implementation. + */ + walkSync(): PathBase[]; + walkSync(opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): PathBase[]; + walkSync(opts: WalkOptionsWithFileTypesFalse): string[]; + walkSync(opts: WalkOptions): string[] | PathBase[]; + walkSync(entry: string | PathBase): PathBase[]; + walkSync(entry: string | PathBase, opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue): PathBase[]; + walkSync(entry: string | PathBase, opts: WalkOptionsWithFileTypesFalse): string[]; + walkSync(entry: string | PathBase, opts: WalkOptions): PathBase[] | string[]; + /** + * Support for `for await` + * + * Alias for {@link PathScurryBase.iterate} + * + * Note: As of Node 19, this is very slow, compared to other methods of + * walking. Consider using {@link PathScurryBase.stream} if memory overhead + * and backpressure are concerns, or {@link PathScurryBase.walk} if not. + */ + [Symbol.asyncIterator](): AsyncGenerator; + /** + * Async generator form of {@link PathScurryBase.walk} + * + * Note: As of Node 19, this is very slow, compared to other methods of + * walking, especially if most/all of the directory tree has been previously + * walked. Consider using {@link PathScurryBase.stream} if memory overhead + * and backpressure are concerns, or {@link PathScurryBase.walk} if not. + */ + iterate(): AsyncGenerator; + iterate(opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): AsyncGenerator; + iterate(opts: WalkOptionsWithFileTypesFalse): AsyncGenerator; + iterate(opts: WalkOptions): AsyncGenerator; + iterate(entry: string | PathBase): AsyncGenerator; + iterate(entry: string | PathBase, opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): AsyncGenerator; + iterate(entry: string | PathBase, opts: WalkOptionsWithFileTypesFalse): AsyncGenerator; + iterate(entry: string | PathBase, opts: WalkOptions): AsyncGenerator; + /** + * Iterating over a PathScurry performs a synchronous walk. + * + * Alias for {@link PathScurryBase.iterateSync} + */ + [Symbol.iterator](): Generator; + iterateSync(): Generator; + iterateSync(opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): Generator; + iterateSync(opts: WalkOptionsWithFileTypesFalse): Generator; + iterateSync(opts: WalkOptions): Generator; + iterateSync(entry: string | PathBase): Generator; + iterateSync(entry: string | PathBase, opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): Generator; + iterateSync(entry: string | PathBase, opts: WalkOptionsWithFileTypesFalse): Generator; + iterateSync(entry: string | PathBase, opts: WalkOptions): Generator; + /** + * Stream form of {@link PathScurryBase.walk} + * + * Returns a Minipass stream that emits {@link PathBase} objects by default, + * or strings if `{ withFileTypes: false }` is set in the options. + */ + stream(): Minipass; + stream(opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): Minipass; + stream(opts: WalkOptionsWithFileTypesFalse): Minipass; + stream(opts: WalkOptions): Minipass; + stream(entry: string | PathBase): Minipass; + stream(entry: string | PathBase, opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue): Minipass; + stream(entry: string | PathBase, opts: WalkOptionsWithFileTypesFalse): Minipass; + stream(entry: string | PathBase, opts: WalkOptions): Minipass | Minipass; + /** + * Synchronous form of {@link PathScurryBase.stream} + * + * Returns a Minipass stream that emits {@link PathBase} objects by default, + * or strings if `{ withFileTypes: false }` is set in the options. + * + * Will complete the walk in a single tick if the stream is consumed fully. + * Otherwise, will pause as needed for stream backpressure. + */ + streamSync(): Minipass; + streamSync(opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): Minipass; + streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass; + streamSync(opts: WalkOptions): Minipass; + streamSync(entry: string | PathBase): Minipass; + streamSync(entry: string | PathBase, opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue): Minipass; + streamSync(entry: string | PathBase, opts: WalkOptionsWithFileTypesFalse): Minipass; + streamSync(entry: string | PathBase, opts: WalkOptions): Minipass | Minipass; + chdir(path?: string | Path): void; +} +/** + * Options provided to all walk methods. + */ +export interface WalkOptions { + /** + * Return results as {@link PathBase} objects rather than strings. + * When set to false, results are fully resolved paths, as returned by + * {@link PathBase.fullpath}. + * @default true + */ + withFileTypes?: boolean; + /** + * Attempt to read directory entries from symbolic links. Otherwise, only + * actual directories are traversed. Regardless of this setting, a given + * target path will only ever be walked once, meaning that a symbolic link + * to a previously traversed directory will never be followed. + * + * Setting this imposes a slight performance penalty, because `readlink` + * must be called on all symbolic links encountered, in order to avoid + * infinite cycles. + * @default false + */ + follow?: boolean; + /** + * Only return entries where the provided function returns true. + * + * This will not prevent directories from being traversed, even if they do + * not pass the filter, though it will prevent directories themselves from + * being included in the result set. See {@link walkFilter} + * + * Asynchronous functions are not supported here. + * + * By default, if no filter is provided, all entries and traversed + * directories are included. + */ + filter?: (entry: PathBase) => boolean; + /** + * Only traverse directories (and in the case of {@link follow} being set to + * true, symbolic links to directories) if the provided function returns + * true. + * + * This will not prevent directories from being included in the result set, + * even if they do not pass the supplied filter function. See {@link filter} + * to do that. + * + * Asynchronous functions are not supported here. + */ + walkFilter?: (entry: PathBase) => boolean; +} +export type WalkOptionsWithFileTypesUnset = WalkOptions & { + withFileTypes?: undefined; +}; +export type WalkOptionsWithFileTypesTrue = WalkOptions & { + withFileTypes: true; +}; +export type WalkOptionsWithFileTypesFalse = WalkOptions & { + withFileTypes: false; +}; +/** + * Windows implementation of {@link PathScurryBase} + * + * Defaults to case insensitve, uses `'\\'` to generate path strings. Uses + * {@link PathWin32} for Path objects. + */ +export declare class PathScurryWin32 extends PathScurryBase { + /** + * separator for generating path strings + */ + sep: '\\'; + constructor(cwd?: URL | string, opts?: PathScurryOpts); + /** + * @internal + */ + parseRootPath(dir: string): string; + /** + * @internal + */ + newRoot(fs: FSValue): PathWin32; + /** + * Return true if the provided path string is an absolute path + */ + isAbsolute(p: string): boolean; +} +/** + * {@link PathScurryBase} implementation for all posix systems other than Darwin. + * + * Defaults to case-sensitive matching, uses `'/'` to generate path strings. + * + * Uses {@link PathPosix} for Path objects. + */ +export declare class PathScurryPosix extends PathScurryBase { + /** + * separator for generating path strings + */ + sep: '/'; + constructor(cwd?: URL | string, opts?: PathScurryOpts); + /** + * @internal + */ + parseRootPath(_dir: string): string; + /** + * @internal + */ + newRoot(fs: FSValue): PathPosix; + /** + * Return true if the provided path string is an absolute path + */ + isAbsolute(p: string): boolean; +} +/** + * {@link PathScurryBase} implementation for Darwin (macOS) systems. + * + * Defaults to case-insensitive matching, uses `'/'` for generating path + * strings. + * + * Uses {@link PathPosix} for Path objects. + */ +export declare class PathScurryDarwin extends PathScurryPosix { + constructor(cwd?: URL | string, opts?: PathScurryOpts); +} +/** + * Default {@link PathBase} implementation for the current platform. + * + * {@link PathWin32} on Windows systems, {@link PathPosix} on all others. + */ +export declare const Path: typeof PathWin32 | typeof PathPosix; +export type Path = PathBase | InstanceType; +/** + * Default {@link PathScurryBase} implementation for the current platform. + * + * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on + * Darwin (macOS) systems, {@link PathScurryPosix} on all others. + */ +export declare const PathScurry: typeof PathScurryWin32 | typeof PathScurryDarwin | typeof PathScurryPosix; +export type PathScurry = PathScurryBase | InstanceType; +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/path-scurry/dist/commonjs/index.d.ts.map b/node_modules/path-scurry/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000..1f59f8f --- /dev/null +++ b/node_modules/path-scurry/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,WAAW,CAAA;AAmBxC,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAE5C;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,WAAW,QAAQ;IACvB,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,KAAK,CAAA;IACnC,OAAO,CAAC,EAAE,CACR,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE;QAAE,aAAa,EAAE,IAAI,CAAA;KAAE,EAChC,EAAE,EAAE,CAAC,EAAE,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,EAAE,OAAO,CAAC,EAAE,MAAM,EAAE,KAAK,GAAG,KAC9D,IAAI,CAAA;IACT,WAAW,CAAC,EAAE,CACZ,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE;QAAE,aAAa,EAAE,IAAI,CAAA;KAAE,KAC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ED;;;;;GAKG;AACH,qBAAa,eAAgB,SAAQ,cAAc;IACjD;;OAEG;IACH,GAAG,EAAE,IAAI,CAAO;gBAGd,GAAG,GAAE,GAAG,GAAG,MAAsB,EACjC,IAAI,GAAE,cAAmB;IAU3B;;OAEG;IACH,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM;IAOlC;;OAEG;IACH,OAAO,CAAC,EAAE,EAAE,OAAO;IAYnB;;OAEG;IACH,UAAU,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO;CAK/B;AAED;;;;;;GAMG;AACH,qBAAa,eAAgB,SAAQ,cAAc;IACjD;;OAEG;IACH,GAAG,EAAE,GAAG,CAAM;gBAEZ,GAAG,GAAE,GAAG,GAAG,MAAsB,EACjC,IAAI,GAAE,cAAmB;IAO3B;;OAEG;IACH,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAInC;;OAEG;IACH,OAAO,CAAC,EAAE,EAAE,OAAO;IAYnB;;OAEG;IACH,UAAU,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO;CAG/B;AAED;;;;;;;GAOG;AACH,qBAAa,gBAAiB,SAAQ,eAAe;gBAEjD,GAAG,GAAE,GAAG,GAAG,MAAsB,EACjC,IAAI,GAAE,cAAmB;CAK5B;AAED;;;;GAIG;AACH,eAAO,MAAM,IAAI,qCAAuD,CAAA;AACxE,MAAM,MAAM,IAAI,GAAG,QAAQ,GAAG,YAAY,CAAC,OAAO,IAAI,CAAC,CAAA;AAEvD;;;;;GAKG;AACH,eAAO,MAAM,UAAU,EACnB,OAAO,eAAe,GACtB,OAAO,gBAAgB,GACvB,OAAO,eAGQ,CAAA;AACnB,MAAM,MAAM,UAAU,GAAG,cAAc,GAAG,YAAY,CAAC,OAAO,UAAU,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/path-scurry/dist/commonjs/index.js b/node_modules/path-scurry/dist/commonjs/index.js new file mode 100644 index 0000000..555de62 --- /dev/null +++ b/node_modules/path-scurry/dist/commonjs/index.js @@ -0,0 +1,2014 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PathScurry = exports.Path = exports.PathScurryDarwin = exports.PathScurryPosix = exports.PathScurryWin32 = exports.PathScurryBase = exports.PathPosix = exports.PathWin32 = exports.PathBase = exports.ChildrenCache = exports.ResolveCache = void 0; +const lru_cache_1 = require("lru-cache"); +const node_path_1 = require("node:path"); +const node_url_1 = require("node:url"); +const fs_1 = require("fs"); +const actualFS = __importStar(require("node:fs")); +const realpathSync = fs_1.realpathSync.native; +// TODO: test perf of fs/promises realpath vs realpathCB, +// since the promises one uses realpath.native +const promises_1 = require("node:fs/promises"); +const minipass_1 = require("minipass"); +const defaultFS = { + lstatSync: fs_1.lstatSync, + readdir: fs_1.readdir, + readdirSync: fs_1.readdirSync, + readlinkSync: fs_1.readlinkSync, + realpathSync, + promises: { + lstat: promises_1.lstat, + readdir: promises_1.readdir, + readlink: promises_1.readlink, + realpath: promises_1.realpath, + }, +}; +// if they just gave us require('fs') then use our default +const fsFromOption = (fsOption) => !fsOption || fsOption === defaultFS || fsOption === actualFS ? + defaultFS + : { + ...defaultFS, + ...fsOption, + promises: { + ...defaultFS.promises, + ...(fsOption.promises || {}), + }, + }; +// turn something like //?/c:/ into c:\ +const uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i; +const uncToDrive = (rootPath) => rootPath.replace(/\//g, '\\').replace(uncDriveRegexp, '$1\\'); +// windows paths are separated by either / or \ +const eitherSep = /[\\\/]/; +const UNKNOWN = 0; // may not even exist, for all we know +const IFIFO = 0b0001; +const IFCHR = 0b0010; +const IFDIR = 0b0100; +const IFBLK = 0b0110; +const IFREG = 0b1000; +const IFLNK = 0b1010; +const IFSOCK = 0b1100; +const IFMT = 0b1111; +// mask to unset low 4 bits +const IFMT_UNKNOWN = ~IFMT; +// set after successfully calling readdir() and getting entries. +const READDIR_CALLED = 0b0000_0001_0000; +// set after a successful lstat() +const LSTAT_CALLED = 0b0000_0010_0000; +// set if an entry (or one of its parents) is definitely not a dir +const ENOTDIR = 0b0000_0100_0000; +// set if an entry (or one of its parents) does not exist +// (can also be set on lstat errors like EACCES or ENAMETOOLONG) +const ENOENT = 0b0000_1000_0000; +// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK +// set if we fail to readlink +const ENOREADLINK = 0b0001_0000_0000; +// set if we know realpath() will fail +const ENOREALPATH = 0b0010_0000_0000; +const ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH; +const TYPEMASK = 0b0011_1111_1111; +const entToType = (s) => s.isFile() ? IFREG + : s.isDirectory() ? IFDIR + : s.isSymbolicLink() ? IFLNK + : s.isCharacterDevice() ? IFCHR + : s.isBlockDevice() ? IFBLK + : s.isSocket() ? IFSOCK + : s.isFIFO() ? IFIFO + : UNKNOWN; +// normalize unicode path names +const normalizeCache = new Map(); +const normalize = (s) => { + const c = normalizeCache.get(s); + if (c) + return c; + const n = s.normalize('NFKD'); + normalizeCache.set(s, n); + return n; +}; +const normalizeNocaseCache = new Map(); +const normalizeNocase = (s) => { + const c = normalizeNocaseCache.get(s); + if (c) + return c; + const n = normalize(s.toLowerCase()); + normalizeNocaseCache.set(s, n); + return n; +}; +/** + * An LRUCache for storing resolved path strings or Path objects. + * @internal + */ +class ResolveCache extends lru_cache_1.LRUCache { + constructor() { + super({ max: 256 }); + } +} +exports.ResolveCache = ResolveCache; +// In order to prevent blowing out the js heap by allocating hundreds of +// thousands of Path entries when walking extremely large trees, the "children" +// in this tree are represented by storing an array of Path entries in an +// LRUCache, indexed by the parent. At any time, Path.children() may return an +// empty array, indicating that it doesn't know about any of its children, and +// thus has to rebuild that cache. This is fine, it just means that we don't +// benefit as much from having the cached entries, but huge directory walks +// don't blow out the stack, and smaller ones are still as fast as possible. +// +//It does impose some complexity when building up the readdir data, because we +//need to pass a reference to the children array that we started with. +/** + * an LRUCache for storing child entries. + * @internal + */ +class ChildrenCache extends lru_cache_1.LRUCache { + constructor(maxSize = 16 * 1024) { + super({ + maxSize, + // parent + children + sizeCalculation: a => a.length + 1, + }); + } +} +exports.ChildrenCache = ChildrenCache; +const setAsCwd = Symbol('PathScurry setAsCwd'); +/** + * Path objects are sort of like a super-powered + * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent} + * + * Each one represents a single filesystem entry on disk, which may or may not + * exist. It includes methods for reading various types of information via + * lstat, readlink, and readdir, and caches all information to the greatest + * degree possible. + * + * Note that fs operations that would normally throw will instead return an + * "empty" value. This is in order to prevent excessive overhead from error + * stack traces. + */ +class PathBase { + /** + * the basename of this path + * + * **Important**: *always* test the path name against any test string + * usingthe {@link isNamed} method, and not by directly comparing this + * string. Otherwise, unicode path strings that the system sees as identical + * will not be properly treated as the same path, leading to incorrect + * behavior and possible security issues. + */ + name; + /** + * the Path entry corresponding to the path root. + * + * @internal + */ + root; + /** + * All roots found within the current PathScurry family + * + * @internal + */ + roots; + /** + * a reference to the parent path, or undefined in the case of root entries + * + * @internal + */ + parent; + /** + * boolean indicating whether paths are compared case-insensitively + * @internal + */ + nocase; + /** + * boolean indicating that this path is the current working directory + * of the PathScurry collection that contains it. + */ + isCWD = false; + // potential default fs override + #fs; + // Stats fields + #dev; + get dev() { + return this.#dev; + } + #mode; + get mode() { + return this.#mode; + } + #nlink; + get nlink() { + return this.#nlink; + } + #uid; + get uid() { + return this.#uid; + } + #gid; + get gid() { + return this.#gid; + } + #rdev; + get rdev() { + return this.#rdev; + } + #blksize; + get blksize() { + return this.#blksize; + } + #ino; + get ino() { + return this.#ino; + } + #size; + get size() { + return this.#size; + } + #blocks; + get blocks() { + return this.#blocks; + } + #atimeMs; + get atimeMs() { + return this.#atimeMs; + } + #mtimeMs; + get mtimeMs() { + return this.#mtimeMs; + } + #ctimeMs; + get ctimeMs() { + return this.#ctimeMs; + } + #birthtimeMs; + get birthtimeMs() { + return this.#birthtimeMs; + } + #atime; + get atime() { + return this.#atime; + } + #mtime; + get mtime() { + return this.#mtime; + } + #ctime; + get ctime() { + return this.#ctime; + } + #birthtime; + get birthtime() { + return this.#birthtime; + } + #matchName; + #depth; + #fullpath; + #fullpathPosix; + #relative; + #relativePosix; + #type; + #children; + #linkTarget; + #realpath; + /** + * This property is for compatibility with the Dirent class as of + * Node v20, where Dirent['parentPath'] refers to the path of the + * directory that was passed to readdir. For root entries, it's the path + * to the entry itself. + */ + get parentPath() { + return (this.parent || this).fullpath(); + } + /** + * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively, + * this property refers to the *parent* path, not the path object itself. + */ + get path() { + return this.parentPath; + } + /** + * Do not create new Path objects directly. They should always be accessed + * via the PathScurry class or other methods on the Path class. + * + * @internal + */ + constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) { + this.name = name; + this.#matchName = nocase ? normalizeNocase(name) : normalize(name); + this.#type = type & TYPEMASK; + this.nocase = nocase; + this.roots = roots; + this.root = root || this; + this.#children = children; + this.#fullpath = opts.fullpath; + this.#relative = opts.relative; + this.#relativePosix = opts.relativePosix; + this.parent = opts.parent; + if (this.parent) { + this.#fs = this.parent.#fs; + } + else { + this.#fs = fsFromOption(opts.fs); + } + } + /** + * Returns the depth of the Path object from its root. + * + * For example, a path at `/foo/bar` would have a depth of 2. + */ + depth() { + if (this.#depth !== undefined) + return this.#depth; + if (!this.parent) + return (this.#depth = 0); + return (this.#depth = this.parent.depth() + 1); + } + /** + * @internal + */ + childrenCache() { + return this.#children; + } + /** + * Get the Path object referenced by the string path, resolved from this Path + */ + resolve(path) { + if (!path) { + return this; + } + const rootPath = this.getRootString(path); + const dir = path.substring(rootPath.length); + const dirParts = dir.split(this.splitSep); + const result = rootPath ? + this.getRoot(rootPath).#resolveParts(dirParts) + : this.#resolveParts(dirParts); + return result; + } + #resolveParts(dirParts) { + let p = this; + for (const part of dirParts) { + p = p.child(part); + } + return p; + } + /** + * Returns the cached children Path objects, if still available. If they + * have fallen out of the cache, then returns an empty array, and resets the + * READDIR_CALLED bit, so that future calls to readdir() will require an fs + * lookup. + * + * @internal + */ + children() { + const cached = this.#children.get(this); + if (cached) { + return cached; + } + const children = Object.assign([], { provisional: 0 }); + this.#children.set(this, children); + this.#type &= ~READDIR_CALLED; + return children; + } + /** + * Resolves a path portion and returns or creates the child Path. + * + * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is + * `'..'`. + * + * This should not be called directly. If `pathPart` contains any path + * separators, it will lead to unsafe undefined behavior. + * + * Use `Path.resolve()` instead. + * + * @internal + */ + child(pathPart, opts) { + if (pathPart === '' || pathPart === '.') { + return this; + } + if (pathPart === '..') { + return this.parent || this; + } + // find the child + const children = this.children(); + const name = this.nocase ? normalizeNocase(pathPart) : normalize(pathPart); + for (const p of children) { + if (p.#matchName === name) { + return p; + } + } + // didn't find it, create provisional child, since it might not + // actually exist. If we know the parent isn't a dir, then + // in fact it CAN'T exist. + const s = this.parent ? this.sep : ''; + const fullpath = this.#fullpath ? this.#fullpath + s + pathPart : undefined; + const pchild = this.newChild(pathPart, UNKNOWN, { + ...opts, + parent: this, + fullpath, + }); + if (!this.canReaddir()) { + pchild.#type |= ENOENT; + } + // don't have to update provisional, because if we have real children, + // then provisional is set to children.length, otherwise a lower number + children.push(pchild); + return pchild; + } + /** + * The relative path from the cwd. If it does not share an ancestor with + * the cwd, then this ends up being equivalent to the fullpath() + */ + relative() { + if (this.isCWD) + return ''; + if (this.#relative !== undefined) { + return this.#relative; + } + const name = this.name; + const p = this.parent; + if (!p) { + return (this.#relative = this.name); + } + const pv = p.relative(); + return pv + (!pv || !p.parent ? '' : this.sep) + name; + } + /** + * The relative path from the cwd, using / as the path separator. + * If it does not share an ancestor with + * the cwd, then this ends up being equivalent to the fullpathPosix() + * On posix systems, this is identical to relative(). + */ + relativePosix() { + if (this.sep === '/') + return this.relative(); + if (this.isCWD) + return ''; + if (this.#relativePosix !== undefined) + return this.#relativePosix; + const name = this.name; + const p = this.parent; + if (!p) { + return (this.#relativePosix = this.fullpathPosix()); + } + const pv = p.relativePosix(); + return pv + (!pv || !p.parent ? '' : '/') + name; + } + /** + * The fully resolved path string for this Path entry + */ + fullpath() { + if (this.#fullpath !== undefined) { + return this.#fullpath; + } + const name = this.name; + const p = this.parent; + if (!p) { + return (this.#fullpath = this.name); + } + const pv = p.fullpath(); + const fp = pv + (!p.parent ? '' : this.sep) + name; + return (this.#fullpath = fp); + } + /** + * On platforms other than windows, this is identical to fullpath. + * + * On windows, this is overridden to return the forward-slash form of the + * full UNC path. + */ + fullpathPosix() { + if (this.#fullpathPosix !== undefined) + return this.#fullpathPosix; + if (this.sep === '/') + return (this.#fullpathPosix = this.fullpath()); + if (!this.parent) { + const p = this.fullpath().replace(/\\/g, '/'); + if (/^[a-z]:\//i.test(p)) { + return (this.#fullpathPosix = `//?/${p}`); + } + else { + return (this.#fullpathPosix = p); + } + } + const p = this.parent; + const pfpp = p.fullpathPosix(); + const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name; + return (this.#fullpathPosix = fpp); + } + /** + * Is the Path of an unknown type? + * + * Note that we might know *something* about it if there has been a previous + * filesystem operation, for example that it does not exist, or is not a + * link, or whether it has child entries. + */ + isUnknown() { + return (this.#type & IFMT) === UNKNOWN; + } + isType(type) { + return this[`is${type}`](); + } + getType() { + return (this.isUnknown() ? 'Unknown' + : this.isDirectory() ? 'Directory' + : this.isFile() ? 'File' + : this.isSymbolicLink() ? 'SymbolicLink' + : this.isFIFO() ? 'FIFO' + : this.isCharacterDevice() ? 'CharacterDevice' + : this.isBlockDevice() ? 'BlockDevice' + : /* c8 ignore start */ this.isSocket() ? 'Socket' + : 'Unknown'); + /* c8 ignore stop */ + } + /** + * Is the Path a regular file? + */ + isFile() { + return (this.#type & IFMT) === IFREG; + } + /** + * Is the Path a directory? + */ + isDirectory() { + return (this.#type & IFMT) === IFDIR; + } + /** + * Is the path a character device? + */ + isCharacterDevice() { + return (this.#type & IFMT) === IFCHR; + } + /** + * Is the path a block device? + */ + isBlockDevice() { + return (this.#type & IFMT) === IFBLK; + } + /** + * Is the path a FIFO pipe? + */ + isFIFO() { + return (this.#type & IFMT) === IFIFO; + } + /** + * Is the path a socket? + */ + isSocket() { + return (this.#type & IFMT) === IFSOCK; + } + /** + * Is the path a symbolic link? + */ + isSymbolicLink() { + return (this.#type & IFLNK) === IFLNK; + } + /** + * Return the entry if it has been subject of a successful lstat, or + * undefined otherwise. + * + * Does not read the filesystem, so an undefined result *could* simply + * mean that we haven't called lstat on it. + */ + lstatCached() { + return this.#type & LSTAT_CALLED ? this : undefined; + } + /** + * Return the cached link target if the entry has been the subject of a + * successful readlink, or undefined otherwise. + * + * Does not read the filesystem, so an undefined result *could* just mean we + * don't have any cached data. Only use it if you are very sure that a + * readlink() has been called at some point. + */ + readlinkCached() { + return this.#linkTarget; + } + /** + * Returns the cached realpath target if the entry has been the subject + * of a successful realpath, or undefined otherwise. + * + * Does not read the filesystem, so an undefined result *could* just mean we + * don't have any cached data. Only use it if you are very sure that a + * realpath() has been called at some point. + */ + realpathCached() { + return this.#realpath; + } + /** + * Returns the cached child Path entries array if the entry has been the + * subject of a successful readdir(), or [] otherwise. + * + * Does not read the filesystem, so an empty array *could* just mean we + * don't have any cached data. Only use it if you are very sure that a + * readdir() has been called recently enough to still be valid. + */ + readdirCached() { + const children = this.children(); + return children.slice(0, children.provisional); + } + /** + * Return true if it's worth trying to readlink. Ie, we don't (yet) have + * any indication that readlink will definitely fail. + * + * Returns false if the path is known to not be a symlink, if a previous + * readlink failed, or if the entry does not exist. + */ + canReadlink() { + if (this.#linkTarget) + return true; + if (!this.parent) + return false; + // cases where it cannot possibly succeed + const ifmt = this.#type & IFMT; + return !((ifmt !== UNKNOWN && ifmt !== IFLNK) || + this.#type & ENOREADLINK || + this.#type & ENOENT); + } + /** + * Return true if readdir has previously been successfully called on this + * path, indicating that cachedReaddir() is likely valid. + */ + calledReaddir() { + return !!(this.#type & READDIR_CALLED); + } + /** + * Returns true if the path is known to not exist. That is, a previous lstat + * or readdir failed to verify its existence when that would have been + * expected, or a parent entry was marked either enoent or enotdir. + */ + isENOENT() { + return !!(this.#type & ENOENT); + } + /** + * Return true if the path is a match for the given path name. This handles + * case sensitivity and unicode normalization. + * + * Note: even on case-sensitive systems, it is **not** safe to test the + * equality of the `.name` property to determine whether a given pathname + * matches, due to unicode normalization mismatches. + * + * Always use this method instead of testing the `path.name` property + * directly. + */ + isNamed(n) { + return !this.nocase ? + this.#matchName === normalize(n) + : this.#matchName === normalizeNocase(n); + } + /** + * Return the Path object corresponding to the target of a symbolic link. + * + * If the Path is not a symbolic link, or if the readlink call fails for any + * reason, `undefined` is returned. + * + * Result is cached, and thus may be outdated if the filesystem is mutated. + */ + async readlink() { + const target = this.#linkTarget; + if (target) { + return target; + } + if (!this.canReadlink()) { + return undefined; + } + /* c8 ignore start */ + // already covered by the canReadlink test, here for ts grumples + if (!this.parent) { + return undefined; + } + /* c8 ignore stop */ + try { + const read = await this.#fs.promises.readlink(this.fullpath()); + const linkTarget = (await this.parent.realpath())?.resolve(read); + if (linkTarget) { + return (this.#linkTarget = linkTarget); + } + } + catch (er) { + this.#readlinkFail(er.code); + return undefined; + } + } + /** + * Synchronous {@link PathBase.readlink} + */ + readlinkSync() { + const target = this.#linkTarget; + if (target) { + return target; + } + if (!this.canReadlink()) { + return undefined; + } + /* c8 ignore start */ + // already covered by the canReadlink test, here for ts grumples + if (!this.parent) { + return undefined; + } + /* c8 ignore stop */ + try { + const read = this.#fs.readlinkSync(this.fullpath()); + const linkTarget = this.parent.realpathSync()?.resolve(read); + if (linkTarget) { + return (this.#linkTarget = linkTarget); + } + } + catch (er) { + this.#readlinkFail(er.code); + return undefined; + } + } + #readdirSuccess(children) { + // succeeded, mark readdir called bit + this.#type |= READDIR_CALLED; + // mark all remaining provisional children as ENOENT + for (let p = children.provisional; p < children.length; p++) { + const c = children[p]; + if (c) + c.#markENOENT(); + } + } + #markENOENT() { + // mark as UNKNOWN and ENOENT + if (this.#type & ENOENT) + return; + this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN; + this.#markChildrenENOENT(); + } + #markChildrenENOENT() { + // all children are provisional and do not exist + const children = this.children(); + children.provisional = 0; + for (const p of children) { + p.#markENOENT(); + } + } + #markENOREALPATH() { + this.#type |= ENOREALPATH; + this.#markENOTDIR(); + } + // save the information when we know the entry is not a dir + #markENOTDIR() { + // entry is not a directory, so any children can't exist. + // this *should* be impossible, since any children created + // after it's been marked ENOTDIR should be marked ENOENT, + // so it won't even get to this point. + /* c8 ignore start */ + if (this.#type & ENOTDIR) + return; + /* c8 ignore stop */ + let t = this.#type; + // this could happen if we stat a dir, then delete it, + // then try to read it or one of its children. + if ((t & IFMT) === IFDIR) + t &= IFMT_UNKNOWN; + this.#type = t | ENOTDIR; + this.#markChildrenENOENT(); + } + #readdirFail(code = '') { + // markENOTDIR and markENOENT also set provisional=0 + if (code === 'ENOTDIR' || code === 'EPERM') { + this.#markENOTDIR(); + } + else if (code === 'ENOENT') { + this.#markENOENT(); + } + else { + this.children().provisional = 0; + } + } + #lstatFail(code = '') { + // Windows just raises ENOENT in this case, disable for win CI + /* c8 ignore start */ + if (code === 'ENOTDIR') { + // already know it has a parent by this point + const p = this.parent; + p.#markENOTDIR(); + } + else if (code === 'ENOENT') { + /* c8 ignore stop */ + this.#markENOENT(); + } + } + #readlinkFail(code = '') { + let ter = this.#type; + ter |= ENOREADLINK; + if (code === 'ENOENT') + ter |= ENOENT; + // windows gets a weird error when you try to readlink a file + if (code === 'EINVAL' || code === 'UNKNOWN') { + // exists, but not a symlink, we don't know WHAT it is, so remove + // all IFMT bits. + ter &= IFMT_UNKNOWN; + } + this.#type = ter; + // windows just gets ENOENT in this case. We do cover the case, + // just disabled because it's impossible on Windows CI + /* c8 ignore start */ + if (code === 'ENOTDIR' && this.parent) { + this.parent.#markENOTDIR(); + } + /* c8 ignore stop */ + } + #readdirAddChild(e, c) { + return (this.#readdirMaybePromoteChild(e, c) || + this.#readdirAddNewChild(e, c)); + } + #readdirAddNewChild(e, c) { + // alloc new entry at head, so it's never provisional + const type = entToType(e); + const child = this.newChild(e.name, type, { parent: this }); + const ifmt = child.#type & IFMT; + if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) { + child.#type |= ENOTDIR; + } + c.unshift(child); + c.provisional++; + return child; + } + #readdirMaybePromoteChild(e, c) { + for (let p = c.provisional; p < c.length; p++) { + const pchild = c[p]; + const name = this.nocase ? normalizeNocase(e.name) : normalize(e.name); + if (name !== pchild.#matchName) { + continue; + } + return this.#readdirPromoteChild(e, pchild, p, c); + } + } + #readdirPromoteChild(e, p, index, c) { + const v = p.name; + // retain any other flags, but set ifmt from dirent + p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e); + // case sensitivity fixing when we learn the true name. + if (v !== e.name) + p.name = e.name; + // just advance provisional index (potentially off the list), + // otherwise we have to splice/pop it out and re-insert at head + if (index !== c.provisional) { + if (index === c.length - 1) + c.pop(); + else + c.splice(index, 1); + c.unshift(p); + } + c.provisional++; + return p; + } + /** + * Call lstat() on this Path, and update all known information that can be + * determined. + * + * Note that unlike `fs.lstat()`, the returned value does not contain some + * information, such as `mode`, `dev`, `nlink`, and `ino`. If that + * information is required, you will need to call `fs.lstat` yourself. + * + * If the Path refers to a nonexistent file, or if the lstat call fails for + * any reason, `undefined` is returned. Otherwise the updated Path object is + * returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + */ + async lstat() { + if ((this.#type & ENOENT) === 0) { + try { + this.#applyStat(await this.#fs.promises.lstat(this.fullpath())); + return this; + } + catch (er) { + this.#lstatFail(er.code); + } + } + } + /** + * synchronous {@link PathBase.lstat} + */ + lstatSync() { + if ((this.#type & ENOENT) === 0) { + try { + this.#applyStat(this.#fs.lstatSync(this.fullpath())); + return this; + } + catch (er) { + this.#lstatFail(er.code); + } + } + } + #applyStat(st) { + const { atime, atimeMs, birthtime, birthtimeMs, blksize, blocks, ctime, ctimeMs, dev, gid, ino, mode, mtime, mtimeMs, nlink, rdev, size, uid, } = st; + this.#atime = atime; + this.#atimeMs = atimeMs; + this.#birthtime = birthtime; + this.#birthtimeMs = birthtimeMs; + this.#blksize = blksize; + this.#blocks = blocks; + this.#ctime = ctime; + this.#ctimeMs = ctimeMs; + this.#dev = dev; + this.#gid = gid; + this.#ino = ino; + this.#mode = mode; + this.#mtime = mtime; + this.#mtimeMs = mtimeMs; + this.#nlink = nlink; + this.#rdev = rdev; + this.#size = size; + this.#uid = uid; + const ifmt = entToType(st); + // retain any other flags, but set the ifmt + this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED; + if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) { + this.#type |= ENOTDIR; + } + } + #onReaddirCB = []; + #readdirCBInFlight = false; + #callOnReaddirCB(children) { + this.#readdirCBInFlight = false; + const cbs = this.#onReaddirCB.slice(); + this.#onReaddirCB.length = 0; + cbs.forEach(cb => cb(null, children)); + } + /** + * Standard node-style callback interface to get list of directory entries. + * + * If the Path cannot or does not contain any children, then an empty array + * is returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + * + * @param cb The callback called with (er, entries). Note that the `er` + * param is somewhat extraneous, as all readdir() errors are handled and + * simply result in an empty set of entries being returned. + * @param allowZalgo Boolean indicating that immediately known results should + * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release + * zalgo at your peril, the dark pony lord is devious and unforgiving. + */ + readdirCB(cb, allowZalgo = false) { + if (!this.canReaddir()) { + if (allowZalgo) + cb(null, []); + else + queueMicrotask(() => cb(null, [])); + return; + } + const children = this.children(); + if (this.calledReaddir()) { + const c = children.slice(0, children.provisional); + if (allowZalgo) + cb(null, c); + else + queueMicrotask(() => cb(null, c)); + return; + } + // don't have to worry about zalgo at this point. + this.#onReaddirCB.push(cb); + if (this.#readdirCBInFlight) { + return; + } + this.#readdirCBInFlight = true; + // else read the directory, fill up children + // de-provisionalize any provisional children. + const fullpath = this.fullpath(); + this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => { + if (er) { + this.#readdirFail(er.code); + children.provisional = 0; + } + else { + // if we didn't get an error, we always get entries. + //@ts-ignore + for (const e of entries) { + this.#readdirAddChild(e, children); + } + this.#readdirSuccess(children); + } + this.#callOnReaddirCB(children.slice(0, children.provisional)); + return; + }); + } + #asyncReaddirInFlight; + /** + * Return an array of known child entries. + * + * If the Path cannot or does not contain any children, then an empty array + * is returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + */ + async readdir() { + if (!this.canReaddir()) { + return []; + } + const children = this.children(); + if (this.calledReaddir()) { + return children.slice(0, children.provisional); + } + // else read the directory, fill up children + // de-provisionalize any provisional children. + const fullpath = this.fullpath(); + if (this.#asyncReaddirInFlight) { + await this.#asyncReaddirInFlight; + } + else { + /* c8 ignore start */ + let resolve = () => { }; + /* c8 ignore stop */ + this.#asyncReaddirInFlight = new Promise(res => (resolve = res)); + try { + for (const e of await this.#fs.promises.readdir(fullpath, { + withFileTypes: true, + })) { + this.#readdirAddChild(e, children); + } + this.#readdirSuccess(children); + } + catch (er) { + this.#readdirFail(er.code); + children.provisional = 0; + } + this.#asyncReaddirInFlight = undefined; + resolve(); + } + return children.slice(0, children.provisional); + } + /** + * synchronous {@link PathBase.readdir} + */ + readdirSync() { + if (!this.canReaddir()) { + return []; + } + const children = this.children(); + if (this.calledReaddir()) { + return children.slice(0, children.provisional); + } + // else read the directory, fill up children + // de-provisionalize any provisional children. + const fullpath = this.fullpath(); + try { + for (const e of this.#fs.readdirSync(fullpath, { + withFileTypes: true, + })) { + this.#readdirAddChild(e, children); + } + this.#readdirSuccess(children); + } + catch (er) { + this.#readdirFail(er.code); + children.provisional = 0; + } + return children.slice(0, children.provisional); + } + canReaddir() { + if (this.#type & ENOCHILD) + return false; + const ifmt = IFMT & this.#type; + // we always set ENOTDIR when setting IFMT, so should be impossible + /* c8 ignore start */ + if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) { + return false; + } + /* c8 ignore stop */ + return true; + } + shouldWalk(dirs, walkFilter) { + return ((this.#type & IFDIR) === IFDIR && + !(this.#type & ENOCHILD) && + !dirs.has(this) && + (!walkFilter || walkFilter(this))); + } + /** + * Return the Path object corresponding to path as resolved + * by realpath(3). + * + * If the realpath call fails for any reason, `undefined` is returned. + * + * Result is cached, and thus may be outdated if the filesystem is mutated. + * On success, returns a Path object. + */ + async realpath() { + if (this.#realpath) + return this.#realpath; + if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) + return undefined; + try { + const rp = await this.#fs.promises.realpath(this.fullpath()); + return (this.#realpath = this.resolve(rp)); + } + catch (_) { + this.#markENOREALPATH(); + } + } + /** + * Synchronous {@link realpath} + */ + realpathSync() { + if (this.#realpath) + return this.#realpath; + if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) + return undefined; + try { + const rp = this.#fs.realpathSync(this.fullpath()); + return (this.#realpath = this.resolve(rp)); + } + catch (_) { + this.#markENOREALPATH(); + } + } + /** + * Internal method to mark this Path object as the scurry cwd, + * called by {@link PathScurry#chdir} + * + * @internal + */ + [setAsCwd](oldCwd) { + if (oldCwd === this) + return; + oldCwd.isCWD = false; + this.isCWD = true; + const changed = new Set([]); + let rp = []; + let p = this; + while (p && p.parent) { + changed.add(p); + p.#relative = rp.join(this.sep); + p.#relativePosix = rp.join('/'); + p = p.parent; + rp.push('..'); + } + // now un-memoize parents of old cwd + p = oldCwd; + while (p && p.parent && !changed.has(p)) { + p.#relative = undefined; + p.#relativePosix = undefined; + p = p.parent; + } + } +} +exports.PathBase = PathBase; +/** + * Path class used on win32 systems + * + * Uses `'\\'` as the path separator for returned paths, either `'\\'` or `'/'` + * as the path separator for parsing paths. + */ +class PathWin32 extends PathBase { + /** + * Separator for generating path strings. + */ + sep = '\\'; + /** + * Separator for parsing path strings. + */ + splitSep = eitherSep; + /** + * Do not create new Path objects directly. They should always be accessed + * via the PathScurry class or other methods on the Path class. + * + * @internal + */ + constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) { + super(name, type, root, roots, nocase, children, opts); + } + /** + * @internal + */ + newChild(name, type = UNKNOWN, opts = {}) { + return new PathWin32(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts); + } + /** + * @internal + */ + getRootString(path) { + return node_path_1.win32.parse(path).root; + } + /** + * @internal + */ + getRoot(rootPath) { + rootPath = uncToDrive(rootPath.toUpperCase()); + if (rootPath === this.root.name) { + return this.root; + } + // ok, not that one, check if it matches another we know about + for (const [compare, root] of Object.entries(this.roots)) { + if (this.sameRoot(rootPath, compare)) { + return (this.roots[rootPath] = root); + } + } + // otherwise, have to create a new one. + return (this.roots[rootPath] = new PathScurryWin32(rootPath, this).root); + } + /** + * @internal + */ + sameRoot(rootPath, compare = this.root.name) { + // windows can (rarely) have case-sensitive filesystem, but + // UNC and drive letters are always case-insensitive, and canonically + // represented uppercase. + rootPath = rootPath + .toUpperCase() + .replace(/\//g, '\\') + .replace(uncDriveRegexp, '$1\\'); + return rootPath === compare; + } +} +exports.PathWin32 = PathWin32; +/** + * Path class used on all posix systems. + * + * Uses `'/'` as the path separator. + */ +class PathPosix extends PathBase { + /** + * separator for parsing path strings + */ + splitSep = '/'; + /** + * separator for generating path strings + */ + sep = '/'; + /** + * Do not create new Path objects directly. They should always be accessed + * via the PathScurry class or other methods on the Path class. + * + * @internal + */ + constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) { + super(name, type, root, roots, nocase, children, opts); + } + /** + * @internal + */ + getRootString(path) { + return path.startsWith('/') ? '/' : ''; + } + /** + * @internal + */ + getRoot(_rootPath) { + return this.root; + } + /** + * @internal + */ + newChild(name, type = UNKNOWN, opts = {}) { + return new PathPosix(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts); + } +} +exports.PathPosix = PathPosix; +/** + * The base class for all PathScurry classes, providing the interface for path + * resolution and filesystem operations. + * + * Typically, you should *not* instantiate this class directly, but rather one + * of the platform-specific classes, or the exported {@link PathScurry} which + * defaults to the current platform. + */ +class PathScurryBase { + /** + * The root Path entry for the current working directory of this Scurry + */ + root; + /** + * The string path for the root of this Scurry's current working directory + */ + rootPath; + /** + * A collection of all roots encountered, referenced by rootPath + */ + roots; + /** + * The Path entry corresponding to this PathScurry's current working directory. + */ + cwd; + #resolveCache; + #resolvePosixCache; + #children; + /** + * Perform path comparisons case-insensitively. + * + * Defaults true on Darwin and Windows systems, false elsewhere. + */ + nocase; + #fs; + /** + * This class should not be instantiated directly. + * + * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry + * + * @internal + */ + constructor(cwd = process.cwd(), pathImpl, sep, { nocase, childrenCacheSize = 16 * 1024, fs = defaultFS, } = {}) { + this.#fs = fsFromOption(fs); + if (cwd instanceof URL || cwd.startsWith('file://')) { + cwd = (0, node_url_1.fileURLToPath)(cwd); + } + // resolve and split root, and then add to the store. + // this is the only time we call path.resolve() + const cwdPath = pathImpl.resolve(cwd); + this.roots = Object.create(null); + this.rootPath = this.parseRootPath(cwdPath); + this.#resolveCache = new ResolveCache(); + this.#resolvePosixCache = new ResolveCache(); + this.#children = new ChildrenCache(childrenCacheSize); + const split = cwdPath.substring(this.rootPath.length).split(sep); + // resolve('/') leaves '', splits to [''], we don't want that. + if (split.length === 1 && !split[0]) { + split.pop(); + } + /* c8 ignore start */ + if (nocase === undefined) { + throw new TypeError('must provide nocase setting to PathScurryBase ctor'); + } + /* c8 ignore stop */ + this.nocase = nocase; + this.root = this.newRoot(this.#fs); + this.roots[this.rootPath] = this.root; + let prev = this.root; + let len = split.length - 1; + const joinSep = pathImpl.sep; + let abs = this.rootPath; + let sawFirst = false; + for (const part of split) { + const l = len--; + prev = prev.child(part, { + relative: new Array(l).fill('..').join(joinSep), + relativePosix: new Array(l).fill('..').join('/'), + fullpath: (abs += (sawFirst ? '' : joinSep) + part), + }); + sawFirst = true; + } + this.cwd = prev; + } + /** + * Get the depth of a provided path, string, or the cwd + */ + depth(path = this.cwd) { + if (typeof path === 'string') { + path = this.cwd.resolve(path); + } + return path.depth(); + } + /** + * Return the cache of child entries. Exposed so subclasses can create + * child Path objects in a platform-specific way. + * + * @internal + */ + childrenCache() { + return this.#children; + } + /** + * Resolve one or more path strings to a resolved string + * + * Same interface as require('path').resolve. + * + * Much faster than path.resolve() when called multiple times for the same + * path, because the resolved Path objects are cached. Much slower + * otherwise. + */ + resolve(...paths) { + // first figure out the minimum number of paths we have to test + // we always start at cwd, but any absolutes will bump the start + let r = ''; + for (let i = paths.length - 1; i >= 0; i--) { + const p = paths[i]; + if (!p || p === '.') + continue; + r = r ? `${p}/${r}` : p; + if (this.isAbsolute(p)) { + break; + } + } + const cached = this.#resolveCache.get(r); + if (cached !== undefined) { + return cached; + } + const result = this.cwd.resolve(r).fullpath(); + this.#resolveCache.set(r, result); + return result; + } + /** + * Resolve one or more path strings to a resolved string, returning + * the posix path. Identical to .resolve() on posix systems, but on + * windows will return a forward-slash separated UNC path. + * + * Same interface as require('path').resolve. + * + * Much faster than path.resolve() when called multiple times for the same + * path, because the resolved Path objects are cached. Much slower + * otherwise. + */ + resolvePosix(...paths) { + // first figure out the minimum number of paths we have to test + // we always start at cwd, but any absolutes will bump the start + let r = ''; + for (let i = paths.length - 1; i >= 0; i--) { + const p = paths[i]; + if (!p || p === '.') + continue; + r = r ? `${p}/${r}` : p; + if (this.isAbsolute(p)) { + break; + } + } + const cached = this.#resolvePosixCache.get(r); + if (cached !== undefined) { + return cached; + } + const result = this.cwd.resolve(r).fullpathPosix(); + this.#resolvePosixCache.set(r, result); + return result; + } + /** + * find the relative path from the cwd to the supplied path string or entry + */ + relative(entry = this.cwd) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + return entry.relative(); + } + /** + * find the relative path from the cwd to the supplied path string or + * entry, using / as the path delimiter, even on Windows. + */ + relativePosix(entry = this.cwd) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + return entry.relativePosix(); + } + /** + * Return the basename for the provided string or Path object + */ + basename(entry = this.cwd) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + return entry.name; + } + /** + * Return the dirname for the provided string or Path object + */ + dirname(entry = this.cwd) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + return (entry.parent || entry).fullpath(); + } + async readdir(entry = this.cwd, opts = { + withFileTypes: true, + }) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + opts = entry; + entry = this.cwd; + } + const { withFileTypes } = opts; + if (!entry.canReaddir()) { + return []; + } + else { + const p = await entry.readdir(); + return withFileTypes ? p : p.map(e => e.name); + } + } + readdirSync(entry = this.cwd, opts = { + withFileTypes: true, + }) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + opts = entry; + entry = this.cwd; + } + const { withFileTypes = true } = opts; + if (!entry.canReaddir()) { + return []; + } + else if (withFileTypes) { + return entry.readdirSync(); + } + else { + return entry.readdirSync().map(e => e.name); + } + } + /** + * Call lstat() on the string or Path object, and update all known + * information that can be determined. + * + * Note that unlike `fs.lstat()`, the returned value does not contain some + * information, such as `mode`, `dev`, `nlink`, and `ino`. If that + * information is required, you will need to call `fs.lstat` yourself. + * + * If the Path refers to a nonexistent file, or if the lstat call fails for + * any reason, `undefined` is returned. Otherwise the updated Path object is + * returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + */ + async lstat(entry = this.cwd) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + return entry.lstat(); + } + /** + * synchronous {@link PathScurryBase.lstat} + */ + lstatSync(entry = this.cwd) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + return entry.lstatSync(); + } + async readlink(entry = this.cwd, { withFileTypes } = { + withFileTypes: false, + }) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + withFileTypes = entry.withFileTypes; + entry = this.cwd; + } + const e = await entry.readlink(); + return withFileTypes ? e : e?.fullpath(); + } + readlinkSync(entry = this.cwd, { withFileTypes } = { + withFileTypes: false, + }) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + withFileTypes = entry.withFileTypes; + entry = this.cwd; + } + const e = entry.readlinkSync(); + return withFileTypes ? e : e?.fullpath(); + } + async realpath(entry = this.cwd, { withFileTypes } = { + withFileTypes: false, + }) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + withFileTypes = entry.withFileTypes; + entry = this.cwd; + } + const e = await entry.realpath(); + return withFileTypes ? e : e?.fullpath(); + } + realpathSync(entry = this.cwd, { withFileTypes } = { + withFileTypes: false, + }) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + withFileTypes = entry.withFileTypes; + entry = this.cwd; + } + const e = entry.realpathSync(); + return withFileTypes ? e : e?.fullpath(); + } + async walk(entry = this.cwd, opts = {}) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + opts = entry; + entry = this.cwd; + } + const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; + const results = []; + if (!filter || filter(entry)) { + results.push(withFileTypes ? entry : entry.fullpath()); + } + const dirs = new Set(); + const walk = (dir, cb) => { + dirs.add(dir); + dir.readdirCB((er, entries) => { + /* c8 ignore start */ + if (er) { + return cb(er); + } + /* c8 ignore stop */ + let len = entries.length; + if (!len) + return cb(); + const next = () => { + if (--len === 0) { + cb(); + } + }; + for (const e of entries) { + if (!filter || filter(e)) { + results.push(withFileTypes ? e : e.fullpath()); + } + if (follow && e.isSymbolicLink()) { + e.realpath() + .then(r => (r?.isUnknown() ? r.lstat() : r)) + .then(r => r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next()); + } + else { + if (e.shouldWalk(dirs, walkFilter)) { + walk(e, next); + } + else { + next(); + } + } + } + }, true); // zalgooooooo + }; + const start = entry; + return new Promise((res, rej) => { + walk(start, er => { + /* c8 ignore start */ + if (er) + return rej(er); + /* c8 ignore stop */ + res(results); + }); + }); + } + walkSync(entry = this.cwd, opts = {}) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + opts = entry; + entry = this.cwd; + } + const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; + const results = []; + if (!filter || filter(entry)) { + results.push(withFileTypes ? entry : entry.fullpath()); + } + const dirs = new Set([entry]); + for (const dir of dirs) { + const entries = dir.readdirSync(); + for (const e of entries) { + if (!filter || filter(e)) { + results.push(withFileTypes ? e : e.fullpath()); + } + let r = e; + if (e.isSymbolicLink()) { + if (!(follow && (r = e.realpathSync()))) + continue; + if (r.isUnknown()) + r.lstatSync(); + } + if (r.shouldWalk(dirs, walkFilter)) { + dirs.add(r); + } + } + } + return results; + } + /** + * Support for `for await` + * + * Alias for {@link PathScurryBase.iterate} + * + * Note: As of Node 19, this is very slow, compared to other methods of + * walking. Consider using {@link PathScurryBase.stream} if memory overhead + * and backpressure are concerns, or {@link PathScurryBase.walk} if not. + */ + [Symbol.asyncIterator]() { + return this.iterate(); + } + iterate(entry = this.cwd, options = {}) { + // iterating async over the stream is significantly more performant, + // especially in the warm-cache scenario, because it buffers up directory + // entries in the background instead of waiting for a yield for each one. + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + options = entry; + entry = this.cwd; + } + return this.stream(entry, options)[Symbol.asyncIterator](); + } + /** + * Iterating over a PathScurry performs a synchronous walk. + * + * Alias for {@link PathScurryBase.iterateSync} + */ + [Symbol.iterator]() { + return this.iterateSync(); + } + *iterateSync(entry = this.cwd, opts = {}) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + opts = entry; + entry = this.cwd; + } + const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; + if (!filter || filter(entry)) { + yield withFileTypes ? entry : entry.fullpath(); + } + const dirs = new Set([entry]); + for (const dir of dirs) { + const entries = dir.readdirSync(); + for (const e of entries) { + if (!filter || filter(e)) { + yield withFileTypes ? e : e.fullpath(); + } + let r = e; + if (e.isSymbolicLink()) { + if (!(follow && (r = e.realpathSync()))) + continue; + if (r.isUnknown()) + r.lstatSync(); + } + if (r.shouldWalk(dirs, walkFilter)) { + dirs.add(r); + } + } + } + } + stream(entry = this.cwd, opts = {}) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + opts = entry; + entry = this.cwd; + } + const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; + const results = new minipass_1.Minipass({ objectMode: true }); + if (!filter || filter(entry)) { + results.write(withFileTypes ? entry : entry.fullpath()); + } + const dirs = new Set(); + const queue = [entry]; + let processing = 0; + const process = () => { + let paused = false; + while (!paused) { + const dir = queue.shift(); + if (!dir) { + if (processing === 0) + results.end(); + return; + } + processing++; + dirs.add(dir); + const onReaddir = (er, entries, didRealpaths = false) => { + /* c8 ignore start */ + if (er) + return results.emit('error', er); + /* c8 ignore stop */ + if (follow && !didRealpaths) { + const promises = []; + for (const e of entries) { + if (e.isSymbolicLink()) { + promises.push(e + .realpath() + .then((r) => r?.isUnknown() ? r.lstat() : r)); + } + } + if (promises.length) { + Promise.all(promises).then(() => onReaddir(null, entries, true)); + return; + } + } + for (const e of entries) { + if (e && (!filter || filter(e))) { + if (!results.write(withFileTypes ? e : e.fullpath())) { + paused = true; + } + } + } + processing--; + for (const e of entries) { + const r = e.realpathCached() || e; + if (r.shouldWalk(dirs, walkFilter)) { + queue.push(r); + } + } + if (paused && !results.flowing) { + results.once('drain', process); + } + else if (!sync) { + process(); + } + }; + // zalgo containment + let sync = true; + dir.readdirCB(onReaddir, true); + sync = false; + } + }; + process(); + return results; + } + streamSync(entry = this.cwd, opts = {}) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + opts = entry; + entry = this.cwd; + } + const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; + const results = new minipass_1.Minipass({ objectMode: true }); + const dirs = new Set(); + if (!filter || filter(entry)) { + results.write(withFileTypes ? entry : entry.fullpath()); + } + const queue = [entry]; + let processing = 0; + const process = () => { + let paused = false; + while (!paused) { + const dir = queue.shift(); + if (!dir) { + if (processing === 0) + results.end(); + return; + } + processing++; + dirs.add(dir); + const entries = dir.readdirSync(); + for (const e of entries) { + if (!filter || filter(e)) { + if (!results.write(withFileTypes ? e : e.fullpath())) { + paused = true; + } + } + } + processing--; + for (const e of entries) { + let r = e; + if (e.isSymbolicLink()) { + if (!(follow && (r = e.realpathSync()))) + continue; + if (r.isUnknown()) + r.lstatSync(); + } + if (r.shouldWalk(dirs, walkFilter)) { + queue.push(r); + } + } + } + if (paused && !results.flowing) + results.once('drain', process); + }; + process(); + return results; + } + chdir(path = this.cwd) { + const oldCwd = this.cwd; + this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path; + this.cwd[setAsCwd](oldCwd); + } +} +exports.PathScurryBase = PathScurryBase; +/** + * Windows implementation of {@link PathScurryBase} + * + * Defaults to case insensitve, uses `'\\'` to generate path strings. Uses + * {@link PathWin32} for Path objects. + */ +class PathScurryWin32 extends PathScurryBase { + /** + * separator for generating path strings + */ + sep = '\\'; + constructor(cwd = process.cwd(), opts = {}) { + const { nocase = true } = opts; + super(cwd, node_path_1.win32, '\\', { ...opts, nocase }); + this.nocase = nocase; + for (let p = this.cwd; p; p = p.parent) { + p.nocase = this.nocase; + } + } + /** + * @internal + */ + parseRootPath(dir) { + // if the path starts with a single separator, it's not a UNC, and we'll + // just get separator as the root, and driveFromUNC will return \ + // In that case, mount \ on the root from the cwd. + return node_path_1.win32.parse(dir).root.toUpperCase(); + } + /** + * @internal + */ + newRoot(fs) { + return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs }); + } + /** + * Return true if the provided path string is an absolute path + */ + isAbsolute(p) { + return (p.startsWith('/') || p.startsWith('\\') || /^[a-z]:(\/|\\)/i.test(p)); + } +} +exports.PathScurryWin32 = PathScurryWin32; +/** + * {@link PathScurryBase} implementation for all posix systems other than Darwin. + * + * Defaults to case-sensitive matching, uses `'/'` to generate path strings. + * + * Uses {@link PathPosix} for Path objects. + */ +class PathScurryPosix extends PathScurryBase { + /** + * separator for generating path strings + */ + sep = '/'; + constructor(cwd = process.cwd(), opts = {}) { + const { nocase = false } = opts; + super(cwd, node_path_1.posix, '/', { ...opts, nocase }); + this.nocase = nocase; + } + /** + * @internal + */ + parseRootPath(_dir) { + return '/'; + } + /** + * @internal + */ + newRoot(fs) { + return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs }); + } + /** + * Return true if the provided path string is an absolute path + */ + isAbsolute(p) { + return p.startsWith('/'); + } +} +exports.PathScurryPosix = PathScurryPosix; +/** + * {@link PathScurryBase} implementation for Darwin (macOS) systems. + * + * Defaults to case-insensitive matching, uses `'/'` for generating path + * strings. + * + * Uses {@link PathPosix} for Path objects. + */ +class PathScurryDarwin extends PathScurryPosix { + constructor(cwd = process.cwd(), opts = {}) { + const { nocase = true } = opts; + super(cwd, { ...opts, nocase }); + } +} +exports.PathScurryDarwin = PathScurryDarwin; +/** + * Default {@link PathBase} implementation for the current platform. + * + * {@link PathWin32} on Windows systems, {@link PathPosix} on all others. + */ +exports.Path = process.platform === 'win32' ? PathWin32 : PathPosix; +/** + * Default {@link PathScurryBase} implementation for the current platform. + * + * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on + * Darwin (macOS) systems, {@link PathScurryPosix} on all others. + */ +exports.PathScurry = process.platform === 'win32' ? PathScurryWin32 + : process.platform === 'darwin' ? PathScurryDarwin + : PathScurryPosix; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/path-scurry/dist/commonjs/index.js.map b/node_modules/path-scurry/dist/commonjs/index.js.map new file mode 100644 index 0000000..fdeca21 --- /dev/null +++ b/node_modules/path-scurry/dist/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yCAAoC;AACpC,yCAAwC;AAExC,uCAAwC;AAExC,2BAMW;AACX,kDAAmC;AAEnC,MAAM,YAAY,GAAG,iBAAG,CAAC,MAAM,CAAA;AAC/B,yDAAyD;AACzD,8CAA8C;AAE9C,+CAAqE;AAErE,uCAAmC;AAqEnC,MAAM,SAAS,GAAY;IACzB,SAAS,EAAT,cAAS;IACT,OAAO,EAAE,YAAS;IAClB,WAAW,EAAX,gBAAW;IACX,YAAY,EAAZ,iBAAY;IACZ,YAAY;IACZ,QAAQ,EAAE;QACR,KAAK,EAAL,gBAAK;QACL,OAAO,EAAP,kBAAO;QACP,QAAQ,EAAR,mBAAQ;QACR,QAAQ,EAAR,mBAAQ;KACT;CACF,CAAA;AAED,0DAA0D;AAC1D,MAAM,YAAY,GAAG,CAAC,QAAmB,EAAW,EAAE,CACpD,CAAC,QAAQ,IAAI,QAAQ,KAAK,SAAS,IAAI,QAAQ,KAAK,QAAQ,CAAC,CAAC;IAC5D,SAAS;IACX,CAAC,CAAC;QACE,GAAG,SAAS;QACZ,GAAG,QAAQ;QACX,QAAQ,EAAE;YACR,GAAG,SAAS,CAAC,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AC,QAAQ,EACb,KAAK,EACL,SAAS,EACT,IAAI,CAAC,KAAK,EACV,IAAI,CAAC,MAAM,EACX,IAAI,CAAC,aAAa,EAAE,EACpB,EAAE,EAAE,EAAE,CACP,CAAA;IACH,CAAC;IAED;;OAEG;IACH,UAAU,CAAC,CAAS;QAClB,OAAO,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;IAC1B,CAAC;CACF;AA1CD,0CA0CC;AAED;;;;;;;GAOG;AACH,MAAa,gBAAiB,SAAQ,eAAe;IACnD,YACE,MAAoB,OAAO,CAAC,GAAG,EAAE,EACjC,OAAuB,EAAE;QAEzB,MAAM,EAAE,MAAM,GAAG,IAAI,EAAE,GAAG,IAAI,CAAA;QAC9B,KAAK,CAAC,GAAG,EAAE,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,CAAC,CAAA;IACjC,CAAC;CACF;AARD,4CAQC;AAED;;;;GAIG;AACU,QAAA,IAAI,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAA;AAGxE;;;;;GAKG;AACU,QAAA,UAAU,GAIrB,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,eAAe;IAC9C,CAAC,CAAC,OAAO,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,gBAAgB;QAClD,CAAC,CAAC,eAAe,CAAA","sourcesContent":["import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'node:path'\n\nimport { fileURLToPath } from 'node:url'\n\nimport {\n lstatSync,\n readdir as readdirCB,\n readdirSync,\n readlinkSync,\n realpathSync as rps,\n} from 'fs'\nimport * as actualFS from 'node:fs'\n\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\n\nimport { lstat, readdir, readlink, realpath } from 'node:fs/promises'\n\nimport { Minipass } from 'minipass'\nimport type { Dirent, Stats } from 'node:fs'\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() ? IFREG\n : s.isDirectory() ? IFDIR\n : s.isSymbolicLink() ? IFLNK\n : s.isCharacterDevice() ? IFCHR\n : s.isBlockDevice() ? IFBLK\n : s.isSocket() ? IFSOCK\n : s.isFIFO() ? 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 * boolean indicating that this path is the current working directory\n * of the PathScurry collection that contains it.\n */\n isCWD: boolean = false\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['parentPath'] refers to the path of the\n * directory that was passed to readdir. For root entries, it's the path\n * to the entry itself.\n */\n get parentPath(): string {\n return (this.parent || this).fullpath()\n }\n\n /**\n * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,\n * this property refers to the *parent* path, not the path object itself.\n */\n get path(): string {\n return this.parentPath\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 =\n 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 =\n this.nocase ? normalizeNocase(pathPart) : 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 =\n this.#fullpath ? this.#fullpath + s + pathPart : 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.isCWD) return ''\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.isCWD) return ''\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 (\n this.isUnknown() ? 'Unknown'\n : this.isDirectory() ? 'Directory'\n : this.isFile() ? 'File'\n : this.isSymbolicLink() ? 'SymbolicLink'\n : this.isFIFO() ? 'FIFO'\n : this.isCharacterDevice() ? 'CharacterDevice'\n : this.isBlockDevice() ? 'BlockDevice'\n : /* c8 ignore start */ this.isSocket() ? 'Socket'\n : 'Unknown'\n )\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 = (await this.parent.realpath())?.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.realpathSync()?.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 const c = children[p]\n if (c) c.#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 =\n this.nocase ? normalizeNocase(e.name) : 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 oldCwd.isCWD = false\n this.isCWD = true\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' ? PathScurryWin32\n : process.platform === 'darwin' ? PathScurryDarwin\n : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType\n"]} \ No newline at end of file diff --git a/node_modules/path-scurry/dist/commonjs/package.json b/node_modules/path-scurry/dist/commonjs/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/node_modules/path-scurry/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/path-scurry/dist/esm/index.d.ts b/node_modules/path-scurry/dist/esm/index.d.ts new file mode 100644 index 0000000..33b3edb --- /dev/null +++ b/node_modules/path-scurry/dist/esm/index.d.ts @@ -0,0 +1,1116 @@ +/// +/// +/// +import { LRUCache } from 'lru-cache'; +import { posix, win32 } from 'node:path'; +import { Minipass } from 'minipass'; +import type { Dirent, Stats } from 'node:fs'; +/** + * An object that will be used to override the default `fs` + * methods. Any methods that are not overridden will use Node's + * built-in implementations. + * + * - lstatSync + * - readdir (callback `withFileTypes` Dirent variant, used for + * readdirCB and most walks) + * - readdirSync + * - readlinkSync + * - realpathSync + * - promises: Object containing the following async methods: + * - lstat + * - readdir (Dirent variant only) + * - readlink + * - realpath + */ +export interface FSOption { + lstatSync?: (path: string) => Stats; + readdir?: (path: string, options: { + withFileTypes: true; + }, cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any) => void; + readdirSync?: (path: string, options: { + withFileTypes: true; + }) => Dirent[]; + readlinkSync?: (path: string) => string; + realpathSync?: (path: string) => string; + promises?: { + lstat?: (path: string) => Promise; + readdir?: (path: string, options: { + withFileTypes: true; + }) => Promise; + readlink?: (path: string) => Promise; + realpath?: (path: string) => Promise; + [k: string]: any; + }; + [k: string]: any; +} +interface FSValue { + lstatSync: (path: string) => Stats; + readdir: (path: string, options: { + withFileTypes: true; + }, cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any) => void; + readdirSync: (path: string, options: { + withFileTypes: true; + }) => Dirent[]; + readlinkSync: (path: string) => string; + realpathSync: (path: string) => string; + promises: { + lstat: (path: string) => Promise; + readdir: (path: string, options: { + withFileTypes: true; + }) => Promise; + readlink: (path: string) => Promise; + realpath: (path: string) => Promise; + [k: string]: any; + }; + [k: string]: any; +} +export type Type = 'Unknown' | 'FIFO' | 'CharacterDevice' | 'Directory' | 'BlockDevice' | 'File' | 'SymbolicLink' | 'Socket'; +/** + * Options that may be provided to the Path constructor + */ +export interface PathOpts { + fullpath?: string; + relative?: string; + relativePosix?: string; + parent?: PathBase; + /** + * See {@link FSOption} + */ + fs?: FSOption; +} +/** + * An LRUCache for storing resolved path strings or Path objects. + * @internal + */ +export declare class ResolveCache extends LRUCache { + constructor(); +} +/** + * an LRUCache for storing child entries. + * @internal + */ +export declare class ChildrenCache extends LRUCache { + constructor(maxSize?: number); +} +/** + * Array of Path objects, plus a marker indicating the first provisional entry + * + * @internal + */ +export type Children = PathBase[] & { + provisional: number; +}; +declare const setAsCwd: unique symbol; +/** + * Path objects are sort of like a super-powered + * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent} + * + * Each one represents a single filesystem entry on disk, which may or may not + * exist. It includes methods for reading various types of information via + * lstat, readlink, and readdir, and caches all information to the greatest + * degree possible. + * + * Note that fs operations that would normally throw will instead return an + * "empty" value. This is in order to prevent excessive overhead from error + * stack traces. + */ +export declare abstract class PathBase implements Dirent { + #private; + /** + * the basename of this path + * + * **Important**: *always* test the path name against any test string + * usingthe {@link isNamed} method, and not by directly comparing this + * string. Otherwise, unicode path strings that the system sees as identical + * will not be properly treated as the same path, leading to incorrect + * behavior and possible security issues. + */ + name: string; + /** + * the Path entry corresponding to the path root. + * + * @internal + */ + root: PathBase; + /** + * All roots found within the current PathScurry family + * + * @internal + */ + roots: { + [k: string]: PathBase; + }; + /** + * a reference to the parent path, or undefined in the case of root entries + * + * @internal + */ + parent?: PathBase; + /** + * boolean indicating whether paths are compared case-insensitively + * @internal + */ + nocase: boolean; + /** + * boolean indicating that this path is the current working directory + * of the PathScurry collection that contains it. + */ + isCWD: boolean; + /** + * the string or regexp used to split paths. On posix, it is `'/'`, and on + * windows it is a RegExp matching either `'/'` or `'\\'` + */ + abstract splitSep: string | RegExp; + /** + * The path separator string to use when joining paths + */ + abstract sep: string; + get dev(): number | undefined; + get mode(): number | undefined; + get nlink(): number | undefined; + get uid(): number | undefined; + get gid(): number | undefined; + get rdev(): number | undefined; + get blksize(): number | undefined; + get ino(): number | undefined; + get size(): number | undefined; + get blocks(): number | undefined; + get atimeMs(): number | undefined; + get mtimeMs(): number | undefined; + get ctimeMs(): number | undefined; + get birthtimeMs(): number | undefined; + get atime(): Date | undefined; + get mtime(): Date | undefined; + get ctime(): Date | undefined; + get birthtime(): Date | undefined; + /** + * This property is for compatibility with the Dirent class as of + * Node v20, where Dirent['parentPath'] refers to the path of the + * directory that was passed to readdir. For root entries, it's the path + * to the entry itself. + */ + get parentPath(): string; + /** + * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively, + * this property refers to the *parent* path, not the path object itself. + */ + get path(): string; + /** + * Do not create new Path objects directly. They should always be accessed + * via the PathScurry class or other methods on the Path class. + * + * @internal + */ + constructor(name: string, type: number | undefined, root: PathBase | undefined, roots: { + [k: string]: PathBase; + }, nocase: boolean, children: ChildrenCache, opts: PathOpts); + /** + * Returns the depth of the Path object from its root. + * + * For example, a path at `/foo/bar` would have a depth of 2. + */ + depth(): number; + /** + * @internal + */ + abstract getRootString(path: string): string; + /** + * @internal + */ + abstract getRoot(rootPath: string): PathBase; + /** + * @internal + */ + abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase; + /** + * @internal + */ + childrenCache(): ChildrenCache; + /** + * Get the Path object referenced by the string path, resolved from this Path + */ + resolve(path?: string): PathBase; + /** + * Returns the cached children Path objects, if still available. If they + * have fallen out of the cache, then returns an empty array, and resets the + * READDIR_CALLED bit, so that future calls to readdir() will require an fs + * lookup. + * + * @internal + */ + children(): Children; + /** + * Resolves a path portion and returns or creates the child Path. + * + * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is + * `'..'`. + * + * This should not be called directly. If `pathPart` contains any path + * separators, it will lead to unsafe undefined behavior. + * + * Use `Path.resolve()` instead. + * + * @internal + */ + child(pathPart: string, opts?: PathOpts): PathBase; + /** + * The relative path from the cwd. If it does not share an ancestor with + * the cwd, then this ends up being equivalent to the fullpath() + */ + relative(): string; + /** + * The relative path from the cwd, using / as the path separator. + * If it does not share an ancestor with + * the cwd, then this ends up being equivalent to the fullpathPosix() + * On posix systems, this is identical to relative(). + */ + relativePosix(): string; + /** + * The fully resolved path string for this Path entry + */ + fullpath(): string; + /** + * On platforms other than windows, this is identical to fullpath. + * + * On windows, this is overridden to return the forward-slash form of the + * full UNC path. + */ + fullpathPosix(): string; + /** + * Is the Path of an unknown type? + * + * Note that we might know *something* about it if there has been a previous + * filesystem operation, for example that it does not exist, or is not a + * link, or whether it has child entries. + */ + isUnknown(): boolean; + isType(type: Type): boolean; + getType(): Type; + /** + * Is the Path a regular file? + */ + isFile(): boolean; + /** + * Is the Path a directory? + */ + isDirectory(): boolean; + /** + * Is the path a character device? + */ + isCharacterDevice(): boolean; + /** + * Is the path a block device? + */ + isBlockDevice(): boolean; + /** + * Is the path a FIFO pipe? + */ + isFIFO(): boolean; + /** + * Is the path a socket? + */ + isSocket(): boolean; + /** + * Is the path a symbolic link? + */ + isSymbolicLink(): boolean; + /** + * Return the entry if it has been subject of a successful lstat, or + * undefined otherwise. + * + * Does not read the filesystem, so an undefined result *could* simply + * mean that we haven't called lstat on it. + */ + lstatCached(): PathBase | undefined; + /** + * Return the cached link target if the entry has been the subject of a + * successful readlink, or undefined otherwise. + * + * Does not read the filesystem, so an undefined result *could* just mean we + * don't have any cached data. Only use it if you are very sure that a + * readlink() has been called at some point. + */ + readlinkCached(): PathBase | undefined; + /** + * Returns the cached realpath target if the entry has been the subject + * of a successful realpath, or undefined otherwise. + * + * Does not read the filesystem, so an undefined result *could* just mean we + * don't have any cached data. Only use it if you are very sure that a + * realpath() has been called at some point. + */ + realpathCached(): PathBase | undefined; + /** + * Returns the cached child Path entries array if the entry has been the + * subject of a successful readdir(), or [] otherwise. + * + * Does not read the filesystem, so an empty array *could* just mean we + * don't have any cached data. Only use it if you are very sure that a + * readdir() has been called recently enough to still be valid. + */ + readdirCached(): PathBase[]; + /** + * Return true if it's worth trying to readlink. Ie, we don't (yet) have + * any indication that readlink will definitely fail. + * + * Returns false if the path is known to not be a symlink, if a previous + * readlink failed, or if the entry does not exist. + */ + canReadlink(): boolean; + /** + * Return true if readdir has previously been successfully called on this + * path, indicating that cachedReaddir() is likely valid. + */ + calledReaddir(): boolean; + /** + * Returns true if the path is known to not exist. That is, a previous lstat + * or readdir failed to verify its existence when that would have been + * expected, or a parent entry was marked either enoent or enotdir. + */ + isENOENT(): boolean; + /** + * Return true if the path is a match for the given path name. This handles + * case sensitivity and unicode normalization. + * + * Note: even on case-sensitive systems, it is **not** safe to test the + * equality of the `.name` property to determine whether a given pathname + * matches, due to unicode normalization mismatches. + * + * Always use this method instead of testing the `path.name` property + * directly. + */ + isNamed(n: string): boolean; + /** + * Return the Path object corresponding to the target of a symbolic link. + * + * If the Path is not a symbolic link, or if the readlink call fails for any + * reason, `undefined` is returned. + * + * Result is cached, and thus may be outdated if the filesystem is mutated. + */ + readlink(): Promise; + /** + * Synchronous {@link PathBase.readlink} + */ + readlinkSync(): PathBase | undefined; + /** + * Call lstat() on this Path, and update all known information that can be + * determined. + * + * Note that unlike `fs.lstat()`, the returned value does not contain some + * information, such as `mode`, `dev`, `nlink`, and `ino`. If that + * information is required, you will need to call `fs.lstat` yourself. + * + * If the Path refers to a nonexistent file, or if the lstat call fails for + * any reason, `undefined` is returned. Otherwise the updated Path object is + * returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + */ + lstat(): Promise; + /** + * synchronous {@link PathBase.lstat} + */ + lstatSync(): PathBase | undefined; + /** + * Standard node-style callback interface to get list of directory entries. + * + * If the Path cannot or does not contain any children, then an empty array + * is returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + * + * @param cb The callback called with (er, entries). Note that the `er` + * param is somewhat extraneous, as all readdir() errors are handled and + * simply result in an empty set of entries being returned. + * @param allowZalgo Boolean indicating that immediately known results should + * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release + * zalgo at your peril, the dark pony lord is devious and unforgiving. + */ + readdirCB(cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any, allowZalgo?: boolean): void; + /** + * Return an array of known child entries. + * + * If the Path cannot or does not contain any children, then an empty array + * is returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + */ + readdir(): Promise; + /** + * synchronous {@link PathBase.readdir} + */ + readdirSync(): PathBase[]; + canReaddir(): boolean; + shouldWalk(dirs: Set, walkFilter?: (e: PathBase) => boolean): boolean; + /** + * Return the Path object corresponding to path as resolved + * by realpath(3). + * + * If the realpath call fails for any reason, `undefined` is returned. + * + * Result is cached, and thus may be outdated if the filesystem is mutated. + * On success, returns a Path object. + */ + realpath(): Promise; + /** + * Synchronous {@link realpath} + */ + realpathSync(): PathBase | undefined; + /** + * Internal method to mark this Path object as the scurry cwd, + * called by {@link PathScurry#chdir} + * + * @internal + */ + [setAsCwd](oldCwd: PathBase): void; +} +/** + * Path class used on win32 systems + * + * Uses `'\\'` as the path separator for returned paths, either `'\\'` or `'/'` + * as the path separator for parsing paths. + */ +export declare class PathWin32 extends PathBase { + /** + * Separator for generating path strings. + */ + sep: '\\'; + /** + * Separator for parsing path strings. + */ + splitSep: RegExp; + /** + * Do not create new Path objects directly. They should always be accessed + * via the PathScurry class or other methods on the Path class. + * + * @internal + */ + constructor(name: string, type: number | undefined, root: PathBase | undefined, roots: { + [k: string]: PathBase; + }, nocase: boolean, children: ChildrenCache, opts: PathOpts); + /** + * @internal + */ + newChild(name: string, type?: number, opts?: PathOpts): PathWin32; + /** + * @internal + */ + getRootString(path: string): string; + /** + * @internal + */ + getRoot(rootPath: string): PathBase; + /** + * @internal + */ + sameRoot(rootPath: string, compare?: string): boolean; +} +/** + * Path class used on all posix systems. + * + * Uses `'/'` as the path separator. + */ +export declare class PathPosix extends PathBase { + /** + * separator for parsing path strings + */ + splitSep: '/'; + /** + * separator for generating path strings + */ + sep: '/'; + /** + * Do not create new Path objects directly. They should always be accessed + * via the PathScurry class or other methods on the Path class. + * + * @internal + */ + constructor(name: string, type: number | undefined, root: PathBase | undefined, roots: { + [k: string]: PathBase; + }, nocase: boolean, children: ChildrenCache, opts: PathOpts); + /** + * @internal + */ + getRootString(path: string): string; + /** + * @internal + */ + getRoot(_rootPath: string): PathBase; + /** + * @internal + */ + newChild(name: string, type?: number, opts?: PathOpts): PathPosix; +} +/** + * Options that may be provided to the PathScurry constructor + */ +export interface PathScurryOpts { + /** + * perform case-insensitive path matching. Default based on platform + * subclass. + */ + nocase?: boolean; + /** + * Number of Path entries to keep in the cache of Path child references. + * + * Setting this higher than 65536 will dramatically increase the data + * consumption and construction time overhead of each PathScurry. + * + * Setting this value to 256 or lower will significantly reduce the data + * consumption and construction time overhead, but may also reduce resolve() + * and readdir() performance on large filesystems. + * + * Default `16384`. + */ + childrenCacheSize?: number; + /** + * An object that overrides the built-in functions from the fs and + * fs/promises modules. + * + * See {@link FSOption} + */ + fs?: FSOption; +} +/** + * The base class for all PathScurry classes, providing the interface for path + * resolution and filesystem operations. + * + * Typically, you should *not* instantiate this class directly, but rather one + * of the platform-specific classes, or the exported {@link PathScurry} which + * defaults to the current platform. + */ +export declare abstract class PathScurryBase { + #private; + /** + * The root Path entry for the current working directory of this Scurry + */ + root: PathBase; + /** + * The string path for the root of this Scurry's current working directory + */ + rootPath: string; + /** + * A collection of all roots encountered, referenced by rootPath + */ + roots: { + [k: string]: PathBase; + }; + /** + * The Path entry corresponding to this PathScurry's current working directory. + */ + cwd: PathBase; + /** + * Perform path comparisons case-insensitively. + * + * Defaults true on Darwin and Windows systems, false elsewhere. + */ + nocase: boolean; + /** + * The path separator used for parsing paths + * + * `'/'` on Posix systems, either `'/'` or `'\\'` on Windows + */ + abstract sep: string | RegExp; + /** + * This class should not be instantiated directly. + * + * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry + * + * @internal + */ + constructor(cwd: string | URL | undefined, pathImpl: typeof win32 | typeof posix, sep: string | RegExp, { nocase, childrenCacheSize, fs, }?: PathScurryOpts); + /** + * Get the depth of a provided path, string, or the cwd + */ + depth(path?: Path | string): number; + /** + * Parse the root portion of a path string + * + * @internal + */ + abstract parseRootPath(dir: string): string; + /** + * create a new Path to use as root during construction. + * + * @internal + */ + abstract newRoot(fs: FSValue): PathBase; + /** + * Determine whether a given path string is absolute + */ + abstract isAbsolute(p: string): boolean; + /** + * Return the cache of child entries. Exposed so subclasses can create + * child Path objects in a platform-specific way. + * + * @internal + */ + childrenCache(): ChildrenCache; + /** + * Resolve one or more path strings to a resolved string + * + * Same interface as require('path').resolve. + * + * Much faster than path.resolve() when called multiple times for the same + * path, because the resolved Path objects are cached. Much slower + * otherwise. + */ + resolve(...paths: string[]): string; + /** + * Resolve one or more path strings to a resolved string, returning + * the posix path. Identical to .resolve() on posix systems, but on + * windows will return a forward-slash separated UNC path. + * + * Same interface as require('path').resolve. + * + * Much faster than path.resolve() when called multiple times for the same + * path, because the resolved Path objects are cached. Much slower + * otherwise. + */ + resolvePosix(...paths: string[]): string; + /** + * find the relative path from the cwd to the supplied path string or entry + */ + relative(entry?: PathBase | string): string; + /** + * find the relative path from the cwd to the supplied path string or + * entry, using / as the path delimiter, even on Windows. + */ + relativePosix(entry?: PathBase | string): string; + /** + * Return the basename for the provided string or Path object + */ + basename(entry?: PathBase | string): string; + /** + * Return the dirname for the provided string or Path object + */ + dirname(entry?: PathBase | string): string; + /** + * Return an array of known child entries. + * + * First argument may be either a string, or a Path object. + * + * If the Path cannot or does not contain any children, then an empty array + * is returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + * + * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set + * `{ withFileTypes: false }` to return strings. + */ + readdir(): Promise; + readdir(opts: { + withFileTypes: true; + }): Promise; + readdir(opts: { + withFileTypes: false; + }): Promise; + readdir(opts: { + withFileTypes: boolean; + }): Promise; + readdir(entry: PathBase | string): Promise; + readdir(entry: PathBase | string, opts: { + withFileTypes: true; + }): Promise; + readdir(entry: PathBase | string, opts: { + withFileTypes: false; + }): Promise; + readdir(entry: PathBase | string, opts: { + withFileTypes: boolean; + }): Promise; + /** + * synchronous {@link PathScurryBase.readdir} + */ + readdirSync(): PathBase[]; + readdirSync(opts: { + withFileTypes: true; + }): PathBase[]; + readdirSync(opts: { + withFileTypes: false; + }): string[]; + readdirSync(opts: { + withFileTypes: boolean; + }): PathBase[] | string[]; + readdirSync(entry: PathBase | string): PathBase[]; + readdirSync(entry: PathBase | string, opts: { + withFileTypes: true; + }): PathBase[]; + readdirSync(entry: PathBase | string, opts: { + withFileTypes: false; + }): string[]; + readdirSync(entry: PathBase | string, opts: { + withFileTypes: boolean; + }): PathBase[] | string[]; + /** + * Call lstat() on the string or Path object, and update all known + * information that can be determined. + * + * Note that unlike `fs.lstat()`, the returned value does not contain some + * information, such as `mode`, `dev`, `nlink`, and `ino`. If that + * information is required, you will need to call `fs.lstat` yourself. + * + * If the Path refers to a nonexistent file, or if the lstat call fails for + * any reason, `undefined` is returned. Otherwise the updated Path object is + * returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + */ + lstat(entry?: string | PathBase): Promise; + /** + * synchronous {@link PathScurryBase.lstat} + */ + lstatSync(entry?: string | PathBase): PathBase | undefined; + /** + * Return the Path object or string path corresponding to the target of a + * symbolic link. + * + * If the path is not a symbolic link, or if the readlink call fails for any + * reason, `undefined` is returned. + * + * Result is cached, and thus may be outdated if the filesystem is mutated. + * + * `{withFileTypes}` option defaults to `false`. + * + * On success, returns a Path object if `withFileTypes` option is true, + * otherwise a string. + */ + readlink(): Promise; + readlink(opt: { + withFileTypes: false; + }): Promise; + readlink(opt: { + withFileTypes: true; + }): Promise; + readlink(opt: { + withFileTypes: boolean; + }): Promise; + readlink(entry: string | PathBase, opt?: { + withFileTypes: false; + }): Promise; + readlink(entry: string | PathBase, opt: { + withFileTypes: true; + }): Promise; + readlink(entry: string | PathBase, opt: { + withFileTypes: boolean; + }): Promise; + /** + * synchronous {@link PathScurryBase.readlink} + */ + readlinkSync(): string | undefined; + readlinkSync(opt: { + withFileTypes: false; + }): string | undefined; + readlinkSync(opt: { + withFileTypes: true; + }): PathBase | undefined; + readlinkSync(opt: { + withFileTypes: boolean; + }): PathBase | string | undefined; + readlinkSync(entry: string | PathBase, opt?: { + withFileTypes: false; + }): string | undefined; + readlinkSync(entry: string | PathBase, opt: { + withFileTypes: true; + }): PathBase | undefined; + readlinkSync(entry: string | PathBase, opt: { + withFileTypes: boolean; + }): string | PathBase | undefined; + /** + * Return the Path object or string path corresponding to path as resolved + * by realpath(3). + * + * If the realpath call fails for any reason, `undefined` is returned. + * + * Result is cached, and thus may be outdated if the filesystem is mutated. + * + * `{withFileTypes}` option defaults to `false`. + * + * On success, returns a Path object if `withFileTypes` option is true, + * otherwise a string. + */ + realpath(): Promise; + realpath(opt: { + withFileTypes: false; + }): Promise; + realpath(opt: { + withFileTypes: true; + }): Promise; + realpath(opt: { + withFileTypes: boolean; + }): Promise; + realpath(entry: string | PathBase, opt?: { + withFileTypes: false; + }): Promise; + realpath(entry: string | PathBase, opt: { + withFileTypes: true; + }): Promise; + realpath(entry: string | PathBase, opt: { + withFileTypes: boolean; + }): Promise; + realpathSync(): string | undefined; + realpathSync(opt: { + withFileTypes: false; + }): string | undefined; + realpathSync(opt: { + withFileTypes: true; + }): PathBase | undefined; + realpathSync(opt: { + withFileTypes: boolean; + }): PathBase | string | undefined; + realpathSync(entry: string | PathBase, opt?: { + withFileTypes: false; + }): string | undefined; + realpathSync(entry: string | PathBase, opt: { + withFileTypes: true; + }): PathBase | undefined; + realpathSync(entry: string | PathBase, opt: { + withFileTypes: boolean; + }): string | PathBase | undefined; + /** + * Asynchronously walk the directory tree, returning an array of + * all path strings or Path objects found. + * + * Note that this will be extremely memory-hungry on large filesystems. + * In such cases, it may be better to use the stream or async iterator + * walk implementation. + */ + walk(): Promise; + walk(opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): Promise; + walk(opts: WalkOptionsWithFileTypesFalse): Promise; + walk(opts: WalkOptions): Promise; + walk(entry: string | PathBase): Promise; + walk(entry: string | PathBase, opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): Promise; + walk(entry: string | PathBase, opts: WalkOptionsWithFileTypesFalse): Promise; + walk(entry: string | PathBase, opts: WalkOptions): Promise; + /** + * Synchronously walk the directory tree, returning an array of + * all path strings or Path objects found. + * + * Note that this will be extremely memory-hungry on large filesystems. + * In such cases, it may be better to use the stream or async iterator + * walk implementation. + */ + walkSync(): PathBase[]; + walkSync(opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): PathBase[]; + walkSync(opts: WalkOptionsWithFileTypesFalse): string[]; + walkSync(opts: WalkOptions): string[] | PathBase[]; + walkSync(entry: string | PathBase): PathBase[]; + walkSync(entry: string | PathBase, opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue): PathBase[]; + walkSync(entry: string | PathBase, opts: WalkOptionsWithFileTypesFalse): string[]; + walkSync(entry: string | PathBase, opts: WalkOptions): PathBase[] | string[]; + /** + * Support for `for await` + * + * Alias for {@link PathScurryBase.iterate} + * + * Note: As of Node 19, this is very slow, compared to other methods of + * walking. Consider using {@link PathScurryBase.stream} if memory overhead + * and backpressure are concerns, or {@link PathScurryBase.walk} if not. + */ + [Symbol.asyncIterator](): AsyncGenerator; + /** + * Async generator form of {@link PathScurryBase.walk} + * + * Note: As of Node 19, this is very slow, compared to other methods of + * walking, especially if most/all of the directory tree has been previously + * walked. Consider using {@link PathScurryBase.stream} if memory overhead + * and backpressure are concerns, or {@link PathScurryBase.walk} if not. + */ + iterate(): AsyncGenerator; + iterate(opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): AsyncGenerator; + iterate(opts: WalkOptionsWithFileTypesFalse): AsyncGenerator; + iterate(opts: WalkOptions): AsyncGenerator; + iterate(entry: string | PathBase): AsyncGenerator; + iterate(entry: string | PathBase, opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): AsyncGenerator; + iterate(entry: string | PathBase, opts: WalkOptionsWithFileTypesFalse): AsyncGenerator; + iterate(entry: string | PathBase, opts: WalkOptions): AsyncGenerator; + /** + * Iterating over a PathScurry performs a synchronous walk. + * + * Alias for {@link PathScurryBase.iterateSync} + */ + [Symbol.iterator](): Generator; + iterateSync(): Generator; + iterateSync(opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): Generator; + iterateSync(opts: WalkOptionsWithFileTypesFalse): Generator; + iterateSync(opts: WalkOptions): Generator; + iterateSync(entry: string | PathBase): Generator; + iterateSync(entry: string | PathBase, opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): Generator; + iterateSync(entry: string | PathBase, opts: WalkOptionsWithFileTypesFalse): Generator; + iterateSync(entry: string | PathBase, opts: WalkOptions): Generator; + /** + * Stream form of {@link PathScurryBase.walk} + * + * Returns a Minipass stream that emits {@link PathBase} objects by default, + * or strings if `{ withFileTypes: false }` is set in the options. + */ + stream(): Minipass; + stream(opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): Minipass; + stream(opts: WalkOptionsWithFileTypesFalse): Minipass; + stream(opts: WalkOptions): Minipass; + stream(entry: string | PathBase): Minipass; + stream(entry: string | PathBase, opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue): Minipass; + stream(entry: string | PathBase, opts: WalkOptionsWithFileTypesFalse): Minipass; + stream(entry: string | PathBase, opts: WalkOptions): Minipass | Minipass; + /** + * Synchronous form of {@link PathScurryBase.stream} + * + * Returns a Minipass stream that emits {@link PathBase} objects by default, + * or strings if `{ withFileTypes: false }` is set in the options. + * + * Will complete the walk in a single tick if the stream is consumed fully. + * Otherwise, will pause as needed for stream backpressure. + */ + streamSync(): Minipass; + streamSync(opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset): Minipass; + streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass; + streamSync(opts: WalkOptions): Minipass; + streamSync(entry: string | PathBase): Minipass; + streamSync(entry: string | PathBase, opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue): Minipass; + streamSync(entry: string | PathBase, opts: WalkOptionsWithFileTypesFalse): Minipass; + streamSync(entry: string | PathBase, opts: WalkOptions): Minipass | Minipass; + chdir(path?: string | Path): void; +} +/** + * Options provided to all walk methods. + */ +export interface WalkOptions { + /** + * Return results as {@link PathBase} objects rather than strings. + * When set to false, results are fully resolved paths, as returned by + * {@link PathBase.fullpath}. + * @default true + */ + withFileTypes?: boolean; + /** + * Attempt to read directory entries from symbolic links. Otherwise, only + * actual directories are traversed. Regardless of this setting, a given + * target path will only ever be walked once, meaning that a symbolic link + * to a previously traversed directory will never be followed. + * + * Setting this imposes a slight performance penalty, because `readlink` + * must be called on all symbolic links encountered, in order to avoid + * infinite cycles. + * @default false + */ + follow?: boolean; + /** + * Only return entries where the provided function returns true. + * + * This will not prevent directories from being traversed, even if they do + * not pass the filter, though it will prevent directories themselves from + * being included in the result set. See {@link walkFilter} + * + * Asynchronous functions are not supported here. + * + * By default, if no filter is provided, all entries and traversed + * directories are included. + */ + filter?: (entry: PathBase) => boolean; + /** + * Only traverse directories (and in the case of {@link follow} being set to + * true, symbolic links to directories) if the provided function returns + * true. + * + * This will not prevent directories from being included in the result set, + * even if they do not pass the supplied filter function. See {@link filter} + * to do that. + * + * Asynchronous functions are not supported here. + */ + walkFilter?: (entry: PathBase) => boolean; +} +export type WalkOptionsWithFileTypesUnset = WalkOptions & { + withFileTypes?: undefined; +}; +export type WalkOptionsWithFileTypesTrue = WalkOptions & { + withFileTypes: true; +}; +export type WalkOptionsWithFileTypesFalse = WalkOptions & { + withFileTypes: false; +}; +/** + * Windows implementation of {@link PathScurryBase} + * + * Defaults to case insensitve, uses `'\\'` to generate path strings. Uses + * {@link PathWin32} for Path objects. + */ +export declare class PathScurryWin32 extends PathScurryBase { + /** + * separator for generating path strings + */ + sep: '\\'; + constructor(cwd?: URL | string, opts?: PathScurryOpts); + /** + * @internal + */ + parseRootPath(dir: string): string; + /** + * @internal + */ + newRoot(fs: FSValue): PathWin32; + /** + * Return true if the provided path string is an absolute path + */ + isAbsolute(p: string): boolean; +} +/** + * {@link PathScurryBase} implementation for all posix systems other than Darwin. + * + * Defaults to case-sensitive matching, uses `'/'` to generate path strings. + * + * Uses {@link PathPosix} for Path objects. + */ +export declare class PathScurryPosix extends PathScurryBase { + /** + * separator for generating path strings + */ + sep: '/'; + constructor(cwd?: URL | string, opts?: PathScurryOpts); + /** + * @internal + */ + parseRootPath(_dir: string): string; + /** + * @internal + */ + newRoot(fs: FSValue): PathPosix; + /** + * Return true if the provided path string is an absolute path + */ + isAbsolute(p: string): boolean; +} +/** + * {@link PathScurryBase} implementation for Darwin (macOS) systems. + * + * Defaults to case-insensitive matching, uses `'/'` for generating path + * strings. + * + * Uses {@link PathPosix} for Path objects. + */ +export declare class PathScurryDarwin extends PathScurryPosix { + constructor(cwd?: URL | string, opts?: PathScurryOpts); +} +/** + * Default {@link PathBase} implementation for the current platform. + * + * {@link PathWin32} on Windows systems, {@link PathPosix} on all others. + */ +export declare const Path: typeof PathWin32 | typeof PathPosix; +export type Path = PathBase | InstanceType; +/** + * Default {@link PathScurryBase} implementation for the current platform. + * + * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on + * Darwin (macOS) systems, {@link PathScurryPosix} on all others. + */ +export declare const PathScurry: typeof PathScurryWin32 | typeof PathScurryDarwin | typeof PathScurryPosix; +export type PathScurry = PathScurryBase | InstanceType; +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/path-scurry/dist/esm/index.d.ts.map b/node_modules/path-scurry/dist/esm/index.d.ts.map new file mode 100644 index 0000000..1f59f8f --- /dev/null +++ b/node_modules/path-scurry/dist/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,WAAW,CAAA;AAmBxC,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAE5C;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,WAAW,QAAQ;IACvB,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,KAAK,CAAA;IACnC,OAAO,CAAC,EAAE,CACR,I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EvD;;;;;GAKG;AACH,eAAO,MAAM,UAAU,EACnB,OAAO,eAAe,GACtB,OAAO,gBAAgB,GACvB,OAAO,eAGQ,CAAA;AACnB,MAAM,MAAM,UAAU,GAAG,cAAc,GAAG,YAAY,CAAC,OAAO,UAAU,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/path-scurry/dist/esm/index.js b/node_modules/path-scurry/dist/esm/index.js new file mode 100644 index 0000000..3b11b81 --- /dev/null +++ b/node_modules/path-scurry/dist/esm/index.js @@ -0,0 +1,1979 @@ +import { LRUCache } from 'lru-cache'; +import { posix, win32 } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { lstatSync, readdir as readdirCB, readdirSync, readlinkSync, realpathSync as rps, } from 'fs'; +import * as actualFS from 'node:fs'; +const realpathSync = rps.native; +// TODO: test perf of fs/promises realpath vs realpathCB, +// since the promises one uses realpath.native +import { lstat, readdir, readlink, realpath } from 'node:fs/promises'; +import { Minipass } from 'minipass'; +const defaultFS = { + lstatSync, + readdir: readdirCB, + readdirSync, + readlinkSync, + realpathSync, + promises: { + lstat, + readdir, + readlink, + realpath, + }, +}; +// if they just gave us require('fs') then use our default +const fsFromOption = (fsOption) => !fsOption || fsOption === defaultFS || fsOption === actualFS ? + defaultFS + : { + ...defaultFS, + ...fsOption, + promises: { + ...defaultFS.promises, + ...(fsOption.promises || {}), + }, + }; +// turn something like //?/c:/ into c:\ +const uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i; +const uncToDrive = (rootPath) => rootPath.replace(/\//g, '\\').replace(uncDriveRegexp, '$1\\'); +// windows paths are separated by either / or \ +const eitherSep = /[\\\/]/; +const UNKNOWN = 0; // may not even exist, for all we know +const IFIFO = 0b0001; +const IFCHR = 0b0010; +const IFDIR = 0b0100; +const IFBLK = 0b0110; +const IFREG = 0b1000; +const IFLNK = 0b1010; +const IFSOCK = 0b1100; +const IFMT = 0b1111; +// mask to unset low 4 bits +const IFMT_UNKNOWN = ~IFMT; +// set after successfully calling readdir() and getting entries. +const READDIR_CALLED = 0b0000_0001_0000; +// set after a successful lstat() +const LSTAT_CALLED = 0b0000_0010_0000; +// set if an entry (or one of its parents) is definitely not a dir +const ENOTDIR = 0b0000_0100_0000; +// set if an entry (or one of its parents) does not exist +// (can also be set on lstat errors like EACCES or ENAMETOOLONG) +const ENOENT = 0b0000_1000_0000; +// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK +// set if we fail to readlink +const ENOREADLINK = 0b0001_0000_0000; +// set if we know realpath() will fail +const ENOREALPATH = 0b0010_0000_0000; +const ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH; +const TYPEMASK = 0b0011_1111_1111; +const entToType = (s) => s.isFile() ? IFREG + : s.isDirectory() ? IFDIR + : s.isSymbolicLink() ? IFLNK + : s.isCharacterDevice() ? IFCHR + : s.isBlockDevice() ? IFBLK + : s.isSocket() ? IFSOCK + : s.isFIFO() ? IFIFO + : UNKNOWN; +// normalize unicode path names +const normalizeCache = new Map(); +const normalize = (s) => { + const c = normalizeCache.get(s); + if (c) + return c; + const n = s.normalize('NFKD'); + normalizeCache.set(s, n); + return n; +}; +const normalizeNocaseCache = new Map(); +const normalizeNocase = (s) => { + const c = normalizeNocaseCache.get(s); + if (c) + return c; + const n = normalize(s.toLowerCase()); + normalizeNocaseCache.set(s, n); + return n; +}; +/** + * An LRUCache for storing resolved path strings or Path objects. + * @internal + */ +export class ResolveCache extends LRUCache { + constructor() { + super({ max: 256 }); + } +} +// In order to prevent blowing out the js heap by allocating hundreds of +// thousands of Path entries when walking extremely large trees, the "children" +// in this tree are represented by storing an array of Path entries in an +// LRUCache, indexed by the parent. At any time, Path.children() may return an +// empty array, indicating that it doesn't know about any of its children, and +// thus has to rebuild that cache. This is fine, it just means that we don't +// benefit as much from having the cached entries, but huge directory walks +// don't blow out the stack, and smaller ones are still as fast as possible. +// +//It does impose some complexity when building up the readdir data, because we +//need to pass a reference to the children array that we started with. +/** + * an LRUCache for storing child entries. + * @internal + */ +export class ChildrenCache extends LRUCache { + constructor(maxSize = 16 * 1024) { + super({ + maxSize, + // parent + children + sizeCalculation: a => a.length + 1, + }); + } +} +const setAsCwd = Symbol('PathScurry setAsCwd'); +/** + * Path objects are sort of like a super-powered + * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent} + * + * Each one represents a single filesystem entry on disk, which may or may not + * exist. It includes methods for reading various types of information via + * lstat, readlink, and readdir, and caches all information to the greatest + * degree possible. + * + * Note that fs operations that would normally throw will instead return an + * "empty" value. This is in order to prevent excessive overhead from error + * stack traces. + */ +export class PathBase { + /** + * the basename of this path + * + * **Important**: *always* test the path name against any test string + * usingthe {@link isNamed} method, and not by directly comparing this + * string. Otherwise, unicode path strings that the system sees as identical + * will not be properly treated as the same path, leading to incorrect + * behavior and possible security issues. + */ + name; + /** + * the Path entry corresponding to the path root. + * + * @internal + */ + root; + /** + * All roots found within the current PathScurry family + * + * @internal + */ + roots; + /** + * a reference to the parent path, or undefined in the case of root entries + * + * @internal + */ + parent; + /** + * boolean indicating whether paths are compared case-insensitively + * @internal + */ + nocase; + /** + * boolean indicating that this path is the current working directory + * of the PathScurry collection that contains it. + */ + isCWD = false; + // potential default fs override + #fs; + // Stats fields + #dev; + get dev() { + return this.#dev; + } + #mode; + get mode() { + return this.#mode; + } + #nlink; + get nlink() { + return this.#nlink; + } + #uid; + get uid() { + return this.#uid; + } + #gid; + get gid() { + return this.#gid; + } + #rdev; + get rdev() { + return this.#rdev; + } + #blksize; + get blksize() { + return this.#blksize; + } + #ino; + get ino() { + return this.#ino; + } + #size; + get size() { + return this.#size; + } + #blocks; + get blocks() { + return this.#blocks; + } + #atimeMs; + get atimeMs() { + return this.#atimeMs; + } + #mtimeMs; + get mtimeMs() { + return this.#mtimeMs; + } + #ctimeMs; + get ctimeMs() { + return this.#ctimeMs; + } + #birthtimeMs; + get birthtimeMs() { + return this.#birthtimeMs; + } + #atime; + get atime() { + return this.#atime; + } + #mtime; + get mtime() { + return this.#mtime; + } + #ctime; + get ctime() { + return this.#ctime; + } + #birthtime; + get birthtime() { + return this.#birthtime; + } + #matchName; + #depth; + #fullpath; + #fullpathPosix; + #relative; + #relativePosix; + #type; + #children; + #linkTarget; + #realpath; + /** + * This property is for compatibility with the Dirent class as of + * Node v20, where Dirent['parentPath'] refers to the path of the + * directory that was passed to readdir. For root entries, it's the path + * to the entry itself. + */ + get parentPath() { + return (this.parent || this).fullpath(); + } + /** + * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively, + * this property refers to the *parent* path, not the path object itself. + */ + get path() { + return this.parentPath; + } + /** + * Do not create new Path objects directly. They should always be accessed + * via the PathScurry class or other methods on the Path class. + * + * @internal + */ + constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) { + this.name = name; + this.#matchName = nocase ? normalizeNocase(name) : normalize(name); + this.#type = type & TYPEMASK; + this.nocase = nocase; + this.roots = roots; + this.root = root || this; + this.#children = children; + this.#fullpath = opts.fullpath; + this.#relative = opts.relative; + this.#relativePosix = opts.relativePosix; + this.parent = opts.parent; + if (this.parent) { + this.#fs = this.parent.#fs; + } + else { + this.#fs = fsFromOption(opts.fs); + } + } + /** + * Returns the depth of the Path object from its root. + * + * For example, a path at `/foo/bar` would have a depth of 2. + */ + depth() { + if (this.#depth !== undefined) + return this.#depth; + if (!this.parent) + return (this.#depth = 0); + return (this.#depth = this.parent.depth() + 1); + } + /** + * @internal + */ + childrenCache() { + return this.#children; + } + /** + * Get the Path object referenced by the string path, resolved from this Path + */ + resolve(path) { + if (!path) { + return this; + } + const rootPath = this.getRootString(path); + const dir = path.substring(rootPath.length); + const dirParts = dir.split(this.splitSep); + const result = rootPath ? + this.getRoot(rootPath).#resolveParts(dirParts) + : this.#resolveParts(dirParts); + return result; + } + #resolveParts(dirParts) { + let p = this; + for (const part of dirParts) { + p = p.child(part); + } + return p; + } + /** + * Returns the cached children Path objects, if still available. If they + * have fallen out of the cache, then returns an empty array, and resets the + * READDIR_CALLED bit, so that future calls to readdir() will require an fs + * lookup. + * + * @internal + */ + children() { + const cached = this.#children.get(this); + if (cached) { + return cached; + } + const children = Object.assign([], { provisional: 0 }); + this.#children.set(this, children); + this.#type &= ~READDIR_CALLED; + return children; + } + /** + * Resolves a path portion and returns or creates the child Path. + * + * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is + * `'..'`. + * + * This should not be called directly. If `pathPart` contains any path + * separators, it will lead to unsafe undefined behavior. + * + * Use `Path.resolve()` instead. + * + * @internal + */ + child(pathPart, opts) { + if (pathPart === '' || pathPart === '.') { + return this; + } + if (pathPart === '..') { + return this.parent || this; + } + // find the child + const children = this.children(); + const name = this.nocase ? normalizeNocase(pathPart) : normalize(pathPart); + for (const p of children) { + if (p.#matchName === name) { + return p; + } + } + // didn't find it, create provisional child, since it might not + // actually exist. If we know the parent isn't a dir, then + // in fact it CAN'T exist. + const s = this.parent ? this.sep : ''; + const fullpath = this.#fullpath ? this.#fullpath + s + pathPart : undefined; + const pchild = this.newChild(pathPart, UNKNOWN, { + ...opts, + parent: this, + fullpath, + }); + if (!this.canReaddir()) { + pchild.#type |= ENOENT; + } + // don't have to update provisional, because if we have real children, + // then provisional is set to children.length, otherwise a lower number + children.push(pchild); + return pchild; + } + /** + * The relative path from the cwd. If it does not share an ancestor with + * the cwd, then this ends up being equivalent to the fullpath() + */ + relative() { + if (this.isCWD) + return ''; + if (this.#relative !== undefined) { + return this.#relative; + } + const name = this.name; + const p = this.parent; + if (!p) { + return (this.#relative = this.name); + } + const pv = p.relative(); + return pv + (!pv || !p.parent ? '' : this.sep) + name; + } + /** + * The relative path from the cwd, using / as the path separator. + * If it does not share an ancestor with + * the cwd, then this ends up being equivalent to the fullpathPosix() + * On posix systems, this is identical to relative(). + */ + relativePosix() { + if (this.sep === '/') + return this.relative(); + if (this.isCWD) + return ''; + if (this.#relativePosix !== undefined) + return this.#relativePosix; + const name = this.name; + const p = this.parent; + if (!p) { + return (this.#relativePosix = this.fullpathPosix()); + } + const pv = p.relativePosix(); + return pv + (!pv || !p.parent ? '' : '/') + name; + } + /** + * The fully resolved path string for this Path entry + */ + fullpath() { + if (this.#fullpath !== undefined) { + return this.#fullpath; + } + const name = this.name; + const p = this.parent; + if (!p) { + return (this.#fullpath = this.name); + } + const pv = p.fullpath(); + const fp = pv + (!p.parent ? '' : this.sep) + name; + return (this.#fullpath = fp); + } + /** + * On platforms other than windows, this is identical to fullpath. + * + * On windows, this is overridden to return the forward-slash form of the + * full UNC path. + */ + fullpathPosix() { + if (this.#fullpathPosix !== undefined) + return this.#fullpathPosix; + if (this.sep === '/') + return (this.#fullpathPosix = this.fullpath()); + if (!this.parent) { + const p = this.fullpath().replace(/\\/g, '/'); + if (/^[a-z]:\//i.test(p)) { + return (this.#fullpathPosix = `//?/${p}`); + } + else { + return (this.#fullpathPosix = p); + } + } + const p = this.parent; + const pfpp = p.fullpathPosix(); + const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name; + return (this.#fullpathPosix = fpp); + } + /** + * Is the Path of an unknown type? + * + * Note that we might know *something* about it if there has been a previous + * filesystem operation, for example that it does not exist, or is not a + * link, or whether it has child entries. + */ + isUnknown() { + return (this.#type & IFMT) === UNKNOWN; + } + isType(type) { + return this[`is${type}`](); + } + getType() { + return (this.isUnknown() ? 'Unknown' + : this.isDirectory() ? 'Directory' + : this.isFile() ? 'File' + : this.isSymbolicLink() ? 'SymbolicLink' + : this.isFIFO() ? 'FIFO' + : this.isCharacterDevice() ? 'CharacterDevice' + : this.isBlockDevice() ? 'BlockDevice' + : /* c8 ignore start */ this.isSocket() ? 'Socket' + : 'Unknown'); + /* c8 ignore stop */ + } + /** + * Is the Path a regular file? + */ + isFile() { + return (this.#type & IFMT) === IFREG; + } + /** + * Is the Path a directory? + */ + isDirectory() { + return (this.#type & IFMT) === IFDIR; + } + /** + * Is the path a character device? + */ + isCharacterDevice() { + return (this.#type & IFMT) === IFCHR; + } + /** + * Is the path a block device? + */ + isBlockDevice() { + return (this.#type & IFMT) === IFBLK; + } + /** + * Is the path a FIFO pipe? + */ + isFIFO() { + return (this.#type & IFMT) === IFIFO; + } + /** + * Is the path a socket? + */ + isSocket() { + return (this.#type & IFMT) === IFSOCK; + } + /** + * Is the path a symbolic link? + */ + isSymbolicLink() { + return (this.#type & IFLNK) === IFLNK; + } + /** + * Return the entry if it has been subject of a successful lstat, or + * undefined otherwise. + * + * Does not read the filesystem, so an undefined result *could* simply + * mean that we haven't called lstat on it. + */ + lstatCached() { + return this.#type & LSTAT_CALLED ? this : undefined; + } + /** + * Return the cached link target if the entry has been the subject of a + * successful readlink, or undefined otherwise. + * + * Does not read the filesystem, so an undefined result *could* just mean we + * don't have any cached data. Only use it if you are very sure that a + * readlink() has been called at some point. + */ + readlinkCached() { + return this.#linkTarget; + } + /** + * Returns the cached realpath target if the entry has been the subject + * of a successful realpath, or undefined otherwise. + * + * Does not read the filesystem, so an undefined result *could* just mean we + * don't have any cached data. Only use it if you are very sure that a + * realpath() has been called at some point. + */ + realpathCached() { + return this.#realpath; + } + /** + * Returns the cached child Path entries array if the entry has been the + * subject of a successful readdir(), or [] otherwise. + * + * Does not read the filesystem, so an empty array *could* just mean we + * don't have any cached data. Only use it if you are very sure that a + * readdir() has been called recently enough to still be valid. + */ + readdirCached() { + const children = this.children(); + return children.slice(0, children.provisional); + } + /** + * Return true if it's worth trying to readlink. Ie, we don't (yet) have + * any indication that readlink will definitely fail. + * + * Returns false if the path is known to not be a symlink, if a previous + * readlink failed, or if the entry does not exist. + */ + canReadlink() { + if (this.#linkTarget) + return true; + if (!this.parent) + return false; + // cases where it cannot possibly succeed + const ifmt = this.#type & IFMT; + return !((ifmt !== UNKNOWN && ifmt !== IFLNK) || + this.#type & ENOREADLINK || + this.#type & ENOENT); + } + /** + * Return true if readdir has previously been successfully called on this + * path, indicating that cachedReaddir() is likely valid. + */ + calledReaddir() { + return !!(this.#type & READDIR_CALLED); + } + /** + * Returns true if the path is known to not exist. That is, a previous lstat + * or readdir failed to verify its existence when that would have been + * expected, or a parent entry was marked either enoent or enotdir. + */ + isENOENT() { + return !!(this.#type & ENOENT); + } + /** + * Return true if the path is a match for the given path name. This handles + * case sensitivity and unicode normalization. + * + * Note: even on case-sensitive systems, it is **not** safe to test the + * equality of the `.name` property to determine whether a given pathname + * matches, due to unicode normalization mismatches. + * + * Always use this method instead of testing the `path.name` property + * directly. + */ + isNamed(n) { + return !this.nocase ? + this.#matchName === normalize(n) + : this.#matchName === normalizeNocase(n); + } + /** + * Return the Path object corresponding to the target of a symbolic link. + * + * If the Path is not a symbolic link, or if the readlink call fails for any + * reason, `undefined` is returned. + * + * Result is cached, and thus may be outdated if the filesystem is mutated. + */ + async readlink() { + const target = this.#linkTarget; + if (target) { + return target; + } + if (!this.canReadlink()) { + return undefined; + } + /* c8 ignore start */ + // already covered by the canReadlink test, here for ts grumples + if (!this.parent) { + return undefined; + } + /* c8 ignore stop */ + try { + const read = await this.#fs.promises.readlink(this.fullpath()); + const linkTarget = (await this.parent.realpath())?.resolve(read); + if (linkTarget) { + return (this.#linkTarget = linkTarget); + } + } + catch (er) { + this.#readlinkFail(er.code); + return undefined; + } + } + /** + * Synchronous {@link PathBase.readlink} + */ + readlinkSync() { + const target = this.#linkTarget; + if (target) { + return target; + } + if (!this.canReadlink()) { + return undefined; + } + /* c8 ignore start */ + // already covered by the canReadlink test, here for ts grumples + if (!this.parent) { + return undefined; + } + /* c8 ignore stop */ + try { + const read = this.#fs.readlinkSync(this.fullpath()); + const linkTarget = this.parent.realpathSync()?.resolve(read); + if (linkTarget) { + return (this.#linkTarget = linkTarget); + } + } + catch (er) { + this.#readlinkFail(er.code); + return undefined; + } + } + #readdirSuccess(children) { + // succeeded, mark readdir called bit + this.#type |= READDIR_CALLED; + // mark all remaining provisional children as ENOENT + for (let p = children.provisional; p < children.length; p++) { + const c = children[p]; + if (c) + c.#markENOENT(); + } + } + #markENOENT() { + // mark as UNKNOWN and ENOENT + if (this.#type & ENOENT) + return; + this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN; + this.#markChildrenENOENT(); + } + #markChildrenENOENT() { + // all children are provisional and do not exist + const children = this.children(); + children.provisional = 0; + for (const p of children) { + p.#markENOENT(); + } + } + #markENOREALPATH() { + this.#type |= ENOREALPATH; + this.#markENOTDIR(); + } + // save the information when we know the entry is not a dir + #markENOTDIR() { + // entry is not a directory, so any children can't exist. + // this *should* be impossible, since any children created + // after it's been marked ENOTDIR should be marked ENOENT, + // so it won't even get to this point. + /* c8 ignore start */ + if (this.#type & ENOTDIR) + return; + /* c8 ignore stop */ + let t = this.#type; + // this could happen if we stat a dir, then delete it, + // then try to read it or one of its children. + if ((t & IFMT) === IFDIR) + t &= IFMT_UNKNOWN; + this.#type = t | ENOTDIR; + this.#markChildrenENOENT(); + } + #readdirFail(code = '') { + // markENOTDIR and markENOENT also set provisional=0 + if (code === 'ENOTDIR' || code === 'EPERM') { + this.#markENOTDIR(); + } + else if (code === 'ENOENT') { + this.#markENOENT(); + } + else { + this.children().provisional = 0; + } + } + #lstatFail(code = '') { + // Windows just raises ENOENT in this case, disable for win CI + /* c8 ignore start */ + if (code === 'ENOTDIR') { + // already know it has a parent by this point + const p = this.parent; + p.#markENOTDIR(); + } + else if (code === 'ENOENT') { + /* c8 ignore stop */ + this.#markENOENT(); + } + } + #readlinkFail(code = '') { + let ter = this.#type; + ter |= ENOREADLINK; + if (code === 'ENOENT') + ter |= ENOENT; + // windows gets a weird error when you try to readlink a file + if (code === 'EINVAL' || code === 'UNKNOWN') { + // exists, but not a symlink, we don't know WHAT it is, so remove + // all IFMT bits. + ter &= IFMT_UNKNOWN; + } + this.#type = ter; + // windows just gets ENOENT in this case. We do cover the case, + // just disabled because it's impossible on Windows CI + /* c8 ignore start */ + if (code === 'ENOTDIR' && this.parent) { + this.parent.#markENOTDIR(); + } + /* c8 ignore stop */ + } + #readdirAddChild(e, c) { + return (this.#readdirMaybePromoteChild(e, c) || + this.#readdirAddNewChild(e, c)); + } + #readdirAddNewChild(e, c) { + // alloc new entry at head, so it's never provisional + const type = entToType(e); + const child = this.newChild(e.name, type, { parent: this }); + const ifmt = child.#type & IFMT; + if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) { + child.#type |= ENOTDIR; + } + c.unshift(child); + c.provisional++; + return child; + } + #readdirMaybePromoteChild(e, c) { + for (let p = c.provisional; p < c.length; p++) { + const pchild = c[p]; + const name = this.nocase ? normalizeNocase(e.name) : normalize(e.name); + if (name !== pchild.#matchName) { + continue; + } + return this.#readdirPromoteChild(e, pchild, p, c); + } + } + #readdirPromoteChild(e, p, index, c) { + const v = p.name; + // retain any other flags, but set ifmt from dirent + p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e); + // case sensitivity fixing when we learn the true name. + if (v !== e.name) + p.name = e.name; + // just advance provisional index (potentially off the list), + // otherwise we have to splice/pop it out and re-insert at head + if (index !== c.provisional) { + if (index === c.length - 1) + c.pop(); + else + c.splice(index, 1); + c.unshift(p); + } + c.provisional++; + return p; + } + /** + * Call lstat() on this Path, and update all known information that can be + * determined. + * + * Note that unlike `fs.lstat()`, the returned value does not contain some + * information, such as `mode`, `dev`, `nlink`, and `ino`. If that + * information is required, you will need to call `fs.lstat` yourself. + * + * If the Path refers to a nonexistent file, or if the lstat call fails for + * any reason, `undefined` is returned. Otherwise the updated Path object is + * returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + */ + async lstat() { + if ((this.#type & ENOENT) === 0) { + try { + this.#applyStat(await this.#fs.promises.lstat(this.fullpath())); + return this; + } + catch (er) { + this.#lstatFail(er.code); + } + } + } + /** + * synchronous {@link PathBase.lstat} + */ + lstatSync() { + if ((this.#type & ENOENT) === 0) { + try { + this.#applyStat(this.#fs.lstatSync(this.fullpath())); + return this; + } + catch (er) { + this.#lstatFail(er.code); + } + } + } + #applyStat(st) { + const { atime, atimeMs, birthtime, birthtimeMs, blksize, blocks, ctime, ctimeMs, dev, gid, ino, mode, mtime, mtimeMs, nlink, rdev, size, uid, } = st; + this.#atime = atime; + this.#atimeMs = atimeMs; + this.#birthtime = birthtime; + this.#birthtimeMs = birthtimeMs; + this.#blksize = blksize; + this.#blocks = blocks; + this.#ctime = ctime; + this.#ctimeMs = ctimeMs; + this.#dev = dev; + this.#gid = gid; + this.#ino = ino; + this.#mode = mode; + this.#mtime = mtime; + this.#mtimeMs = mtimeMs; + this.#nlink = nlink; + this.#rdev = rdev; + this.#size = size; + this.#uid = uid; + const ifmt = entToType(st); + // retain any other flags, but set the ifmt + this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED; + if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) { + this.#type |= ENOTDIR; + } + } + #onReaddirCB = []; + #readdirCBInFlight = false; + #callOnReaddirCB(children) { + this.#readdirCBInFlight = false; + const cbs = this.#onReaddirCB.slice(); + this.#onReaddirCB.length = 0; + cbs.forEach(cb => cb(null, children)); + } + /** + * Standard node-style callback interface to get list of directory entries. + * + * If the Path cannot or does not contain any children, then an empty array + * is returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + * + * @param cb The callback called with (er, entries). Note that the `er` + * param is somewhat extraneous, as all readdir() errors are handled and + * simply result in an empty set of entries being returned. + * @param allowZalgo Boolean indicating that immediately known results should + * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release + * zalgo at your peril, the dark pony lord is devious and unforgiving. + */ + readdirCB(cb, allowZalgo = false) { + if (!this.canReaddir()) { + if (allowZalgo) + cb(null, []); + else + queueMicrotask(() => cb(null, [])); + return; + } + const children = this.children(); + if (this.calledReaddir()) { + const c = children.slice(0, children.provisional); + if (allowZalgo) + cb(null, c); + else + queueMicrotask(() => cb(null, c)); + return; + } + // don't have to worry about zalgo at this point. + this.#onReaddirCB.push(cb); + if (this.#readdirCBInFlight) { + return; + } + this.#readdirCBInFlight = true; + // else read the directory, fill up children + // de-provisionalize any provisional children. + const fullpath = this.fullpath(); + this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => { + if (er) { + this.#readdirFail(er.code); + children.provisional = 0; + } + else { + // if we didn't get an error, we always get entries. + //@ts-ignore + for (const e of entries) { + this.#readdirAddChild(e, children); + } + this.#readdirSuccess(children); + } + this.#callOnReaddirCB(children.slice(0, children.provisional)); + return; + }); + } + #asyncReaddirInFlight; + /** + * Return an array of known child entries. + * + * If the Path cannot or does not contain any children, then an empty array + * is returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + */ + async readdir() { + if (!this.canReaddir()) { + return []; + } + const children = this.children(); + if (this.calledReaddir()) { + return children.slice(0, children.provisional); + } + // else read the directory, fill up children + // de-provisionalize any provisional children. + const fullpath = this.fullpath(); + if (this.#asyncReaddirInFlight) { + await this.#asyncReaddirInFlight; + } + else { + /* c8 ignore start */ + let resolve = () => { }; + /* c8 ignore stop */ + this.#asyncReaddirInFlight = new Promise(res => (resolve = res)); + try { + for (const e of await this.#fs.promises.readdir(fullpath, { + withFileTypes: true, + })) { + this.#readdirAddChild(e, children); + } + this.#readdirSuccess(children); + } + catch (er) { + this.#readdirFail(er.code); + children.provisional = 0; + } + this.#asyncReaddirInFlight = undefined; + resolve(); + } + return children.slice(0, children.provisional); + } + /** + * synchronous {@link PathBase.readdir} + */ + readdirSync() { + if (!this.canReaddir()) { + return []; + } + const children = this.children(); + if (this.calledReaddir()) { + return children.slice(0, children.provisional); + } + // else read the directory, fill up children + // de-provisionalize any provisional children. + const fullpath = this.fullpath(); + try { + for (const e of this.#fs.readdirSync(fullpath, { + withFileTypes: true, + })) { + this.#readdirAddChild(e, children); + } + this.#readdirSuccess(children); + } + catch (er) { + this.#readdirFail(er.code); + children.provisional = 0; + } + return children.slice(0, children.provisional); + } + canReaddir() { + if (this.#type & ENOCHILD) + return false; + const ifmt = IFMT & this.#type; + // we always set ENOTDIR when setting IFMT, so should be impossible + /* c8 ignore start */ + if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) { + return false; + } + /* c8 ignore stop */ + return true; + } + shouldWalk(dirs, walkFilter) { + return ((this.#type & IFDIR) === IFDIR && + !(this.#type & ENOCHILD) && + !dirs.has(this) && + (!walkFilter || walkFilter(this))); + } + /** + * Return the Path object corresponding to path as resolved + * by realpath(3). + * + * If the realpath call fails for any reason, `undefined` is returned. + * + * Result is cached, and thus may be outdated if the filesystem is mutated. + * On success, returns a Path object. + */ + async realpath() { + if (this.#realpath) + return this.#realpath; + if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) + return undefined; + try { + const rp = await this.#fs.promises.realpath(this.fullpath()); + return (this.#realpath = this.resolve(rp)); + } + catch (_) { + this.#markENOREALPATH(); + } + } + /** + * Synchronous {@link realpath} + */ + realpathSync() { + if (this.#realpath) + return this.#realpath; + if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) + return undefined; + try { + const rp = this.#fs.realpathSync(this.fullpath()); + return (this.#realpath = this.resolve(rp)); + } + catch (_) { + this.#markENOREALPATH(); + } + } + /** + * Internal method to mark this Path object as the scurry cwd, + * called by {@link PathScurry#chdir} + * + * @internal + */ + [setAsCwd](oldCwd) { + if (oldCwd === this) + return; + oldCwd.isCWD = false; + this.isCWD = true; + const changed = new Set([]); + let rp = []; + let p = this; + while (p && p.parent) { + changed.add(p); + p.#relative = rp.join(this.sep); + p.#relativePosix = rp.join('/'); + p = p.parent; + rp.push('..'); + } + // now un-memoize parents of old cwd + p = oldCwd; + while (p && p.parent && !changed.has(p)) { + p.#relative = undefined; + p.#relativePosix = undefined; + p = p.parent; + } + } +} +/** + * Path class used on win32 systems + * + * Uses `'\\'` as the path separator for returned paths, either `'\\'` or `'/'` + * as the path separator for parsing paths. + */ +export class PathWin32 extends PathBase { + /** + * Separator for generating path strings. + */ + sep = '\\'; + /** + * Separator for parsing path strings. + */ + splitSep = eitherSep; + /** + * Do not create new Path objects directly. They should always be accessed + * via the PathScurry class or other methods on the Path class. + * + * @internal + */ + constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) { + super(name, type, root, roots, nocase, children, opts); + } + /** + * @internal + */ + newChild(name, type = UNKNOWN, opts = {}) { + return new PathWin32(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts); + } + /** + * @internal + */ + getRootString(path) { + return win32.parse(path).root; + } + /** + * @internal + */ + getRoot(rootPath) { + rootPath = uncToDrive(rootPath.toUpperCase()); + if (rootPath === this.root.name) { + return this.root; + } + // ok, not that one, check if it matches another we know about + for (const [compare, root] of Object.entries(this.roots)) { + if (this.sameRoot(rootPath, compare)) { + return (this.roots[rootPath] = root); + } + } + // otherwise, have to create a new one. + return (this.roots[rootPath] = new PathScurryWin32(rootPath, this).root); + } + /** + * @internal + */ + sameRoot(rootPath, compare = this.root.name) { + // windows can (rarely) have case-sensitive filesystem, but + // UNC and drive letters are always case-insensitive, and canonically + // represented uppercase. + rootPath = rootPath + .toUpperCase() + .replace(/\//g, '\\') + .replace(uncDriveRegexp, '$1\\'); + return rootPath === compare; + } +} +/** + * Path class used on all posix systems. + * + * Uses `'/'` as the path separator. + */ +export class PathPosix extends PathBase { + /** + * separator for parsing path strings + */ + splitSep = '/'; + /** + * separator for generating path strings + */ + sep = '/'; + /** + * Do not create new Path objects directly. They should always be accessed + * via the PathScurry class or other methods on the Path class. + * + * @internal + */ + constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) { + super(name, type, root, roots, nocase, children, opts); + } + /** + * @internal + */ + getRootString(path) { + return path.startsWith('/') ? '/' : ''; + } + /** + * @internal + */ + getRoot(_rootPath) { + return this.root; + } + /** + * @internal + */ + newChild(name, type = UNKNOWN, opts = {}) { + return new PathPosix(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts); + } +} +/** + * The base class for all PathScurry classes, providing the interface for path + * resolution and filesystem operations. + * + * Typically, you should *not* instantiate this class directly, but rather one + * of the platform-specific classes, or the exported {@link PathScurry} which + * defaults to the current platform. + */ +export class PathScurryBase { + /** + * The root Path entry for the current working directory of this Scurry + */ + root; + /** + * The string path for the root of this Scurry's current working directory + */ + rootPath; + /** + * A collection of all roots encountered, referenced by rootPath + */ + roots; + /** + * The Path entry corresponding to this PathScurry's current working directory. + */ + cwd; + #resolveCache; + #resolvePosixCache; + #children; + /** + * Perform path comparisons case-insensitively. + * + * Defaults true on Darwin and Windows systems, false elsewhere. + */ + nocase; + #fs; + /** + * This class should not be instantiated directly. + * + * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry + * + * @internal + */ + constructor(cwd = process.cwd(), pathImpl, sep, { nocase, childrenCacheSize = 16 * 1024, fs = defaultFS, } = {}) { + this.#fs = fsFromOption(fs); + if (cwd instanceof URL || cwd.startsWith('file://')) { + cwd = fileURLToPath(cwd); + } + // resolve and split root, and then add to the store. + // this is the only time we call path.resolve() + const cwdPath = pathImpl.resolve(cwd); + this.roots = Object.create(null); + this.rootPath = this.parseRootPath(cwdPath); + this.#resolveCache = new ResolveCache(); + this.#resolvePosixCache = new ResolveCache(); + this.#children = new ChildrenCache(childrenCacheSize); + const split = cwdPath.substring(this.rootPath.length).split(sep); + // resolve('/') leaves '', splits to [''], we don't want that. + if (split.length === 1 && !split[0]) { + split.pop(); + } + /* c8 ignore start */ + if (nocase === undefined) { + throw new TypeError('must provide nocase setting to PathScurryBase ctor'); + } + /* c8 ignore stop */ + this.nocase = nocase; + this.root = this.newRoot(this.#fs); + this.roots[this.rootPath] = this.root; + let prev = this.root; + let len = split.length - 1; + const joinSep = pathImpl.sep; + let abs = this.rootPath; + let sawFirst = false; + for (const part of split) { + const l = len--; + prev = prev.child(part, { + relative: new Array(l).fill('..').join(joinSep), + relativePosix: new Array(l).fill('..').join('/'), + fullpath: (abs += (sawFirst ? '' : joinSep) + part), + }); + sawFirst = true; + } + this.cwd = prev; + } + /** + * Get the depth of a provided path, string, or the cwd + */ + depth(path = this.cwd) { + if (typeof path === 'string') { + path = this.cwd.resolve(path); + } + return path.depth(); + } + /** + * Return the cache of child entries. Exposed so subclasses can create + * child Path objects in a platform-specific way. + * + * @internal + */ + childrenCache() { + return this.#children; + } + /** + * Resolve one or more path strings to a resolved string + * + * Same interface as require('path').resolve. + * + * Much faster than path.resolve() when called multiple times for the same + * path, because the resolved Path objects are cached. Much slower + * otherwise. + */ + resolve(...paths) { + // first figure out the minimum number of paths we have to test + // we always start at cwd, but any absolutes will bump the start + let r = ''; + for (let i = paths.length - 1; i >= 0; i--) { + const p = paths[i]; + if (!p || p === '.') + continue; + r = r ? `${p}/${r}` : p; + if (this.isAbsolute(p)) { + break; + } + } + const cached = this.#resolveCache.get(r); + if (cached !== undefined) { + return cached; + } + const result = this.cwd.resolve(r).fullpath(); + this.#resolveCache.set(r, result); + return result; + } + /** + * Resolve one or more path strings to a resolved string, returning + * the posix path. Identical to .resolve() on posix systems, but on + * windows will return a forward-slash separated UNC path. + * + * Same interface as require('path').resolve. + * + * Much faster than path.resolve() when called multiple times for the same + * path, because the resolved Path objects are cached. Much slower + * otherwise. + */ + resolvePosix(...paths) { + // first figure out the minimum number of paths we have to test + // we always start at cwd, but any absolutes will bump the start + let r = ''; + for (let i = paths.length - 1; i >= 0; i--) { + const p = paths[i]; + if (!p || p === '.') + continue; + r = r ? `${p}/${r}` : p; + if (this.isAbsolute(p)) { + break; + } + } + const cached = this.#resolvePosixCache.get(r); + if (cached !== undefined) { + return cached; + } + const result = this.cwd.resolve(r).fullpathPosix(); + this.#resolvePosixCache.set(r, result); + return result; + } + /** + * find the relative path from the cwd to the supplied path string or entry + */ + relative(entry = this.cwd) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + return entry.relative(); + } + /** + * find the relative path from the cwd to the supplied path string or + * entry, using / as the path delimiter, even on Windows. + */ + relativePosix(entry = this.cwd) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + return entry.relativePosix(); + } + /** + * Return the basename for the provided string or Path object + */ + basename(entry = this.cwd) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + return entry.name; + } + /** + * Return the dirname for the provided string or Path object + */ + dirname(entry = this.cwd) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + return (entry.parent || entry).fullpath(); + } + async readdir(entry = this.cwd, opts = { + withFileTypes: true, + }) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + opts = entry; + entry = this.cwd; + } + const { withFileTypes } = opts; + if (!entry.canReaddir()) { + return []; + } + else { + const p = await entry.readdir(); + return withFileTypes ? p : p.map(e => e.name); + } + } + readdirSync(entry = this.cwd, opts = { + withFileTypes: true, + }) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + opts = entry; + entry = this.cwd; + } + const { withFileTypes = true } = opts; + if (!entry.canReaddir()) { + return []; + } + else if (withFileTypes) { + return entry.readdirSync(); + } + else { + return entry.readdirSync().map(e => e.name); + } + } + /** + * Call lstat() on the string or Path object, and update all known + * information that can be determined. + * + * Note that unlike `fs.lstat()`, the returned value does not contain some + * information, such as `mode`, `dev`, `nlink`, and `ino`. If that + * information is required, you will need to call `fs.lstat` yourself. + * + * If the Path refers to a nonexistent file, or if the lstat call fails for + * any reason, `undefined` is returned. Otherwise the updated Path object is + * returned. + * + * Results are cached, and thus may be out of date if the filesystem is + * mutated. + */ + async lstat(entry = this.cwd) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + return entry.lstat(); + } + /** + * synchronous {@link PathScurryBase.lstat} + */ + lstatSync(entry = this.cwd) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + return entry.lstatSync(); + } + async readlink(entry = this.cwd, { withFileTypes } = { + withFileTypes: false, + }) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + withFileTypes = entry.withFileTypes; + entry = this.cwd; + } + const e = await entry.readlink(); + return withFileTypes ? e : e?.fullpath(); + } + readlinkSync(entry = this.cwd, { withFileTypes } = { + withFileTypes: false, + }) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + withFileTypes = entry.withFileTypes; + entry = this.cwd; + } + const e = entry.readlinkSync(); + return withFileTypes ? e : e?.fullpath(); + } + async realpath(entry = this.cwd, { withFileTypes } = { + withFileTypes: false, + }) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + withFileTypes = entry.withFileTypes; + entry = this.cwd; + } + const e = await entry.realpath(); + return withFileTypes ? e : e?.fullpath(); + } + realpathSync(entry = this.cwd, { withFileTypes } = { + withFileTypes: false, + }) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + withFileTypes = entry.withFileTypes; + entry = this.cwd; + } + const e = entry.realpathSync(); + return withFileTypes ? e : e?.fullpath(); + } + async walk(entry = this.cwd, opts = {}) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + opts = entry; + entry = this.cwd; + } + const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; + const results = []; + if (!filter || filter(entry)) { + results.push(withFileTypes ? entry : entry.fullpath()); + } + const dirs = new Set(); + const walk = (dir, cb) => { + dirs.add(dir); + dir.readdirCB((er, entries) => { + /* c8 ignore start */ + if (er) { + return cb(er); + } + /* c8 ignore stop */ + let len = entries.length; + if (!len) + return cb(); + const next = () => { + if (--len === 0) { + cb(); + } + }; + for (const e of entries) { + if (!filter || filter(e)) { + results.push(withFileTypes ? e : e.fullpath()); + } + if (follow && e.isSymbolicLink()) { + e.realpath() + .then(r => (r?.isUnknown() ? r.lstat() : r)) + .then(r => r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next()); + } + else { + if (e.shouldWalk(dirs, walkFilter)) { + walk(e, next); + } + else { + next(); + } + } + } + }, true); // zalgooooooo + }; + const start = entry; + return new Promise((res, rej) => { + walk(start, er => { + /* c8 ignore start */ + if (er) + return rej(er); + /* c8 ignore stop */ + res(results); + }); + }); + } + walkSync(entry = this.cwd, opts = {}) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + opts = entry; + entry = this.cwd; + } + const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; + const results = []; + if (!filter || filter(entry)) { + results.push(withFileTypes ? entry : entry.fullpath()); + } + const dirs = new Set([entry]); + for (const dir of dirs) { + const entries = dir.readdirSync(); + for (const e of entries) { + if (!filter || filter(e)) { + results.push(withFileTypes ? e : e.fullpath()); + } + let r = e; + if (e.isSymbolicLink()) { + if (!(follow && (r = e.realpathSync()))) + continue; + if (r.isUnknown()) + r.lstatSync(); + } + if (r.shouldWalk(dirs, walkFilter)) { + dirs.add(r); + } + } + } + return results; + } + /** + * Support for `for await` + * + * Alias for {@link PathScurryBase.iterate} + * + * Note: As of Node 19, this is very slow, compared to other methods of + * walking. Consider using {@link PathScurryBase.stream} if memory overhead + * and backpressure are concerns, or {@link PathScurryBase.walk} if not. + */ + [Symbol.asyncIterator]() { + return this.iterate(); + } + iterate(entry = this.cwd, options = {}) { + // iterating async over the stream is significantly more performant, + // especially in the warm-cache scenario, because it buffers up directory + // entries in the background instead of waiting for a yield for each one. + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + options = entry; + entry = this.cwd; + } + return this.stream(entry, options)[Symbol.asyncIterator](); + } + /** + * Iterating over a PathScurry performs a synchronous walk. + * + * Alias for {@link PathScurryBase.iterateSync} + */ + [Symbol.iterator]() { + return this.iterateSync(); + } + *iterateSync(entry = this.cwd, opts = {}) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + opts = entry; + entry = this.cwd; + } + const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; + if (!filter || filter(entry)) { + yield withFileTypes ? entry : entry.fullpath(); + } + const dirs = new Set([entry]); + for (const dir of dirs) { + const entries = dir.readdirSync(); + for (const e of entries) { + if (!filter || filter(e)) { + yield withFileTypes ? e : e.fullpath(); + } + let r = e; + if (e.isSymbolicLink()) { + if (!(follow && (r = e.realpathSync()))) + continue; + if (r.isUnknown()) + r.lstatSync(); + } + if (r.shouldWalk(dirs, walkFilter)) { + dirs.add(r); + } + } + } + } + stream(entry = this.cwd, opts = {}) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + opts = entry; + entry = this.cwd; + } + const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; + const results = new Minipass({ objectMode: true }); + if (!filter || filter(entry)) { + results.write(withFileTypes ? entry : entry.fullpath()); + } + const dirs = new Set(); + const queue = [entry]; + let processing = 0; + const process = () => { + let paused = false; + while (!paused) { + const dir = queue.shift(); + if (!dir) { + if (processing === 0) + results.end(); + return; + } + processing++; + dirs.add(dir); + const onReaddir = (er, entries, didRealpaths = false) => { + /* c8 ignore start */ + if (er) + return results.emit('error', er); + /* c8 ignore stop */ + if (follow && !didRealpaths) { + const promises = []; + for (const e of entries) { + if (e.isSymbolicLink()) { + promises.push(e + .realpath() + .then((r) => r?.isUnknown() ? r.lstat() : r)); + } + } + if (promises.length) { + Promise.all(promises).then(() => onReaddir(null, entries, true)); + return; + } + } + for (const e of entries) { + if (e && (!filter || filter(e))) { + if (!results.write(withFileTypes ? e : e.fullpath())) { + paused = true; + } + } + } + processing--; + for (const e of entries) { + const r = e.realpathCached() || e; + if (r.shouldWalk(dirs, walkFilter)) { + queue.push(r); + } + } + if (paused && !results.flowing) { + results.once('drain', process); + } + else if (!sync) { + process(); + } + }; + // zalgo containment + let sync = true; + dir.readdirCB(onReaddir, true); + sync = false; + } + }; + process(); + return results; + } + streamSync(entry = this.cwd, opts = {}) { + if (typeof entry === 'string') { + entry = this.cwd.resolve(entry); + } + else if (!(entry instanceof PathBase)) { + opts = entry; + entry = this.cwd; + } + const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; + const results = new Minipass({ objectMode: true }); + const dirs = new Set(); + if (!filter || filter(entry)) { + results.write(withFileTypes ? entry : entry.fullpath()); + } + const queue = [entry]; + let processing = 0; + const process = () => { + let paused = false; + while (!paused) { + const dir = queue.shift(); + if (!dir) { + if (processing === 0) + results.end(); + return; + } + processing++; + dirs.add(dir); + const entries = dir.readdirSync(); + for (const e of entries) { + if (!filter || filter(e)) { + if (!results.write(withFileTypes ? e : e.fullpath())) { + paused = true; + } + } + } + processing--; + for (const e of entries) { + let r = e; + if (e.isSymbolicLink()) { + if (!(follow && (r = e.realpathSync()))) + continue; + if (r.isUnknown()) + r.lstatSync(); + } + if (r.shouldWalk(dirs, walkFilter)) { + queue.push(r); + } + } + } + if (paused && !results.flowing) + results.once('drain', process); + }; + process(); + return results; + } + chdir(path = this.cwd) { + const oldCwd = this.cwd; + this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path; + this.cwd[setAsCwd](oldCwd); + } +} +/** + * Windows implementation of {@link PathScurryBase} + * + * Defaults to case insensitve, uses `'\\'` to generate path strings. Uses + * {@link PathWin32} for Path objects. + */ +export class PathScurryWin32 extends PathScurryBase { + /** + * separator for generating path strings + */ + sep = '\\'; + constructor(cwd = process.cwd(), opts = {}) { + const { nocase = true } = opts; + super(cwd, win32, '\\', { ...opts, nocase }); + this.nocase = nocase; + for (let p = this.cwd; p; p = p.parent) { + p.nocase = this.nocase; + } + } + /** + * @internal + */ + parseRootPath(dir) { + // if the path starts with a single separator, it's not a UNC, and we'll + // just get separator as the root, and driveFromUNC will return \ + // In that case, mount \ on the root from the cwd. + return win32.parse(dir).root.toUpperCase(); + } + /** + * @internal + */ + newRoot(fs) { + return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs }); + } + /** + * Return true if the provided path string is an absolute path + */ + isAbsolute(p) { + return (p.startsWith('/') || p.startsWith('\\') || /^[a-z]:(\/|\\)/i.test(p)); + } +} +/** + * {@link PathScurryBase} implementation for all posix systems other than Darwin. + * + * Defaults to case-sensitive matching, uses `'/'` to generate path strings. + * + * Uses {@link PathPosix} for Path objects. + */ +export class PathScurryPosix extends PathScurryBase { + /** + * separator for generating path strings + */ + sep = '/'; + constructor(cwd = process.cwd(), opts = {}) { + const { nocase = false } = opts; + super(cwd, posix, '/', { ...opts, nocase }); + this.nocase = nocase; + } + /** + * @internal + */ + parseRootPath(_dir) { + return '/'; + } + /** + * @internal + */ + newRoot(fs) { + return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs }); + } + /** + * Return true if the provided path string is an absolute path + */ + isAbsolute(p) { + return p.startsWith('/'); + } +} +/** + * {@link PathScurryBase} implementation for Darwin (macOS) systems. + * + * Defaults to case-insensitive matching, uses `'/'` for generating path + * strings. + * + * Uses {@link PathPosix} for Path objects. + */ +export class PathScurryDarwin extends PathScurryPosix { + constructor(cwd = process.cwd(), opts = {}) { + const { nocase = true } = opts; + super(cwd, { ...opts, nocase }); + } +} +/** + * Default {@link PathBase} implementation for the current platform. + * + * {@link PathWin32} on Windows systems, {@link PathPosix} on all others. + */ +export const Path = process.platform === 'win32' ? PathWin32 : PathPosix; +/** + * Default {@link PathScurryBase} implementation for the current platform. + * + * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on + * Darwin (macOS) systems, {@link PathScurryPosix} on all others. + */ +export const PathScurry = process.platform === 'win32' ? PathScurryWin32 + : process.platform === 'darwin' ? PathScurryDarwin + : PathScurryPosix; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/path-scurry/dist/esm/index.js.map b/node_modules/path-scurry/dist/esm/index.js.map new file mode 100644 index 0000000..7e01bd2 --- /dev/null +++ b/node_modules/path-scurry/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,WAAW,CAAA;AAExC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAExC,OAAO,EACL,SAAS,EACT,OAAO,IAAI,SAAS,EACpB,WAAW,EACX,YAAY,EACZ,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IAAI,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAA;AAGxE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,UAAU,GAIrB,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,eAAe;IAC9C,CAAC,CAAC,OAAO,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,gBAAgB;QAClD,CAAC,CAAC,eAAe,CAAA","sourcesContent":["import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'node:path'\n\nimport { fileURLToPath } from 'node:url'\n\nimport {\n lstatSync,\n readdir as readdirCB,\n readdirSync,\n readlinkSync,\n realpathSync as rps,\n} from 'fs'\nimport * as actualFS from 'node:fs'\n\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\n\nimport { lstat, readdir, readlink, realpath } from 'node:fs/promises'\n\nimport { Minipass } from 'minipass'\nimport type { Dirent, Stats } from 'node:fs'\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() ? IFREG\n : s.isDirectory() ? IFDIR\n : s.isSymbolicLink() ? IFLNK\n : s.isCharacterDevice() ? IFCHR\n : s.isBlockDevice() ? IFBLK\n : s.isSocket() ? IFSOCK\n : s.isFIFO() ? 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 * boolean indicating that this path is the current working directory\n * of the PathScurry collection that contains it.\n */\n isCWD: boolean = false\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['parentPath'] refers to the path of the\n * directory that was passed to readdir. For root entries, it's the path\n * to the entry itself.\n */\n get parentPath(): string {\n return (this.parent || this).fullpath()\n }\n\n /**\n * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,\n * this property refers to the *parent* path, not the path object itself.\n */\n get path(): string {\n return this.parentPath\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 =\n 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 =\n this.nocase ? normalizeNocase(pathPart) : 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 =\n this.#fullpath ? this.#fullpath + s + pathPart : 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.isCWD) return ''\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.isCWD) return ''\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 (\n this.isUnknown() ? 'Unknown'\n : this.isDirectory() ? 'Directory'\n : this.isFile() ? 'File'\n : this.isSymbolicLink() ? 'SymbolicLink'\n : this.isFIFO() ? 'FIFO'\n : this.isCharacterDevice() ? 'CharacterDevice'\n : this.isBlockDevice() ? 'BlockDevice'\n : /* c8 ignore start */ this.isSocket() ? 'Socket'\n : 'Unknown'\n )\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 = (await this.parent.realpath())?.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.realpathSync()?.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 const c = children[p]\n if (c) c.#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 =\n this.nocase ? normalizeNocase(e.name) : 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 oldCwd.isCWD = false\n this.isCWD = true\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' ? PathScurryWin32\n : process.platform === 'darwin' ? PathScurryDarwin\n : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType\n"]} \ No newline at end of file diff --git a/node_modules/path-scurry/dist/esm/package.json b/node_modules/path-scurry/dist/esm/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/node_modules/path-scurry/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/path-scurry/package.json b/node_modules/path-scurry/package.json new file mode 100644 index 0000000..e176615 --- /dev/null +++ b/node_modules/path-scurry/package.json @@ -0,0 +1,89 @@ +{ + "name": "path-scurry", + "version": "1.11.1", + "description": "walk paths fast and efficiently", + "author": "Isaac Z. Schlueter (https://blog.izs.me)", + "main": "./dist/commonjs/index.js", + "type": "module", + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "files": [ + "dist" + ], + "license": "BlueOak-1.0.0", + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --loglevel warn", + "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts", + "bench": "bash ./scripts/bench.sh" + }, + "prettier": { + "experimentalTernaries": true, + "semi": false, + "printWidth": 75, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "devDependencies": { + "@nodelib/fs.walk": "^1.2.8", + "@types/node": "^20.12.11", + "c8": "^7.12.0", + "eslint-config-prettier": "^8.6.0", + "mkdirp": "^3.0.0", + "prettier": "^3.2.5", + "rimraf": "^5.0.1", + "tap": "^18.7.2", + "ts-node": "^10.9.2", + "tshy": "^1.14.0", + "typedoc": "^0.25.12", + "typescript": "^5.4.3" + }, + "tap": { + "typecheck": true + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/path-scurry" + }, + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "tshy": { + "selfLink": false, + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "types": "./dist/commonjs/index.d.ts" +} diff --git a/node_modules/picocolors/LICENSE b/node_modules/picocolors/LICENSE new file mode 100644 index 0000000..46c9b95 --- /dev/null +++ b/node_modules/picocolors/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/picocolors/README.md b/node_modules/picocolors/README.md new file mode 100644 index 0000000..8e47aa8 --- /dev/null +++ b/node_modules/picocolors/README.md @@ -0,0 +1,21 @@ +# picocolors + +The tiniest and the fastest library for terminal output formatting with ANSI colors. + +```javascript +import pc from "picocolors" + +console.log( + pc.green(`How are ${pc.italic(`you`)} doing?`) +) +``` + +- **No dependencies.** +- **14 times** smaller and **2 times** faster than chalk. +- Used by popular tools like PostCSS, SVGO, Stylelint, and Browserslist. +- Node.js v6+ & browsers support. Support for both CJS and ESM projects. +- TypeScript type declarations included. +- [`NO_COLOR`](https://no-color.org/) friendly. + +## Docs +Read **[full docs](https://github.com/alexeyraspopov/picocolors#readme)** on GitHub. diff --git a/node_modules/picocolors/package.json b/node_modules/picocolors/package.json new file mode 100644 index 0000000..372d4b6 --- /dev/null +++ b/node_modules/picocolors/package.json @@ -0,0 +1,25 @@ +{ + "name": "picocolors", + "version": "1.1.1", + "main": "./picocolors.js", + "types": "./picocolors.d.ts", + "browser": { + "./picocolors.js": "./picocolors.browser.js" + }, + "sideEffects": false, + "description": "The tiniest and the fastest library for terminal output formatting with ANSI colors", + "files": [ + "picocolors.*", + "types.d.ts" + ], + "keywords": [ + "terminal", + "colors", + "formatting", + "cli", + "console" + ], + "author": "Alexey Raspopov", + "repository": "alexeyraspopov/picocolors", + "license": "ISC" +} diff --git a/node_modules/picocolors/picocolors.browser.js b/node_modules/picocolors/picocolors.browser.js new file mode 100644 index 0000000..9dcf637 --- /dev/null +++ b/node_modules/picocolors/picocolors.browser.js @@ -0,0 +1,4 @@ +var x=String; +var create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x,blackBright:x,redBright:x,greenBright:x,yellowBright:x,blueBright:x,magentaBright:x,cyanBright:x,whiteBright:x,bgBlackBright:x,bgRedBright:x,bgGreenBright:x,bgYellowBright:x,bgBlueBright:x,bgMagentaBright:x,bgCyanBright:x,bgWhiteBright:x}}; +module.exports=create(); +module.exports.createColors = create; diff --git a/node_modules/picocolors/picocolors.d.ts b/node_modules/picocolors/picocolors.d.ts new file mode 100644 index 0000000..94e146a --- /dev/null +++ b/node_modules/picocolors/picocolors.d.ts @@ -0,0 +1,5 @@ +import { Colors } from "./types" + +declare const picocolors: Colors & { createColors: (enabled?: boolean) => Colors } + +export = picocolors diff --git a/node_modules/picocolors/picocolors.js b/node_modules/picocolors/picocolors.js new file mode 100644 index 0000000..e32df85 --- /dev/null +++ b/node_modules/picocolors/picocolors.js @@ -0,0 +1,75 @@ +let p = process || {}, argv = p.argv || [], env = p.env || {} +let isColorSupported = + !(!!env.NO_COLOR || argv.includes("--no-color")) && + (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI) + +let formatter = (open, close, replace = open) => + input => { + let string = "" + input, index = string.indexOf(close, open.length) + return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close + } + +let replaceClose = (string, close, replace, index) => { + let result = "", cursor = 0 + do { + result += string.substring(cursor, index) + replace + cursor = index + close.length + index = string.indexOf(close, cursor) + } while (~index) + return result + string.substring(cursor) +} + +let createColors = (enabled = isColorSupported) => { + let f = enabled ? formatter : () => String + return { + isColorSupported: enabled, + reset: f("\x1b[0m", "\x1b[0m"), + bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), + dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), + italic: f("\x1b[3m", "\x1b[23m"), + underline: f("\x1b[4m", "\x1b[24m"), + inverse: f("\x1b[7m", "\x1b[27m"), + hidden: f("\x1b[8m", "\x1b[28m"), + strikethrough: f("\x1b[9m", "\x1b[29m"), + + black: f("\x1b[30m", "\x1b[39m"), + red: f("\x1b[31m", "\x1b[39m"), + green: f("\x1b[32m", "\x1b[39m"), + yellow: f("\x1b[33m", "\x1b[39m"), + blue: f("\x1b[34m", "\x1b[39m"), + magenta: f("\x1b[35m", "\x1b[39m"), + cyan: f("\x1b[36m", "\x1b[39m"), + white: f("\x1b[37m", "\x1b[39m"), + gray: f("\x1b[90m", "\x1b[39m"), + + bgBlack: f("\x1b[40m", "\x1b[49m"), + bgRed: f("\x1b[41m", "\x1b[49m"), + bgGreen: f("\x1b[42m", "\x1b[49m"), + bgYellow: f("\x1b[43m", "\x1b[49m"), + bgBlue: f("\x1b[44m", "\x1b[49m"), + bgMagenta: f("\x1b[45m", "\x1b[49m"), + bgCyan: f("\x1b[46m", "\x1b[49m"), + bgWhite: f("\x1b[47m", "\x1b[49m"), + + blackBright: f("\x1b[90m", "\x1b[39m"), + redBright: f("\x1b[91m", "\x1b[39m"), + greenBright: f("\x1b[92m", "\x1b[39m"), + yellowBright: f("\x1b[93m", "\x1b[39m"), + blueBright: f("\x1b[94m", "\x1b[39m"), + magentaBright: f("\x1b[95m", "\x1b[39m"), + cyanBright: f("\x1b[96m", "\x1b[39m"), + whiteBright: f("\x1b[97m", "\x1b[39m"), + + bgBlackBright: f("\x1b[100m", "\x1b[49m"), + bgRedBright: f("\x1b[101m", "\x1b[49m"), + bgGreenBright: f("\x1b[102m", "\x1b[49m"), + bgYellowBright: f("\x1b[103m", "\x1b[49m"), + bgBlueBright: f("\x1b[104m", "\x1b[49m"), + bgMagentaBright: f("\x1b[105m", "\x1b[49m"), + bgCyanBright: f("\x1b[106m", "\x1b[49m"), + bgWhiteBright: f("\x1b[107m", "\x1b[49m"), + } +} + +module.exports = createColors() +module.exports.createColors = createColors diff --git a/node_modules/picocolors/types.d.ts b/node_modules/picocolors/types.d.ts new file mode 100644 index 0000000..cd1aec4 --- /dev/null +++ b/node_modules/picocolors/types.d.ts @@ -0,0 +1,51 @@ +export type Formatter = (input: string | number | null | undefined) => string + +export interface Colors { + isColorSupported: boolean + + reset: Formatter + bold: Formatter + dim: Formatter + italic: Formatter + underline: Formatter + inverse: Formatter + hidden: Formatter + strikethrough: Formatter + + black: Formatter + red: Formatter + green: Formatter + yellow: Formatter + blue: Formatter + magenta: Formatter + cyan: Formatter + white: Formatter + gray: Formatter + + bgBlack: Formatter + bgRed: Formatter + bgGreen: Formatter + bgYellow: Formatter + bgBlue: Formatter + bgMagenta: Formatter + bgCyan: Formatter + bgWhite: Formatter + + blackBright: Formatter + redBright: Formatter + greenBright: Formatter + yellowBright: Formatter + blueBright: Formatter + magentaBright: Formatter + cyanBright: Formatter + whiteBright: Formatter + + bgBlackBright: Formatter + bgRedBright: Formatter + bgGreenBright: Formatter + bgYellowBright: Formatter + bgBlueBright: Formatter + bgMagentaBright: Formatter + bgCyanBright: Formatter + bgWhiteBright: Formatter +} diff --git a/node_modules/picomatch/CHANGELOG.md b/node_modules/picomatch/CHANGELOG.md new file mode 100644 index 0000000..8ccc6c1 --- /dev/null +++ b/node_modules/picomatch/CHANGELOG.md @@ -0,0 +1,136 @@ +# Release history + +**All notable changes to this project will be documented in this file.** + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +
+ Guiding Principles + +- Changelogs are for humans, not machines. +- There should be an entry for every single version. +- The same types of changes should be grouped. +- Versions and sections should be linkable. +- The latest version comes first. +- The release date of each versions is displayed. +- Mention whether you follow Semantic Versioning. + +
+ +
+ Types of changes + +Changelog entries are classified using the following labels _(from [keep-a-changelog](http://keepachangelog.com/)_): + +- `Added` for new features. +- `Changed` for changes in existing functionality. +- `Deprecated` for soon-to-be removed features. +- `Removed` for now removed features. +- `Fixed` for any bug fixes. +- `Security` in case of vulnerabilities. + +
+ +## 2.3.1 (2022-01-02) + +### Fixed + +* Fixes bug when a pattern containing an expression after the closing parenthesis (`/!(*.d).{ts,tsx}`) was incorrectly converted to regexp ([9f241ef](https://github.com/micromatch/picomatch/commit/9f241ef)). + +### Changed + +* Some documentation improvements ([f81d236](https://github.com/micromatch/picomatch/commit/f81d236), [421e0e7](https://github.com/micromatch/picomatch/commit/421e0e7)). + +## 2.3.0 (2021-05-21) + +### Fixed + +* Fixes bug where file names with two dots were not being matched consistently with negation extglobs containing a star ([56083ef](https://github.com/micromatch/picomatch/commit/56083ef)) + +## 2.2.3 (2021-04-10) + +### Fixed + +* Do not skip pattern seperator for square brackets ([fb08a30](https://github.com/micromatch/picomatch/commit/fb08a30)). +* Set negatedExtGlob also if it does not span the whole pattern ([032e3f5](https://github.com/micromatch/picomatch/commit/032e3f5)). + +## 2.2.2 (2020-03-21) + +### Fixed + +* Correctly handle parts of the pattern after parentheses in the `scan` method ([e15b920](https://github.com/micromatch/picomatch/commit/e15b920)). + +## 2.2.1 (2020-01-04) + +* Fixes [#49](https://github.com/micromatch/picomatch/issues/49), so that braces with no sets or ranges are now propertly treated as literals. + +## 2.2.0 (2020-01-04) + +* Disable fastpaths mode for the parse method ([5b8d33f](https://github.com/micromatch/picomatch/commit/5b8d33f)) +* Add `tokens`, `slashes`, and `parts` to the object returned by `picomatch.scan()`. + +## 2.1.0 (2019-10-31) + +* add benchmarks for scan ([4793b92](https://github.com/micromatch/picomatch/commit/4793b92)) +* Add eslint object-curly-spacing rule ([707c650](https://github.com/micromatch/picomatch/commit/707c650)) +* Add prefer-const eslint rule ([5c7501c](https://github.com/micromatch/picomatch/commit/5c7501c)) +* Add support for nonegate in scan API ([275c9b9](https://github.com/micromatch/picomatch/commit/275c9b9)) +* Change lets to consts. Move root import up. ([4840625](https://github.com/micromatch/picomatch/commit/4840625)) +* closes https://github.com/micromatch/picomatch/issues/21 ([766bcb0](https://github.com/micromatch/picomatch/commit/766bcb0)) +* Fix "Extglobs" table in readme ([eb19da8](https://github.com/micromatch/picomatch/commit/eb19da8)) +* fixes https://github.com/micromatch/picomatch/issues/20 ([9caca07](https://github.com/micromatch/picomatch/commit/9caca07)) +* fixes https://github.com/micromatch/picomatch/issues/26 ([fa58f45](https://github.com/micromatch/picomatch/commit/fa58f45)) +* Lint test ([d433a34](https://github.com/micromatch/picomatch/commit/d433a34)) +* lint unit tests ([0159b55](https://github.com/micromatch/picomatch/commit/0159b55)) +* Make scan work with noext ([6c02e03](https://github.com/micromatch/picomatch/commit/6c02e03)) +* minor linting ([c2a2b87](https://github.com/micromatch/picomatch/commit/c2a2b87)) +* minor parser improvements ([197671d](https://github.com/micromatch/picomatch/commit/197671d)) +* remove eslint since it... ([07876fa](https://github.com/micromatch/picomatch/commit/07876fa)) +* remove funding file ([8ebe96d](https://github.com/micromatch/picomatch/commit/8ebe96d)) +* Remove unused funks ([cbc6d54](https://github.com/micromatch/picomatch/commit/cbc6d54)) +* Run eslint during pretest, fix existing eslint findings ([0682367](https://github.com/micromatch/picomatch/commit/0682367)) +* support `noparen` in scan ([3d37569](https://github.com/micromatch/picomatch/commit/3d37569)) +* update changelog ([7b34e77](https://github.com/micromatch/picomatch/commit/7b34e77)) +* update travis ([777f038](https://github.com/micromatch/picomatch/commit/777f038)) +* Use eslint-disable-next-line instead of eslint-disable ([4e7c1fd](https://github.com/micromatch/picomatch/commit/4e7c1fd)) + +## 2.0.7 (2019-05-14) + +* 2.0.7 ([9eb9a71](https://github.com/micromatch/picomatch/commit/9eb9a71)) +* supports lookbehinds ([1f63f7e](https://github.com/micromatch/picomatch/commit/1f63f7e)) +* update .verb.md file with typo change ([2741279](https://github.com/micromatch/picomatch/commit/2741279)) +* fix: typo in README ([0753e44](https://github.com/micromatch/picomatch/commit/0753e44)) + +## 2.0.4 (2019-04-10) + +### Fixed + +- Readme link [fixed](https://github.com/micromatch/picomatch/pull/13/commits/a96ab3aa2b11b6861c23289964613d85563b05df) by @danez. +- `options.capture` now works as expected when fastpaths are enabled. See https://github.com/micromatch/picomatch/pull/12/commits/26aefd71f1cfaf95c37f1c1fcab68a693b037304. Thanks to @DrPizza. + +## 2.0.0 (2019-04-10) + +### Added + +- Adds support for `options.onIgnore`. See the readme for details +- Adds support for `options.onResult`. See the readme for details + +### Breaking changes + +- The unixify option was renamed to `windows` +- caching and all related options and methods have been removed + +## 1.0.0 (2018-11-05) + +- adds `.onMatch` option +- improvements to `.scan` method +- numerous improvements and optimizations for matching and parsing +- better windows path handling + +## 0.1.0 - 2017-04-13 + +First release. + + +[keep-a-changelog]: https://github.com/olivierlacan/keep-a-changelog diff --git a/node_modules/picomatch/LICENSE b/node_modules/picomatch/LICENSE new file mode 100644 index 0000000..3608dca --- /dev/null +++ b/node_modules/picomatch/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/picomatch/README.md b/node_modules/picomatch/README.md new file mode 100644 index 0000000..b0526e2 --- /dev/null +++ b/node_modules/picomatch/README.md @@ -0,0 +1,708 @@ +

Picomatch

+ +

+ +version + + +test status + + +coverage status + + +downloads + +

+ +
+
+ +

+Blazing fast and accurate glob matcher written in JavaScript.
+No dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions. +

+ +
+
+ +## Why picomatch? + +* **Lightweight** - No dependencies +* **Minimal** - Tiny API surface. Main export is a function that takes a glob pattern and returns a matcher function. +* **Fast** - Loads in about 2ms (that's several times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps) +* **Performant** - Use the returned matcher function to speed up repeat matching (like when watching files) +* **Accurate matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories, [advanced globbing](#advanced-globbing) with extglobs, braces, and POSIX brackets, and support for escaping special characters with `\` or quotes. +* **Well tested** - Thousands of unit tests + +See the [library comparison](#library-comparisons) to other libraries. + +
+
+ +## Table of Contents + +
Click to expand + +- [Install](#install) +- [Usage](#usage) +- [API](#api) + * [picomatch](#picomatch) + * [.test](#test) + * [.matchBase](#matchbase) + * [.isMatch](#ismatch) + * [.parse](#parse) + * [.scan](#scan) + * [.compileRe](#compilere) + * [.makeRe](#makere) + * [.toRegex](#toregex) +- [Options](#options) + * [Picomatch options](#picomatch-options) + * [Scan Options](#scan-options) + * [Options Examples](#options-examples) +- [Globbing features](#globbing-features) + * [Basic globbing](#basic-globbing) + * [Advanced globbing](#advanced-globbing) + * [Braces](#braces) + * [Matching special characters as literals](#matching-special-characters-as-literals) +- [Library Comparisons](#library-comparisons) +- [Benchmarks](#benchmarks) +- [Philosophies](#philosophies) +- [About](#about) + * [Author](#author) + * [License](#license) + +_(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_ + +
+ +
+
+ +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +npm install --save picomatch +``` + +
+ +## Usage + +The main export is a function that takes a glob pattern and an options object and returns a function for matching strings. + +```js +const pm = require('picomatch'); +const isMatch = pm('*.js'); + +console.log(isMatch('abcd')); //=> false +console.log(isMatch('a.js')); //=> true +console.log(isMatch('a.md')); //=> false +console.log(isMatch('a/b.js')); //=> false +``` + +
+ +## API + +### [picomatch](lib/picomatch.js#L32) + +Creates a matcher function from one or more glob patterns. The returned function takes a string to match as its first argument, and returns true if the string is a match. The returned matcher function also takes a boolean as the second argument that, when true, returns an object with additional information. + +**Params** + +* `globs` **{String|Array}**: One or more glob patterns. +* `options` **{Object=}** +* `returns` **{Function=}**: Returns a matcher function. + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch(glob[, options]); + +const isMatch = picomatch('*.!(*a)'); +console.log(isMatch('a.a')); //=> false +console.log(isMatch('a.b')); //=> true +``` + +### [.test](lib/picomatch.js#L117) + +Test `input` with the given `regex`. This is used by the main `picomatch()` function to test the input string. + +**Params** + +* `input` **{String}**: String to test. +* `regex` **{RegExp}** +* `returns` **{Object}**: Returns an object with matching info. + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch.test(input, regex[, options]); + +console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); +// { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } +``` + +### [.matchBase](lib/picomatch.js#L161) + +Match the basename of a filepath. + +**Params** + +* `input` **{String}**: String to test. +* `glob` **{RegExp|String}**: Glob pattern or regex created by [.makeRe](#makeRe). +* `returns` **{Boolean}** + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch.matchBase(input, glob[, options]); +console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true +``` + +### [.isMatch](lib/picomatch.js#L183) + +Returns true if **any** of the given glob `patterns` match the specified `string`. + +**Params** + +* **{String|Array}**: str The string to test. +* **{String|Array}**: patterns One or more glob patterns to use for matching. +* **{Object}**: See available [options](#options). +* `returns` **{Boolean}**: Returns true if any patterns match `str` + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch.isMatch(string, patterns[, options]); + +console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true +console.log(picomatch.isMatch('a.a', 'b.*')); //=> false +``` + +### [.parse](lib/picomatch.js#L199) + +Parse a glob pattern to create the source string for a regular expression. + +**Params** + +* `pattern` **{String}** +* `options` **{Object}** +* `returns` **{Object}**: Returns an object with useful properties and output to be used as a regex source string. + +**Example** + +```js +const picomatch = require('picomatch'); +const result = picomatch.parse(pattern[, options]); +``` + +### [.scan](lib/picomatch.js#L231) + +Scan a glob pattern to separate the pattern into segments. + +**Params** + +* `input` **{String}**: Glob pattern to scan. +* `options` **{Object}** +* `returns` **{Object}**: Returns an object with + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch.scan(input[, options]); + +const result = picomatch.scan('!./foo/*.js'); +console.log(result); +{ prefix: '!./', + input: '!./foo/*.js', + start: 3, + base: 'foo', + glob: '*.js', + isBrace: false, + isBracket: false, + isGlob: true, + isExtglob: false, + isGlobstar: false, + negated: true } +``` + +### [.compileRe](lib/picomatch.js#L245) + +Compile a regular expression from the `state` object returned by the +[parse()](#parse) method. + +**Params** + +* `state` **{Object}** +* `options` **{Object}** +* `returnOutput` **{Boolean}**: Intended for implementors, this argument allows you to return the raw output from the parser. +* `returnState` **{Boolean}**: Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. +* `returns` **{RegExp}** + +### [.makeRe](lib/picomatch.js#L286) + +Create a regular expression from a parsed glob pattern. + +**Params** + +* `state` **{String}**: The object returned from the `.parse` method. +* `options` **{Object}** +* `returnOutput` **{Boolean}**: Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. +* `returnState` **{Boolean}**: Implementors may use this argument to return the state from the parsed glob with the returned regular expression. +* `returns` **{RegExp}**: Returns a regex created from the given pattern. + +**Example** + +```js +const picomatch = require('picomatch'); +const state = picomatch.parse('*.js'); +// picomatch.compileRe(state[, options]); + +console.log(picomatch.compileRe(state)); +//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ +``` + +### [.toRegex](lib/picomatch.js#L321) + +Create a regular expression from the given regex source string. + +**Params** + +* `source` **{String}**: Regular expression source string. +* `options` **{Object}** +* `returns` **{RegExp}** + +**Example** + +```js +const picomatch = require('picomatch'); +// picomatch.toRegex(source[, options]); + +const { output } = picomatch.parse('*.js'); +console.log(picomatch.toRegex(output)); +//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ +``` + +
+ +## Options + +### Picomatch options + +The following options may be used with the main `picomatch()` function or any of the methods on the picomatch API. + +| **Option** | **Type** | **Default value** | **Description** | +| --- | --- | --- | --- | +| `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. | +| `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). | +| `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. | +| `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). | +| `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` | +| `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. | +| `dot` | `boolean` | `false` | Enable dotfile matching. By default, dotfiles are ignored unless a `.` is explicitly defined in the pattern, or `options.dot` is true | +| `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. | +| `failglob` | `boolean` | `false` | Throws an error if no matches are found. Based on the bash option of the same name. | +| `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. | +| `flags` | `string` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. | +| [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. | +| `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. | +| `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. | +| `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. | +| `matchBase` | `boolean` | `false` | Alias for `basename` | +| `maxLength` | `boolean` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. | +| `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. | +| `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. | +| `nocase` | `boolean` | `false` | Make matching case-insensitive. Equivalent to the regex `i` flag. Note that this option is overridden by the `flags` option. | +| `nodupes` | `boolean` | `true` | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. | +| `noext` | `boolean` | `false` | Alias for `noextglob` | +| `noextglob` | `boolean` | `false` | Disable support for matching with extglobs (like `+(a\|b)`) | +| `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) | +| `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` | +| `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. | +| [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. | +| [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. | +| [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. | +| `posix` | `boolean` | `false` | Support POSIX character classes ("posix brackets"). | +| `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself | +| `prepend` | `boolean` | `undefined` | String to prepend to the generated regex used for matching. | +| `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). | +| `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. | +| `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. | +| `unescape` | `boolean` | `undefined` | Remove backslashes preceding escaped characters in the glob pattern. By default, backslashes are retained. | +| `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatibility. | + +picomatch has automatic detection for regex positive and negative lookbehinds. If the pattern contains a negative lookbehind, you must be using Node.js >= 8.10 or else picomatch will throw an error. + +### Scan Options + +In addition to the main [picomatch options](#picomatch-options), the following options may also be used with the [.scan](#scan) method. + +| **Option** | **Type** | **Default value** | **Description** | +| --- | --- | --- | --- | +| `tokens` | `boolean` | `false` | When `true`, the returned object will include an array of tokens (objects), representing each path "segment" in the scanned glob pattern | +| `parts` | `boolean` | `false` | When `true`, the returned object will include an array of strings representing each path "segment" in the scanned glob pattern. This is automatically enabled when `options.tokens` is true | + +**Example** + +```js +const picomatch = require('picomatch'); +const result = picomatch.scan('!./foo/*.js', { tokens: true }); +console.log(result); +// { +// prefix: '!./', +// input: '!./foo/*.js', +// start: 3, +// base: 'foo', +// glob: '*.js', +// isBrace: false, +// isBracket: false, +// isGlob: true, +// isExtglob: false, +// isGlobstar: false, +// negated: true, +// maxDepth: 2, +// tokens: [ +// { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true }, +// { value: 'foo', depth: 1, isGlob: false }, +// { value: '*.js', depth: 1, isGlob: true } +// ], +// slashes: [ 2, 6 ], +// parts: [ 'foo', '*.js' ] +// } +``` + +
+ +### Options Examples + +#### options.expandRange + +**Type**: `function` + +**Default**: `undefined` + +Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need. + +**Example** + +The following example shows how to create a glob that matches a folder + +```js +const fill = require('fill-range'); +const regex = pm.makeRe('foo/{01..25}/bar', { + expandRange(a, b) { + return `(${fill(a, b, { toRegex: true })})`; + } +}); + +console.log(regex); +//=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/ + +console.log(regex.test('foo/00/bar')) // false +console.log(regex.test('foo/01/bar')) // true +console.log(regex.test('foo/10/bar')) // true +console.log(regex.test('foo/22/bar')) // true +console.log(regex.test('foo/25/bar')) // true +console.log(regex.test('foo/26/bar')) // false +``` + +#### options.format + +**Type**: `function` + +**Default**: `undefined` + +Custom function for formatting strings before they're matched. + +**Example** + +```js +// strip leading './' from strings +const format = str => str.replace(/^\.\//, ''); +const isMatch = picomatch('foo/*.js', { format }); +console.log(isMatch('./foo/bar.js')); //=> true +``` + +#### options.onMatch + +```js +const onMatch = ({ glob, regex, input, output }) => { + console.log({ glob, regex, input, output }); +}; + +const isMatch = picomatch('*', { onMatch }); +isMatch('foo'); +isMatch('bar'); +isMatch('baz'); +``` + +#### options.onIgnore + +```js +const onIgnore = ({ glob, regex, input, output }) => { + console.log({ glob, regex, input, output }); +}; + +const isMatch = picomatch('*', { onIgnore, ignore: 'f*' }); +isMatch('foo'); +isMatch('bar'); +isMatch('baz'); +``` + +#### options.onResult + +```js +const onResult = ({ glob, regex, input, output }) => { + console.log({ glob, regex, input, output }); +}; + +const isMatch = picomatch('*', { onResult, ignore: 'f*' }); +isMatch('foo'); +isMatch('bar'); +isMatch('baz'); +``` + +
+
+ +## Globbing features + +* [Basic globbing](#basic-globbing) (Wildcard matching) +* [Advanced globbing](#advanced-globbing) (extglobs, posix brackets, brace matching) + +### Basic globbing + +| **Character** | **Description** | +| --- | --- | +| `*` | Matches any character zero or more times, excluding path separators. Does _not match_ path separators or hidden files or directories ("dotfiles"), unless explicitly enabled by setting the `dot` option to `true`. | +| `**` | Matches any character zero or more times, including path separators. Note that `**` will only match path separators (`/`, and `\\` on Windows) when they are the only characters in a path segment. Thus, `foo**/bar` is equivalent to `foo*/bar`, and `foo/a**b/bar` is equivalent to `foo/a*b/bar`, and _more than two_ consecutive stars in a glob path segment are regarded as _a single star_. Thus, `foo/***/bar` is equivalent to `foo/*/bar`. | +| `?` | Matches any character excluding path separators one time. Does _not match_ path separators or leading dots. | +| `[abc]` | Matches any characters inside the brackets. For example, `[abc]` would match the characters `a`, `b` or `c`, and nothing else. | + +#### Matching behavior vs. Bash + +Picomatch's matching features and expected results in unit tests are based on Bash's unit tests and the Bash 4.3 specification, with the following exceptions: + +* Bash will match `foo/bar/baz` with `*`. Picomatch only matches nested directories with `**`. +* Bash greedily matches with negated extglobs. For example, Bash 4.3 says that `!(foo)*` should match `foo` and `foobar`, since the trailing `*` bracktracks to match the preceding pattern. This is very memory-inefficient, and IMHO, also incorrect. Picomatch would return `false` for both `foo` and `foobar`. + +
+ +### Advanced globbing + +* [extglobs](#extglobs) +* [POSIX brackets](#posix-brackets) +* [Braces](#brace-expansion) + +#### Extglobs + +| **Pattern** | **Description** | +| --- | --- | +| `@(pattern)` | Match _only one_ consecutive occurrence of `pattern` | +| `*(pattern)` | Match _zero or more_ consecutive occurrences of `pattern` | +| `+(pattern)` | Match _one or more_ consecutive occurrences of `pattern` | +| `?(pattern)` | Match _zero or **one**_ consecutive occurrences of `pattern` | +| `!(pattern)` | Match _anything but_ `pattern` | + +**Examples** + +```js +const pm = require('picomatch'); + +// *(pattern) matches ZERO or more of "pattern" +console.log(pm.isMatch('a', 'a*(z)')); // true +console.log(pm.isMatch('az', 'a*(z)')); // true +console.log(pm.isMatch('azzz', 'a*(z)')); // true + +// +(pattern) matches ONE or more of "pattern" +console.log(pm.isMatch('a', 'a*(z)')); // true +console.log(pm.isMatch('az', 'a*(z)')); // true +console.log(pm.isMatch('azzz', 'a*(z)')); // true + +// supports multiple extglobs +console.log(pm.isMatch('foo.bar', '!(foo).!(bar)')); // false + +// supports nested extglobs +console.log(pm.isMatch('foo.bar', '!(!(foo)).!(!(bar))')); // true +``` + +#### POSIX brackets + +POSIX classes are disabled by default. Enable this feature by setting the `posix` option to true. + +**Enable POSIX bracket support** + +```js +console.log(pm.makeRe('[[:word:]]+', { posix: true })); +//=> /^(?:(?=.)[A-Za-z0-9_]+\/?)$/ +``` + +**Supported POSIX classes** + +The following named POSIX bracket expressions are supported: + +* `[:alnum:]` - Alphanumeric characters, equ `[a-zA-Z0-9]` +* `[:alpha:]` - Alphabetical characters, equivalent to `[a-zA-Z]`. +* `[:ascii:]` - ASCII characters, equivalent to `[\\x00-\\x7F]`. +* `[:blank:]` - Space and tab characters, equivalent to `[ \\t]`. +* `[:cntrl:]` - Control characters, equivalent to `[\\x00-\\x1F\\x7F]`. +* `[:digit:]` - Numerical digits, equivalent to `[0-9]`. +* `[:graph:]` - Graph characters, equivalent to `[\\x21-\\x7E]`. +* `[:lower:]` - Lowercase letters, equivalent to `[a-z]`. +* `[:print:]` - Print characters, equivalent to `[\\x20-\\x7E ]`. +* `[:punct:]` - Punctuation and symbols, equivalent to `[\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~]`. +* `[:space:]` - Extended space characters, equivalent to `[ \\t\\r\\n\\v\\f]`. +* `[:upper:]` - Uppercase letters, equivalent to `[A-Z]`. +* `[:word:]` - Word characters (letters, numbers and underscores), equivalent to `[A-Za-z0-9_]`. +* `[:xdigit:]` - Hexadecimal digits, equivalent to `[A-Fa-f0-9]`. + +See the [Bash Reference Manual](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) for more information. + +### Braces + +Picomatch does not do brace expansion. For [brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) and advanced matching with braces, use [micromatch](https://github.com/micromatch/micromatch) instead. Picomatch has very basic support for braces. + +### Matching special characters as literals + +If you wish to match the following special characters in a filepath, and you want to use these characters in your glob pattern, they must be escaped with backslashes or quotes: + +**Special Characters** + +Some characters that are used for matching in regular expressions are also regarded as valid file path characters on some platforms. + +To match any of the following characters as literals: `$^*+?()[] + +Examples: + +```js +console.log(pm.makeRe('foo/bar \\(1\\)')); +console.log(pm.makeRe('foo/bar \\(1\\)')); +``` + +
+
+ +## Library Comparisons + +The following table shows which features are supported by [minimatch](https://github.com/isaacs/minimatch), [micromatch](https://github.com/micromatch/micromatch), [picomatch](https://github.com/micromatch/picomatch), [nanomatch](https://github.com/micromatch/nanomatch), [extglob](https://github.com/micromatch/extglob), [braces](https://github.com/micromatch/braces), and [expand-brackets](https://github.com/micromatch/expand-brackets). + +| **Feature** | `minimatch` | `micromatch` | `picomatch` | `nanomatch` | `extglob` | `braces` | `expand-brackets` | +| --- | --- | --- | --- | --- | --- | --- | --- | +| Wildcard matching (`*?+`) | ✔ | ✔ | ✔ | ✔ | - | - | - | +| Advancing globbing | ✔ | ✔ | ✔ | - | - | - | - | +| Brace _matching_ | ✔ | ✔ | ✔ | - | - | ✔ | - | +| Brace _expansion_ | ✔ | ✔ | - | - | - | ✔ | - | +| Extglobs | partial | ✔ | ✔ | - | ✔ | - | - | +| Posix brackets | - | ✔ | ✔ | - | - | - | ✔ | +| Regular expression syntax | - | ✔ | ✔ | ✔ | ✔ | - | ✔ | +| File system operations | - | - | - | - | - | - | - | + +
+
+ +## Benchmarks + +Performance comparison of picomatch and minimatch. + +``` +# .makeRe star + picomatch x 1,993,050 ops/sec ±0.51% (91 runs sampled) + minimatch x 627,206 ops/sec ±1.96% (87 runs sampled)) + +# .makeRe star; dot=true + picomatch x 1,436,640 ops/sec ±0.62% (91 runs sampled) + minimatch x 525,876 ops/sec ±0.60% (88 runs sampled) + +# .makeRe globstar + picomatch x 1,592,742 ops/sec ±0.42% (90 runs sampled) + minimatch x 962,043 ops/sec ±1.76% (91 runs sampled)d) + +# .makeRe globstars + picomatch x 1,615,199 ops/sec ±0.35% (94 runs sampled) + minimatch x 477,179 ops/sec ±1.33% (91 runs sampled) + +# .makeRe with leading star + picomatch x 1,220,856 ops/sec ±0.40% (92 runs sampled) + minimatch x 453,564 ops/sec ±1.43% (94 runs sampled) + +# .makeRe - basic braces + picomatch x 392,067 ops/sec ±0.70% (90 runs sampled) + minimatch x 99,532 ops/sec ±2.03% (87 runs sampled)) +``` + +
+
+ +## Philosophies + +The goal of this library is to be blazing fast, without compromising on accuracy. + +**Accuracy** + +The number one of goal of this library is accuracy. However, it's not unusual for different glob implementations to have different rules for matching behavior, even with simple wildcard matching. It gets increasingly more complicated when combinations of different features are combined, like when extglobs are combined with globstars, braces, slashes, and so on: `!(**/{a,b,*/c})`. + +Thus, given that there is no canonical glob specification to use as a single source of truth when differences of opinion arise regarding behavior, sometimes we have to implement our best judgement and rely on feedback from users to make improvements. + +**Performance** + +Although this library performs well in benchmarks, and in most cases it's faster than other popular libraries we benchmarked against, we will always choose accuracy over performance. It's not helpful to anyone if our library is faster at returning the wrong answer. + +
+
+ +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2017-present, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). diff --git a/node_modules/picomatch/index.js b/node_modules/picomatch/index.js new file mode 100644 index 0000000..d2f2bc5 --- /dev/null +++ b/node_modules/picomatch/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/picomatch'); diff --git a/node_modules/picomatch/lib/constants.js b/node_modules/picomatch/lib/constants.js new file mode 100644 index 0000000..a62ef38 --- /dev/null +++ b/node_modules/picomatch/lib/constants.js @@ -0,0 +1,179 @@ +'use strict'; + +const path = require('path'); +const WIN_SLASH = '\\\\/'; +const WIN_NO_SLASH = `[^${WIN_SLASH}]`; + +/** + * Posix glob regex + */ + +const DOT_LITERAL = '\\.'; +const PLUS_LITERAL = '\\+'; +const QMARK_LITERAL = '\\?'; +const SLASH_LITERAL = '\\/'; +const ONE_CHAR = '(?=.)'; +const QMARK = '[^/]'; +const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; +const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; +const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; +const NO_DOT = `(?!${DOT_LITERAL})`; +const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; +const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; +const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; +const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; +const STAR = `${QMARK}*?`; + +const POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR, + START_ANCHOR +}; + +/** + * Windows glob regex + */ + +const WINDOWS_CHARS = { + ...POSIX_CHARS, + + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)` +}; + +/** + * POSIX Bracket Regex + */ + +const POSIX_REGEX_SOURCE = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; + +module.exports = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE, + + // regular expressions + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + + // Replace globs with equivalent patterns to reduce parsing time. + REPLACEMENTS: { + '***': '*', + '**/**': '**', + '**/**/**': '**' + }, + + // Digits + CHAR_0: 48, /* 0 */ + CHAR_9: 57, /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 65, /* A */ + CHAR_LOWERCASE_A: 97, /* a */ + CHAR_UPPERCASE_Z: 90, /* Z */ + CHAR_LOWERCASE_Z: 122, /* z */ + + CHAR_LEFT_PARENTHESES: 40, /* ( */ + CHAR_RIGHT_PARENTHESES: 41, /* ) */ + + CHAR_ASTERISK: 42, /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: 38, /* & */ + CHAR_AT: 64, /* @ */ + CHAR_BACKWARD_SLASH: 92, /* \ */ + CHAR_CARRIAGE_RETURN: 13, /* \r */ + CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ + CHAR_COLON: 58, /* : */ + CHAR_COMMA: 44, /* , */ + CHAR_DOT: 46, /* . */ + CHAR_DOUBLE_QUOTE: 34, /* " */ + CHAR_EQUAL: 61, /* = */ + CHAR_EXCLAMATION_MARK: 33, /* ! */ + CHAR_FORM_FEED: 12, /* \f */ + CHAR_FORWARD_SLASH: 47, /* / */ + CHAR_GRAVE_ACCENT: 96, /* ` */ + CHAR_HASH: 35, /* # */ + CHAR_HYPHEN_MINUS: 45, /* - */ + CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ + CHAR_LEFT_CURLY_BRACE: 123, /* { */ + CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ + CHAR_LINE_FEED: 10, /* \n */ + CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ + CHAR_PERCENT: 37, /* % */ + CHAR_PLUS: 43, /* + */ + CHAR_QUESTION_MARK: 63, /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ + CHAR_RIGHT_CURLY_BRACE: 125, /* } */ + CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ + CHAR_SEMICOLON: 59, /* ; */ + CHAR_SINGLE_QUOTE: 39, /* ' */ + CHAR_SPACE: 32, /* */ + CHAR_TAB: 9, /* \t */ + CHAR_UNDERSCORE: 95, /* _ */ + CHAR_VERTICAL_LINE: 124, /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ + + SEP: path.sep, + + /** + * Create EXTGLOB_CHARS + */ + + extglobChars(chars) { + return { + '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, + '?': { type: 'qmark', open: '(?:', close: ')?' }, + '+': { type: 'plus', open: '(?:', close: ')+' }, + '*': { type: 'star', open: '(?:', close: ')*' }, + '@': { type: 'at', open: '(?:', close: ')' } + }; + }, + + /** + * Create GLOB_CHARS + */ + + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } +}; diff --git a/node_modules/picomatch/lib/parse.js b/node_modules/picomatch/lib/parse.js new file mode 100644 index 0000000..58269d0 --- /dev/null +++ b/node_modules/picomatch/lib/parse.js @@ -0,0 +1,1091 @@ +'use strict'; + +const constants = require('./constants'); +const utils = require('./utils'); + +/** + * Constants + */ + +const { + MAX_LENGTH, + POSIX_REGEX_SOURCE, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants; + +/** + * Helpers + */ + +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } + + args.sort(); + const value = `[${args.join('-')}]`; + + try { + /* eslint-disable-next-line no-new */ + new RegExp(value); + } catch (ex) { + return args.map(v => utils.escapeRegex(v)).join('..'); + } + + return value; +}; + +/** + * Create the message for a syntax error + */ + +const syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; +}; + +/** + * Parse the given input string. + * @param {String} input + * @param {Object} options + * @return {Object} + */ + +const parse = (input, options) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + input = REPLACEMENTS[input] || input; + + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + + let len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + const bos = { type: 'bos', value: '', output: opts.prepend || '' }; + const tokens = [bos]; + + const capture = opts.capture ? '' : '?:'; + const win32 = utils.isWindows(options); + + // create constants based on platform, for windows or posix + const PLATFORM_CHARS = constants.globChars(win32); + const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); + + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; + + const globstar = opts => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const nodot = opts.dot ? '' : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + // minimatch options support + if (typeof opts.noext === 'boolean') { + opts.noextglob = opts.noext; + } + + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: '', + output: '', + prefix: '', + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + + input = utils.removePrefix(input, state); + len = input.length; + + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + + /** + * Tokenizing helpers + */ + + const eos = () => state.index === len - 1; + const peek = state.peek = (n = 1) => input[state.index + n]; + const advance = state.advance = () => input[++state.index] || ''; + const remaining = () => input.slice(state.index + 1); + const consume = (value = '', num = 0) => { + state.consumed += value; + state.index += num; + }; + + const append = token => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + + const negate = () => { + let count = 1; + + while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { + advance(); + state.start++; + count++; + } + + if (count % 2 === 0) { + return false; + } + + state.negated = true; + state.start++; + return true; + }; + + const increment = type => { + state[type]++; + stack.push(type); + }; + + const decrement = type => { + state[type]--; + stack.pop(); + }; + + /** + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. + */ + + const push = tok => { + if (prev.type === 'globstar') { + const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); + const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); + + if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = 'star'; + prev.value = '*'; + prev.output = star; + state.output += prev.output; + } + } + + if (extglobs.length && tok.type !== 'paren') { + extglobs[extglobs.length - 1].inner += tok.value; + } + + if (tok.value || tok.output) append(tok); + if (prev && prev.type === 'text' && tok.type === 'text') { + prev.value += tok.value; + prev.output = (prev.output || '') + tok.value; + return; + } + + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + + const extglobOpen = (type, value) => { + const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + const output = (opts.capture ? '(' : '') + token.open; + + increment('parens'); + push({ type, value, output: state.output ? '' : ONE_CHAR }); + push({ type: 'paren', extglob: true, value: advance(), output }); + extglobs.push(token); + }; + + const extglobClose = token => { + let output = token.close + (opts.capture ? ')' : ''); + let rest; + + if (token.type === 'negate') { + let extglobStar = star; + + if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { + extglobStar = globstar(opts); + } + + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; + } + + if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { + // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. + // In this case, we need to parse the string and use it in the output of the original pattern. + // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. + // + // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. + const expression = parse(rest, { ...options, fastpaths: false }).output; + + output = token.close = `)${expression})${extglobStar})`; + } + + if (token.prev.type === 'bos') { + state.negatedExtglob = true; + } + } + + push({ type: 'paren', extglob: true, value, output }); + decrement('parens'); + }; + + /** + * Fast paths + */ + + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === '\\') { + backslashes = true; + return m; + } + + if (first === '?') { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ''); + } + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); + } + return QMARK.repeat(chars.length); + } + + if (first === '.') { + return DOT_LITERAL.repeat(chars.length); + } + + if (first === '*') { + if (esc) { + return esc + first + (rest ? star : ''); + } + return star; + } + return esc ? m : `\\${m}`; + }); + + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ''); + } else { + output = output.replace(/\\+/g, m => { + return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); + }); + } + } + + if (output === input && opts.contains === true) { + state.output = input; + return state; + } + + state.output = utils.wrapOutput(output, state, options); + return state; + } + + /** + * Tokenize input until we reach end-of-string + */ + + while (!eos()) { + value = advance(); + + if (value === '\u0000') { + continue; + } + + /** + * Escaped characters + */ + + if (value === '\\') { + const next = peek(); + + if (next === '/' && opts.bash !== true) { + continue; + } + + if (next === '.' || next === ';') { + continue; + } + + if (!next) { + value += '\\'; + push({ type: 'text', value }); + continue; + } + + // collapse slashes to reduce potential for exploits + const match = /^\\+/.exec(remaining()); + let slashes = 0; + + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + if (slashes % 2 !== 0) { + value += '\\'; + } + } + + if (opts.unescape === true) { + value = advance(); + } else { + value += advance(); + } + + if (state.brackets === 0) { + push({ type: 'text', value }); + continue; + } + } + + /** + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ + + if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { + if (opts.posix !== false && value === ':') { + const inner = prev.value.slice(1); + if (inner.includes('[')) { + prev.posix = true; + + if (inner.includes(':')) { + const idx = prev.value.lastIndexOf('['); + const pre = prev.value.slice(0, idx); + const rest = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE[rest]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + continue; + } + } + } + } + + if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { + value = `\\${value}`; + } + + if (value === ']' && (prev.value === '[' || prev.value === '[^')) { + value = `\\${value}`; + } + + if (opts.posix === true && value === '!' && prev.value === '[') { + value = '^'; + } + + prev.value += value; + append({ value }); + continue; + } + + /** + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ + + if (state.quotes === 1 && value !== '"') { + value = utils.escapeRegex(value); + prev.value += value; + append({ value }); + continue; + } + + /** + * Double quotes + */ + + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) { + push({ type: 'text', value }); + } + continue; + } + + /** + * Parentheses + */ + + if (value === '(') { + increment('parens'); + push({ type: 'paren', value }); + continue; + } + + if (value === ')') { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '(')); + } + + const extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } + + push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); + decrement('parens'); + continue; + } + + /** + * Square brackets + */ + + if (value === '[') { + if (opts.nobracket === true || !remaining().includes(']')) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('closing', ']')); + } + + value = `\\${value}`; + } else { + increment('brackets'); + } + + push({ type: 'bracket', value }); + continue; + } + + if (value === ']') { + if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '[')); + } + + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + decrement('brackets'); + + const prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { + value = `/${value}`; + } + + prev.value += value; + append({ value }); + + // when literal brackets are explicitly disabled + // assume we should match with a regex character class + if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { + continue; + } + + const escaped = utils.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); + + // when literal brackets are explicitly enabled + // assume we should escape the brackets to match literal characters + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } + + // when the user specifies nothing, try to match both + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } + + /** + * Braces + */ + + if (value === '{' && opts.nobrace !== true) { + increment('braces'); + + const open = { + type: 'brace', + value, + output: '(', + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; + + braces.push(open); + push(open); + continue; + } + + if (value === '}') { + const brace = braces[braces.length - 1]; + + if (opts.nobrace === true || !brace) { + push({ type: 'text', value, output: value }); + continue; + } + + let output = ')'; + + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; + + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + if (arr[i].type === 'brace') { + break; + } + if (arr[i].type !== 'dots') { + range.unshift(arr[i].value); + } + } + + output = expandRange(range, opts); + state.backtrack = true; + } + + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = '\\{'; + value = output = '\\}'; + state.output = out; + for (const t of toks) { + state.output += (t.output || t.value); + } + } + + push({ type: 'brace', value, output }); + decrement('braces'); + braces.pop(); + continue; + } + + /** + * Pipes + */ + + if (value === '|') { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + push({ type: 'text', value }); + continue; + } + + /** + * Commas + */ + + if (value === ',') { + let output = value; + + const brace = braces[braces.length - 1]; + if (brace && stack[stack.length - 1] === 'braces') { + brace.comma = true; + output = '|'; + } + + push({ type: 'comma', value, output }); + continue; + } + + /** + * Slashes + */ + + if (value === '/') { + // if the beginning of the glob is "./", advance the start + // to the current index, and don't add the "./" characters + // to the state. This greatly simplifies lookbehinds when + // checking for BOS characters like "!" and "." (not "./") + if (prev.type === 'dot' && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ''; + state.output = ''; + tokens.pop(); + prev = bos; // reset "prev" to the first token + continue; + } + + push({ type: 'slash', value, output: SLASH_LITERAL }); + continue; + } + + /** + * Dots + */ + + if (value === '.') { + if (state.braces > 0 && prev.type === 'dot') { + if (prev.value === '.') prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = 'dots'; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } + + if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { + push({ type: 'text', value, output: DOT_LITERAL }); + continue; + } + + push({ type: 'dot', value, output: DOT_LITERAL }); + continue; + } + + /** + * Question marks + */ + + if (value === '?') { + const isGroup = prev && prev.value === '('; + if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('qmark', value); + continue; + } + + if (prev && prev.type === 'paren') { + const next = peek(); + let output = value; + + if (next === '<' && !utils.supportsLookbehinds()) { + throw new Error('Node.js v10 or higher is required for regex lookbehinds'); + } + + if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { + output = `\\${value}`; + } + + push({ type: 'text', value, output }); + continue; + } + + if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { + push({ type: 'qmark', value, output: QMARK_NO_DOT }); + continue; + } + + push({ type: 'qmark', value, output: QMARK }); + continue; + } + + /** + * Exclamation + */ + + if (value === '!') { + if (opts.noextglob !== true && peek() === '(') { + if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { + extglobOpen('negate', value); + continue; + } + } + + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; + } + } + + /** + * Plus + */ + + if (value === '+') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('plus', value); + continue; + } + + if ((prev && prev.value === '(') || opts.regex === false) { + push({ type: 'plus', value, output: PLUS_LITERAL }); + continue; + } + + if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { + push({ type: 'plus', value }); + continue; + } + + push({ type: 'plus', value: PLUS_LITERAL }); + continue; + } + + /** + * Plain text + */ + + if (value === '@') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + push({ type: 'at', extglob: true, value, output: '' }); + continue; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Plain text + */ + + if (value !== '*') { + if (value === '$' || value === '^') { + value = `\\${value}`; + } + + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + if (match) { + value += match[0]; + state.index += match[0].length; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Stars + */ + + if (prev && (prev.type === 'globstar' || prev.star === true)) { + prev.type = 'star'; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } + + let rest = remaining(); + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen('star', value); + continue; + } + + if (prev.type === 'star') { + if (opts.noglobstar === true) { + consume(value); + continue; + } + + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === 'slash' || prior.type === 'bos'; + const afterStar = before && (before.type === 'star' || before.type === 'globstar'); + + if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { + push({ type: 'star', value, output: '' }); + continue; + } + + const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); + const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); + if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { + push({ type: 'star', value, output: '' }); + continue; + } + + // strip consecutive `/**/` + while (rest.slice(0, 3) === '/**') { + const after = input[state.index + 4]; + if (after && after !== '/') { + break; + } + rest = rest.slice(3); + consume('/**', 3); + } + + if (prior.type === 'bos' && eos()) { + prev.type = 'globstar'; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { + const end = rest[1] !== void 0 ? '|$' : ''; + + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; + + state.output += prior.output + prev.output; + state.globstar = true; + + consume(value + advance()); + + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + if (prior.type === 'bos' && rest[0] === '/') { + prev.type = 'globstar'; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + // remove single star from output + state.output = state.output.slice(0, -prev.output.length); + + // reset previous token to globstar + prev.type = 'globstar'; + prev.output = globstar(opts); + prev.value += value; + + // reset output with globstar + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + + const token = { type: 'star', value, output: star }; + + if (opts.bash === true) { + token.output = '.*?'; + if (prev.type === 'bos' || prev.type === 'slash') { + token.output = nodot + token.output; + } + push(token); + continue; + } + + if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { + token.output = value; + push(token); + continue; + } + + if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { + if (prev.type === 'dot') { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; + + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + + } else { + state.output += nodot; + prev.output += nodot; + } + + if (peek() !== '*') { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + + push(token); + } + + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); + state.output = utils.escapeLast(state.output, '['); + decrement('brackets'); + } + + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils.escapeLast(state.output, '('); + decrement('parens'); + } + + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils.escapeLast(state.output, '{'); + decrement('braces'); + } + + if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { + push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); + } + + // rebuild the output if we had to backtrack at any point + if (state.backtrack === true) { + state.output = ''; + + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + + if (token.suffix) { + state.output += token.suffix; + } + } + } + + return state; +}; + +/** + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. + */ + +parse.fastpaths = (input, options) => { + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + input = REPLACEMENTS[input] || input; + const win32 = utils.isWindows(options); + + // create constants based on platform, for windows or posix + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants.globChars(win32); + + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? '' : '?:'; + const state = { negated: false, prefix: '' }; + let star = opts.bash === true ? '.*?' : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + const globstar = opts => { + if (opts.noglobstar === true) return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const create = str => { + switch (str) { + case '*': + return `${nodot}${ONE_CHAR}${star}`; + + case '.*': + return `${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*.*': + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*/*': + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + + case '**': + return nodot + globstar(opts); + + case '**/*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; + + case '**/*.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '**/.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; + + default: { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; + + const source = create(match[1]); + if (!source) return; + + return source + DOT_LITERAL + match[2]; + } + } + }; + + const output = utils.removePrefix(input, state); + let source = create(output); + + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; + } + + return source; +}; + +module.exports = parse; diff --git a/node_modules/picomatch/lib/picomatch.js b/node_modules/picomatch/lib/picomatch.js new file mode 100644 index 0000000..782d809 --- /dev/null +++ b/node_modules/picomatch/lib/picomatch.js @@ -0,0 +1,342 @@ +'use strict'; + +const path = require('path'); +const scan = require('./scan'); +const parse = require('./parse'); +const utils = require('./utils'); +const constants = require('./constants'); +const isObject = val => val && typeof val === 'object' && !Array.isArray(val); + +/** + * Creates a matcher function from one or more glob patterns. The + * returned function takes a string to match as its first argument, + * and returns true if the string is a match. The returned matcher + * function also takes a boolean as the second argument that, when true, + * returns an object with additional information. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch(glob[, options]); + * + * const isMatch = picomatch('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @name picomatch + * @param {String|Array} `globs` One or more glob patterns. + * @param {Object=} `options` + * @return {Function=} Returns a matcher function. + * @api public + */ + +const picomatch = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch(input, options, returnState)); + const arrayMatcher = str => { + for (const isMatch of fns) { + const state = isMatch(str); + if (state) return state; + } + return false; + }; + return arrayMatcher; + } + + const isState = isObject(glob) && glob.tokens && glob.input; + + if (glob === '' || (typeof glob !== 'string' && !isState)) { + throw new TypeError('Expected pattern to be a non-empty string'); + } + + const opts = options || {}; + const posix = utils.isWindows(options); + const regex = isState + ? picomatch.compileRe(glob, options) + : picomatch.makeRe(glob, options, false, true); + + const state = regex.state; + delete regex.state; + + let isIgnored = () => false; + if (opts.ignore) { + const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; + isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); + } + + const matcher = (input, returnObject = false) => { + const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); + const result = { glob, state, regex, posix, input, output, match, isMatch }; + + if (typeof opts.onResult === 'function') { + opts.onResult(result); + } + + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } + + if (isIgnored(input)) { + if (typeof opts.onIgnore === 'function') { + opts.onIgnore(result); + } + result.isMatch = false; + return returnObject ? result : false; + } + + if (typeof opts.onMatch === 'function') { + opts.onMatch(result); + } + return returnObject ? result : true; + }; + + if (returnState) { + matcher.state = state; + } + + return matcher; +}; + +/** + * Test `input` with the given `regex`. This is used by the main + * `picomatch()` function to test the input string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.test(input, regex[, options]); + * + * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); + * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } + * ``` + * @param {String} `input` String to test. + * @param {RegExp} `regex` + * @return {Object} Returns an object with matching info. + * @api public + */ + +picomatch.test = (input, regex, options, { glob, posix } = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected input to be a string'); + } + + if (input === '') { + return { isMatch: false, output: '' }; + } + + const opts = options || {}; + const format = opts.format || (posix ? utils.toPosixSlashes : null); + let match = input === glob; + let output = (match && format) ? format(input) : input; + + if (match === false) { + output = format ? format(input) : input; + match = output === glob; + } + + if (match === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match = picomatch.matchBase(input, regex, options, posix); + } else { + match = regex.exec(output); + } + } + + return { isMatch: Boolean(match), match, output }; +}; + +/** + * Match the basename of a filepath. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.matchBase(input, glob[, options]); + * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true + * ``` + * @param {String} `input` String to test. + * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). + * @return {Boolean} + * @api public + */ + +picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { + const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); + return regex.test(path.basename(input)); +}; + +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.isMatch(string, patterns[, options]); + * + * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String|Array} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); + +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const picomatch = require('picomatch'); + * const result = picomatch.parse(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as a regex source string. + * @api public + */ + +picomatch.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options)); + return parse(pattern, { ...options, fastpaths: false }); +}; + +/** + * Scan a glob pattern to separate the pattern into segments. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.scan(input[, options]); + * + * const result = picomatch.scan('!./foo/*.js'); + * console.log(result); + * { prefix: '!./', + * input: '!./foo/*.js', + * start: 3, + * base: 'foo', + * glob: '*.js', + * isBrace: false, + * isBracket: false, + * isGlob: true, + * isExtglob: false, + * isGlobstar: false, + * negated: true } + * ``` + * @param {String} `input` Glob pattern to scan. + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + +picomatch.scan = (input, options) => scan(input, options); + +/** + * Compile a regular expression from the `state` object returned by the + * [parse()](#parse) method. + * + * @param {Object} `state` + * @param {Object} `options` + * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. + * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. + * @return {RegExp} + * @api public + */ + +picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return state.output; + } + + const opts = options || {}; + const prepend = opts.contains ? '' : '^'; + const append = opts.contains ? '' : '$'; + + let source = `${prepend}(?:${state.output})${append}`; + if (state && state.negated === true) { + source = `^(?!${source}).*$`; + } + + const regex = picomatch.toRegex(source, options); + if (returnState === true) { + regex.state = state; + } + + return regex; +}; + +/** + * Create a regular expression from a parsed glob pattern. + * + * ```js + * const picomatch = require('picomatch'); + * const state = picomatch.parse('*.js'); + * // picomatch.compileRe(state[, options]); + * + * console.log(picomatch.compileRe(state)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `state` The object returned from the `.parse` method. + * @param {Object} `options` + * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. + * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { + if (!input || typeof input !== 'string') { + throw new TypeError('Expected a non-empty string'); + } + + let parsed = { negated: false, fastpaths: true }; + + if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { + parsed.output = parse.fastpaths(input, options); + } + + if (!parsed.output) { + parsed = parse(input, options); + } + + return picomatch.compileRe(parsed, options, returnOutput, returnState); +}; + +/** + * Create a regular expression from the given regex source string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.toRegex(source[, options]); + * + * const { output } = picomatch.parse('*.js'); + * console.log(picomatch.toRegex(output)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `source` Regular expression source string. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +picomatch.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); + } catch (err) { + if (options && options.debug === true) throw err; + return /$^/; + } +}; + +/** + * Picomatch constants. + * @return {Object} + */ + +picomatch.constants = constants; + +/** + * Expose "picomatch" + */ + +module.exports = picomatch; diff --git a/node_modules/picomatch/lib/scan.js b/node_modules/picomatch/lib/scan.js new file mode 100644 index 0000000..e59cd7a --- /dev/null +++ b/node_modules/picomatch/lib/scan.js @@ -0,0 +1,391 @@ +'use strict'; + +const utils = require('./utils'); +const { + CHAR_ASTERISK, /* * */ + CHAR_AT, /* @ */ + CHAR_BACKWARD_SLASH, /* \ */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_EXCLAMATION_MARK, /* ! */ + CHAR_FORWARD_SLASH, /* / */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_PLUS, /* + */ + CHAR_QUESTION_MARK, /* ? */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_RIGHT_SQUARE_BRACKET /* ] */ +} = require('./constants'); + +const isPathSeparator = code => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +}; + +const depth = token => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; + } +}; + +/** + * Quickly scans a glob pattern and returns an object with a handful of + * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), + * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not + * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). + * + * ```js + * const pm = require('picomatch'); + * console.log(pm.scan('foo/bar/*.js')); + * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an object with tokens and regex source string. + * @api public + */ + +const scan = (input, options) => { + const opts = options || {}; + + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; + + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let negatedExtglob = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { value: '', depth: 0, isGlob: false }; + + const eos = () => index >= length; + const peek = () => str.charCodeAt(index + 1); + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; + + while (index < length) { + code = advance(); + let next; + + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + + if (code === CHAR_LEFT_CURLY_BRACE) { + braceEscaped = true; + } + continue; + } + + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { + braces++; + + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (code === CHAR_LEFT_CURLY_BRACE) { + braces++; + continue; + } + + if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (braceEscaped !== true && code === CHAR_COMMA) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_RIGHT_CURLY_BRACE) { + braces--; + + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = { value: '', depth: 0, isGlob: false }; + + if (finished === true) continue; + if (prev === CHAR_DOT && index === (start + 1)) { + start += 2; + continue; + } + + lastIndex = index + 1; + continue; + } + + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS + || code === CHAR_AT + || code === CHAR_ASTERISK + || code === CHAR_QUESTION_MARK + || code === CHAR_EXCLAMATION_MARK; + + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + if (code === CHAR_EXCLAMATION_MARK && index === start) { + negatedExtglob = true; + } + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + continue; + } + break; + } + } + + if (code === CHAR_ASTERISK) { + if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_LEFT_SQUARE_BRACKET) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + break; + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; + continue; + } + + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + finished = true; + break; + } + } + continue; + } + break; + } + + if (isGlob === true) { + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + } + + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } + + let base = str; + let prefix = ''; + let glob = ''; + + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } + + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ''; + glob = str; + } else { + base = str; + } + + if (base && base !== '' && base !== '/' && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); + } + } + + if (opts.unescape === true) { + if (glob) glob = utils.removeBackslashes(glob); + + if (base && backslashes === true) { + base = utils.removeBackslashes(base); + } + } + + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated, + negatedExtglob + }; + + if (opts.tokens === true) { + state.maxDepth = 0; + if (!isPathSeparator(code)) { + tokens.push(token); + } + state.tokens = tokens; + } + + if (opts.parts === true || opts.tokens === true) { + let prevIndex; + + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; + } + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; + } + if (idx !== 0 || value !== '') { + parts.push(value); + } + prevIndex = i; + } + + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); + + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; + } + } + + state.slashes = slashes; + state.parts = parts; + } + + return state; +}; + +module.exports = scan; diff --git a/node_modules/picomatch/lib/utils.js b/node_modules/picomatch/lib/utils.js new file mode 100644 index 0000000..c3ca766 --- /dev/null +++ b/node_modules/picomatch/lib/utils.js @@ -0,0 +1,64 @@ +'use strict'; + +const path = require('path'); +const win32 = process.platform === 'win32'; +const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL +} = require('./constants'); + +exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); +exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); +exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); +exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); +exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); + +exports.removeBackslashes = str => { + return str.replace(REGEX_REMOVE_BACKSLASH, match => { + return match === '\\' ? '' : match; + }); +}; + +exports.supportsLookbehinds = () => { + const segs = process.version.slice(1).split('.').map(Number); + if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { + return true; + } + return false; +}; + +exports.isWindows = options => { + if (options && typeof options.windows === 'boolean') { + return options.windows; + } + return win32 === true || path.sep === '\\'; +}; + +exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) return input; + if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; +}; + +exports.removePrefix = (input, state = {}) => { + let output = input; + if (output.startsWith('./')) { + output = output.slice(2); + state.prefix = './'; + } + return output; +}; + +exports.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? '' : '^'; + const append = options.contains ? '' : '$'; + + let output = `${prepend}(?:${input})${append}`; + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; + } + return output; +}; diff --git a/node_modules/picomatch/package.json b/node_modules/picomatch/package.json new file mode 100644 index 0000000..3db22d4 --- /dev/null +++ b/node_modules/picomatch/package.json @@ -0,0 +1,81 @@ +{ + "name": "picomatch", + "description": "Blazing fast and accurate glob matcher written in JavaScript, with no dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.", + "version": "2.3.1", + "homepage": "https://github.com/micromatch/picomatch", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "funding": "https://github.com/sponsors/jonschlinkert", + "repository": "micromatch/picomatch", + "bugs": { + "url": "https://github.com/micromatch/picomatch/issues" + }, + "license": "MIT", + "files": [ + "index.js", + "lib" + ], + "main": "index.js", + "engines": { + "node": ">=8.6" + }, + "scripts": { + "lint": "eslint --cache --cache-location node_modules/.cache/.eslintcache --report-unused-disable-directives --ignore-path .gitignore .", + "mocha": "mocha --reporter dot", + "test": "npm run lint && npm run mocha", + "test:ci": "npm run test:cover", + "test:cover": "nyc npm run mocha" + }, + "devDependencies": { + "eslint": "^6.8.0", + "fill-range": "^7.0.1", + "gulp-format-md": "^2.0.0", + "mocha": "^6.2.2", + "nyc": "^15.0.0", + "time-require": "github:jonschlinkert/time-require" + }, + "keywords": [ + "glob", + "match", + "picomatch" + ], + "nyc": { + "reporter": [ + "html", + "lcov", + "text-summary" + ] + }, + "verb": { + "toc": { + "render": true, + "method": "preWrite", + "maxdepth": 3 + }, + "layout": "empty", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + }, + "related": { + "list": [ + "braces", + "micromatch" + ] + }, + "reflinks": [ + "braces", + "expand-brackets", + "extglob", + "fill-range", + "micromatch", + "minimatch", + "nanomatch", + "picomatch" + ] + } +} diff --git a/node_modules/pify/index.js b/node_modules/pify/index.js new file mode 100644 index 0000000..7c720eb --- /dev/null +++ b/node_modules/pify/index.js @@ -0,0 +1,68 @@ +'use strict'; + +var processFn = function (fn, P, opts) { + return function () { + var that = this; + var args = new Array(arguments.length); + + for (var i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + return new P(function (resolve, reject) { + args.push(function (err, result) { + if (err) { + reject(err); + } else if (opts.multiArgs) { + var results = new Array(arguments.length - 1); + + for (var i = 1; i < arguments.length; i++) { + results[i - 1] = arguments[i]; + } + + resolve(results); + } else { + resolve(result); + } + }); + + fn.apply(that, args); + }); + }; +}; + +var pify = module.exports = function (obj, P, opts) { + if (typeof P !== 'function') { + opts = P; + P = Promise; + } + + opts = opts || {}; + opts.exclude = opts.exclude || [/.+Sync$/]; + + var filter = function (key) { + var match = function (pattern) { + return typeof pattern === 'string' ? key === pattern : pattern.test(key); + }; + + return opts.include ? opts.include.some(match) : !opts.exclude.some(match); + }; + + var ret = typeof obj === 'function' ? function () { + if (opts.excludeMain) { + return obj.apply(this, arguments); + } + + return processFn(obj, P, opts).apply(this, arguments); + } : {}; + + return Object.keys(obj).reduce(function (ret, key) { + var x = obj[key]; + + ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x; + + return ret; + }, ret); +}; + +pify.all = pify; diff --git a/node_modules/pify/license b/node_modules/pify/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/node_modules/pify/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/pify/package.json b/node_modules/pify/package.json new file mode 100644 index 0000000..311d198 --- /dev/null +++ b/node_modules/pify/package.json @@ -0,0 +1,48 @@ +{ + "name": "pify", + "version": "2.3.0", + "description": "Promisify a callback-style function", + "license": "MIT", + "repository": "sindresorhus/pify", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava && npm run optimization-test", + "optimization-test": "node --allow-natives-syntax optimization-test.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "promise", + "promises", + "promisify", + "denodify", + "denodeify", + "callback", + "cb", + "node", + "then", + "thenify", + "convert", + "transform", + "wrap", + "wrapper", + "bind", + "to", + "async", + "es2015" + ], + "devDependencies": { + "ava": "*", + "pinkie-promise": "^1.0.0", + "v8-natives": "0.0.2", + "xo": "*" + } +} diff --git a/node_modules/pify/readme.md b/node_modules/pify/readme.md new file mode 100644 index 0000000..c79ca8b --- /dev/null +++ b/node_modules/pify/readme.md @@ -0,0 +1,119 @@ +# pify [![Build Status](https://travis-ci.org/sindresorhus/pify.svg?branch=master)](https://travis-ci.org/sindresorhus/pify) + +> Promisify a callback-style function + + +## Install + +``` +$ npm install --save pify +``` + + +## Usage + +```js +const fs = require('fs'); +const pify = require('pify'); + +// promisify a single function + +pify(fs.readFile)('package.json', 'utf8').then(data => { + console.log(JSON.parse(data).name); + //=> 'pify' +}); + +// or promisify all methods in a module + +pify(fs).readFile('package.json', 'utf8').then(data => { + console.log(JSON.parse(data).name); + //=> 'pify' +}); +``` + + +## API + +### pify(input, [promiseModule], [options]) + +Returns a promise wrapped version of the supplied function or module. + +#### input + +Type: `function`, `object` + +Callback-style function or module whose methods you want to promisify. + +#### promiseModule + +Type: `function` + +Custom promise module to use instead of the native one. + +Check out [`pinkie-promise`](https://github.com/floatdrop/pinkie-promise) if you need a tiny promise polyfill. + +#### options + +##### multiArgs + +Type: `boolean` +Default: `false` + +By default, the promisified function will only return the second argument from the callback, which works fine for most APIs. This option can be useful for modules like `request` that return multiple arguments. Turning this on will make it return an array of all arguments from the callback, excluding the error argument, instead of just the second argument. + +```js +const request = require('request'); +const pify = require('pify'); + +pify(request, {multiArgs: true})('https://sindresorhus.com').then(result => { + const [httpResponse, body] = result; +}); +``` + +##### include + +Type: `array` of (`string`|`regex`) + +Methods in a module to promisify. Remaining methods will be left untouched. + +##### exclude + +Type: `array` of (`string`|`regex`) +Default: `[/.+Sync$/]` + +Methods in a module **not** to promisify. Methods with names ending with `'Sync'` are excluded by default. + +##### excludeMain + +Type: `boolean` +Default: `false` + +By default, if given module is a function itself, this function will be promisified. Turn this option on if you want to promisify only methods of the module. + +```js +const pify = require('pify'); + +function fn() { + return true; +} + +fn.method = (data, callback) => { + setImmediate(() => { + callback(data, null); + }); +}; + +// promisify methods but not fn() +const promiseFn = pify(fn, {excludeMain: true}); + +if (promiseFn()) { + promiseFn.method('hi').then(data => { + console.log(data); + }); +} +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/node_modules/pirates/LICENSE b/node_modules/pirates/LICENSE new file mode 100644 index 0000000..acc7a0e --- /dev/null +++ b/node_modules/pirates/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016-2018 Ari Porad + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/pirates/README.md b/node_modules/pirates/README.md new file mode 100644 index 0000000..f36bc5a --- /dev/null +++ b/node_modules/pirates/README.md @@ -0,0 +1,73 @@ +# Pirates [![Coverage][codecov-badge]][codecov-link] + +### Properly hijack require + +This library allows to add custom require hooks, which do not interfere with other require hooks. + +This library only works with commonJS. + +[codecov-badge]: https://img.shields.io/codecov/c/github/danez/pirates/master.svg?style=flat "codecov" +[codecov-link]: https://codecov.io/gh/danez/pirates "codecov" + +## Why? + +Two reasons: +1. Babel and istanbul were breaking each other. +2. Everyone seemed to re-invent the wheel on this, and everyone wanted a solution that was DRY, simple, easy to use, +and made everything Just Work™, while allowing multiple require hooks, in a fashion similar to calling `super`. + +For some context, see [the Babel issue thread][] which started this all, then [the nyc issue thread][], where +discussion was moved (as we began to discuss just using the code nyc had developed), and finally to [#1][issue-1] +where discussion was finally moved. + +[the Babel issue thread]: https://github.com/babel/babel/pull/3062 "Babel Issue Thread" +[the nyc issue thread]: https://github.com/bcoe/nyc/issues/70 "NYC Issue Thread" +[issue-1]: https://github.com/danez/pirates/issues/1 "Issue #1" + +## Installation + + npm install --save pirates + +## Usage + +Using pirates is really easy: +```javascript +// my-module/register.js +const addHook = require('pirates').addHook; +// Or if you use ES modules +// import { addHook } from 'pirates'; + +function matcher(filename) { + // Here, you can inspect the filename to determine if it should be hooked or + // not. Just return a truthy/falsey. Files in node_modules are automatically ignored, + // unless otherwise specified in options (see below). + + // TODO: Implement your logic here + return true; +} + +const revert = addHook( + (code, filename) => code.replace('@@foo', 'console.log(\'foo\');'), + { exts: ['.js'], matcher } +); + +// And later, if you want to un-hook require, you can just do: +revert(); +``` + +## API + +### pirates.addHook(hook, [opts={ [matcher: true], [exts: ['.js']], [ignoreNodeModules: true] }]); +Add a require hook. `hook` must be a function that takes `(code, filename)`, and returns the modified code. `opts` is +an optional options object. Available options are: `matcher`, which is a function that accepts a filename, and +returns a truthy value if the file should be hooked (defaults to a function that always returns true), falsey if +otherwise; `exts`, which is an array of extensions to hook, they should begin with `.` (defaults to `['.js']`); +`ignoreNodeModules`, if true, any file in a `node_modules` folder wont be hooked (the matcher also wont be called), +if false, then the matcher will be called for any files in `node_modules` (defaults to true). + + +## Projects that use Pirates + +See the [wiki page](https://github.com/danez/pirates/wiki/Projects-using-Pirates). If you add Pirates to your project, +(And you should! It works best if everyone uses it. Then we can have a happy world full of happy require hooks!), please +add yourself to the wiki. diff --git a/node_modules/pirates/index.d.ts b/node_modules/pirates/index.d.ts new file mode 100644 index 0000000..b2d8ce6 --- /dev/null +++ b/node_modules/pirates/index.d.ts @@ -0,0 +1,82 @@ +/* (c) 2015 Ari Porad (@ariporad) . License: ariporad.mit-license.org */ + +/** + * The hook. Accepts the code of the module and the filename. + */ +declare type Hook = (code: string, filename: string) => string; + +/** + * A matcher function, will be called with path to a file. + * + * Should return truthy if the file should be hooked, falsy otherwise. + */ +declare type Matcher = (path: string) => boolean; + +/** + * Reverts the hook when called. + */ +declare type RevertFunction = () => void; +interface Options { + /** + * The extensions to hook. Should start with '.' (ex. ['.js']). + * + * Takes precedence over `exts`, `extension` and `ext`. + * + * @alias exts + * @alias extension + * @alias ext + * @default ['.js'] + */ + extensions?: ReadonlyArray | string; + + /** + * The extensions to hook. Should start with '.' (ex. ['.js']). + * + * Takes precedence over `extension` and `ext`. + * + * @alias extension + * @alias ext + * @default ['.js'] + */ + exts?: ReadonlyArray | string; + + /** + * The extensions to hook. Should start with '.' (ex. ['.js']). + * + * Takes precedence over `ext`. + * + * @alias ext + * @default ['.js'] + */ + extension?: ReadonlyArray | string; + + /** + * The extensions to hook. Should start with '.' (ex. ['.js']). + * + * @default ['.js'] + */ + ext?: ReadonlyArray | string; + + /** + * A matcher function, will be called with path to a file. + * + * Should return truthy if the file should be hooked, falsy otherwise. + */ + matcher?: Matcher | null; + + /** + * Auto-ignore node_modules. Independent of any matcher. + * + * @default true + */ + ignoreNodeModules?: boolean; +} + +/** + * Add a require hook. + * + * @param hook The hook. Accepts the code of the module and the filename. Required. + * @returns The `revert` function. Reverts the hook when called. + */ +export declare function addHook(hook: Hook, opts?: Options): RevertFunction; +export {}; diff --git a/node_modules/pirates/lib/index.js b/node_modules/pirates/lib/index.js new file mode 100644 index 0000000..5b76163 --- /dev/null +++ b/node_modules/pirates/lib/index.js @@ -0,0 +1,155 @@ +'use strict'; + +/* (c) 2015 Ari Porad (@ariporad) . License: ariporad.mit-license.org */ +const BuiltinModule = require('module'); +const path = require('path'); + +const nodeModulesRegex = /^(?:.*[\\/])?node_modules(?:[\\/].*)?$/; +// Guard against poorly-mocked module constructors. +const Module = + module.constructor.length > 1 ? module.constructor : BuiltinModule; + +const HOOK_RETURNED_NOTHING_ERROR_MESSAGE = + '[Pirates] A hook returned a non-string, or nothing at all! This is a' + + ' violation of intergalactic law!\n' + + '--------------------\n' + + 'If you have no idea what this means or what Pirates is, let me explain: ' + + 'Pirates is a module that makes it easy to implement require hooks. One of' + + " the require hooks you're using uses it. One of these require hooks" + + " didn't return anything from it's handler, so we don't know what to" + + ' do. You might want to debug this.'; + +/** + * @param {string} filename The filename to check. + * @param {string[]} exts The extensions to hook. Should start with '.' (ex. ['.js']). + * @param {Matcher|null} matcher A matcher function, will be called with path to a file. Should return truthy if the file should be hooked, falsy otherwise. + * @param {boolean} ignoreNodeModules Auto-ignore node_modules. Independent of any matcher. + */ +function shouldCompile(filename, exts, matcher, ignoreNodeModules) { + if (typeof filename !== 'string') { + return false; + } + if (exts.indexOf(path.extname(filename)) === -1) { + return false; + } + + const resolvedFilename = path.resolve(filename); + + if (ignoreNodeModules && nodeModulesRegex.test(resolvedFilename)) { + return false; + } + if (matcher && typeof matcher === 'function') { + return !!matcher(resolvedFilename); + } + + return true; +} + +/** + * @callback Hook The hook. Accepts the code of the module and the filename. + * @param {string} code + * @param {string} filename + * @returns {string} + */ +/** + * @callback Matcher A matcher function, will be called with path to a file. + * + * Should return truthy if the file should be hooked, falsy otherwise. + * @param {string} path + * @returns {boolean} + */ +/** + * @callback RevertFunction Reverts the hook when called. + * @returns {void} + */ +/** + * @typedef {object} Options + * @property {Matcher|null} [matcher=null] A matcher function, will be called with path to a file. + * + * Should return truthy if the file should be hooked, falsy otherwise. + * + * @property {string[]} [extensions=['.js']] The extensions to hook. Should start with '.' (ex. ['.js']). + * @property {string[]} [exts=['.js']] The extensions to hook. Should start with '.' (ex. ['.js']). + * + * @property {string[]} [extension=['.js']] The extensions to hook. Should start with '.' (ex. ['.js']). + * @property {string[]} [ext=['.js']] The extensions to hook. Should start with '.' (ex. ['.js']). + * + * @property {boolean} [ignoreNodeModules=true] Auto-ignore node_modules. Independent of any matcher. + */ + +/** + * Add a require hook. + * + * @param {Hook} hook The hook. Accepts the code of the module and the filename. Required. + * @param {Options} [opts] Options + * @returns {RevertFunction} The `revert` function. Reverts the hook when called. + */ +function addHook(hook, opts = {}) { + let reverted = false; + const loaders = []; + const oldLoaders = []; + let exts; + + // We need to do this to fix #15. Basically, if you use a non-standard extension (ie. .jsx), then + // We modify the .js loader, then use the modified .js loader for as the base for .jsx. + // This prevents that. + const originalJSLoader = Module._extensions['.js']; + + const matcher = opts.matcher || null; + const ignoreNodeModules = opts.ignoreNodeModules !== false; + exts = opts.extensions || opts.exts || opts.extension || opts.ext || ['.js']; + if (!Array.isArray(exts)) { + exts = [exts]; + } + + exts.forEach((ext) => { + if (typeof ext !== 'string') { + throw new TypeError(`Invalid Extension: ${ext}`); + } + const oldLoader = Module._extensions[ext] || originalJSLoader; + oldLoaders[ext] = Module._extensions[ext]; + + loaders[ext] = Module._extensions[ext] = function newLoader(mod, filename) { + let compile; + if (!reverted) { + if (shouldCompile(filename, exts, matcher, ignoreNodeModules)) { + compile = mod._compile; + mod._compile = function _compile(code) { + // reset the compile immediately as otherwise we end up having the + // compile function being changed even though this loader might be reverted + // Not reverting it here leads to long useless compile chains when doing + // addHook -> revert -> addHook -> revert -> ... + // The compile function is also anyway created new when the loader is called a second time. + mod._compile = compile; + const newCode = hook(code, filename); + if (typeof newCode !== 'string') { + throw new Error(HOOK_RETURNED_NOTHING_ERROR_MESSAGE); + } + + return mod._compile(newCode, filename); + }; + } + } + + oldLoader(mod, filename); + }; + }); + return function revert() { + if (reverted) return; + reverted = true; + + exts.forEach((ext) => { + // if the current loader for the extension is our loader then unregister it and set the oldLoader again + // if not we cannot do anything as we cannot remove a loader from within the loader-chain + if (Module._extensions[ext] === loaders[ext]) { + if (!oldLoaders[ext]) { + delete Module._extensions[ext]; + } else { + Module._extensions[ext] = oldLoaders[ext]; + } + } + }); + }; +} + +exports.addHook = addHook; diff --git a/node_modules/pirates/package.json b/node_modules/pirates/package.json new file mode 100644 index 0000000..131277c --- /dev/null +++ b/node_modules/pirates/package.json @@ -0,0 +1,43 @@ +{ + "name": "pirates", + "description": "Properly hijack require, i.e., properly define require hooks and customizations", + "main": "lib/index.js", + "types": "index.d.ts", + "scripts": { + "test": "ava" + }, + "files": [ + "lib", + "index.d.ts" + ], + "repository": { + "type": "git", + "url": "https://github.com/danez/pirates.git" + }, + "engines": { + "node": ">= 6" + }, + "author": { + "name": "Ari Porad", + "email": "ari@ariporad.com", + "url": "http://ariporad.com" + }, + "devDependencies": { + "ava": "1.4.1", + "decache": "4.6.2" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/danez/pirates/issues" + }, + "homepage": "https://github.com/danez/pirates#readme", + "ava": { + "files": [ + "test/*.js" + ], + "sources": [ + "lib/**/*.js" + ] + }, + "version": "4.0.7" +} diff --git a/node_modules/postcss-import/LICENSE b/node_modules/postcss-import/LICENSE new file mode 100644 index 0000000..13983fb --- /dev/null +++ b/node_modules/postcss-import/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Maxime Thirouin, Jason Campbell & Kevin Mårtensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/postcss-import/README.md b/node_modules/postcss-import/README.md new file mode 100644 index 0000000..ac0148e --- /dev/null +++ b/node_modules/postcss-import/README.md @@ -0,0 +1,244 @@ +# postcss-import + +[![Build](https://img.shields.io/travis/postcss/postcss-import/master)](https://travis-ci.org/postcss/postcss-import) +[![Version](https://img.shields.io/npm/v/postcss-import)](https://github.com/postcss/postcss-import/blob/master/CHANGELOG.md) +[![postcss compatibility](https://img.shields.io/npm/dependency-version/postcss-import/peer/postcss)](https://postcss.org/) + +> [PostCSS](https://github.com/postcss/postcss) plugin to transform `@import` +rules by inlining content. + +This plugin can consume local files, node modules or web_modules. +To resolve path of an `@import` rule, it can look into root directory +(by default `process.cwd()`), `web_modules`, `node_modules` +or local modules. +_When importing a module, it will look for `index.css` or file referenced in +`package.json` in the `style` or `main` fields._ +You can also provide manually multiples paths where to look at. + +**Notes:** + +- **This plugin should probably be used as the first plugin of your list. +This way, other plugins will work on the AST as if there were only a single file +to process, and will probably work as you can expect**. +- This plugin works great with +[postcss-url](https://github.com/postcss/postcss-url) plugin, +which will allow you to adjust assets `url()` (or even inline them) after +inlining imported files. +- In order to optimize output, **this plugin will only import a file once** on +a given scope (root, media query...). +Tests are made from the path & the content of imported files (using a hash +table). +If this behavior is not what you want, look at `skipDuplicates` option +- If you are looking for **Glob Imports**, you can use [postcss-import-ext-glob](https://github.com/dimitrinicolas/postcss-import-ext-glob) to extend postcss-import. +- Imports which are not modified (by `options.filter` or because they are remote + imports) are moved to the top of the output. +- **This plugin attempts to follow the CSS `@import` spec**; `@import` + statements must precede all other statements (besides `@charset`). + +## Installation + +```console +$ npm install -D postcss-import +``` + +## Usage + +Unless your stylesheet is in the same place where you run postcss +(`process.cwd()`), you will need to use `from` option to make relative imports +work. + +```js +// dependencies +const fs = require("fs") +const postcss = require("postcss") +const atImport = require("postcss-import") + +// css to be processed +const css = fs.readFileSync("css/input.css", "utf8") + +// process css +postcss() + .use(atImport()) + .process(css, { + // `from` option is needed here + from: "css/input.css" + }) + .then((result) => { + const output = result.css + + console.log(output) + }) +``` + +`css/input.css`: + +```css +/* can consume `node_modules`, `web_modules` or local modules */ +@import "cssrecipes-defaults"; /* == @import "../node_modules/cssrecipes-defaults/index.css"; */ +@import "normalize.css"; /* == @import "../node_modules/normalize.css/normalize.css"; */ + +@import "foo.css"; /* relative to css/ according to `from` option above */ + +@import "bar.css" (min-width: 25em); + +@import 'baz.css' layer(baz-layer); + +body { + background: black; +} +``` + +will give you: + +```css +/* ... content of ../node_modules/cssrecipes-defaults/index.css */ +/* ... content of ../node_modules/normalize.css/normalize.css */ + +/* ... content of css/foo.css */ + +@media (min-width: 25em) { +/* ... content of css/bar.css */ +} + +@layer baz-layer { +/* ... content of css/baz.css */ +} + +body { + background: black; +} +``` + +Checkout the [tests](test) for more examples. + +### Options + +### `filter` +Type: `Function` +Default: `() => true` + +Only transform imports for which the test function returns `true`. Imports for +which the test function returns `false` will be left as is. The function gets +the path to import as an argument and should return a boolean. + +#### `root` + +Type: `String` +Default: `process.cwd()` or _dirname of +[the postcss `from`](https://github.com/postcss/postcss#node-source)_ + +Define the root where to resolve path (eg: place where `node_modules` are). +Should not be used that much. +_Note: nested `@import` will additionally benefit of the relative dirname of +imported files._ + +#### `path` + +Type: `String|Array` +Default: `[]` + +A string or an array of paths in where to look for files. + +#### `plugins` + +Type: `Array` +Default: `undefined` + +An array of plugins to be applied on each imported files. + +#### `resolve` + +Type: `Function` +Default: `null` + +You can provide a custom path resolver with this option. This function gets +`(id, basedir, importOptions)` arguments and should return a path, an array of +paths or a promise resolving to the path(s). If you do not return an absolute +path, your path will be resolved to an absolute path using the default +resolver. +You can use [resolve](https://github.com/substack/node-resolve) for this. + +#### `load` + +Type: `Function` +Default: null + +You can overwrite the default loading way by setting this option. +This function gets `(filename, importOptions)` arguments and returns content or +promised content. + +#### `skipDuplicates` + +Type: `Boolean` +Default: `true` + +By default, similar files (based on the same content) are being skipped. +It's to optimize output and skip similar files like `normalize.css` for example. +If this behavior is not what you want, just set this option to `false` to +disable it. + +#### `addModulesDirectories` + +Type: `Array` +Default: `[]` + +An array of folder names to add to [Node's resolver](https://github.com/substack/node-resolve). +Values will be appended to the default resolve directories: +`["node_modules", "web_modules"]`. + +This option is only for adding additional directories to default resolver. If +you provide your own resolver via the `resolve` configuration option above, then +this value will be ignored. + +#### `nameLayer` + +Type: `Function` +Default: `null` + +You can provide a custom naming function for anonymous layers (`@import 'baz.css' layer;`). +This function gets `(index, rootFilename)` arguments and should return a unique string. + +This option only influences imports without a layer name. +Without this option the plugin will warn on anonymous layers. + +#### Example with some options + +```js +const postcss = require("postcss") +const atImport = require("postcss-import") + +postcss() + .use(atImport({ + path: ["src/css"], + })) + .process(cssString) + .then((result) => { + const { css } = result + }) +``` + +## `dependency` Message Support + +`postcss-import` adds a message to `result.messages` for each `@import`. Messages are in the following format: + +``` +{ + type: 'dependency', + file: absoluteFilePath, + parent: fileContainingTheImport +} +``` + +This is mainly for use by postcss runners that implement file watching. + +--- + +## CONTRIBUTING + +* ⇄ Pull requests and ★ Stars are always welcome. +* For bugs and feature requests, please create an issue. +* Pull requests must be accompanied by passing automated tests (`$ npm test`). + +## [Changelog](CHANGELOG.md) + +## [License](LICENSE) diff --git a/node_modules/postcss-import/index.js b/node_modules/postcss-import/index.js new file mode 100644 index 0000000..d324a7e --- /dev/null +++ b/node_modules/postcss-import/index.js @@ -0,0 +1,420 @@ +"use strict" +// builtin tooling +const path = require("path") + +// internal tooling +const joinMedia = require("./lib/join-media") +const joinLayer = require("./lib/join-layer") +const resolveId = require("./lib/resolve-id") +const loadContent = require("./lib/load-content") +const processContent = require("./lib/process-content") +const parseStatements = require("./lib/parse-statements") +const assignLayerNames = require("./lib/assign-layer-names") +const dataURL = require("./lib/data-url") + +function AtImport(options) { + options = { + root: process.cwd(), + path: [], + skipDuplicates: true, + resolve: resolveId, + load: loadContent, + plugins: [], + addModulesDirectories: [], + nameLayer: null, + ...options, + } + + options.root = path.resolve(options.root) + + // convert string to an array of a single element + if (typeof options.path === "string") options.path = [options.path] + + if (!Array.isArray(options.path)) options.path = [] + + options.path = options.path.map(p => path.resolve(options.root, p)) + + return { + postcssPlugin: "postcss-import", + Once(styles, { result, atRule, postcss }) { + const state = { + importedFiles: {}, + hashFiles: {}, + rootFilename: null, + anonymousLayerCounter: 0, + } + + if (styles.source?.input?.file) { + state.rootFilename = styles.source.input.file + state.importedFiles[styles.source.input.file] = {} + } + + if (options.plugins && !Array.isArray(options.plugins)) { + throw new Error("plugins option must be an array") + } + + if (options.nameLayer && typeof options.nameLayer !== "function") { + throw new Error("nameLayer option must be a function") + } + + return parseStyles(result, styles, options, state, [], []).then( + bundle => { + applyRaws(bundle) + applyMedia(bundle) + applyStyles(bundle, styles) + } + ) + + function applyRaws(bundle) { + bundle.forEach((stmt, index) => { + if (index === 0) return + + if (stmt.parent) { + const { before } = stmt.parent.node.raws + if (stmt.type === "nodes") stmt.nodes[0].raws.before = before + else stmt.node.raws.before = before + } else if (stmt.type === "nodes") { + stmt.nodes[0].raws.before = stmt.nodes[0].raws.before || "\n" + } + }) + } + + function applyMedia(bundle) { + bundle.forEach(stmt => { + if ( + (!stmt.media.length && !stmt.layer.length) || + stmt.type === "charset" + ) { + return + } + + if (stmt.layer.length > 1) { + assignLayerNames(stmt.layer, stmt.node, state, options) + } + + if (stmt.type === "import") { + const parts = [stmt.fullUri] + + const media = stmt.media.join(", ") + + if (stmt.layer.length) { + const layerName = stmt.layer.join(".") + + let layerParams = "layer" + if (layerName) { + layerParams = `layer(${layerName})` + } + + parts.push(layerParams) + } + + if (media) { + parts.push(media) + } + + stmt.node.params = parts.join(" ") + } else if (stmt.type === "media") { + if (stmt.layer.length) { + const layerNode = atRule({ + name: "layer", + params: stmt.layer.join("."), + source: stmt.node.source, + }) + + if (stmt.parentMedia?.length) { + const mediaNode = atRule({ + name: "media", + params: stmt.parentMedia.join(", "), + source: stmt.node.source, + }) + + mediaNode.append(layerNode) + layerNode.append(stmt.node) + stmt.node = mediaNode + } else { + layerNode.append(stmt.node) + stmt.node = layerNode + } + } else { + stmt.node.params = stmt.media.join(", ") + } + } else { + const { nodes } = stmt + const { parent } = nodes[0] + + let outerAtRule + let innerAtRule + if (stmt.media.length && stmt.layer.length) { + const mediaNode = atRule({ + name: "media", + params: stmt.media.join(", "), + source: parent.source, + }) + + const layerNode = atRule({ + name: "layer", + params: stmt.layer.join("."), + source: parent.source, + }) + + mediaNode.append(layerNode) + innerAtRule = layerNode + outerAtRule = mediaNode + } else if (stmt.media.length) { + const mediaNode = atRule({ + name: "media", + params: stmt.media.join(", "), + source: parent.source, + }) + + innerAtRule = mediaNode + outerAtRule = mediaNode + } else if (stmt.layer.length) { + const layerNode = atRule({ + name: "layer", + params: stmt.layer.join("."), + source: parent.source, + }) + + innerAtRule = layerNode + outerAtRule = layerNode + } + + parent.insertBefore(nodes[0], outerAtRule) + + // remove nodes + nodes.forEach(node => { + node.parent = undefined + }) + + // better output + nodes[0].raws.before = nodes[0].raws.before || "\n" + + // wrap new rules with media query and/or layer at rule + innerAtRule.append(nodes) + + stmt.type = "media" + stmt.node = outerAtRule + delete stmt.nodes + } + }) + } + + function applyStyles(bundle, styles) { + styles.nodes = [] + + // Strip additional statements. + bundle.forEach(stmt => { + if (["charset", "import", "media"].includes(stmt.type)) { + stmt.node.parent = undefined + styles.append(stmt.node) + } else if (stmt.type === "nodes") { + stmt.nodes.forEach(node => { + node.parent = undefined + styles.append(node) + }) + } + }) + } + + function parseStyles(result, styles, options, state, media, layer) { + const statements = parseStatements(result, styles) + + return Promise.resolve(statements) + .then(stmts => { + // process each statement in series + return stmts.reduce((promise, stmt) => { + return promise.then(() => { + stmt.media = joinMedia(media, stmt.media || []) + stmt.parentMedia = media + stmt.layer = joinLayer(layer, stmt.layer || []) + + // skip protocol base uri (protocol://url) or protocol-relative + if ( + stmt.type !== "import" || + /^(?:[a-z]+:)?\/\//i.test(stmt.uri) + ) { + return + } + + if (options.filter && !options.filter(stmt.uri)) { + // rejected by filter + return + } + + return resolveImportId(result, stmt, options, state) + }) + }, Promise.resolve()) + }) + .then(() => { + let charset + const imports = [] + const bundle = [] + + function handleCharset(stmt) { + if (!charset) charset = stmt + // charsets aren't case-sensitive, so convert to lower case to compare + else if ( + stmt.node.params.toLowerCase() !== + charset.node.params.toLowerCase() + ) { + throw new Error( + `Incompatable @charset statements: + ${stmt.node.params} specified in ${stmt.node.source.input.file} + ${charset.node.params} specified in ${charset.node.source.input.file}` + ) + } + } + + // squash statements and their children + statements.forEach(stmt => { + if (stmt.type === "charset") handleCharset(stmt) + else if (stmt.type === "import") { + if (stmt.children) { + stmt.children.forEach((child, index) => { + if (child.type === "import") imports.push(child) + else if (child.type === "charset") handleCharset(child) + else bundle.push(child) + // For better output + if (index === 0) child.parent = stmt + }) + } else imports.push(stmt) + } else if (stmt.type === "media" || stmt.type === "nodes") { + bundle.push(stmt) + } + }) + + return charset + ? [charset, ...imports.concat(bundle)] + : imports.concat(bundle) + }) + } + + function resolveImportId(result, stmt, options, state) { + if (dataURL.isValid(stmt.uri)) { + return loadImportContent(result, stmt, stmt.uri, options, state).then( + result => { + stmt.children = result + } + ) + } + + const atRule = stmt.node + let sourceFile + if (atRule.source?.input?.file) { + sourceFile = atRule.source.input.file + } + const base = sourceFile + ? path.dirname(atRule.source.input.file) + : options.root + + return Promise.resolve(options.resolve(stmt.uri, base, options)) + .then(paths => { + if (!Array.isArray(paths)) paths = [paths] + // Ensure that each path is absolute: + return Promise.all( + paths.map(file => { + return !path.isAbsolute(file) + ? resolveId(file, base, options) + : file + }) + ) + }) + .then(resolved => { + // Add dependency messages: + resolved.forEach(file => { + result.messages.push({ + type: "dependency", + plugin: "postcss-import", + file, + parent: sourceFile, + }) + }) + + return Promise.all( + resolved.map(file => { + return loadImportContent(result, stmt, file, options, state) + }) + ) + }) + .then(result => { + // Merge loaded statements + stmt.children = result.reduce((result, statements) => { + return statements ? result.concat(statements) : result + }, []) + }) + } + + function loadImportContent(result, stmt, filename, options, state) { + const atRule = stmt.node + const { media, layer } = stmt + + assignLayerNames(layer, atRule, state, options) + + if (options.skipDuplicates) { + // skip files already imported at the same scope + if (state.importedFiles[filename]?.[media]?.[layer]) { + return + } + + // save imported files to skip them next time + if (!state.importedFiles[filename]) { + state.importedFiles[filename] = {} + } + if (!state.importedFiles[filename][media]) { + state.importedFiles[filename][media] = {} + } + state.importedFiles[filename][media][layer] = true + } + + return Promise.resolve(options.load(filename, options)).then( + content => { + if (content.trim() === "") { + result.warn(`${filename} is empty`, { node: atRule }) + return + } + + // skip previous imported files not containing @import rules + if (state.hashFiles[content]?.[media]?.[layer]) { + return + } + + return processContent( + result, + content, + filename, + options, + postcss + ).then(importedResult => { + const styles = importedResult.root + result.messages = result.messages.concat(importedResult.messages) + + if (options.skipDuplicates) { + const hasImport = styles.some(child => { + return child.type === "atrule" && child.name === "import" + }) + if (!hasImport) { + // save hash files to skip them next time + if (!state.hashFiles[content]) { + state.hashFiles[content] = {} + } + if (!state.hashFiles[content][media]) { + state.hashFiles[content][media] = {} + } + state.hashFiles[content][media][layer] = true + } + } + + // recursion: import @import from imported file + return parseStyles(result, styles, options, state, media, layer) + }) + } + ) + } + }, + } +} + +AtImport.postcss = true + +module.exports = AtImport diff --git a/node_modules/postcss-import/lib/assign-layer-names.js b/node_modules/postcss-import/lib/assign-layer-names.js new file mode 100644 index 0000000..18cfcc7 --- /dev/null +++ b/node_modules/postcss-import/lib/assign-layer-names.js @@ -0,0 +1,17 @@ +"use strict" + +module.exports = function (layer, node, state, options) { + layer.forEach((layerPart, i) => { + if (layerPart.trim() === "") { + if (options.nameLayer) { + layer[i] = options + .nameLayer(state.anonymousLayerCounter++, state.rootFilename) + .toString() + } else { + throw node.error( + `When using anonymous layers in @import you must also set the "nameLayer" plugin option` + ) + } + } + }) +} diff --git a/node_modules/postcss-import/lib/data-url.js b/node_modules/postcss-import/lib/data-url.js new file mode 100644 index 0000000..a59c5fb --- /dev/null +++ b/node_modules/postcss-import/lib/data-url.js @@ -0,0 +1,17 @@ +"use strict" + +const dataURLRegexp = /^data:text\/css;base64,/i + +function isValid(url) { + return dataURLRegexp.test(url) +} + +function contents(url) { + // "data:text/css;base64,".length === 21 + return Buffer.from(url.slice(21), "base64").toString() +} + +module.exports = { + isValid, + contents, +} diff --git a/node_modules/postcss-import/lib/join-layer.js b/node_modules/postcss-import/lib/join-layer.js new file mode 100644 index 0000000..9d91519 --- /dev/null +++ b/node_modules/postcss-import/lib/join-layer.js @@ -0,0 +1,9 @@ +"use strict" + +module.exports = function (parentLayer, childLayer) { + if (!parentLayer.length && childLayer.length) return childLayer + if (parentLayer.length && !childLayer.length) return parentLayer + if (!parentLayer.length && !childLayer.length) return [] + + return parentLayer.concat(childLayer) +} diff --git a/node_modules/postcss-import/lib/join-media.js b/node_modules/postcss-import/lib/join-media.js new file mode 100644 index 0000000..fcaaecd --- /dev/null +++ b/node_modules/postcss-import/lib/join-media.js @@ -0,0 +1,28 @@ +"use strict" + +const startsWithKeywordRegexp = /^(all|not|only|print|screen)/i + +module.exports = function (parentMedia, childMedia) { + if (!parentMedia.length && childMedia.length) return childMedia + if (parentMedia.length && !childMedia.length) return parentMedia + if (!parentMedia.length && !childMedia.length) return [] + + const media = [] + + parentMedia.forEach(parentItem => { + const parentItemStartsWithKeyword = startsWithKeywordRegexp.test(parentItem) + + childMedia.forEach(childItem => { + const childItemStartsWithKeyword = startsWithKeywordRegexp.test(childItem) + if (parentItem !== childItem) { + if (childItemStartsWithKeyword && !parentItemStartsWithKeyword) { + media.push(`${childItem} and ${parentItem}`) + } else { + media.push(`${parentItem} and ${childItem}`) + } + } + }) + }) + + return media +} diff --git a/node_modules/postcss-import/lib/load-content.js b/node_modules/postcss-import/lib/load-content.js new file mode 100644 index 0000000..c10b57e --- /dev/null +++ b/node_modules/postcss-import/lib/load-content.js @@ -0,0 +1,12 @@ +"use strict" + +const readCache = require("read-cache") +const dataURL = require("./data-url") + +module.exports = filename => { + if (dataURL.isValid(filename)) { + return dataURL.contents(filename) + } + + return readCache(filename, "utf-8") +} diff --git a/node_modules/postcss-import/lib/parse-statements.js b/node_modules/postcss-import/lib/parse-statements.js new file mode 100644 index 0000000..0c94e5a --- /dev/null +++ b/node_modules/postcss-import/lib/parse-statements.js @@ -0,0 +1,172 @@ +"use strict" + +// external tooling +const valueParser = require("postcss-value-parser") + +// extended tooling +const { stringify } = valueParser + +function split(params, start) { + const list = [] + const last = params.reduce((item, node, index) => { + if (index < start) return "" + if (node.type === "div" && node.value === ",") { + list.push(item) + return "" + } + return item + stringify(node) + }, "") + list.push(last) + return list +} + +module.exports = function (result, styles) { + const statements = [] + let nodes = [] + + styles.each(node => { + let stmt + if (node.type === "atrule") { + if (node.name === "import") stmt = parseImport(result, node) + else if (node.name === "media") stmt = parseMedia(result, node) + else if (node.name === "charset") stmt = parseCharset(result, node) + } + + if (stmt) { + if (nodes.length) { + statements.push({ + type: "nodes", + nodes, + media: [], + layer: [], + }) + nodes = [] + } + statements.push(stmt) + } else nodes.push(node) + }) + + if (nodes.length) { + statements.push({ + type: "nodes", + nodes, + media: [], + layer: [], + }) + } + + return statements +} + +function parseMedia(result, atRule) { + const params = valueParser(atRule.params).nodes + return { + type: "media", + node: atRule, + media: split(params, 0), + layer: [], + } +} + +function parseCharset(result, atRule) { + if (atRule.prev()) { + return result.warn("@charset must precede all other statements", { + node: atRule, + }) + } + return { + type: "charset", + node: atRule, + media: [], + layer: [], + } +} + +function parseImport(result, atRule) { + let prev = atRule.prev() + if (prev) { + do { + if ( + prev.type !== "comment" && + (prev.type !== "atrule" || + (prev.name !== "import" && + prev.name !== "charset" && + !(prev.name === "layer" && !prev.nodes))) + ) { + return result.warn( + "@import must precede all other statements (besides @charset or empty @layer)", + { node: atRule } + ) + } + prev = prev.prev() + } while (prev) + } + + if (atRule.nodes) { + return result.warn( + "It looks like you didn't end your @import statement correctly. " + + "Child nodes are attached to it.", + { node: atRule } + ) + } + + const params = valueParser(atRule.params).nodes + const stmt = { + type: "import", + node: atRule, + media: [], + layer: [], + } + + // prettier-ignore + if ( + !params.length || + ( + params[0].type !== "string" || + !params[0].value + ) && + ( + params[0].type !== "function" || + params[0].value !== "url" || + !params[0].nodes.length || + !params[0].nodes[0].value + ) + ) { + return result.warn(`Unable to find uri in '${ atRule.toString() }'`, { + node: atRule, + }) + } + + if (params[0].type === "string") stmt.uri = params[0].value + else stmt.uri = params[0].nodes[0].value + stmt.fullUri = stringify(params[0]) + + let remainder = params + if (remainder.length > 2) { + if ( + (remainder[2].type === "word" || remainder[2].type === "function") && + remainder[2].value === "layer" + ) { + if (remainder[1].type !== "space") { + return result.warn("Invalid import layer statement", { node: atRule }) + } + + if (remainder[2].nodes) { + stmt.layer = [stringify(remainder[2].nodes)] + } else { + stmt.layer = [""] + } + remainder = remainder.slice(2) + } + } + + if (remainder.length > 2) { + if (remainder[1].type !== "space") { + return result.warn("Invalid import media statement", { node: atRule }) + } + + stmt.media = split(remainder, 2) + } + + return stmt +} diff --git a/node_modules/postcss-import/lib/process-content.js b/node_modules/postcss-import/lib/process-content.js new file mode 100644 index 0000000..ec413e0 --- /dev/null +++ b/node_modules/postcss-import/lib/process-content.js @@ -0,0 +1,59 @@ +"use strict" + +// builtin tooling +const path = require("path") + +// placeholder tooling +let sugarss + +module.exports = function processContent( + result, + content, + filename, + options, + postcss +) { + const { plugins } = options + const ext = path.extname(filename) + + const parserList = [] + + // SugarSS support: + if (ext === ".sss") { + if (!sugarss) { + try { + sugarss = require("sugarss") + } catch {} // Ignore + } + if (sugarss) + return runPostcss(postcss, content, filename, plugins, [sugarss]) + } + + // Syntax support: + if (result.opts.syntax?.parse) { + parserList.push(result.opts.syntax.parse) + } + + // Parser support: + if (result.opts.parser) parserList.push(result.opts.parser) + // Try the default as a last resort: + parserList.push(null) + + return runPostcss(postcss, content, filename, plugins, parserList) +} + +function runPostcss(postcss, content, filename, plugins, parsers, index) { + if (!index) index = 0 + return postcss(plugins) + .process(content, { + from: filename, + parser: parsers[index], + }) + .catch(err => { + // If there's an error, try the next parser + index++ + // If there are no parsers left, throw it + if (index === parsers.length) throw err + return runPostcss(postcss, content, filename, plugins, parsers, index) + }) +} diff --git a/node_modules/postcss-import/lib/resolve-id.js b/node_modules/postcss-import/lib/resolve-id.js new file mode 100644 index 0000000..ffef034 --- /dev/null +++ b/node_modules/postcss-import/lib/resolve-id.js @@ -0,0 +1,42 @@ +"use strict" + +// external tooling +const resolve = require("resolve") + +const moduleDirectories = ["web_modules", "node_modules"] + +function resolveModule(id, opts) { + return new Promise((res, rej) => { + resolve(id, opts, (err, path) => (err ? rej(err) : res(path))) + }) +} + +module.exports = function (id, base, options) { + const paths = options.path + + const resolveOpts = { + basedir: base, + moduleDirectory: moduleDirectories.concat(options.addModulesDirectories), + paths, + extensions: [".css"], + packageFilter: function processPackage(pkg) { + if (pkg.style) pkg.main = pkg.style + else if (!pkg.main || !/\.css$/.test(pkg.main)) pkg.main = "index.css" + return pkg + }, + preserveSymlinks: false, + } + + return resolveModule(`./${id}`, resolveOpts) + .catch(() => resolveModule(id, resolveOpts)) + .catch(() => { + if (paths.indexOf(base) === -1) paths.unshift(base) + + throw new Error( + `Failed to find '${id}' + in [ + ${paths.join(",\n ")} + ]` + ) + }) +} diff --git a/node_modules/postcss-import/package.json b/node_modules/postcss-import/package.json new file mode 100644 index 0000000..a81ea5f --- /dev/null +++ b/node_modules/postcss-import/package.json @@ -0,0 +1,65 @@ +{ + "name": "postcss-import", + "version": "15.1.0", + "description": "PostCSS plugin to import CSS files", + "keywords": [ + "css", + "postcss", + "postcss-plugin", + "import", + "node modules", + "npm" + ], + "author": "Maxime Thirouin", + "license": "MIT", + "repository": "https://github.com/postcss/postcss-import.git", + "files": [ + "index.js", + "lib" + ], + "engines": { + "node": ">=14.0.0" + }, + "dependencies": { + "postcss-value-parser": "^4.0.0", + "read-cache": "^1.0.0", + "resolve": "^1.1.7" + }, + "devDependencies": { + "ava": "^5.0.0", + "eslint": "^8.2.0", + "eslint-config-problems": "^7.0.0", + "eslint-plugin-prettier": "^4.0.0", + "postcss": "^8.0.0", + "postcss-scss": "^4.0.0", + "prettier": "~2.8.0", + "sugarss": "^4.0.0" + }, + "peerDependencies": { + "postcss": "^8.0.0" + }, + "scripts": { + "ci": "eslint . && ava", + "lint": "eslint . --fix", + "pretest": "npm run lint", + "test": "ava" + }, + "eslintConfig": { + "extends": "eslint-config-problems", + "env": { + "node": true + }, + "plugins": [ + "prettier" + ], + "rules": { + "prettier/prettier": [ + "error", + { + "semi": false, + "arrowParens": "avoid" + } + ] + } + } +} diff --git a/node_modules/postcss-js/LICENSE b/node_modules/postcss-js/LICENSE new file mode 100644 index 0000000..d3bd672 --- /dev/null +++ b/node_modules/postcss-js/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright 2015 Andrey Sitnik + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/postcss-js/README.md b/node_modules/postcss-js/README.md new file mode 100644 index 0000000..a29e3b0 --- /dev/null +++ b/node_modules/postcss-js/README.md @@ -0,0 +1,22 @@ +# PostCSS JS + + + +[PostCSS] for CSS-in-JS and styles in JS objects. + +For example, to use [Stylelint] or [RTLCSS] plugins in your workflow. + + + Sponsored by Evil Martians + + +[Stylelint]: https://github.com/stylelint/stylelint +[PostCSS]: https://github.com/postcss/postcss +[RTLCSS]: https://github.com/MohammadYounes/rtlcss + + +## Docs +Read full docs **[here](https://github.com/postcss/postcss-js#readme)**. diff --git a/node_modules/postcss-js/async.js b/node_modules/postcss-js/async.js new file mode 100644 index 0000000..4c2f3c6 --- /dev/null +++ b/node_modules/postcss-js/async.js @@ -0,0 +1,15 @@ +let postcss = require('postcss') + +let processResult = require('./process-result') +let parse = require('./parser') + +module.exports = function async(plugins) { + let processor = postcss(plugins) + return async input => { + let result = await processor.process(input, { + parser: parse, + from: undefined + }) + return processResult(result) + } +} diff --git a/node_modules/postcss-js/index.js b/node_modules/postcss-js/index.js new file mode 100644 index 0000000..8a4274e --- /dev/null +++ b/node_modules/postcss-js/index.js @@ -0,0 +1,11 @@ +let objectify = require('./objectifier') +let parse = require('./parser') +let async = require('./async') +let sync = require('./sync') + +module.exports = { + objectify, + parse, + async, + sync +} diff --git a/node_modules/postcss-js/index.mjs b/node_modules/postcss-js/index.mjs new file mode 100644 index 0000000..d14b61c --- /dev/null +++ b/node_modules/postcss-js/index.mjs @@ -0,0 +1,8 @@ +import index from './index.js' + +export default index + +export const objectify = index.objectify +export const parse = index.parse +export const async = index.async +export const sync = index.sync diff --git a/node_modules/postcss-js/objectifier.js b/node_modules/postcss-js/objectifier.js new file mode 100644 index 0000000..a4708b8 --- /dev/null +++ b/node_modules/postcss-js/objectifier.js @@ -0,0 +1,85 @@ +let camelcase = require('camelcase-css') + +let UNITLESS = { + boxFlex: true, + boxFlexGroup: true, + columnCount: true, + flex: true, + flexGrow: true, + flexPositive: true, + flexShrink: true, + flexNegative: true, + fontWeight: true, + lineClamp: true, + lineHeight: true, + opacity: true, + order: true, + orphans: true, + tabSize: true, + widows: true, + zIndex: true, + zoom: true, + fillOpacity: true, + strokeDashoffset: true, + strokeOpacity: true, + strokeWidth: true +} + +function atRule(node) { + if (typeof node.nodes === 'undefined') { + return true + } else { + return process(node) + } +} + +function process(node) { + let name + let result = {} + + node.each(child => { + if (child.type === 'atrule') { + name = '@' + child.name + if (child.params) name += ' ' + child.params + if (typeof result[name] === 'undefined') { + result[name] = atRule(child) + } else if (Array.isArray(result[name])) { + result[name].push(atRule(child)) + } else { + result[name] = [result[name], atRule(child)] + } + } else if (child.type === 'rule') { + let body = process(child) + if (result[child.selector]) { + for (let i in body) { + result[child.selector][i] = body[i] + } + } else { + result[child.selector] = body + } + } else if (child.type === 'decl') { + if (child.prop[0] === '-' && child.prop[1] === '-') { + name = child.prop + } else if (child.parent && child.parent.selector === ':export') { + name = child.prop + } else { + name = camelcase(child.prop) + } + let value = child.value + if (!isNaN(child.value) && UNITLESS[name]) { + value = parseFloat(child.value) + } + if (child.important) value += ' !important' + if (typeof result[name] === 'undefined') { + result[name] = value + } else if (Array.isArray(result[name])) { + result[name].push(value) + } else { + result[name] = [result[name], value] + } + } + }) + return result +} + +module.exports = process diff --git a/node_modules/postcss-js/package.json b/node_modules/postcss-js/package.json new file mode 100644 index 0000000..ce0ff35 --- /dev/null +++ b/node_modules/postcss-js/package.json @@ -0,0 +1,42 @@ +{ + "name": "postcss-js", + "version": "4.0.1", + "description": "PostCSS for CSS-in-JS and styles in JS objects", + "keywords": [ + "postcss", + "postcss-runner", + "js", + "inline", + "react", + "css", + "cssinjs" + ], + "author": "Andrey Sitnik ", + "license": "MIT", + "repository": "postcss/postcss-js", + "engines": { + "node": "^12 || ^14 || >= 16" + }, + "exports": { + ".": { + "require": "./index.js", + "import": "./index.mjs" + }, + "./package.json": "./package.json", + "./async": "./async.js", + "./objectifier": "./objectifier.js", + "./parser": "./parser.js", + "./process-result": "./process-result.js", + "./sync": "./sync.js" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + "peerDependencies": { + "postcss": "^8.4.21" + }, + "dependencies": { + "camelcase-css": "^2.0.1" + } +} diff --git a/node_modules/postcss-js/parser.js b/node_modules/postcss-js/parser.js new file mode 100644 index 0000000..17ae264 --- /dev/null +++ b/node_modules/postcss-js/parser.js @@ -0,0 +1,104 @@ +let postcss = require('postcss') + +let IMPORTANT = /\s*!important\s*$/i + +let UNITLESS = { + 'box-flex': true, + 'box-flex-group': true, + 'column-count': true, + 'flex': true, + 'flex-grow': true, + 'flex-positive': true, + 'flex-shrink': true, + 'flex-negative': true, + 'font-weight': true, + 'line-clamp': true, + 'line-height': true, + 'opacity': true, + 'order': true, + 'orphans': true, + 'tab-size': true, + 'widows': true, + 'z-index': true, + 'zoom': true, + 'fill-opacity': true, + 'stroke-dashoffset': true, + 'stroke-opacity': true, + 'stroke-width': true +} + +function dashify(str) { + return str + .replace(/([A-Z])/g, '-$1') + .replace(/^ms-/, '-ms-') + .toLowerCase() +} + +function decl(parent, name, value) { + if (value === false || value === null) return + + if (!name.startsWith('--')) { + name = dashify(name) + } + + if (typeof value === 'number') { + if (value === 0 || UNITLESS[name]) { + value = value.toString() + } else { + value += 'px' + } + } + + if (name === 'css-float') name = 'float' + + if (IMPORTANT.test(value)) { + value = value.replace(IMPORTANT, '') + parent.push(postcss.decl({ prop: name, value, important: true })) + } else { + parent.push(postcss.decl({ prop: name, value })) + } +} + +function atRule(parent, parts, value) { + let node = postcss.atRule({ name: parts[1], params: parts[3] || '' }) + if (typeof value === 'object') { + node.nodes = [] + parse(value, node) + } + parent.push(node) +} + +function parse(obj, parent) { + let name, value, node + for (name in obj) { + value = obj[name] + if (value === null || typeof value === 'undefined') { + continue + } else if (name[0] === '@') { + let parts = name.match(/@(\S+)(\s+([\W\w]*)\s*)?/) + if (Array.isArray(value)) { + for (let i of value) { + atRule(parent, parts, i) + } + } else { + atRule(parent, parts, value) + } + } else if (Array.isArray(value)) { + for (let i of value) { + decl(parent, name, i) + } + } else if (typeof value === 'object') { + node = postcss.rule({ selector: name }) + parse(value, node) + parent.push(node) + } else { + decl(parent, name, value) + } + } +} + +module.exports = function (obj) { + let root = postcss.root() + parse(obj, root) + return root +} diff --git a/node_modules/postcss-js/process-result.js b/node_modules/postcss-js/process-result.js new file mode 100644 index 0000000..215a95c --- /dev/null +++ b/node_modules/postcss-js/process-result.js @@ -0,0 +1,11 @@ +let objectify = require('./objectifier') + +module.exports = function processResult(result) { + if (console && console.warn) { + result.warnings().forEach(warn => { + let source = warn.plugin || 'PostCSS' + console.warn(source + ': ' + warn.text) + }) + } + return objectify(result.root) +} diff --git a/node_modules/postcss-js/sync.js b/node_modules/postcss-js/sync.js new file mode 100644 index 0000000..745bd27 --- /dev/null +++ b/node_modules/postcss-js/sync.js @@ -0,0 +1,12 @@ +let postcss = require('postcss') + +let processResult = require('./process-result') +let parse = require('./parser') + +module.exports = function (plugins) { + let processor = postcss(plugins) + return input => { + let result = processor.process(input, { parser: parse, from: undefined }) + return processResult(result) + } +} diff --git a/node_modules/postcss-load-config/LICENSE b/node_modules/postcss-load-config/LICENSE new file mode 100644 index 0000000..458e8a3 --- /dev/null +++ b/node_modules/postcss-load-config/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright Michael Ciniawsky + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/postcss-load-config/README.md b/node_modules/postcss-load-config/README.md new file mode 100644 index 0000000..9de4de2 --- /dev/null +++ b/node_modules/postcss-load-config/README.md @@ -0,0 +1,466 @@ + + +
+ + + + + +

Load Config

+
+ +

Install

+ +```bash +npm i -D postcss-load-config +``` + +

Usage

+ +```bash +npm i -S|-D postcss-plugin +``` + +Install all required PostCSS plugins and save them to your **package.json** `dependencies`/`devDependencies` + +Then create a PostCSS config file by choosing one of the following formats + +### `package.json` + +Create a **`postcss`** section in your project's **`package.json`** + +``` +Project (Root) + |– client + |– public + | + |- package.json +``` + +```json +{ + "postcss": { + "parser": "sugarss", + "map": false, + "plugins": { + "postcss-plugin": {} + } + } +} +``` + +### `.postcssrc` + +Create a **`.postcssrc`** file in JSON or YAML format + +> ℹ️ It's recommended to use an extension (e.g **`.postcssrc.json`** or **`.postcssrc.yml`**) instead of `.postcssrc` + +``` +Project (Root) + |– client + |– public + | + |- (.postcssrc|.postcssrc.json|.postcssrc.yml) + |- package.json +``` + +**`.postcssrc.json`** +```json +{ + "parser": "sugarss", + "map": false, + "plugins": { + "postcss-plugin": {} + } +} +``` + +**`.postcssrc.yml`** +```yaml +parser: sugarss +map: false +plugins: + postcss-plugin: {} +``` + +### `.postcssrc.js` or `postcss.config.js` + +You may need some logic within your config. +In this case create JS file named: +- `.postcssrc.js` +- `.postcssrc.mjs` +- `.postcssrc.cjs` +- `.postcssrc.ts` +- `.postcssrc.cts` +- `postcss.config.js` +- `postcss.config.mjs` +- `postcss.config.cjs` +- `postcss.config.ts` +- `postcss.config.cts` + +``` +Project (Root) + |– client + |– public + |- (.postcssrc|postcss.config).(js|mjs|cjs|ts|cts) + |- package.json +``` + +You can export the config as an `{Object}` + +**.postcssrc.js** +```js +module.exports = { + parser: 'sugarss', + map: false, + plugins: { + 'postcss-plugin': {} + } +} +``` + +Or export a `{Function}` that returns the config (more about the `ctx` param below) + +**.postcssrc.js** +```js +module.exports = (ctx) => ({ + parser: ctx.parser ? 'sugarss' : false, + map: ctx.env === 'development' ? ctx.map : false, + plugins: { + 'postcss-plugin': ctx.options.plugin + } +}) +``` + +Plugins can be loaded either using an `{Object}` or an `{Array}` + +#### `{Object}` + +**.postcssrc.js** +```js +module.exports = ({ env }) => ({ + ...options, + plugins: { + 'postcss-plugin': env === 'production' ? {} : false + } +}) +``` + +> ℹ️ When using an `{Object}`, the key can be a Node.js module name, a path to a JavaScript file that is relative to the directory of the PostCSS config file, or an absolute path to a JavaScript file. + +#### `{Array}` + +**.postcssrc.js** +```js +module.exports = ({ env }) => ({ + ...options, + plugins: [ + env === 'production' ? require('postcss-plugin')() : false + ] +}) +``` +> :warning: When using an `{Array}`, make sure to `require()` each plugin + +

Options

+ +|Name|Type|Default|Description| +|:--:|:--:|:-----:|:----------| +|[**`to`**](#to)|`{String}`|`undefined`|Destination File Path| +|[**`map`**](#map)|`{String\|Object}`|`false`|Enable/Disable Source Maps| +|[**`from`**](#from)|`{String}`|`undefined`|Source File Path| +|[**`parser`**](#parser)|`{String\|Function}`|`false`|Custom PostCSS Parser| +|[**`syntax`**](#syntax)|`{String\|Function}`|`false`|Custom PostCSS Syntax| +|[**`stringifier`**](#stringifier)|`{String\|Function}`|`false`|Custom PostCSS Stringifier| + +### `parser` + +**.postcssrc.js** +```js +module.exports = { + parser: 'sugarss' +} +``` + +### `syntax` + +**.postcssrc.js** +```js +module.exports = { + syntax: 'postcss-scss' +} +``` + +### `stringifier` + +**.postcssrc.js** +```js +module.exports = { + stringifier: 'midas' +} +``` + +### [**`map`**](https://github.com/postcss/postcss/blob/master/docs/source-maps.md) + +**.postcssrc.js** +```js +module.exports = { + map: 'inline' +} +``` + +> :warning: In most cases `options.from` && `options.to` are set by the third-party which integrates this package (CLI, gulp, webpack). It's unlikely one needs to set/use `options.from` && `options.to` within a config file. Unless you're a third-party plugin author using this module and its Node API directly **dont't set `options.from` && `options.to` yourself** + +### `to` + +```js +module.exports = { + to: 'path/to/dest.css' +} +``` + +### `from` + +```js +module.exports = { + from: 'path/to/src.css' +} +``` + +

Plugins

+ +### `{} || null` + +The plugin will be loaded with defaults + +```js +'postcss-plugin': {} || null +``` + +**.postcssrc.js** +```js +module.exports = { + plugins: { + 'postcss-plugin': {} || null + } +} +``` + +> :warning: `{}` must be an **empty** `{Object}` literal + +### `{Object}` + +The plugin will be loaded with given options + +```js +'postcss-plugin': { option: '', option: '' } +``` + +**.postcssrc.js** +```js +module.exports = { + plugins: { + 'postcss-plugin': { option: '', option: '' } + } +} +``` + +### `false` + +The plugin will not be loaded + +```js +'postcss-plugin': false +``` + +**.postcssrc.js** +```js +module.exports = { + plugins: { + 'postcss-plugin': false + } +} +``` + +### `Ordering` + +Plugin **execution order** is determined by declaration in the plugins section (**top-down**) + +```js +{ + plugins: { + 'postcss-plugin': {}, // [0] + 'postcss-plugin': {}, // [1] + 'postcss-plugin': {} // [2] + } +} +``` + +

Context

+ +When using a `{Function}` (`postcss.config.js` or `.postcssrc.js`), it's possible to pass context to `postcss-load-config`, which will be evaluated while loading your config. By default `ctx.env (process.env.NODE_ENV)` and `ctx.cwd (process.cwd())` are available on the `ctx` `{Object}` + +> ℹ️ Most third-party integrations add additional properties to the `ctx` (e.g `postcss-loader`). Check the specific module's README for more information about what is available on the respective `ctx` + +

Examples

+ +**postcss.config.js** + +```js +module.exports = (ctx) => ({ + parser: ctx.parser ? 'sugarss' : false, + map: ctx.env === 'development' ? ctx.map : false, + plugins: { + 'postcss-import': {}, + 'postcss-nested': {}, + cssnano: ctx.env === 'production' ? {} : false + } +}) +``` + +
+ +
+ +```json +"scripts": { + "build": "NODE_ENV=production node postcss", + "start": "NODE_ENV=development node postcss" +} +``` + +```js +const { readFileSync } = require('fs') + +const postcss = require('postcss') +const postcssrc = require('postcss-load-config') + +const css = readFileSync('index.sss', 'utf8') + +const ctx = { parser: true, map: 'inline' } + +postcssrc(ctx).then(({ plugins, options }) => { + postcss(plugins) + .process(css, options) + .then((result) => console.log(result.css)) +}) +``` + +
+ +
+ +```json +"scripts": { + "build": "NODE_ENV=production gulp", + "start": "NODE_ENV=development gulp" +} +``` + +```js +const { task, src, dest, series, watch } = require('gulp') + +const postcss = require('gulp-postcssrc') + +const css = () => { + src('src/*.css') + .pipe(postcss()) + .pipe(dest('dest')) +}) + +task('watch', () => { + watch(['src/*.css', 'postcss.config.js'], css) +}) + +task('default', series(css, 'watch')) +``` + +
+ +
+ +```json +"scripts": { + "build": "NODE_ENV=production webpack", + "start": "NODE_ENV=development webpack-dev-server" +} +``` + +**webpack.config.js** +```js +module.exports = (env) => ({ + module: { + rules: [ + { + test: /\.css$/, + use: [ + 'style-loader', + 'css-loader', + 'postcss-loader' + ] + } + ] + } +}) +``` + +

Maintainers

+ + + + + + + + +
+ +
+ Michael Ciniawsky +
+ +
+ Mateusz Derks +
+ +

Contributors

+ + + + + + + + + + +
+ +
+ Ryan Dunckel +
+ +
+ Patrick Gilday +
+ +
+ Dalton Santos +
+ +
+ François Wouts +
= 14" + }, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "lilconfig": "^3.0.0", + "yaml": "^2.3.4" + }, + "peerDependencies": { + "postcss": ">=8.0.9", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "ts-node": { + "optional": true + }, + "postcss": { + "optional": true + } + }, + "keywords": [ + "postcss", + "postcssrc", + "postcss.config.js" + ], + "author": "Michael Ciniawky ", + "contributors": [ + "Ryan Dunckel", + "Mateusz Derks", + "Dalton Santos", + "Patrick Gilday", + "François Wouts" + ], + "repository": "postcss/postcss-load-config", + "license": "MIT" +} diff --git a/node_modules/postcss-load-config/src/index.d.ts b/node_modules/postcss-load-config/src/index.d.ts new file mode 100644 index 0000000..4979220 --- /dev/null +++ b/node_modules/postcss-load-config/src/index.d.ts @@ -0,0 +1,65 @@ +// based on @types/postcss-load-config@2.0.1 +// Type definitions for postcss-load-config 2.1 +import Processor from 'postcss/lib/processor'; +import { Plugin, ProcessOptions, Transformer } from 'postcss'; +import { Options as ConfigOptions } from "lilconfig"; + +declare function postcssrc( + ctx?: postcssrc.ConfigContext, + path?: string, + options?: ConfigOptions +): Promise; + +declare namespace postcssrc { + // In the ConfigContext, these three options can be instances of the + // appropriate class, or strings. If they are strings, postcss-load-config will + // require() them and pass the instances along. + export interface ProcessOptionsPreload { + parser?: string | ProcessOptions['parser']; + stringifier?: string | ProcessOptions['stringifier']; + syntax?: string | ProcessOptions['syntax']; + } + + // The remaining ProcessOptions, sans the three above. + export type RemainingProcessOptions = Pick< + ProcessOptions, + Exclude + >; + + // Additional context options that postcss-load-config understands. + export interface Context { + cwd?: string; + env?: string; + } + + // The full shape of the ConfigContext. + export type ConfigContext = Context & + ProcessOptionsPreload & + RemainingProcessOptions; + + // Result of postcssrc is a Promise containing the filename plus the options + // and plugins that are ready to pass on to postcss. + export type ResultPlugin = Plugin | Transformer | Processor; + + export interface Result { + file: string; + options: ProcessOptions; + plugins: ResultPlugin[]; + } + + export type ConfigPlugin = Transformer | Plugin | Processor; + + export interface Config { + parser?: string | ProcessOptions['parser'] | false; + stringifier?: string | ProcessOptions['stringifier'] | false; + syntax?: string | ProcessOptions['syntax'] | false; + map?: string | false; + from?: string; + to?: string; + plugins?: Array | Record; + } + + export type ConfigFn = (ctx: ConfigContext) => Config | Promise; +} + +export = postcssrc; diff --git a/node_modules/postcss-load-config/src/index.js b/node_modules/postcss-load-config/src/index.js new file mode 100644 index 0000000..ce86aaa --- /dev/null +++ b/node_modules/postcss-load-config/src/index.js @@ -0,0 +1,185 @@ +'use strict' + +const resolve = require('path').resolve +const url = require('url') + +const config = require('lilconfig') +const yaml = require('yaml') + +const loadOptions = require('./options.js') +const loadPlugins = require('./plugins.js') + +/* istanbul ignore next */ +const interopRequireDefault = (obj) => obj && obj.__esModule ? obj : { default: obj } + +/** + * Process the result from cosmiconfig + * + * @param {Object} ctx Config Context + * @param {Object} result Cosmiconfig result + * + * @return {Object} PostCSS Config + */ +const processResult = (ctx, result) => { + const file = result.filepath || '' + let config = interopRequireDefault(result.config).default || {} + + if (typeof config === 'function') { + config = config(ctx) + } else { + config = Object.assign({}, config, ctx) + } + + if (!config.plugins) { + config.plugins = [] + } + + return { + plugins: loadPlugins(config, file), + options: loadOptions(config, file), + file + } +} + +/** + * Builds the Config Context + * + * @param {Object} ctx Config Context + * + * @return {Object} Config Context + */ +const createContext = (ctx) => { + /** + * @type {Object} + * + * @prop {String} cwd=process.cwd() Config search start location + * @prop {String} env=process.env.NODE_ENV Config Enviroment, will be set to `development` by `postcss-load-config` if `process.env.NODE_ENV` is `undefined` + */ + ctx = Object.assign({ + cwd: process.cwd(), + env: process.env.NODE_ENV + }, ctx) + + if (!ctx.env) { + process.env.NODE_ENV = 'development' + } + + return ctx +} + +const importDefault = async filepath => { + const module = await import(url.pathToFileURL(filepath).href) + return module.default +} + +const addTypeScriptLoader = (options = {}, loader) => { + const moduleName = 'postcss' + + return { + ...options, + searchPlaces: [ + ...(options.searchPlaces || []), + 'package.json', + `.${moduleName}rc`, + `.${moduleName}rc.json`, + `.${moduleName}rc.yaml`, + `.${moduleName}rc.yml`, + `.${moduleName}rc.ts`, + `.${moduleName}rc.cts`, + `.${moduleName}rc.js`, + `.${moduleName}rc.cjs`, + `.${moduleName}rc.mjs`, + `${moduleName}.config.ts`, + `${moduleName}.config.cts`, + `${moduleName}.config.js`, + `${moduleName}.config.cjs`, + `${moduleName}.config.mjs` + ], + loaders: { + ...options.loaders, + '.yaml': (filepath, content) => yaml.parse(content), + '.yml': (filepath, content) => yaml.parse(content), + '.js': importDefault, + '.cjs': importDefault, + '.mjs': importDefault, + '.ts': loader, + '.cts': loader + } + } +} + +const withTypeScriptLoader = (rcFunc) => { + return (ctx, path, options) => { + return rcFunc(ctx, path, addTypeScriptLoader(options, (configFile) => { + let registerer = { enabled () {} } + + try { + // Register TypeScript compiler instance + registerer = require('ts-node').register({ + // transpile to cjs even if compilerOptions.module in tsconfig is not Node16/NodeNext. + moduleTypes: { '**/*.cts': 'cjs' } + }) + + return require(configFile) + } catch (err) { + if (err.code === 'MODULE_NOT_FOUND') { + throw new Error( + `'ts-node' is required for the TypeScript configuration files. Make sure it is installed\nError: ${err.message}` + ) + } + + throw err + } finally { + registerer.enabled(false) + } + })) + } +} + +/** + * Load Config + * + * @method rc + * + * @param {Object} ctx Config Context + * @param {String} path Config Path + * @param {Object} options Config Options + * + * @return {Promise} config PostCSS Config + */ +const rc = withTypeScriptLoader((ctx, path, options) => { + /** + * @type {Object} The full Config Context + */ + ctx = createContext(ctx) + + /** + * @type {String} `process.cwd()` + */ + path = path ? resolve(path) : process.cwd() + + return config.lilconfig('postcss', options) + .search(path) + .then((result) => { + if (!result) { + throw new Error(`No PostCSS Config found in: ${path}`) + } + + return processResult(ctx, result) + }) +}) + +/** + * Autoload Config for PostCSS + * + * @author Michael Ciniawsky @michael-ciniawsky + * @license MIT + * + * @module postcss-load-config + * @version 2.1.0 + * + * @requires comsiconfig + * @requires ./options + * @requires ./plugins + */ +module.exports = rc diff --git a/node_modules/postcss-load-config/src/options.js b/node_modules/postcss-load-config/src/options.js new file mode 100644 index 0000000..d3ef2d6 --- /dev/null +++ b/node_modules/postcss-load-config/src/options.js @@ -0,0 +1,47 @@ +'use strict' + +const req = require('./req.js') + +/** + * Load Options + * + * @private + * @method options + * + * @param {Object} config PostCSS Config + * + * @return {Object} options PostCSS Options + */ +const options = (config, file) => { + if (config.parser && typeof config.parser === 'string') { + try { + config.parser = req(config.parser, file) + } catch (err) { + throw new Error(`Loading PostCSS Parser failed: ${err.message}\n\n(@${file})`) + } + } + + if (config.syntax && typeof config.syntax === 'string') { + try { + config.syntax = req(config.syntax, file) + } catch (err) { + throw new Error(`Loading PostCSS Syntax failed: ${err.message}\n\n(@${file})`) + } + } + + if (config.stringifier && typeof config.stringifier === 'string') { + try { + config.stringifier = req(config.stringifier, file) + } catch (err) { + throw new Error(`Loading PostCSS Stringifier failed: ${err.message}\n\n(@${file})`) + } + } + + if (config.plugins) { + delete config.plugins + } + + return config +} + +module.exports = options diff --git a/node_modules/postcss-load-config/src/plugins.js b/node_modules/postcss-load-config/src/plugins.js new file mode 100644 index 0000000..6cb994b --- /dev/null +++ b/node_modules/postcss-load-config/src/plugins.js @@ -0,0 +1,85 @@ +'use strict' + +const req = require('./req.js') + +/** + * Plugin Loader + * + * @private + * @method load + * + * @param {String} plugin PostCSS Plugin Name + * @param {Object} options PostCSS Plugin Options + * + * @return {Function} PostCSS Plugin + */ +const load = (plugin, options, file) => { + try { + if ( + options === null || + options === undefined || + Object.keys(options).length === 0 + ) { + return req(plugin, file) + } else { + return req(plugin, file)(options) + } + } catch (err) { + throw new Error(`Loading PostCSS Plugin failed: ${err.message}\n\n(@${file})`) + } +} + +/** + * Load Plugins + * + * @private + * @method plugins + * + * @param {Object} config PostCSS Config Plugins + * + * @return {Array} plugins PostCSS Plugins + */ +const plugins = (config, file) => { + let plugins = [] + + if (Array.isArray(config.plugins)) { + plugins = config.plugins.filter(Boolean) + } else { + plugins = Object.keys(config.plugins) + .filter((plugin) => { + return config.plugins[plugin] !== false ? plugin : '' + }) + .map((plugin) => { + return load(plugin, config.plugins[plugin], file) + }) + } + + if (plugins.length && plugins.length > 0) { + plugins.forEach((plugin, i) => { + if (plugin.default) { + plugin = plugin.default + } + + if (plugin.postcss === true) { + plugin = plugin() + } else if (plugin.postcss) { + plugin = plugin.postcss + } + + if ( + // eslint-disable-next-line + !( + (typeof plugin === 'object' && Array.isArray(plugin.plugins)) || + (typeof plugin === 'object' && plugin.postcssPlugin) || + (typeof plugin === 'function') + ) + ) { + throw new TypeError(`Invalid PostCSS Plugin found at: plugins[${i}]\n\n(@${file})`) + } + }) + } + + return plugins +} + +module.exports = plugins diff --git a/node_modules/postcss-load-config/src/req.js b/node_modules/postcss-load-config/src/req.js new file mode 100644 index 0000000..42020c9 --- /dev/null +++ b/node_modules/postcss-load-config/src/req.js @@ -0,0 +1,10 @@ +// eslint-disable-next-line n/no-deprecated-api +const { createRequire, createRequireFromPath } = require('module') + +function req (name, rootFile) { + const create = createRequire || createRequireFromPath + const require = create(rootFile) + return require(name) +} + +module.exports = req diff --git a/node_modules/postcss-nested/LICENSE b/node_modules/postcss-nested/LICENSE new file mode 100644 index 0000000..1ae47a2 --- /dev/null +++ b/node_modules/postcss-nested/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright 2014 Andrey Sitnik + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/postcss-nested/README.md b/node_modules/postcss-nested/README.md new file mode 100644 index 0000000..c65988d --- /dev/null +++ b/node_modules/postcss-nested/README.md @@ -0,0 +1,85 @@ +# PostCSS Nested + + + +[PostCSS] plugin to unwrap nested rules closer to Sass syntax. + +```css +.phone { + &_title { + width: 500px; + @media (max-width: 500px) { + width: auto; + } + body.is_dark & { + color: white; + } + } + img { + display: block; + } +} + +.title { + font-size: var(--font); + + @at-root html { + --font: 16px; + } +} +``` + +will be processed to: + +```css +.phone_title { + width: 500px; +} +@media (max-width: 500px) { + .phone_title { + width: auto; + } +} +body.is_dark .phone_title { + color: white; +} +.phone img { + display: block; +} + +.title { + font-size: var(--font); +} +html { + --font: 16px; +} +``` + +Related plugins: + +- Use [`postcss-current-selector`] **after** this plugin if you want + to use current selector in properties or variables values. +- Use [`postcss-nested-ancestors`] **before** this plugin if you want + to reference any ancestor element directly in your selectors with `^&`. + +Alternatives: + +- See also [`postcss-nesting`], which implements [CSSWG draft]. +- [`postcss-nested-props`] for nested properties like `font-size`. + + + Sponsored by Evil Martians + + +[`postcss-current-selector`]: https://github.com/komlev/postcss-current-selector +[`postcss-nested-ancestors`]: https://github.com/toomuchdesign/postcss-nested-ancestors +[`postcss-nested-props`]: https://github.com/jedmao/postcss-nested-props +[`postcss-nesting`]: https://github.com/csstools/postcss-plugins/tree/main/plugins/postcss-nesting +[CSSWG draft]: https://drafts.csswg.org/css-nesting-1/ +[PostCSS]: https://github.com/postcss/postcss + +## Docs +Read full docs **[here](https://github.com/postcss/postcss-nested#readme)**. diff --git a/node_modules/postcss-nested/index.d.ts b/node_modules/postcss-nested/index.d.ts new file mode 100644 index 0000000..5367682 --- /dev/null +++ b/node_modules/postcss-nested/index.d.ts @@ -0,0 +1,41 @@ +// Original definitions (@types/postcss-nested) +// by Maxim Vorontsov + +import { PluginCreator } from 'postcss' + +declare namespace nested { + interface Options { + /** + * By default, plugin will bubble only `@media`, `@supports` and `@layer` + * at-rules. Use this option to add your custom at-rules to this list. + */ + bubble?: string[] + + /** + * By default, plugin will unwrap only `@font-face`, `@keyframes`, + * and `@document` at-rules. You can add your custom at-rules + * to this list by this option. + */ + unwrap?: string[] + + /** + * By default, plugin will strip out any empty selector generated + * by intermediate nesting levels. You can set this option to `true` + * to preserve them. + */ + preserveEmpty?: boolean + + /** + * The plugin supports the SCSS custom at-rule `@at-root` which breaks + * rule blocks out of their nested position. If you want, you can choose + * a new custom name for this rule in your code. + */ + rootRuleName?: string + } + + type Nested = PluginCreator +} + +declare const nested: nested.Nested + +export = nested diff --git a/node_modules/postcss-nested/index.js b/node_modules/postcss-nested/index.js new file mode 100644 index 0000000..79831b6 --- /dev/null +++ b/node_modules/postcss-nested/index.js @@ -0,0 +1,361 @@ +const { AtRule, Rule } = require('postcss') +let parser = require('postcss-selector-parser') + +/** + * Run a selector string through postcss-selector-parser + */ +function parse(rawSelector, rule) { + let nodes + try { + parser(parsed => { + nodes = parsed + }).processSync(rawSelector) + } catch (e) { + if (rawSelector.includes(':')) { + throw rule ? rule.error('Missed semicolon') : e + } else { + throw rule ? rule.error(e.message) : e + } + } + return nodes.at(0) +} + +/** + * Replaces the "&" token in a node's selector with the parent selector + * similar to what SCSS does. + * + * Mutates the nodes list + */ +function interpolateAmpInSelector(nodes, parent) { + let replaced = false + nodes.each(node => { + if (node.type === 'nesting') { + let clonedParent = parent.clone({}) + if (node.value !== '&') { + node.replaceWith( + parse(node.value.replace('&', clonedParent.toString())) + ) + } else { + node.replaceWith(clonedParent) + } + replaced = true + } else if ('nodes' in node && node.nodes) { + if (interpolateAmpInSelector(node, parent)) { + replaced = true + } + } + }) + return replaced +} + +/** + * Combines parent and child selectors, in a SCSS-like way + */ +function mergeSelectors(parent, child) { + let merged = [] + parent.selectors.forEach(sel => { + let parentNode = parse(sel, parent) + + child.selectors.forEach(selector => { + if (!selector) { + return + } + let node = parse(selector, child) + let replaced = interpolateAmpInSelector(node, parentNode) + if (!replaced) { + node.prepend(parser.combinator({ value: ' ' })) + node.prepend(parentNode.clone({})) + } + merged.push(node.toString()) + }) + }) + return merged +} + +/** + * Move a child and its preceeding comment(s) to after "after" + */ +function breakOut(child, after) { + let prev = child.prev() + after.after(child) + while (prev && prev.type === 'comment') { + let nextPrev = prev.prev() + after.after(prev) + prev = nextPrev + } + return child +} + +function createFnAtruleChilds(bubble) { + return function atruleChilds(rule, atrule, bubbling, mergeSels = bubbling) { + let children = [] + atrule.each(child => { + if (child.type === 'rule' && bubbling) { + if (mergeSels) { + child.selectors = mergeSelectors(rule, child) + } + } else if (child.type === 'atrule' && child.nodes) { + if (bubble[child.name]) { + atruleChilds(rule, child, mergeSels) + } else if (atrule[rootRuleMergeSel] !== false) { + children.push(child) + } + } else { + children.push(child) + } + }) + if (bubbling) { + if (children.length) { + let clone = rule.clone({ nodes: [] }) + for (let child of children) { + clone.append(child) + } + atrule.prepend(clone) + } + } + } +} + +function pickDeclarations(selector, declarations, after) { + let parent = new Rule({ + nodes: [], + selector + }) + parent.append(declarations) + after.after(parent) + return parent +} + +function atruleNames(defaults, custom) { + let list = {} + for (let name of defaults) { + list[name] = true + } + if (custom) { + for (let name of custom) { + list[name.replace(/^@/, '')] = true + } + } + return list +} + +function parseRootRuleParams(params) { + params = params.trim() + let braceBlock = params.match(/^\((.*)\)$/) + if (!braceBlock) { + return { selector: params, type: 'basic' } + } + let bits = braceBlock[1].match(/^(with(?:out)?):(.+)$/) + if (bits) { + let allowlist = bits[1] === 'with' + let rules = Object.fromEntries( + bits[2] + .trim() + .split(/\s+/) + .map(name => [name, true]) + ) + if (allowlist && rules.all) { + return { type: 'noop' } + } + let escapes = rule => !!rules[rule] + if (rules.all) { + escapes = () => true + } else if (allowlist) { + escapes = rule => (rule === 'all' ? false : !rules[rule]) + } + + return { + escapes, + type: 'withrules' + } + } + // Unrecognized brace block + return { type: 'unknown' } +} + +function getAncestorRules(leaf) { + let lineage = [] + let parent = leaf.parent + + while (parent && parent instanceof AtRule) { + lineage.push(parent) + parent = parent.parent + } + return lineage +} + +function unwrapRootRule(rule) { + let escapes = rule[rootRuleEscapes] + + if (!escapes) { + rule.after(rule.nodes) + } else { + let nodes = rule.nodes + + let topEscaped + let topEscapedIdx = -1 + let breakoutLeaf + let breakoutRoot + let clone + + let lineage = getAncestorRules(rule) + lineage.forEach((parent, i) => { + if (escapes(parent.name)) { + topEscaped = parent + topEscapedIdx = i + breakoutRoot = clone + } else { + let oldClone = clone + clone = parent.clone({ nodes: [] }) + oldClone && clone.append(oldClone) + breakoutLeaf = breakoutLeaf || clone + } + }) + + if (!topEscaped) { + rule.after(nodes) + } else if (!breakoutRoot) { + topEscaped.after(nodes) + } else { + let leaf = breakoutLeaf + leaf.append(nodes) + topEscaped.after(breakoutRoot) + } + + if (rule.next() && topEscaped) { + let restRoot + lineage.slice(0, topEscapedIdx + 1).forEach((parent, i, arr) => { + let oldRoot = restRoot + restRoot = parent.clone({ nodes: [] }) + oldRoot && restRoot.append(oldRoot) + + let nextSibs = [] + let _child = arr[i - 1] || rule + let next = _child.next() + while (next) { + nextSibs.push(next) + next = next.next() + } + restRoot.append(nextSibs) + }) + restRoot && (breakoutRoot || nodes[nodes.length - 1]).after(restRoot) + } + } + + rule.remove() +} + +const rootRuleMergeSel = Symbol('rootRuleMergeSel') +const rootRuleEscapes = Symbol('rootRuleEscapes') + +function normalizeRootRule(rule) { + let { params } = rule + let { escapes, selector, type } = parseRootRuleParams(params) + if (type === 'unknown') { + throw rule.error( + `Unknown @${rule.name} parameter ${JSON.stringify(params)}` + ) + } + if (type === 'basic' && selector) { + let selectorBlock = new Rule({ nodes: rule.nodes, selector }) + rule.removeAll() + rule.append(selectorBlock) + } + rule[rootRuleEscapes] = escapes + rule[rootRuleMergeSel] = escapes ? !escapes('all') : type === 'noop' +} + +const hasRootRule = Symbol('hasRootRule') + +module.exports = (opts = {}) => { + let bubble = atruleNames( + ['media', 'supports', 'layer', 'container', 'starting-style'], + opts.bubble + ) + let atruleChilds = createFnAtruleChilds(bubble) + let unwrap = atruleNames( + [ + 'document', + 'font-face', + 'keyframes', + '-webkit-keyframes', + '-moz-keyframes' + ], + opts.unwrap + ) + let rootRuleName = (opts.rootRuleName || 'at-root').replace(/^@/, '') + let preserveEmpty = opts.preserveEmpty + + return { + Once(root) { + root.walkAtRules(rootRuleName, node => { + normalizeRootRule(node) + root[hasRootRule] = true + }) + }, + + postcssPlugin: 'postcss-nested', + + RootExit(root) { + if (root[hasRootRule]) { + root.walkAtRules(rootRuleName, unwrapRootRule) + root[hasRootRule] = false + } + }, + + Rule(rule) { + let unwrapped = false + let after = rule + let copyDeclarations = false + let declarations = [] + + rule.each(child => { + if (child.type === 'rule') { + if (declarations.length) { + after = pickDeclarations(rule.selector, declarations, after) + declarations = [] + } + + copyDeclarations = true + unwrapped = true + child.selectors = mergeSelectors(rule, child) + after = breakOut(child, after) + } else if (child.type === 'atrule') { + if (declarations.length) { + after = pickDeclarations(rule.selector, declarations, after) + declarations = [] + } + if (child.name === rootRuleName) { + unwrapped = true + atruleChilds(rule, child, true, child[rootRuleMergeSel]) + after = breakOut(child, after) + } else if (bubble[child.name]) { + copyDeclarations = true + unwrapped = true + atruleChilds(rule, child, true) + after = breakOut(child, after) + } else if (unwrap[child.name]) { + copyDeclarations = true + unwrapped = true + atruleChilds(rule, child, false) + after = breakOut(child, after) + } else if (copyDeclarations) { + declarations.push(child) + } + } else if (child.type === 'decl' && copyDeclarations) { + declarations.push(child) + } + }) + + if (declarations.length) { + after = pickDeclarations(rule.selector, declarations, after) + } + + if (unwrapped && preserveEmpty !== true) { + rule.raws.semicolon = true + if (rule.nodes.length === 0) rule.remove() + } + } + } +} +module.exports.postcss = true diff --git a/node_modules/postcss-nested/package.json b/node_modules/postcss-nested/package.json new file mode 100644 index 0000000..abc8e6c --- /dev/null +++ b/node_modules/postcss-nested/package.json @@ -0,0 +1,34 @@ +{ + "name": "postcss-nested", + "version": "6.2.0", + "description": "PostCSS plugin to unwrap nested rules like how Sass does it", + "keywords": [ + "postcss", + "css", + "postcss-plugin", + "sass", + "nested" + ], + "author": "Andrey Sitnik ", + "license": "MIT", + "repository": "postcss/postcss-nested", + "engines": { + "node": ">=12.0" + }, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "peerDependencies": { + "postcss": "^8.2.14" + }, + "dependencies": { + "postcss-selector-parser": "^6.1.1" + } +} diff --git a/node_modules/postcss-selector-parser/API.md b/node_modules/postcss-selector-parser/API.md new file mode 100644 index 0000000..c8e55ee --- /dev/null +++ b/node_modules/postcss-selector-parser/API.md @@ -0,0 +1,872 @@ +# API Documentation + +*Please use only this documented API when working with the parser. Methods +not documented here are subject to change at any point.* + +## `parser` function + +This is the module's main entry point. + +```js +const parser = require('postcss-selector-parser'); +``` + +### `parser([transform], [options])` + +Creates a new `processor` instance + +```js +const processor = parser(); +``` + +Or, with optional transform function + +```js +const transform = selectors => { + selectors.walkUniversals(selector => { + selector.remove(); + }); +}; + +const processor = parser(transform) + +// Example +const result = processor.processSync('*.class'); +// => .class +``` + +[See processor documentation](#processor) + +Arguments: + +* `transform (function)`: Provide a function to work with the parsed AST. +* `options (object)`: Provide default options for all calls on the returned `Processor`. + +### `parser.attribute([props])` + +Creates a new attribute selector. + +```js +parser.attribute({attribute: 'href'}); +// => [href] +``` + +Arguments: + +* `props (object)`: The new node's properties. + +### `parser.className([props])` + +Creates a new class selector. + +```js +parser.className({value: 'button'}); +// => .button +``` + +Arguments: + +* `props (object)`: The new node's properties. + +### `parser.combinator([props])` + +Creates a new selector combinator. + +```js +parser.combinator({value: '+'}); +// => + +``` + +Arguments: + +* `props (object)`: The new node's properties. + +Notes: +* **Descendant Combinators** The value of descendant combinators created by the + parser always just a single space (`" "`). For descendant selectors with no + comments, additional space is now stored in `node.spaces.before`. Depending + on the location of comments, additional spaces may be stored in + `node.raws.spaces.before`, `node.raws.spaces.after`, or `node.raws.value`. +* **Named Combinators** Although, nonstandard and unlikely to ever become a standard, + named combinators like `/deep/` and `/for/` are parsed as combinators. The + `node.value` is name after being unescaped and normalized as lowercase. The + original value for the combinator name is stored in `node.raws.value`. + + +### `parser.comment([props])` + +Creates a new comment. + +```js +parser.comment({value: '/* Affirmative, Dave. I read you. */'}); +// => /* Affirmative, Dave. I read you. */ +``` + +Arguments: + +* `props (object)`: The new node's properties. + +### `parser.id([props])` + +Creates a new id selector. + +```js +parser.id({value: 'search'}); +// => #search +``` + +Arguments: + +* `props (object)`: The new node's properties. + +### `parser.nesting([props])` + +Creates a new nesting selector. + +```js +parser.nesting(); +// => & +``` + +Arguments: + +* `props (object)`: The new node's properties. + +### `parser.pseudo([props])` + +Creates a new pseudo selector. + +```js +parser.pseudo({value: '::before'}); +// => ::before +``` + +Arguments: + +* `props (object)`: The new node's properties. + +### `parser.root([props])` + +Creates a new root node. + +```js +parser.root(); +// => (empty) +``` + +Arguments: + +* `props (object)`: The new node's properties. + +### `parser.selector([props])` + +Creates a new selector node. + +```js +parser.selector(); +// => (empty) +``` + +Arguments: + +* `props (object)`: The new node's properties. + +### `parser.string([props])` + +Creates a new string node. + +```js +parser.string(); +// => (empty) +``` + +Arguments: + +* `props (object)`: The new node's properties. + +### `parser.tag([props])` + +Creates a new tag selector. + +```js +parser.tag({value: 'button'}); +// => button +``` + +Arguments: + +* `props (object)`: The new node's properties. + +### `parser.universal([props])` + +Creates a new universal selector. + +```js +parser.universal(); +// => * +``` + +Arguments: + +* `props (object)`: The new node's properties. + +## Node types + +### `node.type` + +A string representation of the selector type. It can be one of the following; +`attribute`, `class`, `combinator`, `comment`, `id`, `nesting`, `pseudo`, +`root`, `selector`, `string`, `tag`, or `universal`. Note that for convenience, +these constants are exposed on the main `parser` as uppercased keys. So for +example you can get `id` by querying `parser.ID`. + +```js +parser.attribute({attribute: 'href'}).type; +// => 'attribute' +``` + +### `node.parent` + +Returns the parent node. + +```js +root.nodes[0].parent === root; +``` + +### `node.toString()`, `String(node)`, or `'' + node` + +Returns a string representation of the node. + +```js +const id = parser.id({value: 'search'}); +console.log(String(id)); +// => #search +``` + +### `node.next()` & `node.prev()` + +Returns the next/previous child of the parent node. + +```js +const next = id.next(); +if (next && next.type !== 'combinator') { + throw new Error('Qualified IDs are not allowed!'); +} +``` + +### `node.replaceWith(node)` + +Replace a node with another. + +```js +const attr = selectors.first.first; +const className = parser.className({value: 'test'}); +attr.replaceWith(className); +``` + +Arguments: + +* `node`: The node to substitute the original with. + +### `node.remove()` + +Removes the node from its parent node. + +```js +if (node.type === 'id') { + node.remove(); +} +``` + +### `node.clone([opts])` + +Returns a copy of a node, detached from any parent containers that the +original might have had. + +```js +const cloned = node.clone(); +``` + +### `node.isAtPosition(line, column)` + +Return a `boolean` indicating whether this node includes the character at the +position of the given line and column. Returns `undefined` if the nodes lack +sufficient source metadata to determine the position. + +Arguments: + +* `line`: 1-index based line number relative to the start of the selector. +* `column`: 1-index based column number relative to the start of the selector. + +### `node.spaces` + +Extra whitespaces around the node will be moved into `node.spaces.before` and +`node.spaces.after`. So for example, these spaces will be moved as they have +no semantic meaning: + +```css + h1 , h2 {} +``` + +For descendent selectors, the value is always a single space. + +```css +h1 h2 {} +``` + +Additional whitespace is found in either the `node.spaces.before` and `node.spaces.after` depending on the presence of comments or other whitespace characters. If the actual whitespace does not start or end with a single space, the node's raw value is set to the actual space(s) found in the source. + +### `node.source` + +An object describing the node's start/end, line/column source position. + +Within the following CSS, the `.bar` class node ... + +```css +.foo, + .bar {} +``` + +... will contain the following `source` object. + +```js +source: { + start: { + line: 2, + column: 3 + }, + end: { + line: 2, + column: 6 + } +} +``` + +### `node.sourceIndex` + +The zero-based index of the node within the original source string. + +Within the following CSS, the `.baz` class node will have a `sourceIndex` of `12`. + +```css +.foo, .bar, .baz {} +``` + +## Container types + +The `root`, `selector`, and `pseudo` nodes have some helper methods for working +with their children. + +### `container.nodes` + +An array of the container's children. + +```js +// Input: h1 h2 +selectors.at(0).nodes.length // => 3 +selectors.at(0).nodes[0].value // => 'h1' +selectors.at(0).nodes[1].value // => ' ' +``` + +### `container.first` & `container.last` + +The first/last child of the container. + +```js +selector.first === selector.nodes[0]; +selector.last === selector.nodes[selector.nodes.length - 1]; +``` + +### `container.at(index)` + +Returns the node at position `index`. + +```js +selector.at(0) === selector.first; +selector.at(0) === selector.nodes[0]; +``` + +Arguments: + +* `index`: The index of the node to return. + +### `container.atPosition(line, column)` + +Returns the node at the source position `line` and `column`. + +```js +// Input: :not(.foo),\n#foo > :matches(ol, ul) +selector.atPosition(1, 1); // => :not(.foo) +selector.atPosition(2, 1); // => \n#foo +``` + +Arguments: + +* `line`: The line number of the node to return. +* `column`: The column number of the node to return. + +### `container.index(node)` + +Return the index of the node within its container. + +```js +selector.index(selector.nodes[2]) // => 2 +``` + +Arguments: + +* `node`: A node within the current container. + +### `container.length` + +Proxy to the length of the container's nodes. + +```js +container.length === container.nodes.length +``` + +### `container` Array iterators + +The container class provides proxies to certain Array methods; these are: + +* `container.map === container.nodes.map` +* `container.reduce === container.nodes.reduce` +* `container.every === container.nodes.every` +* `container.some === container.nodes.some` +* `container.filter === container.nodes.filter` +* `container.sort === container.nodes.sort` + +Note that these methods only work on a container's immediate children; recursive +iteration is provided by `container.walk`. + +### `container.each(callback)` + +Iterate the container's immediate children, calling `callback` for each child. +You may return `false` within the callback to break the iteration. + +```js +let className; +selectors.each((selector, index) => { + if (selector.type === 'class') { + className = selector.value; + return false; + } +}); +``` + +Note that unlike `Array#forEach()`, this iterator is safe to use whilst adding +or removing nodes from the container. + +Arguments: + +* `callback (function)`: A function to call for each node, which receives `node` + and `index` arguments. + +### `container.walk(callback)` + +Like `container#each`, but will also iterate child nodes as long as they are +`container` types. + +```js +selectors.walk((selector, index) => { + // all nodes +}); +``` + +Arguments: + +* `callback (function)`: A function to call for each node, which receives `node` + and `index` arguments. + +This iterator is safe to use whilst mutating `container.nodes`, +like `container#each`. + +### `container.walk` proxies + +The container class provides proxy methods for iterating over types of nodes, +so that it is easier to write modules that target specific selectors. Those +methods are: + +* `container.walkAttributes` +* `container.walkClasses` +* `container.walkCombinators` +* `container.walkComments` +* `container.walkIds` +* `container.walkNesting` +* `container.walkPseudos` +* `container.walkTags` +* `container.walkUniversals` + +### `container.split(callback)` + +This method allows you to split a group of nodes by returning `true` from +a callback. It returns an array of arrays, where each inner array corresponds +to the groups that you created via the callback. + +```js +// (input) => h1 h2>>h3 +const list = selectors.first.split(selector => { + return selector.type === 'combinator'; +}); + +// (node values) => [['h1', ' '], ['h2', '>>'], ['h3']] +``` + +Arguments: + +* `callback (function)`: A function to call for each node, which receives `node` + as an argument. + +### `container.prepend(node)` & `container.append(node)` + +Add a node to the start/end of the container. Note that doing so will set +the parent property of the node to this container. + +```js +const id = parser.id({value: 'search'}); +selector.append(id); +``` + +Arguments: + +* `node`: The node to add. + +### `container.insertBefore(old, new)` & `container.insertAfter(old, new)` + +Add a node before or after an existing node in a container: + +```js +selectors.walk(selector => { + if (selector.type !== 'class') { + const className = parser.className({value: 'theme-name'}); + selector.parent.insertAfter(selector, className); + } +}); +``` + +Arguments: + +* `old`: The existing node in the container. +* `new`: The new node to add before/after the existing node. + +### `container.removeChild(node)` + +Remove the node from the container. Note that you can also use +`node.remove()` if you would like to remove just a single node. + +```js +selector.length // => 2 +selector.remove(id) +selector.length // => 1; +id.parent // undefined +``` + +Arguments: + +* `node`: The node to remove. + +### `container.removeAll()` or `container.empty()` + +Remove all children from the container. + +```js +selector.removeAll(); +selector.length // => 0 +``` + +## Root nodes + +A root node represents a comma separated list of selectors. Indeed, all +a root's `toString()` method does is join its selector children with a ','. +Other than this, it has no special functionality and acts like a container. + +### `root.trailingComma` + +This will be set to `true` if the input has a trailing comma, in order to +support parsing of legacy CSS hacks. + +## Selector nodes + +A selector node represents a single complex selector. For example, this +selector string `h1 h2 h3, [href] > p`, is represented as two selector nodes. +It has no special functionality of its own. + +## Pseudo nodes + +A pseudo selector extends a container node; if it has any parameters of its +own (such as `h1:not(h2, h3)`), they will be its children. Note that the pseudo +`value` will always contain the colons preceding the pseudo identifier. This +is so that both `:before` and `::before` are properly represented in the AST. + +## Attribute nodes + +### `attribute.quoted` + +Returns `true` if the attribute's value is wrapped in quotation marks, false if it is not. +Remains `undefined` if there is no attribute value. + +```css +[href=foo] /* false */ +[href='foo'] /* true */ +[href="foo"] /* true */ +[href] /* undefined */ +``` + +### `attribute.qualifiedAttribute` + +Returns the attribute name qualified with the namespace if one is given. + +### `attribute.offsetOf(part)` + + Returns the offset of the attribute part specified relative to the + start of the node of the output string. This is useful in raising + error messages about a specific part of the attribute, especially + in combination with `attribute.sourceIndex`. + + Returns `-1` if the name is invalid or the value doesn't exist in this + attribute. + + The legal values for `part` are: + + * `"ns"` - alias for "namespace" + * `"namespace"` - the namespace if it exists. + * `"attribute"` - the attribute name + * `"attributeNS"` - the start of the attribute or its namespace + * `"operator"` - the match operator of the attribute + * `"value"` - The value (string or identifier) + * `"insensitive"` - the case insensitivity flag + +### `attribute.raws.unquoted` + +Returns the unquoted content of the attribute's value. +Remains `undefined` if there is no attribute value. + +```css +[href=foo] /* foo */ +[href='foo'] /* foo */ +[href="foo"] /* foo */ +[href] /* undefined */ +``` + +### `attribute.spaces` + +Like `node.spaces` with the `before` and `after` values containing the spaces +around the element, the parts of the attribute can also have spaces before +and after them. The for each of `attribute`, `operator`, `value` and +`insensitive` there is corresponding property of the same nam in +`node.spaces` that has an optional `before` or `after` string containing only +whitespace. + +Note that corresponding values in `attributes.raws.spaces` contain values +including any comments. If set, these values will override the +`attribute.spaces` value. Take care to remove them if changing +`attribute.spaces`. + +### `attribute.raws` + +The raws object stores comments and other information necessary to re-render +the node exactly as it was in the source. + +If a comment is embedded within the identifiers for the `namespace`, `attribute` +or `value` then a property is placed in the raws for that value containing the full source of the propery including comments. + +If a comment is embedded within the space between parts of the attribute +then the raw for that space is set accordingly. + +Setting an attribute's property `raws` value to be deleted. + +For now, changing the spaces required also updating or removing any of the +raws values that override them. + +Example: `[ /*before*/ href /* after-attr */ = /* after-operator */ te/*inside-value*/st/* wow */ /*omg*/i/*bbq*/ /*whodoesthis*/]` would parse as: + +```js +{ + attribute: "href", + operator: "=", + value: "test", + spaces: { + before: '', + after: '', + attribute: { before: ' ', after: ' ' }, + operator: { after: ' ' }, + value: { after: ' ' }, + insensitive: { after: ' ' } + }, + raws: { + spaces: { + attribute: { before: ' /*before*/ ', after: ' /* after-attr */ ' }, + operator: { after: ' /* after-operator */ ' }, + value: { after: '/* wow */ /*omg*/' }, + insensitive: { after: '/*bbq*/ /*whodoesthis*/' } + }, + unquoted: 'test', + value: 'te/*inside-value*/st' + } +} +``` + +## `Processor` + +### `ProcessorOptions` + +* `lossless` - When `true`, whitespace is preserved. Defaults to `true`. +* `updateSelector` - When `true`, if any processor methods are passed a postcss + `Rule` node instead of a string, then that Rule's selector is updated + with the results of the processing. Defaults to `true`. + +### `process|processSync(selectors, [options])` + +Processes the `selectors`, returning a string from the result of processing. + +Note: when the `updateSelector` option is set, the rule's selector +will be updated with the resulting string. + +**Example:** + +```js +const parser = require("postcss-selector-parser"); +const processor = parser(); + +let result = processor.processSync(' .class'); +console.log(result); +// => .class + +// Asynchronous operation +let promise = processor.process(' .class').then(result => { + console.log(result) + // => .class +}); + +// To have the parser normalize whitespace values, utilize the options +result = processor.processSync(' .class ', {lossless: false}); +console.log(result); +// => .class + +// For better syntax errors, pass a PostCSS Rule node. +const postcss = require('postcss'); +rule = postcss.rule({selector: ' #foo > a, .class '}); +processor.process(rule, {lossless: false, updateSelector: true}).then(result => { + console.log(result); + // => #foo>a,.class + console.log("rule:", rule.selector); + // => rule: #foo>a,.class +}) +``` + +Arguments: + +* `selectors (string|postcss.Rule)`: Either a selector string or a PostCSS Rule + node. +* `[options] (object)`: Process options + + +### `ast|astSync(selectors, [options])` + +Like `process()` and `processSync()` but after +processing the `selectors` these methods return the `Root` node of the result +instead of a string. + +Note: when the `updateSelector` option is set, the rule's selector +will be updated with the resulting string. + +### `transform|transformSync(selectors, [options])` + +Like `process()` and `processSync()` but after +processing the `selectors` these methods return the value returned by the +processor callback. + +Note: when the `updateSelector` option is set, the rule's selector +will be updated with the resulting string. + +### Error Handling Within Selector Processors + +The root node passed to the selector processor callback +has a method `error(message, options)` that returns an +error object. This method should always be used to raise +errors relating to the syntax of selectors. The options +to this method are passed to postcss's error constructor +([documentation](http://postcss.org/api/#container-error)). + +#### Async Error Example + +```js +let processor = (root) => { + return new Promise((resolve, reject) => { + root.walkClasses((classNode) => { + if (/^(.*)[-_]/.test(classNode.value)) { + let msg = "classes may not have underscores or dashes in them"; + reject(root.error(msg, { + index: classNode.sourceIndex + RegExp.$1.length + 1, + word: classNode.value + })); + } + }); + resolve(); + }); +}; + +const postcss = require("postcss"); +const parser = require("postcss-selector-parser"); +const selectorProcessor = parser(processor); +const plugin = postcss.plugin('classValidator', (options) => { + return (root) => { + let promises = []; + root.walkRules(rule => { + promises.push(selectorProcessor.process(rule)); + }); + return Promise.all(promises); + }; +}); +postcss(plugin()).process(` +.foo-bar { + color: red; +} +`.trim(), {from: 'test.css'}).catch((e) => console.error(e.toString())); + +// CssSyntaxError: classValidator: ./test.css:1:5: classes may not have underscores or dashes in them +// +// > 1 | .foo-bar { +// | ^ +// 2 | color: red; +// 3 | } +``` + +#### Synchronous Error Example + +```js +let processor = (root) => { + root.walkClasses((classNode) => { + if (/.*[-_]/.test(classNode.value)) { + let msg = "classes may not have underscores or dashes in them"; + throw root.error(msg, { + index: classNode.sourceIndex, + word: classNode.value + }); + } + }); +}; + +const postcss = require("postcss"); +const parser = require("postcss-selector-parser"); +const selectorProcessor = parser(processor); +const plugin = postcss.plugin('classValidator', (options) => { + return (root) => { + root.walkRules(rule => { + selectorProcessor.processSync(rule); + }); + }; +}); +postcss(plugin()).process(` +.foo-bar { + color: red; +} +`.trim(), {from: 'test.css'}).catch((e) => console.error(e.toString())); + +// CssSyntaxError: classValidator: ./test.css:1:5: classes may not have underscores or dashes in them +// +// > 1 | .foo-bar { +// | ^ +// 2 | color: red; +// 3 | } +``` diff --git a/node_modules/postcss-selector-parser/CHANGELOG.md b/node_modules/postcss-selector-parser/CHANGELOG.md new file mode 100644 index 0000000..14ffadc --- /dev/null +++ b/node_modules/postcss-selector-parser/CHANGELOG.md @@ -0,0 +1,549 @@ +# 6.1.2 + +- Fixed: erroneous trailing combinators in pseudos + +# 6.1.1 + +- Fixed: improve typings of constructor helpers (#292) + +# 6.1.0 + +- Feature: add `sourceIndex` to `Selector` nodes (#290) + +# 6.0.16 + +- Fixed: add missing `index` argument to `each`/`walk` callback types (#289) + +# 6.0.15 + +- Fixed: Node#prev and Node#next type for the first/last node + +# 6.0.14 + +- Fixed: type definitions + +# 6.0.13 + +- Fixed: throw on unexpected pipe symbols + +# 6.0.12 + +- Fixed: `clone` arguments should be optional + +# 6.0.11 + +- Fixed: parse attribute case insensitivity flag + +# 6.0.10 + +- Fixed: `isPseudoElement()` supports `:first-letter` and `:first-line` + +# 6.0.9 + +- Fixed: `Combinator.raws` property type + +# 6.0.8 + +- Fixed: reduced size + +# 6.0.7 + +- Fixed: parse animation percents + +# 6.0.6 + +- Fixed: parse quoted attributes containing a newline correctly + +# 6.0.5 + +- Perf: rework unesc for a 63+% performance boost + +# 6.0.4 + +- Fixed: ts errors + +# 6.0.3 + +- Fixed: replace node built-in "util" module with "util-deprecate" +- Fixed: handle uppercase pseudo elements +- Fixed: do not create invalid combinator before comment + +# 6.0.2 + +- Fixed an issue with parsing and stringifying an empty attribute value + +# 6.0.1 + +- Fixed an issue with unicode surrogate pair parsing + +# 6.0.0 + +- Updated: `cssesc` to 3.0.0 (major) +- Fixed: Issues with escaped `id` and `class` selectors + +# 5.0.0 + +- Allow escaped dot within class name. +- Update PostCSS to 7.0.7 (patch) + +# 5.0.0-rc.4 + +- Fixed an issue where comments immediately after an insensitive (in attribute) + were not parsed correctly. +- Updated `cssesc` to 2.0.0 (major). +- Removed outdated integration tests. +- Added tests for custom selectors, tags with attributes, the universal + selector with pseudos, and tokens after combinators. + +# 5.0.0-rc.1 + +To ease adoption of the v5.0 release, we have relaxed the node version +check performed by npm at installation time to allow for node 4, which +remains officially unsupported, but likely to continue working for the +time being. + +# 5.0.0-rc.0 + +This release has **BREAKING CHANGES** that were required to fix regressions +in 4.0.0 and to make the Combinator Node API consistent for all combinator +types. Please read carefully. + +## Summary of Changes + +* The way a descendent combinator that isn't a single space character (E.g. `.a .b`) is stored in the AST has changed. +* Named Combinators (E.g. `.a /for/ .b`) are now properly parsed as a combinator. +* It is now possible to look up a node based on the source location of a character in that node and to query nodes if they contain some character. +* Several bug fixes that caused the parser to hang and run out of memory when a `/` was encountered have been fixed. +* The minimum supported version of Node is now `v6.0.0`. + +### Changes to the Descendent Combinator + +In prior releases, the value of a descendant combinator with multiple spaces included all the spaces. + +* `.a .b`: Extra spaces are now stored as space before. + - Old & Busted: + - `combinator.value === " "` + - New hotness: + - `combinator.value === " " && combinator.spaces.before === " "` +* `.a /*comment*/.b`: A comment at the end of the combinator causes extra space to become after space. + - Old & Busted: + - `combinator.value === " "` + - `combinator.raws.value === " /*comment/"` + - New hotness: + - `combinator.value === " "` + - `combinator.spaces.after === " "` + - `combinator.raws.spaces.after === " /*comment*/"` +* `.a.b`: whitespace that doesn't start or end with a single space character is stored as a raw value. + - Old & Busted: + - `combinator.value === "\n"` + - `combinator.raws.value === undefined` + - New hotness: + - `combinator.value === " "` + - `combinator.raws.value === "\n"` + +### Support for "Named Combinators" + +Although, nonstandard and unlikely to ever become a standard, combinators like `/deep/` and `/for/` are now properly supported. + +Because they've been taken off the standardization track, there is no spec-official name for combinators of the form `//`. However, I talked to [Tab Atkins](https://twitter.com/tabatkins) and we agreed to call them "named combinators" so now they are called that. + +Before this release such named combinators were parsed without intention and generated three nodes of type `"tag"` where the first and last nodes had a value of `"/"`. + +* `.a /for/ .b` is parsed as a combinator. + - Old & Busted: + - `root.nodes[0].nodes[1].type === "tag"` + - `root.nodes[0].nodes[1].value === "/"` + - New hotness: + - `root.nodes[0].nodes[1].type === "combinator"` + - `root.nodes[0].nodes[1].value === "/for/"` +* `.a /F\6fR/ .b` escapes are handled and uppercase is normalized. + - Old & Busted: + - `root.nodes[0].nodes[2].type === "tag"` + - `root.nodes[0].nodes[2].value === "F\\6fR"` + - New hotness: + - `root.nodes[0].nodes[1].type === "combinator"` + - `root.nodes[0].nodes[1].value === "/for/"` + - `root.nodes[0].nodes[1].raws.value === "/F\\6fR/"` + +### Source position checks and lookups + +A new API was added to look up a node based on the source location. + +```js +const selectorParser = require("postcss-selector-parser"); +// You can find the most specific node for any given character +let combinator = selectorParser.astSync(".a > .b").atPosition(1,4); +combinator.toString() === " > "; +// You can check if a node includes a specific character +// Whitespace surrounding the node that is owned by that node +// is included in the check. +[2,3,4,5,6].map(column => combinator.isAtPosition(1, column)); +// => [false, true, true, true, false] +``` + +# 4.0.0 + +This release has **BREAKING CHANGES** that were required to fix bugs regarding values with escape sequences. Please read carefully. + +* **Identifiers with escapes** - CSS escape sequences are now hidden from the public API by default. + The normal value of a node like a class name or ID, or an aspect of a node such as attribute + selector's value, is unescaped. Escapes representing Non-ascii characters are unescaped into + unicode characters. For example: `bu\tton, .\31 00, #i\2764\FE0Fu, [attr="value is \"quoted\""]` + will parse respectively to the values `button`, `100`, `i❤️u`, `value is "quoted"`. + The original escape sequences for these values can be found in the corresponding property name + in `node.raws`. Where possible, deprecation warnings were added, but the nature + of escape handling makes it impossible to detect what is escaped or not. Our expectation is + that most users are neither expecting nor handling escape sequences in their use of this library, + and so for them, this is a bug fix. Users who are taking care to handle escapes correctly can + now update their code to remove the escape handling and let us do it for them. + +* **Mutating values with escapes** - When you make an update to a node property that has escape handling + The value is assumed to be unescaped, and any special characters are escaped automatically and + the corresponding `raws` value is immediately updated. This can result in changes to the original + escape format. Where the exact value of the escape sequence is important there are methods that + allow both values to be set in conjunction. There are a number of new convenience methods for + manipulating values that involve escapes, especially for attributes values where the quote mark + is involved. See https://github.com/postcss/postcss-selector-parser/pull/133 for an extensive + write-up on these changes. + + +**Upgrade/API Example** + +In `3.x` there was no unescape handling and internal consistency of several properties was the caller's job to maintain. It was very easy for the developer +to create a CSS file that did not parse correctly when some types of values +were in use. + +```js +const selectorParser = require("postcss-selector-parser"); +let attr = selectorParser.attribute({attribute: "id", operator: "=", value: "a-value"}); +attr.value; // => "a-value" +attr.toString(); // => [id=a-value] +// Add quotes to an attribute's value. +// All these values have to be set by the caller to be consistent: +// no internal consistency is maintained. +attr.raws.unquoted = attr.value +attr.value = "'" + attr.value + "'"; +attr.value; // => "'a-value'" +attr.quoted = true; +attr.toString(); // => "[id='a-value']" +``` + +In `4.0` there is a convenient API for setting and mutating values +that may need escaping. Especially for attributes. + +```js +const selectorParser = require("postcss-selector-parser"); + +// The constructor requires you specify the exact escape sequence +let className = selectorParser.className({value: "illegal class name", raws: {value: "illegal\\ class\\ name"}}); +className.toString(); // => '.illegal\\ class\\ name' + +// So it's better to set the value as a property +className = selectorParser.className(); +// Most properties that deal with identifiers work like this +className.value = "escape for me"; +className.value; // => 'escape for me' +className.toString(); // => '.escape\\ for\\ me' + +// emoji and all non-ascii are escaped to ensure it works in every css file. +className.value = "😱🦄😍"; +className.value; // => '😱🦄😍' +className.toString(); // => '.\\1F631\\1F984\\1F60D' + +// you can control the escape sequence if you want, or do bad bad things +className.setPropertyAndEscape('value', 'xxxx', 'yyyy'); +className.value; // => "xxxx" +className.toString(); // => ".yyyy" + +// Pass a value directly through to the css output without escaping it. +className.setPropertyWithoutEscape('value', '$REPLACE_ME$'); +className.value; // => "$REPLACE_ME$" +className.toString(); // => ".$REPLACE_ME$" + +// The biggest changes are to the Attribute class +// passing quoteMark explicitly is required to avoid a deprecation warning. +let attr = selectorParser.attribute({attribute: "id", operator: "=", value: "a-value", quoteMark: null}); +attr.toString(); // => "[id=a-value]" +// Get the value with quotes on it and any necessary escapes. +// This is the same as reading attr.value in 3.x. +attr.getQuotedValue(); // => "a-value"; +attr.quoteMark; // => null + +// Add quotes to an attribute's value. +attr.quoteMark = "'"; // This is all that's required. +attr.toString(); // => "[id='a-value']" +attr.quoted; // => true +// The value is still the same, only the quotes have changed. +attr.value; // => a-value +attr.getQuotedValue(); // => "'a-value'"; + +// deprecated assignment, no warning because there's no escapes +attr.value = "new-value"; +// no quote mark is needed so it is removed +attr.getQuotedValue(); // => "new-value"; + +// deprecated assignment, +attr.value = "\"a 'single quoted' value\""; +// > (node:27859) DeprecationWarning: Assigning an attribute a value containing characters that might need to be escaped is deprecated. Call attribute.setValue() instead. +attr.getQuotedValue(); // => '"a \'single quoted\' value"'; +// quote mark inferred from first and last characters. +attr.quoteMark; // => '"' + +// setValue takes options to make manipulating the value simple. +attr.setValue('foo', {smart: true}); +// foo doesn't require any escapes or quotes. +attr.toString(); // => '[id=foo]' +attr.quoteMark; // => null + +// An explicit quote mark can be specified +attr.setValue('foo', {quoteMark: '"'}); +attr.toString(); // => '[id="foo"]' + +// preserves quote mark by default +attr.setValue('bar'); +attr.toString(); // => '[id="bar"]' +attr.quoteMark = null; +attr.toString(); // => '[id=bar]' + +// with no arguments, it preserves quote mark even when it's not a great idea +attr.setValue('a value \n that should be quoted'); +attr.toString(); // => '[id=a\\ value\\ \\A\\ that\\ should\\ be\\ quoted]' + +// smart preservation with a specified default +attr.setValue('a value \n that should be quoted', {smart: true, preferCurrentQuoteMark: true, quoteMark: "'"}); +// => "[id='a value \\A that should be quoted']" +attr.quoteMark = '"'; +// => '[id="a value \\A that should be quoted"]' + +// this keeps double quotes because it wants to quote the value and the existing value has double quotes. +attr.setValue('this should be quoted', {smart: true, preferCurrentQuoteMark: true, quoteMark: "'"}); +// => '[id="this should be quoted"]' + +// picks single quotes because the value has double quotes +attr.setValue('a "double quoted" value', {smart: true, preferCurrentQuoteMark: true, quoteMark: "'"}); +// => "[id='a "double quoted" value']" + +// setPropertyAndEscape lets you do anything you want. Even things that are a bad idea and illegal. +attr.setPropertyAndEscape('value', 'xxxx', 'the password is 42'); +attr.value; // => "xxxx" +attr.toString(); // => "[id=the password is 42]" + +// Pass a value directly through to the css output without escaping it. +attr.setPropertyWithoutEscape('value', '$REPLACEMENT$'); +attr.value; // => "$REPLACEMENT$" +attr.toString(); // => "[id=$REPLACEMENT$]" +``` + +# 3.1.2 + +* Fix: Removed dot-prop dependency since it's no longer written in es5. + +# 3.1.1 + +* Fix: typescript definitions weren't in the published package. + +# 3.1.0 + +* Fixed numerous bugs in attribute nodes relating to the handling of comments + and whitespace. There's significant changes to `attrNode.spaces` and `attrNode.raws` since the `3.0.0` release. +* Added `Attribute#offsetOf(part)` to get the offset location of + attribute parts like `"operator"` and `"value"`. This is most + often added to `Attribute#sourceIndex` for error reporting. + +# 3.0.0 + +## Breaking changes + +* Some tweaks to the tokenizer/attribute selector parsing mean that whitespace + locations might be slightly different to the 2.x code. +* Better attribute selector parsing with more validation; postcss-selector-parser + no longer uses regular expressions to parse attribute selectors. +* Added an async API (thanks to @jacobp100); the default `process` API is now + async, and the sync API is now accessed through `processSync` instead. +* `process()` and `processSync()` now return a string instead of the Processor + instance. +* Tweaks handling of Less interpolation (thanks to @jwilsson). +* Removes support for Node 0.12. + +## Other changes + +* `ast()` and `astSync()` methods have been added to the `Processor`. These + return the `Root` node of the selectors after processing them. +* `transform()` and `transformSync()` methods have been added to the + `Processor`. These return the value returned by the processor callback + after processing the selectors. +* Set the parent when inserting a node (thanks to @chriseppstein). +* Correctly adjust indices when using insertBefore/insertAfter (thanks to @tivac). +* Fixes handling of namespaces with qualified tag selectors. +* `process`, `ast` and `transform` (and their sync variants) now accept a + `postcss` rule node. When provided, better errors are generated and selector + processing is automatically set back to the rule selector (unless the `updateSelector` option is set to `false`.) +* Now more memory efficient when tokenizing selectors. + +### Upgrade hints + +The pattern of: + +`rule.selector = processor.process(rule.selector).result.toString();` + +is now: + +`processor.processSync(rule)` + +# 2.2.3 + +* Resolves an issue where the parser would not reduce multiple spaces between an + ampersand and another simple selector in lossy mode (thanks to @adam-26). + +# 2.2.2 + +* No longer hangs on an unescaped semicolon; instead the parser will throw + an exception for these cases. + +# 2.2.1 + +* Allows a consumer to specify whitespace tokens when creating a new Node + (thanks to @Semigradsky). + +# 2.2.0 + +* Added a new option to normalize whitespace when parsing the selector string + (thanks to @adam-26). + +# 2.1.1 + +* Better unquoted value handling within attribute selectors + (thanks to @evilebottnawi). + +# 2.1.0 + +* Added: Use string constants for all node types & expose them on the main + parser instance (thanks to @Aweary). + +# 2.0.0 + +This release contains the following breaking changes: + +* Renamed all `eachInside` iterators to `walk`. For example, `eachTag` is now + `walkTags`, and `eachInside` is now `walk`. +* Renamed `Node#removeSelf()` to `Node#remove()`. +* Renamed `Container#remove()` to `Container#removeChild()`. +* Renamed `Node#raw` to `Node#raws` (thanks to @davidtheclark). +* Now parses `&` as the *nesting* selector, rather than a *tag* selector. +* Fixes misinterpretation of Sass interpolation (e.g. `#{foo}`) as an + id selector (thanks to @davidtheclark). + +and; + +* Fixes parsing of attribute selectors with equals signs in them + (e.g. `[data-attr="foo=bar"]`) (thanks to @montmanu). +* Adds `quoted` and `raw.unquoted` properties to attribute nodes + (thanks to @davidtheclark). + +# 1.3.3 + +* Fixes an infinite loop on `)` and `]` tokens when they had no opening pairs. + Now postcss-selector-parser will throw when it encounters these lone tokens. + +# 1.3.2 + +* Now uses plain integers rather than `str.charCodeAt(0)` for compiled builds. + +# 1.3.1 + +* Update flatten to v1.x (thanks to @shinnn). + +# 1.3.0 + +* Adds a new node type, `String`, to fix a crash on selectors such as + `foo:bar("test")`. + +# 1.2.1 + +* Fixes a crash when the parser encountered a trailing combinator. + +# 1.2.0 + +* A more descriptive error is thrown when the parser expects to find a + pseudo-class/pseudo-element (thanks to @ashelley). +* Adds support for line/column locations for selector nodes, as well as a + `Node#sourceIndex` method (thanks to @davidtheclark). + +# 1.1.4 + +* Fixes a crash when a selector started with a `>` combinator. The module will + now no longer throw if a selector has a leading/trailing combinator node. + +# 1.1.3 + +* Fixes a crash on `@` tokens. + +# 1.1.2 + +* Fixes an infinite loop caused by using parentheses in a non-pseudo element + context. + +# 1.1.1 + +* Fixes a crash when a backslash ended a selector string. + +# 1.1.0 + +* Adds support for replacing multiple nodes at once with `replaceWith` + (thanks to @jonathantneal). +* Parser no longer throws on sequential IDs and trailing commas, to support + parsing of selector hacks. + +# 1.0.1 + +* Fixes using `insertAfter` and `insertBefore` during iteration. + +# 1.0.0 + +* Adds `clone` and `replaceWith` methods to nodes. +* Adds `insertBefore` and `insertAfter` to containers. +* Stabilises API. + +# 0.0.5 + +* Fixes crash on extra whitespace inside a pseudo selector's parentheses. +* Adds sort function to the container class. +* Enables the parser to pass its input through without transforming. +* Iteration-safe `each` and `eachInside`. + +# 0.0.4 + +* Tidy up redundant duplication. +* Fixes a bug where the parser would loop infinitely on universal selectors + inside pseudo selectors. +* Adds `length` getter and `eachInside`, `map`, `reduce` to the container class. +* When a selector has been removed from the tree, the root node will no longer + cast it to a string. +* Adds node type iterators to the container class (e.g. `eachComment`). +* Adds filter function to the container class. +* Adds split function to the container class. +* Create new node types by doing `parser.id(opts)` etc. +* Adds support for pseudo classes anywhere in the selector. + +# 0.0.3 + +* Adds `next` and `prev` to the node class. +* Adds `first` and `last` getters to the container class. +* Adds `every` and `some` iterators to the container class. +* Add `empty` alias for `removeAll`. +* Combinators are now types of node. +* Fixes the at method so that it is not an alias for `index`. +* Tidy up creation of new nodes in the parser. +* Refactors how namespaces are handled for consistency & less redundant code. +* Refactors AST to use `nodes` exclusively, and eliminates excessive nesting. +* Fixes nested pseudo parsing. +* Fixes whitespace parsing. + +# 0.0.2 + +* Adds support for namespace selectors. +* Adds support for selectors joined by escaped spaces - such as `.\31\ 0`. + +# 0.0.1 + +* Initial release. diff --git a/node_modules/postcss-selector-parser/LICENSE-MIT b/node_modules/postcss-selector-parser/LICENSE-MIT new file mode 100644 index 0000000..fd0e863 --- /dev/null +++ b/node_modules/postcss-selector-parser/LICENSE-MIT @@ -0,0 +1,22 @@ +Copyright (c) Ben Briggs (http://beneb.info) + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/postcss-selector-parser/README.md b/node_modules/postcss-selector-parser/README.md new file mode 100644 index 0000000..28e44f2 --- /dev/null +++ b/node_modules/postcss-selector-parser/README.md @@ -0,0 +1,49 @@ +# postcss-selector-parser [![test](https://github.com/postcss/postcss-selector-parser/actions/workflows/test.yml/badge.svg)](https://github.com/postcss/postcss-selector-parser/actions/workflows/test.yml) + +> Selector parser with built in methods for working with selector strings. + +## Install + +With [npm](https://npmjs.com/package/postcss-selector-parser) do: + +``` +npm install postcss-selector-parser +``` + +## Quick Start + +```js +const parser = require('postcss-selector-parser'); +const transform = selectors => { + selectors.walk(selector => { + // do something with the selector + console.log(String(selector)) + }); +}; + +const transformed = parser(transform).processSync('h1, h2, h3'); +``` + +To normalize selector whitespace: + +```js +const parser = require('postcss-selector-parser'); +const normalized = parser().processSync('h1, h2, h3', {lossless: false}); +// -> h1,h2,h3 +``` + +Async support is provided through `parser.process` and will resolve a Promise +with the resulting selector string. + +## API + +Please see [API.md](API.md). + +## Credits + +* Huge thanks to Andrey Sitnik (@ai) for work on PostCSS which helped + accelerate this module's development. + +## License + +MIT diff --git a/node_modules/postcss-selector-parser/dist/index.js b/node_modules/postcss-selector-parser/dist/index.js new file mode 100644 index 0000000..995741a --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/index.js @@ -0,0 +1,17 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _processor = _interopRequireDefault(require("./processor")); +var selectors = _interopRequireWildcard(require("./selectors")); +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +var parser = function parser(processor) { + return new _processor["default"](processor); +}; +Object.assign(parser, selectors); +delete parser.__esModule; +var _default = parser; +exports["default"] = _default; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/parser.js b/node_modules/postcss-selector-parser/dist/parser.js new file mode 100644 index 0000000..ada6158 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/parser.js @@ -0,0 +1,1015 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _root = _interopRequireDefault(require("./selectors/root")); +var _selector = _interopRequireDefault(require("./selectors/selector")); +var _className = _interopRequireDefault(require("./selectors/className")); +var _comment = _interopRequireDefault(require("./selectors/comment")); +var _id = _interopRequireDefault(require("./selectors/id")); +var _tag = _interopRequireDefault(require("./selectors/tag")); +var _string = _interopRequireDefault(require("./selectors/string")); +var _pseudo = _interopRequireDefault(require("./selectors/pseudo")); +var _attribute = _interopRequireWildcard(require("./selectors/attribute")); +var _universal = _interopRequireDefault(require("./selectors/universal")); +var _combinator = _interopRequireDefault(require("./selectors/combinator")); +var _nesting = _interopRequireDefault(require("./selectors/nesting")); +var _sortAscending = _interopRequireDefault(require("./sortAscending")); +var _tokenize = _interopRequireWildcard(require("./tokenize")); +var tokens = _interopRequireWildcard(require("./tokenTypes")); +var types = _interopRequireWildcard(require("./selectors/types")); +var _util = require("./util"); +var _WHITESPACE_TOKENS, _Object$assign; +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS); +var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign)); +function tokenStart(token) { + return { + line: token[_tokenize.FIELDS.START_LINE], + column: token[_tokenize.FIELDS.START_COL] + }; +} +function tokenEnd(token) { + return { + line: token[_tokenize.FIELDS.END_LINE], + column: token[_tokenize.FIELDS.END_COL] + }; +} +function getSource(startLine, startColumn, endLine, endColumn) { + return { + start: { + line: startLine, + column: startColumn + }, + end: { + line: endLine, + column: endColumn + } + }; +} +function getTokenSource(token) { + return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]); +} +function getTokenSourceSpan(startToken, endToken) { + if (!startToken) { + return undefined; + } + return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]); +} +function unescapeProp(node, prop) { + var value = node[prop]; + if (typeof value !== "string") { + return; + } + if (value.indexOf("\\") !== -1) { + (0, _util.ensureObject)(node, 'raws'); + node[prop] = (0, _util.unesc)(value); + if (node.raws[prop] === undefined) { + node.raws[prop] = value; + } + } + return node; +} +function indexesOf(array, item) { + var i = -1; + var indexes = []; + while ((i = array.indexOf(item, i + 1)) !== -1) { + indexes.push(i); + } + return indexes; +} +function uniqs() { + var list = Array.prototype.concat.apply([], arguments); + return list.filter(function (item, i) { + return i === list.indexOf(item); + }); +} +var Parser = /*#__PURE__*/function () { + function Parser(rule, options) { + if (options === void 0) { + options = {}; + } + this.rule = rule; + this.options = Object.assign({ + lossy: false, + safe: false + }, options); + this.position = 0; + this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector; + this.tokens = (0, _tokenize["default"])({ + css: this.css, + error: this._errorGenerator(), + safe: this.options.safe + }); + var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]); + this.root = new _root["default"]({ + source: rootSource + }); + this.root.errorGenerator = this._errorGenerator(); + var selector = new _selector["default"]({ + source: { + start: { + line: 1, + column: 1 + } + }, + sourceIndex: 0 + }); + this.root.append(selector); + this.current = selector; + this.loop(); + } + var _proto = Parser.prototype; + _proto._errorGenerator = function _errorGenerator() { + var _this = this; + return function (message, errorOptions) { + if (typeof _this.rule === 'string') { + return new Error(message); + } + return _this.rule.error(message, errorOptions); + }; + }; + _proto.attribute = function attribute() { + var attr = []; + var startingToken = this.currToken; + this.position++; + while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) { + attr.push(this.currToken); + this.position++; + } + if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) { + return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]); + } + var len = attr.length; + var node = { + source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]), + sourceIndex: startingToken[_tokenize.FIELDS.START_POS] + }; + if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) { + return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]); + } + var pos = 0; + var spaceBefore = ''; + var commentBefore = ''; + var lastAdded = null; + var spaceAfterMeaningfulToken = false; + while (pos < len) { + var token = attr[pos]; + var content = this.content(token); + var next = attr[pos + 1]; + switch (token[_tokenize.FIELDS.TYPE]) { + case tokens.space: + // if ( + // len === 1 || + // pos === 0 && this.content(next) === '|' + // ) { + // return this.expected('attribute', token[TOKEN.START_POS], content); + // } + spaceAfterMeaningfulToken = true; + if (this.options.lossy) { + break; + } + if (lastAdded) { + (0, _util.ensureObject)(node, 'spaces', lastAdded); + var prevContent = node.spaces[lastAdded].after || ''; + node.spaces[lastAdded].after = prevContent + content; + var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null; + if (existingComment) { + node.raws.spaces[lastAdded].after = existingComment + content; + } + } else { + spaceBefore = spaceBefore + content; + commentBefore = commentBefore + content; + } + break; + case tokens.asterisk: + if (next[_tokenize.FIELDS.TYPE] === tokens.equals) { + node.operator = content; + lastAdded = 'operator'; + } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) { + if (spaceBefore) { + (0, _util.ensureObject)(node, 'spaces', 'attribute'); + node.spaces.attribute.before = spaceBefore; + spaceBefore = ''; + } + if (commentBefore) { + (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute'); + node.raws.spaces.attribute.before = spaceBefore; + commentBefore = ''; + } + node.namespace = (node.namespace || "") + content; + var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null; + if (rawValue) { + node.raws.namespace += content; + } + lastAdded = 'namespace'; + } + spaceAfterMeaningfulToken = false; + break; + case tokens.dollar: + if (lastAdded === "value") { + var oldRawValue = (0, _util.getProp)(node, 'raws', 'value'); + node.value += "$"; + if (oldRawValue) { + node.raws.value = oldRawValue + "$"; + } + break; + } + // Falls through + case tokens.caret: + if (next[_tokenize.FIELDS.TYPE] === tokens.equals) { + node.operator = content; + lastAdded = 'operator'; + } + spaceAfterMeaningfulToken = false; + break; + case tokens.combinator: + if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) { + node.operator = content; + lastAdded = 'operator'; + } + if (content !== '|') { + spaceAfterMeaningfulToken = false; + break; + } + if (next[_tokenize.FIELDS.TYPE] === tokens.equals) { + node.operator = content; + lastAdded = 'operator'; + } else if (!node.namespace && !node.attribute) { + node.namespace = true; + } + spaceAfterMeaningfulToken = false; + break; + case tokens.word: + if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals && + // this look-ahead probably fails with comment nodes involved. + !node.operator && !node.namespace) { + node.namespace = content; + lastAdded = 'namespace'; + } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) { + if (spaceBefore) { + (0, _util.ensureObject)(node, 'spaces', 'attribute'); + node.spaces.attribute.before = spaceBefore; + spaceBefore = ''; + } + if (commentBefore) { + (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute'); + node.raws.spaces.attribute.before = commentBefore; + commentBefore = ''; + } + node.attribute = (node.attribute || "") + content; + var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null; + if (_rawValue) { + node.raws.attribute += content; + } + lastAdded = 'attribute'; + } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) { + var _unescaped = (0, _util.unesc)(content); + var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || ''; + var oldValue = node.value || ''; + node.value = oldValue + _unescaped; + node.quoteMark = null; + if (_unescaped !== content || _oldRawValue) { + (0, _util.ensureObject)(node, 'raws'); + node.raws.value = (_oldRawValue || oldValue) + content; + } + lastAdded = 'value'; + } else { + var insensitive = content === 'i' || content === "I"; + if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) { + node.insensitive = insensitive; + if (!insensitive || content === "I") { + (0, _util.ensureObject)(node, 'raws'); + node.raws.insensitiveFlag = content; + } + lastAdded = 'insensitive'; + if (spaceBefore) { + (0, _util.ensureObject)(node, 'spaces', 'insensitive'); + node.spaces.insensitive.before = spaceBefore; + spaceBefore = ''; + } + if (commentBefore) { + (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive'); + node.raws.spaces.insensitive.before = commentBefore; + commentBefore = ''; + } + } else if (node.value || node.value === '') { + lastAdded = 'value'; + node.value += content; + if (node.raws.value) { + node.raws.value += content; + } + } + } + spaceAfterMeaningfulToken = false; + break; + case tokens.str: + if (!node.attribute || !node.operator) { + return this.error("Expected an attribute followed by an operator preceding the string.", { + index: token[_tokenize.FIELDS.START_POS] + }); + } + var _unescapeValue = (0, _attribute.unescapeValue)(content), + unescaped = _unescapeValue.unescaped, + quoteMark = _unescapeValue.quoteMark; + node.value = unescaped; + node.quoteMark = quoteMark; + lastAdded = 'value'; + (0, _util.ensureObject)(node, 'raws'); + node.raws.value = content; + spaceAfterMeaningfulToken = false; + break; + case tokens.equals: + if (!node.attribute) { + return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content); + } + if (node.value) { + return this.error('Unexpected "=" found; an operator was already defined.', { + index: token[_tokenize.FIELDS.START_POS] + }); + } + node.operator = node.operator ? node.operator + content : content; + lastAdded = 'operator'; + spaceAfterMeaningfulToken = false; + break; + case tokens.comment: + if (lastAdded) { + if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') { + var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || ''; + var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment; + (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded); + node.raws.spaces[lastAdded].after = rawLastComment + content; + } else { + var lastValue = node[lastAdded] || ''; + var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue; + (0, _util.ensureObject)(node, 'raws'); + node.raws[lastAdded] = rawLastValue + content; + } + } else { + commentBefore = commentBefore + content; + } + break; + default: + return this.error("Unexpected \"" + content + "\" found.", { + index: token[_tokenize.FIELDS.START_POS] + }); + } + pos++; + } + unescapeProp(node, "attribute"); + unescapeProp(node, "namespace"); + this.newNode(new _attribute["default"](node)); + this.position++; + } + + /** + * return a node containing meaningless garbage up to (but not including) the specified token position. + * if the token position is negative, all remaining tokens are consumed. + * + * This returns an array containing a single string node if all whitespace, + * otherwise an array of comment nodes with space before and after. + * + * These tokens are not added to the current selector, the caller can add them or use them to amend + * a previous node's space metadata. + * + * In lossy mode, this returns only comments. + */; + _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) { + if (stopPosition < 0) { + stopPosition = this.tokens.length; + } + var startPosition = this.position; + var nodes = []; + var space = ""; + var lastComment = undefined; + do { + if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) { + if (!this.options.lossy) { + space += this.content(); + } + } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) { + var spaces = {}; + if (space) { + spaces.before = space; + space = ""; + } + lastComment = new _comment["default"]({ + value: this.content(), + source: getTokenSource(this.currToken), + sourceIndex: this.currToken[_tokenize.FIELDS.START_POS], + spaces: spaces + }); + nodes.push(lastComment); + } + } while (++this.position < stopPosition); + if (space) { + if (lastComment) { + lastComment.spaces.after = space; + } else if (!this.options.lossy) { + var firstToken = this.tokens[startPosition]; + var lastToken = this.tokens[this.position - 1]; + nodes.push(new _string["default"]({ + value: '', + source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]), + sourceIndex: firstToken[_tokenize.FIELDS.START_POS], + spaces: { + before: space, + after: '' + } + })); + } + } + return nodes; + } + + /** + * + * @param {*} nodes + */; + _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) { + var _this2 = this; + if (requiredSpace === void 0) { + requiredSpace = false; + } + var space = ""; + var rawSpace = ""; + nodes.forEach(function (n) { + var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace); + var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace); + space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0); + rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0); + }); + if (rawSpace === space) { + rawSpace = undefined; + } + var result = { + space: space, + rawSpace: rawSpace + }; + return result; + }; + _proto.isNamedCombinator = function isNamedCombinator(position) { + if (position === void 0) { + position = this.position; + } + return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash; + }; + _proto.namedCombinator = function namedCombinator() { + if (this.isNamedCombinator()) { + var nameRaw = this.content(this.tokens[this.position + 1]); + var name = (0, _util.unesc)(nameRaw).toLowerCase(); + var raws = {}; + if (name !== nameRaw) { + raws.value = "/" + nameRaw + "/"; + } + var node = new _combinator["default"]({ + value: "/" + name + "/", + source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]), + sourceIndex: this.currToken[_tokenize.FIELDS.START_POS], + raws: raws + }); + this.position = this.position + 3; + return node; + } else { + this.unexpected(); + } + }; + _proto.combinator = function combinator() { + var _this3 = this; + if (this.content() === '|') { + return this.namespace(); + } + // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector. + var nextSigTokenPos = this.locateNextMeaningfulToken(this.position); + if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) { + var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos); + if (nodes.length > 0) { + var last = this.current.last; + if (last) { + var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes), + space = _this$convertWhitespa.space, + rawSpace = _this$convertWhitespa.rawSpace; + if (rawSpace !== undefined) { + last.rawSpaceAfter += rawSpace; + } + last.spaces.after += space; + } else { + nodes.forEach(function (n) { + return _this3.newNode(n); + }); + } + } + return; + } + var firstToken = this.currToken; + var spaceOrDescendantSelectorNodes = undefined; + if (nextSigTokenPos > this.position) { + spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos); + } + var node; + if (this.isNamedCombinator()) { + node = this.namedCombinator(); + } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) { + node = new _combinator["default"]({ + value: this.content(), + source: getTokenSource(this.currToken), + sourceIndex: this.currToken[_tokenize.FIELDS.START_POS] + }); + this.position++; + } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) { + // pass + } else if (!spaceOrDescendantSelectorNodes) { + this.unexpected(); + } + if (node) { + if (spaceOrDescendantSelectorNodes) { + var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes), + _space = _this$convertWhitespa2.space, + _rawSpace = _this$convertWhitespa2.rawSpace; + node.spaces.before = _space; + node.rawSpaceBefore = _rawSpace; + } + } else { + // descendant combinator + var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true), + _space2 = _this$convertWhitespa3.space, + _rawSpace2 = _this$convertWhitespa3.rawSpace; + if (!_rawSpace2) { + _rawSpace2 = _space2; + } + var spaces = {}; + var raws = { + spaces: {} + }; + if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) { + spaces.before = _space2.slice(0, _space2.length - 1); + raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1); + } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) { + spaces.after = _space2.slice(1); + raws.spaces.after = _rawSpace2.slice(1); + } else { + raws.value = _rawSpace2; + } + node = new _combinator["default"]({ + value: ' ', + source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]), + sourceIndex: firstToken[_tokenize.FIELDS.START_POS], + spaces: spaces, + raws: raws + }); + } + if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) { + node.spaces.after = this.optionalSpace(this.content()); + this.position++; + } + return this.newNode(node); + }; + _proto.comma = function comma() { + if (this.position === this.tokens.length - 1) { + this.root.trailingComma = true; + this.position++; + return; + } + this.current._inferEndPosition(); + var selector = new _selector["default"]({ + source: { + start: tokenStart(this.tokens[this.position + 1]) + }, + sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS] + }); + this.current.parent.append(selector); + this.current = selector; + this.position++; + }; + _proto.comment = function comment() { + var current = this.currToken; + this.newNode(new _comment["default"]({ + value: this.content(), + source: getTokenSource(current), + sourceIndex: current[_tokenize.FIELDS.START_POS] + })); + this.position++; + }; + _proto.error = function error(message, opts) { + throw this.root.error(message, opts); + }; + _proto.missingBackslash = function missingBackslash() { + return this.error('Expected a backslash preceding the semicolon.', { + index: this.currToken[_tokenize.FIELDS.START_POS] + }); + }; + _proto.missingParenthesis = function missingParenthesis() { + return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]); + }; + _proto.missingSquareBracket = function missingSquareBracket() { + return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]); + }; + _proto.unexpected = function unexpected() { + return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]); + }; + _proto.unexpectedPipe = function unexpectedPipe() { + return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]); + }; + _proto.namespace = function namespace() { + var before = this.prevToken && this.content(this.prevToken) || true; + if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) { + this.position++; + return this.word(before); + } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) { + this.position++; + return this.universal(before); + } + this.unexpectedPipe(); + }; + _proto.nesting = function nesting() { + if (this.nextToken) { + var nextContent = this.content(this.nextToken); + if (nextContent === "|") { + this.position++; + return; + } + } + var current = this.currToken; + this.newNode(new _nesting["default"]({ + value: this.content(), + source: getTokenSource(current), + sourceIndex: current[_tokenize.FIELDS.START_POS] + })); + this.position++; + }; + _proto.parentheses = function parentheses() { + var last = this.current.last; + var unbalanced = 1; + this.position++; + if (last && last.type === types.PSEUDO) { + var selector = new _selector["default"]({ + source: { + start: tokenStart(this.tokens[this.position]) + }, + sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS] + }); + var cache = this.current; + last.append(selector); + this.current = selector; + while (this.position < this.tokens.length && unbalanced) { + if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) { + unbalanced++; + } + if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) { + unbalanced--; + } + if (unbalanced) { + this.parse(); + } else { + this.current.source.end = tokenEnd(this.currToken); + this.current.parent.source.end = tokenEnd(this.currToken); + this.position++; + } + } + this.current = cache; + } else { + // I think this case should be an error. It's used to implement a basic parse of media queries + // but I don't think it's a good idea. + var parenStart = this.currToken; + var parenValue = "("; + var parenEnd; + while (this.position < this.tokens.length && unbalanced) { + if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) { + unbalanced++; + } + if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) { + unbalanced--; + } + parenEnd = this.currToken; + parenValue += this.parseParenthesisToken(this.currToken); + this.position++; + } + if (last) { + last.appendToPropertyAndEscape("value", parenValue, parenValue); + } else { + this.newNode(new _string["default"]({ + value: parenValue, + source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]), + sourceIndex: parenStart[_tokenize.FIELDS.START_POS] + })); + } + } + if (unbalanced) { + return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]); + } + }; + _proto.pseudo = function pseudo() { + var _this4 = this; + var pseudoStr = ''; + var startingToken = this.currToken; + while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) { + pseudoStr += this.content(); + this.position++; + } + if (!this.currToken) { + return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1); + } + if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) { + this.splitWord(false, function (first, length) { + pseudoStr += first; + _this4.newNode(new _pseudo["default"]({ + value: pseudoStr, + source: getTokenSourceSpan(startingToken, _this4.currToken), + sourceIndex: startingToken[_tokenize.FIELDS.START_POS] + })); + if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) { + _this4.error('Misplaced parenthesis.', { + index: _this4.nextToken[_tokenize.FIELDS.START_POS] + }); + } + }); + } else { + return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]); + } + }; + _proto.space = function space() { + var content = this.content(); + // Handle space before and after the selector + if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) { + return node.type === 'comment'; + })) { + this.spaces = this.optionalSpace(content); + this.position++; + } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) { + this.current.last.spaces.after = this.optionalSpace(content); + this.position++; + } else { + this.combinator(); + } + }; + _proto.string = function string() { + var current = this.currToken; + this.newNode(new _string["default"]({ + value: this.content(), + source: getTokenSource(current), + sourceIndex: current[_tokenize.FIELDS.START_POS] + })); + this.position++; + }; + _proto.universal = function universal(namespace) { + var nextToken = this.nextToken; + if (nextToken && this.content(nextToken) === '|') { + this.position++; + return this.namespace(); + } + var current = this.currToken; + this.newNode(new _universal["default"]({ + value: this.content(), + source: getTokenSource(current), + sourceIndex: current[_tokenize.FIELDS.START_POS] + }), namespace); + this.position++; + }; + _proto.splitWord = function splitWord(namespace, firstCallback) { + var _this5 = this; + var nextToken = this.nextToken; + var word = this.content(); + while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) { + this.position++; + var current = this.content(); + word += current; + if (current.lastIndexOf('\\') === current.length - 1) { + var next = this.nextToken; + if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) { + word += this.requiredSpace(this.content(next)); + this.position++; + } + } + nextToken = this.nextToken; + } + var hasClass = indexesOf(word, '.').filter(function (i) { + // Allow escaped dot within class name + var escapedDot = word[i - 1] === '\\'; + // Allow decimal numbers percent in @keyframes + var isKeyframesPercent = /^\d+\.\d+%$/.test(word); + return !escapedDot && !isKeyframesPercent; + }); + var hasId = indexesOf(word, '#').filter(function (i) { + return word[i - 1] !== '\\'; + }); + // Eliminate Sass interpolations from the list of id indexes + var interpolations = indexesOf(word, '#{'); + if (interpolations.length) { + hasId = hasId.filter(function (hashIndex) { + return !~interpolations.indexOf(hashIndex); + }); + } + var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId))); + indices.forEach(function (ind, i) { + var index = indices[i + 1] || word.length; + var value = word.slice(ind, index); + if (i === 0 && firstCallback) { + return firstCallback.call(_this5, value, indices.length); + } + var node; + var current = _this5.currToken; + var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i]; + var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1)); + if (~hasClass.indexOf(ind)) { + var classNameOpts = { + value: value.slice(1), + source: source, + sourceIndex: sourceIndex + }; + node = new _className["default"](unescapeProp(classNameOpts, "value")); + } else if (~hasId.indexOf(ind)) { + var idOpts = { + value: value.slice(1), + source: source, + sourceIndex: sourceIndex + }; + node = new _id["default"](unescapeProp(idOpts, "value")); + } else { + var tagOpts = { + value: value, + source: source, + sourceIndex: sourceIndex + }; + unescapeProp(tagOpts, "value"); + node = new _tag["default"](tagOpts); + } + _this5.newNode(node, namespace); + // Ensure that the namespace is used only once + namespace = null; + }); + this.position++; + }; + _proto.word = function word(namespace) { + var nextToken = this.nextToken; + if (nextToken && this.content(nextToken) === '|') { + this.position++; + return this.namespace(); + } + return this.splitWord(namespace); + }; + _proto.loop = function loop() { + while (this.position < this.tokens.length) { + this.parse(true); + } + this.current._inferEndPosition(); + return this.root; + }; + _proto.parse = function parse(throwOnParenthesis) { + switch (this.currToken[_tokenize.FIELDS.TYPE]) { + case tokens.space: + this.space(); + break; + case tokens.comment: + this.comment(); + break; + case tokens.openParenthesis: + this.parentheses(); + break; + case tokens.closeParenthesis: + if (throwOnParenthesis) { + this.missingParenthesis(); + } + break; + case tokens.openSquare: + this.attribute(); + break; + case tokens.dollar: + case tokens.caret: + case tokens.equals: + case tokens.word: + this.word(); + break; + case tokens.colon: + this.pseudo(); + break; + case tokens.comma: + this.comma(); + break; + case tokens.asterisk: + this.universal(); + break; + case tokens.ampersand: + this.nesting(); + break; + case tokens.slash: + case tokens.combinator: + this.combinator(); + break; + case tokens.str: + this.string(); + break; + // These cases throw; no break needed. + case tokens.closeSquare: + this.missingSquareBracket(); + case tokens.semicolon: + this.missingBackslash(); + default: + this.unexpected(); + } + } + + /** + * Helpers + */; + _proto.expected = function expected(description, index, found) { + if (Array.isArray(description)) { + var last = description.pop(); + description = description.join(', ') + " or " + last; + } + var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a'; + if (!found) { + return this.error("Expected " + an + " " + description + ".", { + index: index + }); + } + return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", { + index: index + }); + }; + _proto.requiredSpace = function requiredSpace(space) { + return this.options.lossy ? ' ' : space; + }; + _proto.optionalSpace = function optionalSpace(space) { + return this.options.lossy ? '' : space; + }; + _proto.lossySpace = function lossySpace(space, required) { + if (this.options.lossy) { + return required ? ' ' : ''; + } else { + return space; + } + }; + _proto.parseParenthesisToken = function parseParenthesisToken(token) { + var content = this.content(token); + if (token[_tokenize.FIELDS.TYPE] === tokens.space) { + return this.requiredSpace(content); + } else { + return content; + } + }; + _proto.newNode = function newNode(node, namespace) { + if (namespace) { + if (/^ +$/.test(namespace)) { + if (!this.options.lossy) { + this.spaces = (this.spaces || '') + namespace; + } + namespace = true; + } + node.namespace = namespace; + unescapeProp(node, "namespace"); + } + if (this.spaces) { + node.spaces.before = this.spaces; + this.spaces = ''; + } + return this.current.append(node); + }; + _proto.content = function content(token) { + if (token === void 0) { + token = this.currToken; + } + return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]); + }; + /** + * returns the index of the next non-whitespace, non-comment token. + * returns -1 if no meaningful token is found. + */ + _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) { + if (startPosition === void 0) { + startPosition = this.position + 1; + } + var searchPosition = startPosition; + while (searchPosition < this.tokens.length) { + if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) { + searchPosition++; + continue; + } else { + return searchPosition; + } + } + return -1; + }; + _createClass(Parser, [{ + key: "currToken", + get: function get() { + return this.tokens[this.position]; + } + }, { + key: "nextToken", + get: function get() { + return this.tokens[this.position + 1]; + } + }, { + key: "prevToken", + get: function get() { + return this.tokens[this.position - 1]; + } + }]); + return Parser; +}(); +exports["default"] = Parser; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/processor.js b/node_modules/postcss-selector-parser/dist/processor.js new file mode 100644 index 0000000..dbfa091 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/processor.js @@ -0,0 +1,170 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _parser = _interopRequireDefault(require("./parser")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +var Processor = /*#__PURE__*/function () { + function Processor(func, options) { + this.func = func || function noop() {}; + this.funcRes = null; + this.options = options; + } + var _proto = Processor.prototype; + _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) { + if (options === void 0) { + options = {}; + } + var merged = Object.assign({}, this.options, options); + if (merged.updateSelector === false) { + return false; + } else { + return typeof rule !== "string"; + } + }; + _proto._isLossy = function _isLossy(options) { + if (options === void 0) { + options = {}; + } + var merged = Object.assign({}, this.options, options); + if (merged.lossless === false) { + return true; + } else { + return false; + } + }; + _proto._root = function _root(rule, options) { + if (options === void 0) { + options = {}; + } + var parser = new _parser["default"](rule, this._parseOptions(options)); + return parser.root; + }; + _proto._parseOptions = function _parseOptions(options) { + return { + lossy: this._isLossy(options) + }; + }; + _proto._run = function _run(rule, options) { + var _this = this; + if (options === void 0) { + options = {}; + } + return new Promise(function (resolve, reject) { + try { + var root = _this._root(rule, options); + Promise.resolve(_this.func(root)).then(function (transform) { + var string = undefined; + if (_this._shouldUpdateSelector(rule, options)) { + string = root.toString(); + rule.selector = string; + } + return { + transform: transform, + root: root, + string: string + }; + }).then(resolve, reject); + } catch (e) { + reject(e); + return; + } + }); + }; + _proto._runSync = function _runSync(rule, options) { + if (options === void 0) { + options = {}; + } + var root = this._root(rule, options); + var transform = this.func(root); + if (transform && typeof transform.then === "function") { + throw new Error("Selector processor returned a promise to a synchronous call."); + } + var string = undefined; + if (options.updateSelector && typeof rule !== "string") { + string = root.toString(); + rule.selector = string; + } + return { + transform: transform, + root: root, + string: string + }; + } + + /** + * Process rule into a selector AST. + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {Promise} The AST of the selector after processing it. + */; + _proto.ast = function ast(rule, options) { + return this._run(rule, options).then(function (result) { + return result.root; + }); + } + + /** + * Process rule into a selector AST synchronously. + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {parser.Root} The AST of the selector after processing it. + */; + _proto.astSync = function astSync(rule, options) { + return this._runSync(rule, options).root; + } + + /** + * Process a selector into a transformed value asynchronously + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {Promise} The value returned by the processor. + */; + _proto.transform = function transform(rule, options) { + return this._run(rule, options).then(function (result) { + return result.transform; + }); + } + + /** + * Process a selector into a transformed value synchronously. + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {any} The value returned by the processor. + */; + _proto.transformSync = function transformSync(rule, options) { + return this._runSync(rule, options).transform; + } + + /** + * Process a selector into a new selector string asynchronously. + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {string} the selector after processing. + */; + _proto.process = function process(rule, options) { + return this._run(rule, options).then(function (result) { + return result.string || result.root.toString(); + }); + } + + /** + * Process a selector into a new selector string synchronously. + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {string} the selector after processing. + */; + _proto.processSync = function processSync(rule, options) { + var result = this._runSync(rule, options); + return result.string || result.root.toString(); + }; + return Processor; +}(); +exports["default"] = Processor; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/attribute.js b/node_modules/postcss-selector-parser/dist/selectors/attribute.js new file mode 100644 index 0000000..0351a22 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/attribute.js @@ -0,0 +1,448 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +exports.unescapeValue = unescapeValue; +var _cssesc = _interopRequireDefault(require("cssesc")); +var _unesc = _interopRequireDefault(require("../util/unesc")); +var _namespace = _interopRequireDefault(require("./namespace")); +var _types = require("./types"); +var _CSSESC_QUOTE_OPTIONS; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var deprecate = require("util-deprecate"); +var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/; +var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead."); +var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead."); +var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now."); +function unescapeValue(value) { + var deprecatedUsage = false; + var quoteMark = null; + var unescaped = value; + var m = unescaped.match(WRAPPED_IN_QUOTES); + if (m) { + quoteMark = m[1]; + unescaped = m[2]; + } + unescaped = (0, _unesc["default"])(unescaped); + if (unescaped !== value) { + deprecatedUsage = true; + } + return { + deprecatedUsage: deprecatedUsage, + unescaped: unescaped, + quoteMark: quoteMark + }; +} +function handleDeprecatedContructorOpts(opts) { + if (opts.quoteMark !== undefined) { + return opts; + } + if (opts.value === undefined) { + return opts; + } + warnOfDeprecatedConstructor(); + var _unescapeValue = unescapeValue(opts.value), + quoteMark = _unescapeValue.quoteMark, + unescaped = _unescapeValue.unescaped; + if (!opts.raws) { + opts.raws = {}; + } + if (opts.raws.value === undefined) { + opts.raws.value = opts.value; + } + opts.value = unescaped; + opts.quoteMark = quoteMark; + return opts; +} +var Attribute = /*#__PURE__*/function (_Namespace) { + _inheritsLoose(Attribute, _Namespace); + function Attribute(opts) { + var _this; + if (opts === void 0) { + opts = {}; + } + _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this; + _this.type = _types.ATTRIBUTE; + _this.raws = _this.raws || {}; + Object.defineProperty(_this.raws, 'unquoted', { + get: deprecate(function () { + return _this.value; + }, "attr.raws.unquoted is deprecated. Call attr.value instead."), + set: deprecate(function () { + return _this.value; + }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.") + }); + _this._constructed = true; + return _this; + } + + /** + * Returns the Attribute's value quoted such that it would be legal to use + * in the value of a css file. The original value's quotation setting + * used for stringification is left unchanged. See `setValue(value, options)` + * if you want to control the quote settings of a new value for the attribute. + * + * You can also change the quotation used for the current value by setting quoteMark. + * + * Options: + * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this + * option is not set, the original value for quoteMark will be used. If + * indeterminate, a double quote is used. The legal values are: + * * `null` - the value will be unquoted and characters will be escaped as necessary. + * * `'` - the value will be quoted with a single quote and single quotes are escaped. + * * `"` - the value will be quoted with a double quote and double quotes are escaped. + * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark + * over the quoteMark option value. + * * smart {boolean} - if true, will select a quote mark based on the value + * and the other options specified here. See the `smartQuoteMark()` + * method. + **/ + var _proto = Attribute.prototype; + _proto.getQuotedValue = function getQuotedValue(options) { + if (options === void 0) { + options = {}; + } + var quoteMark = this._determineQuoteMark(options); + var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark]; + var escaped = (0, _cssesc["default"])(this._value, cssescopts); + return escaped; + }; + _proto._determineQuoteMark = function _determineQuoteMark(options) { + return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options); + } + + /** + * Set the unescaped value with the specified quotation options. The value + * provided must not include any wrapping quote marks -- those quotes will + * be interpreted as part of the value and escaped accordingly. + */; + _proto.setValue = function setValue(value, options) { + if (options === void 0) { + options = {}; + } + this._value = value; + this._quoteMark = this._determineQuoteMark(options); + this._syncRawValue(); + } + + /** + * Intelligently select a quoteMark value based on the value's contents. If + * the value is a legal CSS ident, it will not be quoted. Otherwise a quote + * mark will be picked that minimizes the number of escapes. + * + * If there's no clear winner, the quote mark from these options is used, + * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is + * true). If the quoteMark is unspecified, a double quote is used. + * + * @param options This takes the quoteMark and preferCurrentQuoteMark options + * from the quoteValue method. + */; + _proto.smartQuoteMark = function smartQuoteMark(options) { + var v = this.value; + var numSingleQuotes = v.replace(/[^']/g, '').length; + var numDoubleQuotes = v.replace(/[^"]/g, '').length; + if (numSingleQuotes + numDoubleQuotes === 0) { + var escaped = (0, _cssesc["default"])(v, { + isIdentifier: true + }); + if (escaped === v) { + return Attribute.NO_QUOTE; + } else { + var pref = this.preferredQuoteMark(options); + if (pref === Attribute.NO_QUOTE) { + // pick a quote mark that isn't none and see if it's smaller + var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE; + var opts = CSSESC_QUOTE_OPTIONS[quote]; + var quoteValue = (0, _cssesc["default"])(v, opts); + if (quoteValue.length < escaped.length) { + return quote; + } + } + return pref; + } + } else if (numDoubleQuotes === numSingleQuotes) { + return this.preferredQuoteMark(options); + } else if (numDoubleQuotes < numSingleQuotes) { + return Attribute.DOUBLE_QUOTE; + } else { + return Attribute.SINGLE_QUOTE; + } + } + + /** + * Selects the preferred quote mark based on the options and the current quote mark value. + * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)` + * instead. + */; + _proto.preferredQuoteMark = function preferredQuoteMark(options) { + var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark; + if (quoteMark === undefined) { + quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark; + } + if (quoteMark === undefined) { + quoteMark = Attribute.DOUBLE_QUOTE; + } + return quoteMark; + }; + _proto._syncRawValue = function _syncRawValue() { + var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]); + if (rawValue === this._value) { + if (this.raws) { + delete this.raws.value; + } + } else { + this.raws.value = rawValue; + } + }; + _proto._handleEscapes = function _handleEscapes(prop, value) { + if (this._constructed) { + var escaped = (0, _cssesc["default"])(value, { + isIdentifier: true + }); + if (escaped !== value) { + this.raws[prop] = escaped; + } else { + delete this.raws[prop]; + } + } + }; + _proto._spacesFor = function _spacesFor(name) { + var attrSpaces = { + before: '', + after: '' + }; + var spaces = this.spaces[name] || {}; + var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {}; + return Object.assign(attrSpaces, spaces, rawSpaces); + }; + _proto._stringFor = function _stringFor(name, spaceName, concat) { + if (spaceName === void 0) { + spaceName = name; + } + if (concat === void 0) { + concat = defaultAttrConcat; + } + var attrSpaces = this._spacesFor(spaceName); + return concat(this.stringifyProperty(name), attrSpaces); + } + + /** + * returns the offset of the attribute part specified relative to the + * start of the node of the output string. + * + * * "ns" - alias for "namespace" + * * "namespace" - the namespace if it exists. + * * "attribute" - the attribute name + * * "attributeNS" - the start of the attribute or its namespace + * * "operator" - the match operator of the attribute + * * "value" - The value (string or identifier) + * * "insensitive" - the case insensitivity flag; + * @param part One of the possible values inside an attribute. + * @returns -1 if the name is invalid or the value doesn't exist in this attribute. + */; + _proto.offsetOf = function offsetOf(name) { + var count = 1; + var attributeSpaces = this._spacesFor("attribute"); + count += attributeSpaces.before.length; + if (name === "namespace" || name === "ns") { + return this.namespace ? count : -1; + } + if (name === "attributeNS") { + return count; + } + count += this.namespaceString.length; + if (this.namespace) { + count += 1; + } + if (name === "attribute") { + return count; + } + count += this.stringifyProperty("attribute").length; + count += attributeSpaces.after.length; + var operatorSpaces = this._spacesFor("operator"); + count += operatorSpaces.before.length; + var operator = this.stringifyProperty("operator"); + if (name === "operator") { + return operator ? count : -1; + } + count += operator.length; + count += operatorSpaces.after.length; + var valueSpaces = this._spacesFor("value"); + count += valueSpaces.before.length; + var value = this.stringifyProperty("value"); + if (name === "value") { + return value ? count : -1; + } + count += value.length; + count += valueSpaces.after.length; + var insensitiveSpaces = this._spacesFor("insensitive"); + count += insensitiveSpaces.before.length; + if (name === "insensitive") { + return this.insensitive ? count : -1; + } + return -1; + }; + _proto.toString = function toString() { + var _this2 = this; + var selector = [this.rawSpaceBefore, '[']; + selector.push(this._stringFor('qualifiedAttribute', 'attribute')); + if (this.operator && (this.value || this.value === '')) { + selector.push(this._stringFor('operator')); + selector.push(this._stringFor('value')); + selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) { + if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) { + attrSpaces.before = " "; + } + return defaultAttrConcat(attrValue, attrSpaces); + })); + } + selector.push(']'); + selector.push(this.rawSpaceAfter); + return selector.join(''); + }; + _createClass(Attribute, [{ + key: "quoted", + get: function get() { + var qm = this.quoteMark; + return qm === "'" || qm === '"'; + }, + set: function set(value) { + warnOfDeprecatedQuotedAssignment(); + } + + /** + * returns a single (`'`) or double (`"`) quote character if the value is quoted. + * returns `null` if the value is not quoted. + * returns `undefined` if the quotation state is unknown (this can happen when + * the attribute is constructed without specifying a quote mark.) + */ + }, { + key: "quoteMark", + get: function get() { + return this._quoteMark; + } + + /** + * Set the quote mark to be used by this attribute's value. + * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute + * value is updated accordingly. + * + * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted. + */, + set: function set(quoteMark) { + if (!this._constructed) { + this._quoteMark = quoteMark; + return; + } + if (this._quoteMark !== quoteMark) { + this._quoteMark = quoteMark; + this._syncRawValue(); + } + } + }, { + key: "qualifiedAttribute", + get: function get() { + return this.qualifiedName(this.raws.attribute || this.attribute); + } + }, { + key: "insensitiveFlag", + get: function get() { + return this.insensitive ? 'i' : ''; + } + }, { + key: "value", + get: function get() { + return this._value; + }, + set: + /** + * Before 3.0, the value had to be set to an escaped value including any wrapped + * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value + * is unescaped during parsing and any quote marks are removed. + * + * Because the ambiguity of this semantic change, if you set `attr.value = newValue`, + * a deprecation warning is raised when the new value contains any characters that would + * require escaping (including if it contains wrapped quotes). + * + * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe + * how the new value is quoted. + */ + function set(v) { + if (this._constructed) { + var _unescapeValue2 = unescapeValue(v), + deprecatedUsage = _unescapeValue2.deprecatedUsage, + unescaped = _unescapeValue2.unescaped, + quoteMark = _unescapeValue2.quoteMark; + if (deprecatedUsage) { + warnOfDeprecatedValueAssignment(); + } + if (unescaped === this._value && quoteMark === this._quoteMark) { + return; + } + this._value = unescaped; + this._quoteMark = quoteMark; + this._syncRawValue(); + } else { + this._value = v; + } + } + }, { + key: "insensitive", + get: function get() { + return this._insensitive; + } + + /** + * Set the case insensitive flag. + * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag` + * of the attribute is updated accordingly. + * + * @param {true | false} insensitive true if the attribute should match case-insensitively. + */, + set: function set(insensitive) { + if (!insensitive) { + this._insensitive = false; + + // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation. + // When setting `attr.insensitive = false` both should be erased to ensure correct serialization. + if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) { + this.raws.insensitiveFlag = undefined; + } + } + this._insensitive = insensitive; + } + }, { + key: "attribute", + get: function get() { + return this._attribute; + }, + set: function set(name) { + this._handleEscapes("attribute", name); + this._attribute = name; + } + }]); + return Attribute; +}(_namespace["default"]); +exports["default"] = Attribute; +Attribute.NO_QUOTE = null; +Attribute.SINGLE_QUOTE = "'"; +Attribute.DOUBLE_QUOTE = '"'; +var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = { + "'": { + quotes: 'single', + wrap: true + }, + '"': { + quotes: 'double', + wrap: true + } +}, _CSSESC_QUOTE_OPTIONS[null] = { + isIdentifier: true +}, _CSSESC_QUOTE_OPTIONS); +function defaultAttrConcat(attrValue, attrSpaces) { + return "" + attrSpaces.before + attrValue + attrSpaces.after; +} \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/className.js b/node_modules/postcss-selector-parser/dist/selectors/className.js new file mode 100644 index 0000000..af32597 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/className.js @@ -0,0 +1,50 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _cssesc = _interopRequireDefault(require("cssesc")); +var _util = require("../util"); +var _node = _interopRequireDefault(require("./node")); +var _types = require("./types"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var ClassName = /*#__PURE__*/function (_Node) { + _inheritsLoose(ClassName, _Node); + function ClassName(opts) { + var _this; + _this = _Node.call(this, opts) || this; + _this.type = _types.CLASS; + _this._constructed = true; + return _this; + } + var _proto = ClassName.prototype; + _proto.valueToString = function valueToString() { + return '.' + _Node.prototype.valueToString.call(this); + }; + _createClass(ClassName, [{ + key: "value", + get: function get() { + return this._value; + }, + set: function set(v) { + if (this._constructed) { + var escaped = (0, _cssesc["default"])(v, { + isIdentifier: true + }); + if (escaped !== v) { + (0, _util.ensureObject)(this, "raws"); + this.raws.value = escaped; + } else if (this.raws) { + delete this.raws.value; + } + } + this._value = v; + } + }]); + return ClassName; +}(_node["default"]); +exports["default"] = ClassName; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/combinator.js b/node_modules/postcss-selector-parser/dist/selectors/combinator.js new file mode 100644 index 0000000..c6449f4 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/combinator.js @@ -0,0 +1,21 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _node = _interopRequireDefault(require("./node")); +var _types = require("./types"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var Combinator = /*#__PURE__*/function (_Node) { + _inheritsLoose(Combinator, _Node); + function Combinator(opts) { + var _this; + _this = _Node.call(this, opts) || this; + _this.type = _types.COMBINATOR; + return _this; + } + return Combinator; +}(_node["default"]); +exports["default"] = Combinator; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/comment.js b/node_modules/postcss-selector-parser/dist/selectors/comment.js new file mode 100644 index 0000000..1709d5b --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/comment.js @@ -0,0 +1,21 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _node = _interopRequireDefault(require("./node")); +var _types = require("./types"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var Comment = /*#__PURE__*/function (_Node) { + _inheritsLoose(Comment, _Node); + function Comment(opts) { + var _this; + _this = _Node.call(this, opts) || this; + _this.type = _types.COMMENT; + return _this; + } + return Comment; +}(_node["default"]); +exports["default"] = Comment; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/constructors.js b/node_modules/postcss-selector-parser/dist/selectors/constructors.js new file mode 100644 index 0000000..6882593 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/constructors.js @@ -0,0 +1,65 @@ +"use strict"; + +exports.__esModule = true; +exports.universal = exports.tag = exports.string = exports.selector = exports.root = exports.pseudo = exports.nesting = exports.id = exports.comment = exports.combinator = exports.className = exports.attribute = void 0; +var _attribute = _interopRequireDefault(require("./attribute")); +var _className = _interopRequireDefault(require("./className")); +var _combinator = _interopRequireDefault(require("./combinator")); +var _comment = _interopRequireDefault(require("./comment")); +var _id = _interopRequireDefault(require("./id")); +var _nesting = _interopRequireDefault(require("./nesting")); +var _pseudo = _interopRequireDefault(require("./pseudo")); +var _root = _interopRequireDefault(require("./root")); +var _selector = _interopRequireDefault(require("./selector")); +var _string = _interopRequireDefault(require("./string")); +var _tag = _interopRequireDefault(require("./tag")); +var _universal = _interopRequireDefault(require("./universal")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +var attribute = function attribute(opts) { + return new _attribute["default"](opts); +}; +exports.attribute = attribute; +var className = function className(opts) { + return new _className["default"](opts); +}; +exports.className = className; +var combinator = function combinator(opts) { + return new _combinator["default"](opts); +}; +exports.combinator = combinator; +var comment = function comment(opts) { + return new _comment["default"](opts); +}; +exports.comment = comment; +var id = function id(opts) { + return new _id["default"](opts); +}; +exports.id = id; +var nesting = function nesting(opts) { + return new _nesting["default"](opts); +}; +exports.nesting = nesting; +var pseudo = function pseudo(opts) { + return new _pseudo["default"](opts); +}; +exports.pseudo = pseudo; +var root = function root(opts) { + return new _root["default"](opts); +}; +exports.root = root; +var selector = function selector(opts) { + return new _selector["default"](opts); +}; +exports.selector = selector; +var string = function string(opts) { + return new _string["default"](opts); +}; +exports.string = string; +var tag = function tag(opts) { + return new _tag["default"](opts); +}; +exports.tag = tag; +var universal = function universal(opts) { + return new _universal["default"](opts); +}; +exports.universal = universal; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/container.js b/node_modules/postcss-selector-parser/dist/selectors/container.js new file mode 100644 index 0000000..8600c54 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/container.js @@ -0,0 +1,308 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _node = _interopRequireDefault(require("./node")); +var types = _interopRequireWildcard(require("./types")); +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var Container = /*#__PURE__*/function (_Node) { + _inheritsLoose(Container, _Node); + function Container(opts) { + var _this; + _this = _Node.call(this, opts) || this; + if (!_this.nodes) { + _this.nodes = []; + } + return _this; + } + var _proto = Container.prototype; + _proto.append = function append(selector) { + selector.parent = this; + this.nodes.push(selector); + return this; + }; + _proto.prepend = function prepend(selector) { + selector.parent = this; + this.nodes.unshift(selector); + return this; + }; + _proto.at = function at(index) { + return this.nodes[index]; + }; + _proto.index = function index(child) { + if (typeof child === 'number') { + return child; + } + return this.nodes.indexOf(child); + }; + _proto.removeChild = function removeChild(child) { + child = this.index(child); + this.at(child).parent = undefined; + this.nodes.splice(child, 1); + var index; + for (var id in this.indexes) { + index = this.indexes[id]; + if (index >= child) { + this.indexes[id] = index - 1; + } + } + return this; + }; + _proto.removeAll = function removeAll() { + for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) { + var node = _step.value; + node.parent = undefined; + } + this.nodes = []; + return this; + }; + _proto.empty = function empty() { + return this.removeAll(); + }; + _proto.insertAfter = function insertAfter(oldNode, newNode) { + newNode.parent = this; + var oldIndex = this.index(oldNode); + this.nodes.splice(oldIndex + 1, 0, newNode); + newNode.parent = this; + var index; + for (var id in this.indexes) { + index = this.indexes[id]; + if (oldIndex <= index) { + this.indexes[id] = index + 1; + } + } + return this; + }; + _proto.insertBefore = function insertBefore(oldNode, newNode) { + newNode.parent = this; + var oldIndex = this.index(oldNode); + this.nodes.splice(oldIndex, 0, newNode); + newNode.parent = this; + var index; + for (var id in this.indexes) { + index = this.indexes[id]; + if (index <= oldIndex) { + this.indexes[id] = index + 1; + } + } + return this; + }; + _proto._findChildAtPosition = function _findChildAtPosition(line, col) { + var found = undefined; + this.each(function (node) { + if (node.atPosition) { + var foundChild = node.atPosition(line, col); + if (foundChild) { + found = foundChild; + return false; + } + } else if (node.isAtPosition(line, col)) { + found = node; + return false; + } + }); + return found; + } + + /** + * Return the most specific node at the line and column number given. + * The source location is based on the original parsed location, locations aren't + * updated as selector nodes are mutated. + * + * Note that this location is relative to the location of the first character + * of the selector, and not the location of the selector in the overall document + * when used in conjunction with postcss. + * + * If not found, returns undefined. + * @param {number} line The line number of the node to find. (1-based index) + * @param {number} col The column number of the node to find. (1-based index) + */; + _proto.atPosition = function atPosition(line, col) { + if (this.isAtPosition(line, col)) { + return this._findChildAtPosition(line, col) || this; + } else { + return undefined; + } + }; + _proto._inferEndPosition = function _inferEndPosition() { + if (this.last && this.last.source && this.last.source.end) { + this.source = this.source || {}; + this.source.end = this.source.end || {}; + Object.assign(this.source.end, this.last.source.end); + } + }; + _proto.each = function each(callback) { + if (!this.lastEach) { + this.lastEach = 0; + } + if (!this.indexes) { + this.indexes = {}; + } + this.lastEach++; + var id = this.lastEach; + this.indexes[id] = 0; + if (!this.length) { + return undefined; + } + var index, result; + while (this.indexes[id] < this.length) { + index = this.indexes[id]; + result = callback(this.at(index), index); + if (result === false) { + break; + } + this.indexes[id] += 1; + } + delete this.indexes[id]; + if (result === false) { + return false; + } + }; + _proto.walk = function walk(callback) { + return this.each(function (node, i) { + var result = callback(node, i); + if (result !== false && node.length) { + result = node.walk(callback); + } + if (result === false) { + return false; + } + }); + }; + _proto.walkAttributes = function walkAttributes(callback) { + var _this2 = this; + return this.walk(function (selector) { + if (selector.type === types.ATTRIBUTE) { + return callback.call(_this2, selector); + } + }); + }; + _proto.walkClasses = function walkClasses(callback) { + var _this3 = this; + return this.walk(function (selector) { + if (selector.type === types.CLASS) { + return callback.call(_this3, selector); + } + }); + }; + _proto.walkCombinators = function walkCombinators(callback) { + var _this4 = this; + return this.walk(function (selector) { + if (selector.type === types.COMBINATOR) { + return callback.call(_this4, selector); + } + }); + }; + _proto.walkComments = function walkComments(callback) { + var _this5 = this; + return this.walk(function (selector) { + if (selector.type === types.COMMENT) { + return callback.call(_this5, selector); + } + }); + }; + _proto.walkIds = function walkIds(callback) { + var _this6 = this; + return this.walk(function (selector) { + if (selector.type === types.ID) { + return callback.call(_this6, selector); + } + }); + }; + _proto.walkNesting = function walkNesting(callback) { + var _this7 = this; + return this.walk(function (selector) { + if (selector.type === types.NESTING) { + return callback.call(_this7, selector); + } + }); + }; + _proto.walkPseudos = function walkPseudos(callback) { + var _this8 = this; + return this.walk(function (selector) { + if (selector.type === types.PSEUDO) { + return callback.call(_this8, selector); + } + }); + }; + _proto.walkTags = function walkTags(callback) { + var _this9 = this; + return this.walk(function (selector) { + if (selector.type === types.TAG) { + return callback.call(_this9, selector); + } + }); + }; + _proto.walkUniversals = function walkUniversals(callback) { + var _this10 = this; + return this.walk(function (selector) { + if (selector.type === types.UNIVERSAL) { + return callback.call(_this10, selector); + } + }); + }; + _proto.split = function split(callback) { + var _this11 = this; + var current = []; + return this.reduce(function (memo, node, index) { + var split = callback.call(_this11, node); + current.push(node); + if (split) { + memo.push(current); + current = []; + } else if (index === _this11.length - 1) { + memo.push(current); + } + return memo; + }, []); + }; + _proto.map = function map(callback) { + return this.nodes.map(callback); + }; + _proto.reduce = function reduce(callback, memo) { + return this.nodes.reduce(callback, memo); + }; + _proto.every = function every(callback) { + return this.nodes.every(callback); + }; + _proto.some = function some(callback) { + return this.nodes.some(callback); + }; + _proto.filter = function filter(callback) { + return this.nodes.filter(callback); + }; + _proto.sort = function sort(callback) { + return this.nodes.sort(callback); + }; + _proto.toString = function toString() { + return this.map(String).join(''); + }; + _createClass(Container, [{ + key: "first", + get: function get() { + return this.at(0); + } + }, { + key: "last", + get: function get() { + return this.at(this.length - 1); + } + }, { + key: "length", + get: function get() { + return this.nodes.length; + } + }]); + return Container; +}(_node["default"]); +exports["default"] = Container; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/guards.js b/node_modules/postcss-selector-parser/dist/selectors/guards.js new file mode 100644 index 0000000..f06161e --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/guards.js @@ -0,0 +1,58 @@ +"use strict"; + +exports.__esModule = true; +exports.isComment = exports.isCombinator = exports.isClassName = exports.isAttribute = void 0; +exports.isContainer = isContainer; +exports.isIdentifier = void 0; +exports.isNamespace = isNamespace; +exports.isNesting = void 0; +exports.isNode = isNode; +exports.isPseudo = void 0; +exports.isPseudoClass = isPseudoClass; +exports.isPseudoElement = isPseudoElement; +exports.isUniversal = exports.isTag = exports.isString = exports.isSelector = exports.isRoot = void 0; +var _types = require("./types"); +var _IS_TYPE; +var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types.ATTRIBUTE] = true, _IS_TYPE[_types.CLASS] = true, _IS_TYPE[_types.COMBINATOR] = true, _IS_TYPE[_types.COMMENT] = true, _IS_TYPE[_types.ID] = true, _IS_TYPE[_types.NESTING] = true, _IS_TYPE[_types.PSEUDO] = true, _IS_TYPE[_types.ROOT] = true, _IS_TYPE[_types.SELECTOR] = true, _IS_TYPE[_types.STRING] = true, _IS_TYPE[_types.TAG] = true, _IS_TYPE[_types.UNIVERSAL] = true, _IS_TYPE); +function isNode(node) { + return typeof node === "object" && IS_TYPE[node.type]; +} +function isNodeType(type, node) { + return isNode(node) && node.type === type; +} +var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE); +exports.isAttribute = isAttribute; +var isClassName = isNodeType.bind(null, _types.CLASS); +exports.isClassName = isClassName; +var isCombinator = isNodeType.bind(null, _types.COMBINATOR); +exports.isCombinator = isCombinator; +var isComment = isNodeType.bind(null, _types.COMMENT); +exports.isComment = isComment; +var isIdentifier = isNodeType.bind(null, _types.ID); +exports.isIdentifier = isIdentifier; +var isNesting = isNodeType.bind(null, _types.NESTING); +exports.isNesting = isNesting; +var isPseudo = isNodeType.bind(null, _types.PSEUDO); +exports.isPseudo = isPseudo; +var isRoot = isNodeType.bind(null, _types.ROOT); +exports.isRoot = isRoot; +var isSelector = isNodeType.bind(null, _types.SELECTOR); +exports.isSelector = isSelector; +var isString = isNodeType.bind(null, _types.STRING); +exports.isString = isString; +var isTag = isNodeType.bind(null, _types.TAG); +exports.isTag = isTag; +var isUniversal = isNodeType.bind(null, _types.UNIVERSAL); +exports.isUniversal = isUniversal; +function isPseudoElement(node) { + return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after" || node.value.toLowerCase() === ":first-letter" || node.value.toLowerCase() === ":first-line"); +} +function isPseudoClass(node) { + return isPseudo(node) && !isPseudoElement(node); +} +function isContainer(node) { + return !!(isNode(node) && node.walk); +} +function isNamespace(node) { + return isAttribute(node) || isTag(node); +} \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/id.js b/node_modules/postcss-selector-parser/dist/selectors/id.js new file mode 100644 index 0000000..8baef72 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/id.js @@ -0,0 +1,25 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _node = _interopRequireDefault(require("./node")); +var _types = require("./types"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var ID = /*#__PURE__*/function (_Node) { + _inheritsLoose(ID, _Node); + function ID(opts) { + var _this; + _this = _Node.call(this, opts) || this; + _this.type = _types.ID; + return _this; + } + var _proto = ID.prototype; + _proto.valueToString = function valueToString() { + return '#' + _Node.prototype.valueToString.call(this); + }; + return ID; +}(_node["default"]); +exports["default"] = ID; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/index.js b/node_modules/postcss-selector-parser/dist/selectors/index.js new file mode 100644 index 0000000..f1f6b7f --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/index.js @@ -0,0 +1,21 @@ +"use strict"; + +exports.__esModule = true; +var _types = require("./types"); +Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _types[key]) return; + exports[key] = _types[key]; +}); +var _constructors = require("./constructors"); +Object.keys(_constructors).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _constructors[key]) return; + exports[key] = _constructors[key]; +}); +var _guards = require("./guards"); +Object.keys(_guards).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _guards[key]) return; + exports[key] = _guards[key]; +}); \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/namespace.js b/node_modules/postcss-selector-parser/dist/selectors/namespace.js new file mode 100644 index 0000000..cc97647 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/namespace.js @@ -0,0 +1,80 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _cssesc = _interopRequireDefault(require("cssesc")); +var _util = require("../util"); +var _node = _interopRequireDefault(require("./node")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var Namespace = /*#__PURE__*/function (_Node) { + _inheritsLoose(Namespace, _Node); + function Namespace() { + return _Node.apply(this, arguments) || this; + } + var _proto = Namespace.prototype; + _proto.qualifiedName = function qualifiedName(value) { + if (this.namespace) { + return this.namespaceString + "|" + value; + } else { + return value; + } + }; + _proto.valueToString = function valueToString() { + return this.qualifiedName(_Node.prototype.valueToString.call(this)); + }; + _createClass(Namespace, [{ + key: "namespace", + get: function get() { + return this._namespace; + }, + set: function set(namespace) { + if (namespace === true || namespace === "*" || namespace === "&") { + this._namespace = namespace; + if (this.raws) { + delete this.raws.namespace; + } + return; + } + var escaped = (0, _cssesc["default"])(namespace, { + isIdentifier: true + }); + this._namespace = namespace; + if (escaped !== namespace) { + (0, _util.ensureObject)(this, "raws"); + this.raws.namespace = escaped; + } else if (this.raws) { + delete this.raws.namespace; + } + } + }, { + key: "ns", + get: function get() { + return this._namespace; + }, + set: function set(namespace) { + this.namespace = namespace; + } + }, { + key: "namespaceString", + get: function get() { + if (this.namespace) { + var ns = this.stringifyProperty("namespace"); + if (ns === true) { + return ''; + } else { + return ns; + } + } else { + return ''; + } + } + }]); + return Namespace; +}(_node["default"]); +exports["default"] = Namespace; +; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/nesting.js b/node_modules/postcss-selector-parser/dist/selectors/nesting.js new file mode 100644 index 0000000..2189928 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/nesting.js @@ -0,0 +1,22 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _node = _interopRequireDefault(require("./node")); +var _types = require("./types"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var Nesting = /*#__PURE__*/function (_Node) { + _inheritsLoose(Nesting, _Node); + function Nesting(opts) { + var _this; + _this = _Node.call(this, opts) || this; + _this.type = _types.NESTING; + _this.value = '&'; + return _this; + } + return Nesting; +}(_node["default"]); +exports["default"] = Nesting; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/node.js b/node_modules/postcss-selector-parser/dist/selectors/node.js new file mode 100644 index 0000000..9a82951 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/node.js @@ -0,0 +1,192 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _util = require("../util"); +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +var cloneNode = function cloneNode(obj, parent) { + if (typeof obj !== 'object' || obj === null) { + return obj; + } + var cloned = new obj.constructor(); + for (var i in obj) { + if (!obj.hasOwnProperty(i)) { + continue; + } + var value = obj[i]; + var type = typeof value; + if (i === 'parent' && type === 'object') { + if (parent) { + cloned[i] = parent; + } + } else if (value instanceof Array) { + cloned[i] = value.map(function (j) { + return cloneNode(j, cloned); + }); + } else { + cloned[i] = cloneNode(value, cloned); + } + } + return cloned; +}; +var Node = /*#__PURE__*/function () { + function Node(opts) { + if (opts === void 0) { + opts = {}; + } + Object.assign(this, opts); + this.spaces = this.spaces || {}; + this.spaces.before = this.spaces.before || ''; + this.spaces.after = this.spaces.after || ''; + } + var _proto = Node.prototype; + _proto.remove = function remove() { + if (this.parent) { + this.parent.removeChild(this); + } + this.parent = undefined; + return this; + }; + _proto.replaceWith = function replaceWith() { + if (this.parent) { + for (var index in arguments) { + this.parent.insertBefore(this, arguments[index]); + } + this.remove(); + } + return this; + }; + _proto.next = function next() { + return this.parent.at(this.parent.index(this) + 1); + }; + _proto.prev = function prev() { + return this.parent.at(this.parent.index(this) - 1); + }; + _proto.clone = function clone(overrides) { + if (overrides === void 0) { + overrides = {}; + } + var cloned = cloneNode(this); + for (var name in overrides) { + cloned[name] = overrides[name]; + } + return cloned; + } + + /** + * Some non-standard syntax doesn't follow normal escaping rules for css. + * This allows non standard syntax to be appended to an existing property + * by specifying the escaped value. By specifying the escaped value, + * illegal characters are allowed to be directly inserted into css output. + * @param {string} name the property to set + * @param {any} value the unescaped value of the property + * @param {string} valueEscaped optional. the escaped value of the property. + */; + _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) { + if (!this.raws) { + this.raws = {}; + } + var originalValue = this[name]; + var originalEscaped = this.raws[name]; + this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first. + if (originalEscaped || valueEscaped !== value) { + this.raws[name] = (originalEscaped || originalValue) + valueEscaped; + } else { + delete this.raws[name]; // delete any escaped value that was created by the setter. + } + } + + /** + * Some non-standard syntax doesn't follow normal escaping rules for css. + * This allows the escaped value to be specified directly, allowing illegal + * characters to be directly inserted into css output. + * @param {string} name the property to set + * @param {any} value the unescaped value of the property + * @param {string} valueEscaped the escaped value of the property. + */; + _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) { + if (!this.raws) { + this.raws = {}; + } + this[name] = value; // this may trigger a setter that updates raws, so it has to be set first. + this.raws[name] = valueEscaped; + } + + /** + * When you want a value to passed through to CSS directly. This method + * deletes the corresponding raw value causing the stringifier to fallback + * to the unescaped value. + * @param {string} name the property to set. + * @param {any} value The value that is both escaped and unescaped. + */; + _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) { + this[name] = value; // this may trigger a setter that updates raws, so it has to be set first. + if (this.raws) { + delete this.raws[name]; + } + } + + /** + * + * @param {number} line The number (starting with 1) + * @param {number} column The column number (starting with 1) + */; + _proto.isAtPosition = function isAtPosition(line, column) { + if (this.source && this.source.start && this.source.end) { + if (this.source.start.line > line) { + return false; + } + if (this.source.end.line < line) { + return false; + } + if (this.source.start.line === line && this.source.start.column > column) { + return false; + } + if (this.source.end.line === line && this.source.end.column < column) { + return false; + } + return true; + } + return undefined; + }; + _proto.stringifyProperty = function stringifyProperty(name) { + return this.raws && this.raws[name] || this[name]; + }; + _proto.valueToString = function valueToString() { + return String(this.stringifyProperty("value")); + }; + _proto.toString = function toString() { + return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join(''); + }; + _createClass(Node, [{ + key: "rawSpaceBefore", + get: function get() { + var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before; + if (rawSpace === undefined) { + rawSpace = this.spaces && this.spaces.before; + } + return rawSpace || ""; + }, + set: function set(raw) { + (0, _util.ensureObject)(this, "raws", "spaces"); + this.raws.spaces.before = raw; + } + }, { + key: "rawSpaceAfter", + get: function get() { + var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after; + if (rawSpace === undefined) { + rawSpace = this.spaces.after; + } + return rawSpace || ""; + }, + set: function set(raw) { + (0, _util.ensureObject)(this, "raws", "spaces"); + this.raws.spaces.after = raw; + } + }]); + return Node; +}(); +exports["default"] = Node; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/pseudo.js b/node_modules/postcss-selector-parser/dist/selectors/pseudo.js new file mode 100644 index 0000000..4371e59 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/pseudo.js @@ -0,0 +1,26 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _container = _interopRequireDefault(require("./container")); +var _types = require("./types"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var Pseudo = /*#__PURE__*/function (_Container) { + _inheritsLoose(Pseudo, _Container); + function Pseudo(opts) { + var _this; + _this = _Container.call(this, opts) || this; + _this.type = _types.PSEUDO; + return _this; + } + var _proto = Pseudo.prototype; + _proto.toString = function toString() { + var params = this.length ? '(' + this.map(String).join(',') + ')' : ''; + return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join(''); + }; + return Pseudo; +}(_container["default"]); +exports["default"] = Pseudo; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/root.js b/node_modules/postcss-selector-parser/dist/selectors/root.js new file mode 100644 index 0000000..8c599d1 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/root.js @@ -0,0 +1,44 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _container = _interopRequireDefault(require("./container")); +var _types = require("./types"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var Root = /*#__PURE__*/function (_Container) { + _inheritsLoose(Root, _Container); + function Root(opts) { + var _this; + _this = _Container.call(this, opts) || this; + _this.type = _types.ROOT; + return _this; + } + var _proto = Root.prototype; + _proto.toString = function toString() { + var str = this.reduce(function (memo, selector) { + memo.push(String(selector)); + return memo; + }, []).join(','); + return this.trailingComma ? str + ',' : str; + }; + _proto.error = function error(message, options) { + if (this._error) { + return this._error(message, options); + } else { + return new Error(message); + } + }; + _createClass(Root, [{ + key: "errorGenerator", + set: function set(handler) { + this._error = handler; + } + }]); + return Root; +}(_container["default"]); +exports["default"] = Root; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/selector.js b/node_modules/postcss-selector-parser/dist/selectors/selector.js new file mode 100644 index 0000000..8cc4bc1 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/selector.js @@ -0,0 +1,21 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _container = _interopRequireDefault(require("./container")); +var _types = require("./types"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var Selector = /*#__PURE__*/function (_Container) { + _inheritsLoose(Selector, _Container); + function Selector(opts) { + var _this; + _this = _Container.call(this, opts) || this; + _this.type = _types.SELECTOR; + return _this; + } + return Selector; +}(_container["default"]); +exports["default"] = Selector; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/string.js b/node_modules/postcss-selector-parser/dist/selectors/string.js new file mode 100644 index 0000000..4749791 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/string.js @@ -0,0 +1,21 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _node = _interopRequireDefault(require("./node")); +var _types = require("./types"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var String = /*#__PURE__*/function (_Node) { + _inheritsLoose(String, _Node); + function String(opts) { + var _this; + _this = _Node.call(this, opts) || this; + _this.type = _types.STRING; + return _this; + } + return String; +}(_node["default"]); +exports["default"] = String; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/tag.js b/node_modules/postcss-selector-parser/dist/selectors/tag.js new file mode 100644 index 0000000..224e74d --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/tag.js @@ -0,0 +1,21 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _namespace = _interopRequireDefault(require("./namespace")); +var _types = require("./types"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var Tag = /*#__PURE__*/function (_Namespace) { + _inheritsLoose(Tag, _Namespace); + function Tag(opts) { + var _this; + _this = _Namespace.call(this, opts) || this; + _this.type = _types.TAG; + return _this; + } + return Tag; +}(_namespace["default"]); +exports["default"] = Tag; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/types.js b/node_modules/postcss-selector-parser/dist/selectors/types.js new file mode 100644 index 0000000..824cc0c --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/types.js @@ -0,0 +1,28 @@ +"use strict"; + +exports.__esModule = true; +exports.UNIVERSAL = exports.TAG = exports.STRING = exports.SELECTOR = exports.ROOT = exports.PSEUDO = exports.NESTING = exports.ID = exports.COMMENT = exports.COMBINATOR = exports.CLASS = exports.ATTRIBUTE = void 0; +var TAG = 'tag'; +exports.TAG = TAG; +var STRING = 'string'; +exports.STRING = STRING; +var SELECTOR = 'selector'; +exports.SELECTOR = SELECTOR; +var ROOT = 'root'; +exports.ROOT = ROOT; +var PSEUDO = 'pseudo'; +exports.PSEUDO = PSEUDO; +var NESTING = 'nesting'; +exports.NESTING = NESTING; +var ID = 'id'; +exports.ID = ID; +var COMMENT = 'comment'; +exports.COMMENT = COMMENT; +var COMBINATOR = 'combinator'; +exports.COMBINATOR = COMBINATOR; +var CLASS = 'class'; +exports.CLASS = CLASS; +var ATTRIBUTE = 'attribute'; +exports.ATTRIBUTE = ATTRIBUTE; +var UNIVERSAL = 'universal'; +exports.UNIVERSAL = UNIVERSAL; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/selectors/universal.js b/node_modules/postcss-selector-parser/dist/selectors/universal.js new file mode 100644 index 0000000..5b58743 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/selectors/universal.js @@ -0,0 +1,22 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; +var _namespace = _interopRequireDefault(require("./namespace")); +var _types = require("./types"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var Universal = /*#__PURE__*/function (_Namespace) { + _inheritsLoose(Universal, _Namespace); + function Universal(opts) { + var _this; + _this = _Namespace.call(this, opts) || this; + _this.type = _types.UNIVERSAL; + _this.value = '*'; + return _this; + } + return Universal; +}(_namespace["default"]); +exports["default"] = Universal; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/sortAscending.js b/node_modules/postcss-selector-parser/dist/sortAscending.js new file mode 100644 index 0000000..5666d5d --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/sortAscending.js @@ -0,0 +1,11 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = sortAscending; +function sortAscending(list) { + return list.sort(function (a, b) { + return a - b; + }); +} +; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/tokenTypes.js b/node_modules/postcss-selector-parser/dist/tokenTypes.js new file mode 100644 index 0000000..59d8e6c --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/tokenTypes.js @@ -0,0 +1,70 @@ +"use strict"; + +exports.__esModule = true; +exports.word = exports.tilde = exports.tab = exports.str = exports.space = exports.slash = exports.singleQuote = exports.semicolon = exports.plus = exports.pipe = exports.openSquare = exports.openParenthesis = exports.newline = exports.greaterThan = exports.feed = exports.equals = exports.doubleQuote = exports.dollar = exports.cr = exports.comment = exports.comma = exports.combinator = exports.colon = exports.closeSquare = exports.closeParenthesis = exports.caret = exports.bang = exports.backslash = exports.at = exports.asterisk = exports.ampersand = void 0; +var ampersand = 38; // `&`.charCodeAt(0); +exports.ampersand = ampersand; +var asterisk = 42; // `*`.charCodeAt(0); +exports.asterisk = asterisk; +var at = 64; // `@`.charCodeAt(0); +exports.at = at; +var comma = 44; // `,`.charCodeAt(0); +exports.comma = comma; +var colon = 58; // `:`.charCodeAt(0); +exports.colon = colon; +var semicolon = 59; // `;`.charCodeAt(0); +exports.semicolon = semicolon; +var openParenthesis = 40; // `(`.charCodeAt(0); +exports.openParenthesis = openParenthesis; +var closeParenthesis = 41; // `)`.charCodeAt(0); +exports.closeParenthesis = closeParenthesis; +var openSquare = 91; // `[`.charCodeAt(0); +exports.openSquare = openSquare; +var closeSquare = 93; // `]`.charCodeAt(0); +exports.closeSquare = closeSquare; +var dollar = 36; // `$`.charCodeAt(0); +exports.dollar = dollar; +var tilde = 126; // `~`.charCodeAt(0); +exports.tilde = tilde; +var caret = 94; // `^`.charCodeAt(0); +exports.caret = caret; +var plus = 43; // `+`.charCodeAt(0); +exports.plus = plus; +var equals = 61; // `=`.charCodeAt(0); +exports.equals = equals; +var pipe = 124; // `|`.charCodeAt(0); +exports.pipe = pipe; +var greaterThan = 62; // `>`.charCodeAt(0); +exports.greaterThan = greaterThan; +var space = 32; // ` `.charCodeAt(0); +exports.space = space; +var singleQuote = 39; // `'`.charCodeAt(0); +exports.singleQuote = singleQuote; +var doubleQuote = 34; // `"`.charCodeAt(0); +exports.doubleQuote = doubleQuote; +var slash = 47; // `/`.charCodeAt(0); +exports.slash = slash; +var bang = 33; // `!`.charCodeAt(0); +exports.bang = bang; +var backslash = 92; // '\\'.charCodeAt(0); +exports.backslash = backslash; +var cr = 13; // '\r'.charCodeAt(0); +exports.cr = cr; +var feed = 12; // '\f'.charCodeAt(0); +exports.feed = feed; +var newline = 10; // '\n'.charCodeAt(0); +exports.newline = newline; +var tab = 9; // '\t'.charCodeAt(0); + +// Expose aliases primarily for readability. +exports.tab = tab; +var str = singleQuote; + +// No good single character representation! +exports.str = str; +var comment = -1; +exports.comment = comment; +var word = -2; +exports.word = word; +var combinator = -3; +exports.combinator = combinator; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/tokenize.js b/node_modules/postcss-selector-parser/dist/tokenize.js new file mode 100644 index 0000000..bf61d26 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/tokenize.js @@ -0,0 +1,239 @@ +"use strict"; + +exports.__esModule = true; +exports.FIELDS = void 0; +exports["default"] = tokenize; +var t = _interopRequireWildcard(require("./tokenTypes")); +var _unescapable, _wordDelimiters; +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } +var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable); +var wordDelimiters = (_wordDelimiters = {}, _wordDelimiters[t.space] = true, _wordDelimiters[t.tab] = true, _wordDelimiters[t.newline] = true, _wordDelimiters[t.cr] = true, _wordDelimiters[t.feed] = true, _wordDelimiters[t.ampersand] = true, _wordDelimiters[t.asterisk] = true, _wordDelimiters[t.bang] = true, _wordDelimiters[t.comma] = true, _wordDelimiters[t.colon] = true, _wordDelimiters[t.semicolon] = true, _wordDelimiters[t.openParenthesis] = true, _wordDelimiters[t.closeParenthesis] = true, _wordDelimiters[t.openSquare] = true, _wordDelimiters[t.closeSquare] = true, _wordDelimiters[t.singleQuote] = true, _wordDelimiters[t.doubleQuote] = true, _wordDelimiters[t.plus] = true, _wordDelimiters[t.pipe] = true, _wordDelimiters[t.tilde] = true, _wordDelimiters[t.greaterThan] = true, _wordDelimiters[t.equals] = true, _wordDelimiters[t.dollar] = true, _wordDelimiters[t.caret] = true, _wordDelimiters[t.slash] = true, _wordDelimiters); +var hex = {}; +var hexChars = "0123456789abcdefABCDEF"; +for (var i = 0; i < hexChars.length; i++) { + hex[hexChars.charCodeAt(i)] = true; +} + +/** + * Returns the last index of the bar css word + * @param {string} css The string in which the word begins + * @param {number} start The index into the string where word's first letter occurs + */ +function consumeWord(css, start) { + var next = start; + var code; + do { + code = css.charCodeAt(next); + if (wordDelimiters[code]) { + return next - 1; + } else if (code === t.backslash) { + next = consumeEscape(css, next) + 1; + } else { + // All other characters are part of the word + next++; + } + } while (next < css.length); + return next - 1; +} + +/** + * Returns the last index of the escape sequence + * @param {string} css The string in which the sequence begins + * @param {number} start The index into the string where escape character (`\`) occurs. + */ +function consumeEscape(css, start) { + var next = start; + var code = css.charCodeAt(next + 1); + if (unescapable[code]) { + // just consume the escape char + } else if (hex[code]) { + var hexDigits = 0; + // consume up to 6 hex chars + do { + next++; + hexDigits++; + code = css.charCodeAt(next + 1); + } while (hex[code] && hexDigits < 6); + // if fewer than 6 hex chars, a trailing space ends the escape + if (hexDigits < 6 && code === t.space) { + next++; + } + } else { + // the next char is part of the current word + next++; + } + return next; +} +var FIELDS = { + TYPE: 0, + START_LINE: 1, + START_COL: 2, + END_LINE: 3, + END_COL: 4, + START_POS: 5, + END_POS: 6 +}; +exports.FIELDS = FIELDS; +function tokenize(input) { + var tokens = []; + var css = input.css.valueOf(); + var _css = css, + length = _css.length; + var offset = -1; + var line = 1; + var start = 0; + var end = 0; + var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType; + function unclosed(what, fix) { + if (input.safe) { + // fyi: this is never set to true. + css += fix; + next = css.length - 1; + } else { + throw input.error('Unclosed ' + what, line, start - offset, start); + } + } + while (start < length) { + code = css.charCodeAt(start); + if (code === t.newline) { + offset = start; + line += 1; + } + switch (code) { + case t.space: + case t.tab: + case t.newline: + case t.cr: + case t.feed: + next = start; + do { + next += 1; + code = css.charCodeAt(next); + if (code === t.newline) { + offset = next; + line += 1; + } + } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed); + tokenType = t.space; + endLine = line; + endColumn = next - offset - 1; + end = next; + break; + case t.plus: + case t.greaterThan: + case t.tilde: + case t.pipe: + next = start; + do { + next += 1; + code = css.charCodeAt(next); + } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe); + tokenType = t.combinator; + endLine = line; + endColumn = start - offset; + end = next; + break; + + // Consume these characters as single tokens. + case t.asterisk: + case t.ampersand: + case t.bang: + case t.comma: + case t.equals: + case t.dollar: + case t.caret: + case t.openSquare: + case t.closeSquare: + case t.colon: + case t.semicolon: + case t.openParenthesis: + case t.closeParenthesis: + next = start; + tokenType = code; + endLine = line; + endColumn = start - offset; + end = next + 1; + break; + case t.singleQuote: + case t.doubleQuote: + quote = code === t.singleQuote ? "'" : '"'; + next = start; + do { + escaped = false; + next = css.indexOf(quote, next + 1); + if (next === -1) { + unclosed('quote', quote); + } + escapePos = next; + while (css.charCodeAt(escapePos - 1) === t.backslash) { + escapePos -= 1; + escaped = !escaped; + } + } while (escaped); + tokenType = t.str; + endLine = line; + endColumn = start - offset; + end = next + 1; + break; + default: + if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) { + next = css.indexOf('*/', start + 2) + 1; + if (next === 0) { + unclosed('comment', '*/'); + } + content = css.slice(start, next + 1); + lines = content.split('\n'); + last = lines.length - 1; + if (last > 0) { + nextLine = line + last; + nextOffset = next - lines[last].length; + } else { + nextLine = line; + nextOffset = offset; + } + tokenType = t.comment; + line = nextLine; + endLine = nextLine; + endColumn = next - nextOffset; + } else if (code === t.slash) { + next = start; + tokenType = code; + endLine = line; + endColumn = start - offset; + end = next + 1; + } else { + next = consumeWord(css, start); + tokenType = t.word; + endLine = line; + endColumn = next - offset; + } + end = next + 1; + break; + } + + // Ensure that the token structure remains consistent + tokens.push([tokenType, + // [0] Token type + line, + // [1] Starting line + start - offset, + // [2] Starting column + endLine, + // [3] Ending line + endColumn, + // [4] Ending column + start, + // [5] Start position / Source index + end // [6] End position + ]); + + // Reset offset for the next token + if (nextOffset) { + offset = nextOffset; + nextOffset = null; + } + start = end; + } + return tokens; +} \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/util/ensureObject.js b/node_modules/postcss-selector-parser/dist/util/ensureObject.js new file mode 100644 index 0000000..494941a --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/util/ensureObject.js @@ -0,0 +1,17 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = ensureObject; +function ensureObject(obj) { + for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + props[_key - 1] = arguments[_key]; + } + while (props.length > 0) { + var prop = props.shift(); + if (!obj[prop]) { + obj[prop] = {}; + } + obj = obj[prop]; + } +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/util/getProp.js b/node_modules/postcss-selector-parser/dist/util/getProp.js new file mode 100644 index 0000000..a2b7a07 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/util/getProp.js @@ -0,0 +1,18 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = getProp; +function getProp(obj) { + for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + props[_key - 1] = arguments[_key]; + } + while (props.length > 0) { + var prop = props.shift(); + if (!obj[prop]) { + return undefined; + } + obj = obj[prop]; + } + return obj; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/util/index.js b/node_modules/postcss-selector-parser/dist/util/index.js new file mode 100644 index 0000000..f96ec11 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/util/index.js @@ -0,0 +1,13 @@ +"use strict"; + +exports.__esModule = true; +exports.unesc = exports.stripComments = exports.getProp = exports.ensureObject = void 0; +var _unesc = _interopRequireDefault(require("./unesc")); +exports.unesc = _unesc["default"]; +var _getProp = _interopRequireDefault(require("./getProp")); +exports.getProp = _getProp["default"]; +var _ensureObject = _interopRequireDefault(require("./ensureObject")); +exports.ensureObject = _ensureObject["default"]; +var _stripComments = _interopRequireDefault(require("./stripComments")); +exports.stripComments = _stripComments["default"]; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/util/stripComments.js b/node_modules/postcss-selector-parser/dist/util/stripComments.js new file mode 100644 index 0000000..0baa0e0 --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/util/stripComments.js @@ -0,0 +1,21 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = stripComments; +function stripComments(str) { + var s = ""; + var commentStart = str.indexOf("/*"); + var lastEnd = 0; + while (commentStart >= 0) { + s = s + str.slice(lastEnd, commentStart); + var commentEnd = str.indexOf("*/", commentStart + 2); + if (commentEnd < 0) { + return s; + } + lastEnd = commentEnd + 2; + commentStart = str.indexOf("/*", lastEnd); + } + s = s + str.slice(lastEnd); + return s; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/dist/util/unesc.js b/node_modules/postcss-selector-parser/dist/util/unesc.js new file mode 100644 index 0000000..87396be --- /dev/null +++ b/node_modules/postcss-selector-parser/dist/util/unesc.js @@ -0,0 +1,76 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = unesc; +// Many thanks for this post which made this migration much easier. +// https://mathiasbynens.be/notes/css-escapes + +/** + * + * @param {string} str + * @returns {[string, number]|undefined} + */ +function gobbleHex(str) { + var lower = str.toLowerCase(); + var hex = ''; + var spaceTerminated = false; + for (var i = 0; i < 6 && lower[i] !== undefined; i++) { + var code = lower.charCodeAt(i); + // check to see if we are dealing with a valid hex char [a-f|0-9] + var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57; + // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point + spaceTerminated = code === 32; + if (!valid) { + break; + } + hex += lower[i]; + } + if (hex.length === 0) { + return undefined; + } + var codePoint = parseInt(hex, 16); + var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF; + // Add special case for + // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point" + // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point + if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) { + return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)]; + } + return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)]; +} +var CONTAINS_ESCAPE = /\\/; +function unesc(str) { + var needToProcess = CONTAINS_ESCAPE.test(str); + if (!needToProcess) { + return str; + } + var ret = ""; + for (var i = 0; i < str.length; i++) { + if (str[i] === "\\") { + var gobbled = gobbleHex(str.slice(i + 1, i + 7)); + if (gobbled !== undefined) { + ret += gobbled[0]; + i += gobbled[1]; + continue; + } + + // Retain a pair of \\ if double escaped `\\\\` + // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e + if (str[i + 1] === "\\") { + ret += "\\"; + i++; + continue; + } + + // if \\ is at the end of the string retain it + // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb + if (str.length === i + 1) { + ret += str[i]; + } + continue; + } + ret += str[i]; + } + return ret; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/postcss-selector-parser/package.json b/node_modules/postcss-selector-parser/package.json new file mode 100644 index 0000000..0b074d0 --- /dev/null +++ b/node_modules/postcss-selector-parser/package.json @@ -0,0 +1,80 @@ +{ + "name": "postcss-selector-parser", + "version": "6.1.2", + "devDependencies": { + "@babel/cli": "^7.11.6", + "@babel/core": "^7.11.6", + "@babel/eslint-parser": "^7.11.5", + "@babel/eslint-plugin": "^7.11.5", + "@babel/plugin-proposal-class-properties": "^7.10.4", + "@babel/preset-env": "^7.11.5", + "@babel/register": "^7.11.5", + "ava": "^5.1.0", + "babel-plugin-add-module-exports": "^1.0.4", + "coveralls": "^3.1.0", + "del-cli": "^5.0.0", + "eslint": "^8.28.0", + "eslint-plugin-import": "^2.26.0", + "glob": "^8.0.3", + "minimist": "^1.2.5", + "nyc": "^15.1.0", + "postcss": "^8.4.31", + "semver": "^7.3.2", + "typescript": "^4.0.3" + }, + "main": "dist/index.js", + "types": "postcss-selector-parser.d.ts", + "files": [ + "API.md", + "CHANGELOG.md", + "LICENSE-MIT", + "dist", + "postcss-selector-parser.d.ts", + "!**/__tests__" + ], + "scripts": { + "typecheck": "tsc --noEmit --strict postcss-selector-parser.d.ts postcss-selector-parser.test.ts", + "pretest": "eslint src && npm run typecheck", + "prepare": "del-cli dist && BABEL_ENV=publish babel src --out-dir dist --ignore /__tests__/", + "lintfix": "eslint --fix src", + "report": "nyc report --reporter=html", + "test": "nyc ava src/__tests__/*.mjs", + "testone": "ava" + }, + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "license": "MIT", + "engines": { + "node": ">=4" + }, + "homepage": "https://github.com/postcss/postcss-selector-parser", + "contributors": [ + { + "name": "Ben Briggs", + "email": "beneb.info@gmail.com", + "url": "http://beneb.info" + }, + { + "name": "Chris Eppstein", + "email": "chris@eppsteins.net", + "url": "http://twitter.com/chriseppstein" + } + ], + "repository": "postcss/postcss-selector-parser", + "ava": { + "require": [ + "@babel/register" + ], + "concurrency": 5, + "timeout": "25s", + "nodeArguments": [] + }, + "nyc": { + "exclude": [ + "node_modules", + "**/__tests__" + ] + } +} diff --git a/node_modules/postcss-selector-parser/postcss-selector-parser.d.ts b/node_modules/postcss-selector-parser/postcss-selector-parser.d.ts new file mode 100644 index 0000000..af609e6 --- /dev/null +++ b/node_modules/postcss-selector-parser/postcss-selector-parser.d.ts @@ -0,0 +1,555 @@ +// Type definitions for postcss-selector-parser 2.2.3 +// Definitions by: Chris Eppstein + +/*~ Note that ES6 modules cannot directly export callable functions. + *~ This file should be imported using the CommonJS-style: + *~ import x = require('someLibrary'); + *~ + *~ Refer to the documentation to understand common + *~ workarounds for this limitation of ES6 modules. + */ + +/*~ This declaration specifies that the function + *~ is the exported object from the file + */ +export = parser; + +// A type that's T but not U. +type Diff = T extends U ? never : T; + +// TODO: Conditional types in TS 1.8 will really clean this up. +declare function parser(): parser.Processor; +declare function parser(processor: parser.AsyncProcessor): parser.Processor; +declare function parser(processor: parser.AsyncProcessor): parser.Processor; +declare function parser(processor: parser.SyncProcessor): parser.Processor; +declare function parser(processor: parser.SyncProcessor): parser.Processor; +declare function parser(processor?: parser.SyncProcessor | parser.AsyncProcessor): parser.Processor; + +/*~ If you want to expose types from your module as well, you can + *~ place them in this block. Often you will want to describe the + *~ shape of the return type of the function; that type should + *~ be declared in here, as this example shows. + */ +declare namespace parser { + /* copied from postcss -- so we don't need to add a dependency */ + type ErrorOptions = { + plugin?: string; + word?: string; + index?: number + }; + /* the bits we use of postcss.Rule, copied from postcss -- so we don't need to add a dependency */ + type PostCSSRuleNode = { + selector: string + /** + * @returns postcss.CssSyntaxError but it's a complex object, caller + * should cast to it if they have a dependency on postcss. + */ + error(message: string, options?: ErrorOptions): Error; + }; + /** Accepts a string */ + type Selectors = string | PostCSSRuleNode + type ProcessorFn = (root: parser.Root) => ReturnType; + type SyncProcessor = ProcessorFn; + type AsyncProcessor = ProcessorFn>; + + const TAG: "tag"; + const STRING: "string"; + const SELECTOR: "selector"; + const ROOT: "root"; + const PSEUDO: "pseudo"; + const NESTING: "nesting"; + const ID: "id"; + const COMMENT: "comment"; + const COMBINATOR: "combinator"; + const CLASS: "class"; + const ATTRIBUTE: "attribute"; + const UNIVERSAL: "universal"; + + interface NodeTypes { + tag: Tag, + string: String, + selector: Selector, + root: Root, + pseudo: Pseudo, + nesting: Nesting, + id: Identifier, + comment: Comment, + combinator: Combinator, + class: ClassName, + attribute: Attribute, + universal: Universal + } + + type Node = NodeTypes[keyof NodeTypes]; + + function isNode(node: any): node is Node; + + interface Options { + /** + * Preserve whitespace when true. Default: false; + */ + lossless: boolean; + /** + * When true and a postcss.Rule is passed, set the result of + * processing back onto the rule when done. Default: false. + */ + updateSelector: boolean; + } + class Processor< + TransformType = never, + SyncSelectorsType extends Selectors | never = Selectors + > { + res: Root; + readonly result: String; + ast(selectors: Selectors, options?: Partial): Promise; + astSync(selectors: SyncSelectorsType, options?: Partial): Root; + transform(selectors: Selectors, options?: Partial): Promise; + transformSync(selectors: SyncSelectorsType, options?: Partial): TransformType; + process(selectors: Selectors, options?: Partial): Promise; + processSync(selectors: SyncSelectorsType, options?: Partial): string; + } + interface ParserOptions { + css: string; + error: (message: string, options: ErrorOptions) => Error; + options: Options; + } + class Parser { + input: ParserOptions; + lossy: boolean; + position: number; + root: Root; + selectors: string; + current: Selector; + constructor(input: ParserOptions); + /** + * Raises an error, if the processor is invoked on + * a postcss Rule node, a better error message is raised. + */ + error(message: string, options?: ErrorOptions): void; + } + interface NodeSource { + start?: { + line: number, + column: number + }, + end?: { + line: number, + column: number + } + } + interface SpaceAround { + before: string; + after: string; + } + interface Spaces extends SpaceAround { + [spaceType: string]: string | Partial | undefined; + } + interface NodeOptions { + value: Value; + spaces?: Partial; + source?: NodeSource; + sourceIndex?: number; + } + interface Base< + Value extends string | undefined = string, + ParentType extends Container | undefined = Container | undefined + > { + type: keyof NodeTypes; + parent: ParentType; + value: Value; + spaces: Spaces; + source?: NodeSource; + sourceIndex: number; + rawSpaceBefore: string; + rawSpaceAfter: string; + remove(): Node; + replaceWith(...nodes: Node[]): Node; + next(): Node | undefined; + prev(): Node | undefined; + clone(opts?: {[override: string]:any}): this; + /** + * Return whether this node includes the character at the position of the given line and column. + * Returns undefined if the nodes lack sufficient source metadata to determine the position. + * @param line 1-index based line number relative to the start of the selector. + * @param column 1-index based column number relative to the start of the selector. + */ + isAtPosition(line: number, column: number): boolean | undefined; + /** + * Some non-standard syntax doesn't follow normal escaping rules for css, + * this allows the escaped value to be specified directly, allowing illegal characters to be + * directly inserted into css output. + * @param name the property to set + * @param value the unescaped value of the property + * @param valueEscaped optional. the escaped value of the property. + */ + setPropertyAndEscape(name: string, value: any, valueEscaped: string): void; + /** + * When you want a value to passed through to CSS directly. This method + * deletes the corresponding raw value causing the stringifier to fallback + * to the unescaped value. + * @param name the property to set. + * @param value The value that is both escaped and unescaped. + */ + setPropertyWithoutEscape(name: string, value: any): void; + /** + * Some non-standard syntax doesn't follow normal escaping rules for css. + * This allows non standard syntax to be appended to an existing property + * by specifying the escaped value. By specifying the escaped value, + * illegal characters are allowed to be directly inserted into css output. + * @param {string} name the property to set + * @param {any} value the unescaped value of the property + * @param {string} valueEscaped optional. the escaped value of the property. + */ + appendToPropertyAndEscape(name: string, value: any, valueEscaped: string): void; + toString(): string; + } + interface ContainerOptions extends NodeOptions { + nodes?: Array; + } + interface Container< + Value extends string | undefined = string, + Child extends Node = Node + > extends Base { + nodes: Array; + append(selector: Child): this; + prepend(selector: Child): this; + at(index: number): Child; + /** + * Return the most specific node at the line and column number given. + * The source location is based on the original parsed location, locations aren't + * updated as selector nodes are mutated. + * + * Note that this location is relative to the location of the first character + * of the selector, and not the location of the selector in the overall document + * when used in conjunction with postcss. + * + * If not found, returns undefined. + * @param line The line number of the node to find. (1-based index) + * @param col The column number of the node to find. (1-based index) + */ + atPosition(line: number, column: number): Child; + index(child: Child): number; + readonly first: Child; + readonly last: Child; + readonly length: number; + removeChild(child: Child): this; + removeAll(): this; + empty(): this; + insertAfter(oldNode: Child, newNode: Child): this; + insertBefore(oldNode: Child, newNode: Child): this; + each(callback: (node: Child, index: number) => boolean | void): boolean | undefined; + walk( + callback: (node: Node, index: number) => boolean | void + ): boolean | undefined; + walkAttributes( + callback: (node: Attribute) => boolean | void + ): boolean | undefined; + walkClasses( + callback: (node: ClassName) => boolean | void + ): boolean | undefined; + walkCombinators( + callback: (node: Combinator) => boolean | void + ): boolean | undefined; + walkComments( + callback: (node: Comment) => boolean | void + ): boolean | undefined; + walkIds( + callback: (node: Identifier) => boolean | void + ): boolean | undefined; + walkNesting( + callback: (node: Nesting) => boolean | void + ): boolean | undefined; + walkPseudos( + callback: (node: Pseudo) => boolean | void + ): boolean | undefined; + walkTags(callback: (node: Tag) => boolean | void): boolean | undefined; + split(callback: (node: Child) => boolean): [Child[], Child[]]; + map(callback: (node: Child) => T): T[]; + reduce( + callback: ( + previousValue: Child, + currentValue: Child, + currentIndex: number, + array: readonly Child[] + ) => Child + ): Child; + reduce( + callback: ( + previousValue: Child, + currentValue: Child, + currentIndex: number, + array: readonly Child[] + ) => Child, + initialValue: Child + ): Child; + reduce( + callback: ( + previousValue: T, + currentValue: Child, + currentIndex: number, + array: readonly Child[] + ) => T, + initialValue: T + ): T; + every(callback: (node: Child) => boolean): boolean; + some(callback: (node: Child) => boolean): boolean; + filter(callback: (node: Child) => boolean): Child[]; + sort(callback: (nodeA: Child, nodeB: Child) => number): Child[]; + toString(): string; + } + function isContainer(node: any): node is Root | Selector | Pseudo; + + interface NamespaceOptions extends NodeOptions { + namespace?: string | true; + } + interface Namespace extends Base { + /** alias for namespace */ + ns: string | true; + /** + * namespace prefix. + */ + namespace: string | true; + /** + * If a namespace exists, prefix the value provided with it, separated by |. + */ + qualifiedName(value: string): string; + /** + * A string representing the namespace suitable for output. + */ + readonly namespaceString: string; + } + function isNamespace(node: any): node is Attribute | Tag; + + interface Root extends Container { + type: "root"; + /** + * Raises an error, if the processor is invoked on + * a postcss Rule node, a better error message is raised. + */ + error(message: string, options?: ErrorOptions): Error; + nodeAt(line: number, column: number): Node + } + function root(opts: ContainerOptions): Root; + function isRoot(node: any): node is Root; + + interface _Selector extends Container> { + type: "selector"; + } + type Selector = _Selector; + function selector(opts: ContainerOptions): Selector; + function isSelector(node: any): node is Selector; + + interface CombinatorRaws { + value?: string; + spaces?: { + before?: string; + after?: string; + }; + } + interface Combinator extends Base { + type: "combinator"; + raws?: CombinatorRaws; + } + function combinator(opts: NodeOptions): Combinator; + function isCombinator(node: any): node is Combinator; + + interface ClassName extends Base { + type: "class"; + } + function className(opts: NamespaceOptions): ClassName; + function isClassName(node: any): node is ClassName; + + type AttributeOperator = "=" | "~=" | "|=" | "^=" | "$=" | "*="; + type QuoteMark = '"' | "'" | null; + interface PreferredQuoteMarkOptions { + quoteMark?: QuoteMark; + preferCurrentQuoteMark?: boolean; + } + interface SmartQuoteMarkOptions extends PreferredQuoteMarkOptions { + smart?: boolean; + } + interface AttributeOptions extends NamespaceOptions { + attribute: string; + operator?: AttributeOperator; + insensitive?: boolean; + quoteMark?: QuoteMark; + /** @deprecated Use quoteMark instead. */ + quoted?: boolean; + spaces?: { + before?: string; + after?: string; + attribute?: Partial; + operator?: Partial; + value?: Partial; + insensitive?: Partial; + } + raws: { + unquoted?: string; + attribute?: string; + operator?: string; + value?: string; + insensitive?: string; + spaces?: { + attribute?: Partial; + operator?: Partial; + value?: Partial; + insensitive?: Partial; + } + }; + } + interface Attribute extends Namespace { + type: "attribute"; + attribute: string; + operator?: AttributeOperator; + insensitive?: boolean; + quoteMark: QuoteMark; + quoted?: boolean; + spaces: { + before: string; + after: string; + attribute?: Partial; + operator?: Partial; + value?: Partial; + insensitive?: Partial; + } + raws: { + /** @deprecated The attribute value is unquoted, use that instead.. */ + unquoted?: string; + attribute?: string; + operator?: string; + /** The value of the attribute with quotes and escapes. */ + value?: string; + insensitive?: string; + spaces?: { + attribute?: Partial; + operator?: Partial; + value?: Partial; + insensitive?: Partial; + } + }; + /** + * The attribute name after having been qualified with a namespace. + */ + readonly qualifiedAttribute: string; + + /** + * The case insensitivity flag or an empty string depending on whether this + * attribute is case insensitive. + */ + readonly insensitiveFlag : 'i' | ''; + + /** + * Returns the attribute's value quoted such that it would be legal to use + * in the value of a css file. The original value's quotation setting + * used for stringification is left unchanged. See `setValue(value, options)` + * if you want to control the quote settings of a new value for the attribute or + * `set quoteMark(mark)` if you want to change the quote settings of the current + * value. + * + * You can also change the quotation used for the current value by setting quoteMark. + **/ + getQuotedValue(options?: SmartQuoteMarkOptions): string; + + /** + * Set the unescaped value with the specified quotation options. The value + * provided must not include any wrapping quote marks -- those quotes will + * be interpreted as part of the value and escaped accordingly. + * @param value + */ + setValue(value: string, options?: SmartQuoteMarkOptions): void; + + /** + * Intelligently select a quoteMark value based on the value's contents. If + * the value is a legal CSS ident, it will not be quoted. Otherwise a quote + * mark will be picked that minimizes the number of escapes. + * + * If there's no clear winner, the quote mark from these options is used, + * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is + * true). If the quoteMark is unspecified, a double quote is used. + **/ + smartQuoteMark(options: PreferredQuoteMarkOptions): QuoteMark; + + /** + * Selects the preferred quote mark based on the options and the current quote mark value. + * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)` + * instead. + */ + preferredQuoteMark(options: PreferredQuoteMarkOptions): QuoteMark + + /** + * returns the offset of the attribute part specified relative to the + * start of the node of the output string. + * + * * "ns" - alias for "namespace" + * * "namespace" - the namespace if it exists. + * * "attribute" - the attribute name + * * "attributeNS" - the start of the attribute or its namespace + * * "operator" - the match operator of the attribute + * * "value" - The value (string or identifier) + * * "insensitive" - the case insensitivity flag; + * @param part One of the possible values inside an attribute. + * @returns -1 if the name is invalid or the value doesn't exist in this attribute. + */ + offsetOf(part: "ns" | "namespace" | "attribute" | "attributeNS" | "operator" | "value" | "insensitive"): number; + } + function attribute(opts: AttributeOptions): Attribute; + function isAttribute(node: any): node is Attribute; + + interface Pseudo extends Container { + type: "pseudo"; + } + function pseudo(opts: ContainerOptions): Pseudo; + /** + * Checks whether the node is the Pseudo subtype of node. + */ + function isPseudo(node: any): node is Pseudo; + + /** + * Checks whether the node is, specifically, a pseudo element instead of + * pseudo class. + */ + function isPseudoElement(node: any): node is Pseudo; + + /** + * Checks whether the node is, specifically, a pseudo class instead of + * pseudo element. + */ + function isPseudoClass(node: any): node is Pseudo; + + + interface Tag extends Namespace { + type: "tag"; + } + function tag(opts: NamespaceOptions): Tag; + function isTag(node: any): node is Tag; + + interface Comment extends Base { + type: "comment"; + } + function comment(opts: NodeOptions): Comment; + function isComment(node: any): node is Comment; + + interface Identifier extends Base { + type: "id"; + } + function id(opts: any): Identifier; + function isIdentifier(node: any): node is Identifier; + + interface Nesting extends Base { + type: "nesting"; + } + function nesting(opts?: any): Nesting; + function isNesting(node: any): node is Nesting; + + interface String extends Base { + type: "string"; + } + function string(opts: NodeOptions): String; + function isString(node: any): node is String; + + interface Universal extends Base { + type: "universal"; + } + function universal(opts?: NamespaceOptions): Universal; + function isUniversal(node: any): node is Universal; +} diff --git a/node_modules/postcss-value-parser/LICENSE b/node_modules/postcss-value-parser/LICENSE new file mode 100644 index 0000000..6dcaefc --- /dev/null +++ b/node_modules/postcss-value-parser/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) Bogdan Chadkin + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/postcss-value-parser/README.md b/node_modules/postcss-value-parser/README.md new file mode 100644 index 0000000..3bd6a0d --- /dev/null +++ b/node_modules/postcss-value-parser/README.md @@ -0,0 +1,263 @@ +# postcss-value-parser + +[![Travis CI](https://travis-ci.org/TrySound/postcss-value-parser.svg)](https://travis-ci.org/TrySound/postcss-value-parser) + +Transforms CSS declaration values and at-rule parameters into a tree of nodes, and provides a simple traversal API. + +## Usage + +```js +var valueParser = require('postcss-value-parser'); +var cssBackgroundValue = 'url(foo.png) no-repeat 40px 73%'; +var parsedValue = valueParser(cssBackgroundValue); +// parsedValue exposes an API described below, +// e.g. parsedValue.walk(..), parsedValue.toString(), etc. +``` + +For example, parsing the value `rgba(233, 45, 66, .5)` will return the following: + +```js +{ + nodes: [ + { + type: 'function', + value: 'rgba', + before: '', + after: '', + nodes: [ + { type: 'word', value: '233' }, + { type: 'div', value: ',', before: '', after: ' ' }, + { type: 'word', value: '45' }, + { type: 'div', value: ',', before: '', after: ' ' }, + { type: 'word', value: '66' }, + { type: 'div', value: ',', before: ' ', after: '' }, + { type: 'word', value: '.5' } + ] + } + ] +} +``` + +If you wanted to convert each `rgba()` value in `sourceCSS` to a hex value, you could do so like this: + +```js +var valueParser = require('postcss-value-parser'); + +var parsed = valueParser(sourceCSS); + +// walk() will visit all the of the nodes in the tree, +// invoking the callback for each. +parsed.walk(function (node) { + + // Since we only want to transform rgba() values, + // we can ignore anything else. + if (node.type !== 'function' && node.value !== 'rgba') return; + + // We can make an array of the rgba() arguments to feed to a + // convertToHex() function + var color = node.nodes.filter(function (node) { + return node.type === 'word'; + }).map(function (node) { + return Number(node.value); + }); // [233, 45, 66, .5] + + // Now we will transform the existing rgba() function node + // into a word node with the hex value + node.type = 'word'; + node.value = convertToHex(color); +}) + +parsed.toString(); // #E92D42 +``` + +## Nodes + +Each node is an object with these common properties: + +- **type**: The type of node (`word`, `string`, `div`, `space`, `comment`, or `function`). + Each type is documented below. +- **value**: Each node has a `value` property; but what exactly `value` means + is specific to the node type. Details are documented for each type below. +- **sourceIndex**: The starting index of the node within the original source + string. For example, given the source string `10px 20px`, the `word` node + whose value is `20px` will have a `sourceIndex` of `5`. + +### word + +The catch-all node type that includes keywords (e.g. `no-repeat`), +quantities (e.g. `20px`, `75%`, `1.5`), and hex colors (e.g. `#e6e6e6`). + +Node-specific properties: + +- **value**: The "word" itself. + +### string + +A quoted string value, e.g. `"something"` in `content: "something";`. + +Node-specific properties: + +- **value**: The text content of the string. +- **quote**: The quotation mark surrounding the string, either `"` or `'`. +- **unclosed**: `true` if the string was not closed properly. e.g. `"unclosed string `. + +### div + +A divider, for example + +- `,` in `animation-duration: 1s, 2s, 3s` +- `/` in `border-radius: 10px / 23px` +- `:` in `(min-width: 700px)` + +Node-specific properties: + +- **value**: The divider character. Either `,`, `/`, or `:` (see examples above). +- **before**: Whitespace before the divider. +- **after**: Whitespace after the divider. + +### space + +Whitespace used as a separator, e.g. ` ` occurring twice in `border: 1px solid black;`. + +Node-specific properties: + +- **value**: The whitespace itself. + +### comment + +A CSS comment starts with `/*` and ends with `*/` + +Node-specific properties: + +- **value**: The comment value without `/*` and `*/` +- **unclosed**: `true` if the comment was not closed properly. e.g. `/* comment without an end `. + +### function + +A CSS function, e.g. `rgb(0,0,0)` or `url(foo.bar)`. + +Function nodes have nodes nested within them: the function arguments. + +Additional properties: + +- **value**: The name of the function, e.g. `rgb` in `rgb(0,0,0)`. +- **before**: Whitespace after the opening parenthesis and before the first argument, + e.g. ` ` in `rgb( 0,0,0)`. +- **after**: Whitespace before the closing parenthesis and after the last argument, + e.g. ` ` in `rgb(0,0,0 )`. +- **nodes**: More nodes representing the arguments to the function. +- **unclosed**: `true` if the parentheses was not closed properly. e.g. `( unclosed-function `. + +Media features surrounded by parentheses are considered functions with an +empty value. For example, `(min-width: 700px)` parses to these nodes: + +```js +[ + { + type: 'function', value: '', before: '', after: '', + nodes: [ + { type: 'word', value: 'min-width' }, + { type: 'div', value: ':', before: '', after: ' ' }, + { type: 'word', value: '700px' } + ] + } +] +``` + +`url()` functions can be parsed a little bit differently depending on +whether the first character in the argument is a quotation mark. + +`url( /gfx/img/bg.jpg )` parses to: + +```js +{ type: 'function', sourceIndex: 0, value: 'url', before: ' ', after: ' ', nodes: [ + { type: 'word', sourceIndex: 5, value: '/gfx/img/bg.jpg' } +] } +``` + +`url( "/gfx/img/bg.jpg" )`, on the other hand, parses to: + +```js +{ type: 'function', sourceIndex: 0, value: 'url', before: ' ', after: ' ', nodes: [ + type: 'string', sourceIndex: 5, quote: '"', value: '/gfx/img/bg.jpg' }, +] } +``` + +### unicode-range + +The unicode-range CSS descriptor sets the specific range of characters to be +used from a font defined by @font-face and made available +for use on the current page (`unicode-range: U+0025-00FF`). + +Node-specific properties: + +- **value**: The "unicode-range" itself. + +## API + +``` +var valueParser = require('postcss-value-parser'); +``` + +### valueParser.unit(quantity) + +Parses `quantity`, distinguishing the number from the unit. Returns an object like the following: + +```js +// Given 2rem +{ + number: '2', + unit: 'rem' +} +``` + +If the `quantity` argument cannot be parsed as a number, returns `false`. + +*This function does not parse complete values*: you cannot pass it `1px solid black` and expect `px` as +the unit. Instead, you should pass it single quantities only. Parse `1px solid black`, then pass it +the stringified `1px` node (a `word` node) to parse the number and unit. + +### valueParser.stringify(nodes[, custom]) + +Stringifies a node or array of nodes. + +The `custom` function is called for each `node`; return a string to override the default behaviour. + +### valueParser.walk(nodes, callback[, bubble]) + +Walks each provided node, recursively walking all descendent nodes within functions. + +Returning `false` in the `callback` will prevent traversal of descendent nodes (within functions). +You can use this feature to for shallow iteration, walking over only the *immediate* children. +*Note: This only applies if `bubble` is `false` (which is the default).* + +By default, the tree is walked from the outermost node inwards. +To reverse the direction, pass `true` for the `bubble` argument. + +The `callback` is invoked with three arguments: `callback(node, index, nodes)`. + +- `node`: The current node. +- `index`: The index of the current node. +- `nodes`: The complete nodes array passed to `walk()`. + +Returns the `valueParser` instance. + +### var parsed = valueParser(value) + +Returns the parsed node tree. + +### parsed.nodes + +The array of nodes. + +### parsed.toString() + +Stringifies the node tree. + +### parsed.walk(callback[, bubble]) + +Walks each node inside `parsed.nodes`. See the documentation for `valueParser.walk()` above. + +# License + +MIT © [Bogdan Chadkin](mailto:trysound@yandex.ru) diff --git a/node_modules/postcss-value-parser/lib/index.d.ts b/node_modules/postcss-value-parser/lib/index.d.ts new file mode 100644 index 0000000..8759f3f --- /dev/null +++ b/node_modules/postcss-value-parser/lib/index.d.ts @@ -0,0 +1,177 @@ +declare namespace postcssValueParser { + interface BaseNode { + /** + * The offset, inclusive, inside the CSS value at which the node starts. + */ + sourceIndex: number; + + /** + * The offset, exclusive, inside the CSS value at which the node ends. + */ + sourceEndIndex: number; + + /** + * The node's characteristic value + */ + value: string; + } + + interface ClosableNode { + /** + * Whether the parsed CSS value ended before the node was properly closed + */ + unclosed?: true; + } + + interface AdjacentAwareNode { + /** + * The token at the start of the node + */ + before: string; + + /** + * The token at the end of the node + */ + after: string; + } + + interface CommentNode extends BaseNode, ClosableNode { + type: "comment"; + } + + interface DivNode extends BaseNode, AdjacentAwareNode { + type: "div"; + } + + interface FunctionNode extends BaseNode, ClosableNode, AdjacentAwareNode { + type: "function"; + + /** + * Nodes inside the function + */ + nodes: Node[]; + } + + interface SpaceNode extends BaseNode { + type: "space"; + } + + interface StringNode extends BaseNode, ClosableNode { + type: "string"; + + /** + * The quote type delimiting the string + */ + quote: '"' | "'"; + } + + interface UnicodeRangeNode extends BaseNode { + type: "unicode-range"; + } + + interface WordNode extends BaseNode { + type: "word"; + } + + /** + * Any node parsed from a CSS value + */ + type Node = + | CommentNode + | DivNode + | FunctionNode + | SpaceNode + | StringNode + | UnicodeRangeNode + | WordNode; + + interface CustomStringifierCallback { + /** + * @param node The node to stringify + * @returns The serialized CSS representation of the node + */ + (nodes: Node): string | undefined; + } + + interface WalkCallback { + /** + * @param node The currently visited node + * @param index The index of the node in the series of parsed nodes + * @param nodes The series of parsed nodes + * @returns Returning `false` will prevent traversal of descendant nodes (only applies if `bubble` was set to `true` in the `walk()` call) + */ + (node: Node, index: number, nodes: Node[]): void | boolean; + } + + /** + * A CSS dimension, decomposed into its numeric and unit parts + */ + interface Dimension { + number: string; + unit: string; + } + + /** + * A wrapper around a parsed CSS value that allows for inspecting and walking nodes + */ + interface ParsedValue { + /** + * The series of parsed nodes + */ + nodes: Node[]; + + /** + * Walk all parsed nodes, applying a callback + * + * @param callback A visitor callback that will be executed for each node + * @param bubble When set to `true`, walking will be done inside-out instead of outside-in + */ + walk(callback: WalkCallback, bubble?: boolean): this; + } + + interface ValueParser { + /** + * Decompose a CSS dimension into its numeric and unit part + * + * @param value The dimension to decompose + * @returns An object representing `number` and `unit` part of the dimension or `false` if the decomposing fails + */ + unit(value: string): Dimension | false; + + /** + * Serialize a series of nodes into a CSS value + * + * @param nodes The nodes to stringify + * @param custom A custom stringifier callback + * @returns The generated CSS value + */ + stringify(nodes: Node | Node[], custom?: CustomStringifierCallback): string; + + /** + * Walk a series of nodes, applying a callback + * + * @param nodes The nodes to walk + * @param callback A visitor callback that will be executed for each node + * @param bubble When set to `true`, walking will be done inside-out instead of outside-in + */ + walk(nodes: Node[], callback: WalkCallback, bubble?: boolean): void; + + /** + * Parse a CSS value into a series of nodes to operate on + * + * @param value The value to parse + */ + new (value: string): ParsedValue; + + /** + * Parse a CSS value into a series of nodes to operate on + * + * @param value The value to parse + */ + (value: string): ParsedValue; + } +} + +declare const postcssValueParser: postcssValueParser.ValueParser; + +export = postcssValueParser; diff --git a/node_modules/postcss-value-parser/lib/index.js b/node_modules/postcss-value-parser/lib/index.js new file mode 100644 index 0000000..f9ac0e6 --- /dev/null +++ b/node_modules/postcss-value-parser/lib/index.js @@ -0,0 +1,28 @@ +var parse = require("./parse"); +var walk = require("./walk"); +var stringify = require("./stringify"); + +function ValueParser(value) { + if (this instanceof ValueParser) { + this.nodes = parse(value); + return this; + } + return new ValueParser(value); +} + +ValueParser.prototype.toString = function() { + return Array.isArray(this.nodes) ? stringify(this.nodes) : ""; +}; + +ValueParser.prototype.walk = function(cb, bubble) { + walk(this.nodes, cb, bubble); + return this; +}; + +ValueParser.unit = require("./unit"); + +ValueParser.walk = walk; + +ValueParser.stringify = stringify; + +module.exports = ValueParser; diff --git a/node_modules/postcss-value-parser/lib/parse.js b/node_modules/postcss-value-parser/lib/parse.js new file mode 100644 index 0000000..950631c --- /dev/null +++ b/node_modules/postcss-value-parser/lib/parse.js @@ -0,0 +1,321 @@ +var openParentheses = "(".charCodeAt(0); +var closeParentheses = ")".charCodeAt(0); +var singleQuote = "'".charCodeAt(0); +var doubleQuote = '"'.charCodeAt(0); +var backslash = "\\".charCodeAt(0); +var slash = "/".charCodeAt(0); +var comma = ",".charCodeAt(0); +var colon = ":".charCodeAt(0); +var star = "*".charCodeAt(0); +var uLower = "u".charCodeAt(0); +var uUpper = "U".charCodeAt(0); +var plus = "+".charCodeAt(0); +var isUnicodeRange = /^[a-f0-9?-]+$/i; + +module.exports = function(input) { + var tokens = []; + var value = input; + + var next, + quote, + prev, + token, + escape, + escapePos, + whitespacePos, + parenthesesOpenPos; + var pos = 0; + var code = value.charCodeAt(pos); + var max = value.length; + var stack = [{ nodes: tokens }]; + var balanced = 0; + var parent; + + var name = ""; + var before = ""; + var after = ""; + + while (pos < max) { + // Whitespaces + if (code <= 32) { + next = pos; + do { + next += 1; + code = value.charCodeAt(next); + } while (code <= 32); + token = value.slice(pos, next); + + prev = tokens[tokens.length - 1]; + if (code === closeParentheses && balanced) { + after = token; + } else if (prev && prev.type === "div") { + prev.after = token; + prev.sourceEndIndex += token.length; + } else if ( + code === comma || + code === colon || + (code === slash && + value.charCodeAt(next + 1) !== star && + (!parent || + (parent && parent.type === "function" && parent.value !== "calc"))) + ) { + before = token; + } else { + tokens.push({ + type: "space", + sourceIndex: pos, + sourceEndIndex: next, + value: token + }); + } + + pos = next; + + // Quotes + } else if (code === singleQuote || code === doubleQuote) { + next = pos; + quote = code === singleQuote ? "'" : '"'; + token = { + type: "string", + sourceIndex: pos, + quote: quote + }; + do { + escape = false; + next = value.indexOf(quote, next + 1); + if (~next) { + escapePos = next; + while (value.charCodeAt(escapePos - 1) === backslash) { + escapePos -= 1; + escape = !escape; + } + } else { + value += quote; + next = value.length - 1; + token.unclosed = true; + } + } while (escape); + token.value = value.slice(pos + 1, next); + token.sourceEndIndex = token.unclosed ? next : next + 1; + tokens.push(token); + pos = next + 1; + code = value.charCodeAt(pos); + + // Comments + } else if (code === slash && value.charCodeAt(pos + 1) === star) { + next = value.indexOf("*/", pos); + + token = { + type: "comment", + sourceIndex: pos, + sourceEndIndex: next + 2 + }; + + if (next === -1) { + token.unclosed = true; + next = value.length; + token.sourceEndIndex = next; + } + + token.value = value.slice(pos + 2, next); + tokens.push(token); + + pos = next + 2; + code = value.charCodeAt(pos); + + // Operation within calc + } else if ( + (code === slash || code === star) && + parent && + parent.type === "function" && + parent.value === "calc" + ) { + token = value[pos]; + tokens.push({ + type: "word", + sourceIndex: pos - before.length, + sourceEndIndex: pos + token.length, + value: token + }); + pos += 1; + code = value.charCodeAt(pos); + + // Dividers + } else if (code === slash || code === comma || code === colon) { + token = value[pos]; + + tokens.push({ + type: "div", + sourceIndex: pos - before.length, + sourceEndIndex: pos + token.length, + value: token, + before: before, + after: "" + }); + before = ""; + + pos += 1; + code = value.charCodeAt(pos); + + // Open parentheses + } else if (openParentheses === code) { + // Whitespaces after open parentheses + next = pos; + do { + next += 1; + code = value.charCodeAt(next); + } while (code <= 32); + parenthesesOpenPos = pos; + token = { + type: "function", + sourceIndex: pos - name.length, + value: name, + before: value.slice(parenthesesOpenPos + 1, next) + }; + pos = next; + + if (name === "url" && code !== singleQuote && code !== doubleQuote) { + next -= 1; + do { + escape = false; + next = value.indexOf(")", next + 1); + if (~next) { + escapePos = next; + while (value.charCodeAt(escapePos - 1) === backslash) { + escapePos -= 1; + escape = !escape; + } + } else { + value += ")"; + next = value.length - 1; + token.unclosed = true; + } + } while (escape); + // Whitespaces before closed + whitespacePos = next; + do { + whitespacePos -= 1; + code = value.charCodeAt(whitespacePos); + } while (code <= 32); + if (parenthesesOpenPos < whitespacePos) { + if (pos !== whitespacePos + 1) { + token.nodes = [ + { + type: "word", + sourceIndex: pos, + sourceEndIndex: whitespacePos + 1, + value: value.slice(pos, whitespacePos + 1) + } + ]; + } else { + token.nodes = []; + } + if (token.unclosed && whitespacePos + 1 !== next) { + token.after = ""; + token.nodes.push({ + type: "space", + sourceIndex: whitespacePos + 1, + sourceEndIndex: next, + value: value.slice(whitespacePos + 1, next) + }); + } else { + token.after = value.slice(whitespacePos + 1, next); + token.sourceEndIndex = next; + } + } else { + token.after = ""; + token.nodes = []; + } + pos = next + 1; + token.sourceEndIndex = token.unclosed ? next : pos; + code = value.charCodeAt(pos); + tokens.push(token); + } else { + balanced += 1; + token.after = ""; + token.sourceEndIndex = pos + 1; + tokens.push(token); + stack.push(token); + tokens = token.nodes = []; + parent = token; + } + name = ""; + + // Close parentheses + } else if (closeParentheses === code && balanced) { + pos += 1; + code = value.charCodeAt(pos); + + parent.after = after; + parent.sourceEndIndex += after.length; + after = ""; + balanced -= 1; + stack[stack.length - 1].sourceEndIndex = pos; + stack.pop(); + parent = stack[balanced]; + tokens = parent.nodes; + + // Words + } else { + next = pos; + do { + if (code === backslash) { + next += 1; + } + next += 1; + code = value.charCodeAt(next); + } while ( + next < max && + !( + code <= 32 || + code === singleQuote || + code === doubleQuote || + code === comma || + code === colon || + code === slash || + code === openParentheses || + (code === star && + parent && + parent.type === "function" && + parent.value === "calc") || + (code === slash && + parent.type === "function" && + parent.value === "calc") || + (code === closeParentheses && balanced) + ) + ); + token = value.slice(pos, next); + + if (openParentheses === code) { + name = token; + } else if ( + (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) && + plus === token.charCodeAt(1) && + isUnicodeRange.test(token.slice(2)) + ) { + tokens.push({ + type: "unicode-range", + sourceIndex: pos, + sourceEndIndex: next, + value: token + }); + } else { + tokens.push({ + type: "word", + sourceIndex: pos, + sourceEndIndex: next, + value: token + }); + } + + pos = next; + } + } + + for (pos = stack.length - 1; pos; pos -= 1) { + stack[pos].unclosed = true; + stack[pos].sourceEndIndex = value.length; + } + + return stack[0].nodes; +}; diff --git a/node_modules/postcss-value-parser/lib/stringify.js b/node_modules/postcss-value-parser/lib/stringify.js new file mode 100644 index 0000000..6079671 --- /dev/null +++ b/node_modules/postcss-value-parser/lib/stringify.js @@ -0,0 +1,48 @@ +function stringifyNode(node, custom) { + var type = node.type; + var value = node.value; + var buf; + var customResult; + + if (custom && (customResult = custom(node)) !== undefined) { + return customResult; + } else if (type === "word" || type === "space") { + return value; + } else if (type === "string") { + buf = node.quote || ""; + return buf + value + (node.unclosed ? "" : buf); + } else if (type === "comment") { + return "/*" + value + (node.unclosed ? "" : "*/"); + } else if (type === "div") { + return (node.before || "") + value + (node.after || ""); + } else if (Array.isArray(node.nodes)) { + buf = stringify(node.nodes, custom); + if (type !== "function") { + return buf; + } + return ( + value + + "(" + + (node.before || "") + + buf + + (node.after || "") + + (node.unclosed ? "" : ")") + ); + } + return value; +} + +function stringify(nodes, custom) { + var result, i; + + if (Array.isArray(nodes)) { + result = ""; + for (i = nodes.length - 1; ~i; i -= 1) { + result = stringifyNode(nodes[i], custom) + result; + } + return result; + } + return stringifyNode(nodes, custom); +} + +module.exports = stringify; diff --git a/node_modules/postcss-value-parser/lib/unit.js b/node_modules/postcss-value-parser/lib/unit.js new file mode 100644 index 0000000..c349661 --- /dev/null +++ b/node_modules/postcss-value-parser/lib/unit.js @@ -0,0 +1,120 @@ +var minus = "-".charCodeAt(0); +var plus = "+".charCodeAt(0); +var dot = ".".charCodeAt(0); +var exp = "e".charCodeAt(0); +var EXP = "E".charCodeAt(0); + +// Check if three code points would start a number +// https://www.w3.org/TR/css-syntax-3/#starts-with-a-number +function likeNumber(value) { + var code = value.charCodeAt(0); + var nextCode; + + if (code === plus || code === minus) { + nextCode = value.charCodeAt(1); + + if (nextCode >= 48 && nextCode <= 57) { + return true; + } + + var nextNextCode = value.charCodeAt(2); + + if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) { + return true; + } + + return false; + } + + if (code === dot) { + nextCode = value.charCodeAt(1); + + if (nextCode >= 48 && nextCode <= 57) { + return true; + } + + return false; + } + + if (code >= 48 && code <= 57) { + return true; + } + + return false; +} + +// Consume a number +// https://www.w3.org/TR/css-syntax-3/#consume-number +module.exports = function(value) { + var pos = 0; + var length = value.length; + var code; + var nextCode; + var nextNextCode; + + if (length === 0 || !likeNumber(value)) { + return false; + } + + code = value.charCodeAt(pos); + + if (code === plus || code === minus) { + pos++; + } + + while (pos < length) { + code = value.charCodeAt(pos); + + if (code < 48 || code > 57) { + break; + } + + pos += 1; + } + + code = value.charCodeAt(pos); + nextCode = value.charCodeAt(pos + 1); + + if (code === dot && nextCode >= 48 && nextCode <= 57) { + pos += 2; + + while (pos < length) { + code = value.charCodeAt(pos); + + if (code < 48 || code > 57) { + break; + } + + pos += 1; + } + } + + code = value.charCodeAt(pos); + nextCode = value.charCodeAt(pos + 1); + nextNextCode = value.charCodeAt(pos + 2); + + if ( + (code === exp || code === EXP) && + ((nextCode >= 48 && nextCode <= 57) || + ((nextCode === plus || nextCode === minus) && + nextNextCode >= 48 && + nextNextCode <= 57)) + ) { + pos += nextCode === plus || nextCode === minus ? 3 : 2; + + while (pos < length) { + code = value.charCodeAt(pos); + + if (code < 48 || code > 57) { + break; + } + + pos += 1; + } + } + + return { + number: value.slice(0, pos), + unit: value.slice(pos) + }; +}; diff --git a/node_modules/postcss-value-parser/lib/walk.js b/node_modules/postcss-value-parser/lib/walk.js new file mode 100644 index 0000000..7666c5b --- /dev/null +++ b/node_modules/postcss-value-parser/lib/walk.js @@ -0,0 +1,22 @@ +module.exports = function walk(nodes, cb, bubble) { + var i, max, node, result; + + for (i = 0, max = nodes.length; i < max; i += 1) { + node = nodes[i]; + if (!bubble) { + result = cb(node, i, nodes); + } + + if ( + result !== false && + node.type === "function" && + Array.isArray(node.nodes) + ) { + walk(node.nodes, cb, bubble); + } + + if (bubble) { + cb(node, i, nodes); + } + } +}; diff --git a/node_modules/postcss-value-parser/package.json b/node_modules/postcss-value-parser/package.json new file mode 100644 index 0000000..02d744a --- /dev/null +++ b/node_modules/postcss-value-parser/package.json @@ -0,0 +1,58 @@ +{ + "name": "postcss-value-parser", + "version": "4.2.0", + "description": "Transforms css values and at-rule params into the tree", + "main": "lib/index.js", + "files": [ + "lib" + ], + "devDependencies": { + "eslint": "^5.16.0", + "husky": "^2.3.0", + "lint-staged": "^8.1.7", + "prettier": "^1.17.1", + "tap-spec": "^5.0.0", + "tape": "^4.10.2" + }, + "scripts": { + "lint:prettier": "prettier \"**/*.js\" \"**/*.ts\" --list-different", + "lint:js": "eslint . --cache", + "lint": "yarn lint:js && yarn lint:prettier", + "pretest": "yarn lint", + "test": "tape test/*.js | tap-spec" + }, + "eslintConfig": { + "env": { + "es6": true, + "node": true + }, + "extends": "eslint:recommended" + }, + "lint-staged": { + "*.js": [ + "eslint", + "prettier --write", + "git add" + ] + }, + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, + "author": "Bogdan Chadkin ", + "license": "MIT", + "homepage": "https://github.com/TrySound/postcss-value-parser", + "repository": { + "type": "git", + "url": "https://github.com/TrySound/postcss-value-parser.git" + }, + "keywords": [ + "postcss", + "value", + "parser" + ], + "bugs": { + "url": "https://github.com/TrySound/postcss-value-parser/issues" + } +} diff --git a/node_modules/postcss/LICENSE b/node_modules/postcss/LICENSE new file mode 100644 index 0000000..da057b4 --- /dev/null +++ b/node_modules/postcss/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright 2013 Andrey Sitnik + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/postcss/README.md b/node_modules/postcss/README.md new file mode 100644 index 0000000..05fed07 --- /dev/null +++ b/node_modules/postcss/README.md @@ -0,0 +1,29 @@ +# PostCSS + +Philosopher’s stone, logo of PostCSS + +PostCSS is a tool for transforming styles with JS plugins. +These plugins can lint your CSS, support variables and mixins, +transpile future CSS syntax, inline images, and more. + +PostCSS is used by industry leaders including Wikipedia, Twitter, Alibaba, +and JetBrains. The [Autoprefixer] and [Stylelint] PostCSS plugins are some of the most popular CSS tools. + +--- + +  Built by + Evil Martians, go-to agency for developer tools. + +--- + +[Abstract Syntax Tree]: https://en.wikipedia.org/wiki/Abstract_syntax_tree +[Evil Martians]: https://evilmartians.com/?utm_source=postcss +[Autoprefixer]: https://github.com/postcss/autoprefixer +[Stylelint]: https://stylelint.io/ +[plugins]: https://github.com/postcss/postcss#plugins + + +## Docs +Read full docs **[here](https://postcss.org/)**. diff --git a/node_modules/postcss/lib/at-rule.d.ts b/node_modules/postcss/lib/at-rule.d.ts new file mode 100644 index 0000000..89fb505 --- /dev/null +++ b/node_modules/postcss/lib/at-rule.d.ts @@ -0,0 +1,140 @@ +import Container, { + ContainerProps, + ContainerWithChildren +} from './container.js' + +declare namespace AtRule { + export interface AtRuleRaws extends Record { + /** + * The space symbols after the last child of the node to the end of the node. + */ + after?: string + + /** + * The space between the at-rule name and its parameters. + */ + afterName?: string + + /** + * The space symbols before the node. It also stores `*` + * and `_` symbols before the declaration (IE hack). + */ + before?: string + + /** + * The symbols between the last parameter and `{` for rules. + */ + between?: string + + /** + * The rule’s selector with comments. + */ + params?: { + raw: string + value: string + } + + /** + * Contains `true` if the last child has an (optional) semicolon. + */ + semicolon?: boolean + } + + export interface AtRuleProps extends ContainerProps { + /** Name of the at-rule. */ + name: string + /** Parameters following the name of the at-rule. */ + params?: number | string + /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ + raws?: AtRuleRaws + } + + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { AtRule_ as default } +} + +/** + * Represents an at-rule. + * + * ```js + * Once (root, { AtRule }) { + * let media = new AtRule({ name: 'media', params: 'print' }) + * media.append(…) + * root.append(media) + * } + * ``` + * + * If it’s followed in the CSS by a `{}` block, this node will have + * a nodes property representing its children. + * + * ```js + * const root = postcss.parse('@charset "UTF-8"; @media print {}') + * + * const charset = root.first + * charset.type //=> 'atrule' + * charset.nodes //=> undefined + * + * const media = root.last + * media.nodes //=> [] + * ``` + */ +declare class AtRule_ extends Container { + /** + * An array containing the layer’s children. + * + * ```js + * const root = postcss.parse('@layer example { a { color: black } }') + * const layer = root.first + * layer.nodes.length //=> 1 + * layer.nodes[0].selector //=> 'a' + * ``` + * + * Can be `undefinded` if the at-rule has no body. + * + * ```js + * const root = postcss.parse('@layer a, b, c;') + * const layer = root.first + * layer.nodes //=> undefined + * ``` + */ + nodes: Container['nodes'] | undefined + parent: ContainerWithChildren | undefined + + raws: AtRule.AtRuleRaws + type: 'atrule' + /** + * The at-rule’s name immediately follows the `@`. + * + * ```js + * const root = postcss.parse('@media print {}') + * const media = root.first + * media.name //=> 'media' + * ``` + */ + get name(): string + set name(value: string) + + /** + * The at-rule’s parameters, the values that follow the at-rule’s name + * but precede any `{}` block. + * + * ```js + * const root = postcss.parse('@media print, screen {}') + * const media = root.first + * media.params //=> 'print, screen' + * ``` + */ + get params(): string + + set params(value: string) + + constructor(defaults?: AtRule.AtRuleProps) + assign(overrides: AtRule.AtRuleProps | object): this + clone(overrides?: Partial): this + cloneAfter(overrides?: Partial): this + cloneBefore(overrides?: Partial): this +} + +declare class AtRule extends AtRule_ {} + +export = AtRule diff --git a/node_modules/postcss/lib/at-rule.js b/node_modules/postcss/lib/at-rule.js new file mode 100644 index 0000000..9486447 --- /dev/null +++ b/node_modules/postcss/lib/at-rule.js @@ -0,0 +1,25 @@ +'use strict' + +let Container = require('./container') + +class AtRule extends Container { + constructor(defaults) { + super(defaults) + this.type = 'atrule' + } + + append(...children) { + if (!this.proxyOf.nodes) this.nodes = [] + return super.append(...children) + } + + prepend(...children) { + if (!this.proxyOf.nodes) this.nodes = [] + return super.prepend(...children) + } +} + +module.exports = AtRule +AtRule.default = AtRule + +Container.registerAtRule(AtRule) diff --git a/node_modules/postcss/lib/comment.d.ts b/node_modules/postcss/lib/comment.d.ts new file mode 100644 index 0000000..6f1f66f --- /dev/null +++ b/node_modules/postcss/lib/comment.d.ts @@ -0,0 +1,68 @@ +import Container from './container.js' +import Node, { NodeProps } from './node.js' + +declare namespace Comment { + export interface CommentRaws extends Record { + /** + * The space symbols before the node. + */ + before?: string + + /** + * The space symbols between `/*` and the comment’s text. + */ + left?: string + + /** + * The space symbols between the comment’s text. + */ + right?: string + } + + export interface CommentProps extends NodeProps { + /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ + raws?: CommentRaws + /** Content of the comment. */ + text: string + } + + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Comment_ as default } +} + +/** + * It represents a class that handles + * [CSS comments](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments) + * + * ```js + * Once (root, { Comment }) { + * const note = new Comment({ text: 'Note: …' }) + * root.append(note) + * } + * ``` + * + * Remember that CSS comments inside selectors, at-rule parameters, + * or declaration values will be stored in the `raws` properties + * explained above. + */ +declare class Comment_ extends Node { + parent: Container | undefined + raws: Comment.CommentRaws + type: 'comment' + /** + * The comment's text. + */ + get text(): string + + set text(value: string) + + constructor(defaults?: Comment.CommentProps) + assign(overrides: Comment.CommentProps | object): this + clone(overrides?: Partial): this + cloneAfter(overrides?: Partial): this + cloneBefore(overrides?: Partial): this +} + +declare class Comment extends Comment_ {} + +export = Comment diff --git a/node_modules/postcss/lib/comment.js b/node_modules/postcss/lib/comment.js new file mode 100644 index 0000000..c566506 --- /dev/null +++ b/node_modules/postcss/lib/comment.js @@ -0,0 +1,13 @@ +'use strict' + +let Node = require('./node') + +class Comment extends Node { + constructor(defaults) { + super(defaults) + this.type = 'comment' + } +} + +module.exports = Comment +Comment.default = Comment diff --git a/node_modules/postcss/lib/container.d.ts b/node_modules/postcss/lib/container.d.ts new file mode 100644 index 0000000..c2b310b --- /dev/null +++ b/node_modules/postcss/lib/container.d.ts @@ -0,0 +1,483 @@ +import AtRule from './at-rule.js' +import Comment from './comment.js' +import Declaration from './declaration.js' +import Node, { ChildNode, ChildProps, NodeProps } from './node.js' +import { Root } from './postcss.js' +import Rule from './rule.js' + +declare namespace Container { + export type ContainerWithChildren = { + nodes: Child[] + } & ( + | AtRule + | Root + | Rule + ) + + export interface ValueOptions { + /** + * String that’s used to narrow down values and speed up the regexp search. + */ + fast?: string + + /** + * An array of property names. + */ + props?: readonly string[] + } + + export interface ContainerProps extends NodeProps { + nodes?: readonly (ChildProps | Node)[] + } + + /** + * All types that can be passed into container methods to create or add a new + * child node. + */ + export type NewChild = + | ChildProps + | Node + | readonly ChildProps[] + | readonly Node[] + | readonly string[] + | string + | undefined + + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Container_ as default } +} + +/** + * The `Root`, `AtRule`, and `Rule` container nodes + * inherit some common methods to help work with their children. + * + * Note that all containers can store any content. If you write a rule inside + * a rule, PostCSS will parse it. + */ +declare abstract class Container_ extends Node { + /** + * An array containing the container’s children. + * + * ```js + * const root = postcss.parse('a { color: black }') + * root.nodes.length //=> 1 + * root.nodes[0].selector //=> 'a' + * root.nodes[0].nodes[0].prop //=> 'color' + * ``` + */ + nodes: Child[] | undefined + + /** + * The container’s first child. + * + * ```js + * rule.first === rules.nodes[0] + * ``` + */ + get first(): Child | undefined + + /** + * The container’s last child. + * + * ```js + * rule.last === rule.nodes[rule.nodes.length - 1] + * ``` + */ + get last(): Child | undefined + /** + * Inserts new nodes to the end of the container. + * + * ```js + * const decl1 = new Declaration({ prop: 'color', value: 'black' }) + * const decl2 = new Declaration({ prop: 'background-color', value: 'white' }) + * rule.append(decl1, decl2) + * + * root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule + * root.append({ selector: 'a' }) // rule + * rule.append({ prop: 'color', value: 'black' }) // declaration + * rule.append({ text: 'Comment' }) // comment + * + * root.append('a {}') + * root.first.append('color: black; z-index: 1') + * ``` + * + * @param nodes New nodes. + * @return This node for methods chain. + */ + append(...nodes: Container.NewChild[]): this + assign(overrides: Container.ContainerProps | object): this + clone(overrides?: Partial): this + + cloneAfter(overrides?: Partial): this + + cloneBefore(overrides?: Partial): this + /** + * Iterates through the container’s immediate children, + * calling `callback` for each child. + * + * Returning `false` in the callback will break iteration. + * + * This method only iterates through the container’s immediate children. + * If you need to recursively iterate through all the container’s descendant + * nodes, use `Container#walk`. + * + * Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe + * if you are mutating the array of child nodes during iteration. + * PostCSS will adjust the current index to match the mutations. + * + * ```js + * const root = postcss.parse('a { color: black; z-index: 1 }') + * const rule = root.first + * + * for (const decl of rule.nodes) { + * decl.cloneBefore({ prop: '-webkit-' + decl.prop }) + * // Cycle will be infinite, because cloneBefore moves the current node + * // to the next index + * } + * + * rule.each(decl => { + * decl.cloneBefore({ prop: '-webkit-' + decl.prop }) + * // Will be executed only for color and z-index + * }) + * ``` + * + * @param callback Iterator receives each node and index. + * @return Returns `false` if iteration was broke. + */ + each( + callback: (node: Child, index: number) => false | void + ): false | undefined + + /** + * Returns `true` if callback returns `true` + * for all of the container’s children. + * + * ```js + * const noPrefixes = rule.every(i => i.prop[0] !== '-') + * ``` + * + * @param condition Iterator returns true or false. + * @return Is every child pass condition. + */ + every( + condition: (node: Child, index: number, nodes: Child[]) => boolean + ): boolean + /** + * Returns a `child`’s index within the `Container#nodes` array. + * + * ```js + * rule.index( rule.nodes[2] ) //=> 2 + * ``` + * + * @param child Child of the current container. + * @return Child index. + */ + index(child: Child | number): number + + /** + * Insert new node after old node within the container. + * + * @param oldNode Child or child’s index. + * @param newNode New node. + * @return This node for methods chain. + */ + insertAfter(oldNode: Child | number, newNode: Container.NewChild): this + + /** + * Traverses the container’s descendant nodes, calling callback + * for each comment node. + * + * Like `Container#each`, this method is safe + * to use if you are mutating arrays during iteration. + * + * ```js + * root.walkComments(comment => { + * comment.remove() + * }) + * ``` + * + * @param callback Iterator receives each node and index. + * @return Returns `false` if iteration was broke. + */ + + /** + * Insert new node before old node within the container. + * + * ```js + * rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop })) + * ``` + * + * @param oldNode Child or child’s index. + * @param newNode New node. + * @return This node for methods chain. + */ + insertBefore(oldNode: Child | number, newNode: Container.NewChild): this + /** + * Inserts new nodes to the start of the container. + * + * ```js + * const decl1 = new Declaration({ prop: 'color', value: 'black' }) + * const decl2 = new Declaration({ prop: 'background-color', value: 'white' }) + * rule.prepend(decl1, decl2) + * + * root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule + * root.append({ selector: 'a' }) // rule + * rule.append({ prop: 'color', value: 'black' }) // declaration + * rule.append({ text: 'Comment' }) // comment + * + * root.append('a {}') + * root.first.append('color: black; z-index: 1') + * ``` + * + * @param nodes New nodes. + * @return This node for methods chain. + */ + prepend(...nodes: Container.NewChild[]): this + + /** + * Add child to the end of the node. + * + * ```js + * rule.push(new Declaration({ prop: 'color', value: 'black' })) + * ``` + * + * @param child New node. + * @return This node for methods chain. + */ + push(child: Child): this + + /** + * Removes all children from the container + * and cleans their parent properties. + * + * ```js + * rule.removeAll() + * rule.nodes.length //=> 0 + * ``` + * + * @return This node for methods chain. + */ + removeAll(): this + + /** + * Removes node from the container and cleans the parent properties + * from the node and its children. + * + * ```js + * rule.nodes.length //=> 5 + * rule.removeChild(decl) + * rule.nodes.length //=> 4 + * decl.parent //=> undefined + * ``` + * + * @param child Child or child’s index. + * @return This node for methods chain. + */ + removeChild(child: Child | number): this + + replaceValues( + pattern: RegExp | string, + replaced: { (substring: string, ...args: any[]): string } | string + ): this + /** + * Passes all declaration values within the container that match pattern + * through callback, replacing those values with the returned result + * of callback. + * + * This method is useful if you are using a custom unit or function + * and need to iterate through all values. + * + * ```js + * root.replaceValues(/\d+rem/, { fast: 'rem' }, string => { + * return 15 * parseInt(string) + 'px' + * }) + * ``` + * + * @param pattern Replace pattern. + * @param {object} options Options to speed up the search. + * @param replaced String to replace pattern or callback + * that returns a new value. The callback + * will receive the same arguments + * as those passed to a function parameter + * of `String#replace`. + * @return This node for methods chain. + */ + replaceValues( + pattern: RegExp | string, + options: Container.ValueOptions, + replaced: { (substring: string, ...args: any[]): string } | string + ): this + + /** + * Returns `true` if callback returns `true` for (at least) one + * of the container’s children. + * + * ```js + * const hasPrefix = rule.some(i => i.prop[0] === '-') + * ``` + * + * @param condition Iterator returns true or false. + * @return Is some child pass condition. + */ + some( + condition: (node: Child, index: number, nodes: Child[]) => boolean + ): boolean + + /** + * Traverses the container’s descendant nodes, calling callback + * for each node. + * + * Like container.each(), this method is safe to use + * if you are mutating arrays during iteration. + * + * If you only need to iterate through the container’s immediate children, + * use `Container#each`. + * + * ```js + * root.walk(node => { + * // Traverses all descendant nodes. + * }) + * ``` + * + * @param callback Iterator receives each node and index. + * @return Returns `false` if iteration was broke. + */ + walk( + callback: (node: ChildNode, index: number) => false | void + ): false | undefined + + /** + * Traverses the container’s descendant nodes, calling callback + * for each at-rule node. + * + * If you pass a filter, iteration will only happen over at-rules + * that have matching names. + * + * Like `Container#each`, this method is safe + * to use if you are mutating arrays during iteration. + * + * ```js + * root.walkAtRules(rule => { + * if (isOld(rule.name)) rule.remove() + * }) + * + * let first = false + * root.walkAtRules('charset', rule => { + * if (!first) { + * first = true + * } else { + * rule.remove() + * } + * }) + * ``` + * + * @param name String or regular expression to filter at-rules by name. + * @param callback Iterator receives each node and index. + * @return Returns `false` if iteration was broke. + */ + walkAtRules( + nameFilter: RegExp | string, + callback: (atRule: AtRule, index: number) => false | void + ): false | undefined + walkAtRules( + callback: (atRule: AtRule, index: number) => false | void + ): false | undefined + + walkComments( + callback: (comment: Comment, indexed: number) => false | void + ): false | undefined + walkComments( + callback: (comment: Comment, indexed: number) => false | void + ): false | undefined + + /** + * Traverses the container’s descendant nodes, calling callback + * for each declaration node. + * + * If you pass a filter, iteration will only happen over declarations + * with matching properties. + * + * ```js + * root.walkDecls(decl => { + * checkPropertySupport(decl.prop) + * }) + * + * root.walkDecls('border-radius', decl => { + * decl.remove() + * }) + * + * root.walkDecls(/^background/, decl => { + * decl.value = takeFirstColorFromGradient(decl.value) + * }) + * ``` + * + * Like `Container#each`, this method is safe + * to use if you are mutating arrays during iteration. + * + * @param prop String or regular expression to filter declarations + * by property name. + * @param callback Iterator receives each node and index. + * @return Returns `false` if iteration was broke. + */ + walkDecls( + propFilter: RegExp | string, + callback: (decl: Declaration, index: number) => false | void + ): false | undefined + walkDecls( + callback: (decl: Declaration, index: number) => false | void + ): false | undefined + /** + * Traverses the container’s descendant nodes, calling callback + * for each rule node. + * + * If you pass a filter, iteration will only happen over rules + * with matching selectors. + * + * Like `Container#each`, this method is safe + * to use if you are mutating arrays during iteration. + * + * ```js + * const selectors = [] + * root.walkRules(rule => { + * selectors.push(rule.selector) + * }) + * console.log(`Your CSS uses ${ selectors.length } selectors`) + * ``` + * + * @param selector String or regular expression to filter rules by selector. + * @param callback Iterator receives each node and index. + * @return Returns `false` if iteration was broke. + */ + walkRules( + selectorFilter: RegExp | string, + callback: (rule: Rule, index: number) => false | void + ): false | undefined + walkRules( + callback: (rule: Rule, index: number) => false | void + ): false | undefined + /** + * An internal method that converts a {@link NewChild} into a list of actual + * child nodes that can then be added to this container. + * + * This ensures that the nodes' parent is set to this container, that they use + * the correct prototype chain, and that they're marked as dirty. + * + * @param mnodes The new node or nodes to add. + * @param sample A node from whose raws the new node's `before` raw should be + * taken. + * @param type This should be set to `'prepend'` if the new nodes will be + * inserted at the beginning of the container. + * @hidden + */ + protected normalize( + nodes: Container.NewChild, + sample: Node | undefined, + type?: 'prepend' | false + ): Child[] +} + +declare class Container< + Child extends Node = ChildNode +> extends Container_ {} + +export = Container diff --git a/node_modules/postcss/lib/container.js b/node_modules/postcss/lib/container.js new file mode 100644 index 0000000..edb07cc --- /dev/null +++ b/node_modules/postcss/lib/container.js @@ -0,0 +1,447 @@ +'use strict' + +let Comment = require('./comment') +let Declaration = require('./declaration') +let Node = require('./node') +let { isClean, my } = require('./symbols') + +let AtRule, parse, Root, Rule + +function cleanSource(nodes) { + return nodes.map(i => { + if (i.nodes) i.nodes = cleanSource(i.nodes) + delete i.source + return i + }) +} + +function markTreeDirty(node) { + node[isClean] = false + if (node.proxyOf.nodes) { + for (let i of node.proxyOf.nodes) { + markTreeDirty(i) + } + } +} + +class Container extends Node { + get first() { + if (!this.proxyOf.nodes) return undefined + return this.proxyOf.nodes[0] + } + + get last() { + if (!this.proxyOf.nodes) return undefined + return this.proxyOf.nodes[this.proxyOf.nodes.length - 1] + } + + append(...children) { + for (let child of children) { + let nodes = this.normalize(child, this.last) + for (let node of nodes) this.proxyOf.nodes.push(node) + } + + this.markDirty() + + return this + } + + cleanRaws(keepBetween) { + super.cleanRaws(keepBetween) + if (this.nodes) { + for (let node of this.nodes) node.cleanRaws(keepBetween) + } + } + + each(callback) { + if (!this.proxyOf.nodes) return undefined + let iterator = this.getIterator() + + let index, result + while (this.indexes[iterator] < this.proxyOf.nodes.length) { + index = this.indexes[iterator] + result = callback(this.proxyOf.nodes[index], index) + if (result === false) break + + this.indexes[iterator] += 1 + } + + delete this.indexes[iterator] + return result + } + + every(condition) { + return this.nodes.every(condition) + } + + getIterator() { + if (!this.lastEach) this.lastEach = 0 + if (!this.indexes) this.indexes = {} + + this.lastEach += 1 + let iterator = this.lastEach + this.indexes[iterator] = 0 + + return iterator + } + + getProxyProcessor() { + return { + get(node, prop) { + if (prop === 'proxyOf') { + return node + } else if (!node[prop]) { + return node[prop] + } else if ( + prop === 'each' || + (typeof prop === 'string' && prop.startsWith('walk')) + ) { + return (...args) => { + return node[prop]( + ...args.map(i => { + if (typeof i === 'function') { + return (child, index) => i(child.toProxy(), index) + } else { + return i + } + }) + ) + } + } else if (prop === 'every' || prop === 'some') { + return cb => { + return node[prop]((child, ...other) => + cb(child.toProxy(), ...other) + ) + } + } else if (prop === 'root') { + return () => node.root().toProxy() + } else if (prop === 'nodes') { + return node.nodes.map(i => i.toProxy()) + } else if (prop === 'first' || prop === 'last') { + return node[prop].toProxy() + } else { + return node[prop] + } + }, + + set(node, prop, value) { + if (node[prop] === value) return true + node[prop] = value + if (prop === 'name' || prop === 'params' || prop === 'selector') { + node.markDirty() + } + return true + } + } + } + + index(child) { + if (typeof child === 'number') return child + if (child.proxyOf) child = child.proxyOf + return this.proxyOf.nodes.indexOf(child) + } + + insertAfter(exist, add) { + let existIndex = this.index(exist) + let nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse() + existIndex = this.index(exist) + for (let node of nodes) this.proxyOf.nodes.splice(existIndex + 1, 0, node) + + let index + for (let id in this.indexes) { + index = this.indexes[id] + if (existIndex < index) { + this.indexes[id] = index + nodes.length + } + } + + this.markDirty() + + return this + } + + insertBefore(exist, add) { + let existIndex = this.index(exist) + let type = existIndex === 0 ? 'prepend' : false + let nodes = this.normalize( + add, + this.proxyOf.nodes[existIndex], + type + ).reverse() + existIndex = this.index(exist) + for (let node of nodes) this.proxyOf.nodes.splice(existIndex, 0, node) + + let index + for (let id in this.indexes) { + index = this.indexes[id] + if (existIndex <= index) { + this.indexes[id] = index + nodes.length + } + } + + this.markDirty() + + return this + } + + normalize(nodes, sample) { + if (typeof nodes === 'string') { + nodes = cleanSource(parse(nodes).nodes) + } else if (typeof nodes === 'undefined') { + nodes = [] + } else if (Array.isArray(nodes)) { + nodes = nodes.slice(0) + for (let i of nodes) { + if (i.parent) i.parent.removeChild(i, 'ignore') + } + } else if (nodes.type === 'root' && this.type !== 'document') { + nodes = nodes.nodes.slice(0) + for (let i of nodes) { + if (i.parent) i.parent.removeChild(i, 'ignore') + } + } else if (nodes.type) { + nodes = [nodes] + } else if (nodes.prop) { + if (typeof nodes.value === 'undefined') { + throw new Error('Value field is missed in node creation') + } else if (typeof nodes.value !== 'string') { + nodes.value = String(nodes.value) + } + nodes = [new Declaration(nodes)] + } else if (nodes.selector || nodes.selectors) { + nodes = [new Rule(nodes)] + } else if (nodes.name) { + nodes = [new AtRule(nodes)] + } else if (nodes.text) { + nodes = [new Comment(nodes)] + } else { + throw new Error('Unknown node type in node creation') + } + + let processed = nodes.map(i => { + /* c8 ignore next */ + if (!i[my]) Container.rebuild(i) + i = i.proxyOf + if (i.parent) i.parent.removeChild(i) + if (i[isClean]) markTreeDirty(i) + + if (!i.raws) i.raws = {} + if (typeof i.raws.before === 'undefined') { + if (sample && typeof sample.raws.before !== 'undefined') { + i.raws.before = sample.raws.before.replace(/\S/g, '') + } + } + i.parent = this.proxyOf + return i + }) + + return processed + } + + prepend(...children) { + children = children.reverse() + for (let child of children) { + let nodes = this.normalize(child, this.first, 'prepend').reverse() + for (let node of nodes) this.proxyOf.nodes.unshift(node) + for (let id in this.indexes) { + this.indexes[id] = this.indexes[id] + nodes.length + } + } + + this.markDirty() + + return this + } + + push(child) { + child.parent = this + this.proxyOf.nodes.push(child) + return this + } + + removeAll() { + for (let node of this.proxyOf.nodes) node.parent = undefined + this.proxyOf.nodes = [] + + this.markDirty() + + return this + } + + removeChild(child) { + child = this.index(child) + this.proxyOf.nodes[child].parent = undefined + this.proxyOf.nodes.splice(child, 1) + + let index + for (let id in this.indexes) { + index = this.indexes[id] + if (index >= child) { + this.indexes[id] = index - 1 + } + } + + this.markDirty() + + return this + } + + replaceValues(pattern, opts, callback) { + if (!callback) { + callback = opts + opts = {} + } + + this.walkDecls(decl => { + if (opts.props && !opts.props.includes(decl.prop)) return + if (opts.fast && !decl.value.includes(opts.fast)) return + + decl.value = decl.value.replace(pattern, callback) + }) + + this.markDirty() + + return this + } + + some(condition) { + return this.nodes.some(condition) + } + + walk(callback) { + return this.each((child, i) => { + let result + try { + result = callback(child, i) + } catch (e) { + throw child.addToError(e) + } + if (result !== false && child.walk) { + result = child.walk(callback) + } + + return result + }) + } + + walkAtRules(name, callback) { + if (!callback) { + callback = name + return this.walk((child, i) => { + if (child.type === 'atrule') { + return callback(child, i) + } + }) + } + if (name instanceof RegExp) { + return this.walk((child, i) => { + if (child.type === 'atrule' && name.test(child.name)) { + return callback(child, i) + } + }) + } + return this.walk((child, i) => { + if (child.type === 'atrule' && child.name === name) { + return callback(child, i) + } + }) + } + + walkComments(callback) { + return this.walk((child, i) => { + if (child.type === 'comment') { + return callback(child, i) + } + }) + } + + walkDecls(prop, callback) { + if (!callback) { + callback = prop + return this.walk((child, i) => { + if (child.type === 'decl') { + return callback(child, i) + } + }) + } + if (prop instanceof RegExp) { + return this.walk((child, i) => { + if (child.type === 'decl' && prop.test(child.prop)) { + return callback(child, i) + } + }) + } + return this.walk((child, i) => { + if (child.type === 'decl' && child.prop === prop) { + return callback(child, i) + } + }) + } + + walkRules(selector, callback) { + if (!callback) { + callback = selector + + return this.walk((child, i) => { + if (child.type === 'rule') { + return callback(child, i) + } + }) + } + if (selector instanceof RegExp) { + return this.walk((child, i) => { + if (child.type === 'rule' && selector.test(child.selector)) { + return callback(child, i) + } + }) + } + return this.walk((child, i) => { + if (child.type === 'rule' && child.selector === selector) { + return callback(child, i) + } + }) + } +} + +Container.registerParse = dependant => { + parse = dependant +} + +Container.registerRule = dependant => { + Rule = dependant +} + +Container.registerAtRule = dependant => { + AtRule = dependant +} + +Container.registerRoot = dependant => { + Root = dependant +} + +module.exports = Container +Container.default = Container + +/* c8 ignore start */ +Container.rebuild = node => { + if (node.type === 'atrule') { + Object.setPrototypeOf(node, AtRule.prototype) + } else if (node.type === 'rule') { + Object.setPrototypeOf(node, Rule.prototype) + } else if (node.type === 'decl') { + Object.setPrototypeOf(node, Declaration.prototype) + } else if (node.type === 'comment') { + Object.setPrototypeOf(node, Comment.prototype) + } else if (node.type === 'root') { + Object.setPrototypeOf(node, Root.prototype) + } + + node[my] = true + + if (node.nodes) { + node.nodes.forEach(child => { + Container.rebuild(child) + }) + } +} +/* c8 ignore stop */ diff --git a/node_modules/postcss/lib/css-syntax-error.d.ts b/node_modules/postcss/lib/css-syntax-error.d.ts new file mode 100644 index 0000000..e540d84 --- /dev/null +++ b/node_modules/postcss/lib/css-syntax-error.d.ts @@ -0,0 +1,248 @@ +import { FilePosition } from './input.js' + +declare namespace CssSyntaxError { + /** + * A position that is part of a range. + */ + export interface RangePosition { + /** + * The column number in the input. + */ + column: number + + /** + * The line number in the input. + */ + line: number + } + + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { CssSyntaxError_ as default } +} + +/** + * The CSS parser throws this error for broken CSS. + * + * Custom parsers can throw this error for broken custom syntax using + * the `Node#error` method. + * + * PostCSS will use the input source map to detect the original error location. + * If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS, + * PostCSS will show the original position in the Sass file. + * + * If you need the position in the PostCSS input + * (e.g., to debug the previous compiler), use `error.input.file`. + * + * ```js + * // Raising error from plugin + * throw node.error('Unknown variable', { plugin: 'postcss-vars' }) + * ``` + * + * ```js + * // Catching and checking syntax error + * try { + * postcss.parse('a{') + * } catch (error) { + * if (error.name === 'CssSyntaxError') { + * error //=> CssSyntaxError + * } + * } + * ``` + */ +declare class CssSyntaxError_ extends Error { + /** + * Source column of the error. + * + * ```js + * error.column //=> 1 + * error.input.column //=> 4 + * ``` + * + * PostCSS will use the input source map to detect the original location. + * If you need the position in the PostCSS input, use `error.input.column`. + */ + column?: number + + /** + * Source column of the error's end, exclusive. Provided if the error pertains + * to a range. + * + * ```js + * error.endColumn //=> 1 + * error.input.endColumn //=> 4 + * ``` + * + * PostCSS will use the input source map to detect the original location. + * If you need the position in the PostCSS input, use `error.input.endColumn`. + */ + endColumn?: number + + /** + * Source line of the error's end, exclusive. Provided if the error pertains + * to a range. + * + * ```js + * error.endLine //=> 3 + * error.input.endLine //=> 4 + * ``` + * + * PostCSS will use the input source map to detect the original location. + * If you need the position in the PostCSS input, use `error.input.endLine`. + */ + endLine?: number + + /** + * Absolute path to the broken file. + * + * ```js + * error.file //=> 'a.sass' + * error.input.file //=> 'a.css' + * ``` + * + * PostCSS will use the input source map to detect the original location. + * If you need the position in the PostCSS input, use `error.input.file`. + */ + file?: string + + /** + * Input object with PostCSS internal information + * about input file. If input has source map + * from previous tool, PostCSS will use origin + * (for example, Sass) source. You can use this + * object to get PostCSS input source. + * + * ```js + * error.input.file //=> 'a.css' + * error.file //=> 'a.sass' + * ``` + */ + input?: FilePosition + + /** + * Source line of the error. + * + * ```js + * error.line //=> 2 + * error.input.line //=> 4 + * ``` + * + * PostCSS will use the input source map to detect the original location. + * If you need the position in the PostCSS input, use `error.input.line`. + */ + line?: number + + /** + * Full error text in the GNU error format + * with plugin, file, line and column. + * + * ```js + * error.message //=> 'a.css:1:1: Unclosed block' + * ``` + */ + message: string + + /** + * Always equal to `'CssSyntaxError'`. You should always check error type + * by `error.name === 'CssSyntaxError'` + * instead of `error instanceof CssSyntaxError`, + * because npm could have several PostCSS versions. + * + * ```js + * if (error.name === 'CssSyntaxError') { + * error //=> CssSyntaxError + * } + * ``` + */ + name: 'CssSyntaxError' + + /** + * Plugin name, if error came from plugin. + * + * ```js + * error.plugin //=> 'postcss-vars' + * ``` + */ + plugin?: string + + /** + * Error message. + * + * ```js + * error.message //=> 'Unclosed block' + * ``` + */ + reason: string + + /** + * Source code of the broken file. + * + * ```js + * error.source //=> 'a { b {} }' + * error.input.source //=> 'a b { }' + * ``` + */ + source?: string + + stack: string + + /** + * Instantiates a CSS syntax error. Can be instantiated for a single position + * or for a range. + * @param message Error message. + * @param lineOrStartPos If for a single position, the line number, or if for + * a range, the inclusive start position of the error. + * @param columnOrEndPos If for a single position, the column number, or if for + * a range, the exclusive end position of the error. + * @param source Source code of the broken file. + * @param file Absolute path to the broken file. + * @param plugin PostCSS plugin name, if error came from plugin. + */ + constructor( + message: string, + lineOrStartPos?: CssSyntaxError.RangePosition | number, + columnOrEndPos?: CssSyntaxError.RangePosition | number, + source?: string, + file?: string, + plugin?: string + ) + + /** + * Returns a few lines of CSS source that caused the error. + * + * If the CSS has an input source map without `sourceContent`, + * this method will return an empty string. + * + * ```js + * error.showSourceCode() //=> " 4 | } + * // 5 | a { + * // > 6 | bad + * // | ^ + * // 7 | } + * // 8 | b {" + * ``` + * + * @param color Whether arrow will be colored red by terminal + * color codes. By default, PostCSS will detect + * color support by `process.stdout.isTTY` + * and `process.env.NODE_DISABLE_COLORS`. + * @return Few lines of CSS source that caused the error. + */ + showSourceCode(color?: boolean): string + + /** + * Returns error position, message and source code of the broken part. + * + * ```js + * error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block + * // > 1 | a { + * // | ^" + * ``` + * + * @return Error position, message and source code. + */ + toString(): string +} + +declare class CssSyntaxError extends CssSyntaxError_ {} + +export = CssSyntaxError diff --git a/node_modules/postcss/lib/css-syntax-error.js b/node_modules/postcss/lib/css-syntax-error.js new file mode 100644 index 0000000..275a4f6 --- /dev/null +++ b/node_modules/postcss/lib/css-syntax-error.js @@ -0,0 +1,133 @@ +'use strict' + +let pico = require('picocolors') + +let terminalHighlight = require('./terminal-highlight') + +class CssSyntaxError extends Error { + constructor(message, line, column, source, file, plugin) { + super(message) + this.name = 'CssSyntaxError' + this.reason = message + + if (file) { + this.file = file + } + if (source) { + this.source = source + } + if (plugin) { + this.plugin = plugin + } + if (typeof line !== 'undefined' && typeof column !== 'undefined') { + if (typeof line === 'number') { + this.line = line + this.column = column + } else { + this.line = line.line + this.column = line.column + this.endLine = column.line + this.endColumn = column.column + } + } + + this.setMessage() + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, CssSyntaxError) + } + } + + setMessage() { + this.message = this.plugin ? this.plugin + ': ' : '' + this.message += this.file ? this.file : '' + if (typeof this.line !== 'undefined') { + this.message += ':' + this.line + ':' + this.column + } + this.message += ': ' + this.reason + } + + showSourceCode(color) { + if (!this.source) return '' + + let css = this.source + if (color == null) color = pico.isColorSupported + + let aside = text => text + let mark = text => text + let highlight = text => text + if (color) { + let { bold, gray, red } = pico.createColors(true) + mark = text => bold(red(text)) + aside = text => gray(text) + if (terminalHighlight) { + highlight = text => terminalHighlight(text) + } + } + + let lines = css.split(/\r?\n/) + let start = Math.max(this.line - 3, 0) + let end = Math.min(this.line + 2, lines.length) + let maxWidth = String(end).length + + return lines + .slice(start, end) + .map((line, index) => { + let number = start + 1 + index + let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ' + if (number === this.line) { + if (line.length > 160) { + let padding = 20 + let subLineStart = Math.max(0, this.column - padding) + let subLineEnd = Math.max( + this.column + padding, + this.endColumn + padding + ) + let subLine = line.slice(subLineStart, subLineEnd) + + let spacing = + aside(gutter.replace(/\d/g, ' ')) + + line + .slice(0, Math.min(this.column - 1, padding - 1)) + .replace(/[^\t]/g, ' ') + + return ( + mark('>') + + aside(gutter) + + highlight(subLine) + + '\n ' + + spacing + + mark('^') + ) + } + + let spacing = + aside(gutter.replace(/\d/g, ' ')) + + line.slice(0, this.column - 1).replace(/[^\t]/g, ' ') + + return ( + mark('>') + + aside(gutter) + + highlight(line) + + '\n ' + + spacing + + mark('^') + ) + } + + return ' ' + aside(gutter) + highlight(line) + }) + .join('\n') + } + + toString() { + let code = this.showSourceCode() + if (code) { + code = '\n\n' + code + '\n' + } + return this.name + ': ' + this.message + code + } +} + +module.exports = CssSyntaxError +CssSyntaxError.default = CssSyntaxError diff --git a/node_modules/postcss/lib/declaration.d.ts b/node_modules/postcss/lib/declaration.d.ts new file mode 100644 index 0000000..d489b42 --- /dev/null +++ b/node_modules/postcss/lib/declaration.d.ts @@ -0,0 +1,151 @@ +import { ContainerWithChildren } from './container.js' +import Node from './node.js' + +declare namespace Declaration { + export interface DeclarationRaws extends Record { + /** + * The space symbols before the node. It also stores `*` + * and `_` symbols before the declaration (IE hack). + */ + before?: string + + /** + * The symbols between the property and value for declarations. + */ + between?: string + + /** + * The content of the important statement, if it is not just `!important`. + */ + important?: string + + /** + * Declaration value with comments. + */ + value?: { + raw: string + value: string + } + } + + export interface DeclarationProps { + /** Whether the declaration has an `!important` annotation. */ + important?: boolean + /** Name of the declaration. */ + prop: string + /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ + raws?: DeclarationRaws + /** Value of the declaration. */ + value: string + } + + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Declaration_ as default } +} + +/** + * It represents a class that handles + * [CSS declarations](https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_declarations) + * + * ```js + * Once (root, { Declaration }) { + * const color = new Declaration({ prop: 'color', value: 'black' }) + * root.append(color) + * } + * ``` + * + * ```js + * const root = postcss.parse('a { color: black }') + * const decl = root.first?.first + * + * decl.type //=> 'decl' + * decl.toString() //=> ' color: black' + * ``` + */ +declare class Declaration_ extends Node { + parent: ContainerWithChildren | undefined + raws: Declaration.DeclarationRaws + + type: 'decl' + + /** + * It represents a specificity of the declaration. + * + * If true, the CSS declaration will have an + * [important](https://developer.mozilla.org/en-US/docs/Web/CSS/important) + * specifier. + * + * ```js + * const root = postcss.parse('a { color: black !important; color: red }') + * + * root.first.first.important //=> true + * root.first.last.important //=> undefined + * ``` + */ + get important(): boolean + set important(value: boolean) + + /** + * The property name for a CSS declaration. + * + * ```js + * const root = postcss.parse('a { color: black }') + * const decl = root.first.first + * + * decl.prop //=> 'color' + * ``` + */ + get prop(): string + + set prop(value: string) + + /** + * The property value for a CSS declaration. + * + * Any CSS comments inside the value string will be filtered out. + * CSS comments present in the source value will be available in + * the `raws` property. + * + * Assigning new `value` would ignore the comments in `raws` + * property while compiling node to string. + * + * ```js + * const root = postcss.parse('a { color: black }') + * const decl = root.first.first + * + * decl.value //=> 'black' + * ``` + */ + get value(): string + set value(value: string) + + /** + * It represents a getter that returns `true` if a declaration starts with + * `--` or `$`, which are used to declare variables in CSS and SASS/SCSS. + * + * ```js + * const root = postcss.parse(':root { --one: 1 }') + * const one = root.first.first + * + * one.variable //=> true + * ``` + * + * ```js + * const root = postcss.parse('$one: 1') + * const one = root.first + * + * one.variable //=> true + * ``` + */ + get variable(): boolean + constructor(defaults?: Declaration.DeclarationProps) + + assign(overrides: Declaration.DeclarationProps | object): this + clone(overrides?: Partial): this + cloneAfter(overrides?: Partial): this + cloneBefore(overrides?: Partial): this +} + +declare class Declaration extends Declaration_ {} + +export = Declaration diff --git a/node_modules/postcss/lib/declaration.js b/node_modules/postcss/lib/declaration.js new file mode 100644 index 0000000..65a03aa --- /dev/null +++ b/node_modules/postcss/lib/declaration.js @@ -0,0 +1,24 @@ +'use strict' + +let Node = require('./node') + +class Declaration extends Node { + get variable() { + return this.prop.startsWith('--') || this.prop[0] === '$' + } + + constructor(defaults) { + if ( + defaults && + typeof defaults.value !== 'undefined' && + typeof defaults.value !== 'string' + ) { + defaults = { ...defaults, value: String(defaults.value) } + } + super(defaults) + this.type = 'decl' + } +} + +module.exports = Declaration +Declaration.default = Declaration diff --git a/node_modules/postcss/lib/document.d.ts b/node_modules/postcss/lib/document.d.ts new file mode 100644 index 0000000..f9e8063 --- /dev/null +++ b/node_modules/postcss/lib/document.d.ts @@ -0,0 +1,69 @@ +import Container, { ContainerProps } from './container.js' +import { ProcessOptions } from './postcss.js' +import Result from './result.js' +import Root from './root.js' + +declare namespace Document { + export interface DocumentProps extends ContainerProps { + nodes?: readonly Root[] + + /** + * Information to generate byte-to-byte equal node string as it was + * in the origin input. + * + * Every parser saves its own properties. + */ + raws?: Record + } + + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Document_ as default } +} + +/** + * Represents a file and contains all its parsed nodes. + * + * **Experimental:** some aspects of this node could change within minor + * or patch version releases. + * + * ```js + * const document = htmlParser( + * '' + * ) + * document.type //=> 'document' + * document.nodes.length //=> 2 + * ``` + */ +declare class Document_ extends Container { + nodes: Root[] + parent: undefined + type: 'document' + + constructor(defaults?: Document.DocumentProps) + + assign(overrides: Document.DocumentProps | object): this + clone(overrides?: Partial): this + cloneAfter(overrides?: Partial): this + cloneBefore(overrides?: Partial): this + + /** + * Returns a `Result` instance representing the document’s CSS roots. + * + * ```js + * const root1 = postcss.parse(css1, { from: 'a.css' }) + * const root2 = postcss.parse(css2, { from: 'b.css' }) + * const document = postcss.document() + * document.append(root1) + * document.append(root2) + * const result = document.toResult({ to: 'all.css', map: true }) + * ``` + * + * @param opts Options. + * @return Result with current document’s CSS. + */ + toResult(options?: ProcessOptions): Result +} + +declare class Document extends Document_ {} + +export = Document diff --git a/node_modules/postcss/lib/document.js b/node_modules/postcss/lib/document.js new file mode 100644 index 0000000..4468991 --- /dev/null +++ b/node_modules/postcss/lib/document.js @@ -0,0 +1,33 @@ +'use strict' + +let Container = require('./container') + +let LazyResult, Processor + +class Document extends Container { + constructor(defaults) { + // type needs to be passed to super, otherwise child roots won't be normalized correctly + super({ type: 'document', ...defaults }) + + if (!this.nodes) { + this.nodes = [] + } + } + + toResult(opts = {}) { + let lazy = new LazyResult(new Processor(), this, opts) + + return lazy.stringify() + } +} + +Document.registerLazyResult = dependant => { + LazyResult = dependant +} + +Document.registerProcessor = dependant => { + Processor = dependant +} + +module.exports = Document +Document.default = Document diff --git a/node_modules/postcss/lib/fromJSON.d.ts b/node_modules/postcss/lib/fromJSON.d.ts new file mode 100644 index 0000000..e1deedb --- /dev/null +++ b/node_modules/postcss/lib/fromJSON.d.ts @@ -0,0 +1,9 @@ +import { JSONHydrator } from './postcss.js' + +interface FromJSON extends JSONHydrator { + default: FromJSON +} + +declare const fromJSON: FromJSON + +export = fromJSON diff --git a/node_modules/postcss/lib/fromJSON.js b/node_modules/postcss/lib/fromJSON.js new file mode 100644 index 0000000..c9ac1a8 --- /dev/null +++ b/node_modules/postcss/lib/fromJSON.js @@ -0,0 +1,54 @@ +'use strict' + +let AtRule = require('./at-rule') +let Comment = require('./comment') +let Declaration = require('./declaration') +let Input = require('./input') +let PreviousMap = require('./previous-map') +let Root = require('./root') +let Rule = require('./rule') + +function fromJSON(json, inputs) { + if (Array.isArray(json)) return json.map(n => fromJSON(n)) + + let { inputs: ownInputs, ...defaults } = json + if (ownInputs) { + inputs = [] + for (let input of ownInputs) { + let inputHydrated = { ...input, __proto__: Input.prototype } + if (inputHydrated.map) { + inputHydrated.map = { + ...inputHydrated.map, + __proto__: PreviousMap.prototype + } + } + inputs.push(inputHydrated) + } + } + if (defaults.nodes) { + defaults.nodes = json.nodes.map(n => fromJSON(n, inputs)) + } + if (defaults.source) { + let { inputId, ...source } = defaults.source + defaults.source = source + if (inputId != null) { + defaults.source.input = inputs[inputId] + } + } + if (defaults.type === 'root') { + return new Root(defaults) + } else if (defaults.type === 'decl') { + return new Declaration(defaults) + } else if (defaults.type === 'rule') { + return new Rule(defaults) + } else if (defaults.type === 'comment') { + return new Comment(defaults) + } else if (defaults.type === 'atrule') { + return new AtRule(defaults) + } else { + throw new Error('Unknown node type: ' + json.type) + } +} + +module.exports = fromJSON +fromJSON.default = fromJSON diff --git a/node_modules/postcss/lib/input.d.ts b/node_modules/postcss/lib/input.d.ts new file mode 100644 index 0000000..3207da3 --- /dev/null +++ b/node_modules/postcss/lib/input.d.ts @@ -0,0 +1,227 @@ +import { CssSyntaxError, ProcessOptions } from './postcss.js' +import PreviousMap from './previous-map.js' + +declare namespace Input { + export interface FilePosition { + /** + * Column of inclusive start position in source file. + */ + column: number + + /** + * Column of exclusive end position in source file. + */ + endColumn?: number + + /** + * Line of exclusive end position in source file. + */ + endLine?: number + + /** + * Offset of exclusive end position in source file. + */ + endOffset?: number + + /** + * Absolute path to the source file. + */ + file?: string + + /** + * Line of inclusive start position in source file. + */ + line: number + + /** + * Offset of inclusive start position in source file. + */ + offset: number + + /** + * Source code. + */ + source?: string + + /** + * URL for the source file. + */ + url: string + } + + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Input_ as default } +} + +/** + * Represents the source CSS. + * + * ```js + * const root = postcss.parse(css, { from: file }) + * const input = root.source.input + * ``` + */ +declare class Input_ { + /** + * Input CSS source. + * + * ```js + * const input = postcss.parse('a{}', { from: file }).input + * input.css //=> "a{}" + * ``` + */ + css: string + + /** + * Input source with support for non-CSS documents. + * + * ```js + * const input = postcss.parse('a{}', { from: file, document: '' }).input + * input.document //=> "" + * input.css //=> "a{}" + * ``` + */ + document: string + + /** + * The absolute path to the CSS source file defined + * with the `from` option. + * + * ```js + * const root = postcss.parse(css, { from: 'a.css' }) + * root.source.input.file //=> '/home/ai/a.css' + * ``` + */ + file?: string + + /** + * The flag to indicate whether or not the source code has Unicode BOM. + */ + hasBOM: boolean + + /** + * The unique ID of the CSS source. It will be created if `from` option + * is not provided (because PostCSS does not know the file path). + * + * ```js + * const root = postcss.parse(css) + * root.source.input.file //=> undefined + * root.source.input.id //=> "" + * ``` + */ + id?: string + + /** + * The input source map passed from a compilation step before PostCSS + * (for example, from Sass compiler). + * + * ```js + * root.source.input.map.consumer().sources //=> ['a.sass'] + * ``` + */ + map: PreviousMap + + /** + * The CSS source identifier. Contains `Input#file` if the user + * set the `from` option, or `Input#id` if they did not. + * + * ```js + * const root = postcss.parse(css, { from: 'a.css' }) + * root.source.input.from //=> "/home/ai/a.css" + * + * const root = postcss.parse(css) + * root.source.input.from //=> "" + * ``` + */ + get from(): string + + /** + * @param css Input CSS source. + * @param opts Process options. + */ + constructor(css: string, opts?: ProcessOptions) + + /** + * Returns `CssSyntaxError` with information about the error and its position. + */ + error( + message: string, + start: + | { + column: number + line: number + } + | { + offset: number + }, + end: + | { + column: number + line: number + } + | { + offset: number + }, + opts?: { plugin?: CssSyntaxError['plugin'] } + ): CssSyntaxError + error( + message: string, + line: number, + column: number, + opts?: { plugin?: CssSyntaxError['plugin'] } + ): CssSyntaxError + error( + message: string, + offset: number, + opts?: { plugin?: CssSyntaxError['plugin'] } + ): CssSyntaxError + + /** + * Converts source line and column to offset. + * + * @param line Source line. + * @param column Source column. + * @return Source offset. + */ + fromLineAndColumn(line: number, column: number): number + + /** + * Converts source offset to line and column. + * + * @param offset Source offset. + */ + fromOffset(offset: number): { col: number; line: number } | null + + /** + * Reads the input source map and returns a symbol position + * in the input source (e.g., in a Sass file that was compiled + * to CSS before being passed to PostCSS). Optionally takes an + * end position, exclusive. + * + * ```js + * root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 } + * root.source.input.origin(1, 1, 1, 4) + * //=> { file: 'a.css', line: 3, column: 1, endLine: 3, endColumn: 4 } + * ``` + * + * @param line Line for inclusive start position in input CSS. + * @param column Column for inclusive start position in input CSS. + * @param endLine Line for exclusive end position in input CSS. + * @param endColumn Column for exclusive end position in input CSS. + * + * @return Position in input source. + */ + origin( + line: number, + column: number, + endLine?: number, + endColumn?: number + ): false | Input.FilePosition + + /** Converts this to a JSON-friendly object representation. */ + toJSON(): object +} + +declare class Input extends Input_ {} + +export = Input diff --git a/node_modules/postcss/lib/input.js b/node_modules/postcss/lib/input.js new file mode 100644 index 0000000..bb0ccf5 --- /dev/null +++ b/node_modules/postcss/lib/input.js @@ -0,0 +1,265 @@ +'use strict' + +let { nanoid } = require('nanoid/non-secure') +let { isAbsolute, resolve } = require('path') +let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') +let { fileURLToPath, pathToFileURL } = require('url') + +let CssSyntaxError = require('./css-syntax-error') +let PreviousMap = require('./previous-map') +let terminalHighlight = require('./terminal-highlight') + +let lineToIndexCache = Symbol('lineToIndexCache') + +let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator) +let pathAvailable = Boolean(resolve && isAbsolute) + +function getLineToIndex(input) { + if (input[lineToIndexCache]) return input[lineToIndexCache] + let lines = input.css.split('\n') + let lineToIndex = new Array(lines.length) + let prevIndex = 0 + + for (let i = 0, l = lines.length; i < l; i++) { + lineToIndex[i] = prevIndex + prevIndex += lines[i].length + 1 + } + + input[lineToIndexCache] = lineToIndex + return lineToIndex +} + +class Input { + get from() { + return this.file || this.id + } + + constructor(css, opts = {}) { + if ( + css === null || + typeof css === 'undefined' || + (typeof css === 'object' && !css.toString) + ) { + throw new Error(`PostCSS received ${css} instead of CSS string`) + } + + this.css = css.toString() + + if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') { + this.hasBOM = true + this.css = this.css.slice(1) + } else { + this.hasBOM = false + } + + this.document = this.css + if (opts.document) this.document = opts.document.toString() + + if (opts.from) { + if ( + !pathAvailable || + /^\w+:\/\//.test(opts.from) || + isAbsolute(opts.from) + ) { + this.file = opts.from + } else { + this.file = resolve(opts.from) + } + } + + if (pathAvailable && sourceMapAvailable) { + let map = new PreviousMap(this.css, opts) + if (map.text) { + this.map = map + let file = map.consumer().file + if (!this.file && file) this.file = this.mapResolve(file) + } + } + + if (!this.file) { + this.id = '' + } + if (this.map) this.map.file = this.from + } + + error(message, line, column, opts = {}) { + let endColumn, endLine, endOffset, offset, result + + if (line && typeof line === 'object') { + let start = line + let end = column + if (typeof start.offset === 'number') { + offset = start.offset + let pos = this.fromOffset(offset) + line = pos.line + column = pos.col + } else { + line = start.line + column = start.column + offset = this.fromLineAndColumn(line, column) + } + if (typeof end.offset === 'number') { + endOffset = end.offset + let pos = this.fromOffset(endOffset) + endLine = pos.line + endColumn = pos.col + } else { + endLine = end.line + endColumn = end.column + endOffset = this.fromLineAndColumn(end.line, end.column) + } + } else if (!column) { + offset = line + let pos = this.fromOffset(offset) + line = pos.line + column = pos.col + } else { + offset = this.fromLineAndColumn(line, column) + } + + let origin = this.origin(line, column, endLine, endColumn) + if (origin) { + result = new CssSyntaxError( + message, + origin.endLine === undefined + ? origin.line + : { column: origin.column, line: origin.line }, + origin.endLine === undefined + ? origin.column + : { column: origin.endColumn, line: origin.endLine }, + origin.source, + origin.file, + opts.plugin + ) + } else { + result = new CssSyntaxError( + message, + endLine === undefined ? line : { column, line }, + endLine === undefined ? column : { column: endColumn, line: endLine }, + this.css, + this.file, + opts.plugin + ) + } + + result.input = { column, endColumn, endLine, endOffset, line, offset, source: this.css } + if (this.file) { + if (pathToFileURL) { + result.input.url = pathToFileURL(this.file).toString() + } + result.input.file = this.file + } + + return result + } + + fromLineAndColumn(line, column) { + let lineToIndex = getLineToIndex(this) + let index = lineToIndex[line - 1] + return index + column - 1 + } + + fromOffset(offset) { + let lineToIndex = getLineToIndex(this) + let lastLine = lineToIndex[lineToIndex.length - 1] + + let min = 0 + if (offset >= lastLine) { + min = lineToIndex.length - 1 + } else { + let max = lineToIndex.length - 2 + let mid + while (min < max) { + mid = min + ((max - min) >> 1) + if (offset < lineToIndex[mid]) { + max = mid - 1 + } else if (offset >= lineToIndex[mid + 1]) { + min = mid + 1 + } else { + min = mid + break + } + } + } + return { + col: offset - lineToIndex[min] + 1, + line: min + 1 + } + } + + mapResolve(file) { + if (/^\w+:\/\//.test(file)) { + return file + } + return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file) + } + + origin(line, column, endLine, endColumn) { + if (!this.map) return false + let consumer = this.map.consumer() + + let from = consumer.originalPositionFor({ column, line }) + if (!from.source) return false + + let to + if (typeof endLine === 'number') { + to = consumer.originalPositionFor({ column: endColumn, line: endLine }) + } + + let fromUrl + + if (isAbsolute(from.source)) { + fromUrl = pathToFileURL(from.source) + } else { + fromUrl = new URL( + from.source, + this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile) + ) + } + + let result = { + column: from.column, + endColumn: to && to.column, + endLine: to && to.line, + line: from.line, + url: fromUrl.toString() + } + + if (fromUrl.protocol === 'file:') { + if (fileURLToPath) { + result.file = fileURLToPath(fromUrl) + } else { + /* c8 ignore next 2 */ + throw new Error(`file: protocol is not available in this PostCSS build`) + } + } + + let source = consumer.sourceContentFor(from.source) + if (source) result.source = source + + return result + } + + toJSON() { + let json = {} + for (let name of ['hasBOM', 'css', 'file', 'id']) { + if (this[name] != null) { + json[name] = this[name] + } + } + if (this.map) { + json.map = { ...this.map } + if (json.map.consumerCache) { + json.map.consumerCache = undefined + } + } + return json + } +} + +module.exports = Input +Input.default = Input + +if (terminalHighlight && terminalHighlight.registerInput) { + terminalHighlight.registerInput(Input) +} diff --git a/node_modules/postcss/lib/lazy-result.d.ts b/node_modules/postcss/lib/lazy-result.d.ts new file mode 100644 index 0000000..2eb7279 --- /dev/null +++ b/node_modules/postcss/lib/lazy-result.d.ts @@ -0,0 +1,190 @@ +import Document from './document.js' +import { SourceMap } from './postcss.js' +import Processor from './processor.js' +import Result, { Message, ResultOptions } from './result.js' +import Root from './root.js' +import Warning from './warning.js' + +declare namespace LazyResult { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { LazyResult_ as default } +} + +/** + * A Promise proxy for the result of PostCSS transformations. + * + * A `LazyResult` instance is returned by `Processor#process`. + * + * ```js + * const lazy = postcss([autoprefixer]).process(css) + * ``` + */ +declare class LazyResult_ + implements PromiseLike> +{ + /** + * Processes input CSS through synchronous and asynchronous plugins + * and calls onRejected for each error thrown in any plugin. + * + * It implements standard Promise API. + * + * ```js + * postcss([autoprefixer]).process(css).then(result => { + * console.log(result.css) + * }).catch(error => { + * console.error(error) + * }) + * ``` + */ + catch: Promise>['catch'] + + /** + * Processes input CSS through synchronous and asynchronous plugins + * and calls onFinally on any error or when all plugins will finish work. + * + * It implements standard Promise API. + * + * ```js + * postcss([autoprefixer]).process(css).finally(() => { + * console.log('processing ended') + * }) + * ``` + */ + finally: Promise>['finally'] + + /** + * Processes input CSS through synchronous and asynchronous plugins + * and calls `onFulfilled` with a Result instance. If a plugin throws + * an error, the `onRejected` callback will be executed. + * + * It implements standard Promise API. + * + * ```js + * postcss([autoprefixer]).process(css, { from: cssPath }).then(result => { + * console.log(result.css) + * }) + * ``` + */ + then: Promise>['then'] + + /** + * An alias for the `css` property. Use it with syntaxes + * that generate non-CSS output. + * + * This property will only work with synchronous plugins. + * If the processor contains any asynchronous plugins + * it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get content(): string + + /** + * Processes input CSS through synchronous plugins, converts `Root` + * to a CSS string and returns `Result#css`. + * + * This property will only work with synchronous plugins. + * If the processor contains any asynchronous plugins + * it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get css(): string + + /** + * Processes input CSS through synchronous plugins + * and returns `Result#map`. + * + * This property will only work with synchronous plugins. + * If the processor contains any asynchronous plugins + * it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get map(): SourceMap + + /** + * Processes input CSS through synchronous plugins + * and returns `Result#messages`. + * + * This property will only work with synchronous plugins. If the processor + * contains any asynchronous plugins it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get messages(): Message[] + + /** + * Options from the `Processor#process` call. + */ + get opts(): ResultOptions + + /** + * Returns a `Processor` instance, which will be used + * for CSS transformations. + */ + get processor(): Processor + + /** + * Processes input CSS through synchronous plugins + * and returns `Result#root`. + * + * This property will only work with synchronous plugins. If the processor + * contains any asynchronous plugins it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get root(): RootNode + + /** + * Returns the default string description of an object. + * Required to implement the Promise interface. + */ + get [Symbol.toStringTag](): string + + /** + * @param processor Processor used for this transformation. + * @param css CSS to parse and transform. + * @param opts Options from the `Processor#process` or `Root#toResult`. + */ + constructor(processor: Processor, css: string, opts: ResultOptions) + + /** + * Run plugin in async way and return `Result`. + * + * @return Result with output content. + */ + async(): Promise> + + /** + * Run plugin in sync way and return `Result`. + * + * @return Result with output content. + */ + sync(): Result + + /** + * Alias for the `LazyResult#css` property. + * + * ```js + * lazy + '' === lazy.css + * ``` + * + * @return Output CSS. + */ + toString(): string + + /** + * Processes input CSS through synchronous plugins + * and calls `Result#warnings`. + * + * @return Warnings from plugins. + */ + warnings(): Warning[] +} + +declare class LazyResult< + RootNode = Document | Root +> extends LazyResult_ {} + +export = LazyResult diff --git a/node_modules/postcss/lib/lazy-result.js b/node_modules/postcss/lib/lazy-result.js new file mode 100644 index 0000000..1ea52b8 --- /dev/null +++ b/node_modules/postcss/lib/lazy-result.js @@ -0,0 +1,550 @@ +'use strict' + +let Container = require('./container') +let Document = require('./document') +let MapGenerator = require('./map-generator') +let parse = require('./parse') +let Result = require('./result') +let Root = require('./root') +let stringify = require('./stringify') +let { isClean, my } = require('./symbols') +let warnOnce = require('./warn-once') + +const TYPE_TO_CLASS_NAME = { + atrule: 'AtRule', + comment: 'Comment', + decl: 'Declaration', + document: 'Document', + root: 'Root', + rule: 'Rule' +} + +const PLUGIN_PROPS = { + AtRule: true, + AtRuleExit: true, + Comment: true, + CommentExit: true, + Declaration: true, + DeclarationExit: true, + Document: true, + DocumentExit: true, + Once: true, + OnceExit: true, + postcssPlugin: true, + prepare: true, + Root: true, + RootExit: true, + Rule: true, + RuleExit: true +} + +const NOT_VISITORS = { + Once: true, + postcssPlugin: true, + prepare: true +} + +const CHILDREN = 0 + +function isPromise(obj) { + return typeof obj === 'object' && typeof obj.then === 'function' +} + +function getEvents(node) { + let key = false + let type = TYPE_TO_CLASS_NAME[node.type] + if (node.type === 'decl') { + key = node.prop.toLowerCase() + } else if (node.type === 'atrule') { + key = node.name.toLowerCase() + } + + if (key && node.append) { + return [ + type, + type + '-' + key, + CHILDREN, + type + 'Exit', + type + 'Exit-' + key + ] + } else if (key) { + return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key] + } else if (node.append) { + return [type, CHILDREN, type + 'Exit'] + } else { + return [type, type + 'Exit'] + } +} + +function toStack(node) { + let events + if (node.type === 'document') { + events = ['Document', CHILDREN, 'DocumentExit'] + } else if (node.type === 'root') { + events = ['Root', CHILDREN, 'RootExit'] + } else { + events = getEvents(node) + } + + return { + eventIndex: 0, + events, + iterator: 0, + node, + visitorIndex: 0, + visitors: [] + } +} + +function cleanMarks(node) { + node[isClean] = false + if (node.nodes) node.nodes.forEach(i => cleanMarks(i)) + return node +} + +let postcss = {} + +class LazyResult { + get content() { + return this.stringify().content + } + + get css() { + return this.stringify().css + } + + get map() { + return this.stringify().map + } + + get messages() { + return this.sync().messages + } + + get opts() { + return this.result.opts + } + + get processor() { + return this.result.processor + } + + get root() { + return this.sync().root + } + + get [Symbol.toStringTag]() { + return 'LazyResult' + } + + constructor(processor, css, opts) { + this.stringified = false + this.processed = false + + let root + if ( + typeof css === 'object' && + css !== null && + (css.type === 'root' || css.type === 'document') + ) { + root = cleanMarks(css) + } else if (css instanceof LazyResult || css instanceof Result) { + root = cleanMarks(css.root) + if (css.map) { + if (typeof opts.map === 'undefined') opts.map = {} + if (!opts.map.inline) opts.map.inline = false + opts.map.prev = css.map + } + } else { + let parser = parse + if (opts.syntax) parser = opts.syntax.parse + if (opts.parser) parser = opts.parser + if (parser.parse) parser = parser.parse + + try { + root = parser(css, opts) + } catch (error) { + this.processed = true + this.error = error + } + + if (root && !root[my]) { + /* c8 ignore next 2 */ + Container.rebuild(root) + } + } + + this.result = new Result(processor, root, opts) + this.helpers = { ...postcss, postcss, result: this.result } + this.plugins = this.processor.plugins.map(plugin => { + if (typeof plugin === 'object' && plugin.prepare) { + return { ...plugin, ...plugin.prepare(this.result) } + } else { + return plugin + } + }) + } + + async() { + if (this.error) return Promise.reject(this.error) + if (this.processed) return Promise.resolve(this.result) + if (!this.processing) { + this.processing = this.runAsync() + } + return this.processing + } + + catch(onRejected) { + return this.async().catch(onRejected) + } + + finally(onFinally) { + return this.async().then(onFinally, onFinally) + } + + getAsyncError() { + throw new Error('Use process(css).then(cb) to work with async plugins') + } + + handleError(error, node) { + let plugin = this.result.lastPlugin + try { + if (node) node.addToError(error) + this.error = error + if (error.name === 'CssSyntaxError' && !error.plugin) { + error.plugin = plugin.postcssPlugin + error.setMessage() + } else if (plugin.postcssVersion) { + if (process.env.NODE_ENV !== 'production') { + let pluginName = plugin.postcssPlugin + let pluginVer = plugin.postcssVersion + let runtimeVer = this.result.processor.version + let a = pluginVer.split('.') + let b = runtimeVer.split('.') + + if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) { + // eslint-disable-next-line no-console + console.error( + 'Unknown error from PostCSS plugin. Your current PostCSS ' + + 'version is ' + + runtimeVer + + ', but ' + + pluginName + + ' uses ' + + pluginVer + + '. Perhaps this is the source of the error below.' + ) + } + } + } + } catch (err) { + /* c8 ignore next 3 */ + // eslint-disable-next-line no-console + if (console && console.error) console.error(err) + } + return error + } + + prepareVisitors() { + this.listeners = {} + let add = (plugin, type, cb) => { + if (!this.listeners[type]) this.listeners[type] = [] + this.listeners[type].push([plugin, cb]) + } + for (let plugin of this.plugins) { + if (typeof plugin === 'object') { + for (let event in plugin) { + if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) { + throw new Error( + `Unknown event ${event} in ${plugin.postcssPlugin}. ` + + `Try to update PostCSS (${this.processor.version} now).` + ) + } + if (!NOT_VISITORS[event]) { + if (typeof plugin[event] === 'object') { + for (let filter in plugin[event]) { + if (filter === '*') { + add(plugin, event, plugin[event][filter]) + } else { + add( + plugin, + event + '-' + filter.toLowerCase(), + plugin[event][filter] + ) + } + } + } else if (typeof plugin[event] === 'function') { + add(plugin, event, plugin[event]) + } + } + } + } + } + this.hasListener = Object.keys(this.listeners).length > 0 + } + + async runAsync() { + this.plugin = 0 + for (let i = 0; i < this.plugins.length; i++) { + let plugin = this.plugins[i] + let promise = this.runOnRoot(plugin) + if (isPromise(promise)) { + try { + await promise + } catch (error) { + throw this.handleError(error) + } + } + } + + this.prepareVisitors() + if (this.hasListener) { + let root = this.result.root + while (!root[isClean]) { + root[isClean] = true + let stack = [toStack(root)] + while (stack.length > 0) { + let promise = this.visitTick(stack) + if (isPromise(promise)) { + try { + await promise + } catch (e) { + let node = stack[stack.length - 1].node + throw this.handleError(e, node) + } + } + } + } + + if (this.listeners.OnceExit) { + for (let [plugin, visitor] of this.listeners.OnceExit) { + this.result.lastPlugin = plugin + try { + if (root.type === 'document') { + let roots = root.nodes.map(subRoot => + visitor(subRoot, this.helpers) + ) + + await Promise.all(roots) + } else { + await visitor(root, this.helpers) + } + } catch (e) { + throw this.handleError(e) + } + } + } + } + + this.processed = true + return this.stringify() + } + + runOnRoot(plugin) { + this.result.lastPlugin = plugin + try { + if (typeof plugin === 'object' && plugin.Once) { + if (this.result.root.type === 'document') { + let roots = this.result.root.nodes.map(root => + plugin.Once(root, this.helpers) + ) + + if (isPromise(roots[0])) { + return Promise.all(roots) + } + + return roots + } + + return plugin.Once(this.result.root, this.helpers) + } else if (typeof plugin === 'function') { + return plugin(this.result.root, this.result) + } + } catch (error) { + throw this.handleError(error) + } + } + + stringify() { + if (this.error) throw this.error + if (this.stringified) return this.result + this.stringified = true + + this.sync() + + let opts = this.result.opts + let str = stringify + if (opts.syntax) str = opts.syntax.stringify + if (opts.stringifier) str = opts.stringifier + if (str.stringify) str = str.stringify + + let map = new MapGenerator(str, this.result.root, this.result.opts) + let data = map.generate() + this.result.css = data[0] + this.result.map = data[1] + + return this.result + } + + sync() { + if (this.error) throw this.error + if (this.processed) return this.result + this.processed = true + + if (this.processing) { + throw this.getAsyncError() + } + + for (let plugin of this.plugins) { + let promise = this.runOnRoot(plugin) + if (isPromise(promise)) { + throw this.getAsyncError() + } + } + + this.prepareVisitors() + if (this.hasListener) { + let root = this.result.root + while (!root[isClean]) { + root[isClean] = true + this.walkSync(root) + } + if (this.listeners.OnceExit) { + if (root.type === 'document') { + for (let subRoot of root.nodes) { + this.visitSync(this.listeners.OnceExit, subRoot) + } + } else { + this.visitSync(this.listeners.OnceExit, root) + } + } + } + + return this.result + } + + then(onFulfilled, onRejected) { + if (process.env.NODE_ENV !== 'production') { + if (!('from' in this.opts)) { + warnOnce( + 'Without `from` option PostCSS could generate wrong source map ' + + 'and will not find Browserslist config. Set it to CSS file path ' + + 'or to `undefined` to prevent this warning.' + ) + } + } + return this.async().then(onFulfilled, onRejected) + } + + toString() { + return this.css + } + + visitSync(visitors, node) { + for (let [plugin, visitor] of visitors) { + this.result.lastPlugin = plugin + let promise + try { + promise = visitor(node, this.helpers) + } catch (e) { + throw this.handleError(e, node.proxyOf) + } + if (node.type !== 'root' && node.type !== 'document' && !node.parent) { + return true + } + if (isPromise(promise)) { + throw this.getAsyncError() + } + } + } + + visitTick(stack) { + let visit = stack[stack.length - 1] + let { node, visitors } = visit + + if (node.type !== 'root' && node.type !== 'document' && !node.parent) { + stack.pop() + return + } + + if (visitors.length > 0 && visit.visitorIndex < visitors.length) { + let [plugin, visitor] = visitors[visit.visitorIndex] + visit.visitorIndex += 1 + if (visit.visitorIndex === visitors.length) { + visit.visitors = [] + visit.visitorIndex = 0 + } + this.result.lastPlugin = plugin + try { + return visitor(node.toProxy(), this.helpers) + } catch (e) { + throw this.handleError(e, node) + } + } + + if (visit.iterator !== 0) { + let iterator = visit.iterator + let child + while ((child = node.nodes[node.indexes[iterator]])) { + node.indexes[iterator] += 1 + if (!child[isClean]) { + child[isClean] = true + stack.push(toStack(child)) + return + } + } + visit.iterator = 0 + delete node.indexes[iterator] + } + + let events = visit.events + while (visit.eventIndex < events.length) { + let event = events[visit.eventIndex] + visit.eventIndex += 1 + if (event === CHILDREN) { + if (node.nodes && node.nodes.length) { + node[isClean] = true + visit.iterator = node.getIterator() + } + return + } else if (this.listeners[event]) { + visit.visitors = this.listeners[event] + return + } + } + stack.pop() + } + + walkSync(node) { + node[isClean] = true + let events = getEvents(node) + for (let event of events) { + if (event === CHILDREN) { + if (node.nodes) { + node.each(child => { + if (!child[isClean]) this.walkSync(child) + }) + } + } else { + let visitors = this.listeners[event] + if (visitors) { + if (this.visitSync(visitors, node.toProxy())) return + } + } + } + } + + warnings() { + return this.sync().warnings() + } +} + +LazyResult.registerPostcss = dependant => { + postcss = dependant +} + +module.exports = LazyResult +LazyResult.default = LazyResult + +Root.registerLazyResult(LazyResult) +Document.registerLazyResult(LazyResult) diff --git a/node_modules/postcss/lib/list.d.ts b/node_modules/postcss/lib/list.d.ts new file mode 100644 index 0000000..e262ad3 --- /dev/null +++ b/node_modules/postcss/lib/list.d.ts @@ -0,0 +1,60 @@ +declare namespace list { + type List = { + /** + * Safely splits comma-separated values (such as those for `transition-*` + * and `background` properties). + * + * ```js + * Once (root, { list }) { + * list.comma('black, linear-gradient(white, black)') + * //=> ['black', 'linear-gradient(white, black)'] + * } + * ``` + * + * @param str Comma-separated values. + * @return Split values. + */ + comma(str: string): string[] + + default: List + + /** + * Safely splits space-separated values (such as those for `background`, + * `border-radius`, and other shorthand properties). + * + * ```js + * Once (root, { list }) { + * list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)'] + * } + * ``` + * + * @param str Space-separated values. + * @return Split values. + */ + space(str: string): string[] + + /** + * Safely splits values. + * + * ```js + * Once (root, { list }) { + * list.split('1px calc(10% + 1px)', [' ', '\n', '\t']) //=> ['1px', 'calc(10% + 1px)'] + * } + * ``` + * + * @param string separated values. + * @param separators array of separators. + * @param last boolean indicator. + * @return Split values. + */ + split( + string: string, + separators: readonly string[], + last: boolean + ): string[] + } +} + +declare const list: list.List + +export = list diff --git a/node_modules/postcss/lib/list.js b/node_modules/postcss/lib/list.js new file mode 100644 index 0000000..1b31f98 --- /dev/null +++ b/node_modules/postcss/lib/list.js @@ -0,0 +1,58 @@ +'use strict' + +let list = { + comma(string) { + return list.split(string, [','], true) + }, + + space(string) { + let spaces = [' ', '\n', '\t'] + return list.split(string, spaces) + }, + + split(string, separators, last) { + let array = [] + let current = '' + let split = false + + let func = 0 + let inQuote = false + let prevQuote = '' + let escape = false + + for (let letter of string) { + if (escape) { + escape = false + } else if (letter === '\\') { + escape = true + } else if (inQuote) { + if (letter === prevQuote) { + inQuote = false + } + } else if (letter === '"' || letter === "'") { + inQuote = true + prevQuote = letter + } else if (letter === '(') { + func += 1 + } else if (letter === ')') { + if (func > 0) func -= 1 + } else if (func === 0) { + if (separators.includes(letter)) split = true + } + + if (split) { + if (current !== '') array.push(current.trim()) + current = '' + split = false + } else { + current += letter + } + } + + if (last || current !== '') array.push(current.trim()) + return array + } +} + +module.exports = list +list.default = list diff --git a/node_modules/postcss/lib/map-generator.js b/node_modules/postcss/lib/map-generator.js new file mode 100644 index 0000000..89069d3 --- /dev/null +++ b/node_modules/postcss/lib/map-generator.js @@ -0,0 +1,368 @@ +'use strict' + +let { dirname, relative, resolve, sep } = require('path') +let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') +let { pathToFileURL } = require('url') + +let Input = require('./input') + +let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator) +let pathAvailable = Boolean(dirname && resolve && relative && sep) + +class MapGenerator { + constructor(stringify, root, opts, cssString) { + this.stringify = stringify + this.mapOpts = opts.map || {} + this.root = root + this.opts = opts + this.css = cssString + this.originalCSS = cssString + this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute + + this.memoizedFileURLs = new Map() + this.memoizedPaths = new Map() + this.memoizedURLs = new Map() + } + + addAnnotation() { + let content + + if (this.isInline()) { + content = + 'data:application/json;base64,' + this.toBase64(this.map.toString()) + } else if (typeof this.mapOpts.annotation === 'string') { + content = this.mapOpts.annotation + } else if (typeof this.mapOpts.annotation === 'function') { + content = this.mapOpts.annotation(this.opts.to, this.root) + } else { + content = this.outputFile() + '.map' + } + let eol = '\n' + if (this.css.includes('\r\n')) eol = '\r\n' + + this.css += eol + '/*# sourceMappingURL=' + content + ' */' + } + + applyPrevMaps() { + for (let prev of this.previous()) { + let from = this.toUrl(this.path(prev.file)) + let root = prev.root || dirname(prev.file) + let map + + if (this.mapOpts.sourcesContent === false) { + map = new SourceMapConsumer(prev.text) + if (map.sourcesContent) { + map.sourcesContent = null + } + } else { + map = prev.consumer() + } + + this.map.applySourceMap(map, from, this.toUrl(this.path(root))) + } + } + + clearAnnotation() { + if (this.mapOpts.annotation === false) return + + if (this.root) { + let node + for (let i = this.root.nodes.length - 1; i >= 0; i--) { + node = this.root.nodes[i] + if (node.type !== 'comment') continue + if (node.text.startsWith('# sourceMappingURL=')) { + this.root.removeChild(i) + } + } + } else if (this.css) { + this.css = this.css.replace(/\n*\/\*#[\S\s]*?\*\/$/gm, '') + } + } + + generate() { + this.clearAnnotation() + if (pathAvailable && sourceMapAvailable && this.isMap()) { + return this.generateMap() + } else { + let result = '' + this.stringify(this.root, i => { + result += i + }) + return [result] + } + } + + generateMap() { + if (this.root) { + this.generateString() + } else if (this.previous().length === 1) { + let prev = this.previous()[0].consumer() + prev.file = this.outputFile() + this.map = SourceMapGenerator.fromSourceMap(prev, { + ignoreInvalidMapping: true + }) + } else { + this.map = new SourceMapGenerator({ + file: this.outputFile(), + ignoreInvalidMapping: true + }) + this.map.addMapping({ + generated: { column: 0, line: 1 }, + original: { column: 0, line: 1 }, + source: this.opts.from + ? this.toUrl(this.path(this.opts.from)) + : '' + }) + } + + if (this.isSourcesContent()) this.setSourcesContent() + if (this.root && this.previous().length > 0) this.applyPrevMaps() + if (this.isAnnotation()) this.addAnnotation() + + if (this.isInline()) { + return [this.css] + } else { + return [this.css, this.map] + } + } + + generateString() { + this.css = '' + this.map = new SourceMapGenerator({ + file: this.outputFile(), + ignoreInvalidMapping: true + }) + + let line = 1 + let column = 1 + + let noSource = '' + let mapping = { + generated: { column: 0, line: 0 }, + original: { column: 0, line: 0 }, + source: '' + } + + let last, lines + this.stringify(this.root, (str, node, type) => { + this.css += str + + if (node && type !== 'end') { + mapping.generated.line = line + mapping.generated.column = column - 1 + if (node.source && node.source.start) { + mapping.source = this.sourcePath(node) + mapping.original.line = node.source.start.line + mapping.original.column = node.source.start.column - 1 + this.map.addMapping(mapping) + } else { + mapping.source = noSource + mapping.original.line = 1 + mapping.original.column = 0 + this.map.addMapping(mapping) + } + } + + lines = str.match(/\n/g) + if (lines) { + line += lines.length + last = str.lastIndexOf('\n') + column = str.length - last + } else { + column += str.length + } + + if (node && type !== 'start') { + let p = node.parent || { raws: {} } + let childless = + node.type === 'decl' || (node.type === 'atrule' && !node.nodes) + if (!childless || node !== p.last || p.raws.semicolon) { + if (node.source && node.source.end) { + mapping.source = this.sourcePath(node) + mapping.original.line = node.source.end.line + mapping.original.column = node.source.end.column - 1 + mapping.generated.line = line + mapping.generated.column = column - 2 + this.map.addMapping(mapping) + } else { + mapping.source = noSource + mapping.original.line = 1 + mapping.original.column = 0 + mapping.generated.line = line + mapping.generated.column = column - 1 + this.map.addMapping(mapping) + } + } + } + }) + } + + isAnnotation() { + if (this.isInline()) { + return true + } + if (typeof this.mapOpts.annotation !== 'undefined') { + return this.mapOpts.annotation + } + if (this.previous().length) { + return this.previous().some(i => i.annotation) + } + return true + } + + isInline() { + if (typeof this.mapOpts.inline !== 'undefined') { + return this.mapOpts.inline + } + + let annotation = this.mapOpts.annotation + if (typeof annotation !== 'undefined' && annotation !== true) { + return false + } + + if (this.previous().length) { + return this.previous().some(i => i.inline) + } + return true + } + + isMap() { + if (typeof this.opts.map !== 'undefined') { + return !!this.opts.map + } + return this.previous().length > 0 + } + + isSourcesContent() { + if (typeof this.mapOpts.sourcesContent !== 'undefined') { + return this.mapOpts.sourcesContent + } + if (this.previous().length) { + return this.previous().some(i => i.withContent()) + } + return true + } + + outputFile() { + if (this.opts.to) { + return this.path(this.opts.to) + } else if (this.opts.from) { + return this.path(this.opts.from) + } else { + return 'to.css' + } + } + + path(file) { + if (this.mapOpts.absolute) return file + if (file.charCodeAt(0) === 60 /* `<` */) return file + if (/^\w+:\/\//.test(file)) return file + let cached = this.memoizedPaths.get(file) + if (cached) return cached + + let from = this.opts.to ? dirname(this.opts.to) : '.' + + if (typeof this.mapOpts.annotation === 'string') { + from = dirname(resolve(from, this.mapOpts.annotation)) + } + + let path = relative(from, file) + this.memoizedPaths.set(file, path) + + return path + } + + previous() { + if (!this.previousMaps) { + this.previousMaps = [] + if (this.root) { + this.root.walk(node => { + if (node.source && node.source.input.map) { + let map = node.source.input.map + if (!this.previousMaps.includes(map)) { + this.previousMaps.push(map) + } + } + }) + } else { + let input = new Input(this.originalCSS, this.opts) + if (input.map) this.previousMaps.push(input.map) + } + } + + return this.previousMaps + } + + setSourcesContent() { + let already = {} + if (this.root) { + this.root.walk(node => { + if (node.source) { + let from = node.source.input.from + if (from && !already[from]) { + already[from] = true + let fromUrl = this.usesFileUrls + ? this.toFileUrl(from) + : this.toUrl(this.path(from)) + this.map.setSourceContent(fromUrl, node.source.input.css) + } + } + }) + } else if (this.css) { + let from = this.opts.from + ? this.toUrl(this.path(this.opts.from)) + : '' + this.map.setSourceContent(from, this.css) + } + } + + sourcePath(node) { + if (this.mapOpts.from) { + return this.toUrl(this.mapOpts.from) + } else if (this.usesFileUrls) { + return this.toFileUrl(node.source.input.from) + } else { + return this.toUrl(this.path(node.source.input.from)) + } + } + + toBase64(str) { + if (Buffer) { + return Buffer.from(str).toString('base64') + } else { + return window.btoa(unescape(encodeURIComponent(str))) + } + } + + toFileUrl(path) { + let cached = this.memoizedFileURLs.get(path) + if (cached) return cached + + if (pathToFileURL) { + let fileURL = pathToFileURL(path).toString() + this.memoizedFileURLs.set(path, fileURL) + + return fileURL + } else { + throw new Error( + '`map.absolute` option is not available in this PostCSS build' + ) + } + } + + toUrl(path) { + let cached = this.memoizedURLs.get(path) + if (cached) return cached + + if (sep === '\\') { + path = path.replace(/\\/g, '/') + } + + let url = encodeURI(path).replace(/[#?]/g, encodeURIComponent) + this.memoizedURLs.set(path, url) + + return url + } +} + +module.exports = MapGenerator diff --git a/node_modules/postcss/lib/no-work-result.d.ts b/node_modules/postcss/lib/no-work-result.d.ts new file mode 100644 index 0000000..094f30a --- /dev/null +++ b/node_modules/postcss/lib/no-work-result.d.ts @@ -0,0 +1,46 @@ +import LazyResult from './lazy-result.js' +import { SourceMap } from './postcss.js' +import Processor from './processor.js' +import Result, { Message, ResultOptions } from './result.js' +import Root from './root.js' +import Warning from './warning.js' + +declare namespace NoWorkResult { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { NoWorkResult_ as default } +} + +/** + * A Promise proxy for the result of PostCSS transformations. + * This lazy result instance doesn't parse css unless `NoWorkResult#root` or `Result#root` + * are accessed. See the example below for details. + * A `NoWork` instance is returned by `Processor#process` ONLY when no plugins defined. + * + * ```js + * const noWorkResult = postcss().process(css) // No plugins are defined. + * // CSS is not parsed + * let root = noWorkResult.root // now css is parsed because we accessed the root + * ``` + */ +declare class NoWorkResult_ implements LazyResult { + catch: Promise>['catch'] + finally: Promise>['finally'] + then: Promise>['then'] + get content(): string + get css(): string + get map(): SourceMap + get messages(): Message[] + get opts(): ResultOptions + get processor(): Processor + get root(): Root + get [Symbol.toStringTag](): string + constructor(processor: Processor, css: string, opts: ResultOptions) + async(): Promise> + sync(): Result + toString(): string + warnings(): Warning[] +} + +declare class NoWorkResult extends NoWorkResult_ {} + +export = NoWorkResult diff --git a/node_modules/postcss/lib/no-work-result.js b/node_modules/postcss/lib/no-work-result.js new file mode 100644 index 0000000..dd46182 --- /dev/null +++ b/node_modules/postcss/lib/no-work-result.js @@ -0,0 +1,138 @@ +'use strict' + +let MapGenerator = require('./map-generator') +let parse = require('./parse') +const Result = require('./result') +let stringify = require('./stringify') +let warnOnce = require('./warn-once') + +class NoWorkResult { + get content() { + return this.result.css + } + + get css() { + return this.result.css + } + + get map() { + return this.result.map + } + + get messages() { + return [] + } + + get opts() { + return this.result.opts + } + + get processor() { + return this.result.processor + } + + get root() { + if (this._root) { + return this._root + } + + let root + let parser = parse + + try { + root = parser(this._css, this._opts) + } catch (error) { + this.error = error + } + + if (this.error) { + throw this.error + } else { + this._root = root + return root + } + } + + get [Symbol.toStringTag]() { + return 'NoWorkResult' + } + + constructor(processor, css, opts) { + css = css.toString() + this.stringified = false + + this._processor = processor + this._css = css + this._opts = opts + this._map = undefined + let root + + let str = stringify + this.result = new Result(this._processor, root, this._opts) + this.result.css = css + + let self = this + Object.defineProperty(this.result, 'root', { + get() { + return self.root + } + }) + + let map = new MapGenerator(str, root, this._opts, css) + if (map.isMap()) { + let [generatedCSS, generatedMap] = map.generate() + if (generatedCSS) { + this.result.css = generatedCSS + } + if (generatedMap) { + this.result.map = generatedMap + } + } else { + map.clearAnnotation() + this.result.css = map.css + } + } + + async() { + if (this.error) return Promise.reject(this.error) + return Promise.resolve(this.result) + } + + catch(onRejected) { + return this.async().catch(onRejected) + } + + finally(onFinally) { + return this.async().then(onFinally, onFinally) + } + + sync() { + if (this.error) throw this.error + return this.result + } + + then(onFulfilled, onRejected) { + if (process.env.NODE_ENV !== 'production') { + if (!('from' in this._opts)) { + warnOnce( + 'Without `from` option PostCSS could generate wrong source map ' + + 'and will not find Browserslist config. Set it to CSS file path ' + + 'or to `undefined` to prevent this warning.' + ) + } + } + + return this.async().then(onFulfilled, onRejected) + } + + toString() { + return this._css + } + + warnings() { + return [] + } +} + +module.exports = NoWorkResult +NoWorkResult.default = NoWorkResult diff --git a/node_modules/postcss/lib/node.d.ts b/node_modules/postcss/lib/node.d.ts new file mode 100644 index 0000000..a09fe4d --- /dev/null +++ b/node_modules/postcss/lib/node.d.ts @@ -0,0 +1,556 @@ +import AtRule = require('./at-rule.js') +import { AtRuleProps } from './at-rule.js' +import Comment, { CommentProps } from './comment.js' +import Container, { NewChild } from './container.js' +import CssSyntaxError from './css-syntax-error.js' +import Declaration, { DeclarationProps } from './declaration.js' +import Document from './document.js' +import Input from './input.js' +import { Stringifier, Syntax } from './postcss.js' +import Result from './result.js' +import Root from './root.js' +import Rule, { RuleProps } from './rule.js' +import Warning, { WarningOptions } from './warning.js' + +declare namespace Node { + export type ChildNode = AtRule.default | Comment | Declaration | Rule + + export type AnyNode = + | AtRule.default + | Comment + | Declaration + | Document + | Root + | Rule + + export type ChildProps = + | AtRuleProps + | CommentProps + | DeclarationProps + | RuleProps + + export interface Position { + /** + * Source line in file. In contrast to `offset` it starts from 1. + */ + column: number + + /** + * Source column in file. + */ + line: number + + /** + * Source offset in file. It starts from 0. + */ + offset: number + } + + export interface Range { + /** + * End position, exclusive. + */ + end: Position + + /** + * Start position, inclusive. + */ + start: Position + } + + /** + * Source represents an interface for the {@link Node.source} property. + */ + export interface Source { + /** + * The inclusive ending position for the source + * code of a node. + * + * However, `end.offset` of a non `Root` node is the exclusive position. + * See https://github.com/postcss/postcss/pull/1879 for details. + * + * ```js + * const root = postcss.parse('a { color: black }') + * const a = root.first + * const color = a.first + * + * // The offset of `Root` node is the inclusive position + * css.source.end // { line: 1, column: 19, offset: 18 } + * + * // The offset of non `Root` node is the exclusive position + * a.source.end // { line: 1, column: 18, offset: 18 } + * color.source.end // { line: 1, column: 16, offset: 16 } + * ``` + */ + end?: Position + + /** + * The source file from where a node has originated. + */ + input: Input + + /** + * The inclusive starting position for the source + * code of a node. + */ + start?: Position + } + + /** + * Interface represents an interface for an object received + * as parameter by Node class constructor. + */ + export interface NodeProps { + source?: Source + } + + export interface NodeErrorOptions { + /** + * An ending index inside a node's string that should be highlighted as + * source of error. + */ + endIndex?: number + /** + * An index inside a node's string that should be highlighted as source + * of error. + */ + index?: number + /** + * Plugin name that created this error. PostCSS will set it automatically. + */ + plugin?: string + /** + * A word inside a node's string, that should be highlighted as source + * of error. + */ + word?: string + } + + // eslint-disable-next-line @typescript-eslint/no-shadow + class Node extends Node_ {} + export { Node as default } +} + +/** + * It represents an abstract class that handles common + * methods for other CSS abstract syntax tree nodes. + * + * Any node that represents CSS selector or value should + * not extend the `Node` class. + */ +declare abstract class Node_ { + /** + * It represents parent of the current node. + * + * ```js + * root.nodes[0].parent === root //=> true + * ``` + */ + parent: Container | Document | undefined + + /** + * It represents unnecessary whitespace and characters present + * in the css source code. + * + * Information to generate byte-to-byte equal node string as it was + * in the origin input. + * + * The properties of the raws object are decided by parser, + * the default parser uses the following properties: + * + * * `before`: the space symbols before the node. It also stores `*` + * and `_` symbols before the declaration (IE hack). + * * `after`: the space symbols after the last child of the node + * to the end of the node. + * * `between`: the symbols between the property and value + * for declarations, selector and `{` for rules, or last parameter + * and `{` for at-rules. + * * `semicolon`: contains true if the last child has + * an (optional) semicolon. + * * `afterName`: the space between the at-rule name and its parameters. + * * `left`: the space symbols between `/*` and the comment’s text. + * * `right`: the space symbols between the comment’s text + * and */. + * - `important`: the content of the important statement, + * if it is not just `!important`. + * + * PostCSS filters out the comments inside selectors, declaration values + * and at-rule parameters but it stores the origin content in raws. + * + * ```js + * const root = postcss.parse('a {\n color:black\n}') + * root.first.first.raws //=> { before: '\n ', between: ':' } + * ``` + */ + raws: any + + /** + * It represents information related to origin of a node and is required + * for generating source maps. + * + * The nodes that are created manually using the public APIs + * provided by PostCSS will have `source` undefined and + * will be absent in the source map. + * + * For this reason, the plugin developer should consider + * duplicating nodes as the duplicate node will have the + * same source as the original node by default or assign + * source to a node created manually. + * + * ```js + * decl.source.input.from //=> '/home/ai/source.css' + * decl.source.start //=> { line: 10, column: 2 } + * decl.source.end //=> { line: 10, column: 12 } + * ``` + * + * ```js + * // Incorrect method, source not specified! + * const prefixed = postcss.decl({ + * prop: '-moz-' + decl.prop, + * value: decl.value + * }) + * + * // Correct method, source is inherited when duplicating. + * const prefixed = decl.clone({ + * prop: '-moz-' + decl.prop + * }) + * ``` + * + * ```js + * if (atrule.name === 'add-link') { + * const rule = postcss.rule({ + * selector: 'a', + * source: atrule.source + * }) + * + * atrule.parent.insertBefore(atrule, rule) + * } + * ``` + */ + source?: Node.Source + + /** + * It represents type of a node in + * an abstract syntax tree. + * + * A type of node helps in identification of a node + * and perform operation based on it's type. + * + * ```js + * const declaration = new Declaration({ + * prop: 'color', + * value: 'black' + * }) + * + * declaration.type //=> 'decl' + * ``` + */ + type: string + + constructor(defaults?: object) + + /** + * Insert new node after current node to current node’s parent. + * + * Just alias for `node.parent.insertAfter(node, add)`. + * + * ```js + * decl.after('color: black') + * ``` + * + * @param newNode New node. + * @return This node for methods chain. + */ + after( + newNode: Node | Node.ChildProps | readonly Node[] | string | undefined + ): this + + /** + * It assigns properties to an existing node instance. + * + * ```js + * decl.assign({ prop: 'word-wrap', value: 'break-word' }) + * ``` + * + * @param overrides New properties to override the node. + * + * @return `this` for method chaining. + */ + assign(overrides: object): this + + /** + * Insert new node before current node to current node’s parent. + * + * Just alias for `node.parent.insertBefore(node, add)`. + * + * ```js + * decl.before('content: ""') + * ``` + * + * @param newNode New node. + * @return This node for methods chain. + */ + before( + newNode: Node | Node.ChildProps | readonly Node[] | string | undefined + ): this + + /** + * Clear the code style properties for the node and its children. + * + * ```js + * node.raws.before //=> ' ' + * node.cleanRaws() + * node.raws.before //=> undefined + * ``` + * + * @param keepBetween Keep the `raws.between` symbols. + */ + cleanRaws(keepBetween?: boolean): void + + /** + * It creates clone of an existing node, which includes all the properties + * and their values, that includes `raws` but not `type`. + * + * ```js + * decl.raws.before //=> "\n " + * const cloned = decl.clone({ prop: '-moz-' + decl.prop }) + * cloned.raws.before //=> "\n " + * cloned.toString() //=> -moz-transform: scale(0) + * ``` + * + * @param overrides New properties to override in the clone. + * + * @return Duplicate of the node instance. + */ + clone(overrides?: object): this + + /** + * Shortcut to clone the node and insert the resulting cloned node + * after the current node. + * + * @param overrides New properties to override in the clone. + * @return New node. + */ + cloneAfter(overrides?: object): this + + /** + * Shortcut to clone the node and insert the resulting cloned node + * before the current node. + * + * ```js + * decl.cloneBefore({ prop: '-moz-' + decl.prop }) + * ``` + * + * @param overrides Mew properties to override in the clone. + * + * @return New node + */ + cloneBefore(overrides?: object): this + + /** + * It creates an instance of the class `CssSyntaxError` and parameters passed + * to this method are assigned to the error instance. + * + * The error instance will have description for the + * error, original position of the node in the + * source, showing line and column number. + * + * If any previous map is present, it would be used + * to get original position of the source. + * + * The Previous Map here is referred to the source map + * generated by previous compilation, example: Less, + * Stylus and Sass. + * + * This method returns the error instance instead of + * throwing it. + * + * ```js + * if (!variables[name]) { + * throw decl.error(`Unknown variable ${name}`, { word: name }) + * // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black + * // color: $black + * // a + * // ^ + * // background: white + * } + * ``` + * + * @param message Description for the error instance. + * @param options Options for the error instance. + * + * @return Error instance is returned. + */ + error(message: string, options?: Node.NodeErrorOptions): CssSyntaxError + + /** + * Returns the next child of the node’s parent. + * Returns `undefined` if the current node is the last child. + * + * ```js + * if (comment.text === 'delete next') { + * const next = comment.next() + * if (next) { + * next.remove() + * } + * } + * ``` + * + * @return Next node. + */ + next(): Node.ChildNode | undefined + + /** + * Get the position for a word or an index inside the node. + * + * @param opts Options. + * @return Position. + */ + positionBy(opts?: Pick): Node.Position + + /** + * Convert string index to line/column. + * + * @param index The symbol number in the node’s string. + * @return Symbol position in file. + */ + positionInside(index: number): Node.Position + + /** + * Returns the previous child of the node’s parent. + * Returns `undefined` if the current node is the first child. + * + * ```js + * const annotation = decl.prev() + * if (annotation.type === 'comment') { + * readAnnotation(annotation.text) + * } + * ``` + * + * @return Previous node. + */ + prev(): Node.ChildNode | undefined + + /** + * Get the range for a word or start and end index inside the node. + * The start index is inclusive; the end index is exclusive. + * + * @param opts Options. + * @return Range. + */ + rangeBy( + opts?: Pick + ): Node.Range + + /** + * Returns a `raws` value. If the node is missing + * the code style property (because the node was manually built or cloned), + * PostCSS will try to autodetect the code style property by looking + * at other nodes in the tree. + * + * ```js + * const root = postcss.parse('a { background: white }') + * root.nodes[0].append({ prop: 'color', value: 'black' }) + * root.nodes[0].nodes[1].raws.before //=> undefined + * root.nodes[0].nodes[1].raw('before') //=> ' ' + * ``` + * + * @param prop Name of code style property. + * @param defaultType Name of default value, it can be missed + * if the value is the same as prop. + * @return {string} Code style value. + */ + raw(prop: string, defaultType?: string): string + + /** + * It removes the node from its parent and deletes its parent property. + * + * ```js + * if (decl.prop.match(/^-webkit-/)) { + * decl.remove() + * } + * ``` + * + * @return `this` for method chaining. + */ + remove(): this + + /** + * Inserts node(s) before the current node and removes the current node. + * + * ```js + * AtRule: { + * mixin: atrule => { + * atrule.replaceWith(mixinRules[atrule.params]) + * } + * } + * ``` + * + * @param nodes Mode(s) to replace current one. + * @return Current node to methods chain. + */ + replaceWith(...nodes: NewChild[]): this + + /** + * Finds the Root instance of the node’s tree. + * + * ```js + * root.nodes[0].nodes[0].root() === root + * ``` + * + * @return Root parent. + */ + root(): Root + + /** + * Fix circular links on `JSON.stringify()`. + * + * @return Cleaned object. + */ + toJSON(): object + + /** + * It compiles the node to browser readable cascading style sheets string + * depending on it's type. + * + * ```js + * new Rule({ selector: 'a' }).toString() //=> "a {}" + * ``` + * + * @param stringifier A syntax to use in string generation. + * @return CSS string of this node. + */ + toString(stringifier?: Stringifier | Syntax): string + + /** + * It is a wrapper for {@link Result#warn}, providing convenient + * way of generating warnings. + * + * ```js + * Declaration: { + * bad: (decl, { result }) => { + * decl.warn(result, 'Deprecated property: bad') + * } + * } + * ``` + * + * @param result The `Result` instance that will receive the warning. + * @param message Description for the warning. + * @param options Options for the warning. + * + * @return `Warning` instance is returned + */ + warn(result: Result, message: string, options?: WarningOptions): Warning + + /** + * If this node isn't already dirty, marks it and its ancestors as such. This + * indicates to the LazyResult processor that the {@link Root} has been + * modified by the current plugin and may need to be processed again by other + * plugins. + */ + protected markDirty(): void +} + +declare class Node extends Node_ {} + +export = Node diff --git a/node_modules/postcss/lib/node.js b/node_modules/postcss/lib/node.js new file mode 100644 index 0000000..b403b71 --- /dev/null +++ b/node_modules/postcss/lib/node.js @@ -0,0 +1,449 @@ +'use strict' + +let CssSyntaxError = require('./css-syntax-error') +let Stringifier = require('./stringifier') +let stringify = require('./stringify') +let { isClean, my } = require('./symbols') + +function cloneNode(obj, parent) { + let cloned = new obj.constructor() + + for (let i in obj) { + if (!Object.prototype.hasOwnProperty.call(obj, i)) { + /* c8 ignore next 2 */ + continue + } + if (i === 'proxyCache') continue + let value = obj[i] + let type = typeof value + + if (i === 'parent' && type === 'object') { + if (parent) cloned[i] = parent + } else if (i === 'source') { + cloned[i] = value + } else if (Array.isArray(value)) { + cloned[i] = value.map(j => cloneNode(j, cloned)) + } else { + if (type === 'object' && value !== null) value = cloneNode(value) + cloned[i] = value + } + } + + return cloned +} + +function sourceOffset(inputCSS, position) { + // Not all custom syntaxes support `offset` in `source.start` and `source.end` + if (position && typeof position.offset !== 'undefined') { + return position.offset + } + + let column = 1 + let line = 1 + let offset = 0 + + for (let i = 0; i < inputCSS.length; i++) { + if (line === position.line && column === position.column) { + offset = i + break + } + + if (inputCSS[i] === '\n') { + column = 1 + line += 1 + } else { + column += 1 + } + } + + return offset +} + +class Node { + get proxyOf() { + return this + } + + constructor(defaults = {}) { + this.raws = {} + this[isClean] = false + this[my] = true + + for (let name in defaults) { + if (name === 'nodes') { + this.nodes = [] + for (let node of defaults[name]) { + if (typeof node.clone === 'function') { + this.append(node.clone()) + } else { + this.append(node) + } + } + } else { + this[name] = defaults[name] + } + } + } + + addToError(error) { + error.postcssNode = this + if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) { + let s = this.source + error.stack = error.stack.replace( + /\n\s{4}at /, + `$&${s.input.from}:${s.start.line}:${s.start.column}$&` + ) + } + return error + } + + after(add) { + this.parent.insertAfter(this, add) + return this + } + + assign(overrides = {}) { + for (let name in overrides) { + this[name] = overrides[name] + } + return this + } + + before(add) { + this.parent.insertBefore(this, add) + return this + } + + cleanRaws(keepBetween) { + delete this.raws.before + delete this.raws.after + if (!keepBetween) delete this.raws.between + } + + clone(overrides = {}) { + let cloned = cloneNode(this) + for (let name in overrides) { + cloned[name] = overrides[name] + } + return cloned + } + + cloneAfter(overrides = {}) { + let cloned = this.clone(overrides) + this.parent.insertAfter(this, cloned) + return cloned + } + + cloneBefore(overrides = {}) { + let cloned = this.clone(overrides) + this.parent.insertBefore(this, cloned) + return cloned + } + + error(message, opts = {}) { + if (this.source) { + let { end, start } = this.rangeBy(opts) + return this.source.input.error( + message, + { column: start.column, line: start.line }, + { column: end.column, line: end.line }, + opts + ) + } + return new CssSyntaxError(message) + } + + getProxyProcessor() { + return { + get(node, prop) { + if (prop === 'proxyOf') { + return node + } else if (prop === 'root') { + return () => node.root().toProxy() + } else { + return node[prop] + } + }, + + set(node, prop, value) { + if (node[prop] === value) return true + node[prop] = value + if ( + prop === 'prop' || + prop === 'value' || + prop === 'name' || + prop === 'params' || + prop === 'important' || + /* c8 ignore next */ + prop === 'text' + ) { + node.markDirty() + } + return true + } + } + } + + /* c8 ignore next 3 */ + markClean() { + this[isClean] = true + } + + markDirty() { + if (this[isClean]) { + this[isClean] = false + let next = this + while ((next = next.parent)) { + next[isClean] = false + } + } + } + + next() { + if (!this.parent) return undefined + let index = this.parent.index(this) + return this.parent.nodes[index + 1] + } + + positionBy(opts = {}) { + let pos = this.source.start + if (opts.index) { + pos = this.positionInside(opts.index) + } else if (opts.word) { + let inputString = + 'document' in this.source.input + ? this.source.input.document + : this.source.input.css + let stringRepresentation = inputString.slice( + sourceOffset(inputString, this.source.start), + sourceOffset(inputString, this.source.end) + ) + let index = stringRepresentation.indexOf(opts.word) + if (index !== -1) pos = this.positionInside(index) + } + return pos + } + + positionInside(index) { + let column = this.source.start.column + let line = this.source.start.line + let inputString = + 'document' in this.source.input + ? this.source.input.document + : this.source.input.css + let offset = sourceOffset(inputString, this.source.start) + let end = offset + index + + for (let i = offset; i < end; i++) { + if (inputString[i] === '\n') { + column = 1 + line += 1 + } else { + column += 1 + } + } + + return { column, line, offset: end } + } + + prev() { + if (!this.parent) return undefined + let index = this.parent.index(this) + return this.parent.nodes[index - 1] + } + + rangeBy(opts = {}) { + let inputString = + 'document' in this.source.input + ? this.source.input.document + : this.source.input.css + let start = { + column: this.source.start.column, + line: this.source.start.line, + offset: sourceOffset(inputString, this.source.start) + } + let end = this.source.end + ? { + column: this.source.end.column + 1, + line: this.source.end.line, + offset: + typeof this.source.end.offset === 'number' + ? // `source.end.offset` is exclusive, so we don't need to add 1 + this.source.end.offset + : // Since line/column in this.source.end is inclusive, + // the `sourceOffset(... , this.source.end)` returns an inclusive offset. + // So, we add 1 to convert it to exclusive. + sourceOffset(inputString, this.source.end) + 1 + } + : { + column: start.column + 1, + line: start.line, + offset: start.offset + 1 + } + + if (opts.word) { + let stringRepresentation = inputString.slice( + sourceOffset(inputString, this.source.start), + sourceOffset(inputString, this.source.end) + ) + let index = stringRepresentation.indexOf(opts.word) + if (index !== -1) { + start = this.positionInside(index) + end = this.positionInside(index + opts.word.length) + } + } else { + if (opts.start) { + start = { + column: opts.start.column, + line: opts.start.line, + offset: sourceOffset(inputString, opts.start) + } + } else if (opts.index) { + start = this.positionInside(opts.index) + } + + if (opts.end) { + end = { + column: opts.end.column, + line: opts.end.line, + offset: sourceOffset(inputString, opts.end) + } + } else if (typeof opts.endIndex === 'number') { + end = this.positionInside(opts.endIndex) + } else if (opts.index) { + end = this.positionInside(opts.index + 1) + } + } + + if ( + end.line < start.line || + (end.line === start.line && end.column <= start.column) + ) { + end = { + column: start.column + 1, + line: start.line, + offset: start.offset + 1 + } + } + + return { end, start } + } + + raw(prop, defaultType) { + let str = new Stringifier() + return str.raw(this, prop, defaultType) + } + + remove() { + if (this.parent) { + this.parent.removeChild(this) + } + this.parent = undefined + return this + } + + replaceWith(...nodes) { + if (this.parent) { + let bookmark = this + let foundSelf = false + for (let node of nodes) { + if (node === this) { + foundSelf = true + } else if (foundSelf) { + this.parent.insertAfter(bookmark, node) + bookmark = node + } else { + this.parent.insertBefore(bookmark, node) + } + } + + if (!foundSelf) { + this.remove() + } + } + + return this + } + + root() { + let result = this + while (result.parent && result.parent.type !== 'document') { + result = result.parent + } + return result + } + + toJSON(_, inputs) { + let fixed = {} + let emitInputs = inputs == null + inputs = inputs || new Map() + let inputsNextIndex = 0 + + for (let name in this) { + if (!Object.prototype.hasOwnProperty.call(this, name)) { + /* c8 ignore next 2 */ + continue + } + if (name === 'parent' || name === 'proxyCache') continue + let value = this[name] + + if (Array.isArray(value)) { + fixed[name] = value.map(i => { + if (typeof i === 'object' && i.toJSON) { + return i.toJSON(null, inputs) + } else { + return i + } + }) + } else if (typeof value === 'object' && value.toJSON) { + fixed[name] = value.toJSON(null, inputs) + } else if (name === 'source') { + if (value == null) continue + let inputId = inputs.get(value.input) + if (inputId == null) { + inputId = inputsNextIndex + inputs.set(value.input, inputsNextIndex) + inputsNextIndex++ + } + fixed[name] = { + end: value.end, + inputId, + start: value.start + } + } else { + fixed[name] = value + } + } + + if (emitInputs) { + fixed.inputs = [...inputs.keys()].map(input => input.toJSON()) + } + + return fixed + } + + toProxy() { + if (!this.proxyCache) { + this.proxyCache = new Proxy(this, this.getProxyProcessor()) + } + return this.proxyCache + } + + toString(stringifier = stringify) { + if (stringifier.stringify) stringifier = stringifier.stringify + let result = '' + stringifier(this, i => { + result += i + }) + return result + } + + warn(result, text, opts = {}) { + let data = { node: this } + for (let i in opts) data[i] = opts[i] + return result.warn(text, data) + } +} + +module.exports = Node +Node.default = Node diff --git a/node_modules/postcss/lib/parse.d.ts b/node_modules/postcss/lib/parse.d.ts new file mode 100644 index 0000000..4c943a4 --- /dev/null +++ b/node_modules/postcss/lib/parse.d.ts @@ -0,0 +1,9 @@ +import { Parser } from './postcss.js' + +interface Parse extends Parser { + default: Parse +} + +declare const parse: Parse + +export = parse diff --git a/node_modules/postcss/lib/parse.js b/node_modules/postcss/lib/parse.js new file mode 100644 index 0000000..00a1037 --- /dev/null +++ b/node_modules/postcss/lib/parse.js @@ -0,0 +1,42 @@ +'use strict' + +let Container = require('./container') +let Input = require('./input') +let Parser = require('./parser') + +function parse(css, opts) { + let input = new Input(css, opts) + let parser = new Parser(input) + try { + parser.parse() + } catch (e) { + if (process.env.NODE_ENV !== 'production') { + if (e.name === 'CssSyntaxError' && opts && opts.from) { + if (/\.scss$/i.test(opts.from)) { + e.message += + '\nYou tried to parse SCSS with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-scss parser' + } else if (/\.sass/i.test(opts.from)) { + e.message += + '\nYou tried to parse Sass with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-sass parser' + } else if (/\.less$/i.test(opts.from)) { + e.message += + '\nYou tried to parse Less with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-less parser' + } + } + } + throw e + } + + return parser.root +} + +module.exports = parse +parse.default = parse + +Container.registerParse(parse) diff --git a/node_modules/postcss/lib/parser.js b/node_modules/postcss/lib/parser.js new file mode 100644 index 0000000..64fb5d8 --- /dev/null +++ b/node_modules/postcss/lib/parser.js @@ -0,0 +1,611 @@ +'use strict' + +let AtRule = require('./at-rule') +let Comment = require('./comment') +let Declaration = require('./declaration') +let Root = require('./root') +let Rule = require('./rule') +let tokenizer = require('./tokenize') + +const SAFE_COMMENT_NEIGHBOR = { + empty: true, + space: true +} + +function findLastWithPosition(tokens) { + for (let i = tokens.length - 1; i >= 0; i--) { + let token = tokens[i] + let pos = token[3] || token[2] + if (pos) return pos + } +} + +class Parser { + constructor(input) { + this.input = input + + this.root = new Root() + this.current = this.root + this.spaces = '' + this.semicolon = false + + this.createTokenizer() + this.root.source = { input, start: { column: 1, line: 1, offset: 0 } } + } + + atrule(token) { + let node = new AtRule() + node.name = token[1].slice(1) + if (node.name === '') { + this.unnamedAtrule(node, token) + } + this.init(node, token[2]) + + let type + let prev + let shift + let last = false + let open = false + let params = [] + let brackets = [] + + while (!this.tokenizer.endOfFile()) { + token = this.tokenizer.nextToken() + type = token[0] + + if (type === '(' || type === '[') { + brackets.push(type === '(' ? ')' : ']') + } else if (type === '{' && brackets.length > 0) { + brackets.push('}') + } else if (type === brackets[brackets.length - 1]) { + brackets.pop() + } + + if (brackets.length === 0) { + if (type === ';') { + node.source.end = this.getPosition(token[2]) + node.source.end.offset++ + this.semicolon = true + break + } else if (type === '{') { + open = true + break + } else if (type === '}') { + if (params.length > 0) { + shift = params.length - 1 + prev = params[shift] + while (prev && prev[0] === 'space') { + prev = params[--shift] + } + if (prev) { + node.source.end = this.getPosition(prev[3] || prev[2]) + node.source.end.offset++ + } + } + this.end(token) + break + } else { + params.push(token) + } + } else { + params.push(token) + } + + if (this.tokenizer.endOfFile()) { + last = true + break + } + } + + node.raws.between = this.spacesAndCommentsFromEnd(params) + if (params.length) { + node.raws.afterName = this.spacesAndCommentsFromStart(params) + this.raw(node, 'params', params) + if (last) { + token = params[params.length - 1] + node.source.end = this.getPosition(token[3] || token[2]) + node.source.end.offset++ + this.spaces = node.raws.between + node.raws.between = '' + } + } else { + node.raws.afterName = '' + node.params = '' + } + + if (open) { + node.nodes = [] + this.current = node + } + } + + checkMissedSemicolon(tokens) { + let colon = this.colon(tokens) + if (colon === false) return + + let founded = 0 + let token + for (let j = colon - 1; j >= 0; j--) { + token = tokens[j] + if (token[0] !== 'space') { + founded += 1 + if (founded === 2) break + } + } + // If the token is a word, e.g. `!important`, `red` or any other valid property's value. + // Then we need to return the colon after that word token. [3] is the "end" colon of that word. + // And because we need it after that one we do +1 to get the next one. + throw this.input.error( + 'Missed semicolon', + token[0] === 'word' ? token[3] + 1 : token[2] + ) + } + + colon(tokens) { + let brackets = 0 + let prev, token, type + for (let [i, element] of tokens.entries()) { + token = element + type = token[0] + + if (type === '(') { + brackets += 1 + } + if (type === ')') { + brackets -= 1 + } + if (brackets === 0 && type === ':') { + if (!prev) { + this.doubleColon(token) + } else if (prev[0] === 'word' && prev[1] === 'progid') { + continue + } else { + return i + } + } + + prev = token + } + return false + } + + comment(token) { + let node = new Comment() + this.init(node, token[2]) + node.source.end = this.getPosition(token[3] || token[2]) + node.source.end.offset++ + + let text = token[1].slice(2, -2) + if (/^\s*$/.test(text)) { + node.text = '' + node.raws.left = text + node.raws.right = '' + } else { + let match = text.match(/^(\s*)([^]*\S)(\s*)$/) + node.text = match[2] + node.raws.left = match[1] + node.raws.right = match[3] + } + } + + createTokenizer() { + this.tokenizer = tokenizer(this.input) + } + + decl(tokens, customProperty) { + let node = new Declaration() + this.init(node, tokens[0][2]) + + let last = tokens[tokens.length - 1] + if (last[0] === ';') { + this.semicolon = true + tokens.pop() + } + + node.source.end = this.getPosition( + last[3] || last[2] || findLastWithPosition(tokens) + ) + node.source.end.offset++ + + while (tokens[0][0] !== 'word') { + if (tokens.length === 1) this.unknownWord(tokens) + node.raws.before += tokens.shift()[1] + } + node.source.start = this.getPosition(tokens[0][2]) + + node.prop = '' + while (tokens.length) { + let type = tokens[0][0] + if (type === ':' || type === 'space' || type === 'comment') { + break + } + node.prop += tokens.shift()[1] + } + + node.raws.between = '' + + let token + while (tokens.length) { + token = tokens.shift() + + if (token[0] === ':') { + node.raws.between += token[1] + break + } else { + if (token[0] === 'word' && /\w/.test(token[1])) { + this.unknownWord([token]) + } + node.raws.between += token[1] + } + } + + if (node.prop[0] === '_' || node.prop[0] === '*') { + node.raws.before += node.prop[0] + node.prop = node.prop.slice(1) + } + + let firstSpaces = [] + let next + while (tokens.length) { + next = tokens[0][0] + if (next !== 'space' && next !== 'comment') break + firstSpaces.push(tokens.shift()) + } + + this.precheckMissedSemicolon(tokens) + + for (let i = tokens.length - 1; i >= 0; i--) { + token = tokens[i] + if (token[1].toLowerCase() === '!important') { + node.important = true + let string = this.stringFrom(tokens, i) + string = this.spacesFromEnd(tokens) + string + if (string !== ' !important') node.raws.important = string + break + } else if (token[1].toLowerCase() === 'important') { + let cache = tokens.slice(0) + let str = '' + for (let j = i; j > 0; j--) { + let type = cache[j][0] + if (str.trim().startsWith('!') && type !== 'space') { + break + } + str = cache.pop()[1] + str + } + if (str.trim().startsWith('!')) { + node.important = true + node.raws.important = str + tokens = cache + } + } + + if (token[0] !== 'space' && token[0] !== 'comment') { + break + } + } + + let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment') + + if (hasWord) { + node.raws.between += firstSpaces.map(i => i[1]).join('') + firstSpaces = [] + } + this.raw(node, 'value', firstSpaces.concat(tokens), customProperty) + + if (node.value.includes(':') && !customProperty) { + this.checkMissedSemicolon(tokens) + } + } + + doubleColon(token) { + throw this.input.error( + 'Double colon', + { offset: token[2] }, + { offset: token[2] + token[1].length } + ) + } + + emptyRule(token) { + let node = new Rule() + this.init(node, token[2]) + node.selector = '' + node.raws.between = '' + this.current = node + } + + end(token) { + if (this.current.nodes && this.current.nodes.length) { + this.current.raws.semicolon = this.semicolon + } + this.semicolon = false + + this.current.raws.after = (this.current.raws.after || '') + this.spaces + this.spaces = '' + + if (this.current.parent) { + this.current.source.end = this.getPosition(token[2]) + this.current.source.end.offset++ + this.current = this.current.parent + } else { + this.unexpectedClose(token) + } + } + + endFile() { + if (this.current.parent) this.unclosedBlock() + if (this.current.nodes && this.current.nodes.length) { + this.current.raws.semicolon = this.semicolon + } + this.current.raws.after = (this.current.raws.after || '') + this.spaces + this.root.source.end = this.getPosition(this.tokenizer.position()) + } + + freeSemicolon(token) { + this.spaces += token[1] + if (this.current.nodes) { + let prev = this.current.nodes[this.current.nodes.length - 1] + if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) { + prev.raws.ownSemicolon = this.spaces + this.spaces = '' + prev.source.end = this.getPosition(token[2]) + prev.source.end.offset += prev.raws.ownSemicolon.length + } + } + } + + // Helpers + + getPosition(offset) { + let pos = this.input.fromOffset(offset) + return { + column: pos.col, + line: pos.line, + offset + } + } + + init(node, offset) { + this.current.push(node) + node.source = { + input: this.input, + start: this.getPosition(offset) + } + node.raws.before = this.spaces + this.spaces = '' + if (node.type !== 'comment') this.semicolon = false + } + + other(start) { + let end = false + let type = null + let colon = false + let bracket = null + let brackets = [] + let customProperty = start[1].startsWith('--') + + let tokens = [] + let token = start + while (token) { + type = token[0] + tokens.push(token) + + if (type === '(' || type === '[') { + if (!bracket) bracket = token + brackets.push(type === '(' ? ')' : ']') + } else if (customProperty && colon && type === '{') { + if (!bracket) bracket = token + brackets.push('}') + } else if (brackets.length === 0) { + if (type === ';') { + if (colon) { + this.decl(tokens, customProperty) + return + } else { + break + } + } else if (type === '{') { + this.rule(tokens) + return + } else if (type === '}') { + this.tokenizer.back(tokens.pop()) + end = true + break + } else if (type === ':') { + colon = true + } + } else if (type === brackets[brackets.length - 1]) { + brackets.pop() + if (brackets.length === 0) bracket = null + } + + token = this.tokenizer.nextToken() + } + + if (this.tokenizer.endOfFile()) end = true + if (brackets.length > 0) this.unclosedBracket(bracket) + + if (end && colon) { + if (!customProperty) { + while (tokens.length) { + token = tokens[tokens.length - 1][0] + if (token !== 'space' && token !== 'comment') break + this.tokenizer.back(tokens.pop()) + } + } + this.decl(tokens, customProperty) + } else { + this.unknownWord(tokens) + } + } + + parse() { + let token + while (!this.tokenizer.endOfFile()) { + token = this.tokenizer.nextToken() + + switch (token[0]) { + case 'space': + this.spaces += token[1] + break + + case ';': + this.freeSemicolon(token) + break + + case '}': + this.end(token) + break + + case 'comment': + this.comment(token) + break + + case 'at-word': + this.atrule(token) + break + + case '{': + this.emptyRule(token) + break + + default: + this.other(token) + break + } + } + this.endFile() + } + + precheckMissedSemicolon(/* tokens */) { + // Hook for Safe Parser + } + + raw(node, prop, tokens, customProperty) { + let token, type + let length = tokens.length + let value = '' + let clean = true + let next, prev + + for (let i = 0; i < length; i += 1) { + token = tokens[i] + type = token[0] + if (type === 'space' && i === length - 1 && !customProperty) { + clean = false + } else if (type === 'comment') { + prev = tokens[i - 1] ? tokens[i - 1][0] : 'empty' + next = tokens[i + 1] ? tokens[i + 1][0] : 'empty' + if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) { + if (value.slice(-1) === ',') { + clean = false + } else { + value += token[1] + } + } else { + clean = false + } + } else { + value += token[1] + } + } + if (!clean) { + let raw = tokens.reduce((all, i) => all + i[1], '') + node.raws[prop] = { raw, value } + } + node[prop] = value + } + + rule(tokens) { + tokens.pop() + + let node = new Rule() + this.init(node, tokens[0][2]) + + node.raws.between = this.spacesAndCommentsFromEnd(tokens) + this.raw(node, 'selector', tokens) + this.current = node + } + + spacesAndCommentsFromEnd(tokens) { + let lastTokenType + let spaces = '' + while (tokens.length) { + lastTokenType = tokens[tokens.length - 1][0] + if (lastTokenType !== 'space' && lastTokenType !== 'comment') break + spaces = tokens.pop()[1] + spaces + } + return spaces + } + + // Errors + + spacesAndCommentsFromStart(tokens) { + let next + let spaces = '' + while (tokens.length) { + next = tokens[0][0] + if (next !== 'space' && next !== 'comment') break + spaces += tokens.shift()[1] + } + return spaces + } + + spacesFromEnd(tokens) { + let lastTokenType + let spaces = '' + while (tokens.length) { + lastTokenType = tokens[tokens.length - 1][0] + if (lastTokenType !== 'space') break + spaces = tokens.pop()[1] + spaces + } + return spaces + } + + stringFrom(tokens, from) { + let result = '' + for (let i = from; i < tokens.length; i++) { + result += tokens[i][1] + } + tokens.splice(from, tokens.length - from) + return result + } + + unclosedBlock() { + let pos = this.current.source.start + throw this.input.error('Unclosed block', pos.line, pos.column) + } + + unclosedBracket(bracket) { + throw this.input.error( + 'Unclosed bracket', + { offset: bracket[2] }, + { offset: bracket[2] + 1 } + ) + } + + unexpectedClose(token) { + throw this.input.error( + 'Unexpected }', + { offset: token[2] }, + { offset: token[2] + 1 } + ) + } + + unknownWord(tokens) { + throw this.input.error( + 'Unknown word ' + tokens[0][1], + { offset: tokens[0][2] }, + { offset: tokens[0][2] + tokens[0][1].length } + ) + } + + unnamedAtrule(node, token) { + throw this.input.error( + 'At-rule without name', + { offset: token[2] }, + { offset: token[2] + token[1].length } + ) + } +} + +module.exports = Parser diff --git a/node_modules/postcss/lib/postcss.d.mts b/node_modules/postcss/lib/postcss.d.mts new file mode 100644 index 0000000..d343f3c --- /dev/null +++ b/node_modules/postcss/lib/postcss.d.mts @@ -0,0 +1,69 @@ +export { + // Type-only exports + AcceptedPlugin, + + AnyNode, + atRule, + AtRule, + AtRuleProps, + Builder, + ChildNode, + ChildProps, + comment, + Comment, + CommentProps, + Container, + ContainerProps, + CssSyntaxError, + decl, + Declaration, + DeclarationProps, + // postcss function / namespace + default, + document, + Document, + DocumentProps, + FilePosition, + fromJSON, + Helpers, + Input, + + JSONHydrator, + // This is a class, but it’s not re-exported. That’s why it’s exported as type-only here. + type LazyResult, + list, + Message, + Node, + NodeErrorOptions, + NodeProps, + OldPlugin, + parse, + Parser, + // @ts-expect-error This value exists, but it’s untyped. + plugin, + Plugin, + PluginCreator, + Position, + Postcss, + ProcessOptions, + Processor, + Result, + root, + Root, + RootProps, + rule, + Rule, + RuleProps, + Source, + SourceMap, + SourceMapOptions, + Stringifier, + // Value exports from postcss.mjs + stringify, + Syntax, + TransformCallback, + Transformer, + Warning, + + WarningOptions +} from './postcss.js' diff --git a/node_modules/postcss/lib/postcss.d.ts b/node_modules/postcss/lib/postcss.d.ts new file mode 100644 index 0000000..c5e3605 --- /dev/null +++ b/node_modules/postcss/lib/postcss.d.ts @@ -0,0 +1,458 @@ +import { RawSourceMap, SourceMapGenerator } from 'source-map-js' + +import AtRule, { AtRuleProps } from './at-rule.js' +import Comment, { CommentProps } from './comment.js' +import Container, { ContainerProps, NewChild } from './container.js' +import CssSyntaxError from './css-syntax-error.js' +import Declaration, { DeclarationProps } from './declaration.js' +import Document, { DocumentProps } from './document.js' +import Input, { FilePosition } from './input.js' +import LazyResult from './lazy-result.js' +import list from './list.js' +import Node, { + AnyNode, + ChildNode, + ChildProps, + NodeErrorOptions, + NodeProps, + Position, + Source +} from './node.js' +import Processor from './processor.js' +import Result, { Message } from './result.js' +import Root, { RootProps } from './root.js' +import Rule, { RuleProps } from './rule.js' +import Warning, { WarningOptions } from './warning.js' + +type DocumentProcessor = ( + document: Document, + helper: postcss.Helpers +) => Promise | void +type RootProcessor = ( + root: Root, + helper: postcss.Helpers +) => Promise | void +type DeclarationProcessor = ( + decl: Declaration, + helper: postcss.Helpers +) => Promise | void +type RuleProcessor = ( + rule: Rule, + helper: postcss.Helpers +) => Promise | void +type AtRuleProcessor = ( + atRule: AtRule, + helper: postcss.Helpers +) => Promise | void +type CommentProcessor = ( + comment: Comment, + helper: postcss.Helpers +) => Promise | void + +interface Processors { + /** + * Will be called on all`AtRule` nodes. + * + * Will be called again on node or children changes. + */ + AtRule?: { [name: string]: AtRuleProcessor } | AtRuleProcessor + + /** + * Will be called on all `AtRule` nodes, when all children will be processed. + * + * Will be called again on node or children changes. + */ + AtRuleExit?: { [name: string]: AtRuleProcessor } | AtRuleProcessor + + /** + * Will be called on all `Comment` nodes. + * + * Will be called again on node or children changes. + */ + Comment?: CommentProcessor + + /** + * Will be called on all `Comment` nodes after listeners + * for `Comment` event. + * + * Will be called again on node or children changes. + */ + CommentExit?: CommentProcessor + + /** + * Will be called on all `Declaration` nodes after listeners + * for `Declaration` event. + * + * Will be called again on node or children changes. + */ + Declaration?: { [prop: string]: DeclarationProcessor } | DeclarationProcessor + + /** + * Will be called on all `Declaration` nodes. + * + * Will be called again on node or children changes. + */ + DeclarationExit?: + | { [prop: string]: DeclarationProcessor } + | DeclarationProcessor + + /** + * Will be called on `Document` node. + * + * Will be called again on children changes. + */ + Document?: DocumentProcessor + + /** + * Will be called on `Document` node, when all children will be processed. + * + * Will be called again on children changes. + */ + DocumentExit?: DocumentProcessor + + /** + * Will be called on `Root` node once. + */ + Once?: RootProcessor + + /** + * Will be called on `Root` node once, when all children will be processed. + */ + OnceExit?: RootProcessor + + /** + * Will be called on `Root` node. + * + * Will be called again on children changes. + */ + Root?: RootProcessor + + /** + * Will be called on `Root` node, when all children will be processed. + * + * Will be called again on children changes. + */ + RootExit?: RootProcessor + + /** + * Will be called on all `Rule` nodes. + * + * Will be called again on node or children changes. + */ + Rule?: RuleProcessor + + /** + * Will be called on all `Rule` nodes, when all children will be processed. + * + * Will be called again on node or children changes. + */ + RuleExit?: RuleProcessor +} + +declare namespace postcss { + export { + AnyNode, + AtRule, + AtRuleProps, + ChildNode, + ChildProps, + Comment, + CommentProps, + Container, + ContainerProps, + CssSyntaxError, + Declaration, + DeclarationProps, + Document, + DocumentProps, + FilePosition, + Input, + LazyResult, + list, + Message, + NewChild, + Node, + NodeErrorOptions, + NodeProps, + Position, + Processor, + Result, + Root, + RootProps, + Rule, + RuleProps, + Source, + Warning, + WarningOptions + } + + export type SourceMap = { + toJSON(): RawSourceMap + } & SourceMapGenerator + + export type Helpers = { postcss: Postcss; result: Result } & Postcss + + export interface Plugin extends Processors { + postcssPlugin: string + prepare?: (result: Result) => Processors + } + + export interface PluginCreator { + (opts?: PluginOptions): Plugin | Processor + postcss: true + } + + export interface Transformer extends TransformCallback { + postcssPlugin: string + postcssVersion: string + } + + export interface TransformCallback { + (root: Root, result: Result): Promise | void + } + + export interface OldPlugin extends Transformer { + (opts?: T): Transformer + postcss: Transformer + } + + export type AcceptedPlugin = + | { + postcss: Processor | TransformCallback + } + | OldPlugin + | Plugin + | PluginCreator + | Processor + | TransformCallback + + export interface Parser { + ( + css: { toString(): string } | string, + opts?: Pick + ): RootNode + } + + export interface Builder { + (part: string, node?: AnyNode, type?: 'end' | 'start'): void + } + + export interface Stringifier { + (node: AnyNode, builder: Builder): void + } + + export interface JSONHydrator { + (data: object): Node + (data: object[]): Node[] + } + + export interface Syntax { + /** + * Function to generate AST by string. + */ + parse?: Parser + + /** + * Class to generate string by AST. + */ + stringify?: Stringifier + } + + export interface SourceMapOptions { + /** + * Use absolute path in generated source map. + */ + absolute?: boolean + + /** + * Indicates that PostCSS should add annotation comments to the CSS. + * By default, PostCSS will always add a comment with a path + * to the source map. PostCSS will not add annotations to CSS files + * that do not contain any comments. + * + * By default, PostCSS presumes that you want to save the source map as + * `opts.to + '.map'` and will use this path in the annotation comment. + * A different path can be set by providing a string value for annotation. + * + * If you have set `inline: true`, annotation cannot be disabled. + */ + annotation?: ((file: string, root: Root) => string) | boolean | string + + /** + * Override `from` in map’s sources. + */ + from?: string + + /** + * Indicates that the source map should be embedded in the output CSS + * as a Base64-encoded comment. By default, it is `true`. + * But if all previous maps are external, not inline, PostCSS will not embed + * the map even if you do not set this option. + * + * If you have an inline source map, the result.map property will be empty, + * as the source map will be contained within the text of `result.css`. + */ + inline?: boolean + + /** + * Source map content from a previous processing step (e.g., Sass). + * + * PostCSS will try to read the previous source map + * automatically (based on comments within the source CSS), but you can use + * this option to identify it manually. + * + * If desired, you can omit the previous map with prev: `false`. + */ + prev?: ((file: string) => string) | boolean | object | string + + /** + * Indicates that PostCSS should set the origin content (e.g., Sass source) + * of the source map. By default, it is true. But if all previous maps do not + * contain sources content, PostCSS will also leave it out even if you + * do not set this option. + */ + sourcesContent?: boolean + } + + export interface ProcessOptions { + /** + * Input file if it is not simple CSS file, but HTML with

+ + + +